text
stringlengths
180
608k
[Question] [ **This question already has answers here**: [Visual Long Multiplication](/questions/51396/visual-long-multiplication) (10 answers) Closed 4 years ago. There's a visual method for multiplication that is taught to Japanese schoolchildren [citation needed] that uses lines and crossings to get the answer. [![Japanese Multiplication - Archimedes Laboratory Project - CC-BY-NC-ND](https://i.stack.imgur.com/ZTcST.jpg)](https://i.stack.imgur.com/ZTcST.jpg) [Image Source](http://www.archimedes-lab.org/Maths2_Multiplication.html) Your task is to implement this in ASCII art. You will be given two numbers to multiply. The output should be the corresponding ASCII art made up of `\`, `/`, and `X`, padded with ASCII spaces. The first number of the multiplication will use backslashes, starting from left to right. The second number will use forward slashes, once again from leftmost digit to rightmost. The output is made up of distinct diagonal line groupings. The number of lines within a grouping should be equal to the value of the digit. There should be at least one diagonal space between each grouping and there should be no spaces within the grouping. Suppose 43 is the first number. Before extending lines and creating crossings, it will start like this: ``` \ \ \ \ \ \ \ ``` If the second number is 61, it will look like this before extending and crossing: ``` / / / / / / / ``` Conceptually "extend" the lines, using X's for intersection points, to get the result: ``` \ / \ X / \ X X / X X X / \ / X X X / \ X / X X X / \ X X / X X X \ X X X / X X \ / X X X X / X \ X / X X X X / \ X \ / X X X X X \ / X X X \ / \ / X X \ X / X \ X \ / \ X \ X \ / \ ``` # Example Test Cases 5 \* 9 ``` \ / \ X / \ X X / \ X X X / \ X X X X / X X X X X / / X X X X X / / X X X X X / / X X X X X / / X X X X X / X X X X \ / X X X \ / X X \ / X \ / \ ``` 16 \* 27 ``` \ / \ X / \ X X \ X X \ / \ X X \ X / \ X X \ X X / X X \ X X X / \ / X \ X X X X / X / \ X X X X X / / X X X X X X X / / \ / X X X X X X X / X X X X X \ / X / X X X X \ / X / X X X \ / X / X X \ / X / X \ / X / \ / X / \ ``` 7 \* 24 ``` \ / \ X / \ X X \ X X \ / \ X X \ X / \ X X \ X X / \ X X \ X X X / X X \ X X X X / X \ X X X X \ / \ X X X X \ X X X X \ / X X X \ / X X \ / X \ / \ ``` 123 \* 543 ``` \ / \ X / \ X X / X X X / \ / X X X / \ X / X X X X X / X X \ / \ / X X / X \ X / X / X X / \ X X / / X / X X X X X / / X / X \ / X X X / X / \ X / X X \ / / X X X / X \ X / / \ / X X / \ X X / X / X X X X X / X / X \ / X X \ / X / \ X / X \ / X X X / \ / \ / X X X / X \ / X / \ / X / \ ``` 735 \* 21 ``` \ / \ X / \ X X \ X X \ / \ X X \ X X X \ X \ \ / X \ X \ \ X / \ X \ \ X X X \ X X \ / \ \ / X \ X \ X / \ X \ \ X X X \ \ X X \ / \ \ X X \ X \ X X \ X \ \ X X \ X \ X X \ X \ / X \ X \ / \ X \ X \ / \ ``` # Rules * There should be at least one (diagonal) space between each set of lines. For the purposes of this challenge, it doesn't have to line up in any sort of pretty visual way. * Border crossings should jut out by exactly one slash. * Any amount of padding to the left or the right is allowed as long as all the crossings line up correctly. * Single-width ASCII spaces must be used as padding. * You do not need to calculate the actual result of the multiplication. * You may assume the number is in base 10 and and is at most three digits long with no zeros. * Order matters for the purposes of the output. The first number is always in the `\` direction and the second number is always in the `/` direction. * Input and output may be in any convenient format. * Standard loopholes are banned. Happy Golfing! [Answer] # [Canvas](https://github.com/dzaima/Canvas), 41 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` (A┬{[1}0}┐) ⁷L├X⁷lYø;{³×?³y³-╵x\╋ ⁸⤢↔╶╶⁸n ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjA4JXVGRjIxJXUyNTJDJXVGRjVCJXVGRjNCJXVGRjExJXVGRjVEJXVGRjEwJXVGRjVEJXUyNTEwJXVGRjA5JTBBJXUyMDc3JXVGRjJDJXUyNTFDJXVGRjM4JXUyMDc3JXVGRjRDJXVGRjM5JUY4JXVGRjFCJXVGRjVCJUIzJUQ3JXVGRjFGJUIzJXVGRjU5JUIzJXVGRjBEJXUyNTc1JXVGRjU4JXVGRjNDJXUyNTRCJTBBJXUyMDc4JXUyOTIyJXUyMTk0JXUyNTc2JXUyNTc2JXUyMDc4JXVGRjRF,i=NzM1JTBBMjE_,v=8) [Answer] # JavaScript (ES6), ~~207 197 196~~ 188 bytes Takes input as an array of two strings, e.g. `["16", "27"]`. Returns a matrix of characters. ``` a=>([[p,H],[q]]=a.map(x=>[[W=0,...x].map(x=>'1'.repeat(x,W-=~x)).join`0`,W]),[...Array(W+H)]).map((_,y,a)=>a.map((_,x)=>' \\/X'[(d=x-y)<H&~d<H&~(x+=y-H+2)<0&x<W*2&~x&&p[d+H>>1]|2*q[x/2]])) ``` [Try it online!](https://tio.run/##NZBRb4IwFIXf9ysaYmgrpULVmUVLsocl/AOWlJvRAG4aB1jNUuL0r6Ogvtzc755zH87Z6j99yM2mOfpVXZTdWnZaRkSphsXA1B5Aav6rG2JlpFQiA8Y5t/A84RBzUzalPhLLEl9eLKV8W2@qLMhYApSpm/3dGN2SxIsp0OGRfLGWaSoj/UR7A4zSdPKJFSmk9Vu6it1L0Q9iPdn6sSfoKnDtKhkL92Jdt1GFF0dRCP9ivFd2IgAo7ZZKOXOHIefNAYaUE772IBZ3Wgwwe0hi2uN8Nn2I84FF6AC88HVtPnT@QzSSEcrr6lDvSr6rv0k2OmkVwBlZ1G8hnNNqdFoTfc9mer8ZOiAYP9ogOK0wPWeULrsr "JavaScript (Node.js) – Try It Online") ]
[Question] [ *Inspired by [this badly received migrated post](https://codegolf.stackexchange.com/questions/60525/generating-non-dictionary-numeric-passcodes).* The head of security at your company is concerned about your PIN generating system after it gave him `12345`. He also didn't really appreciate the Spaceballs joke you made at his expense, so you've been delegated to re-write the PIN generator. Since it has to fit on some special hardware, you have to make it as small as possible. # Your Task * You take two inputs - # of PINs, and PIN size in digits. * Generate the specified number of PINs of the specified size **randomly** and print it out. * All valid PIN's of the size must be possible to be printed out, even if they aren't uniformly probable. * However, there are some restrictions on the PINs - here are the invalid ones: 1. If all the pairs are the same digit: `114422` (Note: this will obviously include all same digit PINs). 2. Increasingly linear PINs (mod 10): `246802`. 3. All groups of 3 are physical lines on the keypad of `1 2 3;4 5 6;7 8 9;bksp 0 enter;`: `147369`. 4. The PIN can be entirely split up into groups from rule 1 and rule 3. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] # Pyth, 120 bytes ``` Arz7VGJ1WJK%"%0*d",HO-^TH1=J|q1l{m%-F_vMcd1T.:K2u|GHmu|GHm?qlk2:k"(.)\\1"0?qlk3}k+++=bcS"123456789"3_Mb.Tb_M.TbZdZ./K0)K ``` Figured I should add a real implementation then. Generates random numbers until one is found that meets all requirements. Can probably be improved a lot! [Online version](https://pyth.herokuapp.com/?code=Arz7VGJ1WJK%25%22%250%2ad%22%2CHO-%5ETH1%3DJ%7Cq1l%7Bm%25-F_vMcd1T.%3AK2u%7CGHmu%7CGHm%3Fqlk2%3Ak%22%28.%29%5C%5C1%220%3Fqlk3%7Dk%2B%2B%2B%3DbcS%22123456789%223_Mb.Tb_M.TbZdZ.%2FK0%29K&input=10+7&debug=0) [Answer] # Perl 5, 244 Starts with generating random numbers for the given size. And only prints those that don't meet the restrictions. Finding a solution for the keypad lines (without hardcoding combinations) was kinda fun. ``` ($k,$l)=@ARGV;$m=10**$l-1;while($n<$k){$_=sprintf("%0".$l."d",int(rand($m)));@N=split//,$_;pop@N;$i=$d=0;while(++$i<@N&&$d<1){$d=$N[$i-1]<=>$N[$i]}$b=$_;$b=~s|\d|@A=split//,$';2*$A[0]-$&-$A[1]==0|eg;if((!m/(\d)\1/)&$b>0&$d>=0){$n++;print$_.$/}} ``` # Test ``` $ perl gen_pins.pl 10 5 98121 15931 69042 93730 83458 25312 24601 49468 49490 67012 ``` ]
[Question] [ Create a program that halts **exactly** 50% of the time. Be original. Highest voted answer wins. By **exactly** I mean that on *each* run there is a 50% chance of it halting. [Answer] ### Perl ``` fork || do {sleep(1) while(1)} ``` Each time you run this program, it halts and doesn't halt. [Answer] ## Python ``` import random p=.3078458 while random.random()>=p:p/=2 ``` Each time around the loop it breaks with exponentially decreasing probability. The chance of never breaking is the product \$(1-p)(1-\frac{p}{2})(1-\frac{p}{4})...\$ which is \$\frac{1}{2}\$. (Obligatory comment about floating point not being exact.) [Answer] # JavaScript Alternatives halting and not halting. (halts on first run, doesn't halt on second, ...) ``` var h = localStorage.halt; while (h) localStorage.halt = false; localStorage.halt = true; ``` [Answer] # Geometry Dash 2.2 Editor Glitch - 2 objects [![enter image description here](https://i.stack.imgur.com/5bShI.jpg)](https://i.stack.imgur.com/5bShI.jpg) **Explanation:** The random trigger randomly toggles (disables) Group ID 1 or 2 with a 50% chance. The purple pad is on reverse mode (meaning that if the cube touches it, the cube moves backward, which goes to the left forever and ever.). Since the purple pad has Group ID 2, it has a 50% chance of being disabled, which means that the cube can pass through it to the end of the level, which will halt. **How to reproduce this:** Purple pad is on reverse mode and has Group ID 1. [![enter image description here](https://i.stack.imgur.com/tw1yf.png)](https://i.stack.imgur.com/tw1yf.png) Inside the random trigger. [![enter image description here](https://i.stack.imgur.com/Iww7S.png)](https://i.stack.imgur.com/Iww7S.png) [Answer] # C ``` #include <unistd.h> main() { while (getpid()&2); } ``` [Answer] # [Random Brainfuck](https://github.com/TryItOnline/brainfuck), 5 bytes ``` ?[--] ``` [Try it online!](https://tio.run/##K0rMS8nP1U0qSszMSytNzv7/3z5aVzf2/38A "Random Brainfuck – Try It Online") Random BF extends BF's set of primitives with the `?`, which generates a random byte and stores it in the current cell. That is, it generates an integer from 0-255. Given that there are an equal amount of odds and evens in that range, there is a 50% chance that the current cell is set to an even number after the first step. The `[--]` endlessly decrements the current cell by two, as long as the current cell is not zero. Therefore, all even numbers will terminate. On the other hand, since parity is invariant mod 256, all odd numbers will loop forever, never quite reaching zero. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 2 bytes ``` %@ ``` [Try it online!](https://tio.run/##y8kvLvn/X9Xh/38A "Lost – Try It Online") Although this is apparently a popcon, I figure the language itself is adequately interesting! Lost is a fairly standard toroidal 2D language, with the caveat that the instruction pointer's initial position and direction are completely random. Additionally, in order to make it possible to write deterministic programs, there's a piece of global state called the *safety* which doesn't allow the program to halt by reaching `@` until it's been turned off by `%`. So, this program has three cases: * 50% of the time, the IP starts moving left or right. It eventually reaches both instructions, and the program halts. * 25% of the time, the IP starts moving up or down on `%`. The safety is turned off, but it never reaches `@`, so the program does not halt. * 25% of the time, the IP starts moving up or down on `@`. The safety is never turned off, so the program does not halt. [Answer] # [INTERCAL](http://www.catb.org/~esr/intercal/), 59 bytes ``` DO %50 (1) NEXT DO COME FROM COMING FROM (1) PLEASE GIVE UP ``` [Try it online!](https://tio.run/##y8wrSS1KTsz5/9/FX0HV1EBBw1BTwc81IoQLyHf293VVcAvy9wWxPP3cwWwukIoAH1fHYFcFd88wV4XQgP//AQ "INTERCAL – Try It Online") `COME FROM COMING FROM` makes an endless loop, but there is a 50% chance to skip to the end of the program. [Answer] # Ruby ``` n = 2*rand(1...49)+1; divisors = (1...100).select{|x|n % x == 0}.count until divisors == 2 print n ``` There are exactly 24 odd primes between 0..100, the largest being 97. This algorithm chooses a random odd number within the range and repeats until it finds a prime: This particular implementation has two bugs: * an exclusive range is used, meaning that 99 is never tested, meaning there are only 48 possible values for `n`, of which 24 are primes. * while `n` was meant to be redrawn at each iteration, only the primality testing is executed in the loop. If at first it doesn't succeed, it will try again - but with the same number. [Answer] # [><>](https://esolangs.org/wiki/Fish), 3 bytes ``` x;v ``` [Try it online!](https://tio.run/##S8sszvj/v8K67P9/AA "><> – Try It Online") I... don't actually know ><>, but this should work on the same principle as the existing answers, just by "rerolling" vertical travel and looping if it goes left rather than down. [Answer] ## GolfScript ``` 2rand{.}do ``` I know this isn't a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, but I golfed it anyway. :) --- Alternatively, here's a GolfScript implementation of [Keith Randall's solution](https://codegolf.stackexchange.com/a/17151): ``` 2{2*.rand}do ``` In theory, this will have an exactly 1/4 + 1/8 + 1/16 + ... = 1/2 probability of halting. In practice, though, it will always eventually run out of memory and halt, because the denominator keeps getting longer and longer. [Answer] # BASH ``` #!/bin/bash set -e sed -i 's/true\;/false\;/' $0 while false; do echo -n ''; done; sed -i 's/false\;/true\;/' $0 ``` Just a fun self-modifying script. Note: the empty quoted string on `echo -n ''` are just for clarity. They can be removed without loss of functionality. [Answer] I felt like golfing this one: ### Befunge - 5 chars ``` ?>< @ ``` (I'm not sure whether this actually works as I don't have a befunge compiler on me) [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 113 bytes ``` sometimes i,i think i get a choice if its a thing i know i do affect,i bet i do win i`m sorry if it breaks o-h no ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?HYtBDsMgDATvvGIf0P6pQExYIbCELUV9fermtJodjekU5xQDX4R3rgHiFEdG7coqiQ10C/7bM@xYesUcityaVI@wRPA8F1fiZ8J07y@eFGVLHpb03bH0vks@fg) [Answer] Somewhat obfuscated solution: # Haskell ``` import Control.Monad import Control.Monad.Random -- package MonadRandom import Control.Monad.Trans.Maybe import Data.Numbers.Primes -- package primes -- | Continue the computation with a given probability. contWithProb :: (MonadRandom m, MonadPlus m) => Double -> m () contWithProb x = getRandomR (0, 1) >>= guard . (<= x) loop :: MonadRandom m => MaybeT m () loop = contWithProb (pi^2/12) >> mapM_ (contWithProb . f) primes where f p = 1 - (fromIntegral p)^^(-2) main = evalRandIO . runMaybeT $ loop ``` # Python The same solution expressed in Python: ``` import itertools as it import random as rnd from math import pi # An infinite prime number generator # Copied from http://stackoverflow.com/a/3796442/1333025 def primes(): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # old code here: # x = p + q # while x in D or not (x&1): # x += p # changed into: x = q + 2*p while x in D: x += 2*p D[x] = p def contWithProb(p): if rnd.random() >= p: raise Exception() if __name__ == "__main__": rnd.seed() contWithProb(pi**2 / 12) for p in primes(): contWithProb(1 - p**(-2)) ``` ## Explanation > > This solution makes use of the fact that the infinite product \$\Pi(1-p^{-2})\$ converges to \$\frac{6}{\pi^2}\$. This is because \$\zeta(2)=\Pi(\frac{1}{1-p^{-2}})\$ [converges to](https://en.wikipedia.org/wiki/Particular_values_of_Riemann_zeta_function#Even_positive_integers) \$\frac{\pi^2}{6}\$. > > > [Answer] # [Pyt](https://github.com/mudkip201/pyt), 3 bytes ``` ɹ`ł ``` [Try it online!](https://tio.run/##K6gs@f//5M6Eo03//wMA "Pyt – Try It Online") ``` ɹ get a random bit (0 or 1 with equal probability) `ł loop while top of stack is truthy (1 is truthy; 0 is not) ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 4 bytes ``` x; > ``` [Try it online!](https://tio.run/##S8sszvj/v8Kay@7/fwA "><> – Try It Online") [Answer] # ><>, 5 bytes and a beautiful 2x2 square ``` x; >< ``` `x` sends the instruction pointer in a random direction; If it sends left or right the IP will hit `;` and terminate. If it goes up or down the IP will get stuck in the infinite `><` loop, being sent back and forth between the two. [Answer] # C ``` int main() { char i; while(i&1); } ``` [Answer] **Scala** ``` object HaltOrNot extends App { val x = scala.util.Random.nextLong while (((scala.util.Random.nextLong & 0xFFFFFFFFFFFFFFFEL) ^ x) != 0) {} } ``` If x is odd positive or even negative, this program will *never* halt. If x is even positive or odd negative, this program will definitely halt... someday... after thousands of years... (e.g., if your machine can test 100 Mio loops per second it will terminate after 2924 years in expectation) [Answer] ## TI-Basic ``` :Lbl 1:If round(rand):Pause:Goto 1 ``` [Answer] ## Python, 48 ``` import random a=random.randrange(2) while a:pass ``` [Answer] # Perl ``` BEGIN { # Do the following block 50% of time. if (int rand 2) { # Create a function that doubles values. *double = sub { 2 * shift; }; } } double / 3 while 1; # Calculates double divided using / ``` Not code golf, so I could avoid unreadable code (because what it does is more important). It randomly declares a function during compilation phase. If it gets declared, `double` gets regular expression as an argument. If it doesn't get declared, `double` is a bareword, and Perl divides it by `3` endlessly. This abuses Perl's bareword parsing, in order to get parser parse the same code two different ways. [Answer] # Java ``` import java.io.*; public class HaltNoHalt { public static void main(String[] args) throws Exception { RandomAccessFile f = new RandomAccessFile("HaltNoHalt.java", "rw"); f.seek(372); int b = f.read(); f.seek(372); f.write(b ^ 1); Runtime.getRuntime().exec("javac HaltNoHalt.java"); while ((args.length & 1) == 1); } } ``` This self-modifies the code to toggle the `== 1` to `== 0` and back, every time it's run. Save the code with newlines only or the offset will be wrong. The `args.length` is just to prevent compiler optimizations. [Answer] # Java ``` import java.util.Random; class Halt50 { public static void main(String[] args){ if(new Random().nextInt(2)==0)for(;;); } } ``` [Answer] # JavaScript (Node.js), 24 bytes It was incorrect, but somehow correcting it removed 2 bytes, thanks [Roman Czyborra](https://codegolf.stackexchange.com/users/58925) for pointing out it was incorrect And another -2 because I forgot how to JS ``` if(Date.now()%2)for(;;); ``` `Date.now()` returns the amount of milliseconds since the Unix time epoch, which has a 50% chance to be even at the moment of running the program. [Answer] # [Alice](https://github.com/m-ender/alice), 5 bytes ``` 2U$v@ ``` [Try it online!](https://tio.run/##S8zJTE79/98oVKXM4f9/AA "Alice – Try It Online") ``` 2 Pushes the number 2 on the stack U Pops 2, pushes a random number in the range [0,2) on the stack $ Pops the random number, if 0 skip the next instruction v Now moves vertically forever @ Halt ``` [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 19 bytes ``` 1 if(i>0)goto 1 end ``` [Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/hcUZeaVaOlklKanamRq/jdUyEzTyLQz0EzPL8lXMORKzUv5/x8A "Fortran (GFortran) – Try It Online"). Since the lazy programmer did not initialise `i`, it is a random 32 bit integer, populated from whatever bits were floating around in that memory space before. [Answer] **Javascript** JS has these Object URL things, which are generated when you create a file. The hex is all meaningless nonsense, but not in this case! Therefore, something like this works: ``` var blob = URL.createObjectURL(new Blob([""])) // The blob looks something like "blob:null/01234567-1234-1234-1234-0123456789ab" and is hex, which can be exploited, really, any character works! while (TextEncoder && new TextEncoder().encode(blob)[10] > 56) { // Forever! } ``` [Answer] ## Python, 19 bytes ``` while id(1)>>17&1:1 ``` [**Run online**](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhabyzMyc1IVMlM0DDXt7AzN1QytDCEyUAUwhQA) This gets the address of the constant `1` in memory, and gets the 17th bit from the right. It then loops forever if the bit is `1`. I can't use a later bit to save a byte, because those bits seem to be constant between runs. The last bits are always `0011110000`. Some debug code: ``` print(bin(id(1))) print(bin(id(1)>>17)) print(id(1)>>17&1) ``` ]
[Question] [ In golf, the standard scratch of a course is calculated using this formula: ``` (3*num_of_3_par_holes + 4*num_of_4_par_holes + 5*num_of_5_par_holes) - difficulty_rating ``` Your task is to calculate the standard scratch of a golf course, given these 4 inputs. You should take input in any standard form in the format ``` [num_of_3_pars, num_of_4_pars, num_of_5_pars], difficulty rating ``` but if it saves bytes, you many take input in a different way. You should output the final result by any accepted method on meta, such as returning from a function. Shortest code wins because this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! [Answer] # Scratch, [145 bytes](http://scratchblocks.github.io/#?lang=oto&script=adi()-%20temi%0A(a)kuati(thadi%0Aadi()-%20temi%0A(b)kuati(thadi%0Aadi()-%20temi%0A(c)kuati(thadi%0Aadi()-%20temi%0A(d)kuati(thadi%0Ama(((c)-((a)%2B(d)))%2B((4)*(((a)%2B(b))%2B(c) -2 thanks to boboquack -??? because writing it in [Oto](https://en.wikipedia.org/wiki/Oto-Manguean_languages) is shorter than English (Because Scratch is the standard scratch.) ![adi()- temi (a)kuati(thadi adi()- temi (b)kuati(thadi adi()- temi (c)kuati(thadi adi()- temi (d)kuati(thadi ma(((c)-((a)+(d)))+((4)*(((a)(b))+(c translation: ask()and wait set(a)to (answer ask()and wait set(b)to (answer ask()and wait set(c)to (answer ask()and wait set(d)to (answer say(((c)-((a)+(d)))+((4)*(((a)+(b))+(c](https://i.stack.imgur.com/MUYXI.png) Here's a sample run: ![a=18,b=13,c=41,d=23;answer=124](https://i.stack.imgur.com/f0F64.png). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` JḊ~æ.N ``` [Try it online!](https://tio.run/##y0rNyan8/9/r4Y6uusPL9Pz@//9vaGBgoKNgCCGAGAA "Jelly – Try It Online") ### How it works ``` JḊ~æ.N Main link. Argument: [a, b, c, d] J Indices; yield [1, 2, 3, 4]. Ḋ Dequeue; yield [2, 3, 4]. ~ Bitwise NOT; yield [-3, -4, -5]. N Negate; yield [-a, -b, -c, -d]. æ. Dot product; yield (-3)(-a) + (-4)(-b) + (-5)(-c) + (-d) = 3a + 4b + 5c - d. ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 24 bytes ``` (a,b,c,d)->a*3+b*4+c*5-d ``` [Try it online!](https://tio.run/##LYyxCoMwFEV3v@KNiUah1U6lHbt1ciwdXhIjsRrFRKGI357G0Decx4V7T4cr5uPUmE5@/LTwXgsQPVoLT9QGtgRAG9fMCkUDD9iOBIocRHaQR4pISa@wh8XfYx268NZRSxiCjdRu1qZ9vQHn1tIohyBVcPMEGWeCSZrfMS0znlaZSC@59BDvGqv117pmKMbFFVMwud4QVShyYmdWsorSo7Unu/8B "Java (OpenJDK 8) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 22 bytes ``` (a#b)c d=3*a+4*b+5*c-d ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNROUkzWSHF1lgrUdtEK0nbVCtZN@V/bmJmnoKtQkFRZl6JgoqChrGykaapgvl/AA "Haskell – Try It Online") Usage: `(3#2)5 7` yields `35`. This not so nice input format is one byte shorter than the straight forward solution: ``` f a b c d=3*a+4*b+5*c-d ``` --- **Point-free and nice input format:** (23 bytes) ``` (-).sum.zipWith(*)[3..] ``` [Try it online!](https://tio.run/##y0gszk7Nyflfrauck5iXXpqYnqrgHBCgrFvLlWYb819DV1OvuDRXryqzIDyzJENDSzPaWE8v9n9uYmaegq1CQVFmXomCikKaQrSxjpGOaayC@X8A "Haskell – Try It Online") Bind to `f` and call with `f [3,2,5] 7`. [Answer] # Mathematica, 13 ~~14~~ bytes ``` {3,4,5,-1}.#& ``` Thanks to @GregMartin. Take input as a length-4 list. [Answer] # [Julia 0.5](http://julialang.org/), 15 bytes ``` !v=v⋅[3:5;-1] ``` [Try it online!](https://tio.run/##yyrNyUw0/f9fscy27FF3a7Sxlam1rmHsf8VoQwMDAx1DMNYxjVWosVMoKMrMK/kPAA "Julia 0.5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 28 bytes ``` lambda a,b,c,d:3*a+4*b+5*c-d ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFRJ0knWSfFylgrUdtEK0nbVCtZN@V/QVFmXolGmoaJjoKxjoKRjoKhpuZ/AA "Python 3 – Try It Online") [Answer] # Perl6, 16 characters ``` 3* *+4* *+5* *-* ``` (Yepp, that is a sub.) Sample run: ``` > say 3* *+4* *+5* *-* { ... } > say (3* *+4* *+5* *-*)(4, 3, 2, 1) 33 ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKsQ899YS0FL2wREmAIJXa3/1lzFiSBZDUsdBTMdBWMdBVNNuJiFjgIQmQCFNa3/AwA "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 7 bytes ``` 3r5×⁸S_ ``` [Try it online!](https://tio.run/##y0rNyan8/9@4yPTw9EeNO4Lj////H22oo2Cko2Ac@98IAA "Jelly – Try It Online") -3 bytes thanks to Erik The Outgolfer! ## How it works! ``` 3r5×⁸S_ Main link: a, the pars as a list and b, the difficulty rating S The sum of 3r5 [3, 4, 5] × each element times ⁸ the left argument (a) _ Subtract the right argument (b) ``` [Answer] # Javascript, 24 bytes ``` (a,b,c,d)=>3*a+4*b+5*c-d ``` [Answer] # C#, 24 bytes ``` (a,b,c,d)=>a*3+b*4+c*5-d ``` [Answer] # x86-64 Machine Code, 14 bytes ``` 8D 3C 7F 8D 14 92 8D 04 B7 01 D0 29 C8 C3 ``` A function following the System V AMD64 calling convention (ubiquitous on Gnu/Linux systems) that takes four integer parameters: * `EDI` = num\_of\_3\_par\_holes * `ESI` = num\_of\_4\_par\_holes * `EDX` = num\_of\_5\_par\_holes * `ECX` = difficulty\_rating It returns a single value, the standard scratch, in the `EAX` register. **Ungolfed assembly mnemonics:** ``` ; int ComputeStandardScratch(int num_of_3_par_holes, ; int num_of_4_par_holes, ; int num_of_5_par_holes, ; int difficulty_rating); lea edi, [rdi+rdi*2] ; EDI = num_of_3_par_holes * 3 lea edx, [rdx+rdx*4] ; EDX = num_of_5_par_holes * 5 lea eax, [rdi+rsi*4] ; EAX = EDI + (num_of_4_par_holes * 4) add eax, edx ; EAX += EDX sub eax, ecx ; EAX -= difficulty_rating ret ; return, leaving result in EAX ``` Just a simple translation of the formula. What's interesting is that this is essentially the same code that you would write when optimizing for *speed*, too. This really shows the power of the x86's `LEA` instruction, which is designed to *l*oad an *e*ffective *a*ddress, but can do addition and scaling (multiplication by low powers of 2) in a single instruction, making it a powerful multi-purpose arithmetic workhorse. [Answer] # dc, 14 characters ``` ?3*?4*+?5*+?-p ``` The numbers need to be passed on separate lines. Sample run: ``` bash-4.4$ dc -e '?3*?4*+?5*+?-p' <<< '4 > 3 > 2 > 1' 33 ``` [Try it online!](https://tio.run/##S0n@/9/eWMveREvb3hSIdQv@/zfhMuYy4jIEAA "dc – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 14 bytes ``` @(a)[3:5 -1]*a ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1Ez2tjKVEHXMFYr8X@aRrS5tam1pbVprOZ/AA "Octave – Try It Online") About twice as long as the [MATL answer](https://codegolf.stackexchange.com/a/130192/32352). I initially literally ported this to MATL, but it turned out `iY*` is longer than just `*s`. Note that the input `a`, containing the holes in order and then the difficulty, should be a column vector. [Answer] ## [Julia](http://julialang.org/), 21 bytes ``` f(a,b,c,d)=3a+4b+5c-d ``` [Try it online!](https://tio.run/##yyrNyUw0/f8/TSNRJ0knWSdF09Y4UdskSds0WTflf0FRZl5JTp5GmoaljpmOsY6ppiYXQsxCx0LHRMdYU/M/AA "Julia 0.5 – Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 7 bytes ``` 'π𝐂𝕋𝐬S𝕊 ``` Explanation: ``` 'π Push 345 The character ' pushes the next character's index in the codepage plus 100. The characters ", + and * do that same thing except add a different number. This means that in Neim, all 3 digit numbers can be expressed with 2 characters. This commit was pushed 8 days before the answer was posted. 𝐂 Get the characters 𝕋 Vectorised multiply with the input 𝐬 Sum the resulting list S𝕊 Subtract the input ``` Alternative program: `3𝐈ᛖ𝕋𝐬S𝕊` Instead of pushing `345` and then getting the characters, creates the array `[1 2 3]` using `3𝐈`, then adds 2 to each element with `ᛖ`. [Try it online!](https://tio.run/##y0vNzP3/X/18w4e5E5o@zJ3aDaTXBAMZXf//RxsqGCkYx3IZAwA "Neim – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 30 bytes ``` e;f(a,b,c,d){e=3*a+4*b+5*c-d;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/VOk0jUSdJJ1knRbM61dZYK1HbRCtJ21QrWTfFuvZ/bmJmnoZmdUFRZl5JmoaSakpMnpJOmoahjpGOsY6RpiZQCQA "C (gcc) – Try It Online") [Answer] # [Swift 3](https://swift.org), ~~25~~ 19 bytes I realised you do not need the `var f=`, because you can call it like a Python lambda: ``` {$0*3+$1*4+$2*5-$3} ``` [Test it online!](http://swift.sandbox.bluemix.net/#/repl/595d1428ce92ef1217b41e45) **Usage:** `{$0*3+$1*4+$2*5-$3}(a,b,c,d)`, where `a,b,c,d` are the parameters. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 39 bytes ``` ,[->+++<],[->++++<],[->+++++<],[->-<]>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1rXTltb2yYWykBiQZm6NrF2ev//AwA "brainfuck – Try It Online") Takes input and prints output as ASCII characters; for example, the value 99 would be represented as c. ### Explanation: ``` , Take the first input in Cell 0 [ ] While the data being pointed to (Cell 0) is nonzero ->+++< Decrement Cell 0 and add 3 to Cell 1 Now 4 times the first input is in Cell 1 , Take the second input in Cell 0 [->++++<] Add 4 times the second input to Cell 1 ,[->+++++<] Take the third input in Cell 0 and add five times its value to Cell 1 , Take the fourth input in Cell 0 [ ] While the data being pointed to (Cell 0) is nonzero ->-< Decrement Cells 0 and 1 >. Print the value in Cell 1 ``` [Answer] # [Gallina](https://coq.inria.fr/refman/Reference-Manual003.html), 38 bytes ``` Definition f a b c d := 3*a+4*b+5*c-d. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 16 bytes ``` ∧5⟦₁↺b;?z×ᵐġ₃+ᵐ- ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HHctNH85c9amp81LYrydq@6vD0h1snHFn4qKlZG8jQ/f8/2lDHSMdYxyj2fxQA "Brachylog – Try It Online") -2 thanks to [Fatalize](https://codegolf.stackexchange.com/users/41723/fatalize). [Answer] # [,,,](https://github.com/totallyhuman/commata), 12 bytes ``` ↻5×↻4×↻3×↻-# ``` ## Explanation Take input 4, 3, 2, 1 for example. ``` ↻5×↻4×↻3×↻-# implicit input [4, 3, 2, 1] ↻ rotate the stack clockwise [1, 4, 3, 2] 5 push 5 [1, 4, 3, 2, 5] × pop 2 and 5 and push 2 * 5 [1, 4, 3, 10] ↻ rotate the stack clockwise [10, 1, 4, 3] 4 push 4 [10, 1, 4, 3, 4] × pop 3 and 4 and push 3 * 4 [10, 1, 4, 12] ↻ rotate the stack clockwise [12, 10, 1, 4] 3 push 3 [12, 10, 1, 4, 3] × pop 4 and 3 and push 4 * 3 [12, 10, 1, 12] ↻ rotate the stack clockwise [12, 12, 10, 1] - pop 10 and 1 and push 10 - 1 [12, 12, 9] # pop 12, 12, 9 and push the sum [33] implicit output ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 36 bytes ``` w;r5*U4I;I3*r;UW;;r;<\r/;r-I/+p+O@;w ``` [Try it online!](https://tio.run/##Sy5Nyqz4/7/cushUK9TE09rTWKvIOjTc2rrI2iamSN@6SNdTX7tA29/Buvz/fxMFQ0MFYwUzMwA "Cubix – Try It Online") ``` w ; r 5 * U 4 I ; I 3 * r ; U W ; ; r ; < \ r / ; r - I / + p + O @ ; w . . . . . . . . . . . . . . . . . . ``` [Watch It Run](https://ethproductions.github.io/cubix/?code=ICAgICAgdyA7IHIKICAgICAgNSAqIFUKICAgICAgNCBJIDsKSSAzICogciA7IFUgVyA7IDsgciA7IDwKXCByIC8gOyByIC0gSSAvICsgcCArIE8KQCA7IHcgLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=NCAxMSAzIDY2&speed=20) A fairly linear program that winds back around onto itself a few times. Basic steps: * `I3*r;U;` get the first input, multiply by 3 and clean up stack * `I4*/r\` get next input and multiply by 4. Rotate result down. * `Iw5*Ur;w<;r;;W` get next input, multiply by 5 and clean up the stack * `I-r;w;` get last input, subtract from par 5 result and clean up stack * `/+p+O\@` add to par 4 result, bring par3 result to top add, output and halt [Answer] # HP-15C (RPN), 14 bytes Instruction hex codes: ``` 41 C4 F5 FC C5 F4 FC FA C5 F3 FC FA 31 FB ``` Readable version: ``` 001 { 44 1 } STO 1 002 { 33 } R⬇ 003 { 5 } 5 004 { 20 } × 005 { 34 } x↔y 006 { 4 } 4 007 { 20 } × 008 { 40 } + 009 { 34 } x↔y 010 { 3 } 3 011 { 20 } × 012 { 40 } + 013 { 45 1 } RCL 1 014 { 30 } − ``` The four numbers are loaded into the stack in order before running the program. [Answer] # Excel VBA, 20 Bytes Anonymous VBE immediate window function that takes input from the range `[A3:A6]` of which `[A3:A5]` represent the number of `3`,`4` and `5` par holes, respectively and `[A6]` represents the difficulty. Outputs to the VBE immediate window ``` ?[3*A3+4*A4+5*A5-A6] ``` The above is a condensed version of the call ``` Debug.Print Application.Evaluate("=3*A3+4*A4+5*A5-A6") ``` Where `"=3*A3+4*A4+5*A5-A6"` is given to be the formula of an anonymous cell, as indicated by the `[...]` wrapper, and `?` is the deprecated version of the `Print` call with an implicit `Debug.` by context ### More fun Version, 34 Bytes Anonymous VBE immediate window function with same I/O conditions as above. ``` ?[SUMPRODUCT(A3:A5,ROW(A3:A5))-A6] ``` The above is a condensed version of the call ``` Debug.Print Application.Evaluate("=SUMPRODUCT(A3:A5,ROW(A3:A5))") ``` Where `"=SUMPRODUCT(A3:A5,ROW(A3:A5))"` is given to be the formula of an anonymous cell, as indicated by the `[...]` wrapper, and `?` is the deprecated version of the `Print` call with an implicit `Debug.` by context. In this version, the range of `[A3:A5]` and the row numbers of that range (`ROWS(A3:A5)`) are passed as arrays ### Excel Version, 18 bytes Of course, the versions above lend themselves thusly to excel versions of ``` =3*A3+4*A4+5*A5-A6 ``` and ``` =SUMPRODUCT(A3:A5,ROW(A3:A5))-A6 ``` [Answer] # [R](https://www.r-project.org/), ~~25~~ 23 bytes ``` cat(c(3:5,-1)%*%scan()) ``` [Try it online!](https://tio.run/##K/r/PzmxRCNZw9jKVEfXUFNVS7U4OTFPQ1Pzv4WCmYKJgrHpfwA "R – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~10~~ 9 bytes ``` `-Σz*d345 ``` [Try it online!](https://tio.run/##yygtzv7/P0H33OIqrRRjE9P///9HG@sY6ZjG/jcHAA "Husk – Try It Online") [Answer] # [Befunge](https://github.com/catseye/FBBI), 15 bytes ``` &3*&4*+&5*+&-.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X81YS81ES1vNFIh19Rz@/zdVMDRQMFMwMgAA "Befunge-98 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt/), 12 bytes ``` *3+V*4+W*5-X ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=KjMrVio0K1cqNS1Y&input=NSwzLDQsNw==) [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 14 bytes ``` 3*>4*>5*>>++,- ``` [Try it online!](https://tio.run/##SypKzMxLz89J@//fWMvORMvOVMvOTltbR/f///8m/43/G/03BAA "Braingolf – Try It Online") ]
[Question] [ For a given list of number \$[x\_1, x\_2, x\_3, ..., x\_n]\$ find the last digit of \$x\_1 ^{x\_2 ^ {x\_3 ^ {\dots ^ {x\_n}}}}\$ Example: ``` [3, 4, 2] == 1 [4, 3, 2] == 4 [4, 3, 1] == 4 [5, 3, 2] == 5 ``` Because \$3 ^ {(4 ^ 2)} = 3 ^ {16} = 43046721\$. Because \$4 ^ {(3 ^ 2)} = 4 ^ {9} = 262144\$. Because \$4 ^ {(3 ^ 1)} = 4 ^ {3} = 64\$. Because \$5 ^ {(3 ^ 2)} = 5 ^ {9} = 1953125\$. Rules: This is code golf, so the answer with the fewest bytes wins. If your language has limits on integer size (ex. \$2^{32}-1\$) n will be small enough that the sum will fit in the integer. Input can be any reasonable form (stdin, file, command line parameter, integer, string, etc). Output can be any reasonable form (stdout, file, graphical user element that displays the number, etc). Saw on code wars. [Answer] # JavaScript (ES7), 22 bytes Limited to \$2^{53}-1\$. ``` a=>eval(a.join`**`)%10 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i61LDFHI1EvKz8zL0FLK0FT1dDgf3J@XnF@TqpeTn66RppGtLGOgomOglGspqaCvr6CIReaNFDOGCFtgl3aEJe0KYpuUwWF/wA "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), 25 bytes ``` Reduce(`^`,scan(),,T)%%10 ``` [Try it online!](https://tio.run/##K/r/Pyg1pTQ5VSMhLkGnODkxT0NTRydEU1XV0OC/MZcJlxHXfwA "R – Try It Online") [Answer] ## Haskell, 19 bytes ``` (`mod`10).foldr1(^) ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyMhNz8lwdBAUy8tPyelyFAjTvN/bmJmnoKtQkFRZl6JgopCmkK0sY6JjlHs/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") [Answer] # HP 49G RPL, 36.5 bytes Run it in APPROX mode (but enter the program in EXACT mode). Takes input on the stack with the first element deepest in the stack, as integers or reals. ``` WHILE DEPTH 1 - REPEAT ^ END 10 MOD ``` It straightforwardly exponentiates on the stack as in Sophia's solution until there is one value left, then takes it mod 10 to get the last digit. The reason I use APPROX for computation is because 0.0^0.0 = 1 (when they are both reals), but 0^0 = ? (when they are both integers). APPROX coerces all integers to reals, so the input is fine with either. However, I use EXACT to enter the program because 10 (integer) is stored digit-by-digit, and is 6.5 bytes, but 10.0 (real) is stored as a full real number, and is 10.5 bytes. I also avoid using RPL's reduce (called STREAM) because it introduces an extra program object, which is 10 bytes of overhead. I already have one and don't want another. Limited to the precision of an HP 49G real (12 decimal digits) -10 bytes after empty list -> 1 requirement was removed. -2 bytes by taking input on stack. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 17 15 bytes ``` 1[^z1<M]dsMxzA% ``` [Try it online!](https://tio.run/##S0n@b6xgomD03zA6rsrQxjc2pdi3ospR9X/BfwA "dc – Try It Online") Takes input from the stack, outputs to the stack. Very straightforward implementation - exponentiates until only one value is left on the stack and mod for the last digit. Thanks to brhfl for saving two bytes! [Answer] # [J](http://jsoftware.com/), 5 bytes -3 bytes thanks to cole! ``` 10|^/ ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N/QoCZO/78ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoKxgomCUcV/AA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` .«mθ ``` [Try it online!](https://tio.run/##MzBNTDJM/e/6X@/Q6txzO/7/jzbWUTDRUTCKBQA "05AB1E – Try It Online") **Explanation** ``` .« # fold m # power θ # take the last digit ``` [Answer] # Pure [Bash](https://www.gnu.org/software/bash/) (builtins only - no external utilities), 21 ``` echo $[${1//,/**}%10] ``` Input is given on the command line as a comma-separated list. Bash integers are subject to normal signed integer limits for 64- and 32-bit versions. [Try it online!](https://tio.run/##S0oszvj/PzU5I19BJVql2lBfX0dfS6tW1dAg9v///8Y6JjpGAA "Bash – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` Power@##~Mod~10& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T8gvzy1yEFZuc43P6XO0EDtv6Y1V0BRZl5JdLWycq2uXRpQLlbNwcGhmour2lhHwURHwahWB8g20lEAckFkLRdX7X8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 14 bytes ``` {([**] $_)%10} ``` [Try it online!](https://tio.run/##K0gtyjH7n1uplmr7v1ojWksrVkElXlPV0KD2vzVXcWKlglqqhoaxjomOkabmfwA "Perl 6 – Try It Online") Uses the reduction meta square brackets with the operator \*\*, modulo 10. [Answer] # [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), 30 bytes ``` lambda N:eval('**'.join(N))%10 ``` [Try it online!](https://tio.run/##PY1NCsIwGAXX5hTfRpKUEGyjIIV6hFxAXURqMCV/JEEopWeP7cbtG2ZenMsneFH18KhWudeoQPbvr7IENw3mUzCeSEqP7akaF0MqkOeMdEggwXhwKpJcEs/RmsJ2xnMZjac9OsRkfCH4vqxPGG6wrJhvnlPbxuCfZqD3A1oFnKFDLbpcBbSd@AE "Python 3 – Try It Online") The input `N` is expected to be an iterable object over *string representations of number literals*. [Answer] # [Julia 0.6](http://julialang.org/), 30 bytes ``` first∘digits∘x->foldl(^,x) ``` [Try it online!](https://tio.run/##yyrNyUw0@/8/LbOouORRx4yUzPTMkmIgo0LXLi0/JyVHI06nQvO/Q3FGfrmCBn5VmhrRhjpGOsaxmlzEqjfWMdExAqonWkNSZrqSsbGxoZIOmAWjjZRiNf8DAA "Julia 0.6 – Try It Online") This is an anon function ∘ is the composition operator. It is multiple bytes [Answer] # Ruby, ~~41~~ 47 bytes Size increase due to handling of any 0 in the input array, which needs extra consideration. Thanks to `rewritten` ``` ->a{a.reverse.inject{|t,n|n<2?n:n**(t%4+4)}%10} ``` This is solved as I believe the original source intended, i.e. for very large exponentiations that will not fit into language native integers - the restriction is that the array will sum into `2**32-1`, not that the interim calculations are also guaranteed to fit. In fact that would seem to be the point of the challenge on Code Wars. Although Ruby's native integers can get pretty big, they cannot cope with the example below processed naively with a %10 at the end E.g. Input: `[999999,213412499,34532597,4125159,53539,54256439,353259,4314319,5325329,1242149,142219,1243219,14149,1242149,124419,999999999]` Output: `9` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` `.gGm}T% ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/QS/dPbc2RPX//2hjHQUTHQWjWAA "05AB1E – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 [bytes](https://github.com/abrudz/SBCS) ``` 10|*⌿ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///39CgRutRz/7/j/qmPmqboPGot8/oUVczkBcc5AwkQzw8gzWB9H9jBRMFIwA "APL (Dyalog Unicode) – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 84 bytes ``` a=>{int i=a.Length-1,j=a[i];for(;i-->0;)j=(int)System.Math.Pow(a[i],j);return j%10;} ``` [Try it online!](https://tio.run/##jZE9a8MwEIbn@FfcUrBA/u4HVLWXQqcEAh06GA9CkR2ZRDKS3LQY/3ZX@WghtBQPd9zwPPceHDMBU5pPAGxHjYG1Vo2mew9gcAVgLLWCwbsSG1hRIX1jtZBNWQHVjUEn5kwCvH4ay/fhSy/Zk5C2rLDrRZ1PNC8GN4LIabjksrHbIMFtTktRkVppn4ggKGKC2tx3GLrsWVG7Ddfq4B853CKiue21hPYmick4kYW3uJDPShq14@GbFpYvheR@7Ut@KKshw7c4HREiEEXAPzrOLN88QjJDTfHdX2o6Q3WZOPut3s86@CzCtfowJ/XbvFYzbxFF/8tw/FZc/eRKZcH0Xae023B67uj6OH0B "C# (.NET Core) – Try It Online") * -7 bytes thanks to @raznagul [Answer] # [C (gcc)](https://gcc.gnu.org/), 56 * Saved 4 bytes thanks to @JonathanFrech Recursive function `r()` called from macro `f` - normal stack limits apply. ``` R;r(int*n){R=pow(*n,n[1]?r(n+1):1);} #define f(n)r(n)%10 ``` Input given as a zero-terminated int array. This is under the assumption that none of the xn are zero. [Try it online!](https://tio.run/##RYzLCoMwFET3@YqLIiQ2Fl@r2seHWBchvgJ6laitIP5609hNZzfnMCODRkrjKpTdUlZwneZSDef2Tv6oF3NridFU4ewj23Q1LxphHN7UR455VDw0xVPELhHLduKWVa2wgpois5x5UWjsEnqhEI4PELqRHGQrNPi@LS9GNgI2h1zzAm6wJRxSDjGHcM/IT47a6po6XvlEh9v7lbGM7MYkPOXxR9adaCYTdP0X "C (gcc) – Try It Online") [Answer] # [PHP](https://php.net/), ~~50~~ 44 bytes *-6 bytes from @Shaggy* ``` <?=eval("return ".join('**',$argv).";")%10?> ``` [Try it online!](https://tio.run/##K8go@G9jX5BRoKCSWJReZhttrGOiYxRrrWBvBxS3TS1LzNFQKkotKS3KU1DSy8rPzNNQ19JS1wGr1tRTslbSVDU0ACr@/x8A "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, 7 bytes ``` OvUqp)ì ``` [Try it online!](https://tio.run/##y0osKPn/378stLBA8/Ca//@jTXUUjHUUjGK5uHQzAA) ## Explanation: ``` OvUqp)ì Ov ) // Japt eval: q // Join U // Input with p // Power method ì // Split into an array of numbers -h // Return the last number ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-h`, ~~7~~ 6 bytes If input can be taken in reverse order then the first character can be removed. Limited to `2**53-1`. ``` Ôr!p ì ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=1HIhcCDs&input=WzMsNCwyXQotaA==) --- ## Explanation ``` Ô :Reverse the array r :Reduce by !p : Raising the current element to the power of the current total, initially the first element ì :Split to an array of digits :Implicitly output the last element ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` U*@/DṪ ``` [Try it online!](https://tio.run/##y0rNyan8/z9Uy0Hf5eHOVf///4821lEw0VEwigUA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~45~~ 43 bytes ``` lambda x:reduce(lambda b,a:a**b,x[::-1])%10 ``` [Try it online!](https://tio.run/##LYrRCoMgGEav8yn@GynDxqwGQ2gv0rywZUwoi1836uldwi4OH4fvbEd4r66OU/eMs16GUcMu0Yyflyn@PnAtdVkOfO@lrIRiVFyjXbYVA/jDk2lFmK0zYF3yiw@jdZJkGhE6MF89F@lmJNvQugA5RageQH0OFIqz4jClYSz2DW95rUgvTm73hou6UT8 "Python 2 – Try It Online") [Answer] # Excel VBA, 60 bytes An anonymous VBE immediate window function that takes input from range `[A1:XFD1]` ``` s=1:For i=-[Count(1:1)]To-1:s=Cells(1,-i)^s:Next:?Right(s,1) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` üT(Çó╖⌐ ``` [Run and debug it](https://staxlang.xyz/#p=81542880a2b7a9&i=[3,4,2]&a=1&m=2) Algorithm like in [my Python answer](https://codegolf.stackexchange.com/a/168276/78123) [Answer] # [CJam](https://sourceforge.net/p/cjam), 14 bytes ``` q~_,({~#]}*~A% ``` Should work for any input, since CJam isn't limited to 64 bit integers [Try it online!](https://tio.run/##S85KzP3/v7AuXkejuk45tlarzlH1//9oYwUTBaNYAA "CJam – Try It Online") [Answer] # [Python 3](https://docs.python.org/3.6/), 55 bytes ``` p=lambda l,i=-1:not l or f'{l[0]**int(p(l[1:],0))}'[i:] ``` Older versions ``` p=lambda l,i=-1:len(l)and f'{l[0]**int(p(l[1:],0))}'[i:]or 1 (60 bytes) ``` [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` f=lambda x,y=1:f(x[:-1],x[-1]**y)if x else y%10 ``` [Try it online!](https://tio.run/##FYzLCoMwFETXzVfcTTGRVBptoQj2R8SFRUNvyYskiwTx222cxSzmcMbl@LWmOw45qFl/lhkSz4PoJU1jfxMTT2Ppus4MJSRYVVghX8X9QO2sjxByINL6gtCAnh0N0TfBKYz8ZE2ICxrWk4vzaCKtxm2fYHjDtldN8fRcNg5V87NoaGIcJFUYIj2visATO3N08ICWCPJ8dSDa7g8 "Python 3 – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 161 bytes Includes +1 for `-r` ``` ([][()]){({}[()]<({}<(({}))>[()]){({}<(({})<({}<>)({<({}[()])><>({})<>}{}<><{}>)>)>[()])}{}{}>)}{}({}((()()()()()){})(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}) ``` [Try it online!](https://tio.run/##PY07DsMwDEP3nIQcsrQdBV3E8JAOBYoUHbIKPrtK20khQL8nUs9je3/X12fbM1FqASsD0XpjqgYl0v9gLgZyIuy8pZsP4K0Ti@b0U6ZNH5V0AYBXUALIRqqYf67X02dYoUjEKpr5WO7LLdfjBw "Brain-Flak – Try It Online") The example `[3, 4, 2]` takes longer than 60 seconds, so the TIO link uses `[4, 3, 2]`. The `-r` can be removed if input can be taken in reverse order for a byte count of 160. ``` # Push stack size -1 ([][()]) # While there are 2 numbers on the stack {({}[()]< # Duplicate the second number on the stack (we're multiplying this number by itself) ({}<(({}))>[()]) # For 0 .. TOS {({}< # Copy TOS (({})< # Multiple Top 2 numbers ({}<>)({<({}[()])><>({})<>}{}<><{}>) # Paste the old TOS >) # End for (and clean up a little) >[()])}{}{} # End While (and clean up) >)}{} # Mod 10 ({}((()()()()()){})(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{}) ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes ``` a->fold((x,y)->y^x,Vecrev(a))%10 ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y4tPydFQ6NCp1JT164yrkInLDW5KLVMI1FTU9XQ4H9BUWZeiUaaRrSxjomOUaym5n8A "Pari/GP – Try It Online") [Answer] # [Z80Golf](https://github.com/lynn/z80golf), 36 bytes ``` 00000000: cd03 80f5 30fa f1f1 57f1 280d 4f41 15af ....0...W.(.OA.. 00000010: 8110 fd47 1520 f818 ef7a d60a 30fc c60a ...G. ...z..0... 00000020: cd00 8076 ...v ``` [Try it online!](https://tio.run/##hY6xDsIwDESlsvEVNzJZdpo2FhsTIyNzlGAWJDaG/nzqKN05yacbzk@3Kb@/H2uND11RKs9QtgUzW4aJCZbkFpQrokWBLNkAcrHfky70uBGdB0GcoSIMqzF5NXhSUbwsZdSVc@cWlJ46407dt8E6GGHsYN@RVvyRv/1aO03TDg "Z80Golf – Try It Online") [Brute-force test harness](https://tio.run/##hZJbi9swEIWf419xMBTbqVeRnZsJTaFPfezLQh@yS1FsaePEsYylLMm2/e3pKE4b77LQAQ3DaOY7x5fmZDe6Hp/P5b7RrYU2Mcxh3bQ6l8Z4XiEVrDQ2F0aaMFp4A6VblChrtKJ@kmEap9OZ6w9OpawKrMpHqt3Q9r2hQaloezik20@g5qX3bzXG1m0PZGVkd7Nupdi5yhF37xJ7SEq7PrcPjrG7sHvwG/2Cr/p43PhvBShVr1TeyMSoOqW@1FXL04aZk7FyH/rHY4G7Fp/B1mXNbKn9yPOcEeuMvH7rz6LCsvdlWL6R@e6HPtjmYMOVvxZm48fw73KXm7asrULg4yOCgG11WYcqeHg4/rxf8PT4O4CTub/IRDTjB/iFkW7s6CXjT7pSI9Pmf@ubvcdoxenJhDGSfhVJnsJgOLzy96IJjW1jIkYRPiDhWC5BM@czv8YCecHHyLiaYsyVgEpUgumcUprxAhM1SZBMhQIYBafznYXs2xfGvI6QECNLCK2KyZxGU6qyJINUc4FixoXj5shd5RhfmcsvHevKSDsfnHzMZ/hP0NrzHw "Test harness – Try It Online") Takes input as raw bytes. Limited to 2\*\*8-1. ## Explanation ``` input: call $8003 ; the input bytes push af ; push on the stack jr nc, input ; until EOF pop af ; the last byte is going to be pushed twice pop af outer: ld d, a ; d = exponentiation loop counter, aka the exponent pop af ; pop the new base off the stack jr z, output ; The flags are being pushed and popped together with the ; accumulator. Since the Z flag starts as unset and no ; instruction in the input loop modifies it, the Z flag is ; going to be unset as long as there is input, so the jump ; won't be taken. After input is depleted, a controlled stack ; underflow will occur. Since SP starts at 0, the flags ; register will be set to the $cd byte from the very beginning ; of the program. The bit corresponding to the Z flag happens ; to be set in that byte, so the main loop will stop executing ld c, a ; C = current base ld b, c ; B = partial product of the exponentiation loop dec d ; if the exponent is 2, the loop should only execute once, so ; decrement it to adjust that pow: xor a ; the multiplication loop sets A to B*C and zeroes B in the mul: ; process, since it's used as the loop counter add c ; it's definitely not the fastest multiplication algorithm, djnz mul ; but it is the smallest ld b, a ; save the multiplication result as the partial product dec d ; jump back to make the next iteration of either jr nz, pow ; the exponentiation loop or the main loop, adjusting the jr outer ; loop counter in the process output: ; after all input is processed, we jump here. We've prepared ld a, d ; to use the result as the next exponent, so copy it back to A mod: ; simple modulo algorithm: sub 10 ; subtract ten jr nc, mod ; repeatedly until you underflow, add 10 ; then undo the last subtraction by adding ten call $8000 ; output the result halt ; and exit ``` ]
[Question] [ Implement a division algorithm in your favourite language which handles integer division. It need only handle positive numbers - but bonus points if it handles negative and mixed-sign division, too. Results are rounded down for fractional results. The program may not contain the `/`, `\`, `div` or similar operators. It must be a routine which does not use native division capabilities of the language. You only need to handle up to 32-bit division. Using repeated subtraction is not allowed. **Input** Take two inputs on stdin separated by new lines or spaces (your choice) ``` 740 2 ``` **Output** In this case, the output would be `370`. The solution which is the shortest wins. [Answer] ## Python - 73 chars Takes comma separated input, eg `740,2` ``` from math import* x,y=input() z=int(exp(log(x)-log(y))) print(z*y+y<=x)+z ``` [Answer] ## JavaScript, 61 ``` A=Array,P=prompt,P((','+A(+P())).split(','+A(+P())).length-1) ``` This makes a string the length of the dividend `,,,,,,` (6) and splits on the divisor `,,,` (3), resulting in an array of length 3: `['', '', '']`, whose length I then subtract one from. Definitely not the fastest, but hopefully interesting nonetheless! [Answer] ## JavaScript - 36 characters ``` p=prompt;alert(p()*Math.pow(p(),-1)) ``` [Answer] ## Python, 37 Step 1. Convert to unary. Step 2. Unary division algorithm. ``` print('1'*input()).count('1'*input()) ``` [Answer] ## Python - 72 chars Takes comma separated input, eg 740,2 ``` x,y=input();z=0 for i in range(32)[::-1]:z+=(1<<i)*(y<<i<=x-z*y) print z ``` [Answer] ## Mathematica: 34 chars Solves symbolically the equation (x a == b) ``` Solve[x#[[1]]==#[[2]],x]&@Input[] ``` [Answer] ## Python - 41 chars Takes comma separated input, eg `740,2` ``` x,y=input();z=x while y*z>x:z-=1 print z ``` [Answer] ## Python, 70 Something crazy I just thought (using comma separated input): ``` from cmath import* x,y=input() print round(tan(polar(y+x*1j)[1]).real) ``` If you accept small float precision errors, the `round` function can be dropped. [Answer] ## APL (6) ``` ⌊*-/⍟⎕ ``` `/` is not division here, but `foldr`. i.e, `F/a b c` is `a F (b F c)`. If I can't use `foldr` because it's called `/`, it can be done in 9 characters: ``` ⌊*(⍟⎕)-⍟⎕ ``` Explanation: * `⎕`: `input()` * `⍟⎕`: `map(log, input())` * `-/⍟⎕`: `foldr1(sub, map(log, input()))` * `*-/⍟⎕`: `exp(foldr1(sub, map(log, input())))` * `⌊*-/⍟⎕`: `floor(exp(foldr1(sub, map(log, input()))))` [Answer] ## Yabasic - 17 characters ``` input a,b:?a*b^-1 ``` [Answer] ## PHP - 82 characters (buggy) ``` $i=fgets(STDIN);$j=fgets(STDIN);$k=1;while(($a=$j*$k)<$i)$k++;echo($a>$i?--$k:$k); ``` This is a very simple solution, however - it doesn't handle fractions or different signs (would jump into an infinite loop). I won't go into detail in this one, it is fairly simple. Input is in stdin, separated by a new line. ## PHP - 141 characters (full) ``` $i*=$r=($i=fgets(STDIN))<0?-1:1;$j*=$s=($j=fgets(STDIN))<0?-1:1;$k=0;$l=1;while(($a=$j*$k)!=$i){if($a>$i)$k-=($l>>=2)*2;$k+=$l;}echo$k*$r*$s; ``` Input and output same as the previous one. Yes, this is almost twice the size of the previous one, but it: * handles fractions correctly * handles signs correctly * won't ever go into an infinite loop, UNLESS the second parameter is 0 - but that is division by zero - invalid input Re-format and explanation: ``` $i *= $r = ($i = fgets(STDIN)) < 0 ? -1 : 1; $j *= $s = ($j = fgets(STDIN)) < 0 ? -1 : 1; // First, in the parentheses, $i is set to // GET variable i, then $r is set to -1 or // 1, depending whether $i is negative or // not - finally, $i multiplied by $r ef- // fectively resulting in $i being the ab- // solute value of itself, but keeping the // sign in $r. // The same is then done to $j, the sign // is kept in $s. $k = 0; // $k will be the result in the end. $l = 1; // $l is used in the loop - it is added to // $k as long as $j*$k (the divisor times // the result so far) is less than $i (the // divided number). while(($a = $j * $k) != $i){ // Main loop - it is executed until $j*$k // equals $i - that is, until a result is // found. Because a/b=c, c*b=a. // At the same time, $a is set to $j*$k, // to conserve space and time. if($a > $i) // If $a is greater than $i, last step $k -= ($l >>= 2) * 2; // (add $l) is undone by subtracting $l // from $k, and then dividing $l by two // (by a bitwise right shift by 1) for // handling fractional results. // It might seem that using ($l>>=2)*2 here // is unnecessary - but by compressing the // two commands ($k-=$l and $l>>=2) into 1 // means that curly braces are not needed: // // if($a>$i)$k-=($l>>=2)*2; // // vs. // // if($a>$i){$k-=$l;$l>>=2;} $k += $l; // Finally, $k is incremented by $l and // the while loop loops again. } echo $k * $r * $s; // To get the correct result, $k has to be // multiplied by $r and $s, keeping signs // that were removed in the beginning. ``` [Answer] ## Ruby 1.9, 28 characters ``` (?a*a+?b).split(?a*b).size-1 ``` Rest of division, 21 characters ``` ?a*a=~/(#{?a*b})\1*$/ ``` Sample: ``` a = 756 b = 20 print (?a*a+?b).split(?a*b).size-1 # => 37 print ?a*a=~/(#{?a*b})\1*$/ # => 16 ``` For Ruby 1.8: ``` a = 756 b = 20 print ('a'*a+'b').split('a'*b).size-1 # => 37 print 'a'*a=~/(#{'a'*b})\1*$/ # => 16 ``` [Answer] ## PHP, 55 characters ``` <?$a=explode(" ",fgets(STDIN));echo$a[0]*pow($a[1],-1); ``` Output (740/2): <http://codepad.viper-7.com/ucTlcq> [Answer] ## Scala 77 ``` def d(a:Int,b:Int,c:Int=0):Int=if(b<=a)d(a-b,b,c+1)else c d(readInt,readInt) ``` [Answer] ## Haskell, 96 characters ``` main=getLine>>=print.d.map read.words d[x,y]=pred.snd.head.filter((>x).fst)$map(\n->(n*y,n))[0..] ``` Input is on a single line. The code just searches for the answer by taking the divisor `d` and multiplying it against all integers `n >= 0`. Let `m` be the dividend. The largest `n` such that `n * d <= m` is picked to be the answer. The code actually picks the least `n` such that `n * d > m` and subtracts 1 from it because I can take the first element from such a list. In the other case, I would have to take the last, but it's hard work to take the last element from an infinite list. Well, the list can be proven to be finite, but Haskell does not know better when performing the filter, so it continues to filter indefinitately. [Answer] ### Common Lisp, 42 charaacters ``` (1-(loop as x to(read)by(read)counting t)) ``` Accepts space or line-separated input [Answer] ## Python - 45 chars Takes comma separated input, eg 740,2 ``` x,y=input() print-1+len((x*'.').split('.'*y)) ``` [Answer] # Bash, ~~72~~ 64 characters ``` read x y;yes ''|head -n$x>f;ls -l --block-size=$y f|cut -d\ -f5 ``` Output an infinite number of newlines, take the first x, put them all into a file called f, then get the size of f in blocks the size of y. Took manatwork's advice to shave off eight characters. [Answer] # Python, 37 ``` x,y=input() print len(('0'*x)[y-1::y]) ``` Constructs a string of length `x` (`'0'*x`) and uses extended slicing to pick every `y`th character, starting from the index `y-1`. Prints the length of the resulting string. Like Gnibbler, this takes comma separated input. Removing it costs `9` chars: ``` i=input x,y=i(),i() print len(('0'*x)[y-1::y]) ``` [Answer] # [Retina](https://github.com/mbuettner/retina) 0.7.3, 33 bytes Takes space-separated input with the divisor first. Dividing by zero is undefined. ``` \d+ $* ^(.+) (\1)+.*$ $#+ .+ .* 0 ``` [**Try it online**](http://retina.tryitonline.net/#code=XGQrCiQqCl4oLispIChcMSkrLiokCiQjKwouKyAuKgow&input=MiA3NDA) [Answer] ## Python, 46 bytes Nobody had posted the boring subtraction solution, so I could not resist doing it. ``` a,b=input() i=0 while a>=b:a-=b;i+=1 print i ``` [Answer] # Python, 94 characters A recursive binary search: ``` a,b=input() def r(m,n):return r(m,m+n>>1)if n*b>a else n if n*b+b>a else r(n,2*n) print r(0,1) ``` [Answer] # Python, 40 characters ``` print(float(input())*float(input())**-1) ``` [Answer] # C, 43 bytes Implements `a/b` in a linear search. Handles only positive arguments. ``` i;f(a,b){i=0;while(1)if(++i*b>a)return--i;} ``` Ungolfed: ``` i; f(a, b){ i = 0; while (1) if (++i * b > a) return --i; } ``` [Answer] **Smalltalk**, Squeak 4.x flavour define this binary message in Integer: ``` % d | i | d <= self or: [^0]. i := self highBit - d highBit. d << i <= self or: [i := i - 1]. ^1 << i + (self - (d << i) % d) ``` Once golfed, this quotient is still long (88 chars): ``` %d|i n|d<=(n:=self)or:[^0].i:=n highBit-d highBit.d<<i<=n or:[i:=i-1].^1<<i+(n-(d<<i)%d) ``` But it's reasonnably fast: ``` [0 to: 1000 do: [:n | 1 to: 1000 do: [:d | self assert: (n//d) = (n%d)]]. ] timeToRun. ``` -> 127 ms on my modest mac mini (8 MOp/s) Compared to regular division: ``` [0 to: 1000 do: [:n | 1 to: 1000 do: [:d | self assert: (n//d) = (n//d)]]. ] timeToRun. ``` -> 31 ms, it's just 4 times slower I don't count the chars to read stdin or write stdout, Squeak was not designed for scripting. ``` FileStream stdout nextPutAll: FileStream stdin nextLine asNumber%FileStream stdin nextLine asNumber; cr ``` Of course, more stupid repeated subtraction ``` %d self>d and:[^0].^self-d%d+1 ``` or plain stupid enumeration ``` %d^(0to:self)findLast:[:q|q*d<=self] ``` could work too, but are not really interesting [Answer] # DC: 26 characters ``` ?so?se0[1+dle*lo>i]dsix1-p ``` I do admit that it is not the fastest solution around. [Answer] # Python 54 Takes comma delimited input. 1. Makes a string of dots of length x 2. Replaces segments of dots of length y with a single comma 3. Counts commas. Words because markdown dies with a list followed by code?: ``` x,y=input() print("."*x).replace("."*y,',').count(',') ``` [Answer] # Q, 46 ``` {-1+(#){x-y}[;y]\[{s[x-y]<>(s:signum)x}[y];x]} ``` . ``` q){-1+(#){x-y}[;y]\[{s[x-y]<>(s:signum)x}[y];x]}[740;2] 370 q){-1+(#){x-y}[;y]\[{s[x-y]<>(s:signum)x}[y];x]}[740;3] 246 ``` ]
[Question] [ As a big fan of the [Lost TV series](https://en.wikipedia.org/wiki/Lost_(TV_series)), I always got intrigued by the sequence of numbers that repetitively appears on the episodes. These numbers are: \$ 4, 8, 15, 16, 23, 42\$ ([A104101](https://oeis.org/A104101)) Using any programming language, write a code that outputs these numbers. ### Scoring: * Shortest answer wins * The output must not contain any other numbers or letters. You may use any other character as separator, or even no separator at all. * You cannot separate digits of the same number. \$ 48\\_15162342 \$ is a valid answer, but \$481\\_5162342\$ is not. * You must respect the order. * If your code does not contain any of the numbers from the sequence, reduce your score by 30%. This rule does allow you to enter the digits separately. E.g.: ``` abcde1fg5h ``` Is a valid candidate because the answer does not contain the number \$15\$, only its digits. However, any \$4\$ or \$8\$ will invalidate the bonus. * If the code does not contain any digit at all, reduce your score by 50%. Other characters like \$¹\$, \$²\$ or \$³\$ are still valid for this bonus. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), ~~29~~ 27/2 = 13.5 bytes ``` %?\>>>>>>>>>> >>\"*"@" ``` [Try it online!](https://tio.run/##y8kvLvn/X9U@xg4OuOzsYpRYOPgFxLWUHJT@/wcA) or [verify that it is deterministic](https://tio.run/##y8kvLvn/X9U@xg4OuOzsYpRYOPgFxLWUHJT@//@vGwgA) Seemed like the right language to use. ### Explanation: Lost is a 2D language where the pointer starts *anywhere*, going in *any* direction. This generally leads to a lot of double checking that the pointer hasn't entered a section early. ``` ...>>>>>>>>>> These arrows filter all pointers that appear on the top line ............. Or going vertically %............ This flips the flag so that the program can end ............. This stops premature termination .?\.......... Clear the stack by skipping if a value popped from the stack is positive ............. When the stack is empty, the \ directs the pointer down ............. The \ directs the pointer right ..\"*".. The string literal pushes all the Lost values to the stack ..\.......... The @ terminates the program if the % flag is switched >>\........@. Otherwise it clears the stack and repeats ............. The quote here is to prevent the pointer getting stuck ............" This happens when the pointer starts between the other quotes ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7/2 = 3.5 bytes ``` “ƲÞIȥ’Ḥ ``` Prints the numbers without separator, i.e., the integer \$4815162342\$. [Try it online!](https://tio.run/##ARkA5v9qZWxsef//4oCcxrLDnknIpeKAmeG4pP// "Jelly – Try It Online") ### How it works `“ƲÞIȥ’` is bijective base-250 integer literal. `Ʋ`, `Þ`, `I`, and `ȥ` have (1-based) indices \$154\$, \$21\$, \$74\$, and \$171\$ in Jelly's code page, so they encode the integer \$250^3\cdot154+250^2\cdot21+250\cdot74+171=2407581171\$. Finally, `Ḥ` (unhalve) doubles the integer, yielding \$2\cdot2407581171=4815162342\$. Doubling is necessary, because encoding the output directly leads to `“¡9)Ƙ[’`, which contains a digit. [Answer] # [Neim](https://github.com/okx-code/Neim), ~~6~~ 5 bytes, ~~3~~ 2.5 points ``` Jσς§A ``` Explanation: ``` J Push 48 σ Push 15 ς Push 16 § Push 23 A Push 42 Implicitly join the contents of the stack together and print ``` [Try it online!](https://tio.run/##y0vNzP3/3@t88/mmQ8sd//8HAA "Neim – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score: ~~10~~ ~~9~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) / 2 = 3.5 ``` •‘o]Ê•· ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcOiRw0z8mMPdwFZh7b//w8A) Or **7 bytes alternative**: ``` •’µ[%•R ``` [Try it online.](https://tio.run/##yy9OTMpM/f//UcOiRw0zD22NVgWygv7/BwA) Both outputting the integer `4815162342`. **Explanation:** ``` •‘o]Ê• # Compressed integer 2407581171 · # Doubled •’µ[%• # Compressed integer 2432615184 R # Reversed ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•‘o]Ê•` is `2407581171` and `•’µ[%•` is `2432615184`. --- Old **9 bytes** answer outputting the list `[4,8,15,16,23,42]`: ``` •ΓƒÇ²•т;в ``` -1 byte (and therefore -0.5 score) thanks to *@Emigna*. Longer than [the other 05AB1E answer](https://codegolf.stackexchange.com/a/175292/52210), but this outputs the list `[4,8,15,16,23,42]` instead of the integer `4815162342`. [Try it online.](https://tio.run/##yy9OTMpM/f//UcOic5OPTTrcfmgTkHmxyfrCpv//AQ) **Explanation:** ``` •ΓƒÇ²• # Compressed integer 1301916192 т; # Integer 50 (100 halved) в # Convert the first integer to Base-50 (arbitrary): [4,8,15,16,23,42] ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer-lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ΓƒÇ²•` is `1301916192`, and `•ΓƒÇ²•50в` is `[4,8,15,16,23,42]`. [Answer] # JavaScript (ES7), 34/2 = 17 bytes ``` _=>eval(atob`NjUwNTgxMDErNDEqKjY`) ``` [Try it online!](https://tio.run/##FcyxDoIwFEDRna94W9sosBi3MhiYjF3UwUkKtqSk9mFbUL@@yniTkzvKRYbemynmDh8qaZ7uvFKLtFRG7FoxXt/iMnxOdeNF3byO461lqSxhQvvVxlqICHNQsGrKwDgQ/0@2JnAIwCs4zForX2iPTxpgA4RsgXQyqP2OsCLiOXrjBsqyrEcX0KrC4kA1ZSz9AA "JavaScript (Node.js) – Try It Online") This decodes and evaluates the expression `"65058101+41**6"`, which does not contain any digit once encoded in base-64. $$65058101+41^6=65058101+4750104241=4815162342$$ --- # JavaScript (ES6), 13 bytes Boring obvious solution. ``` _=>4815162342 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1s7EwtDU0MzI2MTof3J@XnF@TqpeTn66RpqGpuZ/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 25 bytes, 12.5 points ``` print(*map(ord,'ዏٗ*')) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys3sUAjvyhFR/1hd//N6Vrqmpr//wMA "Python 3 – Try It Online") 𩦦(髒, ⿰馬葬), 𧨦(謚, ⿰言⿱⿵八一皿) cost 4 bytes, but U+0657 only cost 2 bytes... --- # [Python 3](https://docs.python.org/3/), 29 bytes, 14.5 points ``` print(ord('𩦦')*ord('湡')) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI78oRUP9w8ply9Q1tcDsZzsXqmtq/v8PAA "Python 3 – Try It Online") 𩦦 (⿰馬葬) is variant character of 髒 which means "dirty". 湡 is the name of a river. And they are nothing related to this question as I known. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 52/2 == 26 bytes ``` (((((((((()()()())){})){}[()])())[]()()())){}[[]]()) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XwMONCFQU7O6FoSjNTRjQdzoWIR4dHQskKf5/z8A "Brain-Flak – Try It Online") [Answer] # Java 8, score: ~~12~~ 11.9 (70% of 17 bytes) ``` v->767*6277917L+3 ``` -0.1 score thanks to *@RickHitchcock*. [Try it online.](https://tio.run/##LY3BCoJAEIbvPsUc10KhApeQeoLyInSJDttqsraO4o4LET77NpIw/2FmPv6vVV4lbfUO2irn4KoMfiMAg1SPL6VrKJYVwPbYgBa33lTg45xvM4fHkSKjoQCEEwSfnGUmN9leyuNOXraHkEcMDdPTMrSyfinp2CRKGg029weo@K8pP47qLu0nSgd@kUWBqRY4WRuv1jn8AA) **Explanation:** ``` v-> // Method with empty unused parameter and long return-type 767 // 767 *6277917L // multiplied by 6277917 (as long) +3 // And then 3 is added ``` --- **Old answer with a score of: 12 (50% of 24 bytes):** ``` v->(long)''*'Ⓥ'*'䧶' ``` Contains an unprintable character `0x1B`. [Try it online.](https://tio.run/##y0osS9TNSsn@n5yTWFys4JuYmVfNpaCQmVeSWpSWmJyq4AfiKijk5OelKyRrhOVnpiiUaVoDxWqBGIiKSxJLMpMV/BTyFGwV/pfp2mmAlGqqS6trqT@a3A0knyzfpv7fmguotqA0KQeoFqqlDGRWLtBCjeCSosy89OhYhURNiG3BlcUlqbl6@aUlegVAqZKcPI08vWSNvNKcHE2o5bX/AQ) **Explanation:** ``` v-> // Method with empty unused parameter and long return-type (long) // Cast the character (and therefore the result) to a long '' // 27 *'Ⓥ' // Multiplied by 9419 *'䧶' // Multiplied by 18934 ``` In Java, characters can be autoboxed to integers holding their unicode value. Unfortunately, the maximum supported unicode for characters is `65,535`, so I can't use just two characters to multiply (since the largest two numbers that divide the expected `4,815,162,342` are `56,802` and `84,771`, where the `84,771` unfortunately exceeds the maximum `65,535`. In addition, since the maximum size of an `int` is 322-1 (`2,147,483,647`) and the result `4,815,162,342` is larger than that, an explicit cast to `long`, which can hold up to 642-1 (`9,223,372,036,854,775,807`), is required. --- [Answer] # R, 18x0.7 = 12.6 score ``` cat(9*2*267509019) ``` Fairly self explanatory, just does some arithmetic avoiding the numbers in question. [Answer] # [7](https://esolangs.org/wiki/7), 10 bytes, 27 characters ``` 115160723426754314105574033 ``` [Try it online!](https://tio.run/##BcGBAQAACAGwlxLy/2Xa0gLGTZbai0UIY0dDtg8 "7 – Try It Online") The packed representation of this program on disk is (`xxd` format): ``` 00000000: 269c 3a71 6f63 308b 7c0d &.:qoc0.|. ``` ## Explanation We've seen this sequence of numbers before, in [Automate Saving the World](https://codegolf.stackexchange.com/questions/44381/automate-saving-the-world), which was about printing the numbers at regular intervals, making it interesting via requiring the use of a very old language. Much newer languages can have their own twists that make this challenge interesting, though. (Yes, this paragraph, and in fact the reason I started writing this answer, is effectively just a way to get all the related challenges to show up together in the sidebar; normally people do that using comments but I don't have enough rep.) The first thing to note is that 7 is made entirely of digits, so going for the bonuses here is unlikely to work (although if you view the program as a sequence of octets, none of them correspond to ASCII representations of any of the original numbers, so you could claim the bonus in that sense). The next thing to note is that 7 has commands to recreate the command sequence likely to have produced a specific piece of data; so could we possibly interpret the Lost numbers `4815162342` as a section of a 7 program itself? The answer is "not quite". The most problematic part is that second number, `8`. 7 programs are written in octal; there's no such number as 8. So the very start of the string will have to be printed differently. The base of the program is therefore based on the 7 "Hello world" program: ``` 5431410557403 543141055 string literal 7 separate data from code 4 rearrange stack: {program's source}, empty element, {literal} 0 escape {the literal}, appending it to {the empty element} 3 output {the escaped literal}, pop {the program's source} ``` with the escaped literal being in a domain-specific language that's interpreted as follows: ``` 5 output format: US-TTY using pairs of digits in the string 43 select character set: digits and common symbols 14 "4" 10 "8" 55 forget the set output format ``` After this comes an extra `3`, which outputs the remaining stack element (and exits due to insufficient remaining stack). That element is specified at the start of the program, and to avoid the unmatched `6` (which works a bit like a closing bracket), we generate it using code, rather than writing it directly as data. (Note that there are two implied `7` characters at the start of the program, which is relevant here): ``` {77}115160723426 7 empty stack element 7 11516 append "1151" 0 append "6" 723246 append "2324" ``` That produces the following literal: ``` 115162324 1 set output format: literally as octal 15162324 "15162324" ``` which gets printed out. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6\*0.7 = 4.2 bytes ``` •1Z&ð“ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcMiwyi1wxseNcz5/x8A "05AB1E – Try It Online") Prints the number uncompressed from base-255 [Answer] # MASM 8088 Assembly source, (93 bytes - 50%) = 46.5 bytes Using no numbers or the sequence in the source: ``` MOV AH,'P'-'G' LEA DX,L INT '!' RET T EQU '-'-'+' L DW 'ph'/T,'jb'/T,'lb'/T,'fd'/T,'dh'/T,'$' ``` Output: ``` A>LOST.COM 4815162342 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes / 2 = 6.5 ``` IETPIHA.⁻⁸⁸℅ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQEMpJMDTw1FPSUfBNzOvtFjDwkJHwb8oJTMvMUcjUxMIrP///69blgMA "Charcoal – Try It Online") Link is to verbose version of code. Works by subtracting the ASCII codes of the string `TPIHA.` from 88 and casting to string. [Answer] # [Aheui (esotope)](https://github.com/aheui/pyaheui), 45 bytes(15 chars) \* 0.5 = 22.5 points ``` 반밤밪박밭빠따받발따밣뱣히망어 ``` [Try it online!](https://tio.run/##ATYAyf9haGV1af//67CY67Ck67Cq67CV67Ct67mg65Sw67Cb67Cc65Sw67Cj67Gj7Z6I66ed7Ja0//8 "Aheui (esotope) – Try It Online") --- Explanation: See this also; Aheui Reference([English](http://aheui.github.io/specification.en)) ``` Aheui program starts with default stack '아'(or none) 반: push 2, move cursor right by 1(→). 밤: push 4, → 밪: push 3, → 박: push 2, → 밭: push 4, → 빠: dup, → 따: pop 2, push mul result(16). 받: push 3, → 발: push 5, → 따: pop 2, push mul result(15). 밣: push 8, → 뱣: push 4, move cursor right by 2(→→). 히: end. 망: pop 1, print, → (if stack is empty, move cursor left by 1.) 어: move cursor left by 1(←). ``` Note that ㅁ(print instruction) moves cursor by reverse direction if stack(or queue) is empty. [Answer] # [Perl 5](https://www.perl.org/), 16 bytes - 30% = 11.2 ``` say 0x5FAB2EA2*3 ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLBoMLUzdHJyNXRSMv4//9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 12 bytes \* 0.7 = 8.4 ``` 0x5FAB2EA2*3 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/36DC1M3RycjV0UjL@P9/AA "PowerShell – Try It Online") ["Port" of Xcali's answer](https://codegolf.stackexchange.com/a/178287/78849) to have a better Powershell answer. [Answer] ## [W](https://github.com/A-ee/w) `j`, 7 / 2 = 3.5 points I updated the ord to support W's own code page. ``` 0“„√*"C ``` ## Explanation ``` 0“„√*" % Define a string C % Convert to codepoints [48,15,16,23,42] Flag:j % Join the output list without a separator ``` ``` [Answer] # [naz](https://github.com/sporeball/naz), 46 bytes, score 32.2 ``` 2a2a1o2m1o7s1o5m1o2s2s1o6m1o2s2s1o1a1o1a1o2s1o ``` Simply outputs each digit in `4815162342` one at a time. [Answer] # [MAWP](https://esolangs.org/wiki/MAWP), 24 bytes ``` 4!:2W!:2W!1A!::7M!:2W4A: ``` [Try it!](https://8dion8.github.io/MAWP/v1.1?code=4!%3A2W!%3A2W!1A!%3A%3A7M!%3A2W4A%3A&input=) [Answer] ## JavaScript, 143 bytes (not sure how to score) ``` (g=`${2*2}`)=>g.repeat(6).replace(/(.)/g,(m,p,i,k='')=> (k=m*[g-3,g-2,g,g,+g+2,g*3-1][i] ,RegExp(`${g-2}|${g}`).test(i)?k-1:i==+g+1?k-(g/2):k)) ``` [Try it online!](https://tio.run/##FY1BCoMwEEUvU3CiScQIXQhpV71AtyIYbBzSqAkaSqH17HbKX8xjeDP/aV5mG1YXk1jCwx7HqAF1f/qoXO090xeUq43WJDizP01msFCCZCVymHnkjnudZSSC13Peoqg5CsWRUmBBkNei6lrX8bvF2zsC/SZh/9KgApnslsCxqxdV47Smm4oYsFSs8YwdQ1i2MFk5BYQRaPED) Start with six `4`'s, multiply, add, subtract by, to, from `4` to derive output. [Answer] # PHP, 35/2=17.5 ``` <?=zzzzzzzzzzzzzzz^NVBVKOVKLVHIVNH; ``` a digital approach: **40\*.7=28** ``` <?=2+2,_,5+3,_,17-2,_,17-1,_,17+6,_,7*6; ``` no digits, no strings: **68/2 = 34** ``` <?=$p++,!$p++,$p+=$p,_,$p+=$p,_,~-$q=$p+$p,_,$q,_,--$p+$q,_,$p*~-$p; ``` --- [Try them online](http://sandbox.onlinephpfunctions.com/code/f8d8982e896e0dd3c9d5d41481c9f3801fb0d5a2). [Answer] ## JavaScript (SpiderMonkey), 67 bytes / 2 = 33.5 60 bytes / 2 = 30 58 bytes / 2 = 29 48 bytes / 2 = 24 *-7 bytes/3.5*, *-2 bytes/1* courtesy of @JoKing, *-10 bytes/5* courtesy of @tsh ``` print(a=-~-~-~-~[],a+=a,b=a+~-a,a+a,a+b,--b+b+b) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/7@gKDOvRCPRVrcOAqNjdRK1bRN1kmwTtet0E4EcEE7S0dVN0gZCzf//AQ) [Answer] # APL(Dyalog Unicode), 18/2 = 9 bytes ``` ×/⎕UCS'𩦦湡' ``` Just boring old character multiplication. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdoeD/4en6j/qmhjoHq39YuWzZs50L1UES/wsA) [Answer] # JavaScript (ES6), 16 \* 0.7 = 11.2 bytes ``` _=>767*6277917+3 ``` Outputs the digits with no delimiters. [Try It Online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1s7czFzLzMjc3NLQXNv4f3J@XnF@TqpeTn66RpqGpuZ/AA) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score: ~~49~~ 41 bytes / 2 = 20.5 ``` [S S S T S S S T T T T T S S S S S S S T T S S S T S T T T T T S S T T S N _Push_4815162342][T N S T _Print_number] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgROEQUABAsAMTpgQEHNxcilw/v8PAA) (with raw spaces, tabs and new-lines only). **Pseudo-code:** ``` Integer i = 4815162342 Print i as number to STDOUT ``` **Explanation:** In whitespace, a number is pushed as follows: * `S`: Enable Stack Manipulation * `S`: Push number * `S`/`T`: Positive/negative respectively * Some `T`/`S` followed by a single `N`: Decimal as binary, where `T` is 1 and `S` is 0 After that it is simply printed with `TNST`: * `TN`: Enable I/O * `S`: Output the top of the stack * `T`: As number [Answer] # F#, 45 bytes = 22.5 points Just a run-of-the-mill `for` loop that prints the digits: ``` for c in"DHOPWj"do printf"%d"(int c-int '@') ``` The above is a complete program that can be compiled into an executable. In a REPL (read-eval-print loop), e.g. FSI (F# Interactive), the following shorter version will work, as the REPL will output a representation of the expression evaluated; it has 35 bytes = 17.5 points: ``` [for c in"DHOPWj"->int c-int '@'];; ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 points ``` 77 91 f8 86 98 06 ``` [Try it here!](https://pyke.catbus.co.uk/?code=77+91+f8+86+98+06&input=&warnings=0&hex=1) The first byte signals to read in base 128 until a byte without the high bit is set. Finally, 32 is subtracted from the result (for historical reasons). This allows for the generation of large numbers in very small amounts of space [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 7 bytes \* 0.5 = 3.5 ``` ÿ≤┼ÇÅ$∞ ``` [Try it online!](https://tio.run/##ARwA4/9tYXRoZ29sZv//w7/iiaTilLzDh8OFJOKInv// "MathGolf – Try It Online") ## Explanation Note that this code doesn't yet work on TIO. I have made some changes to MathGolf recently, including adding the `$` operator. Once it gets pulled to TIO you can run it there, I'll make an update to this answer then. It runs perfectly in the terminal ``` ÿ≤┼ÇÅ Push "≤┼ÇÅ" $ pop(a), push ord(a) (pushes 2407581171) ∞ pop a, push 2*a ``` I utilize the fact that MathGolf has 1-byte literals for creating strings of up to length 4. If I wanted to convert the entire number from a base-256 string, I would have needed to use two `"`, and the string would have been 5 characters. This way, I save 2 bytes, but I lose one byte by having the doubling operator in the end. [Answer] # [Python 3](https://docs.python.org/3/) 34 Points ``` b=len(" ");c=b*b;d=c*b;e=d*b;g=e+d-b//b;print(c,d,e-b//b,e,g,g*b-c) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~44~~ ~~38~~ ~~19~~ 18.5 bytes -6 bytes thanks to @Jo King -50% bytes thanks to @ouflak for pointing out the 50% bonus -1 byte thanks to @Dennis ``` for i in'밗ɯ*':print(ord(i),end='') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNP/fWG6SfXa6lbFRRl5pVo5BelaGRq6qTmpdiqq2sq/P8PAA "Python 3 – Try It Online") ]
[Question] [ ## Description Given a number, print the amount of `1`s it has in binary representation. ## Input A number `>= 0` in base 10 that won't exceed the highest number your language is able to handle. ## Output The amount of `1`s in binary representation. ## Winning condition The shortest code wins. ## Disallowed * Bitwise operators. Other operators, like addition and multiplication, are allowed. * Built-in base conversion functions. ## Examples ``` Input: Ouput: 56432 8 Input: Output: 45781254 11 Input: Output: 0 0 ``` [Answer] ## APL, ~~9~~ 12 characters ``` +/2|⌊⎕÷2*⍳32 ``` This assumes that the interpreter uses 32-bit integers, and that `⎕IO` is set to 0 (meaning that monadic `⍳` begins with 0, rather than 1). I used the 32-bit version of [Dyalog APL](http://www.dyalog.com). Explanation, from right to left: * `⍳32` generates a vector of the first `32` integers (as explained before, because `⎕IO` is 0, this vector begins with 0). * `*` is the power function. In this case, it generates `2` to the power of each element of the vector supplied as its right argument. * `÷` is the divided-by function. It gives us `⎕` (evaluated user input) divided by each element of the vector to its right (each power of two). * `⌊` floors each element of the argument to its right. * `2|` gives us the remainder of each element of to its right divided by `2`. * `/` reduces (folds) its right argument using the function to its left, `+`. Not quite 9 characters anymore. :( *Old, rule-breaking version:* > > > ``` > +/⎕⊤⍨32/2 > > ``` > > Explanation, from right to left: > > > * `32/2`: Replicate `2`, `32` times. > * `⍨` commutes the dyadic function to its left, which in this case is `⊤` (i.e., `X⊤⍨Y` is equivalent to `Y⊤X`). > * `⊤` is the encode function. It encodes the integer to its right in the base given to its left. Note that, because of the commute operator, the right and left arguments are switched. The base is repeated for the number of digits required, hence `32/2`. > * `⎕` is a niladic function that accepts user input and evaluates it. > * `+/` reduces (folds) its right argument using `+`. (We add up the 0's and 1's.) > > > [Answer] # [Brainbool](https://esolangs.org/wiki/Brainbool), 2 ``` ,. ``` The most reasonable interpretation, in my opinion (and what most of the answers use) of "highest number your language is able to handle" is "largest number your language *natively* supports". Brainbool is a brainfuck derivative that uses bits rather than bytes, and takes input and output in binary (`0` and `1` characters) rather than character codes. The largest natively supported number is therefore `1`, and the smallest is `0`, which have Hamming weights `1` and `0` respectively. Brainbool was created in 2010, according to Esolang. [Answer] # Brainfuck, 53 characters This was missing an obligatory Brainfuck solution, so I made this one: ``` [[->+<[->->>>+<<]>[->>>>+<<]<<<]>>>>[-<<<<+>>>>]<<<<] ``` Takes number from cell 1 and puts the result into cell 6. Unenrolled and commented version: ``` [ while n != 0 [ div 2 loop - >+< marker for if/else [->->>>+<<] if n != 0 inc n/2 > [->>>>+<<] else inc m <<< ] >>>> move n/2 back to n [-<<<<+>>>>] <<<< ] ``` [Answer] ## J, 13 characters (+ the number of digits in the number) ``` +/2|<.n%2^i.32 ``` Usage: replace the `n` in the program with the number to be tested. Examples: ``` +/2|<.56432%2^i.32 8 +/2|<.45781254%2^i.32 11 +/2|<.0%2^i.32 0 ``` There's probably a way of rearranging this so the number can be placed at the beginning or end, but this is my first J entry and my head's hurting slightly now. **Explanation**(mainly so that I understand it in the future) `i.32` - creates an array of the numbers 1 to 32 `2^` - turns the list into the powers of two 1 to 4294967296 `n%` - divides the input number by each element in the list `<.` - rounds all the divison results down to the next integer `2|` - same as `%2` in most languages - returns 0 if even and 1 if odd `+/` - totals the items in the list (which are now just 1s or 0s) [Answer] # Python 2.6, 41 characters ``` t,n=0,input() while n:t+=n%2;n/=2 print t ``` **note:** My other answer uses lambda and recursion and this one uses a while loop. I think they are different enough to warrant two answers. [Answer] ## Ruby, 38 characters ``` f=->u{u<1?0:u%2+f[u/2]} p f[gets.to_i] ``` Another solution using ruby and the same recursive approach as Steven. [Answer] ## GolfScript, 17 16 characters ``` ~{.2%\2/.}do]0-, ``` *Edit:* new version saves 1 character by using list operation instead of fold (original version was `~{.2%\2/.}do]{+}*`, direct count version: `~0\{.2%@+\2/.}do;`). [Answer] ## C, 45 ``` f(n,c){for(c=0;n;n/=2)c+=n%2;printf("%d",c);} ``` Nothing really special here for golfing in C: implicit return type, implicit integer type for parameters. [Answer] ## Python 2.6, 45 characters ``` b=lambda n:n and n%2+b(n/2) print b(input()) ``` [Answer] ## Perl, 45 43 36 Characters ``` $n=<>;while($n){$_+=$n%2;$n/=2}print ``` Thanks to Howard for 45->43, and to User606723 for 43->36. [Answer] ## Perl, 30 chars ``` $==<>;1while$_+=$=%2,$=/=2;say ``` Based on [PhiNotPi's solution](https://codegolf.stackexchange.com/a/4437/3191), with some extra golfing. Run with `perl -M5.010` to enable the Perl 5.10 `say` feature. [Answer] ## Common Lisp, 12 chars (assuming a 1 char variable name - i.e.: 11 + number length) It's not a base conversion function, so it should work: ``` (logcount x) ``` Examples: ``` [1]> (logcount 0) 0 [2]> (logcount 1) 1 [3]> (logcount 1024) 1 [4]> (logcount 1023) 10 [5]> (logcount 1234567890123456789012345678901234567890) 68 ``` (Using GNU CLISP.) [Answer] # C, ~~61 60 57~~ 53 characters ``` void f(x){int i=0;for(;x;x/=2)i+=x%2;printf("%u",i);} ``` The function body only is 38 characters. **Edit**: removed bitwise operator **Edit**: put `printf` out of the loop as suggested in the comments **Edit**: switch to K&R declaration; also, this is no longer C99-specific [Answer] # dc – 26 chars This is rather long, mostly due to the lack of loop constructs in `dc`. ``` 0?[d2%rsi+li2/d0<x]dsxx+p ``` Keeps adding up the modulo 2 of the number and dividing the number by to until it reaches zero. Can handle arbitrarily long integers. Example: ``` $ dc -e '0?[d2%rsi+li2/d0<x]dsxx+p' <<< 127 7 $ dc countones.dc <<< 1273434547453452352342346734573465732856238472384263456458235374653784538469120235 138 ``` [Answer] ## C, 66 characters ``` main(int n,char **a){printf("%u",__builtin_popcount(atoi(a[1])))}; ``` Note: requires gcc or gcc-compatible compiler (e.g. ICC, clang). For some CPUs `__builtin_popcount` compiles to a single instruction (e.g. `POPCNT` on x86). [Answer] ## D (70 chars) ``` int f(string i){int k=to!int(i),r;while(k){if(k%2)r++;k/=2;}return r;} ``` [Answer] ## JavaScript, ~~78 72~~ 71 characters I'll post my initial solution which I came up with before posting the question as well. There is already a much better JavaScript answer though :) ``` for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a) ``` <http://jsfiddle.net/Mk8zd/1/> The idea comes from certain "mind reading cards" which enable you to obtain the number someone else has in mind, by showing them cards and let them say on which cards their number is apparent. It works because each number is a unique combination of `1`s / `0`s in binary. My solution checks on which "cards" the number is apparent so as to determine how many `1`s it has. It's just not very efficient, though... I found [this document](http://assets.cambridge.org/97805217/56075/excerpt/9780521756075_excerpt.pdf) which outlines the mind reading technique. [Answer] ## Haskell (60 chars) ``` f n=sum[1|x<-[0..n],odd$n`div`2^x] main=interact$show.f.read ``` [Answer] ## PHP, 57 ``` $i=$s=0;for(;$i<log($n,2);){$s+=$n/pow(2,$i++)%2;}echo$s; ``` This assumes that `$n` holds the value to be tested. ## PHP, 55 (alternative solution) ``` function b($i){return$i|0?($i%2)+b($i/2):0;}echo b($n); ``` Again, this assumes that `$n` holds the value to be tested. This is an alternative because it uses the or-operator to `floor` the input. Both solutions work and do not cause notices. [Answer] # Ocaml, 45 characters Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else. ``` let rec o=function 0->0|x->(x mod 2)+(o(x/2)) ``` [Answer] # Java 7, 36 bytes ``` int b(Long a){return a.bitCount(a);} ``` Because of course this, of all things, is something that Java has a builtin for... [Answer] # Mathematica 26 ``` Count[n~IntegerDigits~2,1] ``` [Answer] # 386 opcode, 10 Bytes ``` 2BC0 SUB EAX,EAX 01C9 ADD ECX,ECX 1400 ADC AL,0 41 INC ECX E2F9 LOOP $-5 C3 RET ``` Thank Peter Cordes for 1B save and 1B rule save [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 49 bits1, 6.125 [bytes](https://github.com/Vyxal/Vyncode/blob/main/README.md) ``` ʀEṗ'∑?=;f ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJsQT0iLCIiLCLKgEXhuZcn4oiRPz07ZiIsIiIsIjBcbjFcbjJcbjNcbjRcbjVcbjZcbjdcbjhcbjkiXQ==) Brute force solution, so the online interpreter times out. May potentially be made shorter by porting others, but I thought this solution was fun ``` ʀ # range 0..input+1 E # raise 2^n for each value in that range ṗ # powerset ' ; # filtered by ∑ # the sum ?= # is equal to the input? f # flatten # after which the l flag takes the length of the top of the stack and implicitly outputs it ``` [Answer] ## Scala, 86 characters ``` object O extends App{def f(i:Int):Int=if(i>0)i%2+f(i/2)else 0 print(f(args(0).toInt))} ``` Usage: `scala O 56432` [Answer] # R, 53 characters `o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan())` Examples: ``` > o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan()) 1: 56432 2: Read 1 item [1] 8 > o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan()) 1: 45781254 2: Read 1 item [1] 11 > o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0};o(scan()) 1: 0 2: Read 1 item [1] 0 ``` If inputting the number is not part of the character count, then it is 43 characters: `o=function(n){h=n%/%2;n%%2+if(h)o(h)else 0}` with test cases ``` > o(56432) [1] 8 > o(45781254) [1] 11 > o(0) [1] 0 ``` [Answer] # OCaml, 52 characters ``` let rec o x=if x=0 then 0 else (x mod 2) + (o (x/2)) ``` [Answer] # Scheme I polished the rules a bit to add to the challenge. The function doesn't care about the base of the number because it uses its own binary scale. I was inspired by the way analog to numeric conversion works. I just use plain recursion for this: ``` (define (find-ones n) (define (nbits n) (let nbits ([i 2]) (if (< i n) (nbits (* i 2)) i))) (let f ([half (/ (nbits n) 2)] [i 0] [n n])     (cond [(< half 2) i] [(< n i) (f (/ half 2) i (/ n 2))] [else (f (/ half 2) (+ i 1) (/ n 2))]))) ``` [Answer] Isn't reading a number into binary or printing the number from binary a "builtin base conversion function", thus invalidating every answer above that `print`s an integer? If you permit reading and printing an integer, like almost all the above answers do, then I'll make claims using a [builtin `popcount` function](https://codegolf.stackexchange.com/a/4722/3071) : ### Haskell, 50 There was a `popCount` routine added to the `Data.Bits` module for GHC v7.2.1/v7.4.1 this summer (see tickets concerning the [primop](http://hackage.haskell.org/trac/ghc/ticket/5413) and [binding](http://hackage.haskell.org/trac/ghc/ticket/5431)). ``` import Data.Bits main=interact$show.popCount.read ``` I cannot beat the above Python and Perl scores using their `GMPY` or `GMP::Mpz` modules for GMP sadly, although GMP does offer a [popcount function](http://www.dalkescientific.com/writings/diary/archive/2008/07/03/hakmem_and_other_popcounts.html) too. [Answer] # JavaScript, ~~57~~ ~~55~~ ~~51~~ 50 bytes ``` a=prompt(b=0);while(a){b+=a%2;a=(a-a%2)/2}alert(b) ``` Modulo is not bitwise operator ☺ ]
[Question] [ Your task is to write a program to print the sum of the ASCII codes of the characters of the program itself. You are not allowed to open any file (Any input such as command line arguments, standard input or files is prohibited). The program that prints the lowest number (i.e. has the lowest sum of ASCII codes) wins. Here is an example (not the shortest) of such a program written in C: ``` #include <stdio.h> int main(){ printf("4950");/*i*/ return 0; } ``` (no new line after `}`) [Answer] ## PHP, m4, and other cat-like languages: 150 ``` 150 ``` Found this solution using a simple Haskell program to brute-force it: ``` f :: String -> Bool f s = (read s :: Int) == (sum . map fromEnum) s main = mapM_ print [filter f $ sequence $ replicate n ['0'..'9'] | n <- [1..10]] ``` [Answer] ## wc, prints 0 Someone said "cat-like languages", so... An empty file: Execute with `wc -c file.wc`. At 0 bytes, I think this is the winner in the 'not really a programming language' category. Also ## cat, prints 80 (base 13) ``` 80 ``` No terminating newline, the number 8013 is equivalent to 104 in decimal. You can go shorter with 6017 (102 dec), but I figured "base 13" would be worth more geek points. EDIT: New `wc` example, this one can be run as a program. ``` #!/usr/bin/wc ÿÿzw17 ``` (As encoded in Latin-1 - the ÿ is a byte with value 255) Sum of bytes is 2223, output is: ``` 2 2 23 ./w ``` [Answer] ## Brainf\*ck, 255 ``` -.¤ ``` This will not print the number 255, but rather the 255th ASCII character. This might be considered cheating because the BF compiler skips over the `¤`. [Answer] ## Javascript, prints ~~9432~~ 6902 ``` (function a(){b="("+a+")()";c=0;for(i=0;i<b.length;i++){c+=b.charCodeAt(i-0)}alert(c)})() ``` This is the first quine solution so far, unless I am not understanding the [Haskell one](https://codegolf.stackexchange.com/questions/2926/write-a-program-to-print-the-sum-of-the-ascii-codes-of-the-program/2930#2930) correctly. [Answer] ## PowerShell ``` ((310)) ``` prints 310. [Answer] ## Perl, 500 ``` say 500 ``` There are two tabs between `say` and `500`. :) (Run as a one-liner with `perl -E`, as far as I can tell this is within the rules) [Answer] ## Ruby, prints 380 ``` p (380) ``` No trailing newline after the closing parenthesis. [Answer] ## PowerShell ``` (230) ``` prints 230, obviously. [Answer] ## PowerShell ``` -(-320) ``` prints 320. [Answer] ## J, 150 ``` ?!6 ``` With the caveat that it will be correct only 1/720th of the time. [Answer] ## Python, prints 781 ``` print 781 ``` Two spaces. [Answer] ## INTERCAL, 1572 I can't believe no one's done INTERCAL yet! ``` DOREADOUT#1572 DOGIVEUP ``` (Includes terminating newline.) This program prints out MDLXXII. [Answer] # Element, 220 This is a language of my own creation, and it is documented on my answer to another question [here](https://codegolf.stackexchange.com/questions/1171/sum-of-positive-integers-spoj-sizecon#5268). ``` 220`! ``` Here is a walkthrough of how it works: The `220` pushes that number onto the stack. Then the ``` outputs the top element of the stack. The `!` then performs a logical NOT on the control stack (a separate stack), setting it to 1. [Answer] # PHP, prints 4440 ``` <?php for($x=0;$x<15000;$x++)if($x==4440){printf($x);exit;} ``` [Answer] ## PowerShell, prints 3902 ``` &{[char[]]$myinvocation.Line|%{$s+=+$_};$s} ``` Looks into the line currently run and sums the code point values. [Answer] ## C, 1700 Strange - nobody posted a C solution yet (excluding the example in the question). ``` main(R){puts("1700");} ``` No newline at the end. [Answer] ## J, 198 ``` 33*6 ``` and ``` 6*33 ``` Found it by brute force. In J there are no 1 or 2 char solutions, and the only 3-char solution is `150`. Barring any bugs in my search, there are no other 4-char solutions, either. --- From the #jsoftware IRC channel, we also had `<.%:10!20` at 429 and a self-counting quine `+/a.i.2#(,{:)'+/a.i.2#(,{:)'''` at 1706. [Answer] # [naz](https://github.com/sporeball/naz), score ~~777~~ 333 ``` 3a 3o ``` I think this is allowed. The newline is normalized to `\r\n` by the naz interpreter at runtime, a sequence which contributes **23** to the overall score. **Explanation** ``` 3a # Add 3 to the register 3o # Output 3 times ``` The previous solution: ``` 7a2o1m1o1a ``` [Answer] ## Perl, prints 690 ``` die 690 . $/ ``` Or, if we can post one-liners (`perl -E`) ``` say(570) ``` Prints 570. (No trailing newlines) [Answer] ## JavaScript, ~~1750 900 860~~ 790 `alert(790)` (Carriage return (CR, `\r` or `\x0D`) after or before the program) These programs are found by brute-forcing. Bigger values: ``` alert(860)%0 alert(900)&&6 document.write(1750) ``` [Answer] # Java -128 I know reading stdin isn't allowed but I wanted to provide an example of how I calculated my score. My code sums the ASCII count of itself passed on stdin and prints out -128 ``` class P{public static void main(String[]z)throws Exception{byte v=0;int b=0;while((b=System.in.read())!=-1){v+=(byte)b;}System.out.println(v);}} ``` No trailing new line [Answer] ## Ruby, prints 300 ``` p 300 ``` There is a space and a tab between the `p` and the `300`. No trailing newline. [Answer] ## Batch files, 500 ``` ECHO 500 ``` As well, notice the two spaces between "ECHO" (uppercase on purpose) and "500". [Answer] # K (~~923 796 795 746~~ 513) I'm not sure if this falls afoul of the rules or not. It doesn't use stdin, it opens itself as a vector of bytes and sums. ``` +/1:.z.f ``` Usage: ``` q scriptname.k ``` edit 2012.05.08 - no need to hsym the file handle 2012.05.09 - saved 1 point by converting to byte instead of int 2012.05.17 - Can save a load of points by reading file as bytestream rather than text: [Answer] # Lenguage, 4 bytes, prints 0 Source code consists of 4 null bytes. Therefore, it should output (0+0+0+0)=0. [Answer] ### bc 1160 invoked with echo and blanks, the whole String, including 7 blanks, `echo 1160 | bc` has a bytesum of 1160. ``` echo 1160 | bc ``` 150 works for bc too: ``` echo "150" > 150 bc -q 150 150 ``` [Answer] ## D, 9752 this one actually calculates it similar to my [quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/2987#2987) ``` enum c=q{import std.stdio;void main(){int s;foreach(d;"enum c=q{"~c~"};mixin(c);")s+=d;write(s);}};mixin(c); ``` [Answer] ## Whitespace, 369 This 20-character program prints the number 369, which is the sum of the ascii values of its characters (which are Tab,Space,Linefeed characters, here symbolized by T,S,L, respectively): ``` SSSTSTTTSSSTLTLSTLLL ``` (369 = 7\*9 + 8\*32 + 5\*10, there being 7 Tabs, 8 Spaces, and 5 Linefeeds.) [Answer] # Haskell, 7518 A small modification of my [quine](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good): ``` main=print.sum.map fromEnum$q++show q;q="main=print.sum.map fromEnum$q++show q;q=" ``` [Answer] ## Brainf\*ck, 253 (or 252) Slight improvement on Peter Olson's solution: ``` ---.H ``` Provided non-printables are allowed, it can be improved further by adding a `-` and replacing `H` by ASCII code 26. ]
[Question] [ Create program or function that takes file name as an argument or reads it from standard input, and completes the following task: 1. Read image from a png file (name given as argument). 2. Reverse colors in that image, so that for example dark green (0, 75, 30) would become (255, 180, 225) (because 255-0=255, 255-75=180 and 255-30=225). You should not change alpha channel value. 3. Output that image to a file called `a.png` (in png format), or show it in GUI window. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard loopholes apply. [Answer] # ImageMagick `display -fx`, 3 7 18 24 bytes ``` 1-u ``` The ImageMagick tool `display` with the `fx` parameter can apply the above program to a png given as the parameter and display the results on screen. Check out [my post on meta](http://meta.codegolf.stackexchange.com/questions/8828/is-imagemagick-a-programming-language) about ImageMagick as a programming language. I wrote a prime tester over there as a proof of concept. Re byte counting, `display -fx code filename` is equivalent to `perl -e code filename`, where we traditionally count just `code` for length. [Answer] ## Pyth, ~~16~~ ~~15~~ 13 bytes ``` .w-LLL255'z\a ``` Outputs to `a.png`. ``` z read input ' read as RGB triples from file LLL map over rows, then triples, then individual values... - 255 ...subtract from 255 .w \a write as image to a.png ``` Thanks to [Jakube](https://codegolf.stackexchange.com/users/29577/jakube) for 2 bytes! [Answer] # [MATL](https://esolangs.org/wiki/MATL), 10 bytes ``` 255iYi-IYG ``` There are [five different subformats](https://www.w3.org/TR/PNG/#6Colour-values) of PNG, depending on how color is encoded. None of them seems to be more "optional" than the others. I chose the most flexible one, `Truecolor`, in which each pixel can have an arbitrary color. The above code also supports `Truecolor with alpha`, ignoring the alpha channel. To know the color subformat of a PNG file: look for the byte sequence `[73 72 68 82]` near the beginning of the file; and the [*tenth*](https://www.w3.org/TR/PNG/#11IHDR) byte from there will have one of the five values in the [table linked above](https://www.w3.org/TR/PNG/#6Colour-values). ### How the code works Pretty straightforward: ``` 255 % push 255 to the stack i % input filename with extension '.png' Yi % read contents of that file as (truecolor) image - % subtract IYG % show image ``` ### Example I couldn't resist seeing myself inverted, so I downloaded [this image](https://i.stack.imgur.com/rFMSx.png?s=328&g=1) (which is in subformat `Truecolor with alpha`), ran the code (second line is user input) ``` >> matl 255iYi-IYG > 'C:\Users\Luis\Desktop\me.png' ``` and got [![enter image description here](https://i.stack.imgur.com/Kku70.png)](https://i.stack.imgur.com/Kku70.png) [Answer] # Java, 295 ``` import javax.imageio.*;class V{public static void main(String[]a)throws Exception{java.awt.image.BufferedImage m=ImageIO.read(new java.io.File(a[0]));for(int x=m.getWidth(),y;x-->0;)for(y=m.getHeight();y-->0;)m.setRGB(x,y,m.getRGB(x,y)^-1>>>8);ImageIO.write(m,"png",new java.io.File("a.png"));}} ``` [Answer] # R, 124 bytes ``` p=png::readPNG(readline());p[,,-4]=1-p[,,-4];png("a.png",h=nrow(p),w=ncol(p));par(mar=rep(0,4));plot(as.raster(p));dev.off() ``` Reads in file name through stdin (`readline()`). ``` p=png::readPNG(readline()) #Reads in png as an RGBA array on range [0,1] p[,,-4]=1-p[,,-4] #Takes the opposite value except on alpha layer png("a.png",h=nrow(p),w=ncol(p)) #Prepares output png of same size as input par(mar=rep(0,4)) #Makes the png take the full space of the figure region plot(as.raster(p)) #Transforms p as a raster so that it can be plotted as is. dev.off() #Closes the plotting device. ``` Example Input/Output using the first png I found on this computer :) [![Input](https://i.stack.imgur.com/XmlbE.png)](https://i.stack.imgur.com/XmlbE.png) [![Output](https://i.stack.imgur.com/yr4oX.png)](https://i.stack.imgur.com/yr4oX.png) [Answer] # CSS, 19 Bytes ``` *{filter:invert(1)} ``` <http://output.jsbin.com/suqayudoyu> [Answer] # Tcl, 176 bytes ``` foreach r [[image c photo -file {*}$argv] d] {set x {} foreach c $r {lappend x [format #%06X [expr "0xFFFFFF-0x[string ra $c 1 end]"]]} lappend y $x} image1 p $y image1 w a.png ``` Loads the PNG via the `photo` image type, gets the image data, converting each row and color by subtracting from #FFFFFF, then writes the file back to disk (as "a.png"). For best results, use TrueColor PNGs, since Tk will try to use the same color resolution as the source image data. To see the image without sampling problems, add ``` pack [label .i -image image1] ``` to the end. (Obviously, this is longer than the disk-save option.) [Answer] ## Mathematica, 140 bytes ``` Export["a.png",SetAlphaChannel[ColorCombine[Most@#],Last@#]&@MapAt[Image[1-ImageData@#]&,ColorSeparate[Import[#],{"R","G","B","A"}],{;;3}]]& ``` [Answer] # cmd + IrfanView, 19 characters ``` i_view32 %1 /invert ``` Just the expensive alternative of [Sparr](https://codegolf.stackexchange.com/users/4787/sparr)'s [answer](https://codegolf.stackexchange.com/a/76418). [Answer] # Julia, ~~94~~ 79 bytes ``` using FileIO save(ARGS[1],map(x->typeof(x)(1-x.r,1-x.g,1-x.b,1),load(ARGS[1]))) ``` This is a full program that takes a file name as a command line argument and overwrites the given file with the inverted image. It requires that the `FileIO` and `Image` package be installed. The latter doesn't need to be imported though. Call the program from the command line like `julia filename.jl /path/to/image.png`. Ungolfed: ``` using FileIO # required for reading and writing image files # Load the given image into a matrix where each element is an RGBA value a = load(ARGS[1]) # Construct a new image matrix as the inverse of `a` by, for each element # `x` in `a`, constructing a new RGBA value as 1 - the RGB portions of # `x`, but with an alpha of 1 to avoid transparency. b = map(x -> typeof(x)(1 - x.r, 1 - x.g, 1 - x.b, 1), a) # Save the image using the same filename save(ARGS[1], b) ``` Example: [![regular](https://i.stack.imgur.com/iGwcZ.png)](https://i.stack.imgur.com/iGwcZ.png) [![inverted](https://i.stack.imgur.com/YWRhq.png)](https://i.stack.imgur.com/YWRhq.png) [Answer] ## Python + PIL, 85 bytes ``` from PIL import Image lambda a:Image.eval(Image.open(a),lambda x:255-x).save('a.png') ``` This defines an anonymous function that takes a filename as a string and saves the resultant image to `a.png`. Test run: [![llama](https://i.stack.imgur.com/6bK0v.jpg)](https://i.stack.imgur.com/6bK0v.jpg) [![llama out](https://i.stack.imgur.com/Ap2Ux.jpg)](https://i.stack.imgur.com/Ap2Ux.jpg) [Answer] # C + stb\_image + stb\_image\_write, ~~175~~ 162 bytes (or +72=~~247~~ 234) My first submission on this site ever. ``` #include"stb_image.h" #include"stb_image_write.h" x,y,c,i;f(char*d){d=stbi_load(d,&x,&y,&c,i=0);for(;i<x*y*c;i++)d[i]=255-d[i];stbi_write_png("a.png",x,y,c,d,0);} ``` --- Could probably shave off a few bytes. Needs `stb_*` implementation to either be in a separate library, or at the start of this file with: ``` #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION ``` I didn't include it in the count because it's essentially part of the library (esp. if it's compiled separately). +72 bytes to add that if required, however. --- ### Update 1: Realized only a function (as opposed to an entire program) is acceptable, shaving off 15 bytes. The ***old*** implementation (which is an entire program), for reference: ``` x,y,i;main(int c,char**d){*d=stbi_load(d[1],&x,&y,&c,0);for(;i<x*y*c;i++)i[*d]=255-i[*d];stbi_write_png("a.png",x,y,c,*d,0);} ``` [Answer] # Java, ~~300~~ 298 bytes ``` import javax.swing.*;void c(String f)throws Exception{java.awt.image.BufferedImage r=javax.imageio.ImageIO.read(new java.io.File(f));for(int i=0;i++<r.getWidth();)for(int j=0;j++<r.getHeight();)r.setRGB(i,j,(0xFFFFFF-r.getRGB(i,j))|0xFF000000);JOptionPane.showMessageDialog(null,new ImageIcon(r));} ``` [Answer] # MATLAB / Octave, 31 bytes **Code:** ``` imshow(imcomplement(imread(x))) ``` **Example:** ``` imshow(imcomplement(imread('balloons.png'))) ``` [![enter image description here](https://i.stack.imgur.com/hozVr.png)](https://i.stack.imgur.com/hozVr.png)              [![enter image description here](https://i.stack.imgur.com/41g4r.png)](https://i.stack.imgur.com/41g4r.png) **Explanation:** Read the image, `x`, from a graphics file, complement the image, and then display the image. [Answer] ## FFmpeg, 10 bytes Edit: Taking a cue from @Sparr's answer ``` -vf negate ``` (the above when passed to ffplay alongwith the image name, will display the negated image) --- ``` ffplay %1 -vf negate ``` The above is saved as a batch file. [Answer] # Racket 282 bytes ``` (λ(fname)(let*((i(make-object bitmap% fname))(w(send i get-width))(h(send i get-height))(pixels(make-bytes(* w h 4)))(i2(make-object bitmap% w h))) (send i get-argb-pixels 0 0 w h pixels)(send i2 set-argb-pixels 0 0 w h(list->bytes(map(lambda(x)(- 255 x))(bytes->list pixels))))i2)) ``` More readable form: ``` (define(f fname) (let*( (i (make-object bitmap% fname)) (w (send i get-width)) (h (send i get-height)) (pixels (make-bytes(* w h 4))) (i2 (make-object bitmap% w h))) (send i get-argb-pixels 0 0 w h pixels) (send i2 set-argb-pixels 0 0 w h (list->bytes (map (lambda(x) (- 255 x)) (bytes->list pixels)))) i2)) ``` Usage: ``` (f "myimg.png") ``` [Answer] ## Golang, 311 bytes ``` package main import("image" ."image/png" ."image/color" ."os") func main(){f,_:=Open(Args[1]) i,_:=Decode(f) q:=i.Bounds() n:=image.NewRGBA(q) s:=q.Size() for x:=0;x<s.X;x++{for y:=0;y<s.Y;y++{r,g,b,a:=i.At(x,y).RGBA() n.Set(x,y,RGBA{byte(255-r),byte(255-g),byte(255-b),byte(a)})}} o,_:=Create("o") Encode(o,n)} ``` ### ungolfed ``` package main import( "image" "image/png" "image/color" "os" ) func main(){ // open a png image. f, _ := os.Open(Args[1]) // decode the png image to a positive image object(PIO). p, _ := png.Decode(f) // get a rectangle from the PIO. q := p.Bounds() // create a negative image object(NIO). n := image.NewRGBA(q) // get the size of the PIO. s := q.Size() // invert the PIO. for x := 0; x < s.X; x++ { for y := 0; y < s.Y; y++ { // fetch the value of a pixel from the POI. r, g, b, a := p.At(x, y).RGBA() // set the value of an inverted pixel to the NIO. // Note: byte is an alias for uint8 in Golang. n.Set(x, y, color.RGBA{uint8(255-r), uint8(255-g), uint8(255-b), uint8(a)}) } } // create an output file. o, _ := os.Create("out.png") // output a png image from the NIO. png.Encode(o, n) } ``` [Answer] # [Python 2](https://docs.python.org/2/) + [OpenCV](https://opencv.org/), 55 bytes ``` import cv2 cv2.imwrite('a.png',255-cv2.imread(input())) ``` The OpenCV library uses NumPy arrays to read, process, and write images. Below is an example of this script inverting an image found on [mozilla.org](https://mozilla.org/). [![Edge Artwork Inverted](https://i.stack.imgur.com/8Btph.png)](https://i.stack.imgur.com/8Btph.png) All channels, including the alpha channel, will be inverted. This is problematic for images that have transparency. But as @Mego pointed out, support for the alpha channel is optional. Below is an 82 byte commented version that property handles the alpha channel. ``` import cv2 # import OpenCV library i=cv2.imread(input(),-1) # image file name is specified from stdin # read with the IMREAD_UNCHANGED option # to preserve transparency i[:,:,:3]=255-i[:,:,:3] # invert R,G,B channels cv2.imwrite('a.png',i) # output to a file named a.png ``` As shown below, this properly handles inverting the Firefox logo while preserving the transparent background. [![Firefox Logo Inverted](https://i.stack.imgur.com/QIjRB.png)](https://i.stack.imgur.com/QIjRB.png) ]
[Question] [ **Input:** A string **Output:** The rarity of the string, as described below. To find the rarity of a string, follow the steps below. * **Start** with **0**. * **Subtract 3** for each **E, A, T, or O** in the string. * **Subtract 2** for each **I, N, S, or H** in the string. * **Subtract 1** for each **R, D, L, or C** in the string. * **Add 1** for each **W, F, G, or Y** in the string. * **Add 2** for each **K, V, B, or P** in the string. * **Add 3** for each **J, Q, X, or Z** in the string. **Test cases:** Input: `"rarity"` Output: `-9` Input: `"aardvark"` Output: `-8` Input: `"quine"` Output: `-4` Input: `"wow"` Output: `-1` Input: `"why"` Output: `0` Input: `"puppy"` Output: `7` **Scoring:** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest answer in bytes wins! **Clarifications:** * The input only consists of lowercase letters. * The input is guaranteed to be non-empty. * For U and M, do nothing. * The text can be in any format. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` A2úœ•ι9η†₁Ù^Pι²Qš•èIk4÷3-O ``` Input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f/f0ejwruBHDYvO7bQ8t/1Rw4JHTY2HZ8YFnNt5aFPg0YVACT1Pz2yTw9uNdf3//49WKlLSUUoEYhCdCcQlQFypFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/e94aFVZpb2SwqO2SQpK9pXBof8djQ7vCn7UsOjcTstz2x81LHjU1Hh4ZlzAuZ2HNgUeXQiU0POMyDY5vN1Y1/@/zv9opaLEosySSiUdpcTEopSyxKJsILOwNDMvFUiX55eDyAyQdEFpQUGlUiwA). (With `œ•...•è` replaced with `S•...•.I`, so it won't time out.) **Explanation:** ``` A # Push the lowercase alphabet 2ú # Pad it with two leading spaces œ # Get a list of all permutations of this string •ι9η†₁Ù^Pι²Qš• # Push compressed integer 24022710646877664751280873208 è # Index it into the list of permutations to get string # "aeothinscdlr mufgwybkpvjqxz" Ik # Get the (0-based) index of each character of the input-list in this string 4÷ # Integer-divide each index by 4 3- # Subtract each by 3 O # Take the sum # (which is output implicitly as result) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•ι9η†₁Ù^Pι²Qš•` is `24022710646877664751280873208`. `24022710646877664751280873208` is generated by [the Jelly builtin `Œ¿`](https://tio.run/##BcEHDYAwEABAK2@tdO89ZWCIhARdz53hzm3E734fRCQ8NqVDpcwVAN@FnPuyaZi8DgKQizIupNLGOh9iyqW2Puba5wc) (minus 1, to convert Jelly's 1-based indexing to 05AB1E's 0-based). [Answer] # [Python](https://www.python.org), 63 bytes ``` lambda x:sum('inshrdlcmumuwfgykvbpjqxz'.find(c)//4-2for c in x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NDoIwEEb3nmLCBpqIJMaFMTFexE2hViq0lKHlx6u4wQXeydsY0gZczZvvTWbm9dGDySs1ThzOcJ2s4fHxeympTBmF_tRYGYVCNTmyMpNW2o7fh6JN9aPun-GOC8WijCTJId7zCiEDoaAnfs1bo1AmCpCiMEOwBb4wIRsvKUXWUiycXrp1oLZC3Zx1uKqu6pyY4S_O_bEZ1lhbrb1wSPyj4-jqDw) Port of @Neil's [not yet written charcoal answer](https://codegolf.stackexchange.com/a/254853/107561). ;-p [Answer] # Java 8, ~~63~~ 62 bytes ``` s->s.map(c->"␁ ␆ ␃ ␃ ␁ ␅ ␅ ␂ ␂ ␇ ␆ ␃ ␄ ␂ ␁ ␆ ␇ ␃ ␂ ␁ ␄ ␆ ␅ ␇ ␅ ␇".charAt(c-97)-4).sum() ``` [Try it online.](https://tio.run/##PVCxboMwEFUggJSvODHZCniqVLVRI1WdOjRLxqrDxTiJCRjHNlBa5dupQ9Mup7t3T@@9uxI7zMviNPIKrYU3lOp7ASCVE2aPXMDmOk4AcFJ6NmudrJh1RmDNXpXbTh1YuvLEy8IX69BJDhtQ8DTafG1ZjZrwfJ3O4jCcRVEQJHE4D2ZxEgazeRwlUZIyfkTz7Dzt4Z7md5TZtiZ0XF0FdburvOBNt2tkAbUPSry1VIf3D0D6m3LfGNKhASese0Er4BFSg0a6IUM0hV@dsnMrlcj6ps/645DpVmu/3PFC7A9HWZ6qWjX6bKxru/5z@EqZ1ZV0JM1SSicPgO1gnahZ0zqmfQBXKfJnuEy941Ix/o9Md1lC6e0/l/EH) **Explanation:** ``` s-> // Method with character IntStream parameter and integer return-type s.map(c-> // Map over each character: "␁ ␆ ␃ ␃ ␁ ␅ ␅ ␂ ␂ ␇ ␆ ␃ ␄ ␂ ␁ ␆ ␇ ␃ ␂ ␁ ␄ ␆ ␅ ␇ ␅ ␇" // In this String† .charAt( // Get the character at index: c // The codepoint of the current character -97 // Minus 97 to convert it to a 0-based index )-4 // Then subtract 4 from it // (-1 to convert the codepoint to a digit; and an additional -3) ).sum() // After the map: sum the stream together and return it ``` † This String consists only of unprintable characters. The codepoint-integers of these characters are `[1,6,3,3,1,5,5,2,2,7,6,3,4,2,1,6,7,3,2,1,4,6,5,7,5,7]` (represented above with space-delimited [Control Picture unicode characters](https://www.compart.com/en/unicode/block/U+2400)). [Answer] # Excel (ms365), ~~87~~, ~~86~~, 80 bytes -1 Byte thanks to [@DominicvanEssen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) -6 Bytes thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt) ``` =SUM(MID("16331552276342167321465757",CODE(MID(A1,SEQUENCE(LEN(A1)),1))-96,1)-4) ``` [![enter image description here](https://i.stack.imgur.com/FBOzA.png)](https://i.stack.imgur.com/FBOzA.png) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~38~~ 37 bytes ``` +/3--4!24^"jqxzkvbpwfgymumurdlcinsh"? ``` [Try it online!](https://ngn.codeberg.page/k/#eJxNj01TgzAYhO/5Fch40HHSFMQpTQ6ePXnx1qnTCAlEPhLyUUBHf7spjNDb7j5vJrscP6BHCJObOHkPP7vhqzp/qJ4XY+Map/M6E60pw2cALP6+PYy/GvMgCAZykhW5O3EqajKQkej744+/OYSaamHHkMD98WIp1fmZ6soH6RR0TrTMu2Ryvey9jmZd+mfbSSqnlDe7IwAIlNYqgxHKZM4KWfONsTSr2JCVtC3YJpMN6hwzVsjWoPgpSeMIzS2g5JBCY7VoCwDe/E2QUcMMBi+tchYH/23Bq7NTAPdgYUv1laYrnXesKFnRZdQKoitQXn21XfN57kJ2f1mngW8=) Essentially a port of [Kevin's 05AB1E answer](https://codegolf.stackexchange.com/a/254824/98547). * `24^"jqxzkvbpwfgymumurdlcinsh"?` get 0-based indices of input in this lookup string (the "missing" `"eato"` is filled with `24^`) * `3--4!` integer divide the indices by 4, then subtract the result from 3 * `+/` take the sum (and implicitly return) [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 17.5 bytes (35 nibbles) ``` +.$- 3=?;$$`D7 3c2740e64a52f8f4a8d ``` A rather sneaky port of [hakr14's Pyth answer](https://codegolf.stackexchange.com/a/254897/95126): upvote that! ``` .$ # map across each character of input ?;$$ # get index+1 in alphabet = # get element at that index `D # of data value 3c2740e64a52f8f4a8d 7 # in base-7 -3 # and subtract from 3 + # finally, get the sum ``` [![enter image description here](https://i.stack.imgur.com/VPg9w.png)](https://i.stack.imgur.com/VPg9w.png) --- Previously: # [Nibbles](http://golfscript.com/nibbles/index.html), ~~24.5~~ 24 bytes (48 nibbles) ``` +.$- 3/+?`D-26$3 4 2a4654a17c30c595a94262e628a6 ``` ``` +.$- 3/+?`D-26$3 4 .$ # map across letters of the input ? $ # getting the index (or 0 if not found) of each in: `D # the data value 2a4654a17c30c595a94262e628a6 - # interpreted as characters 26 # in base 26 # (this equates to the string "bkpvfgwy mucdlrhinsaeot") + 3 # add 3, / 4 # integer-divide by 4, - 3 # and subtract from 3, + # and finally output the sum. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 26 bytes ``` «ƛ₇⇩⇧ɽ¬Ẏ₁5≬*⋎ǑṄǑz!«vḟ4ḭ3-∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiwqvGm+KCh+KHqeKHp8m9wqzhuo7igoE14omsKuKLjseR4bmEx5F6IcKrduG4nzThuK0zLeKIkSIsIiIsInJhcml0eVxuYWFyZHZhcmtcbnF1aW5lXG53b3dcbndoeVxucHVwcHlcbm15bmFtZWplZmZcbmx5eGFsZ29sZmluZ1xuYnJ1aG1vbWVudCJd) Port of Kevin's 05AB1E answer. ## Explained (old) *I'll rework this tomorrow when it's not 12:59am* ``` ƛ«∧Ǒ₄ẇ*§,(ε±ẏt∩⁽→«6/$vcT›h3ɾḂNJ0pi ƛ # To each character in the input «∧Ǒ₄ẇ*§,(ε±ẏt∩⁽→« # Push the string "wfgykvbpjqxzeatoinshrdlc" - this corresponds to the groups [+1, +2, +3, -3, -2, -1] 6/ # And split that string into 6 equal length pieces. $vcT›h # Get the 1-based index of where the character is in the +- grouped string (u and m will return 0) 3ɾḂNJ0p # The list [0, 1, 2, 3, -3, -2, -1] i # Indexed by the previous number # At the end of execution, the `s` flag sums the list of numbers ``` [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), ~~62~~ ~~60~~ 56 bytes Rare case where ><> beats python * -2 bytes because I can't be beaten by Java, and by poluting the stacks. * -4 bytes by reading from the stack instead of jumping, which eliminates the delete stack loop ``` 0i:0(?^'a'-1g'3'-+00. 05220441165231056210354646 ;n~\ ``` [Experience it in full HD\*](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiMGk6MCg/XidhJy0xZyczJy0rMDAuXG4wNTIyMDQ0MTE2NTIzMTA1NjIxMDM1NDY0NlxuICAgO25+XFwiLCJpbnB1dCI6InB1cHB5Iiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9) \*only if you have a full HD monitor, you have anti-aliasing enabled in your browser, you are zoomed out 50%, and the stars are aligned. ## Explanation [![enter image description here](https://i.stack.imgur.com/QQ560.png)](https://i.stack.imgur.com/QQ560.png) Top row: Take input, subtract it from "a" to get the index at the bottom. If the input is negative we go up. Read the letter from the middle row, subtract the char code of 3 then add it to accumulator. Middle row: Raw data on char values. Print result and exit [Answer] # [Python](https://www.python.org), ~~80~~ 79 bytes * -1 byte thanks to @Mukandan314 ``` lambda x:sum(map(int,x.translate('0'*98+'5220441165231056210354646')))-len(x)*3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NDoIwEEb3noK4oUUwLX9BE8_gBdyMAQIRSi2twFnc4ALv5G2UtAFX8-Z7k5l5vvkgi4aNU26drMukZO4ln3MF9TUFqz-2qkY1cFQy6fZ7KYC1FcgM2cR2DsnOjnyfhCGlceQHlESxT0kQhXEY2xhjr8oY6rETmLUvLn570FaAKOWwda18YYw3RgKI9AHipvXSrQN3VbJMW42r6ppOixn-4sIcm2GNueLcCI0Y60fHUdcv) [Answer] # [Python](https://www.python.org), ~~70~~ 64 bytes ``` lambda x:sum(int(b'"v4!g2euqc1U'.hex()[ord(c)%26])-4for c in x) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwdI0BVuFmKWlJWm6FjcdchJzk1ISFSqsiktzNTLzSjSS1JXKTBTTjURSSwuTDUPV9TJSKzQ0o_OLUjSSNVWNzGI1dU3S8osUkhUy8xQqNKHmLCwoAmlWKkosyiypVNJRSIOzNTW5oJKJiUUpZYlF2RBpOA-hoLA0My8VIgthIqTK88shEiAGknAG1DIQAyFcUFpQAJWAMDWhDl2wAEIDAA) -6 bytes thanks to [@loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt) and [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 64 bytes ``` s=>Buffer(s).map(c=>s="11652310562103546460522044"[c%26]-4-~s)|s ``` [Try it online!](https://tio.run/##Zc27DsIgAIXh3adoSEzKQAuUog508DWMA8Gi1VoQekkT46tXTbwF5//LOUfZS69cZVvUmF05aTF5Uaw7rUsXe5icpY2VKLwAhPCcZgTnnBKc5YwzjnNKMWNgo@aUbxFDNw@vflKm8aYuk9rsYx0DJ13VjiCKIIzSNEKrWQCkdLteuhN4gWUILl3VlI@B9wILwWCGZ/4A8gcO4y/AYbedteP3YTHdAQ "JavaScript (Node.js) – Try It Online") [Answer] # TI-Basic, 55 bytes ``` sum(seq(int(~inString("KVBPWFGYMMUURDLCINSHEATO",sub(Ans,I,1))/4)+3,I,length(Ans ``` Takes input in `Ans` as a string with all uppercase letters. `~` represents the negative symbol. [Answer] # Python 3, ~~154~~ 150 bytes -4 thanks to Ismael ``` o=0 for I in input(): if I in'eato':o-=3 if I in'insh':o-=2 if I in'rdlc':o-=1 if I in'wfgy':o+=1 if I in'kvbp':o+=2 if I in'jqxz':o+=3 print(o) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3p-XbGnCl5RcpeCpk5gFRQWmJhqYVF2dmGlhEPTWxJF_dKl_X1hghlplXnAEWM0KIFaXkJIPFDBFi5WnplUAxbWSx7LKkArAYkt6swooqsJgxV0FRZl6JRr4mxHVQRy5YkZhYlFKWWJQN4QMA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` IΣES⊖⊖÷⌕”&⌈∨v_≕º↖Rb)}ζ⎇K⮌9”ι⁴ ``` [Try it online!](https://tio.run/##TYzLCsIwEAB/pfS0hXrz5tEi9CAI/YI0WdvVZE3TTXz8/Frw4pwGBsbOJtmH8aqXRCxwNKvAkAOcTYSeY5ZBtjBB01Yd2oQBWdDBv/csHRVyCCdiBzXxOifnbcghP6/T@17GeFten7qtaNvsmx8H1SUTo@6K/wI "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @loopywalt's answer, but only because I didn't have time to write this answer 10 hours ago. Explanation: ``` S Input string E Map over characters ⌕ Find index of ι Current character in ”...” Compressed string `inshrdlcmumuwfgykvbpjqxz` ÷ Integer divide by ⁴ Literal integer `4` ⊖ Decremented ⊖ Decremented Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~64 ...~~ 52 bytes ``` ->s{s.bytes.sum{0x69a560ad416ae264095[_1%49*3,3]-3}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3TXTtiquL9ZIqS1KL9YpLc6sNKswsE03NDBJTTAzNElONzEwMLE2j4w1VTSy1jHWMY3WNa2uhet0LFNKilYoSizJLKpViubgKFDTsE_X07Ks09XITC6prCmvSogtjtY1rwVIGFcYmKUZJBqZmiQZJpuaGxkYGJokWdnbGmhDjFiyA0AA) Thanks south for -2 bytes. So long, TIO, and thanks for all the fish. ### How? The value of each letter is encoded in 3 bit (0 to 6 instead of -3 to +3), then packed into a 26-digit octal number. The letter 'a' is discarded because "out of range" is automatically translated to zero, which becomes -3. This gives a 75-bit value (25\*3) which can be encoded in 19 hexadecimal nibbles. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~88~~ 87 bytes ``` +T`eiran\dts\l\o\hc`321o \d $*- +T`jk\wqvfxbgz\py`321o \d $* m|u +`.\b. ^(-)?.* $1$.& ``` [Try it online!](https://tio.run/##TckxDsIgGAbQ/TsHmtqmJNUDOHoBxz8GKtViFShCEePd0dG3Pj8EbWRZVQdRmqMYtJeGVHjSnSyNZ7HbdhakwOoWv79NlObl8uqvb3L5b/H4RKARnHoOnKp2s@c1WMf4uhQvvQ4ZUnq1SD9hjtoMSDYhjRkuOpe/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` +T`eiran\dts\l\o\hc`321o ``` Translate common letters to digits. (Some letters have special meanings, such as `o`, which means copy the other pattern, so they have to be quoted.) ``` \d $*- ``` Expand the digits to `-`s. ``` +T`jk\wqvfxbgz\py`321o ``` Translate rare letters to digits. ``` \d $* ``` Expand the digits to `1`s (golfier than `+`s). ``` m|u ``` Delete any leftover `m`s and `u`s. ``` +`.\b. ``` Cancel out pairs of `-`s and `1`s. This works because they create a word boundary between them. ``` ^(-)?.* $1$.& ``` Convert to decimal. Edit: Saved 1 byte by copying @MartinEnder's code to subtract signed numbers from his answer to [Add two numbers](https://codegolf.stackexchange.com/q/84260/). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~68~~ 63 bytes -4 bytes thanks to [c--](https://tio.run/##LY1RboMwEES/8SlWSEgGgoRNbKSgqhfoDVI@LIITq9QhayiqEFcvNSFfO7PzNNNkTafsdV01TVw8YzuMaBP3HnJeyuLImSwLzo5SlKJksiiYEOE5cRGXdSZ4qqlLWXzKq2U1doBvZSyNyUwC7xIYWjeca3iDGT5CVGiG3/DgpVJ4@VH49TSP0dj2qab7tN/bjvVj328qh6Uigb4j0G3E@MK82stNXYFJ05gEfnMbBfRogB7R9EXE26dHH2oaRp3zWXT5tL74BRwAN2YhC1n/Gt2pq1uz6R8) ``` f(int*s){s=*s?"22763421673214657571633155"[*s%26]-52+f(s+1):0;} ``` [Try it online!](https://tio.run/##LY7RjoIwEEWf6VdMmpC0IAkttiRLjD@wf6A8NGjdZl1kW1xiCL@@tRWf5s7MmXunKy5d570mph8zR2e3y9wec17LasuZrCvOtlLUomayqpgQ@JC5lMu2EDzXxOWMfpTN4sM1/CjTE4pmlEQvGM9uPLSwgxk@sVXWjA@8CVIpe/pT9vvV/N5Nf36p6Tat9WvFhvswRFXC0qBE3yzEF8EEw7JZzU3bgMlzipKQGUPBBjSxAdHkTdA4GWxYaoLTqwu79HTsg/Eb2ICNzIIW5P87fVUX54vpCQ "C (gcc) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), 62 bytes With the unprintable characters from Kevin Cruijssen's answer as suggested by c-- and Mukundan314. ``` f(int*s){s=*s?""[*s-97]-4+f(s+1):0;} ``` [Try it online!](https://tio.run/##LY5haoNAEIVRo@KeYlgI7GoEA4XSSugFeoPUH4vJpksTY2dNpYhX73Y25te8mfnmvWnLU9s6p4XphtzKye5y@8aDJIqCOA7DNIlWYZCkURiskjiNU77Pbfny3JRPhRa22MrXqp4dHcNFmU5INrHMW8FwtMO@gR1M8M5RoRl@@YakUnj4Ufh1b75vpjve1Xgdl/q5YP2t772qYK5Zpq8I/kMwZFjVi7lpajBFIVlGmT4UkNAMCdHiQUg/6ZGWWvD12dJuffjoyPgBbAA9M7OZub9Wn9XJunL8Bw "C (gcc) – Try It Online") [Answer] # [Zsh](https://www.zsh.org/) `--extendedglob`, 68 bytes ``` a=(insh rdlc um wfgy kvbp jqxz) <<<$[${1//(#m)?/+$a[(I)*$MATCH*]-3}] ``` [Try it online!](https://tio.run/##PYw7D4IwGEV3fsWXyNBqDDGuGGNcdHBzIwyFFlqepQ8KGH87DoZO957k3rNovmpmemmATYZ1lNGy6bMgUEQJMyOMVnJBotMcFG1ysC24opyhHjMJ1TAtOIjjOEzCzymK0K7F1@gQkgQ98T583d73xz49nr/pijcjDI4pM1vRS6JpUfKqbpYpH7Ou9ZN/bESIoiNRNXiDFR3bwPXOV@4/0ko5rz8 "Zsh – Try It Online") Because shell raw strings don't need quotes, using an array is shorter than doing math on a single string lookup. ``` a=(insh rdlc um wfgy kvbp jqxz) # lookup table, offset by 3, with no 'eato' <<<$[${1//(#m)?/+$a[(I)*$MATCH*]-3}] # ${1//(#m)?/ } # Replace every character in the string with # + -3 # "+", "-3" literal strings # $a[(I)*$MATCH*] # The lowest index of $a matching *<char>*, 1-indexed # If no match (e.g.: *e*) substitute "0" # $[ ] # Evaluate arithmetically ``` [Answer] # APL, 60 bytes ``` {s←⍵⋄+/⊃(4-⍨⍳7)+.×{s∊⍵}¨↓7 4⍴'eatoinshrdlcumumwfgykvbpjqxz'} ``` [Try it online!](https://tryapl.org/?clear&q=%7Bs%E2%86%90%E2%8D%B5%E2%8B%84%2B%2F%E2%8A%83(4-%E2%8D%A8%E2%8D%B37)%2B.%C3%97%7Bs%E2%88%8A%E2%8D%B5%7D%C2%A8%E2%86%937%204%E2%8D%B4%27eatoinshrdlcumumwfgykvbpjqxz%27%7D%C2%A8%27rarity%27%20%27aardvark%27%20%27quine%27%20%27wow%27%20%27why%27%20%27puppy%27&run) [Answer] # Raku, 64 bytes ``` .comb>>.&{('inshrdlcmumuwfgykvbpjqxz'.index($_)//-2)div 4-2}.sum ``` [Try it online!](https://glot.io/snippets/gfpzwqdtsv) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 22 (or 29?) bytes. ``` sXQG-L3jC"ÅŽ˜–Ž ê "7 ``` [Test suite](https://pythtemp.herokuapp.com/?code=sXQG-L3jC%22%01%C3%85%C2%8E%C2%98%C2%96%C2%8E%C2%9D%1E%C3%AA%1C%227&test_suite=1&test_suite_input=%22rarity%22%0A%22aardvark%22%0A%22quine%22%0A%22wow%22%0A%22why%22%0A%22puppy%22&debug=0) *Note: the program uses characters not properly displayed by StackExchange, which have been replaced in the above snippet for readability. The link provides a correct and copyable source.* If Pyth's supposed SBCS works the way `C` seems to imply, then this is encoded as 22 bytes. In UTF-8, it's 29 bytes. I've never found a foolproof answer to this issue. (For the record, [`C`](https://github.com/isaacg1/pyth/blob/b70e591254a79b2b6efaa9b05d1d56d1bd9c2512/macros.py#L651) just uses `chr` and `ord` over base 256, which would suggest each of the characters those functions spit out for range [0-255] should be considered a single byte. I dunno though.) ##### Explanation: ``` sXQG-L3jC"..."7 | Full code (with string contents omitted) ----------------+---------------------------------------------------------------------- C"..." | Convert a magic string to an integer from base 256 j 7 | Convert this int to base 7 as a list -L3 | Replace each digit d with 3-d XQG | Translate the input from the lowercase alphabet to the resulting list s | Sum the results ``` [Answer] # Javascript (Browser) 155 Bytes ``` var r=s=>[...s].reduce((o,I)=>o+(({e:-3,a:-3,t:-3,o:-3,i:-2,n:-2,s:-2,h:-2,r:-1,d:-1,l:-1,c:-1,w:1,f:1,g:1,y:1,k:2,v:2,b:2,p:2,j:3,q:3,x:3,z:3})[I]||0),0); ``` [Answer] # [jq](https://stedolan.github.io/jq/), ~~91~~ 86 bytes ***-5 bytes** from using `/` instead of `split()`* ``` ./""|map([inside(["eato","insh","rdlc","um","wfgy","kvbp"][])]|(index(true)//6)-3)|add ``` ~~[Try it online!](https://tio.run/##DcfLDoMgEEDRPZ/BCpKaLpr0Q7o1LkZBHR8w8hBp/PZSNvfkLkcpnjYMgnN570CiReNRadFyDcHyB68/V5zahkrca9I45cp69sS7tpPdLdAofYngopbP51s2L3mDUqUcSbuQI1oCr8ZpXtbtew1nb3bmwGHIDMCpE9zKjohGs2QTS3NmFInyz1JAa3xpPn8 "jq – Try It Online")~~ [Try it online!](https://tio.run/##DcdNDoMgEEDhPcdgBUmtiyY9SLfGxeigjj@ACCKNZy9l8768ec/5WXN@b2BFQ/ogVKLhCrzhD15@Kjhc@0LYSuIwpsJydpa3TSvbW5BGdQnvgpJ1/ZbVS96AmPMelfMpkLFw4DBO87J@r/7s9MYcOPKJATg8wS1sD6QViyayOCVmg7XpZ6wno49cff4 "jq – Try It Online") Leaves off `jqxz` from the array, and instead uses `//6` to catch those cases. ]
[Question] [ Given an input, output that input followed by a newline endlessly. Input will be a string consisting only of printable ASCII characters (`0x20-0x7E`) and newlines (`0x0A`). If input is length 0, endlessly output newlines. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins! [Answer] # [Bash](https://www.gnu.org/software/bash/), 8 bytes ``` yes "$1" ``` [Try it online!](https://tio.run/##S0oszvj/vzK1WEFJxVDp////Hqk5OfkK4flFOSkA "Bash – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` [, ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/Wuf/fyUwAAA "05AB1E – Try It Online") [Answer] # [AutoHotkey](https://autohotkey.com/), 20 Bytes OP did not specify *how* the output should happen, said only it has to happen endlessly with a newline after it. AHK was not tailored for cmd interaction. So the output happens repeatedly in a `ToolTip` at mouse position: ![tooltip](https://i.stack.imgur.com/bQBEe.png) ``` loop tooltip,%1%`n`n ``` I like AHK's `loop` feature. `loop` repeats the next block forever, `loop, 10` would repeat it 10 times. Sometimes I miss this feature in other languages like Python. The escape character in AutoHotkey is ``` (so there are no problems with backslashes in Windows paths). For some reason, a trailing newline is ignored so it is needed twice. (`trayTip` might not have this "bug" but I cannot test it because running with wine) ## old answer: ``` loop msgbox,%1% ``` I just realized that OP probably wont like this solution, the output happens with user-interaction and includes no newlines. I'll look for another way. [Answer] # JavaScript (ES6), 24 bytes ``` f=a=>f(a,console.log(a)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbR1i5NI1EnOT@vOD8nVS8nP10jUVPzf5qGkkdqTk6@jkJ4flFOiqKSpvV/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 3 bytes ``` ∞┼, ``` [Try it online!](https://tio.run/##y8/I/f//Uce8R1P26Pz/n5iUAgA "Ohm – Try It Online") It doesn't work with an empty input because Ohm is bad at input handling compared to other languages, but you can input "". Explanation ``` ∞ Infinite loop next code (until ";" or end of line) ┼ Get first input , Println ``` [Answer] # sed, 5 ``` : # label (unnamed) p # print the pattern space b # branch back to the label ``` Unnamed labels is an undocumented "feature" in sed that works with version 4.2.2, but may not work in future versions. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Ṅß ``` [Try it online!](https://tio.run/##y0rNyan8///hzpbD8////@9clJpYkqqQqBCQWFSUX6IQUJSfXpSYqwgA "Jelly – Try It Online") Print with a newline, repeat the whole link (program). [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 27 bytes ``` +[>,]++++++++++[[<]>>[.>]<] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO9pOJ1YbDqKjbWLt7KL17GJtYv//dy5KTSxJVUhUCEgsKsovUQgoyk8vSsxVBAA "brainfuck – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 21 bytes ``` def f(s):print s;f(s) ``` *Assumes no recursion limit* **[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo1jTqqAoM69EodgaxPmfpqHkXFpSkpOqkJZZnKGopPkfAA "Python 2 – Try It Online")** [Answer] # [V](https://github.com/DJMcMayhem/V), 2 bytes ``` òÙ ``` You can't try this online for obvious reasons. ``` ò 'Recursively Ù 'Duplicate the current line downwards ``` [Answer] # [LibreLogo](https://help.libreoffice.org/Writer/LibreLogo_Toolbar#LibreLogo_programming_language), 33 bytes **Code:** ``` x=input " repeat [ label x bk 9 ] ``` **Explanation:** ``` x = input " ; Input Stored in x as String repeat [ ; Endless Loop label x ; Print x in Current Position bk 9 ; Move Back 9 pt ] ``` **Result:** [![enter image description here](https://i.stack.imgur.com/lbbxw.gif)](https://i.stack.imgur.com/lbbxw.gif) [Answer] # Ruby, ~~18~~ ~~17~~ 12 + 2 = 14 bytes Run with the `-n` flag. ``` loop{$><<$_} ``` Edit: Thanks for @sethrin for the `-n` flag! [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 6 bytes ``` AN/qvo ``` [Test it here](https://ethproductions.github.io/cubix/?code=ICBBCk4gLyBxIHYKICBvCg==&input=dGVzdAoxIC4uIDIgLi4gMw==&speed=200) ``` A N / q v o ``` * `N/A` Push Newline(10) and input onto the stack * `v` redirect into the loop * `o/q` loop that outputs a character and pushes it to the bottom of the stack continuously I was going to remove the EOI (-1) indicator from the stack, but it doesn't appear to affect the output any, so have left it saving bytes. [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes ``` s=input() while 1:print s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9g2M6@gtERDk6s8IzMnVcHQqqAoM69Eofj/f6W0/HwlAA "Python 2 – Try It Online") Input is expected to be a Python literal (quotes for a string, square bracket or parentheses with comma-separated items for a list/tuple, etc.) Python 3 would be +1 byte because `print` is a function, but also could do raw input without the 4-byte penalty for `raw_input()` in Python 2. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ẉ?↰ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuTvtHbRv@/1dyLkpNLElVSFQISCwqyi9RCCjKTy9KzFVUAgA "Brachylog – Try It Online") Port of [my Jelly answer](https://codegolf.stackexchange.com/a/124664/48934). [Answer] # PHP, 20 bytes ``` for(;;)echo"$argn "; ``` [Answer] ## Haskell, 14 bytes ``` cycle.(++"\n") ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802uTI5J1VPQ1tbKSZPSfN/bmJmnoKtQkFpSXBJkYKKQklidqqCkYEBkJmmoBSQn5NTqfQfAA "Haskell – Try It Online") Append a newline to the input and make list of infinite copies of it. Alternative version, also 14 bytes: ``` unlines.repeat ``` [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), ~~14~~ 12 bytes ``` # V[R!&@v1+] ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9fmSssOkhRzaHMUDv2////Hqk5OfmKAA "Braingolf – Try It Online") *-2 bytes thanks to totallyhuman* ## Explanation ``` #\nV[R!&@v1+] Implicit input of string as charcodes #\n Push charcode of newline V Create stack2 [R...v1+] While loop, runs endlessly !&@ Print entire stack1 as chars without popping ``` [Answer] # C, 24 bytes ``` f(char*s){puts(s),f(s);} ``` Basically a recursive function that outputs the string before calling herself again. Its my second post on codegolf so please be nice :p [Answer] # Haskell, 21 bytes ``` putStr.cycle.(++"\n") ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` OpU;ß ``` [Try it online!](https://tio.run/##y0osKPn/378g1Prw/P//lTxSc3LydRTC84tyUhSVAA "Japt – Try It Online") **Explanation** ``` OpU; output the input with a newline ß run the code again with the same input ``` [Answer] # C#, 40 bytes ``` s=>{for(;;)System.Console.WriteLine(s);} ``` [Answer] # MATL, 4 bytes ``` `GDT ``` [**Try it Online**](https://tio.run/##y00syfn/P8HdJeT/f/WM1JycfIXy/KKcFHUA) **Explanation** ``` ` % Do...while loop G % Grab input D % Display it on a new line T % Literal TRUE to create an infinite loop ``` [Answer] # C, 26 bytes ``` f(char*s){for(;;)puts(s);} ``` A function, `f`, that takes a C-style string as a parameter, `s`. The body of the function loops repeatedly, passing the string to the library function `puts`, which outputs the string to the standard output (stdout) along with a trailing new-line. Pretty simple stuff. The only hack here is taking advantage of default-int for the return value and then not actually returning a value. That doesn't matter in this case, though, since the function never returns (it just keeps printing forever)! [Try it online!](https://tio.run/##S9ZNT07@/z9NIzkjsUirWLM6Lb9Iw9pas6C0pFijWNO69n9mXolCbmJmngaIkaejAFaopZCsyVXNxQnUF20Yq2nNxVmUWlJalKdgYM1V@/@/R2pOTj6XQnh@UU6KIgA) [Answer] # Groovy, 20 bytes ``` x={println it;x(it)} ``` [Answer] # Java 8, 34 bytes ``` s->{for(;;System.out.println(s));} ``` Surprised there wasn't a Java answer yet. [Try it here.](https://tio.run/##LY2xDoIwFEV3vuKFqR3gBxqdXWRhNA7PUkyxvJL2gTGEb69FWW5yb3LuGXDByk@Ghu6VtMMY4YqW1gLAEpvQozbQ7BVg8bYDLVoOlp4QpcrrVuSIjGw1NEBwghSr89r7IJRqP5HNWPuZ6ykz7EhEKdWW1E5N88Nl6oB/52NWH/@3O6D8e6nWorwY5zy8fXBdeZi39AU) (Wait 60 second for it to time-out.) [Answer] # Pyth, 2 bytes ``` # ``` ~~Unfortunately I can't remove `Q` :(~~ You need to run from command-line like this, so that this is competing: ``` python3 pyth.py -c "# " ``` The interpreter has been fixed too. [Answer] # [><>](https://esolangs.org/wiki/Fish), 16 bytes ``` i:0(?v :o71.>~a{ ``` [Try it online!](https://tio.run/##S8sszvj/P9PKQMO@jMsq39xQz64usfr/f0MjYxNTMwA "><> – Try It Online") As mentioned in the comments below my first attempt may have misunderstood the question so the newer 16 byte solution has been made, I have left the original below so people may see. # [><>](https://esolangs.org/wiki/Fish), 13 bytes ``` <ov!?+1:i oa< ``` [Try it online!](https://tio.run/##S8sszvj/3ya/TNFe29Aqkys/0eb/f0MjYwA "><> – Try It Online") [Answer] # [CJam](https://sourceforge.net/p/cjam), 6 bytes ``` q{_n}h ``` [Try it online!](https://tio.run/##S85KzP3/v7A6Pq824///AMegIH/sIEQRAA "CJam – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 27 bytes ``` while(1){print"$ARGV[0]\n"} ``` [Try it online!](https://tio.run/##K0gtyjH9/788IzMnVcNQs7qgKDOvREnFMcg9LNogNiZPqfb///8eqTk5@YoA "Perl 5 – Try It Online") ]
[Question] [ **This question already has answers here**: [Orthodiagonal steps](/questions/164760/orthodiagonal-steps) (58 answers) Closed 5 years ago. List the coordinates of 8 squares adjacent to `(0, 0)` in a 2d grid. Namely, `[(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)]` Order does not matter. The goal is to store the points into a list. Shortest answer wins. [Answer] # J - 12 char The most natural representation of a list of pairs is a list of boxes containing each pair. ``` }.4|.,{;~i:1 +---+----+---+---+-----+----+----+----+ |0 1|1 _1|1 0|1 1|_1 _1|_1 0|_1 1|0 _1| +---+----+---+---+-----+----+----+----+ ``` The magic happens in `{`, called *Catalogue*. It is essentially a generalized Cartesian product. The `}.4|.` part is for removing the `0 0` pair. [Answer] ## Bash + grep 35 ``` eval echo\ {-1..1},{-1..1}\;|grep 1 ``` I know this doesn't beat the other bash answer but someone had to think of `grep` [Answer] # Ruby ~~29~~ ~~28~~ 26 ``` (a=-1,1,0).product(a)[0,8] ``` ### Bonus solution: Ruby has many nice builtin array operators, but some of them have ridiculously long names. ``` [*[-1,1,0].repeated_permutation(2)].take 8 ``` [Answer] # Python 43 32 ``` l=zip([1,-1,0]*3,[-1,1]*3+[0]*2) ``` Inspired by @primo [Answer] ## GolfScript (17 chars) ``` 9,4-{[.3/(\3%(]}% ``` Since the question calls for the points to be "listed in natural format", this leaves an array on the stack. To pretty-print it, append `p`, as in the [online demo](http://golfscript.apphb.com/?c=OSw0LXtbLjMvKFwzJShdfSUKcA%3D%3D). [Answer] # Haskell 32 ``` c=[0,1,-1] _:l=[(a,b)|a<-c,b<-c] ``` The list is l (L). [Answer] # Brainfuck, 1093 characters. ``` ++++++++[>+>++>+++>++++>+++++>++++++>+++++++>++++++++>+++++++++>++++++++++>+++++++++++>++++++++++++>+++++++++++++>++++++++++++++>+++++++++++++++>++++++++++++++++<<<<<<<<<<<<<<<<-]>>>>>>>>>>>+++.---<<<<<<<<<<<>>>>>.<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>.<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>.<<<<<<>>>>>>----.++++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>.<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>>----.++++<<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>----.++++<<<<<<>>>>>.<<<<<>>>>>>.<<<<<<>>>>>>----.++++<<<<<<>>>>>>---.+++<<<<<<>>>>>>+.-<<<<<<>>>>>+.-<<<<<>>>>>>>>>>>>---.+++<<<<<<<<<<<<. ``` # EDIT 209 characters ``` ++++++++++[>+++++++++>++++>+++++>++++<<<<-]>+.>.>-.>++++.<.<+.>>.<<-.>.>.<-.<+.>>.<<-.>+.>.+.-<.<+.>>.<<-.>-.>.<+.<+.>>.<<-.>-.>.+.<+.<+.>>-.<<-.>>+.<.>-.<.<+.>>.<<-.>>+.<.>-.<-.<+.>>.<<-.>>+.<+.>-.+.<.<+.<++. ``` Original by Benjamin - i gave it another shot as well and got to 209 characters as well. [Answer] # Perl, 43 bytes ``` for$x(-1..1){$x|$_&&push@r,[$x,$_]for-1..1} ``` The result is stored in array `@r`. Explicitly it can be defined with 58 bytes: ``` @r=([-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]) ``` [Answer] ## J, 16 characters ``` }.4|.,<@,"0/~i:1 ``` Usage: ``` }.4|.,<@,"0/~i:1 ┌───┬────┬───┬───┬─────┬────┬────┬────┐ │0 1│1 _1│1 0│1 1│_1 _1│_1 0│_1 1│0 _1│ └───┴────┴───┴───┴─────┴────┴────┴────┘ ``` Pretty ugly - especially dropping the `(0, 0)`. There's probably a better way. [Answer] # Mathematica 23 ``` Most@Tuples[{-1,1,0},2] (* {{-1, -1}, {-1, 1}, {-1, 0}, {1, -1}, {1, 1}, {1, 0}, {0, -1}, {0, 1}} *) ``` [Answer] # Brainfuck, ~~217~~ 209 characters. Only a bit worse than Java! 5x less than the other BF solution. ``` ++++++++++[>+++++++++>++++>+++++>++++<<<<-]>+.>.>-.>++++.+.<.<+.>>-.<<-.>.>.<-.<+.>>.<<-.>+.>.<.<+.>>.<<-.>-.>.<+.<+.>>.<<-.>>+.<.>-.<.<+.>>.<<-.>>+.<.>-.<-.<+.>>.<<-.>>+.<+.>-.+.<.<+.>>-.<<-.>-.>.+.<+.<+.<++. ``` [Answer] ## Mathematica, 44 characters ``` Outer[List,d=Range@3-2,d]~Flatten~1~Drop~{5} ``` Well. Generates all 9 coordinates, flattens the list and drops the centre. [Answer] # Python 50: ``` l=[(a,b)for a in[1,0,-1]for b in[1,0,-1]];l.pop(4) ``` [Answer] # Bash, 25 characters Storing the list of coordinates as a bash array `a`: ``` a=({-1..1},{-1..1});a[4]= ``` Output: ``` $ a=({-1..1},{-1..1});a[4]= $ echo ${a[@]} -1,-1 -1,0 -1,1 0,-1 0,1 1,-1 1,0 1,1 $ ``` [Answer] # F# - ~~41~~ 36 bytes ``` [for i in 0..7->i*2/5-1,(i*5/4)%3-1] ``` [Answer] # C++, 60 Let's do this an interesting way. Hint: "2" is ASCII 50. ``` char x[]="11123332",y[8],i;for(i=8;i--;)y[(i+2)%8]=x[i]-=50; ``` [Answer] # Python - ~~57~~ ~~54~~ 56 ``` r=range(-1,2);list({(i,j) for i in r for j in r}-{(0,0)}) ``` Improved to ``` r=[-1,0,1];list({(i,j) for i in r for j in r}-{(0,0)}) ``` with storage of the variable ``` r=[-1,0,1];l=list({(i,j) for i in r for j in r}-{(0,0)}) ``` [Answer] # Perl 6: 27 characters Most simply: ``` $/=(-1..1 X -1..1)[^4,5..*] ``` Get the permutations of -1, 0, and 1 with itself, and hard-code skipping (0, 0). But that's no fun! I prefer things to be more complex: (50 characters) ``` $/=map {[.re,.im]},grep *.abs>0,(-1..1 X+ -i,0i,i) ``` [Answer] ## Python - 37 bytes ``` a=[(i*2/5-1,-i%3-1)for i in range(8)] ``` An alternative at 40: ``` a=zip([0,1,-1]*3,[0]*3+[1]*3+[-1]*3)[1:] ``` And a 42 that's also interesting: ``` a=0,1,-1;a=zip(sum(zip(a,a,a),()),a*3)[1:] ``` [Answer] # APL (13 characters) ``` 1↓,∘.,⍨0 1 ¯1 ``` Explanation: ``` 1↓ ⍝ Drop the first element of , ⍝ an array that comes from the matrix formed by ∘.,⍨ ⍝ concatenating each element with every other element 0 1 ¯1⍝ in this array [0,1,-1] ``` [Answer] # Java 207 204 Way too much, I know, but its the best I could do right now... I might think of something better... ``` class A{public static void main(String...a){int[][] l=new int[8][2];for(int x=-1,y,i=0;x<2;x++){for(y=-1;y<2;y++){if(x!=0||y!=0){l[i][0]=x;l[i][1]=y;System.out.print("("+l[i][0]+","+l[i][1]+")");i++;}}}}} ``` Sensibly: ``` class A { public static void main(String...a) { int[][] l = new int[8][2]; for (int x = -1, y, i = 0; x < 2; x++) { for (y = -1; y < 2; y++) { if (x != 0 || y != 0) { l[i][0] = x; l[i][1] = y; System.out.print("("+l[i][0]+","+l[i][1]+")"); i++; } } } } } ``` [Answer] # PYG (27): ``` P(*ItPr((-1,0,1),repeat=2)) ``` Nothing all that special, really. In regular python: ``` from itertools import product for i in product((-1,0,1),repeat=2): print i ``` [Answer] # C, 73 ``` main(i){for(i=0;i<9;i++)if(i-4)printf("%s(%d,%d)",i?",":"",i%3-1,i/3-1);} ``` [Answer] # Mathematica: 41 This works most of the time ;) ``` Union[RandomInteger[2,{99,2}]-1]~Drop~{5} ``` Equivalently: ``` Drop[Union@RandomInteger[2,{99,2}]-1,{5}] ``` [Answer] # Matlab: 53 Similar to my other answer: ``` unique(round(2*rand(99,2))-1,'rows');ans([1:4,6:9],:) ``` I couldn't index on the output of unique directly, and I couldn't find a way around that... [Answer] # Haskell 97 Too much for Haskell and definitely not as good as the other Haskell answer, but here's a different, albeit sucky, approach: ``` take 8 (zip (replicate 3 (-1) ++ replicate 3 1 ++ replicate 3 0) (concat (replicate 3 [-1,1,0]))) ``` :D [Answer] # Scala, 56 Self-explanatory. ``` def x=List(-1,0,1);for{i<-x;j<-x;if i!=0|j!=0}yield(i,j) ``` Ungolfed: ``` def x=List(-1,0,1) for{ i <- x j <- x if i!=0 | j!=0 } yield(i,j) ``` [Answer] # Perl, 42 characters: ``` @r=map[split","],grep/1/,glob"{-1,0,1},"x2 ``` Uses the shell-like glob functionality to generate the list of strings `("-1,-1","-1,0","-1,1","0,-1","0,0","0,1","1,-1","1,0","1,1")`, discards strings that don't contain the character `"1"` (i.e. drop `"0,0"`), then splits the strings on comma to get the desired data structure. ## 41 characters: ``` @r=map[split x],grep/1/,glob"{-1,0,1}x"x2 ``` abuses barewords: the strings are `("-1x-1","-1x0"`, etc.`)` and the split is done on the letter `x` instead. [Answer] ## Fortran: ~~101~~ 96 Fortran supports [complex variables](http://en.wikipedia.org/wiki/Complex_number), so we just store the 8 values as a set of complex numbers and get ourselves a list of tuples. ``` complex x(8);x=reshape([(1,-1),(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1)],[8]);print*,x;end ``` Printing this to look nice might be a pain in the butt because printing the `real` and `aimag` [components](http://gcc.gnu.org/onlinedocs/gcc-3.4.5/g77/REAL_0028_0029-and-AIMAG_0028_0029-of-Complex.html) adds a lot of bytes. But we can deal with floats. --- Old answer: ``` complex x(8);k=1;do i=-1,1;do j=-1,1;if((j==0).and.(i==0))cycle;x(k)=cmplx(i,j);k=k+1;enddo;enddo;end ``` This abuses implicit typing (as usual). [Answer] # SQL 109 (that far) ``` create table a(x int);insert into a values(-1),(0),(1);select a.x,b.x y from a,a b where not(a.x=0 and b.x=0) ``` if you want to retest it, you can prepend `drop table if exists a;` ]
[Question] [ I read about circles somewhere, and just now learned about discs (*it's actually a pretty common concept*) and thought about codegolf. Your task is to randomize a point/several points on a [disc](https://en.wikipedia.org/wiki/Disk_(mathematics)) with the radius 1. **Rules:** * All points must have an equal probability to be generated * Floating point coordinates must be used; the minimum requirement is two decimals (e.g. the points `(0.12, -0.45)` or `(0.00, -1.00)` are valid) * You get -20 bytes if your program actually displays the bounding circle and the point(s) generated in it. Coordinates still has to be valid but not displayed, and the image generated has to be at least 201 by 201 pixels in size * You get -5 bytes if your program takes the number of points to be generated as input on stdin * If you decide not to plot the bounding circle and the point(s), your program has to output the point(s) generated on the format `(x, y)` or `(x,y)` on stdout * If you decide to take the number of generated points as input, but not to plot it - your program has to output all the randomized points on the format stated above with or without one space in between Shortest submission in bytes wins! [Answer] # CJam, ~~28~~ 27 bytes ``` PP+mr_mc\ms]1.mrmqf*"(,)".\ ``` This solution is not rejection-based. I'm generating the points in polar coordinates, but with a non-uniform distribution of the radii to achieve a uniform density of the points. [Test it here.](http://cjam.aditsu.net/#code=PP%2Bmr_mc%5Cms%5D1.mrmqf*'%2C*'(%5C')) ## Explanation ``` PP+ e# Push 2π. mr_ e# Get a random float between 0 and 2π, make a copy. mc\ e# Take the cosine of one copy and swap with the other. ms] e# Take the sine of the other copy and wrap them in an array. e# This gives us a uniform point on the unit circle. 1.mr e# Get a random float between 0 and 1. mq e# Take the square root. This is the random radius. f* e# Multiply x and y by this radius. "(,)".\ e# Put the resulting numbers in the required format. ``` Why does it work? Consider a narrow annulus of radius `r` and (small) width `dr`. The area is approximately `2π*r*dr` (if the annulus is narrow, the inner and outer circumference are almost identical, and the curvature can be ignored, such that the area can be treated as that of a rectangle with side lengths of the circumference and the width of the annulus). So the area increases linearly with the radius. This means that we also want a linear distribution of the random radii, in order to achieve a constant density (at twice the radius, there is twice as much area to fill, so we want twice as many points there). How do we generate a linear random distribution from 0 to 1? Let's look at the discrete case first. Say, we have a desired distribution of 4 values, like `{0.1, 0.4, 0.2, 0.3}` (i.e. we want `1` to be 4 times as common as `0`, and twice as common as `2`; we want `3` three times as common as `0`): [![enter image description here](https://i.stack.imgur.com/6etuX.png)](https://i.stack.imgur.com/6etuX.png) How can pick one of the four values with the desired distribution? We can stack them up, pick a uniformly random value between 0 and 1 on the y-axis and pick the segment at that point: [![enter image description here](https://i.stack.imgur.com/5Ukl9.png)](https://i.stack.imgur.com/5Ukl9.png) There's a different way to visualise this picking though. We could instead replace each value of the distribution with the accumulation of the values up to that point: [![enter image description here](https://i.stack.imgur.com/ddT1f.png)](https://i.stack.imgur.com/ddT1f.png) And now we treat the top line of this chart as a function `f(x) = y` and invert it to get a function `g(y) = f-1(y) = x`, which we can apply to a uniformly random value in `y ∈ [0,1]`: [![enter image description here](https://i.stack.imgur.com/s0Gig.png)](https://i.stack.imgur.com/s0Gig.png) Cool, so how can make use of this to generate a linear distribution of radii? This is the distribution we want: [![enter image description here](https://i.stack.imgur.com/x8LrN.png)](https://i.stack.imgur.com/x8LrN.png) The first step is to accumulate the values of the distribution. But the distribution is continuous, so instead of summing over all previous values, we take an integral from `0` to `r`. We can easily solve that analytically: `∫0r r dr = 1/2 r2`. However, we want this to be normalised, i.e. to multiply it by a constant such that this gives `1` for the maximum value of `r`, so what we really want is `r2`: [![enter image description here](https://i.stack.imgur.com/LKbz9.png)](https://i.stack.imgur.com/LKbz9.png) And finally, we invert this to get a function we can apply to a uniform value in `[0,1]`, which we can again do analytically: it's just `r = √y`, where `y` is the random value: [![enter image description here](https://i.stack.imgur.com/TTy35.png)](https://i.stack.imgur.com/TTy35.png) This is a fairly useful technique that can often be used to generate simple distributions exactly (it works for any distribution, but for complicated ones the last two steps may have to be solved numerically). However, I wouldn't use it in this particular case in production code, because the square root, sine and cosine are prohibitively expensive: using a rejection-based algorithm is on average much faster, because it only needs addition and multiplication. [Answer] # Mathematica, ~~68~~ 44 - 20 = 24 bytes *Many thanks for David Carraher for letting me know about `RandomPoint`, which saved 24 (!) bytes. Mathematica* does *have a built-in for everything.* ``` Graphics@{Circle[],Point@RandomPoint@Disk[]} ``` This plots the point and the bounding circle to qualify for the bonus: [![enter image description here](https://i.stack.imgur.com/y2XMt.png)](https://i.stack.imgur.com/y2XMt.png) The result is a vector image, so the size specification of 201x201 pixels doesn't really make sense, but by default it does render larger than that. [Answer] # CJam, ~~31~~ 26 bytes ``` {];'({2dmr(_}2*@mhi}g',\') ``` This works by repeatedly generating random points in a square of side length 2 and keeping the first that falls inside the unit disc. *Thanks to @MartinBüttner for golfing off 3 bytes!* Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B%5D%3B'(%7B2dmr(_%7D2*%40mhi%7Dg'%2C%5C')). ### How it works ``` { }g Do: ];'( Clear the stack and push a left parenthesis. { }2* Do twice: 2dmr Randomly select a Double between 0 and 2. (_ Subtract 1 and push a copy. @ Rotate the copy of the first on top of the stack. mh Compute the Euclidean norm of the vector consisting of the two topmost Doubles on the stack. i Cast to integer. If the result is non-zero, repeat the loop. ',\ Insert a comma between the Doubles. ') Push a right parenthesis. ``` [Answer] # [iKe](https://github.com/JohnEarnest/ok/tree/gh-pages/ike), ~~53~~ 51 bytes Nothing particularly special, but I suppose we ought to have at least one graphical solution: ``` ,(80+160*t@&{.5>%(x*x)+y*y}.+t:0N 2#-.5+?9999;cga;3) ``` ![plot](https://i.stack.imgur.com/6CEBb.png) Try it [in your browser](http://johnearnest.github.io/ok/ike/ike.html?gist=f309ab91181d04c82eeb). Edit: I can shave off two bytes by applying @MartinBüttner's approach for modifying the distribution of polar coordinates. I think it's also quite a bit more direct: ``` ,(80*1+(%?c){x*(cos y;sin y)}'6.282*?c:9999;cga;3) ``` [Answer] # Perl, 59 Bytes ``` while(($x=1-rand 2)**2+($y=1-rand 2)**2>1){};print"($x,$y)" ``` This is just a simple solution, generating points in a square and rejecting those too far away. My singular golfing trick is to include the assignments inside of the condition. Edit: In the process of golfing, I found an interesting way to print random points on a *circle*. ``` use Math::Trig;$_=rand 2*pi;print"(",sin,",",cos,")" ``` [Answer] # Octave, ~~24~~ 53 - 20 = 33 bytes ``` polar([0:2e-3:1,rand]*2*pi,[ones(1,501),rand^.5],'.') ``` Generates 501 equally-spaced theta values plus one random number and scales them all to [0..2π]. Then generates 501 1's for the radius of the circle, plus a random radius for the point and takes the square root to ensure uniform distribution over the disc. Then plots all the points as polar coordinates. [![enter image description here](https://i.stack.imgur.com/eKxEu.png)](https://i.stack.imgur.com/eKxEu.png) --- Here is a quick demonstration of the distribution (without the unit circle): ``` polar(2*pi*rand(99),rand(99).^.5,'.') ``` [![9801 Points](https://i.stack.imgur.com/ZiBqw.png)](https://i.stack.imgur.com/ZiBqw.png) [Answer] # Pyth, 26 - 5 = 21 bytes ``` VQp(sJ*@OZ2^.n1*yOZ.l_1)eJ ``` Takes the number of coordinates to generate on stdin, and outputs them on stdout like such: ``` (-0.5260190768964058, -0.43631187015380823)(-0.12127959509302746, -0.08556306418467638)(-0.26813756369750996, -0.4564539715526493) ``` Uses a strategy similar to @MartinBüttner, generating polar coordinates and radii, except it does it using complex exponentiation. [Answer] ## Octave / Matlab, ~~74~~ 64 bytes **Rejection method**, 64 bytes: ``` u=1;v=1;while u^2+v^2>1 u=rand;v=rand;end sprintf('(%f,%f)',u,v) ``` **Direct method**, 74 bytes (thanks to Martin Büttner for helping me correct two errors): ``` t=rand*2*pi;r=1-abs(1-sum(rand(2,1)));sprintf('(%f,%f)',r*cos(t),r*sin(t)) ``` [Answer] # R, ~~99~~ ~~95~~ 81-20 = ~~79~~ ~~75~~ 61 Bytes ``` symbols(0,0,1,i=F,asp=1,ylim=c(-1,1));points(complex(,,,runif(9),runif(9,-1)*pi)) ``` Use the complex number construction to build the x/y's from polar coordinates. Taking the input was a bit expensive and there is probably a better way to do this. The `ylim` ~~and `xlim`~~ is to ensure the entire circle is plotted and the `asp` ensures the points are shown under the circle symbol. Thanks to @jbaums and @flodel for the savings Try it [here](http://www.r-fiddle.org/#/fiddle?id=hD4mWHyQ&version=1) [Answer] # Processing /Java 141 bytes-20=121 the requirement for 201\*201 being the minimum size requires me to put in the `setup` method since Processing.org defaults to 200x200 :( ``` void setup(){noFill();size(201,201);}void draw(){float f=10,a=PI*2*random(),r=random();point(f+f*sin(a)*r,f+f*cos(a)*r);ellipse(f,f,f*2,f*2)} ``` [Answer] # QBasic, 138 bytes - 20 - 5 = 113 ``` INPUT n r=200 SCREEN 12 RANDOMIZE TIMER CIRCLE(r,r),r PAINT(r,r) FOR i=1TO n DO x=RND*r*2 y=RND*r*2 LOOP UNTIL POINT(x,y) PSET(x,y),1 NEXT ``` Takes user input and draws the disc and points. Tested on [QB64](http://qb64.net). [![](https://i.stack.imgur.com/B2WXd.gif)](https://i.stack.imgur.com/B2WXd.gif) This is a pretty basic "throw at the dartboard and keep what sticks" strategy. The catch is that "what sticks" is not determined mathematically but graphically: a white disc is plotted on a black background, and then randomly generated points are rejected until they are not black. The points themselves are drawn in blue (though it's hard to tell when they're single pixels--click on the image to enlarge). [Answer] # awk - 95 - 5 = 90 ``` { for(;$1--;printf"("(rand()<.5?x:-x)","(rand()<.5?y:-y)")") while(1<(x=rand())^2+(y=rand())^2); } ``` Since i wasn't quite sure about the rand()<.5 part, I did some distribution testing with this, using this script: ``` BEGIN{ srand() } { split("0 0 0 0", s) split("0 0 0 0", a) for(i=$1; i--; ) { while( 1 < r2 = ( x=rand() )^2 + ( y=rand() )^2 ); x = rand()<.5 ? x : -x y = rand()<.5 ? y : -y ++s[ x>=0 ? y>=0 ? 1 : 4 : y>=0 ? 2 : 3 ] ++a[ r2>.75 ? 1 : r2>.5 ? 2 : r2>.25 ? 3 : 4] } print "sector distribution:" for(i in s) print "sector " i ": " s[i]/$1 print "quarter area distribution:" for(i in a) print "ring " i ": " a[i]/$1 } ``` which for an input of 1e7 gives me this result, after I sipped once or twice at my coffee: ``` 1e7 sector distribution: sector 1: 0.250167 sector 2: 0.249921 sector 3: 0.249964 sector 4: 0.249948 quarter area distribution: ring 1: 0.24996 ring 2: 0.25002 ring 3: 0.250071 ring 4: 0.249949 ``` which I think is quite alright. A little explanation: After scribbling about for a while it turned out, that if you want to divide the disc into four rings with equal area, the radii where you would have to cut are sqrt(1/4), sqrt(1/2) and sqrt(3/4). Since the actual radius of the point I test would be sqrt( x^2 + y^2), I can skip the square rooting all together. The 1/4, 2/4, 3/4 "coincidence" might be related to what M. Buettner pointed out earlier. [Answer] # [HPPPL](http://www.hp-prime.de/en/category/6-downloads), 146 (171-20-5) bytes ``` EXPORT r(n)BEGIN LOCAL R,A,i,Q;RECT();Q:=118.;ARC_P(Q,Q,Q);FOR i FROM 1 TO n DO R:=√RANDOM(1.);A:=RANDOM(2*π);PIXON_P(G0,IP(Q+Q*R*COS(A)),IP(Q+Q*R*SIN(A)));END;FREEZE;END; ``` Example for 10000 points (including timing in seconds for the real device): [![Randomize points on a disc, timing](https://i.stack.imgur.com/Lk7fO.png)](https://i.stack.imgur.com/Lk7fO.png) The function itself is called by `r(n)`. The rest in the image above is only for timing purposes. Result (disc diameter is 236 pixels): [![enter image description here](https://i.stack.imgur.com/aKgAe.png)](https://i.stack.imgur.com/aKgAe.png) The version above does not store the point coordinates, so I wrote a version that takes two parameters `r(n,p)`. `n` is the number of points and `p=0` returns the points to the terminal, `p=1` plots the points and the disc), in case storing coordinates is mandatory. This version is 283 (308-20-5) bytes long: ``` EXPORT r(n,p)BEGIN LOCAL R,A,j,Q,x,y;Q:=118.0;CASE IF p==0 THEN print() END IF p==1 THEN RECT();ARC_P(Q,Q,Q) END END;FOR j FROM 1 TO n DO R:=√RANDOM(1.0);A:=RANDOM(2*π);x:=R*COS(A);y:=R*SIN(A);CASE IF p==0 THEN print("("+x+", "+y+")") END IF p==1 THEN PIXON_P(G0,IP(Q+Q*x),IP(Q+Q*y)) END END;END;FREEZE;END; ``` The ungolfed version: ``` EXPORT r(n,p) BEGIN LOCAL R,A,j,Q,x,y; Q:=118.0; CASE IF p==0 THEN print() END IF p==1 THEN RECT();ARC_P(Q,Q,Q) END END; FOR j FROM 1 TO n DO R:=√RANDOM(1.0); A:=RANDOM(2*π); x:=R*COS(A); y:=R*SIN(A); CASE IF p==0 THEN print("("+x+", "+y+")") END IF p==1 THEN PIXON_P(G0,IP(Q+Q*x),IP(Q+Q*y)) END END; END; FREEZE; END; ``` Terminal output for `r(10,0)`: [![Randomize points on a disc terminal output](https://i.stack.imgur.com/ee0lr.png)](https://i.stack.imgur.com/ee0lr.png) `r(10,1)` shows the disc with the points, like shown above. [Answer] # JavaScript, 75 bytes Rejection-based: ``` do x=(r=()=>4*Math.random()-2)(),y=r() while(x*x+y*y>1) alert(`(${[x,y]})`) ``` Direct method (80 bytes): ``` alert(`(${[(z=(m=Math).sqrt((r=m.random)()))*m.sin(p=m.PI*2*r()),z*m.cos(p)]})`) ``` [Answer] # Python, 135 130 bytes ``` from random import* def r():return uniform(-1,1) p=[] while not p: x,y=r(),r() if x**2+y**2<=1:p=x,y print'(%.2f, %2f)'%p ``` Removed the `**0.5` thanks to [@jimmy23013](https://codegolf.stackexchange.com/users/25180/jimmy23013)’s suggestion (because it is a unit circle, I am now checking whether the distance squared between (x, y) and (0, 0) is equal to 12. This is the same thing). This also freed me to remove the parentheses. [Answer] # Python 3.8 (pre-release), ~~82~~ ~~79~~ 78 Bytes ``` from random import* r=random while(x:=r()*2-1)*x+(y:=r()*2-1)*y>1:1 print(x,y) ``` # -3 from TheThonnu by murdering whitespace and exponents. # -1 from TheThonnu by showing that you can change function names by variable assignment. ### [Verify that it actually works by running on TIO.](https://tio.run/##K6gsycjPM7YoKPr/P60oP1ehKDEvBUhl5hbkF5VocRXZQgS4yjMyc1I1KqxsizQ0tYx0DTW1KrQ1KpG4lXaGVoZcBUWZeSUaFTqVmv//AwA) [![Walrus returns and assigns at the same time.](https://i.stack.imgur.com/ppb2e.png)](https://i.stack.imgur.com/ppb2e.png) ## The walrus likes to assign variables and return their value at the same time, and I don't understand why... [Answer] # Desmos, 52 - 20 = 32 Bytes ``` r=1 a=1 b=1 (acosb,asinb) a->random(),b->2πrandom() ``` I’ve never golfed in Desmos before. Click the bottom action to generate a random point. [Try prettified version online.](https://www.desmos.com/calculator/goukix9jcz) If anyone knows a shorter way to graph a polar coordinate point, please tell me, since I’m unaware of any builtin to graph a point in polar coordinates. [Answer] # [Befunge-with-graphics](https://esolangs.org/wiki/Befunge-with-graphics), ~~224~~ 212 bytes (237 before deductions) Takes input from stdin, draws image to the screen. ``` >99*3*:s000fc88*3*::f765+jv v1j0-10::*:+29p02j50p01j50< >0g29+:*-:*20g92+:*-:*+v v:-1xg02g01_v#!`*:*:+92< >!#v_ >94+2*1j v 0vu< 6>z:1-#v_@ #^$$$$$< >$$99*3*%r 0 |!:-1\<>0>~:52*- #v_$r \ > v* ^+**25\-"0"< >#v?v 4 0123+ >>>>^ ``` ## Explanation Random coordinates are generated using the `?` operator, to build a large random number. Each of the 4 directions the `?` operator could go adds a new digit to a base-4 number which is then eventually modulo'd by the screen width to get a random coordinate on the screen. (bottom-most bit) The distance from the centre of the circle is then calculated, and if it's outside the circle it generates a new pair of coordinates. Else, it draws a pixel and repeats, decrementing a counter. (top block of stuff) Finally, the screen is updated and events are handled. (bit with all the `$$$$`s) Circle with 10 points (to verify there are actually 10): [![10 points](https://i.stack.imgur.com/5k3e3.png)](https://i.stack.imgur.com/5k3e3.png) Circle with 10000 points: [![10000 points](https://i.stack.imgur.com/JHGlX.png)](https://i.stack.imgur.com/JHGlX.png) I'm not certain this counts because of many factors * Befunge-with-graphics is my "made up" language, but it predates my knowledge of this question. * Since befunge doesn't support floating point, all coordinates are in pixels and may not have the required precision. The image, however, is greater than 201x201 pixels in size. * Technically no points can appear directly on the edge of the circle. ]
[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/19214/edit) ![BBC Micro Owl Logo](https://i.stack.imgur.com/RyZuW.png) Can you render out a version of the BBC Micro Owl logo as per above from code? Rules: * You can use any programming language you like. * Output can be text or graphic. * Circles don't have to overlap. Winner: * The answer with the most upvotes wins. Kudos for anyone that attempts this in BBC basic. You can read about the BBC Micro [here](http://en.wikipedia.org/wiki/BBC_Micro) [Answer] # BBC BASIC I tried using trig functions to draw proper circles, but that was painfully slow. Came up with this instead: ``` 10 MODE 1 20 GCOL 0,1 : VDU 19,1,3,0,0,0 30 FOR Y%=0 TO 20 40 READ N% : P%=65536 50 FOR X%=0 TO 16 60 IF (N% AND P%)=0 THEN GOTO 160 70 X0% = X%*32+384 : Y0% = 872-Y%*32 80 FOR DX%=-16 TO 16 STEP 8 90 FOR DY%=-8 TO 8 STEP 8 100 PLOT 69,X0%+DX%,Y0%+DY% 110 NEXT DY% : NEXT DX% 120 FOR DX%=-8 TO 8 STEP 8 130 FOR DY%=-16 TO 16 STEP 32 140 PLOT 69,X0%+DX%,Y0%+DY% 150 NEXT DY% : NEXT DX% 160 P%=P%/2 170 NEXT : NEXT 1000 DATA 87381,33410,69905,10280 1010 DATA 69649,33410,82181,40968 1020 DATA 87377,43520,87297,43520 1030 DATA 21761,10880,5441,2720 1040 DATA 1361,552,1093,43682,1 ``` Here's the output: ![Animated GIF of the BBC Micro Owl Logo](https://i.stack.imgur.com/Y9yg2.gif) [Answer] ### GolfScript ``` "!C-DD[5v`>U8G`J2zX['b#L*\\q>FQp "{32-}%96base 2base{" *"2/=}%18/{""*1>17/~n@n}/ ``` The code prints an ascii art version of the logo (run [here](http://golfscript.apphb.com/?c=IiFDLUREWzV2YD5VOEdgSjJ6WFsnYiNMKlxccT5GUXAgInszMi19JTk2YmFzZSAyYmFzZXsiICAgKiIyLz19JTE4L3siIioxPjE3L35uQG59Lw%3D%3D&run=true)). ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` [Answer] # Mathematica Nothing but grunt work. ``` w = 20; h = 25; r = .7; r2 = .2; t = Table; d = Disk; owl = Graphics[{Polygon[{{0, 0}, {w, 0}, {w, h}, {0, h}}], ColorData[57, 4], t[d[{k, 22}, r], {k, 2, 19, 2}], t[d[{18, k}, r], {k, 2, 21, 2}], t[d[{k, #}, r], {k, #2}] & @@@ {{21, {3, 9, 10, 11, 17}}, {20, {2, 6, 10, 14, 18}}, {19, {5, 6, 7, 13, 14, 15}}, {18, {6, 9, 11, 14}}, {17, {10, 17}, {16, {16}}, {15, {15}}, {14, {8, 10, 12, 14}}, {13, {9}}, {12, {9}}}}, t[d[{# - k, k}, r], #2] & @@@ {{20, {k, 18, 3, -1}}, {19, {k, 16, 6, -1}}, {18, {k, 16, 5, -1}}, {17, {k, 14, 7, -1}}, {16, {k, 14, 6, -1}}, {14, {k, 11, 5, -1}}, {14, {k, 12, 5, -1}}}, t[d[{k, 4}, r], {k, {8, 12}}], t[d[{k, 3}, r], {k, 3, 13, 2}], d[{8, 13}, r], Black, d[{10, 21}, r2], d[{8, 13}, r2], d[{9, 12}, r2], t[d[{19 - k, k}, r2], {k, 16, 6, -1}], t[d[{17 - k, k}, r2], {k, 14, 7, -1}], t[d[{15 - k, k}, r2], {k, 12, 6, -1}], t[d[{k, 19}, r2], {k, {6, 14}}]}, ImageSize -> 220] ``` ![owl](https://i.stack.imgur.com/d64AF.png) [Answer] ### R ``` image(t(matrix(as.integer(sapply(c(1397760,567810,1070336,141954,1381696,133794, 1054036,559786,1332560,557218,1052756,131114, 1380368,139272,1064964,557058,1398101), intToBits)[1:21,]),nr=21)),ax=F) ``` Results in: ![enter image description here](https://i.stack.imgur.com/RuiGO.png) Basically the idea is to take the base-2 representation of the 17 numbers (1397760, 567810, 1070336, 141954, 1381696, 133794, 1054036, 559786, 1332560, 557218, 1052756, 131114, 1380368, 139272, 1064964, 557058 and 1398101), make it into a 21x17 matrix of 1 and 0s and plot the matrix as is. [Answer] # Pov-Ray ``` background{color<.14,.01,.01>} camera{orthographic location z*-2 up y*24 right x*20} #macro s(X,Y)sphere{<X,Y,0>,1.07,2.6}#end #declare b=array[17]{1397760,567810,1070336,141954,1381696,133794,1054036, 559786,1332560,557218,1052756,131114,1380368,139272,1064964,557058,1398101} blob{threshold 0.9 #for(j,0,16,1)#declare V=b[j];#for(i,0,28,1) #if(mod(V,2))s(j-8,i-10)#end #declare V=floor(V/2);#end #end pigment{color<1,1,.8>}finish{ambient 1}} ``` 'compile' with `povray +Ibbc.pov -Obbc.png +A0.1 +R9 -W240 -H285` ![enter image description here](https://i.stack.imgur.com/Ve2VB.png) [Answer] ## Bash Since you didn't specify no external resources... ``` curl -s http://codegolf.stackexchange.com/questions/19214/render-a-version-of-the-bbc-micro-owl-logo | grep '* * *' | sed -n '/code>\*/,/<pre>/p' | sed '$d' | sed 's/<pre><code>//' ``` Howard - stole your Ascii art, thanks. **Or** after I uploaded it [here](http://textuploader.com/1ojd) - ``` curl -s http://textuploader.com/1ojd | sed -n '/<code/,/<\/code>/p' | sed 's/<[^>]\+>//g' ``` [Answer] # BBC Basic, random colours, golfed! 149 characters. I'm not that big on golfing (I prefer the code challenges) but I liked the ridiculousness of golfing in BBC basic. BBC emulator at <http://www.bbcbasic.co.uk/>. Runs in screen mode 6 at the command line. FORK=6TO185S=K MOD9=5VDU-32\*(K MOD18=15),17,128+RND(6)\*(ASCMID$("?OSUuLEMSS^H?=A\_W",K/6,1)/2^(K MOD6)AND1),32,17,128,32,-13\*S,-10\*S:NEXT ![enter image description here](https://i.stack.imgur.com/2aoJ0.png) Explanation (ungolfed version) No IF statements, because the rest of the line would only be executed if the IF was true (so to ensure the NEXT was reached I would have to do a program with line numbers.) Therefore I made a lot of use of ASC(null character)=0 to control output. Also, I had to cut off the pixel at the bottom right corner to fit the whole command line on the screen after printing (and that saved 2 characters. I love how BBC basic can recognise an identifier after FOR, even with no white space. FORE, FORD, FORK, FORM, FORS, FORT :-) ``` FOR K=6 TO 185 REM Set S to true(-1) if K mod 9 = 5, otherwise set S to false(0) S = K MOD 9=5 REM If K mod 18 = 15, send asc(space)=32 to the VDU controller,otherwise send 0. REM This causes staggering every 2 lines. VDU-32*(K MOD18=15) REM Vdu 17 for colour. foreground colours start at 0, background colours at 128. REM Rnd(6) to choose a bright color. Multiply by the horrible expression. REM The horrible expression evaluates to 1 if the pixel is to be printed, 0 if not. REM Picture data is stored in base 64 in the string. REM MID$ extracts the characters in order. REM The FOR loop starts at K=6 so that this will work properly. REM Extracted character SHR ((K mod 6)) AND 1 to decide to REM colour pixel or not. BBC basic does not have SHR operator. REM so we divide by 2^(K mod 6) instead. VDU 17,128+RND(6)* (ASC(MID$( "?OSUuLEMSS^H?=A_<A^tC|dGxEMh>W" ,K/6,1))/2^(K MOD 6)AND 1) REM Print a space in the new background colour VDU 32 REM Change background colour back to black VDU 17,128 REM Print another space VDU 32 REM If S is true (-1) print a carriage return and linefeed. otherwise two 0's VDU -13*S,-10*S NEXT ``` [Answer] ## C ASCII output. ``` x[]={256,191,424,104,376,60,316,30,286,15,287,15,383,67,403,153,325,102,341,153,511};i=20;mai n(){for(;i>=0;i--){i&1&&putchar(32);while(x[i]){putchar(x[i]&1?42:32);x[i]>>=1;putchar(32);}pu tchar(10);}} ``` Code output: ``` * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ``` [Answer] # JavaScript - 326 307 285 characters (ASCII) ``` a=[1716886015,1133746501,253693823,1010572830,3215485048,0];s="";with(Math) for(y=0;44>y;y++,s+="\n")for(x=0;90>x;x++,s+="#8*+=:-. "[min(floor(d),8)]) for(j=d=0;22>j;j++)for(i=0;9>i;i++)1==((8==i?j+1:a[floor(j/4)]>>i+j%4*8)&1) &&(d+=50/pow(pow(x-10*(i+j%2/2)-4,2)+pow(2*y-4*j-4,2),1.5));s; ``` Probably not the shortest code. I tried to be as close as possible to the original logo, using only ASCII. To execute : copy paste to javascript console (eg: chrome or firefox). Note : the script might take a little time to run so if nothing come just after pressing enter, be a little patient. [Answer] # CoffeeScript Code isn't golfed. It uses some [metaballs](http://en.wikipedia.org/wiki/Metaballs)-ish algorithm to simulate "stickyness" of the circles. ASCII owl was shamelessly stolen from other answers :) ``` canvas = document.createElement 'canvas' canvas.style.backgroundColor = '#240202' canvas.style.transform = 'scale(0.5) translate(-480px,-570px)' W = canvas.width = 960 H = canvas.height = 1140 D = 50 R = D / 2 ctx = canvas.getContext '2d' imageData = ctx.getImageData 0, 0, W, H data = imageData.data owl = ''' \ * * * * * * * * * \ * * * * \ * * * * * \ * * * * \ * * * * \ * * * * \ * * * * * \ * * * \ * * * * * * * * \ * * * * \ * * * * * * \ * * * * \ * * * * * \ * * * * \ * * * * * \ * * * * \ * * * * * \ * * * \ * * * * \ * * * * * * * \ * '''.split '\n' insideDot = (x, y) -> w = 0 for du in [-1..1] then for dv in [-1..1] u = x // D + du v = y // D + dv continue unless owl[v]?[u] is '*' dx = x - (u * D + R) dy = y - (v * D + R) d = dx * dx + dy * dy w += 1 / (d * d) return yes if w > 0.0000008 no for y in [0...H] then for x in [0...W] when insideDot x, y i = (y * W + x) * 4 data[i] = data[i+1] = data[i+3] = 255 data[i+2] = 214 ctx.putImageData imageData, 0, 0 document.body.appendChild canvas ``` Watch it [destroy the coffeescript.org documentation](http://coffeescript.org/#try:canvas%20%3D%20document.createElement%20%27canvas%27%0Acanvas.style.backgroundColor%20%3D%20%27%23240202%27%0Acanvas.style.transform%20%3D%20%27scale%280.5%29%20translate%28-480px%2C-570px%29%27%0AW%20%3D%20canvas.width%20%3D%20960%0AH%20%3D%20canvas.height%20%3D%201140%0AD%20%3D%2050%0AR%20%3D%20D%20%2F%202%0Actx%20%3D%20canvas.getContext%20%272d%27%0AimageData%20%3D%20ctx.getImageData%200%2C%200%2C%20W%2C%20H%0Adata%20%3D%20imageData.data%0Aowl%20%3D%20%27%27%27%0A%0A%5c%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%0A%5c%20%20%2a%20%20%20%20%20%2a%20%2a%20%20%20%20%20%2a%0A%5c%20%2a%20%20%20%2a%20%20%20%2a%20%20%20%2a%20%20%20%2a%0A%5c%20%20%20%20%2a%20%2a%20%20%20%20%20%2a%20%2a%0A%5c%20%2a%20%20%20%2a%20%20%20%20%20%20%20%2a%20%20%20%2a%0A%5c%20%20%2a%20%20%20%20%20%2a%20%2a%20%20%20%20%20%2a%0A%5c%20%2a%20%2a%20%20%20%20%20%2a%20%20%20%20%20%2a%20%2a%0A%5c%20%20%2a%20%2a%20%20%20%20%20%20%20%20%20%2a%0A%5c%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%20%20%2a%0A%5c%20%20%2a%20%2a%20%2a%20%2a%0A%5c%20%2a%20%2a%20%2a%20%2a%20%2a%20%20%20%20%20%20%20%2a%0A%5c%20%20%2a%20%2a%20%2a%20%2a%0A%5c%20%20%20%2a%20%2a%20%2a%20%2a%20%20%20%20%20%20%20%2a%0A%5c%20%20%20%20%2a%20%2a%20%2a%20%2a%0A%5c%20%20%20%20%20%2a%20%2a%20%2a%20%2a%20%20%20%20%20%2a%0A%5c%20%20%20%20%20%20%2a%20%2a%20%2a%20%2a%0A%5c%20%20%20%20%20%20%20%2a%20%2a%20%2a%20%2a%20%20%20%2a%0A%5c%20%20%20%20%20%20%20%20%2a%20%20%20%2a%20%2a%0A%5c%20%20%20%20%20%20%20%2a%20%20%20%2a%20%20%20%2a%20%2a%0A%5c%20%20%2a%20%2a%20%2a%20%2a%20%2a%20%2a%20%20%20%2a%0A%5c%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2a%0A%27%27%27.split%20%27%5cn%27%0A%0AinsideDot%20%3D%20%28x%2C%20y%29%20-%3E%0A%20%20w%20%3D%200%0A%20%20for%20du%20in%20%5b-1..1%5d%20then%20for%20dv%20in%20%5b-1..1%5d%0A%20%20%20%20u%20%3D%20x%20%2F%2F%20D%20%2B%20du%0A%20%20%20%20v%20%3D%20y%20%2F%2F%20D%20%2B%20dv%0A%20%20%20%20continue%20unless%20owl%5bv%5d%3F%5bu%5d%20is%20%27%2a%27%0A%20%20%20%20dx%20%3D%20x%20-%20%28u%20%2a%20D%20%2B%20R%29%0A%20%20%20%20dy%20%3D%20y%20-%20%28v%20%2a%20D%20%2B%20R%29%0A%20%20%20%20d%20%3D%20dx%20%2a%20dx%20%2B%20dy%20%2a%20dy%0A%20%20%20%20w%20%2B%3D%201%20%2F%20%28d%20%2a%20d%29%0A%20%20%20%20return%20yes%20if%20w%20%3E%200.0000008%0A%20%20no%0A%0Afor%20y%20in%20%5b0...H%5d%20then%20for%20x%20in%20%5b0...W%5d%20when%20insideDot%20x%2C%20y%0A%20%20i%20%3D%20%28y%20%2a%20W%20%2B%20x%29%20%2a%204%0A%20%20data%5bi%5d%20%3D%20data%5bi%2B1%5d%20%3D%20data%5bi%2B3%5d%20%3D%20255%0A%20%20data%5bi%2B2%5d%20%3D%20214%0A%0Actx.putImageData%20imageData%2C%200%2C%200%0A%0Acontainer%20%3D%20document.querySelector%20%27.container%27%0Acontainer.textContent%20%3D%20%27%27%0Acontainer.appendChild%20canvas%0Adocument.querySelector%28%27.navigation.active%27%29.classList.remove%20%27active%27) (hit Run): ![OwlScript](https://i.stack.imgur.com/IaIJt.png) [Answer] **BBC Basic+GXR** Very late to this but: the 'bbcmicrobot' account on twitter which runs progs<280 chars or so added the Acorn GXR ROM, allowing drawing circles and ellipses. I thought, what could I draw with a couple of circles? And this came to me. It's based in part on the answer by @Level River Street, tho I've used abbreviated basic commands, used bit testing instead of SHR and changed the bit representation: ``` 2MO.2:P."HOW TO DRAW AN OWL":MOV.200,700:PL.&91,120,0:MOV.250,450:PL.0,-200,0:PL.&C1,155,250:V.29,640;130; 5F.G=0TO188:Z=(G MOD18)>8:X=G MOD9*2-Z:Y=G DIV18*2-Z 6IFASC(MID$("@|WhFMxeG|tC^|A_|A?]HSNSEuLUMS?G",(G+6)DIV6,1))AND2^(G MOD6) MOV.X*36,Y*36:PL.&99,24,0 8N.G ``` [![screenshot of bot rendered code](https://i.stack.imgur.com/WvEnO.png)](https://i.stack.imgur.com/WvEnO.png) My original tweet is [here](https://twitter.com/bazzargh/status/1229933643281453056) [Answer] **PHP** Building upon the ascii art versions of the logo submitted previously and using this as the array to render a graphical version using the GD library. ``` $circleWidth = 34; $circleHeight = 34; $movement = 24; $canvasWidth = 480; $canvasHeight = 570; $image = imagecreatetruecolor($canvasWidth, $canvasHeight); $backgroundColour = imagecolorallocate($image, 36, 2, 2); ImageFillToBorder($image, 0, 0, $backgroundColour, $backgroundColour); $circleColour = imagecolorallocate($image, 255, 255, 214); $coordinates =' * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '; $coordinates = str_split($coordinates); $coordinateX = $movement; $coordinatY = $movement; $i=1; foreach ($coordinates as $coordinate) { if ($i < 19) { if ($coordinate == '*') { ImageFilledEllipse($image, $coordinateX, $coordinatY, $circleWidth, $circleHeight, $circleColour); } $coordinateX = $coordinateX + $movement; $i++; } else { $i=1; $coordinateX = $movement; $coordinatY = $coordinatY + $movement; } } header("Content-type: image/png"); imagepng($image); imagedestroy($image); ``` Results in: ![BBC Owl logo from PHP](https://i.stack.imgur.com/7cLQF.png) ]
[Question] [ May this challenge serve as ([another](https://codegolf.stackexchange.com/q/175873/70347)) tribute to Stan Lee, who passed away aged 95. Stan Lee has left us an invaluable legacy and a peculiar catch word: *Excelsior*. So here's a small challenge based on what he said [it was its meaning](https://twitter.com/TheRealStanLee/status/2131837090529280): > > Finally, what does “Excelsior” mean? “Upward and onward to greater glory!” That’s what I wish you whenever I finish tweeting! Excelsior! > > > ### Challenge Given a series of non-negative integers, output a line with `Excelsior!` every time an integer is greater than the previous one. ### Rules * Input will be an array of non-negative integers. * Output will consist of lines with the word `Excelsior` (case does matter) followed by as many `!` as the length of the current run of increasingly greater numbers. You can also return an array of strings. * Input and output formats are flexible according to the site rules, so feel free to adapt them to your language formats. You can also add spaces at the end of the lines, or even extra new lines after or before the text if you need. ### Examples ``` Input Output ----------------------------------- [3,2,1,0,5] Excelsior! // Excelsior because 5 > 0 [1,2,3,4,5] Excelsior! // Excelsior because 2 > 1 Excelsior!! // Excelsior because 3 > 2 (run length: 2) Excelsior!!! // Excelsior because 4 > 3 (run length: 3) Excelsior!!!! // Excelsior because 5 > 4 (run length: 4) [] <Nothing> [42] <Nothing> [1,2,1,3,4,1,5] Excelsior! // Excelsior because 2 > 1 Excelsior! // Excelsior because 3 > 1 Excelsior!! // Excelsior because 4 > 3 (run length: 2) Excelsior! // Excelsior because 5 > 1 [3,3,3,3,4,3] Excelsior! // Excelsior because 4 > 3 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win! [Answer] # JavaScript (ES6), ~~58~~ 54 bytes ``` a=>a.map(c=>a<(a=c)?`Excelsior${s+='!'} `:s='').join`` ``` [Try it online!](https://tio.run/##jc@xCsIwEAbg3aeIKKShsZg2dRCjk2/gpoWGmEpLTUpTRBCfPcYKQQerd8sN93H/VfzCjWjLppspfZS2YJazNY/OvAmEG1YBZwJt8u1VyNqUup3eTMjgGN5H@dIwCFFU6VLluRVaGV3LqNanAO6k6YDgRoIJOSgIQlAE@wTHmOA5TjPgCqHRNxJ7QhxJMP1NEk/6TV8DhHpC4@w/kn4EI3004sINkMXb@6@mOMmeV@wD "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array, also used to store the previous value a.map(c => // for each value c in a[]: a < // compare the previous value (a = c) // with the current one; update a to c // this test is always falsy on the 1st iteration ? // if a is less than c: `Excelsior${s += '!'}\n` // add a '!' to s and yield 'Excelsior' + s + linefeed : // else: s = '' // reset s to an empty string and yield an empty string ).join`` // end of map(); join everything ``` ### Why re-using a[ ] to store the previous value is safe There are three possible cases: * If \$a[\text{ }]\$ is empty, the callback function of `.map()` is not invoked at all and we just get an empty array, yielding an empty string. * If \$a[\text{ }]\$ contains exactly one element \$x\$, it is coerced to that element during the first (and unique) test `a < (a = c)`. So, we're testing \$x < x\$, which is falsy. We get an array containing an empty string, yielding again an empty string. * If \$a[\text{ }]\$ contains several elements, it is coerced to `NaN` during the first test `a < (a = c)`. Therefore, the result is falsy and what's executed is the initialization of \$s\$ to an empty string -- which is what we want. The first meaningful comparison occurs at the 2nd iteration. [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ ~~83~~ ~~81~~ ~~70~~ 68 bytes ``` a=n='' for b in input(): n+='!';n*=a<b;a=b if n:print'Excelsior'+n ``` [Try it online!](https://tio.run/##LYy9DoIwFEb3PkVlqcId7I8OYCdl9gEIA5ASmphLU2uCT19rNd8ZTs7wuXdYVhTxer@1uiiKOGjUjJF59XSkFhPuFfaHmlCsNNuxBks9XMZm0COhdqZYO28xsHabzONpV88qjDmRdEfMZib6PS/PsZMggMMRTj3peHIJKntCiX/jufLcJfymQPYf "Python 2 – Try It Online") -2 bytes, thanks to ASCII-only [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ü‹γvyOE.•1Š¥èò²•™N'!׫, ``` -2 bytes thanks to *@Kroppeb*. [Try it online](https://tio.run/##yy9OTMpM/f//0FKDRw27zm0uq/R31XvUsMjw6IJDSw@vOLzp0CYg71HLIj91xcPTD63W@f8/2lDHSMdQx1jHBEia6pjrGBnoGJkC@YbmsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WqVP5/9BSg0cNu85tLqv0d9V71LDI8OiCQ0sPrzi86dAmIO9RyyI/dcXD0w@t1vlfW3tom/3/6GhjHSMdQx0DHdNYnWhDINtYxwTMBiITI6iYIVjUECxurAOBJjrG6LI65jpGBjpGpkC@oXlsLAA). **Explanation:** ``` ü # Loop over the (implicit) input as pairs ‹ # And check for each pair [a,b] if a<b is truthy # i.e. [1,2,1,3,4,1,5,7,20,25,3,17] # → [1,0,1,1,0,1,1,1,1,0,1] γ # Split it into chunks of equal elements # i.e. [1,0,1,1,0,1,1,1,1,0,1] # → [[1],[0],[1,1],[0],[1,1,1,1],[0],[1]] vy # Foreach `y` over them O # Take the sum of that inner list # i.e. [1,1,1,1] → 4 # i.e. [0] → 0 E # Inner loop `N` in the range [1, length]: .•1Š¥èò²• # Push string "excelsior" ™ # Titlecase it: "Excelsior" N'!׫ '# Append `N` amount of "!" # i.e. N=3 → "Excelsior!!!" , # Output with a trailing newline ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•1Š¥èò²•` is `"excelsior"`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~60 58~~ 57 bytes *-1 byte thanks to nwellnhof* ``` {"Excelsior"X~("!"Xx grep +*,[\[&(-+^*×*)]] .skip Z>$_)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rJtSI5Nac4M79IKaJOQ0lRKaJCIb0otUBBW0snOiZaTUNXO07r8HQtzdhYBb3i7MwChSg7lXjN2v/FiZUKaRrRxjpGOoY6BjqmsZrWXFAxQ6CYsY4JihgS08QITa0hWLUhinpjHQg00TEGiv4HAA "Perl 6 – Try It Online") Anonymous code block that returns a list of Excelsiors! [Answer] # [Java-8](https://docs.oracle.com/javase/8/docs/api/) 118 113 Bytes ``` n->{String e="";for(int i=0;i<n.length-1;)System.out.print(""==(n[i+1]>n[i++]?e+="!":(e=""))?e:"Excelsior"+e+"\n");} ``` *Easy to read :* ``` private static void lee(int num[]) { String exclamation = ""; for (int i = 0; i < num.length - 1;) { exclamation = num[i + 1] > num[i++] ? exclamation += "!" : ""; System.out.print("".equals(exclamation) ? "" : "Excelsior" + exclamation + "\n"); } } ``` [Answer] # [R](https://www.r-project.org/), 86 bytes Half of this answer is @Giuseppe's. RIP Stan Lee. ``` function(a)for(i in diff(a))"if"(i>0,cat("Excelsior",rep("!",F<-F+1)," ",sep=""),F<-0) ``` [Try it online!](https://tio.run/##bcxBDoIwEIXhPafA2TATh6SluBLdySnckNqaSUxLCibevgJLZfnen3wp@7Krs38HO0sMOJCPCaWUUD7E@2UTiAeUq2I7zAi3j3WvSWICTm5EOAD3Xd0fNTEUwJMbLwC0foqyR4uGG9as@ER0XoXqHioq1qKXYrj9KxJm93QJ1c/fNnuC3gy94xs2WzNE@Qs "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ 19 bytes ``` ü‹0¡€ƶ˜ε'!×”¸Îsiorÿ ``` [Try it online!](https://tio.run/##ATsAxP9vc2FiaWX//8O84oC5MMKh4oKsxrbLnM61JyHDl@KAncK4w45zaW9yw7///1sxLDIsMSwzLDQsMSw1XQ "05AB1E – Try It Online") **Explanation** ``` ü‹ # pair-wise comparison, less-than 0¡ # split at zeroes €ƶ # lift each, multiplying by its 1-based index ˜ # flatten ε # apply to each '!× # repeat "!" that many times ÿ # and interpolate it at the end of ”¸Îsior # the compressed word "Excel" followed by the string "sior" ``` [Answer] # C (gcc/clang), ~~106~~ ~~99~~ 97 bytes ``` f(a,n)int*a;{int r=0,s[n];for(memset(s,33,n);n-->1;)r*=*a<*++a&&printf("Excelsior%.*s\n",++r,s);} ``` Thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner) for golfing 2 bytes. Try it online [here](https://tio.run/##jZHRToMwFIavx1McSVwKHBylgBcdu/PWF5i7aBAmiZSlRWNCeHbsaJwum2J70dOT/t/fP6cI90UxjhURKL1adr7gvTlA5RHqrdzxqlWkKRtddkQjY@YVl2G4odxTfu6LtR8EYrk8KCOqiPvwUZSvum7V7Z2vn6SLQaBQe3wYj9BG1JK8t/WzB73jLI4tQbc7yKFnGCPFCNOBw2oFJ86NszB/owipx43k8NZp4oan5U7dCRRbEDUghskl6Ed5Vp9frF/8Dz9m/azN@rHtXmq530xyhhDNyRMrT@JrgASBzgHS77x0Skz/zPxL/MkuRbifs8u@5mR3guzqpDKEzIiG8RM). Ungolfed: ``` f(a, n) // function taking a pointer to the first integer and the length of the array int *a; { // a is of type pointer to int, n is of type int int r = 0, // length of the current run i = 0, // loop variable s[n]; // buffer for exclamation marks; we will never need more than n-1 of those (we are declaring an array of int, but really we will treat it as an array of char) for(memset(s, 33, n); // fill the buffer with n exclamation marks (ASCII code 33) n -- > 1; ) // loop over the array r *= *a < *(++ a) // if the current element is less than the next: && printf("Excelsior%.*s\n", // print (on their own line) "Excelsior", followed by ... ++ r, // ... r (incremented) of the ... s) // ... n exclamation marks in the buffer s ; // else r is reset to 0 } ``` [Answer] # Japt `-R`, ~~25~~ 22 bytes ``` ò¨ ËÅ£`Ex­lÐâ`ú'!Y+A c ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8qggy8WjYEV4rWzQ4mD6JyFZK0EKYw==&input=WzMsMywzLDMsNCwzXQotUg==) 3 bytes saved thanks to [Kamil](https://codegolf.stackexchange.com/users/71434/kamil-drakari) ``` ò¨ :Partition at items that are greater than or equal to the previous item Ë :Map Å : Slice off the first element £ : Map each element at 0-based index Y `Ex­lÐâ` : Compressed string "Excelsior" ú'! : Right pad with exclamation marks Y+A : To length Y+10 c :Flatten :Implicitly join with newlines & output ``` [Answer] # Common Lisp, 111 bytes ``` (setq i 0)(loop for(a b)on(read)do(incf i(if(and b(> b a))1(- i)))(format(> i 0)"Excelsior~v@{~a~:*~}~%"i #\!)) ``` [Try it online!](https://tio.run/##FY1LCgIxEAWv8hwRugXB@Nm4EDfewk2@0BCTmWQQQczVx7h5i4KqZ6PUcVmo@nmCYM8Ucx4RciENwzlR8dqxyyTJBghJIJ0cDF1hoJkV7SDMTF156rnjf2W4v62PVXJpr9un6XbZtm/bDIL1Y8XcDxUOUDji1PfMPw) [Answer] # Java 8, 106 bytes ``` n->{String s="",z=s;for(int i=0;i<n.length-1;)z+=n[i++]<n[i]?"Excelsior"+(s+="!")+"\n":(s="")+s;return z;} ``` [Try it online!](https://tio.run/##fVHLbsIwELzzFVufEsUYQuilJq166LFcONIc3GBS07CJbIcWUL49dR5SVQGVJVv27MzOeHfiIMZFKXG3@WzUviy0BWOFVSnsHMRygRlbHY2Ve1ZUlo/SXBgDr0LheQSg0Eq9FamEZXsFWFmtMIPUc8g6AfS5e65HbhtUl4AQQ4Pjx/NQa2JC6Ck2fFvolgYqnnK1QJZLzOzHOOT@KYhxrYIgWbgjeSIv36nMjSo0CTwTxOSO@AF5Q/LgtWJ@YLiWttIIJ143vO1eVu@56z6YOBRqA3uXwes9OKfC7wNYaayH8gu6AOeIzmhIp/S@7pJc4KHDIzq/gU@T66z57B@5sBMMb7aMaL/mNKovvrdL1hH6ASgsKztE@x0jK11qm6PXzbiyKmfPWoujYbbof8TriYODK0xk6d@ayeRK1eCvbn4A) (those reassignments of `s`...yikes) [Answer] # [Stax](https://github.com/tomtheisen/stax), 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Θx7├╖&σ '@7g┼┘Ñ«═ ``` [Run and debug it](https://staxlang.xyz/#p=e97837c3b726e52027403767c5d9a5aecd&i=[3,2,1,0,5]%0A[1,2,3,4,5]%0A[]%0A[42]%0A[1,2,1,3,4,1,5]%0A[3,3,3,3,4,3]&a=1&m=2) [Answer] # [R](https://www.r-project.org/), 111 bytes ``` function(a,r=rle(sign(diff(a))),v=r$l[r$v>0])write(paste0(rep("Excelsior",sum(v)),strrep("!",sequence(v))),1,1) ``` [Try it online!](https://tio.run/##bYxBDoIwEEX3nkINCTPJmFCKK8Wdp1AXpE5JEyw6LejtK7JUl/@9/CfJLvebZAdvous9NCS1dAzBtR6uzlpoEJHGWrLuJNl4KC74FBcZ7k2IXIDwHdbHl@EuuF7WFIYbjNMjRJnVakL8GNgb/nAkRQqTBQOaymkUtEXcmSZCfvY5Lj5GTUZT9WOcj9yyQPHFq/JfQc0N9aevSc9OI6Y3 "R – Try It Online") A far better R tribute can be found [here](https://codegolf.stackexchange.com/a/175961/67312) -- I was too fixated on `sequence` and `rle`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` <Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ ``` A monadic Link yielding a list of lists of characters. **[Try it online!](https://tio.run/##AT4Awf9qZWxsef//PMad4bmjMMOE4bqO4oCdIeG6i@KAnMOYNuG4pcK7O@Kxrv/Dh1n//1sxLDIsMSwzLDQsMSw1XQ "Jelly – Try It Online")** (footer joins with newlines) ### How? ``` <Ɲṣ0ÄẎ”!ẋ“Ø6ḥ»;Ɱ - Link: list of integers e.g. [1,1,4,2,1,1,3,4] Ɲ - for each pair of integers: [1,1] [1,4] [4,2] [2,1] [1,1] [1,3] [3,4] < - less than? [ 0, 1, 0, 0, 0, 1, 1] ṣ0 - split at zeros [[], [1], [], [], [1, 1]] Ä - cumulative sums [[], [1], [], [], [1, 2]] Ẏ - tighten [1,1,2] ”! - literal '!' character '!' ẋ - repeat (vectorises) [['!'],['!'],['!','!']] “Ø6ḥ» - dictionary lookup ['E','x','c','e','l','s','i','o','r'] Ɱ - map with: ; - concatenate [['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!'],['E','x','c','e','l','s','i','o','r','!','!']] ``` [Answer] # [Perl 5](https://www.perl.org/) `-n`, 41 bytes ``` $_>$l&&$l?say$c.='!':($c=Excelsior);$l=$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3k4lR01NJce@OLFSJVnPVl1R3UpDJdnWtSI5Nac4M79I01olx1Yl/v9/Qy4jLmMuAy4TLtN/@QUlmfl5xf91fU31DAwN/uvmAQA "Perl 5 – Try It Online") Takes its input on separate lines. [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 bytes ``` ò¨ ®£`Ex­lÐâ`+'!pYÃÅÃc ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=8qggrqNgRXitbNDiYCsnIXBZw8XDYw==&input=W1szLDIsMSwwLDVdLApbMSwyLDMsNCw1XSwKW10sCls0Ml0sClsxLDIsMSwzLDQsMSw1XSwKWzMsMywzLDMsNCwzXV0KLW1S) Explanation, with simplified example: ``` ò¨ :Split whenever the sequence does not increase e.g. [2,1,1,3] -> [[2],[1],[1,3]] ® à :For each sub-array: £ à : For each item in that sub-array: `Ex­lÐâ` : Compressed "Excelsior" + : Concat with '!pY : a number of "!" equal to the index e.g. [1,3] -> ["Excelsior","Excelsior!"] Å : Remove the first item of each sub-array e.g. [[Excelsior],[Excelsior],[Excelsior,Excelsior!]]->[[],[],[Excelsior!]] c :Flatten e.g. [[],[],[Excelsior!]] -> [Excelsior!] ``` [Answer] # Powershell, 69 bytes ``` $args|%{if($o-ne$e-and$_-gt$o){'Excelsior'+'!'*++$c}else{$c=0}$o=$_} ``` Less golfed test script: ``` $f = { $args|%{ if($old-ne$empty-and$_-gt$old){ 'Excelsior'+'!'*++$c }else{ $c=0 } $old=$_ } } @( ,( (3,2,1,0,5), 'Excelsior!') # Excelsior because 5 > 0 ,( (1,2,3,4,5), 'Excelsior!', # Excelsior because 2 > 1 'Excelsior!!', # Excelsior because 3 > 2 (run length: 2) 'Excelsior!!!', # Excelsior because 4 > 3 (run length: 3) 'Excelsior!!!!') # Excelsior because 5 > 4 (run length: 4) ,( $null, '') # <Nothing> ,( (42), '') # <Nothing> ,( (1,2,1,3,4,1,5), 'Excelsior!', # Excelsior because 2 > 1 'Excelsior!', # Excelsior because 3 > 1 'Excelsior!!', # Excelsior because 4 > 3 (run length: 2) 'Excelsior!') # Excelsior because 5 > 1 ,( (3,3,3,3,4,3), 'Excelsior!') # Excelsior because 4 > 3 ) | % { $a,$expected = $_ $result = &$f @a "$result"-eq"$expected" $result } ``` Output: ``` True Excelsior! True Excelsior! Excelsior!! Excelsior!!! Excelsior!!!! True True True Excelsior! Excelsior! Excelsior!! Excelsior! True Excelsior! ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~87~~ 85 bytes ``` param($n)for(;++$i-lt$n.count){if($n[$i]-gt$n[$i-1]){"Excelsior"+"!"*++$c}else{$c=0}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPMy2/SMNaW1slUzenRCVPLzm/NK9EszozDSgXrZIZq5teAmboGsZqViu5ViSn5hRn5hcpaSspKmkBtSXXAgVSq1WSbQ1qa////69hqGOkY6hjrGMCJE01AQ "PowerShell – Try It Online") There's probably a restructuring hiding in there, most likely in the if-else, but overall pretty alright. Uses the ol' "Un-instantiated variable defaults to 0" trick for both making the index and the `!`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 55 bytes ``` \d+ * L$rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b Excelsior$#1*! ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8mRZtLi8tHpagsQSNeS0fD3kZRw17DUDPGsCbGSEdTU1NbI15bMyaJy7UiOTWnODO/SEXZUEvx/39jHSMdQx0DHVMuLkMg01jHBMQ0MYJwDcEChiAhYx0INNExBgA "Retina – Try It Online") Link includes test cases. Explanation: ``` \d+ * ``` Convert to unary. ``` rv`(_*,(?<!(?(1)\1|\2,)))+(_+)\b ``` Process overlapping matches from right to left (although the matches are then listed from left to right). This means that we can match every number in a run, and the match extends to the start of the run. Each match is further constrained that each additional matched number must be less than the previously matched additional number, or the first number if no additional numbers have been matched yet. ``` L$... Excelsior$#1*! ``` For each match, output `Excelsior` with the number of additional numbers in the run as desired. [Answer] # Pyth, 32 bytes ``` j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0 ``` Try it online [here](https://pyth.herokuapp.com/?code=j%2BL%22Excelsior%22%2AL%5C%21fT.u%2AhN%3C0Y.%2BQ0&input=%5B1%2C2%2C1%2C3%2C4%2C1%2C5%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=j%2BL%22Excelsior%22%2AL%5C%21fT.u%2AhN%3C0Y.%2BQ0&test_suite=1&test_suite_input=%5B3%2C2%2C1%2C0%2C5%5D%0A%5B1%2C2%2C3%2C4%2C5%5D%0A%5B%5D%0A%5B42%5D%0A%5B1%2C2%2C1%2C3%2C4%2C1%2C5%5D%0A%5B3%2C3%2C3%2C3%2C4%2C3%5D&debug=0). ``` j+L"Excelsior"*L\!fT.u*hN<0Y.+Q0 Implicit: Q=eval(input()) .+Q Get forward difference between consecutive elements of Q .u 0 Reduce the above, returning all steps, with current value N starting at 0, next element as Y, using: hN N+1 * Multiplied by <0Y 1 if 0<Y, 0 otherwise fT Filter to remove 0s *L\! Repeat "!" each element number of times +L"Excelsior" Prepend "Excelsior" to each j Join on newlines, implicit print ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes ``` <Ɲ‘×¥\ḟ0”!ẋ“Ø6ḥ»;Ɱ ``` [Try it online!](https://tio.run/##AUoAtf9qZWxsef//PMad4oCYw5fCpVzhuJ8w4oCdIeG6i@KAnMOYNuG4pcK7O@Kxrv/Dhysv4oKsxZLhuZj//1sxLDIsMSwzLDQsMSw1XQ "Jelly – Try It Online") Output prettified over TIO. [Answer] # [Lua](https://www.lua.org), 88 87 83 82 96 95 113 bytes *Thanks @Kevin Cruijssen for update adhering to spirit of original question.* ``` s=io.read()n=9 e="Excelsior!"f=e for c in s.gmatch(s,"%S+")do if n<c+0then print(e)e=e..'!'else e=f end n=c+0 end ``` [Try it online!](https://tio.run/##FcxBCsMgFEXReVfxIpQoKZLQQQnUYVfQFYh@GyH9BrXQ3Vs7u4PL2T@2tWJi0pmsl4rNCjLi8XW0l5jyIIKhU0gZDpFR9Ottq9tkuYjzcxLKJ8QAvrtprhsxjhy5SlJkSOtxGLtCHQwg9mDTt3@1tuCKGxasmH8 "Lua – Try It Online") [Answer] # C++ 14 (g++), ~~123~~ 118 bytes ``` [](auto a){for(int n=0,i=0;++i<a.size();)a[i]>a[i-1]?puts(&("Excelsior"+std::string(++n,33))[0]):n=0;} ``` Fortunately `std::string` has a constructor that repeats a `char`. Try it online [here](https://tio.run/##lZHRaoMwFECfzVdkFkaC6WqMOlDrnva6Hyg@ZFa7QKuiEdaJ3@6SyMrK2oEJhATuPefm3rxp1oc8n1bi1NStTDrZiuqQws0GOpCG8P0siw6AlajyY78vYMLblp9TAEQl4YmLCmE4AIv3soYl3MJplyHz4Hgo6xbpsGrrErF1Y8cRCX/qxFeBcIz5TmSpOtY0e2l62aFHZL9@5sWxE3VrO53cR9FcDXKcijCG8c7NcKRo8ThZMQCWiTEFJcpDYJBCTlURAyMeocQlwRjrn1ywD8AqEadYJxunvb4sG99DehpJFZIR/y/y1/Xqfv2Yzd4Cs6vMTJtnYfJWyw89GgNiC0BUgXwN8r1bKH8B6lmhgp9uUNMP@m9H7jTHiIMF4lCJw3my8/YJuznbUKWP0zc). Thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner) for saving 5 bytes. Ungolfed: ``` [] (auto a) { // void lambda taking a std::array of integer for(int n = 0, // length of the current run i = 0; // loop variable ++ i < a.size(); ) // start with the second element and loop to the last a[i] > a[i - 1] // if the current element is greater than the previous ... ? puts( // ... print a new line: &("Excelsior" + // "Excelsior, followed by ... std::string(++ n, 33)) // ... the appropriate number of exclamation marks (33 is ASCII code for '!'); increment the run length [0]) // puts() takes a C string : n = 0; // else reset run length } ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 115 107 105 bytes ``` a=>{var b="";for(int i=0;++i<a.Length;)if(a[i]>a[i-1])Console.WriteLine("Excelsior"+(b+="!"));else b="";} ``` [Try it online!](https://tio.run/##hZBBT4MwGIbP8Cs@e6KhW8bAix0ki/E2Tx48IIcOy/wSbBNap4bw27Eyx0GZpEkPfb/nzfO1NItSN7J/M6gO8PBprHzlUNbCGNhC6xsrLJawLS1qtUFl8yKDCtJepFl7FA3sU0J4pZvAZYDpiochbsRyJ9XBvnCKVSByLDJ3LaKC3mpldC2Xjw1auUMlA3L3UcraoG5IGOzDlFwRSrl7kafqrudniaPGZ7gXqALa@t7gAoL73kRpHrM1i9iKXRc3hHLPE5CCku8wUO2YdtxzgnS65EnlkRuMWXKhZkznan7oX7ij/seS9TSYrGfRaNjwWy46y/91Hwfm/GN2OgmLL/znmI9VXdd/AQ "C# (.NET Core) – Try It Online") *-8 bytes: changed* `b` *to a string holding "!"s from an int counter* *-2 bytes: set* `b+="!"` *as an inline function (thanks to [Zac Faragher](https://codegolf.stackexchange.com/questions/175918/upward-and-onward-to-greater-glory/175959?noredirect=1#comment423836_175959))* Uses an [Action delegate](http://docs.microsoft.com/en-us/dotnet/api/system.action-1) to pull in the input and not require a return. Ungolfed: ``` a => { var b = ""; // initialize the '!' string (b) for(int i = 0; ++i < a.Length;) // from index 1 until the end of a if(a[i] > a[i - 1]) // if the current index is greater than the previous index Console.WriteLine("Excelsior" + // on a new line, print "Excelsior" (b += "!")); // add a "!" to b, and print the string else // if the current index is not greater than the previous index b = ""; // reset b } ``` [Answer] # [PHP](https://php.net/), ~~117~~ 109 bytes ``` <?php do{$i=next($argv);if($p!==null&&$p<$i){$e.='!';echo " Excelsior$e";}else$e='';$p=$i;}while($i!==false); ``` [Try it online!](https://tio.run/##DYzLCoNADEX3/QqV4MxsCn2tYuiqHyI2dgKDE7QPQfz2dBb3cODA1ahm3V2jVs@8gdDE69tDP7@@AWX0oDXR9EmpbUE7kLABH8nVDnmIuWoOj3XgtEiegRvcizIwOYegBIL7L0piD1Jexr7EgGZ2snPZxa6Ftz8 "PHP – Try It Online") [Answer] # J, 50 bytes ``` 'Excelsior',"1'!'#"0~[:;@(([:<+/\);._1)0,2</\ ::0] ``` [Try it online!](https://tio.run/##LYxBC4JAFITv/oppg55Ltu6udtlVCaJOnbqqSIhSEQjZoVN/fVtUHjPMfDzm6ZigHrkBIYKE8doJHK@Xs6PTt@1e42N4U8QUrWjN5K809hCGpcm2ccWtaBSXkc7iCsbI2vHg097GbswFEmi/pbCH9a59T6dM5C3VC1UTn7@S5VIkQdfeBxQIa897vhEF5mH3Bw "J – Try It Online") ## ungolfed ``` 'Excelsior' ,"1 '!' #"0~ [: ;@(([: < +/\);._1) 0 , 2 </\ ::0 ] ``` [Answer] **Java, 113 bytes** ``` String i="";for(int a=0;a<s.length-1;a++){if(s[a+1]>s[a]){i+="!";System.out.println("Excelsior"+i);}else{i="";}} ``` [Answer] **VBA, 114 bytes** ``` For i=0 To UBound(a)-LBound(a)-1 If a(i+1)>a(i)Then s=s&"!" Debug.Print("Excelsior"&s&"") Else s="" End If Next i ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 bytes ``` ä< ®?`Ex­lÐâ`+'!p°T:T=0 f ``` [Try it online!](https://tio.run/##y0osKPn///ASG4VD6@wTXCsOrc05POHwogRtdcWCQxtCrEJsDbjS/v@PNtQx0jHUMdYxAZKmsVy6QQA "Japt – Try It Online") ]
[Question] [ **This question already has answers here**: [Create a binary ruler](/questions/126172/create-a-binary-ruler) (26 answers) Closed 6 years ago. ### Input: A positive integer **N**. ### Challenge: Suppose you have a list of integers **n = 1, 2 ... N**. Output a list of integers, where each number is the maximum power of 2, **m**, such that **2^m** divides each number of **n**. --- Test cases: ``` 1 0 15 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0 100 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2 ``` This is [OEIS A007814](https://oeis.org/A007814). [Answer] # [Python 2](https://docs.python.org/2/), 46 bytes Saved a couple of bytes thanks to [nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof). ``` lambda k:[len(bin(t+1&~t))-3for t in range(k)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHbKjonNU8jKTNPo0TbUK2uRFNT1zgtv0ihRCEzT6EoMS89VSNbM/Z/QVFmXolGmoahpiYXnG2KzDEw0NT8DwA "Python 2 – Try It Online") --- **[Python 2](https://docs.python.org/2/), 51 bytes** ``` lambda k:[len(bin(t-~-(t&-~t)))-3for t in range(k)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHbKjonNU8jKTNPo0S3TlejRE23rkRTU1PXOC2/SKFEITNPoSgxLz1VI1sz9n9BUWZeiUaahqGmJhecbYrMMTDQ1PwPAA "Python 2 – Try It Online") # How? The formula for **a(k)** is **log2(k - (k & (k - 1)))**. That's quite fluffy, but fortunately it can be shortened significantly. In Python, **floor(log2(N)) = len(bin(N)) - 3**, because `bin()` appends `0b` to the binary representation of an integer. As a side note, `len(bin(N))-3` can be replaced by `N.bit_length()-1`, but that is not really beneficial for golfing purposes. That gives us the opportunity to get rid of the `import math` and the use of `math.log`. Another part that can be shortened is **k & (k-1)**. Using more bitwise operations, we get **k&~-k** instead, and then we subtract this from the actual **k**. But that would make us iterate over the range **[1, k]**, which would waste bytes because Python lacks inclusive ranges. In order to save a few bytes, we iterate over the integers in **[0, k)** instead and modify the formula, obtaining **k+1-(k&-~k) = k-~-(k&-~k)**. However, than can be simplified further to **k+1&~k** (as @nwellnhof pointed out). [Answer] # Pyth, 6 bytes ``` m/Pd2S ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=m%2FPd2S&input=5&test_suite=1&test_suite_input=1%0A15%0A100&debug=0) ### Explanation: ``` m/Pd2S S range [1, 2, ..., input] m map each number to / 2 the count of two in Pd its prime factorization ``` [Answer] # Mathematica, 29 bytes ``` #~IntegerExponent~2&~Array~#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfuc4zryQ1PbXItaIgPy81r6TOSK3OsagosbJOWe1/QFFmXomCQ1q0oYFB7P//AA "Mathics – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~60~~ ~~59~~ ~~55~~ 40 bytes ``` n=1:scan();cat(log2(n-(bitwAnd(n,n-1)))) ``` Reads from stdin, writes to stdout. Implements the formula referenced in [Mr. Xcoder's solution](https://codegolf.stackexchange.com/a/141852/67312), which fortunately vectorizes nicely in R. [Try it online!](https://tio.run/##K/r/P8/W0Ko4OTFPQ9M6ObFEIyc/3UgjT1cjKbOk3DEvRSNPJ0/XUBMI/hua/QcA "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` ($l).take l=0:do x<-l;[x+1,0] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P8fWwColX6HCRjfHOrpC21DHIJYrzVZDJUdTryQxO/V/bmJmnoKtQko@l4JCQVFmXomCikKagiEqzxSVa2DwHwA "Haskell – Try It Online") Recursively generate the infinite list `l`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~49~~ 44 bytes ``` f(n){n-1&&f(n-1);printf("%.f ",log2(n&-n));} ``` [Try it online!](https://tio.run/##DcnBCoAgDADQc36FBMkGLbSrXxPSJLAVVqfo11vdHrxEOSVVBsFbKDj3iwLGvS5yMrTdwLbty5ZHEEeCGB/9x67TIoD2Ng1D8B6jaep8XlWsj@bRN3GZ8qFU1g8 "C (gcc) – Try It Online") [Answer] # JavaScript (ES6), ~~42~~ 39 bytes *Saved 3 bytes thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* A straight-forward version using [Math.clz32()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32). Returns a comma-delimited string. ``` f=n=>--n&&f(n)+[,31-Math.clz32(++n&-n)] ``` ### Test cases ``` f=n=>--n&&f(n)+[,31-Math.clz32(++n&-n)] console.log(f(1)) console.log(f(15)) console.log(f(100)) ``` --- # Alternate version, ~~42~~ 41 bytes *Saved 1 byte thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* ``` f=n=>--n&&f(n)+[,(g=n=>n&1&&1+g(n/2))(n)] ``` ### How? This is based on the recursive formula: ``` a(n) = 0 if n is odd a(n / 2) + 1 if n is even ``` For golfing purposes, the function ***g*** is actually doing almost the opposite: ``` g(n) = g(n / 2) + 1 if the least significant bit of n is set 0 if the least significant bit of n is clear ``` We do it that way because ***n*** has already been decremented when ***g*** is invoked, so it's off by 1. This generates floats, but testing the LSB rather than computing a modulo ensures that the decimal part is ignored. The function ***f*** is just a wrapper that invokes ***g*** for all values from ***n - 1*** to ***1***, appending the results in reverse order, and eventually appending a leading ***0*** when the recursion stops. ### Test cases ``` f=n=>--n&&f(n)+[,(g=n=>n&1&&1+g(n/2))(n)] console.log(f(1)) console.log(f(15)) console.log(f(100)) ``` [Answer] # x86 Machine Code, 10 bytes ``` 0F BC C1 49 89 04 8A 75 F7 C3 ``` The above bytes of machine code define a function that takes an array of length *n* as input, and then replaces the value at each index with the maximum power of 2, *m*, such that 2m divides each number of *n*. each number is the maximum power of 2, m, such that 2^m divides each number of n. It follows the [`__fastcall`](https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall) register-based calling convention, passing the first parameter (the length of the array, *n*) in the `ECX` register and the second parameter (a pointer to the beginning of the array) in the `EDX` register. I posit that this is legal because, [like C](https://codegolf.meta.stackexchange.com/questions/13210/list-input-in-c-and-length-argument), arrays/lists are represented at the machine-code level as a pointer to the first element and a length. As stipulated in the challenge, *n* is assumed to be a strictly positive integer. **Ungolfed assembly mnemonics:** ``` ; void RulerSequence(unsigned len, unsigned * pSequence); ; ECX = len ; EDX = pSequence Top: 0F BC C1 bsf eax, ecx ; EAX = log2(ECX) 49 dec ecx ; ECX -= 1 89 04 8A mov DWORD PTR [edx+ecx*4], eax ; pSequence[ECX] = EAX 75 F7 jnz Top ; loop to 'Top' if ECX != 0 C3 ret ``` As you can see, the logic is embarrassingly simple. The only thing even slightly tricky is the use of [the `BSF` instruction](http://x86.renejeschke.de/html/file_module_x86_id_19.html), which obtains the index of the least-significant set bit. This is the shortest and fastest way to compute log2(n). **[Try it online!](https://tio.run/##bVDbTsMwDH1uvsIqQkpZBi27U0AaE3viD5apCmm6RepS1KYogPbrFBfYKIgHy5Z9fM6xZX8jZdPIwlQW5FaU4KbjRZGq1RpuwOcuXHJ3t@BuEXE3nHE3xQiHmOfcTUbcLSc4G/gxqaywWsJzoVNIEmFtqR9rq5KE0kxUVoo8DwKgZ8i/dCagtan0xqiUwaE6C1DyWz5uTrSReZ0quK5sqovz7S0hByRYVdl5WYoXtIlLbxAxuGQwYDBkMGIwZjBhMGUwYxCFGDiPEBAhIkJINIJ9/A/dgzJIV@lXVWT02A0u/nZW4TqICdHGwk5oQwPyRryvy2iXjP1Qt3jvqcSVjPpzaWuRX3HLrY8DLytKoC2bRvkwxnT9y1QMvZ4OiIcqR45TfJ3fEVjp1pO378hwc@@elLQqRan2DQzCz0cd60Gn7vT9T7elsnVp0A/ZN@8yy8Wmavq7weUH)** --- **Bonus alternate solution, also 10 bytes** ``` ; void RulerSequence_Alt(unsigned len, unsigned * pSequence); ; ECX = len ; EDX = pSequence Top: 0F BC C1 bsf eax, ecx 89 44 8A FC mov DWORD PTR [edx+ecx*4-4], eax E2 F7 loop Top C3 ret ``` Instead of separate `DEC`+`JNZ` instructions, we use the long-obsolete CISC-style `LOOP` instruction, which decrements `ECX` and loops to the specified label as long as `ECX` != 0. `LOOP` takes the same 2 bytes to encode as `JNZ`, so this saves us 1 byte from `DEC`. However, to compensate for the decrement being done *after* the array offset calculation, we need to add an additional subtraction to the indexing, which costs us an additional byte. So it's a wash. [Answer] # C, 48 bytes Using GCC's [builtin to count trailing zeros](https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Other-Builtins.html#index-_005f_005fbuiltin_005fctz): ``` f(v,n)int*v;{while(n--)v[n]=__builtin_ctz(n+1);} ``` Input in integer `n`, and output to the supplied array `v` (which must be at least `n` long). ## Test program: ``` #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { while (*++argv) { int n = atoi(*argv); if (n>0) { int *v = malloc(sizeof *v * n); if (!v) continue; f(v,n); printf("\n%d:\n", n); for (int i = 0; i < n; ++i) printf("%d ", v[i]); free(v); puts(""); } } } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` †#2†pḣ ``` [Try it online!](https://tio.run/##yygtzv7//1HDAmUjIFHwcMfi////G5oCAA "Husk – Try It Online") # How? It's my first "non-trivial" attempt in Husk, so patient with me :-) ``` †#2†pḣ - Full program. ḣ - The range [1, input]. †p - Map with prime factorisation. †#2 - Count the 2's in each. - Implicitly output. ``` [Alternative](https://tio.run/##yygtzv7/P1fZKLfg4Y7F////NzQFAA), suggested by [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer): `m#2mpḣ`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` RÆEḢ€ ``` [Try it online!](https://tio.run/##y0rNyan8/z/ocJvrwx2LHjWt@f//v6EpAA "Jelly – Try It Online") \*Saved 1 byte thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles)! Definitely not as short as the [built-in answer](https://codegolf.stackexchange.com/a/141845/59487) with *Order, multiplicity, valuation*, but I think it's worth it posting. # How? ``` RÆEḢ€ - Full program. R - The range [1, input]. ÆE - Compute the array of exponents of the prime factorization, including 0's. € - For €ach. Ḣ - Head. - Implicitly output the result. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ọ€2 ``` [Try it online!](https://tio.run/##y0rNyan8///h7t5HTWuM/v//b2gKAA "Jelly – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 29 bytes ``` n->[valuation(x,2)|x<-[1..n]] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y66LDGnNLEkMz9Po0LHSLOmwkY32lBPLy829n9BUWZeiUaahqGBgabmfwA "Pari/GP – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~42~~ 37 bytes *5 bytes removed thanks to [@StewieGriffin!](https://codegolf.stackexchange.com/users/31516/stewie-griffin)* ``` @(n)([~,y]=max(mod(x=1:n,2.^x')>0))-1 ``` [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999BI09TI7pOpzLWNjexQiM3P0WjwtbQKk/HSC@uQl3TzkBTU9fwf5qGoanmfwA) ### Explanation Let `n` be the input. The code computes each number `k` in the range `1`, ..., `n` modulo each number `d` in `1`, `2`, `4`, ..., `2^n`. This gives an `n`×`n` matrix, where `k` is the column index and each `d` corresponds to a row. This matrix is compared for inequality with 0. As a result, nonzeros are transformed into `1`, and zeros remain as `0`. For each column `k`, finding the (1-based) row index of the maximum value and subtracting 1 gives the solution. In other words, the number of initial zeros in each column is the desired `m` for each `k`. [Answer] # [Retina](https://github.com/m-ender/retina), 34 bytes ``` .+ $* \B1 ¶$`1 +`(1+)\1 $+0 %r`0\G ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYsrxsmQ69A2lQRDLu0EDUNtzRhDLhVtAy7VogSDGPf//w1NAQ "Retina – Try It Online") Explanation: ``` .+ $* ``` Convert to unary. ``` \B1 ¶$`1 ``` Create a triangle. ``` +`(1+)\1 $+0 ``` Start converting each row to base 2... ``` %r`0\G ``` ...but instead of completing the conversion, just count the trailing zeros. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes Patched a bug thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna) (`Ý` -> `L`). ``` LÒε2¢ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f5/Ckc1uNDi36/9/QFAA "05AB1E – Try It Online") # How? ``` LÒε2¢ - Full program. L - The range [1, input]. Ò - Prime factors with duplicates. ε - For εach. 2¢ - Count the 2's. - Output (implicitly). ``` Alternative: ``` LεÒ2¢ ``` [Answer] # Java 8, ~~86 + 26~~ ~~75~~ ~~81~~ ~~79~~ ~~77~~ ~~76~~ 74 bytes ``` n->{for(int i=0;i<n;System.out.println(n.toString(++i&-i,2).length()-1));} ``` [Try it online!](https://tio.run/##LY4xb8IwEIX3/IqbkF0aq1RiMrB0YmBiRB1c46SXOmfLPiMhlN@emjZvu@/p9L7B3EwboqPh@jPjGENiGCpThdGrrpBlDKRedNPE8uXRgvUmZzgZJHg0UJPZcOUfgXIZXdodiV3v0gG6PczUHh5dSAKJAfdvGnekz/fMblShsIqpFp4EKQ5nrkcv1mtctfj6LpV31PO3kO1GSj3NVeE5t2gsq7eAVxirjPh/v3yCSX2Wi9sznTLWushis5X6j07NNP8C "Java (OpenJDK 8) – Try It Online") [Answer] # Japt, 7 bytes A port of [Jakube's solution](https://codegolf.stackexchange.com/a/141854/58974). ``` õ_k è¶2 ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9V9rIOi2Mg==&input=MTU=) --- ## Explanation Implicit input of integer `U`. ``` õ_ ``` Generate an array of integers from 1 to `U` and pass each through a function. ``` k ``` Get an array of the prime factors of the current element. ``` è¶2 ``` Count (`è`) the number of elements that are strictly equal to (`¶`) 2. [Answer] # [Perl 6](https://perl6.org), ~~27~~ ~~17~~ 15 bytes -2 bytes thanks to [Brad Gilbert b2gills](https://codegolf.stackexchange.com/users/1147/brad-gilbert-b2gills) ``` {(1..$_)».lsb} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/WsNQT08lXvPQbr2c4qTa/8WJIAkNQwMDTev/AA "Perl 6 – Try It Online") [Answer] ## Haskell, 36 bytes ``` a 0=[0] a n|q<-a$n-1=q++n:q take<*>a ``` An adaption of [my answer](https://codegolf.stackexchange.com/a/69010/34531) from a [similar challenge](https://codegolf.stackexchange.com/q/68978/34531). [Try it online!](https://tio.run/##y0gszk7Nyfn/P1HBwDbaIJYrUSGvptBGN1ElT9fQtlBbO8@qkCvNtiQxO9VGyy7xf25iZp6CrUJKPpeCQkFRZl6JgopCmoIhKs8UlWtg8B8A "Haskell – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes ``` msl-hd.&h ``` **[Verify the test cases.](https://pyth.herokuapp.com/?code=msl-hd.%26h&input=5&test_suite=1&test_suite_input=1%0A15%0A100&debug=0)** If returning as floats was allowed, then **8 bytes**: ``` ml-hd.&h ``` # Explanation ``` msl-hd.&h - Full program. Q means input. m - Map over the implicit range [0, Q) with a variable d. sl - The integer part of logarithm base 2 of... -hd.&h - ... The Logical OR between d and d + 1, subtracted from d + 1. - Output implicitly. ``` The formula for **a(k)** is **log2(k - (k & (k - 1)))**, if we were to work with **[1, Q]**. By mapping over **[0, Q)** instead, we modify the formula accordingly, **log2(k + 1 - (k & (k + 1))**. This allows us to abuse implicit ranges at the end of the program. # [Pyth](https://pyth.readthedocs.io), 6 bytes ``` /R2PMS ``` An alternative to [Jakube's approach](https://codegolf.stackexchange.com/a/141854/59487). ``` /R2PMS - Full program. Q means input. S - The range [1, Q]. PM - Get prime factors of each. /R2 - Count the number of 2's. ``` [Answer] # Pyth, 10 bytes ``` mlec.Bd\1S ``` [Try it here.](http://pyth.herokuapp.com/?code=mlec.Bd%5C1S&input=15&debug=0) [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 5 bytes Port of [Jakube's Pyth answer](https://codegolf.stackexchange.com/a/141854/59487), and [my 05AB1E answer](https://codegolf.stackexchange.com/a/141859/59487). ``` SFP2/ ``` [Try it here!](http://pyke.catbus.co.uk/?code=SFP2%2F&input=100&warnings=0&hex=0) # How? ``` S - The range [1, input] F - For each. P - Prime factors. 2/ - Count the number of 2's. - Output implicitly. ``` [Answer] # [J](http://jsoftware.com/), 10 bytes ``` _{.@q:1+i. ``` [Try it online!](https://tio.run/##y/r/P03B1kohvlrPodDKUDtTj4srNTkjXyFNwdD0/38A "J – Try It Online") ## Explanation ``` _{.@q:1+i. Input: n i. Range, [0, n) 1+ Add 1 _ q: Exponents of each prime in the factorization of each {.@ Head each (Get the exponent of 2) ``` [Answer] # Perl 50 + 2 bytes ``` perl -E'say+sprintf("%b",$_)=~s/.*1//r=~y===c for 1..shift' ``` 50 bytes for the program proper, and 2 for the command line switch. The largest m such that 2^m divides n is just the number of trailing 0s in the binary representation of n. We get the latter by removing everything up to the last 1 of the binary representation, and taking the length of that. `y===c` happens to do that (it replaces every character by itself, returning the number characters it replaced). ]
[Question] [ Referring to the printable ASCII character codes in decimal, we know that from 32 to 126 we have the printable characters with 32 being (space). Your challenge is to write a program using only characters from 32 to 125 (excluding 126) which when executed, prints its own source code except that each character in the source code has its ASCII code increased by one. For example, if the source code was ``` main(){printf("Hello World");} ``` its output would be ``` nbjo)*|qsjoug)#Ifmmp!Xpsme#*<~ ``` The following are forbidden: * Reading/writing/using any external files or storage (including the internet) * Reading/echoing your own source code * Source codes with fewer than 2 characters (they are no fun). Must be greater than or equal to 2. Making it a popularity contest where after waiting for at least two weeks, the answer, in any language, with the highest upvotes wins with the smaller character count being the tie-breaker. [Answer] **Python (27 characters)** In the Python shell, the following script will output the desired result: ``` TzoubyFssps;!jowbmje!tzouby ``` Yes! it outputs: ``` SyntaxError: invalid syntax ``` [Answer] ## [huh?](http://esolangs.org/wiki/Huh%3F), 5 characters ``` Ntbg ``` **Note that the 5th character is a space after `Ntbg`**. This is the same trick as in [one of my previous answers](https://codegolf.stackexchange.com/a/16025/9275). `Ntbg` is an invalid path, so the interpreter will output `Ouch!` You should run it like this: ``` huh.exe Ntbg ``` [Answer] **PHP (351)** I'm sure there's a better way to do this, as I am new to codegolfing, but here's my PHP solution: ``` function q(){$q=chr(39);$a=array('function q(){$q=chr(39);$a=array(',');@$r.=$a[0];foreach($a as$b)$r.=$q.$b.$q.",";$r=substr($r,0,-1);$r.=$a[1];for($i=0;$i<strlen($r);$i++)$r{$i}=chr(ord($r{$i})+1);return $r;}');@$r.=$a[0];foreach($a as$b)$r.=$q.$b.$q.",";$r=substr($r,0,-1);$r.=$a[1];for($i=0;$i<strlen($r);$i++)$r{$i}=chr(ord($r{$i})+1);return $r;} ``` Output: ``` gvodujpo!r)*|%r>dis)4:*<%b>bssbz)(gvodujpo!r)*|%r>dis)4:*<%b>bssbz)(-(*<A%s/>%b\1^<gpsfbdi)%b!bt%c*%s/>%r/%c/%r/#-#<%s>tvctus)%s-1-.2*<%s/>%b\2^<gps)%j>1<%j=tusmfo)%s*<%j,,*%s|%j~>dis)pse)%s|%j~*,2*<sfuvso!%s<~(*<A%s/>%b\1^<gpsfbdi)%b!bt%c*%s/>%r/%c/%r/#-#<%s>tvctus)%s-1-.2*<%s/>%b\2^<gps)%j>1<%j=tusmfo)%s*<%j,,*%s|%j~>dis)pse)%s|%j~*,2*<sfuvso!%s<~ ``` [Answer] ## TI-BASIC, 10 For your TI-83/84 calculator! ``` DQQ9RXMS@W ``` Outputs: ``` ERR:SYNTAX ``` [Answer] ## GolfScript, 15 chars ``` {`{)}%"/2+"}.1* ``` Output: ``` |a|*~&#03,#~/2+ ``` [Try it online.](http://golfscript.apphb.com/?c=e2B7KX0lIi8yKyJ9LjEq) A fairly straightforward solution based on the technique I used for [my entry to the "rotating quine" challenge](https://codegolf.stackexchange.com/questions/5083/create-a-rotating-quine/5160#5160). The one tricky detail is that the character `~` (ASCII 126) is disallowed by the challenge rules, so I can't use it to execute my code block. Fortunately, `1*` can be used as a synonym of it. **Explanation:** The code block `{`{)}%"/2+"}` is duplicated by the `.`, and the second copy executed by `1*` (technically, a one-iteration loop), leaving the other copy on the stack. Inside the code block, ``` stringifies the code block, and `{)}%` loops over (the ASCII codes of) its characters, incrementing each by one. Finally, `"/2+"` pushes the literal string `/2+` (which is `.1*` shifted by one) onto the stack. At the end of the program, the GolfScript interpreter then automatically prints everything on the stack. **Ps.** Yes, I know this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'") rather than strict [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but what else am I going to do with GolfScript — ASCII art? ;-) [Answer] # JavaScript, 117 characters I know it's not code golf but I golfed it anyway. ``` function f(){alert((f+';f()').split('').map(function(x){return String.fromCharCode(x.charCodeAt()+1)}).join(''))};f() ``` (I'm not reading my own source code; I'm simply using the `Function` object's `toString` function.) [Answer] # Java - 1331 bytes, 618 bytes and 504 bytes Here it is in java. The cool thing is that it is pretty legible and flexible. You may experiment to change the `SHIFT` variable to 0 and it will be a quine. You may change it to whatever value you want, including negative values and it will shift the code accordingly. ``` public class Quinex { private static final int SHIFT = 1; private static String next(String now, boolean mangles) { String sb = ""; for (char c : now.toCharArray()) { if (!mangles && c == 87) { sb += next(String.valueOf(SHIFT), true); } else { sb += (char) ((mangles ? c : c == 94 ? 10 : c == 64 ? 34 : c) + SHIFT); } } return sb; } public static void main(String... args) { System.out.println(next(TEXT, false) + next(TEXT, true) + new String(new char[] { 34, 59, 10, 125 })); } private static final String TEXT = "public class Quinex {^^ private static final int SHIFT = W;^^ private static String next(String now, boolean mangles) {^ String sb = @@;^ for (char c : now.toCharArray()) {^ if (!mangles && c == 87) {^ sb += next(String.valueOf(SHIFT), true);^ } else {^ sb += (char) ((mangles ? c : c == 94 ? 10 : c == 64 ? 34 : c) + SHIFT);^ }^ }^ return sb;^ }^^ public static void main(String... args) {^ System.out.println(next(TEXT, false) + next(TEXT, true) + new String(new char[] { 34, 59, 10, 125 }));^ }^^ private static final String TEXT = @"; } ``` However, the only drawback in the previous class are the line breaks, which are not permited in the question spec (are outside the range 32 to 125). So I give here a golfed version that is free of line breaks (and free of the quirks to handle them). You may edit the value of the `S` variable to change the shift. This has 618 bytes: ``` class Q{static String g(String p,int m){int S=1;String u="";for(char c:p.toCharArray()){if(m==0&&c==87){u+=g(String.valueOf(S),1);}else{u+=(char)((m>0?c:c==64?34:c)+S);}}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T="class Q{static String g(String p,int m){int S=W;String u=@@;for(char c:p.toCharArray()){if(m==0&&c==87){u+=g(String.valueOf(S),1);}else{u+=(char)((m>0?c:c==64?34:c)+S);}}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T=@";} ``` Surely, if we drop the fine adjustment of the offset and hardcode the value of the shift, we can do a completely golfed version with 504 bytes: ``` class Q{static String g(String p,int m){String u="";for(char c:p.toCharArray()){u+=(char)((m>0?c:c==64?34:c)+1);}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T="class Q{static String g(String p,int m){String u=@@;for(char c:p.toCharArray()){u+=(char)((m>0?c:c==64?34:c)+1);}return u;}public static void main(String[]y){System.out.println(g(T,0)+g(T,1)+new String(new char[]{34,59,125}));}static final String T=@";} ``` [Answer] ### Perl 5, 284 characters include the linefeeds Not being allowed to use ~ made it a bit more tricky. ``` #!/usr/bin/perl $_=<<X; #!/usr/bin/perl Y \$a=\$_; s/\\\\/\\\\\\\\/g; s/\\\$/\\\\\\\$/g; \$b=\$_; \$_=\$a; s/Y/\\\$\\_\\=\\<\\<X\\;\\n\${b}X/; s/(.)/chr(ord(\$1)+1)/ge; print; X $a=$_; s/\\/\\\\/g; s/\$/\\\$/g; $b=$_; $_=$a; s/Y/\$\_\=\<\<X\;\n${b}X/; s/(.)/chr(ord($1)+1)/ge; print; ``` [Answer] ## Python, 99 ``` s='import sys;sys.stdout.write("".join(chr(ord(c)+1)for c in a%(s,a)))';a='s=%r;a=%r;exec s';exec s ``` Output: ``` t>(jnqpsu!tzt<tzt/tuepvu/xsjuf)##/kpjo)dis)pse)d*,2*gps!d!jo!b&)t-b***(<b>(t>&s<b>&s<fyfd!t(<fyfd!t ``` This can be shortened to **75 chars**, but it will print a new line character after the output, technically breaking the rules: ``` s='print"".join(chr(ord(c)+1)for c in a%(s,a))';a='s=%r;a=%r;exec s';exec s ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 bytes ``` "{^m'#bL"{^m'#bL ``` [Run and debug it](https://staxlang.xyz/#c=%22%7B%5Em%27%23bL%22%7B%5Em%27%23bL&i=&a=1) Adaption of the `"34bL"34bL` quine. Since now `"` becomes `#` which does not need to be escaped we can just include it in the string. [Answer] # Lua - 192 Pretty straightforward, ``` s=[[print((('s=['..'['..s..']'..']'..s):gsub('.',function(x)return string.char(x:byte()+1)end)))]]print((('s=['..'['..s..']'..'];'..s):gsub('.',function(x)return string.char(x:byte()+1)end))) ``` [Answer] # C - 156 ``` char*f="char*f=%c%s%c,q[200];i;main(){sprintf(q,f,34,f,34);while(q[i])q[i++]++;puts(q);}",q[200];i;main(){sprintf(q,f,34,f,34);while(q[i])q[i++]++;puts(q);} ``` Just the classic C quine with required modifications P.S, apparently `sprintf(f,...,f,...)` is a segfault. [Answer] **JavaScript (276)** Without using `.toString()`: ``` function q(){x=String.fromCharCode;y=x(39);a=['function q(){x=String.fromCharCode;y=x(39);a=[','];r=a[0]+y+a[0]+y+","+y+a[1]+y+a[1];q="";for(c in r)q+=x(r[c].charCodeAt(0)+1);return q;}'];r=a[0]+y+a[0]+y+","+y+a[1]+y+a[1];q="";for(c in r)q+=x(r[c].charCodeAt(0)+1);return q;} ``` [Answer] ## Ruby, 63 Darn, can't use a heredoc on this one. ``` s="s=%p;(s%%s).chars{|c|$><<c.succ}";(s%s).chars{|c|$><<c.succ} ``` Ruby has a native method `.succ` that does this on a character, and printing without a newline is shorter than printing with, so this works out pretty neatly. [Answer] # C, 153 ``` main(a){char b[999];sprintf(b,a="main(a){char b[999];printf(a=%c%s%c,34,a,34);for(a=0;b[a];)b[a++]++;puts(b);}",34,a,34);for(a=0;b[a];)b[a++]++;puts(b);} ``` Another modification of the classic quine in c... [Answer] ## ><>, 16 bytes ``` " r:2+l?!;1+o50. ``` [Try it here!](https://fishlanguage.com/playground/ASSj5vcTBX2DDh4He) This is more-or-less just a standard quine in ><> (without using the `g` instruction). The only differences are it doesn't read its own source-code and increments each character by 1 before outputting it. **Outputs** ``` #!s;3,m@"<2,p61/ ``` --- ### [\*><>](https://esolangs.org/wiki/Starfish), 15 bytes (non-competing) ``` " r:2+Ol?!;1+ou ``` [Try it here!](https://starfish.000webhostapp.com/?script=EQAgTgXATA1A8gGwPwEIDcBGGB7ArkA) [Answer] # [Tcl](http://tcl.tk/), 89 bytes ``` puts [join [lmap c [split [read [open $argv0]] ""] {format %c [expr [scan $c %c]+1]}] ""] ``` [Try it online!](https://tio.run/##HctBCoAwDAXRq3xEV270PCGLUKsorQ21iiCePRa3w5vigpme5QBtad1BIYrCgQ4NawFlLxMoqd/RSl6ugRlNw3jmlKMUdJX6W3MdnFTjauF@5PdnZvYB "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 89 bytes ``` puts [join [lmap c [split [read [open $argv0]] ""] {scan $c %c s;format %c [incr s]}] ""] ``` [Try it online!](https://tio.run/##HcpJCoAwDEbhq/yI7t17lNBFiAOVTjTVjXj2OOweH69JMCtHU9CefQKFyAUC0hJ8A9WFZ1AuS0LPdTtH59B1DpcKvyQYBDqtuUZuX5NPUqHu/jczewA "Tcl – Try It Online") --- Two approaches; the same byte length! [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` main=putStr$succ<$>s++show s;s="main=putStr$succ<$>s++show s;s=" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIpbg0OdlGxa5YW7s4I79codi62FaJkPz//wA "Haskell – Try It Online") [Answer] ## [Perl 5](https://www.perl.org/), 55 bytes ``` $_=q{print chr(1+ord)for split//,"\$_=q{$_};eval"};eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rawuqAoM69EITmjSMNQO78oRTMtv0ihuCAns0RfX0cpBqxEJb7WOrUsMUcJQv3/DwA "Perl 5 – Try It Online") [Answer] # J, 42 Bytes ``` (>:&.(u:inv)@,quote)'(>:&.(u:inv)@,quote)' ``` ]
[Question] [ In the New [Modern Times](http://en.wikipedia.org/wiki/Modern_Times_%28film%29), when Charlie Chaplin encounters a computer, he is employed in the sorting Yard, as a validator to determine if the workers are correctly sorting the items. The Items in question are packets of marbles. Packets with Odd number of Marbles are stacked in the Red Basket and Packets with Even Number of Marbles are stacked in the Blue Basket. Charlie Chaplin is supposed to [punch the program](http://en.wikipedia.org/wiki/Punched_card) that would validate if there is any anomaly in the sorting procedure. Mack Swain his immediate Boss, shares an algorithm which he needs to code. **Algorithm** ``` L = List of Marble packets that's already sorted L_ODD = List of packets with Odd Number of Marbles L_EVEN = List of packets with Even Number of Marbles Check_Digit = √(ΣL_ODD² + ΣL_EVEN²) ``` His Job is to determine the Check\_Digit and match it with what ever value his Boss calculates. Charlie Chaplin during his lunch hours, were able to sneak to Mack Swain's drawer and determine, that his drawer has a single card with punches on the first 46 32 columns (which means Mack was able to write a program with only 46 32 characters). Charlie Chaplin would now need the help of all the code ninja's to write a program with as few lines as possible. He also announces a bonus of 50 points, if someone can come up with a program which is shorter than his Boss. **Summary** Given a list/array/vector of positive numbers (odd and even), you need to write a function, which would accept the `array(int [])/vector<int>/list` and calculate the root of the sum of the squares of the sums of odd and even numbers in the list. The Size of the program is the size of the body of the function, i.e. excluding the size of the function signature. **Example** ``` List = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9] Odd = [9, 5, 5, 5, 15, 17, 9] Even = [20, 4, 20] Check_Digit = √(ΣOdd² + ΣEven²) = 78.49203781276162 ``` **Note**, the actual output might vary based on the implementation's floating point precision. **Score** Score is calculated as `Σ(Characters in your Program) - 46`.Score is calculated as `Σ(Characters in your Program) - 32`. Apart from the regular upvoting from the community, the lowest negative score would receive an additional bonus of 50 points. **Edit** 1. The offset that was used to calculate the Score has been changed from 46 to 32. Note, this would not affect the leader-board/ bounty eligibility or invalidate any solution. **Verdict** After a gruesome duel between the Ninjas, Mr. Chaplin received some wonderful answers. Unfortunately few of the answers tried to take undue advantage of the rule and was not very useful. He actually wanted a fair duel and answers where the logic was coded within the function signatures would eventually mean the function signature is an integral part of the solution. Finally, Ninja FireFly was the clear winner and awarded him the bonus he well deserves. **Leaderboard (updated every day)** ``` ╒══════╤═════════════════╤══════════════╤═════════╤════════╤═══════╕ ├ Rank │ Ninja │ Dialect │ Punches │ Scores │ Votes ┤ ╞══════╪═════════════════╪══════════════╪═════════╪════════╪═══════╡ │ 0 │ FireFly │ J │ 17 │ -15 │ 6 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 1 │ tmartin │ Kona │ 22 │ -10 │ 2 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 2 │ Sven Hohenstein │ R │ 24 │ -8 │ 7 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 3 │ Ben Reich │ GolfScript │ 30 │ -2 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 4 │ mollmerx │ k │ 31 │ -1 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 5 │ David Carraher │ Mathematica │ 31 │ -1 │ 3 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 6 │ tmartin │ Q │ 34 │ 2 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 7 │ daniero │ dc │ 35 │ 3 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 8 │ psion5mx │ Python │ 38 │ 6 │ 2 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 9 │ O-I │ Ruby │ 39 │ 7 │ 5 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 10 │ gggg │ Julia │ 40 │ 8 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 11 │ FakeRainBrigand │ LiveScript │ 50 │ 18 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 12 │ Sylwester │ Perl5 │ 50 │ 18 │ 2 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 13 │ daniero │ Ruby │ 55 │ 23 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 14 │ vasuakeel │ Coffeescript │ 57 │ 25 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 15 │ dirkk │ XQuery │ 63 │ 31 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 16 │ crazedgremlin │ Haskell │ 64 │ 32 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 17 │ Uri Agassi │ Ruby │ 66 │ 34 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 18 │ Sumedh │ JAVA │ 67 │ 35 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 19 │ Danny │ Javascript │ 67 │ 35 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 20 │ deroby │ c# │ 69 │ 37 │ 1 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 21 │ Adam Speight │ VB │ 70 │ 38 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 22 │ Andrakis │ Erlang │ 82 │ 50 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 23 │ Sp0T │ PHP │ 85 │ 53 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 24 │ brendanb │ Clojure │ 87 │ 55 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 25 │ Merin Nakarmi │ C# │ 174 │ 142 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 26 │ Boopathi │ JAVA │ 517 │ 485 │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 27 │ Noyo │ ES6 │ ? │ ? │ 2 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 28 │ shiona │ Haskell │ ? │ ? │ 0 │ ├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤ │ 29 │ Vivek │ int │ ? │ ? │ 0 │ └──────┴─────────────────┴──────────────┴─────────┴────────┴───────┘ ``` [Answer] ## ES6, ~~(48 - 32) = 16~~ (1 - 32) = -31 *Original version:* ``` f=l=>(e=o=0)+l.map(x=>x%2?e+=x:o+=x)&&Math.hypot(e,o) ``` Entire function definition is 53 characters, body only is 48. **Updated version, taking full advantage of the problem definition and moving pretty much everything out of the body and into the signature:** ``` f=(l,e=0,o=0,g=x=>x%2?e+=x:o+=x,c=l.map(g)&&Math.hypot(e,o))=>c ``` New function definition is now 63 "punches" total, but function BODY is now just **ONE DAMN CHARACTER LONG.** Plus it no longer corrupts the global namespace! :D Usage: ``` >>> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9]) 78.49203781276161 ``` [Answer] ## J, ~~18~~ 17 chars - 32 = ⁻15 ``` [:+/&.:*:2&|+//.] ``` (As a "function body"; has to be parenthesized or bound to a name.) ### Explanation I tried making an exploded view of what each piece does, like Tobia does in APL answers. ``` +//. ] NB. sum up partitions 2&| NB. given by equality on (x mod 2) *: NB. square, +/ NB. sum, &.: NB. then revert the squaring (square-root) NB. (f&.:g in general acts like g⁻¹(f(g(x)))) [: NB. (syntax to indicate composition of +/&.:*: and (2&| +//. ])) ``` `+/&.:*:` could be replaced with `|@j./` making use of O-I's [complex magnitude trick](https://codegolf.stackexchange.com/a/20420/3918) to save yet another two characters. ### Example ``` f =: [:+/&.:*:2&|+//.] f 20 9 4 5 5 5 15 17 20 9 78.492 ``` [Answer] ## R, (24 − 32) = −8 ``` f=function(x) sum(by(x,x%%2,sum)^2)^.5 ``` The function body consists of 24 characters. Usage: ``` f(c(20, 9, 4, 5, 5, 5, 15, 17, 20, 9)) [1] 78.49204 ``` [Answer] ### Ruby 2.1+ — (39 characters total - 7 non-body - 32 offset = 0) Slightly different approach. I create a complex number `a+b*i` such that `a` and `b` are the sums of the even and odd numbers in `list`, respectively. Then I just take the absolute value. ``` f=->l{l.reduce{|s,x|s+x*1i**(x%2)}.abs} ``` My previous solution, which is 5 characters longer but works on 1.9.3+: ``` f=->l{l.reduce{|s,x|s+x*?i.to_c**(x%2)}.abs} ``` On a final note, if Rails + Ruby 2.1+ were allowed, we can use `Array#sum` to get the body down to a mere 25 characters: ``` l.sum{|x|x+1i**(x%2)}.abs ``` [Answer] # Python 2.7: 45, nay: 40, nay: 38 - 32 = 6 Nothing very new here, just a combination of the complex number trick I saw in the recent Pythagoras challenge, lambda for compactness, and syntax/parenthesis minimisation: ``` lambda x:abs(sum(a*(1-a%2+a%2*1j)for a in x)) ``` Update - saved a few chars. Thanks to @DSM for the trick of raising the complex component to 0/1. ``` lambda x:abs(sum(a*1j**(a%2)for a in x)) ``` Ok, reading the question and recognising the 'body of the function' count rule saves another 2 chars: ``` def f(x): return abs(sum(a*1j**(a%2)for a in x)) ``` iPython testing: ``` In [650]: x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9] In [651]: print (lambda l:abs(sum(a*(1-a%2+a%2*1j)for a in l)))(x) 78.4920378128 ... In [31]: def f(x): ....: return abs(sum(a*1j**(a%2)for a in x)) ....: In [32]: f(x) Out[32]: 78.49203781276162 ``` [Answer] ## APL (27 - 46 = -19) ``` {.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵} ``` e.g.: ``` {.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵} 20 9 4 5 5 5 15 17 20 9 78.49203781 ``` [Answer] # Mathematica 31-32 = -1 ``` √Tr[(Tr/@GatherBy[#,OddQ])²]//N & ``` `GatherBy[#,OddQ]` produces the even-packet, odd-packet lists. The inner `Tr`finds the totals, both of which are squared and then summed (by the outer `Tr`). `N` converts from an irrational number (the square root of an integer) to a decimal approximation. ## Example ``` √Tr[(Tr/@GatherBy[#,OddQ])²]//N &[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}] ``` > > 78.492 > > > --- If `f[n_]:=` is not included in the count, an additional character can be saved. ``` f[n_]:= √Tr[(Tr/@GatherBy[n,OddQ])²]//N ``` Example ``` f[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}] ``` > > 78.492 > > > [Answer] # Kona, 22 - 32 = -10 ``` {(+/(+/'x@=x!2)^2)^.5} ``` [Answer] # Perl5 : (50 - 32 = 18) ``` map{$0[$_&1]+=$_}@ARGV;print sqrt$0[0]**2+$0[1]**2 ``` [Answer] # dc 3 (35 - 32) Using arrays, as suggested by @Tomas. This saves some of characters because I can calculate the parity of each number and use it as an index, instead of tweaking the with parity as a method of branching and putting the right values in the right registers. Also it turns out that arrays will give you a 0 even if the array/index haven't been used, so you don't have to initialize anything. ``` [d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v ``` Assumes the numbers are already on the stack, and leaves the result as the only value left when it's done. Test: ``` $ dc 20 9 4 5 5 5 15 17 20 9 [d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v p 78 ``` # dc 16 (48 - 32) First version using registers *o* and *e* to store odd and even numbers. ``` 0dsose[dd2%rd1+2%*lo+so*le+sez0<x]dsxxle2^lo2^+v ``` [Answer] # Prolog (73 - 32 = 41) Here we count everything after ':-' as the function body. ``` f([],0,0,0). f([H|T],O,E,X):-(1 is H mod 2,f(T,S,E,_),O is H+S,!;f(T,O,S,_),E is H+S),sqrt(O*O+E*E,X). ``` Call function like so: ``` f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9],_,_,X). ``` [Answer] **Python, 9 (55 - 46)** ``` lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5 ``` Using a lambda function saves some bytes on newlines, tabs and `return`. Example: ``` x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9] print (lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5)(x) 78.4920378128 ``` [Answer] # Ruby (66 - 32 = 34) ``` f=->a{o,e=a.partition(&:odd?).map{|x|x.reduce(:+)**2};(e+o)**0.5} ``` test: ``` f.([20, 9, 4, 5, 5, 5, 15, 17, 20, 9]) => 78.49203781276162 ``` [Answer] # Ruby, 55 - 46 = 9 ``` f=->a{h=[0,0];a.map{|v|h[v%2]+=v};e,o=h;(e*e+o*o)**0.5} ``` Test: ``` f[[20, 9, 4, 5, 5, 5, 15, 17, 20, 9]] => 78.49203781276162` ``` [Answer] # Q, 34 - 32 = 2 ``` {sqrt sum{x*x}(+/')(.)x(=)x mod 2} ``` . ``` q){sqrt sum{x*x}(+/')(.)x(=)x mod 2} 20 9 4 5 5 5 15 17 20 9 78.492037812761623 ``` [Answer] # Julia, 40-46=-6 **Implementation** ``` function f(l) a=sum(l);b=sum(l[l%2 .==1]);hypot(a-b,b) end ``` **Output** ``` julia> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9]) 78.49203781276161 ``` [Answer] **Coffeescript, (57 - 32 =25)** **Implementaion** ``` f=(a)->r=[0,0];r[e%2]+=e for e in a;[e,o]=r;(e*e+o*o)**.5 ``` [Answer] ## GolfScript 30 ``` .{2%},]{{+}*}/.@\-]{2?}/+2-1?? ``` I don't think GolfScript has much of a chance on this one! [Answer] ## c#: 69-32=37 ``` double t=l.Sum(),o=l.Sum(x=>x*(x%2)),e=t-o;return Math.Sqrt(o*o+e*e); ``` Full code: ``` class Program { static void Main(string[] args) { int[] list = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 }; Console.WriteLine(F(list)); Console.ReadKey(); } static double F(int[] l) { double t = l.Sum(), // total sum of all elements o = l.Sum(x => x * (x % 2)), // total of odd elements, if even %2 will return zero e = t - o; // even = total - odd return Math.Sqrt(o * o + e * e); } } ``` PS: Just for fun, this works too, sadly it doesn't change the number of characters needed: ``` double t=l.Sum(),o=l.Sum(x=>x*(x%2));return Math.Sqrt(t*t-2*o*(t-o)); ``` [Answer] # Matlab (44 - 46 = -2) Function body is 44 characters: ``` C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5 ``` Total function as follows: ``` function O = Q(A) C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5 end ``` Tests of the function: ``` >> A = [20 9 4 5 5 5 15 17 20 9]; >> Q(A) O = 78.4920 ans = 78.4920 ``` --- ``` >> B = [8 3 24 1 9 8 4 5 52]; >> Q(B) O = 97.6729 ans = 97.6729 ``` [Answer] ## Python 2.7 - 64-46 = 18 This could be shorter using some `zip` magic, but for now: ``` (sum(s for s in x if s%2)**2+sum(s for s in x if s%2==0)**2)**.5 ``` For completion, it turns out you can do zip magic, but it costs you more (by a few characters), so the above stands, unless someone can improve either of these: ``` sum(map(lambda i:sum(i)**2,zip(*[[(0,i),(i,0)][i%2]for i in x])))**.5 ``` [Answer] **C# 174** ``` using System;class P{static void Main(){double[] L={20,9,4,5,5,5,15,17,20,9};double O=0,E=0;foreach(int i in L){if(i%2==0)E+=i;else O+=i;}Console.Write(Math.Sqrt(E*E+O*O));}} ``` Readable ``` using System; class P { static void Main() { double[] L = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 }; double O = 0, E = 0; foreach (int i in L) { if (i % 2 == 0) E += i; else O += i; } Console.Write(Math.Sqrt(E * E + O * O)); } } ``` ![Charlie's Output](https://i.stack.imgur.com/rYPNd.png) [Answer] ### Clojure = 87 - 46 = 41 ``` (defn cd [v] (let [a apply ** #(* % %)] (Math/sqrt(a + (map #(** (a + (% 1)))(group-by even? v)))))) ``` Hardly idiomatic, though. [Answer] ## Haskell, 64C - 46 = 18 ``` c x=sqrt$fromIntegral$s(f odd x)^2+s(f even x)^2 f=filter s=sum ``` Not too difficult to read. Example run: ``` *Main> c [1..10] 39.05124837953327 ``` [Answer] `int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));` ## Actual method in java code ``` public static void checkDigit(int[] n) { int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o)); } ``` > > Test Class > > > ``` public class Sint { public static void main(String[] args) { if(args == null || args.length == 0) args = "20 9 4 5 5 5 15 17 20 9".split(" "); int[] n = null; try { n = new int[args.length]; for(int i=0; i<args.length; i++) n[i] = Integer.parseInt(args[i]); System.out.print("int array is: "); for(int dd : n) System.out.print(dd+", "); System.out.print("\n"); checkDigit(n); } catch (Exception e) { e.printStackTrace(); } } public static void checkDigit(int[] n) { int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o)); } } ``` [Answer] **PHP** 85-32=53 `$a=$b=0;foreach($x as $q){if(($q%2)==0)$a=$a+$q;else$b=$b+$q;}echo sqrt($a*$a+$b*$b);` This is the best i'ld come up being a newbie. I'm sure there must be some shorter versions as well. **EDIT:** A reduced version of the code could be: ``` foreach($x as$q)($q%2)?$a=$a+$q:$b=$b+$q;echo sqrt($a*$a+$b*$b); ``` This version only has 64 (21 less than the original answer) chars. Said so, 64-32=**32** [Answer] ## VB.net (81c - 11c = 70) - 32 = 38 Via liberal usage of the term *Write a function* ``` Function(n)Math.Sqrt(n.Sum(Function(x)x Mod 2=0)^2+n.Sum(Function(x)x Mod 2=1)^2) ``` [Answer] ### XQuery, (63 - 32 = 31) **Implementation** ``` declare default function namespace 'http://www.w3.org/2005/xpath-functions/math'; declare function local:f($s) { sqrt(pow(fn:sum($s[. mod 2=0]),2)+pow(fn:sum($s[. mod 2=1]),2)) }; ``` **Output** ``` local:f((20, 9, 4, 5, 5, 5, 15, 17, 20, 9)) ``` [BaseX](http://basex.org) was used as XQuery processor. [Answer] # Erlang: 82C - 32 = 50 ``` fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end. ``` Erlang isn't great for this. Most shortcuts end up being more characters (tuples etc.) The only real things of note: * `{lists,sum}` is a function reference to `lists:sum` and can be called * Even numbers are calculated by subtracting `--` (*list subtract*) the odd numbers list from the full list Can call using: ``` fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end([20,9,4,5,5,5,15,17,20,9]). ``` Output: `78.49203781276162` [Answer] ## Haskell **57 - 32 = 25** Straight optimization of crazedgremlins answer: ``` c x=sqrt$read$show$sum(odd%x)^2+sum(even%x)^2 (%)=filter ``` Optimizations: * `read$show` is shorter than `fromIntegral` - *3 chars* * `s=sum\n` and two `s`'s has total length of 8 chars, two `sum`'s is just 6 chars. - *2 chars* * making filter into operator does away with need of whitespace - *2 chars* I also tried adding more stuff to the operator, but it ended up being just as long: ``` c x=sqrt$read$show$odd%x+even%x (%)=(((^2).sum).).filter ``` ]
[Question] [ # I need a UUID. Your job is to generate one. The canonical UUID (Universally Unique IDentifier) is a 32 digit hexadecimal number with hyphens inserted in certain points.The program should output 32 hex digits (128 bits), in the form of `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` (`8-4-4-4-12` digits), where `x` is a random hexadecimal number. Assuming that your language's PRNG is perfect, all valid outputs must have the same probability of being generated. ## TL;DR Generate 32 random hexadecimal digits in the form `8-4-4-4-12` digits. Shortest code wins. EDIT: Must be hexadecimal. Always generating decimal only is invalid. EDIT 2: No built-ins. These aren't GUIDs, just generic hex digits. --- ## Example output: ``` ab13901d-5e93-1c7d-49c7-f1d67ef09198 7f7314ca-3504-3860-236b-cface7891277 dbf88932-70c7-9ae7-b9a4-f3df1740fc9c c3f5e449-6d8c-afe3-acc9-47ef50e7e7ae e9a77b51-6e20-79bd-3ee9-1566a95d9ef7 7b10e43c-3c57-48ed-a72a-f2b838d8374b ``` Input, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Also, feel free to ask for clarifications. [Answer] # Pyth, 20 bytes ``` j\-msm.HO16*4hdj83 3 ``` [Demonstration.](https://pyth.herokuapp.com/?code=j%5C-msm.HO16%2a4hdj83+3&debug=0) Encodes `[1, 0, 0, 0, 2]` as 83 in base 3, then adds one and multiplies by four to get the length of each segment. Then makes hex digits and joins on hyphens. [Answer] # Julia, 80 bytes ``` h=hex(rand(Uint128),32) print(h[1:8]"-"h[9:12]"-"h[13:16]"-"h[17:20]"-"h[21:32]) ``` Generate a random 128-bit integer, get its hexidecimal representation as a string padded to 32 digits, and divide that into segments joined with dashes. Thanks to ConfusedMr\_C and kvill for their help! [Answer] # CJam, ~~26~~ 25 bytes ``` 8 4__C]{{Gmr"%x"e%}*'-}/; ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=8%204__C%5D%7B%7BGmr%22%25x%22e%25%7D*'-%7D%2F%3B). ### How it works ``` 8 4__C]{ }/ For each I in [8 4 4 4 12]: { }* Do I times: Gmr Pseudo-randomly select an integer between 0 and 15. "%x"e% Apply hexadecimal string formatting. '- Push a hyphen-minus. ; Discard the last hyphen-minus. ``` [Answer] # PowerShell, 77 69 67 bytes ``` ((8,4,4,4,12)|%{((1..$_)|%{'{0:X}'-f(random(16))})-Join""})-Join"-" ``` edit: extraneous parens: ``` ((8,4,4,4,12)|%{((1..$_)|%{('{0:X}'-f(random(16)))})-Join""})-Join"-" ``` edit: was able to remove the trailing .Trim("-") from the original: ``` (((8,4,4,4,12)|%{((1..$_)|%{('{0:X}'-f(random(16)))})+"-"})-Join"").Trim("-") ``` It may be clearer with some whitespace given the nature of the flags (-f and -Join). I would still like to lose the final Trim("-"): ``` (((8,4,4,4,12)|%{((1..$_)|%{('{0:X}' -f (random(16)))}) + "-"}) -Join "").Trim("-") ``` Or, using the built-in functionality (ala the C# answer above) ``` '{0}'-f[System.Guid]::NewGuid() ``` However, it seems a wee bit shortcut-y even if it comes in at 31 bytes. [Answer] # Python 2, ~~86~~ 84 bytes ``` from random import*;print'-'.join('%%0%ix'%i%randint(0,16**i-1)for i in[8,4,4,4,12]) ``` This chains string formatters to make Python format the hex numbers uniquely for each segment. Ungolfed: ``` import random final = [] for i in [8, 4, 4, 4, 12]: # Iterate through every segment max = (16 ** i) - 1 # This is the largest number that can be # represented in i hex digits number = random.randint(0, max) # Choose our random segment format_string = '%0' + str(i) + 'x' # Build a format string to pad it with zeroes final.append(format_string % number) # Add it to the list print '-'.join(final) # Join every segment with a hyphen and print ``` This could use some improvement, but I'm proud. [Answer] # [Perl 5](https://www.perl.org/), 43 bytes Saved 2 bytes thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali)! ``` printf"%04x"."-"x/[2-5]/,rand 2**16for 1..8 ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1cCkQklPSVepQj/aSNc0Vl@nKDEvRcFIS8vQLC2/SMFQT8/i/38A "Perl 5 – Try It Online") [Answer] # PHP, 69 ~~72~~ ~~75~~ bytes ``` foreach([8,4,4,4,12]as$c)$r[]=rand(".1e$c","1e$c");echo join('-',$r); ``` This does not output hex digits (`a`, ... `f`). They are allowed, but not required by the question body. No digit group starts with `0` (also not required). *edit: saved 3 bytes thanks to @IsmaelMiguel* [Answer] # JavaScript, ES6, 106 bytes ``` "8-4-4-4-12".replace(/\d+/g, m => {t=0;for(i=0; i<m; i++) {t+=(Math.random()*16|0).toString(16)}return t}) ``` Uses Regex replace. Treats the format string as a count for generating a hex char. Hoisting wherever I can; omitting semicolons where possible. [Answer] # C#, 65 Bytes ``` using System;class C{void Main(){Console.Write(Guid.NewGuid());}} ``` edit: Yes ! C# is shorter than another Language (besides Java) :) [Answer] # gawk, 86 ``` BEGIN{for(srand();j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16} ``` You can use this once every second to generate a unique random "UUID". This is because `srand()` uses the system time in seconds since epoch as argument if there is no argument given. ``` for n in `seq 100` do awk 'BEGIN{for(srand();j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16}'; sleep 1; done ``` I think the awk part is rather elegant. ``` BEGIN{ srand() for(;j++<32;) { x=rand()*16 x+=(x>10?87:48) printf "%c", x if(j~"^8|12|16|20")printf "-" } } ``` If you want to use it more often than once every second you can call it in bash like this. Note that the awk part is changed too. ``` echo `awk 'BEGIN{for(srand('$RANDOM');j++<32;printf(j~"^9|13|17|21"?"-":E)"%c",x+(x>10?87:48))x=rand()*16}'` ``` The `echo` is added there to print a new line every time. [Answer] # K5, 35 bytes ``` "-"/(0,8+4*!4)_32?`c$(48+!10),65+!6 ``` To generate a hex alphabet I generate a character string (``c$`) from a list of digits (`48+!10`) and the first 6 capital letters (`65+!6`). An alternate way of generating the digits which is the same length is `,/$!10`. With the string "0123456789ABCDEF" generated, the rest is simple. Select 32 random values from this set (`32?`), slice (`_`) the resulting string at `0 8 12 16 20` computed via `(0,8+4*!4)`, and then join the resulting string fragments with dashes (`"-"/`). In action: ``` "-"/(0,8+4*!4)_32?`c$(48+!10),65+!6 "9550E114-A8DA-9533-1B67-5E1857F355E1" ``` [Answer] # [R](https://www.r-project.org/), 63 bytes ``` x=sample(c(0:9,letters[1:6]),36,1);x[0:3*5+9]='-';cat(x,sep='') ``` [Try it online!](https://tio.run/##K/r/v8K2ODG3ICdVI1nDwMpSJye1pCS1qDja0MosVlPH2EzHUNO6ItrAyljLVNsy1lZdV906ObFEo0KnOLXAVl1d8/9/AA "R – Try It Online") The code first builds a 36 character random string, and then places the four hyphens. It outputs a UUID to stdout. [Answer] ## [Perl 6](http://perl6.org), 53 bytes The obvious one: ``` say join '-',(0..9,'a'..'f').flat.roll(32).rotor(8,4,4,4,12)».join # 67 ``` --- Translating the Perl 5 example using `printf`, results in code that is a bit shorter. ``` printf ($_='%04x')~"$_-"x 4~$_ x 3,(0..^4⁸).roll(8) # 53 ``` [Answer] # [Kotlin](https://kotlinlang.org), 175 bytes ``` fun main(a:Array<String>){ fun f()="0123456789abcdef".get((Math.random()*16).toInt()) var s="" for(i in listOf(8,4,4,4,12)){ for(j in 1..i) s+=f() if(i!=12)s+="-"} println(s)} ``` [Try it online!](https://tio.run/##HY7LDoIwFET3/Qrs6l4fjSAiGjFx6cK48AuqULwKxbTVxBi@vRYzq8mZ5Myjcw1p79VLR60kDXKzN0Z@tmdnSNc7/LIBKcCCz@NkkS6zVb6Wl2tZKS7qygEcpbsJI3XZtYDjOEPhuoN2gMje0kS24JypzgBFpKOGrDspyKfpP3GCgyHQ@0BjIQiZnRTBx0gBjYqwCJ3PeM@e4ZFrNFjsvf8B "Kotlin – Try It Online") My first ever Kotlin program & PPCG submission [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~115~~ 78 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429) ``` a←⊣,'-',⊢ H←⊃∘(⎕D,819⌶⎕A)¨16∘⊥⍣¯1 (H 8?16)a(H 4?16)a(H 4?16)a(H 4?16)a H 12?16 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBI/6pnr6P2qbYMCVCCQfdS3WUddV13nUtYjLA8xvftQxQwOoyEXHwtDyUc82INNR89AKQzOg@KOupY96Fx9ab8il4aFgYW9oppkIZJjgYCh4KBgaAVkA "APL (Dyalog Unicode) – Try It Online") This is my first APL submission. Huge thanks to @Adám for bearing with me at the PPCG's APL chat and for the hexadecimal conversion function. Thanks to @Zacharý for 1 byte Edited to fix byte count. [Answer] # [Japt](https://github.com/ETHproductions/japt), 32 bytes ``` [8,4,4,4,12]m@MqG**X sG ù0X} q"- ``` [Try it online!](https://tio.run/##y0osKPn/P9pCxwQMDY1icx18C921tCIUit0VDu80iKhVKFTS/f8fAA "Japt – Try It Online") [Answer] # [Go](https://golang.org/), ~~119~~ 110 bytes ``` import(."math/rand";."fmt") func f(){for j:=0;j<32;j++{if j>4&&j<24&&j%4<1{Print("-")} Printf("%x",Int()%16)}} ``` [Try it online!](https://tio.run/##JY5BC4IwHMXv@xTjD8qGtdKkQ1r3LhFEH2DoZltsE1kkyD77Urs83nuH33udiz1v3rwT2HBlkTK9GzwDr4yA@E@EgeH@tRu4baFiII0HiuTHNlgSOkk3YH067ytdH4pKZ9mkJNaXMk11XSyalHU@3QdlPYEt0IBWLwkkI2yuc0uT/EhDiCtyuTFT0UOIltzcl1D2tGokdJ4kFIX4Aw "Go – Try It Online") * -9 by @The Thonnu [Answer] # [Julia](https://julialang.org), 57,60 55 bytes ``` !n=bytes2hex(rand(UInt8,n)) join(.![4,2,2,2,6],-)|>show ``` * 57->60 a mistake * 60->55 by @MarcMush and the broadcasting :-) [Attempt This Online!](https://ato.pxeger.com/run?1=fY5BbsJADEX3PcUENokUMyKKElSp7DlAV6iLIXHI0MSGGQdaqTfphg1X4Q7cptOIVuqmsuW_sP77__OyGzprzrfrVHVoHGGtzIYHUZt3QZ-1-KYax71qRfb-UWsvpnrlI7qm49Os4l4fBvRimbwuyqwoizzXLZ9AGLZI6IwgGHCGau4h4EyNle1NB16cpS1YgrHCw1Qd5-FE9PQbHX_b4ucVySKlJAnfHVuK11GeRtnPFi_pBCbJx9KH2MsgDSxu5X-UkTGL1nmajRMA8Md-vstdvwA) [Answer] ## MATLAB/Octave , 95 bytes ``` a='-';b=strcat(dec2hex(randi(16,32,1)-1)');[b(1:8) a b(9:12) a b(13:16) a b(17:20) a b(21:32)] ``` [Answer] ## [Perl](http://perl.org), 51 bytes ``` say"xx-x-x-x-xxx"=~s/x/sprintf"%04x",rand 65536/reg ``` Requires perl5 >= 5.10 I think. For the /r modifier and for say(). [Answer] # [J](http://jsoftware.com/), ~~42 39 37~~ 27 bytes ``` echo'-'(8+5*i.4)},hfd?36#16 ``` [Try it online!](https://tio.run/##y/pvqWhlaKNnaGCgVW1lpmhloK6u4OekpwAB@voKxampKQolGakKQX7u/1OTM/LVddU1LLRNtTL1TDRrdTLSUuyNzZQNzf7/BwA) [Answer] ## C++, ~~194~~ ~~193~~ ~~221~~ ~~210~~ 201 bytes +7 bytes thanks to Zacharý ( detected a `-` that should not be at the end ) ``` #include<iostream> #include<random> #include<ctime> #define L(a)for(int i=0;i<a;++i)std::cout<<"0123456789abcdef"[rand()%16]; #define P(a)printf("-");L(a) void t(){srand(time(0));L(8)P(4)P(4)P(4)P(12)} ``` If someone has a way to get a different value every execution without changing `srand` and without including `<ctime>`, that would be great [Answer] # [Befunge-93](https://esolangs.org/wiki/Befunge), 97 bytes ``` v>4448v,+< < 0* : >59*0^ 62v0-1_$:|>*6+^ >^>41v < @^99< v<*2\_$:54+` | ?0>+\1-^ v*68<> >1^ ``` [Try it online!](https://tio.run/##FckxDoMwDEDR3afw0MkpUoJMRJBlOAgyCImysdUTdw/wlzf8bf/9z2Ov1ZWZe/8GwSeBSK8DonaFokFuPTZp@QyXUg4GasrJUXCyUgRcqJ2f23FY8YIxaphTY@iUe1HQZLXe "Befunge-93 – Try It Online") I'm sure this can be shrunk, but this is my first try :) [Answer] # Bash, 67 bytes ``` for l in 4 2 2 2 6;{ o+=`xxd -p -l$l</dev/random`-;} echo ${o::-1} ``` [Answer] # JavaScript REPL, 79 bytes ``` '66-6-6-6-666'.replace(/6/g,_=>(Math.random().toString(16)+'00000').slice(2,6)) ``` [Try it online!](https://tio.run/##LctBDoMgEEDR4zATdbRdzE5v4MoDNBMklIYyBkivTzXxv/X/yE@KzeGoQ9LdNaupaHQU1UMzzMON2VB2RxTrYOTR9695gVXqm7KkXb@AVHWrOSQPD8bOTFcGqcRwLs@eERu2Pw "JavaScript (Node.js) – Try It Online") `Math.random` may return `0`. Adding 5 zeros make the slicing get 4 `0`s [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 91 89 bytes ``` include random.fs hex : f 0 4 4 4 8 20 0 do dup i = if + ." -" then 10 random 1 .r loop ; ``` [Try it online!](https://tio.run/##LY0xDsIwFEP3nsJ0YYBWLWJAIA7AxMLIEpEf8qU0v0pSoFw@tKjyYFlPto2EZKunmS1n9g83aEJQXktXm1hY@hRHGDTY/3XArpmCFuihB@MMNtigLlGVSJY82mapo0Ud4ER6nLKlQIhEGivccbtcpwmKfp3AnhMrx9@F90F6Cm7cIgreBKtehCTzJSd0yg/KubEw@Qc "Forth (gforth) – Try It Online") ### Explanation Changes the base to hexadecimal, then outputs numbers/segments of the appropriate length with dashes at specified intervals ### Code Explanation ``` include random.fs \ include the random module hex \ set the base to hexadecimal : f \ start a new word definition 0 4 4 4 8 \ enter the intervals to place dashes 20 0 do \ start a counted loop from 0 to 0x20 (32 in decimal) dup i = \ check if we are on a character that needs a dash if \ if we are + \ calculate the next character that gets a dash ." -" \ output a dash then \ end the if block f random \ get a random number between 0x0 and 0xf 1 .r \ output it right-aligned in 1-character space loop \ end the loop ; \ end the word definition ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~94~~ ~~91~~ 86 bytes ``` main(i){srand(&i);i=803912;for(;i--%16||(i/=16)&&printf("-");printf("%x",rand()%16));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzurgoMS9FQy1T0zrT1sLA2NLQyDotv0jDOlNXV9XQrKZGI1Pf1tBMU02toCgzryRNQ0lXSdMaxlatUNIB69cEqtXUtK79/x8A "C (gcc) – Try It Online") I would have liked to suggest this version in a comment to Max Yekhlakov ([his answer](https://codegolf.stackexchange.com/a/170182/81487)), but unfortunately I do not have the 50 needed reputation points yet, so here is my answer. `803912` is `C4448` in hexadecimal, it describes how the output should be formatted (`12-4-4-4-8`), it is reversed because least significant digits will be read first.   ## Edits: * saved 3 bytes thanks to Jonathan Frech * saved 5 more bytes by replacing `srand(time(0))` with `srand(&i)` [Answer] # C (gcc), ~~143~~ ~~110~~ ~~103~~ ~~96~~ 94 bytes Golfed down to 94 bytes thanks to ceilingcat and Jonathan Frech. ``` (*P)()="\xf\x31À";*z=L"\10\4\4\4\14";main(n){for(;*z;*++z&amp;&amp;putchar(45))for(n=*z;n--;printf("%x",P()&amp;15));} ``` [Try it online!](https://tio.run/##S9ZNT07@/19DK0BTQ9NWid/wcIOStVaVrY8SBwsLC4@SdW5iZp5GnmZ1Wn6RBlDCWktbu0pNraC0JDkjsUjDxFRTEySTZwuUytPVtS4oyswrSdNQUq1Q0gnQ0FQzBCqwrv3/HwA "C (gcc) – Try It Online") Explanation: ``` /* P is a pointer to a function. The string literal contains actual machine code of the function: 0F 31 rdtsc C3 ret 0xc3 is the first byte of the UTF-8 representation of the character À */ (*P)() = "\xf\61À"; // encode uuid chunk lengths as literal characters // we use wide characters with 'L' prefix because // sizeof(wchar_t)==sizeof(int) for 64-bit gcc C on TIO // so z is actually a zero-terminated string of ints *z = L"\8\4\4\4\14" main (n) { for ( ; // loop until we reach the trailing zero *z; // increase the pointer and dereference it *++z // and output a hyphen, if the pointer does not point at zero && putchar(45) ) // output a random hex string with length pointed at by z for (n = *z; n--; printf ("%x", P()&15)); } ``` [Answer] # Java with [Ten Foot Laser Pole](https://github.com/SuperJedi224/Ten-Foot-Laser-Pole) v. 1.06, 126 bytes ``` String u(){return sj224.tflp.util.StringUtil.replace("aa-a-a-a-aaa","a",s->String.format("%04x",(int)(Math.random()*65536)));} ``` Tested with version 1.06 of the library, but this *should* work with any version 1.04 or newer. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 31 bytes ``` import uuid;print(uuid.uuid4()) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRKG0NDPFuqAoM69EA8TUAxEmGpqa//8DAA "Python 3.8 (pre-release) – Try It Online") Python has an inbuilt package for this specific task. Enjoy :P ]
[Question] [ Most computers store integers in binary, but output them in decimal. However, decimal is just one representation, we just happen to find it convenient. This challenge is to write some code to output an integer value in ***shortlex decimal***. What's that? <http://en.wikipedia.org/wiki/Shortlex_order> Shortlex takes the length of the sequence of digits as the primary signifier of value. The sequence, starting from an empty string representing zero, is... ``` ε,0,1,...,8,9,00,01,...98,99,000,001,...,998,999,0000,... ``` (Think of Excel columns, but using only the decimal digits.) Write a program or function that accepts an integer and returns a string corresponding to the shortlex-decimal representation of that integer as described above. Test values: 0 → "" (Empty string) 1 → "0" 10 → "9" 11 → "00" 42 → "31" 100 → "89" 800 → "689" 1060 → "949" 10270 → "9159" 100501 → "89390" [Answer] # JavaScript (ES6) 42 ~~74~~ ``` n=>(n-~(n+'').replace(/./g,8)+'').slice(1) ``` **Test in FireFox console** ``` ;[0,1,10,11,42,100,800,1060,10270,100501] .forEach(x => console.log(x +" -> '" + S(x) + "'")) ``` *Output* ``` 0 -> '' 1 -> '0' 10 -> '9' 11 -> '00' 42 -> '31' 100 -> '89' 800 -> '689' 1060 -> '949' 10270 -> '9159' 100501 -> '89390' ``` **How did I think of this?** Given a fixed number of digits, the output sequence is simply ascending, so there is a fixed delta between input and output. Have a look: ``` 1..10 -> 0..9 (delta -1) 11..110 -> 00..99 (delta -11) 111..1110 -> 000..999 (delta -111) mmm there's a pattern here... ``` But the leading 0s are difficult to manage, so I have a standard trick, add a first digit and work modulo (that is, cut the first digit in output). Then -1-> +9, -11 -> +89, -111 -> +889 and so on. Last step: I don't care what the first digit is, so there is no need to check if the iinput number is < or > than 111... (honestly I found this by trial and error) **Test** ``` var F= n=>(n-~(n+'').replace(/./g,8)+'').slice(1) function update() { var i=+I.value O.textContent = F(i) } update() ``` ``` <input id=I value=99 type=number oninput='update()'><pre id=O></pre> ``` [Answer] # [Marbelous](https://github.com/marbelous-lang/marbelous.py) ~~177~~ ~~173~~ 170 ``` @0@6000000@5 }0&0&0&0&0 >0@6&3 \\--\/&2 @0/\@4\/&1!! @4@1..@2@5@3 IIIIIIIIIIII FF&1FF&2FF&3 @1OO@2OO@3OO :I }1..}10001F7 =9&1++..&1&0 &0}0&1&0{1{1 {>\/{0// :O }0 +Z +C {0 ``` It works for only for values under 256 since Marbelous is an 8 bit language. ## How it works Marbelous is a 2D language with values represented by 8 bit marbles that fall down one cell on each tick unless some device prevents them from falling down. This Marbelous program consists of 3 boards; let's start with the easiest one: ``` :O }0 +Z +C {0 ``` `:O` is the name of the board (to be precise, O is the name and : tells the interpreted that this line is a name. By giving boards a name, other boards can call on them `}0` is an input device, this can be seen as an argument of this function. This cell will get replaced by an input marble (value) when the function gets called. `+Z` adds 35 to any marble that passes over it and lets it fall through. `+C` does the same but only adds 12. `{0` is an output cell, when a marble reaches this cell, the function will exit and return the value in this output device. So all together, this board takes one value and then adds 47 to it. For us this means it turns any single digit number into the ascii code of the digit -1 (this will of course also work for 10). ``` :I }1 .. }1 00 01 F7 =9 &1 ++ .. &1 &0 &0 }0 &1 &0 {1 {1 {> \/ {0 // ``` This board is looking a bit more complicated. You should be able to identify `:I` as the name of the board and have spotted some input and output devices. You'll notice that we have two different input devices, `}0` and `}1`. This means this function takes 2 inputs. You'll also notice that there are two instances of the `}1` device. Upon calling the function, both of these cells will contain the same value. The `}0` input device is directly above a `\/` device, this acts as a trashcan and removes any marble that falls upon it immediately. Let's have a look at what happens to one of the marbles put into the board by the `}1` input devices: ``` }1 =9 &1 &0 {> ``` It will fall down on the first tick and hit the `=9` device. This compares the value oif the marble to 9 and lets the marble fall through if the statement `=9` evaluates to through. The marble gets pushed to the right if not. `&0`and `&1` are synchronizers. They hold on to marbles that fall onto them until all other `&n`synchronizers are filled as well. As you can expect, this will conditionally trigger different behaviour on some other part of the board. ``` }1 00 01 F7 ++ .. &1 &0 &1 &0 {1 {1 {0 // ``` If I tell you that `++` is an incrementor, you should already be able to tell what the different synchronizers will be filled with. The left `&1` will contain the input value `}1` + 1, the `&0` next to it will contain 0 (`00` is a language literal, represented in hexadecimal). The second `&1` will contain the value 1 and the right `&0` gets filled with an `F7`, which subtracts 9 from a value since addition in Marbelous is modulo 256. `//` is a deflector device, which pushes any marble to the left instead of letting it fall down. Putting this all together gives you this: if the marble in `}1` is 9, the `&0` synchronizers get filled. This will cause the value 0 to fall into the `{0` output and `F7` (or -9) into the `{1` output. If `}1` is not 9, `{0` will be filled with `}1` + 1 and `{0` will contain 1. There is also a `{>` device, this is a special output that outputs a marble next to a board in stead of underneath it. This will get filled with `}1` if it equals 9. ``` @0 @6 00 00 00 @5 }0 &0 &0 &0 &0 >0 @6 &3 \\ -- \/ &2 @0 /\ @4 \/ &1 !! @4 @1 .. @2 @5 @3 II II II II II II FF &1 FF &2 FF &3 @1 OO @2 OO @3 OO ``` Okay, now for the big one. This board does not have an explicit name, since it is the main board of the file. Its implicit name is `Mb`. You should be able to recognize some cells. There is an input device, some language literals (`00` and `FF`). There are some synchronizers and there's a deflector. lets step through this piece by piece. ``` @0 @6 }0 &0 >0 @6 \\ -- @0 /\ @4 ``` So the input value (the command line input since this is the main board) starts at the second cell from the top where `}0` is located. It will fall down and reach the `>0` device, which is another comparison device. any marble larger than 0 falls through, any other marble gets pushed to the right. (since Marbelous variables are unsigned, only exactly 0 will get pushed to the right). This zero value marble will then hit the `@6` device. This is a portal and transports the marble to another corresponding portal, in this case right above it. The 0 marble will then reach the `&0` synchronizer and trigger some things elsewhere. If the marble is not 0, it falls down, gets deflected to the right by `\\` hits `--` which decrements it by one and then falls onto `/\`, a cloner. This device takes a marble and outputs one copy of it to the right and one to the left. The left one will be taken upwards to the other `@0` where the marble will go through the same sequence again. The left one will be taken elsewhere. This gives us a loop, which decrements the command line input once per loop and triggers some behaviour on every loop until it reaches 0. It then triggers some other behaviour. Let's have a look at what happens with the marble pushed into `@4` on each loop. ``` @4 @1 .. @2 @5 @3 II II II II II II FF &1 FF &2 FF &3 @1 OO @2 OO @3 OO ``` There are 3 language literals here (`FF`), which will immediately fall into portals. These portals will take them to three of the `II` devices. `II` refers to the board `:I` we defined further down the file. Since `:I` has 2 distinct input devices, it's representation on another board must be 2 cells wide. Since we have 6 cells containing `II`, we cam tell we have 3 instances of this function on the board. The `FF` (or 256 or -1 if you will) marbles will sit in the input cells of the `:I` function waiting untill there are enough input marble sto start the function (one more that is). That's where the `@4` portal comes in. A copy of the decremented command line input falls through there on each loop. This will trigger the leftmost `:I` board. Initialy with the values 256 (or -1) and whatever the command line input was -1. The left marble will be put into the `}0` devices of the `:I` board and the right one into the `}1`. If you recall what this board did, you'll be able to tell what result this has. It will output an incremented version of the right input on the left output (and it turns a 9 into a 0, not 10) and outputs either 1 or -9 on the right. The incremented value will be taken right back to the right input cell by a portal, and the value on the right falls into a synchronizer. If a synchronizer is already holding a marble, the two marbles will collide. Colliding marbles get added together modulo 256. So the values in the synchroizers will do the folowing: They start out empty, then turn to 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and then to 1 again (since 247 gets added modulo 256). You also might remember that a marble gets output to the right when the input value loops back to 0. Since the `:I` boards are right next to each other, thsi will trigger the board to the right once. This will fill the three synchronizers with values that are one higher than they should be to be a shortlex representation of the command line input, by the time this has looped down to 0. You might also remember that the `:O` function turns a value into the ascii value of the digit that represents the value -1. The output of these `OO` cells will then fall off the board, which prints their corresponding ascii chars to STDOUT. ``` 00 00 00 @5 &0 &0 &0 &3 \/ &2 \/ &1 !! @5 ``` So what happens when the command line input marble reaches 0 and fills that `&0` synchronizers? well, a few 0 value marbles fall down and trigger the three synchronizers that are holding the digits (+ 1) of the shortlex number at the bottom of the board. `&3` gets triggered first, since it contain the most significant digit, then comes `&2` followed by `&1`. This marble then gets teleported to the other `@5` device before eventually hitting the `!!` cell, which terminates the board. [Answer] # CJam, ~~14~~ 11 bytes ``` l40f-Ab)s1> ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### How it works This approach is heavily based on [edc65's answer](https://codegolf.stackexchange.com/a/37523) (with [his explicit permission](https://codegolf.stackexchange.com/questions/37515/whats-that-number-in-shortlex/37523?noredirect=1#comment85380_37523)): ``` " Read a line L from STDIN. "; l " edc65's answer now forms an integer N by replacing each digit in L by an 8 and computes L - ~N = L + N + 1. Instead of adding L and N, we subtract 40 from each char code of L. Since the char code of the digit `D` is `D + 48`, this basically adds 8 to each digit. "; 40f- " Turn the resulting array into an integer by considering its elements a base 10 number. This is implemented as A ↦ A[-1] + 10 * A[-2] + 100 * A[-3] + ⋅⋅⋅, so it won't choke on digits greater than the base. "; Ab " Increment the integer on the stack to complete the calculation of L + N + 1. "; ) " Push the integers string representation and discard its first character. "; s1> ``` ### Example run ``` $ for i in 0 1 10 11 42 100 800 1060 10270 100501 > do echo $i: $(cjam <(echo 'l40f-Ab)s1>') <<< $i) > done 0: 1: 0 10: 9 11: 00 42: 31 100: 89 800: 689 1060: 949 10270: 9159 100501: 89390 ``` [Answer] # Python 2 (38) (43) ``` f=lambda n:n*'_'and f(~-n/10)+`~-n%10` ``` No character substitution, just arithmetic. **Ungolfed:** ``` def f(n): if n==0: return '' else: return f((n-1)//10) + str((n-1)%10) ``` I don't have a good reason why the recursion works, I just fit this pattern to the list of values. If you changed each `n-1` to `n`, you'd get the regular digit representation. For golfing, I use `~-n` to compute `n-1` with higher precedence than `/10` or `%10`, saving on parens. The `n*'_'` is just to produce the empty string when `n=0` and any other string otherwise. The `'_'` can be any string for this purpose. [Answer] # Ruby, ~~70~~ ~~68~~ ~~66~~ ~~64~~ 57 bytes ``` f=->n{i=-1;n-=10**i while n>=10**i+=1;i<1?'':"%0#{i}d"%n} ``` Defines a function to be called like `f[42]`. Here is the rough breakdown of the algorithm: * Treat `0` separately. * Subtract powers of 10 until the next power of 10 doesn't fit into the number any more. * Turn the number into a string padded with zeroes on the left. Credits for the idea of using a format string go to Falko! --- Alternatively, using edc65's approach: ``` f=->n{"#{n-~n.to_s.tr('^.',?8).to_i}"[1..-1]} ``` That's **45 bytes** and I'm only including it, because I'm not beating him with it. ;) [Answer] # Haskell, 67 bytes ``` n('9':x)='0':n x n(c:x)=succ c:x n""="0" f x=reverse$iterate n""!!x ``` this solution basically adds 1 the given number of times, in shortlex notation. usage: ``` >f 9 "8" >f 100 "89" ``` [Answer] # CJam, 16 bytes ``` li_)9*,{`1>}%_&= ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") Requires at least O(n) time and memory, so leave 100501 to the offline interpreter... ### How it works The basic idea behind this approach is to compute at least N shortlex decimals in their natural order and discard all but the Nth. Not very efficient, but short. ``` li " Read an integer N from STDIN. "; _)9* " Push M := (N + 1) * 9. "; , " Push A := [ 0 1 ... M - 1 ]. "; { }% " For each I ∊ A: "; {`1>}% " Push its string representation and discard the first character. "; _& " Remove duplicates from the resulting array. "; = " Retrieve the Nth element. "; ``` ### Example run ``` $ for i in 0 1 10 11 42 100 800 1060 10270 100501 > do echo $i: $(cjam <(echo 'li_)9*,{`1>}%_&=') <<< $i) > done 0: 1: 0 10: 9 11: 00 42: 31 100: 89 800: 689 1060: 949 10270: 9159 100501: 89390 ``` [Answer] # Bash+coreutils, 27 bytes Port of [@edc65's clever answer](https://codegolf.stackexchange.com/a/37523/11259), with [@Dennis's improvements](https://codegolf.stackexchange.com/a/37534/11259): ``` cut -b2-<<<$[$1-~${1//?/8}] ``` ### Output: ``` $ for n in 0 1 10 11 42 100 110 111 800 1060 1110 1111 10270 100501; do echo "./shortlex.sh $n = \"$(./shortlex.sh $n)\""; done ./shortlex.sh 0 = "" ./shortlex.sh 1 = "0" ./shortlex.sh 10 = "9" ./shortlex.sh 11 = "00" ./shortlex.sh 42 = "31" ./shortlex.sh 100 = "89" ./shortlex.sh 110 = "99" ./shortlex.sh 111 = "000" ./shortlex.sh 800 = "689" ./shortlex.sh 1060 = "949" ./shortlex.sh 1110 = "999" ./shortlex.sh 1111 = "0000" ./shortlex.sh 10270 = "9159" ./shortlex.sh 100501 = "89390" $ ``` --- *Previous answer:* # Bash+coreutils, 71 54 bytes Here's a slightly different way to do it: ``` jot -w%x $1$1|tr 0-9a a0-9|grep -P ^\\d+$|sed $1!d 2>- ``` * `jot` outputs increasing hexadecimal integers * `tr` converts this to (0,1,...,8,9,b,...f,0a,00,01,...,99,9b,...,ff,0aa,...,000,...) * `grep` simply filters all lines containing digits to give (0,1,...,8,9,00,...,99,000....) * `sed` deletes all but the nth line * STDERR is redirected to a throwaway file '-' so that we simply get the empty string when 0 is passed in (`sed` counts line numbers starting at 1, so errors if 0 is passed) * Because we are filtering numbers out with `grep`, we need to generate more base 11 integers with `seq`/`dc` than the input number. Repeating the digits of n is more than sufficient. Note that once the shortlex number is printed, `seq` continues generating numbers up to `$1$1`, which slow especially for larger input numbers - O(n²), I think. We can speed up by having the `seq` quit immediately after printing at the cost of 7 bytes: ``` jot -w%x $1$1|tr 0-9a a0-9|grep -P ^\\d+$|sed -n $1{p\;q} 2>- ``` There is no speed requirement in the question, so I'm going with the shorter version for my main answer. [Answer] # Python 2 - ~~84, 70~~ 66 ``` n=input() i=0 while n>=10**i:n-=10**i;i+=1 print"%%0%dd"%i%n*(i>0) ``` **Alternative approach (same length):** ``` n=input() k=len(`9*(n+1)/10`) print"%%0%dd"%k%(n-int('1'*k))*(n>0) ``` [Answer] # Python 3, 107 characters This didn't end up winning but I thought it was clever: ``` def G():yield'';yield from(r+c for r in G()for c in'0123456789') S=lambda n:list(zip(range(n+1),G()))[n][1] ``` I define a generator for the entire sequence in 64 characters. Unfortunately, I have to go through some contortions to get the nth element of the generator... if only I could do `S=lambda n:G()[n]`. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 Another port of @edc65's answer, who is the clear winner (IMO): ``` t`+hQv*l`Q\8 ``` ### Test package (Thanks to @DigitalTrauama): ``` $ for n in 0 1 10 11 42 100 110 111 800 1060 1110 1111 10270 100501; do echo "shortlex.pyth $n = \"$(pyth programs/shortlex.pyth <<< $n)\""; done shortlex.pyth 0 = "" shortlex.pyth 1 = "0" shortlex.pyth 10 = "9" shortlex.pyth 11 = "00" shortlex.pyth 42 = "31" shortlex.pyth 100 = "89" shortlex.pyth 110 = "99" shortlex.pyth 111 = "000" shortlex.pyth 800 = "689" shortlex.pyth 1060 = "949" shortlex.pyth 1110 = "999" shortlex.pyth 1111 = "0000" shortlex.pyth 10270 = "9159" shortlex.pyth 100501 = "89390" ``` ### Explanation: ``` Q = eval(input()) Implicit. t` All but the first digit of +hQ Q+1 + v eval( *l`Q len(repr(Q)) * \8 "8" ``` [Answer] # Java 8, 60 bytes ``` n->(n-~new Long((n+"").replaceAll(".","8"))+"").substring(1) ``` Port of [@edc65's amazing JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/37523/52210), since I doubt it can be done shorter in an arithmetic way in Java. [Try it here.](https://tio.run/##hY/BisIwEIbvPsWQ0wRtaGVXhaKw910vHmUPMcYSTaelSV1E6qvXWHtdAskh8/188@csrzKpak3n46VXVjoHP9LQfQJgyOvmJJWG7esJsPONoQIUBgLE8zDswg3HeemNgi0QrKGnZIOUPEj/wXdFBSJNGeOi0bUNti9rkQk2YyvG@QBce3CDGjPe529j3R5sMI7ia2WOUIZe@O6w/wXJx1I353UpqtaLOiBvCUkoTPnQ71@exXhUEDN8zKMrYjtW0USWLuKR@TKeST/T8UPdpOuf) [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` ((g=<<[0..])!!) g 0=[""] g n=[c:s|c<-['0'..'9'],s<-g$n-1] ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0Mj3dbGJtpATy9WU1FRkytdwcA2WkkpFsjIs41OtiquSbbRjVY3UNfTU7dUj9UpttFNV8nTNYz9n5uYmWebks/FWVBaElxS5JOnoKKQpmBoYGRu8P9fclpOYnrxf93kggIA "Haskell – Try It Online") Constructs an infinite list of shortlex numbers and indexes into it for the answer. `g n` constructs the nth "generation" of numbers by prepending the next digit in front of each of the numbers in the previous generation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Uses *edc65's* [replace by 8 trick](https://codegolf.stackexchange.com/a/37523/47066) ``` 8sg×+>¦ ``` [Try it online!](https://tio.run/##MzBNTDJM/V9TVln536I4/fB0bbtDy/5XKh3eb6VweL@Szn8DLkMuQyBhyGViBGQYcFkAsaGBGYgwMgeJmBoYAgA "05AB1E – Try It Online") **Explanation** ``` 8 # push 8 sg× # repeat it len(input) times + # add to input > # increment ¦ # discard the first digit ``` [Answer] # Excel, 37 bytes Using @edc65's approach: ``` =REPLACE(REPT(8,LEN(A1))+A1+1,1,1,"") ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ḃ⁵ịØD ``` [Try it online!](https://tio.run/##y0rNyan8///hjuZHjVsf7u4@PMPl////hgYGpgaGAA "Jelly – Try It Online") I'm very new to Jelly, so if you can improve this, please comment! Explanation: ``` ḃ⁵ịØD Main link. ḃ Convert to bijective base ... ⁵ 10. ị Each number (1 - 10) is converted to the character at its index in the string... ØD “0123456789” (digits) ``` (According to r.e.s.'s comment above, the problem is equivalent to convert the number to bijective base 10) ]
[Question] [ Given integers `N , P > 1` , find the largest integer `M` such that `P ^ M ≤ N`. ### I/O: Input is given as 2 integers `N` and `P`. The output will be the integer `M`. ### Examples: ``` 4, 5 -> 0 33, 5 -> 2 40, 20 -> 1 242, 3 -> 4 243, 3 -> 5 400, 2 -> 8 1000, 10 -> 3 ``` ### Notes: The input will always be valid, i.e. it will always be integers greater than 1. ### Credits: Credit for the name goes to @cairdcoinheringaahing. The last 3 examples are by @Nitrodon and credit for improving the description goes to @Giuseppe. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 74 bytes ``` (({}<>)[()])({()<(({})<({([{}]()({}))([{}]({}))}{})>){<>({}[()])}{}>}[()]) ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0OjutbGTjNaQzNWU6NaQ9MGJAAkqzWiq2tjNTRBPE0IG8SqBRJ2mtU2dkAeWA9QwA7C@v/fSMHEwAAA "Brain-Flak – Try It Online") This uses the same concept as the standard Brain-Flak positive integer division algorithm. ``` # Push P and P-1 on other stack (({}<>)[()]) # Count iterations until N reaches zero: ({()< # While keeping the current value (P-1)*(P^M) on the stack: (({})< # Multiply it by P for the next iteration ({([{}]()({}))([{}]({}))}{}) >) # Subtract 1 from N and this (P-1)*(P^M) until one of these is zero {<>({}[()])}{} # If (P-1)*(P^M) became zero, there is a nonzero value below it on the stack >} # Subtract 1 from number of iterations [()]) ``` [Answer] # JavaScript (ES6), 22 bytes *Saved 8 bytes thanks to @Neil* Takes input in currying syntax `(p)(n)`. ``` p=>g=n=>p<=n&&1+g(n/p) ``` [Try it online!](https://tio.run/##XclBDkAwEADAu1f0JLsRSkviYP2lQRsi2wbx/SJxYa6zmNPswzaHI2c/TtFSDNQ7YupDR5ymVeaAZcA4eN79OhWrd2ChQdAaUQgphUq@p0qEurzzvup/T73Xxgs "JavaScript (Node.js) – Try It Online") [Answer] # Excel, 18 bytes ``` =TRUNC(LOG(A1,A2)) ``` Takes input "n" at A1, and input "p" at A2. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` bḊL ``` This doesn't use floating-point arithmetic, so there are no precision issues. [Try it online!](https://tio.run/##y0rNyan8/z/p4Y4un//FRtZKh5cb6bv//29srKNgqqNgYqCjYGQAokEMIDIBEsYg2hhMm4BVGRqApA0NAA "Jelly – Try It Online") ### How it works ``` bḊL Main link. Left argument: n. Right argument: p b Convert n to base p. Ḋ Dequeue; remove the first base-p digit. L Take the length. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 35 bytes ``` .+ $* +r`1*(\2)+¶(1+)$ #$#1$*1¶$2 # ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYtLuyjBUEsjxkhT@9A2DUNtTRUuZRVlQxUtw0PbVIy4lP//NzbmMgUA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $* ``` Convert the arguments to unary. ``` +r`1*(\2)+¶(1+)$ #$#1$*1¶$2 ``` If the second argument divides the first, replace the first argument with a `#` plus the integer result, discarding the remainder. Repeat this until the first argument is less than the second. ``` # ``` Count the number of times the loop ran. [Answer] # Japt, 8 bytes ``` @<Vp°X}a ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QDxWcLBYfWE=&input=NDAwLDI=) [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` n!p=until((>n).(p^).(1+))(1+)0 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P0@xwLY0ryQzR0PDLk9TT6MgDkgYamtqggiD/7mJmXm2BUWZeSUqXApVmQXhmSUZGoqa0cbGOiYGQGQQG22qY2SgYxT7HwA "Haskell – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes ``` &floor∘&log ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZq@18tLSc/v@hRxwy1nPz0/9ZcxYkgcQ0TAwMdI00419hYx1TzPwA "Perl 6 – Try It Online") Concatenation composing log and floor, implicitly has 2 arguments because first function log expects 2. Result is a function. [Answer] # [C (gcc)](https://gcc.gnu.org/) + `-lm`, 24 bytes ``` f(n,m){n=log(n)/log(m);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI08nV7M6zzYnP10jT1MfROVqWtf@z03MzNPQrC4oyswrSdNQUk1R0knTMDbWMdUEyf5LTstJTC/@r5uTCwA "C (gcc) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 16 bytes ``` (floor.).logBase ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyMtJz@/SE9TLyc/3SmxOPV/bmJmnoKtQkFRZl6JgopCmoKpgrHx/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online") Haskell was designed by mathematicians so it has a nice set of math-related functions in Prelude. [Answer] # [R](https://www.r-project.org/), 25 bytes ``` function(p,n)log(p,n)%/%1 ``` [Try it online!](https://tio.run/##K/qfpmCjq/A/rTQvuSQzP0@jQCdPMyc/HUyr6qsa/k/TMDEw0DHS/A8A "R – Try It Online") Take the log of `P` base `N` and do integer division with `1`, as it's shorter than `floor()`. This suffers a bit from numerical precision, so I present the below answer as well, which should not, apart from possibly integer overflow. # [R](https://www.r-project.org/), 31 bytes ``` function(p,n)(x=p:0)[n^x<=p][1] ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NAJ09To8K2wMpAMzovrsLGtiA22jD2f5qGiYGBjpHmfwA "R – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda a,b:math.log(a,b)//1 import math ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFRJ8kqN7EkQy8nP10DyNHU1zfkyswtyC8qUQCJ/y8oyswr0UjT0MrMKygt0dDU1PxvbKyjYAoA "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes OK, so all those log-based approaches are prone to rounding errors, so here is another method that works with integers and is free of those issues: ``` ->n,p{(0..n).find{|i|p**i>n}-1} ``` [Try it online!](https://tio.run/##Pcw7CoAwEEXR3lUM2KjEMMlEsNGNiI1IIE0IgoWoa4/5qK888O62L4fXg29Hy9xZIee25trY9bzM5ZrGjPZuxe0d6ImIQTdDWAmyiKKQgcQ5iXglUpY@iVSSAWVRr9AvXX594SCYRGAMidAugfwD "Ruby – Try It Online") But going back to logarithms, although it is unclear up to what precision we must support the input, but I think this little trick would solve the rounding problem for all more or less "realistic" numbers: # [Ruby](https://www.ruby-lang.org/), 29 bytes ``` ->n,p{Math.log(n+0.1,p).to_i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp6DaN7EkQy8nP10jT9tAz1CnQFOvJD8@s/Z/gUJatLGxjoJprAIQKCsYcYFETAx0FIwMYsEihlARkBBExAIsYmRipKNgDBExgYoYw0VMIbpgBgNFDMAihgYggwyBZisrGP8HAA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` ìV ÊÉ ``` [Try it online!](https://tio.run/##y0osKPn///CaMIXDXYc7//83MTDgMgIA) --- ## 8 bytes ``` N£MlXÃäz ``` [Try it online!](https://tio.run/##y0osKPn/3@/QYt@ciMPNh5dU/f9vYmCgYwQA "Japt – Try It Online") [Answer] # [Emojicode](http://www.emojicode.org/), ~~49~~ 48 bytes ``` 🍇i🚂j🚂➡️🚂🍎➖🐔🔡i j 1🍉 ``` [Try it online!](https://tio.run/##S83Nz8pMzk9J/f9hfn@jwof5ve1cCiBqWVppXvJ/ED/zw/xZTVkg4tG8he939INYQPG@R/OmfZg/YcqH@VMWZipkKRgCxTr/g/TOaFAACYJMWasAMkbB0MDAAEgAERdYFQA "Emojicode – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 2 bytes ``` ⌊⍟ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHPV2Peuf//2@qkKZgbMxlZACkTQy4jMCUAQA "APL (Dyalog Unicode) – Try It Online") Pretty straightforward. `⍟` Log `⌊` floor [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` Lm¹›_O ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJ/fQzkcNu@L9//83NDAw4DI0AAA "05AB1E – Try It Online") [Answer] # [JavaScript](https://nodejs.org), ~~40~~ 33 bytes *-3 bytes thanks to DanielIndie* Takes input in currying syntax. ``` a=>b=>(L=Math.log)(a)/L(b)+.001|0 ``` [Try it online!](https://tio.run/##Zc5NCoMwEAXgfU/hcoZSM/kRuokn0ENEq/1BjFTpyrunmYKljW/7wXvv4V5ubp/3aTmN/tKF3gZny8aWUNnaLbd88FcEh6KCBo85kVwptH6c/dCxQQ9aIxSIWYwQmTr8qyEERR@OKnfKvOk5UWUUgt7U7FT/aJE2f0@xUqKSeFjyr6g6vAE) [Answer] # Pari/GP, 6 bytes ``` logint ``` (built-in added in version 2.7, Mar 2014. Takes two arguments, with an optional third reference which, if present, is set to the base raised to the result) [Answer] # Python 2, 3, 46 bytes *-1 thanks to jonathan* ``` def A(a,b,i=1): while b**i<=a:i+=1 return~-i ``` ## Python 1, 47 bytes ``` def A(a,b,i=1): while b**i<=a:i=i+1 return~-i ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 22 bytes ``` m=>f=n=>n<m?0:f(n/m)+1 ``` [Try it online!](https://tio.run/##LY/BDsIgDIbve4oeAVEZjMQZmQ@ycFjmXDTCzLb4@pOWHUj6/f1o4d39uqWfX9/1GKfHsI1uC655uuiaeAt3dX2yeA78UG7rsKwLOGgLgLaSYCUoL6E1hmqNdaVSkU6JoCstITWrDIbAZg09CReEuq7TBbVPKBX2EI2XuEkLYfWxJN/muZhk1tkxQhhycAc5lGTeHSuEJgffSg4lmbUvfFHQD0@h@zLWRglBwuw5uAb6KS7TZzh9ppGNLHAWU@xg5nz7Aw "JavaScript (Node.js) – Try It Online") Curried recursive function. Use as `g(P)(N)`. Less prone to floating-point errors than [using `Math.log`](https://codegolf.stackexchange.com/a/162720/78410), and (I believe) the code gives correct values as long as both inputs are safe integers (under `2**52`). [Answer] # [Haskell](https://www.haskell.org/), ~~35~~ 34 bytes ``` n!p=last.fst$span((<=n).(p^))[0..] ``` Thanks @Laikoni for saving 1 byte [Try it online!](https://tio.run/##DcJBCoAgEADAr6zQQUFEtG75jg5i4KFQsmXJPfV5a5iS@3W0NgYKCi13NmfnqVNGKdeAykjalYrWmDTuXBEC0FORYYK30la5gBQKovd6tn@bIC7aWe3S@AA "Haskell – Try It Online") [Answer] # [J](http://jsoftware.com/), 5 bytes ``` <.@^. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bfQc4vT@a3JxpSZn5CuYKqQpGBtD2EYGQI6JAZQDZhtw/QcA "J – Try It Online") [Answer] ## Wolfram Language (Mathematica) ~~15~~ 10 Bytes ``` Floor@*Log ``` (requires reversed order on input) Original submission ``` ⌊#2~Log~#⌋& ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 35 bytes ``` : f swap s>f flog s>f flog f/ f>s ; ``` [Try it online!](https://tio.run/##TcxBCoAgFIThvaf4L1CJ2qbAu0TwbBEYGnR8s0XZ6s3HDE9iOrcuyHNKmRDytRxkL8geQwsyID4zF2thpA571qScBqObNObrjDPYV1TaRuX4vSk3 "Forth (gforth) – Try It Online") Could save 5 bytes by swapping expected input parameters, but question specifies N must be first (an argument could be made that in a postfix language "First" means top-of-stack, but I'll stick to the letter of the rules for now) ## Explanation ``` swap \ swap the parameters to put N on top of the stack s>f flog \ move N to the floating-point stack and take the log(10) of N s>f flog \ move P to the floating-point stack and take the log(10) of P f/ \ divide log10(N) by log10(P) f>s \ move the result back to the main (integer) stack, truncating in the process ``` [Answer] # Pyth, 6 4 bytes ``` s.lF ``` Saved 2 bytes thanks to Mmenomic [Try it online](http://pyth.herokuapp.com/?code=s.lhQe&input=400%2C+2&debug=1) ## How it works `.l` is logB(A) To be honest, I have no idea how `F` works. But if it works, it works. `s` truncates a float to an int to give us the highest integer for `M`. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 9 bytes ``` |_.sS log ``` Example usage: ``` (|_.sS log)[1000 10] ``` # Explanation Verbose version: ``` floor . sS log ``` This is written pointfree style. `sS` passes list items as arguments to a function (in this case, `log`). [Answer] # [Gforth](https://www.gnu.org/software/gforth/), 31 Bytes ``` SWAP S>F FLOG S>F FLOG F/ F>S . ``` ## Usage ``` 242 3 SWAP S>F FLOG S>F FLOG F/ F>S . 4 OK ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf@NTIwUjP8HhzsGKATbuSm4@fi7Ixhu@gpudsEKev@BAAA "Forth (gforth) – Try It Online") ## Explanation Unfortunately FORTH uses a dedicated floating-point-stack. For that i have to `SWAP` (exchange) the input values so they get to the floating point stack in the right order. I also have to move the values to that stack with `S>F`. When moving the floating-point result back to integer (`F>S`) I have the benefit to get the truncation for free. ## Shorter version Stretching the requirements and provide the input in float-format and the right order, there is a shorter version with 24 bytes. ``` FLOG FSWAP FLOG F/ F>S . 3e0 242e0 FLOG FSWAP FLOG F/ F>S . 4 OK ``` [Try it online!](https://tio.run/##S8svKsnQTU8DUf@NUw0UjEyMUg3@u/n4uyu4BYc7BihAmPoKbnbBCnr/gQAA "Forth (gforth) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ ~~7~~ 4 bytes ``` Lt`B ``` [Try it online!](https://tio.run/##yygtzv6fe2h5arFGsdujpsb/PiUJTv///4/WMDbWMdXU0TAx0DEyANNABpA2MjHSMQbTxmDaBKzK0AAobWigGQsA "Husk – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 61 bytes ``` i(n,t,l,o,g){for(l=g=0;!g++;g=g>n)for(o=++l;o--;g*=t);g=--l;} ``` [Try it online!](https://tio.run/##RczJboMwFAXQdfMVN1RINhjJGNPJcvMTWXYTMViWwKDALsq3U5uhXTw9v2PdW2WmqpbFEsdm1rGBGfpohzvptNFcnU2aKqPNt6MBB52mnRqyTJlEz9T/ZFmnnstr3bTWNbj6FowMPcV4t25uSWRJLGuGWNQUOizoy7pIPNEfFzFsEbtGqc/@vaE1elwQjbdpauoIX4gSN8wJdqDq1N@sI/RxerkSoCgYUPoRdAPJGYQf5BtIHg7h52MDIcMRYvKAYody74DcS/kKOQ8deegpVpD8s9xK8/yAtx3EAe//8Fx@AQ "C (gcc) – Try It Online") ]
[Question] [ I have this problem where I listen to so much music that I can never remember what songs are called. But even if I remember the lyrics, I won't always know the song's name. But lucky for me, there's a pretty neat formula to determine¹ the title of a song just based on its lyrics. I'll define the way a song title can be guessed as the line repeated in its lyrics the most times. If multiple lines are repeated the same number of times, choose the shortest of them. If multiple lyrics both occur the same number of times and are of equal length, you may choose any of them. Given an input of a multiline string where each line is a lyric (you may take input as a list of lines), output the predicted title of the song, using the method outlined above. For example, say this totally real song was stuck in my head and I couldn't remember its name: ``` Hello, world Hello, world I just got to say it, hello world Goodbye, world Goodbye, world Goodbye ``` I can figure using this formula that the song's title is "Hello, world". You may assume that the input string will contain no empty lines. ## Test cases: * [Love Me Do](https://pastebin.com/D6QLhLTq) → "Love, love me do" * [God Only Knows](https://pastebin.com/JuJj0wzK) → "God only knows what I'd be without you" * [Never Gonna Give You Up](https://pastebin.com/K7KubkBC) → "Never gonna give you up" * [All Star](https://pastebin.com/QfqySUJr) → "Get the show on, get paid" OR “Get your game on, go play“ Links go to pastebins of the lyrics, with any `"` removed. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ¹ Accuracy not guaranteed. No refunds. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` é.M ``` Input as a list of lines. [Try it online](https://tio.run/##yy9OTMpM/f//8Eo93///o5U8UnNy8nUUyvOLclKUdNC5ngpZpcUlCun5JQol@QrFiZUKmSU6ChkgRXA17vn5KUmVqToEBZRiAQ) or [verify all test cases](https://tio.run/##7Vhbbtw2FN0K6x/ZwKRbCNIadaZImo8EMALDH5R0JbEjkQJJWdBfV1Og6@hOuhH33EtJM564zaNB0sT58HiGPLy87wdd0Lmh25vp9s8/vn9@u7m9ujp5Sm3rNmp0vi1PNsc/t@rXIURVu6iiU0FPysSNahi0Yi6cK/OJNm9dOLneqKuTZ@4GWy0@VUeqdNh/7Qa1s25U27Q@uYHvztpW6XbUU1A5qegHwupLp/qWdDimcel0c7T06W566TpyllhHvD6v5K6clKXxHwG80prdwsbXqJnX9MZSQrl3QTYTvtgsMjcHW4@TJ21VB4e08M2ZwwPGfxgiftpa6aBiQ56Uxl@I2gel8z2OxbZ0Qx6fVLJ9SjfkEW6@SN/pZCAVEAADE8rdMAMuXKmcbSfRXFBjo6PaZiWrajSxYdysxyqRwFJbKrkPChR5WE7EE0Q3FY4JIESDm2sH4hsQaw0t0FcNpbBSRUI2MBlU0BjICu672T7CSo24mym25oYRJSMevw/nL9hQzjX4eo7EUN77xwp3I1gdmkf5fV/U6d3DZ2KidwS/06G3nj6k8gDs9rmA6vRyv3H2Hsfu4s6@XfgVXChp@pIyZE2L7Bm9tjUhA@/L4Fp2kKSVH1pCerYl51q4/BaAJ6oaEFOF6zoTO7IxW@/vFIfPjuPDVTMtiRquGDVF3g6q8q4DzUk5rgOqHqZ9XzNqa7WKCGPhn2OSyVaE0LW1CB6j3peAwZZgP4JD7P0i6aB2TKI2NzOiP9ppKemmdKM92vKDRVVyICoylxTIL8F2iFuvL/x0tMUdWT13V3d3RChcb0iIN8NKGvYAs6x0q0gXzayYynlWOxfNpEuPPk971ndOBE4LyVX5ENM2GzU6WBVFeu0NWbU2mBJ@QSoH4WRcNthCp3ZiMCuc7G1f6y5xOoq7JCH6dqH6BDsmJWMddtwGvGmsc2kVRPBOFLawmAMgtT0QfcGG@1L5PpUe4oDjs39bPLtH0s3co@1XGHzxEQ9/kUHxkLPYN74/Jd9SyNeZ1tmC3RztKdwzrp0tiu3MopMULB6qjSRlgEKjfU@BXxJcq4ydF4m98CUT0TzBOannO07YrlLl0OXSYiiJRsPtQ@IM/2ODXQmuhX5PfEhblT3LwKWaQ5gQs@XarzN2Ih4EeRyM3FqAR6GKrWXiDNH18xZO/pRmw7tNylY1JolWJ3vANDbhz400IWKDQDaQjKnc9rDJOatUg10ySu6hJG5YwFHHHOWpn5JcU6aNMomKCaEbkJ1kTt1walp@ptI2TxDcI3mefkV1UYtOmdFcFzu0YQSSj@eMBVOl/ChZZ66xSQcYZE4vH42PRpySuekOPiD10dGB1o3yiMRjOUayuQbDIBrHWN2cjWiWTrIbT0q1k6R230n4UrE7PJksDU7lIBZ6bdi2p9wh8C1RJqjWxMidpvhkWzLzL7gxxVEX2dzpKSD3pHdCs3PpwYt1p2F4uCh4KlA9VsdI2TzZowCc/D7p57B/CycZ@sT/qIHMMA6KdpjP5QC/TMiFFAl@gJYWJUBmwNJUlUB@HspaysokyMa1tMaL5hA1kVRvijj4ZbY0hVSXsMO@CE1RxOw9vkzSKC9TKBA@2yNG7Tt2JOazM3UT@clk5DwQRtPh0PMpxTfOIKQq46ETNkCWz32/F196lfxO0gEUtU0vW9CChMrebVgXOWKy/GyO8p@d5MJJCKcV6GQfJDD8Ybx8KPDelf9/VNVJYX/99vvhC6hUCzTtVG5U9qO8amxV6OU9DhhVNDwVirS1Flfaro9xzEo3BWqR1dmrZJiTsU6CMxNwAK8g/Zr6TRoNOX5xaZ96pPTgMgSSwhYjgqkaqF3pSns1o1jUO8jEXPateHxQ8bhw3z2MsvFRyFxf/w0). **Explanation:** ``` é # Sort the (implicit) input-list by their length (shortest to longest) .M # Pop and leave the (first/shortest) most frequent line # (which is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` Þṡ∆M ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwiw57huaHiiIZNIiwiIiwiW1wiSGVsbG8sIHdvcmxkXCIsXCJIZWxsbywgd29ybGRcIixcIkkganVzdCBnb3QgdG8gc2F5IGl0LCBoZWxsbyB3b3JsZFwiLFwiR29vZGJ5ZSwgd29ybGRcIixcIkdvb2RieWUsIHdvcmxkXCIsXCJHb29kYnllXCJdIl0=) ``` Þṡ # Sort by length ∆M # Get the most common item (order overrides repetitions) ``` [Answer] # Excel (ms365), 74 bytes [![enter image description here](https://i.stack.imgur.com/1k3x6.png)](https://i.stack.imgur.com/1k3x6.png) Formula in `B1`: `=LET(x,TEXTSPLIT(A1," "),@SORTBY(x,MAP(x,LAMBDA(y,SUM(-(x=y)))),,LEN(x),))` * `TEXTSPLIT(A1," ")` - Split input in an horizontal array called 'x'; * `SORTBY(x,MAP(x,LAMBDA(y,SUM(-(x=y)))),,LEN(x),)` - 1st Sort by count, then by length (both ascending by default); * `@` - Use implicit intersection to only return the 1st element in the resulting array. [Answer] # [Python](https://www.python.org), ~~49~~ 43 bytes ``` lambda a:max(sorted(a,key=len),key=a.count) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=7VU9j9QwEC2R8itGaTYRy9UI6YqTkE7bQImQrnHWkw_WmVnZ4w35LTQrIfhP8GsYO3vAHqKDYnVXxZrneX7znhV_-rqfpWc6fm6v775EaV-8_PbcmbGxBsyr0XysAntBW5n1Dudrh1TnhbnaciSpl5bvz8zeDyRVW5Vl-Q5XHoEYgnhDHfoAwuD4gMV7jrAjnkB6BB8dBjBkITBYhk1xA210DrY8joOMSLIKMPVGYLMatWWg3UAdcJt5Jo7O0kqgQ0lggNbzqHwzsNJ76OJcbOBDDAKTITIgqOSztvaqIFG2iE4Zi1sWMTCaHWY4klXRosqKN3hITJzau-Fwwvdndafnp7Llic4AHwmMV59sntJiQJ-3nu36eezWz2dAMLOu2DYzntXzGHrsgJm2jydS9V0FJnsJ0Gz7kw0t-2SwYx1UffPQo_HJ2QZR9W375GkTJYEpOGFNrp9TZknBIMWGwmARJoRGKZcAUyz3HB3nWEgV_Eq3M-Oib8rXYZG-dwvjjdaHNk9twg5058NIXnOKNo86ZnvupTUK2ywO8aLiuSSt1Vvu17-rrP9Wqv-Yaw30oFJUt_-g7YKu92P66zxp_S9a9R29Cns3SFXeUVnXp5f2eFy-PwA) Takes input as a list of lines [Answer] # [J](http://jsoftware.com/), 28 17 bytes ``` {.@\:%@#&>+1#.=/~ ``` [Try it online!](https://tio.run/##7VNda9RAFH2fX3Haomkwja0PQqO1pYptoCBYYSlYZNKZ3Uk7yZVksiEI/vX1TrLaRla7LyIVH2aSe@8593uuF/sbyd7l841kPwjEZhxMcZAgQIRdJHx2Yrx@f/Z28SU@@pg8Otp6/OrJ3lZ88PTrIhT6yhCmePki/vQMl56wK061tRShpcqqsZDiuqkdZuTgCLXskLsIxkOWiBMilXU6@q0oVsc9ozkjLd8oNBSJC2pwU1KLdNB21Ig0sBbStrKrkWm4qtHinPDZalmP2ROSZqT40/7PqdBUat8ar@3ljFSHUrcrjV62@c0Q@KFXf6F/UgwIug9lOv6UgfPx7xgOf7EkKQpeu5I3cJnmj9yPG8dCOYOs4YyuNCSf2smqhsy@o3zVpZ7rim@t/DgUNZnjRR6KL@QwD9S84I13klHTm09IgUrb9U2r0RrpkAbK96nNnfGovoXTgc4Kq9BH4u71ZYkJvxSuPp8ypTfXLueYM2LHETuyuR6AH4wengyuBpzhOXHRJuf6OOeiH0ufwozf1NKbzeferrz9cN183/kJERnxhp@5WnnEMbWcXmN2slU/2B5TQx7FmtA1KPdyb338oxP6GzBsT24N4dqkMS78H@wBBgsX3wA "J – Try It Online") *-11 thanks to [l4m2's idea](https://codegolf.stackexchange.com/a/256505/15469). Also thanks to l4m2 for pointing out an improvement!* Consider: ``` Hello, world Hello, world I just got to say it, hello world Goodbye, world Goodbye, world Goodbye ``` In J we take the input as a list of boxed strings: ``` ┌────────────┬────────────┬─────────────────────────────────┬──────────────┬──────────────┬───────┐ │Hello, world│Hello, world│I just got to say it, hello world│Goodbye, world│Goodbye, world│Goodbye│ └────────────┴────────────┴─────────────────────────────────┴──────────────┴──────────────┴───────┘ ``` * `=/~` Create an equality table to see which lines equal other lines: ``` 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 0 0 1 ``` * `1#.` Sum the rows (resulting length is now equal to input length): ``` 2 2 1 2 2 1 ``` * `%@#&>+` And add the reciprocals of each line length elementwise: ``` 2.083 2.083 1.0303 2.071 2.071 1.1429 ``` * `{.@\:` Use that result to sort the input descending, and take the first: ``` ┌────────────┐ │Hello, world│ └────────────┘ ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 61 bytes ``` x=>x.sort(g=(a,b)=>a?(x.map(b=>b!=a?x:0)+a).length-g(b):0)[0] ``` [Try it online!](https://tio.run/##7Vhbb9xEFH73r5g@eVdsoj6D0qilIiwq9KGVogiQMraP7enaM5ZnHMdv/Bp@WP9I@M4Z7263KUpEKZDSh714zmXO/eI3@kr7vDddOLKuoJvSuZOb65Mn18fe9WFRnSz0KluePNGni@vjVneL7ORJ9uhEn15//Xj5lV4eN2SrUB9Vi2yJk58f/3rzTe6sdw0dN65agN/i8oW7opVq8K1aUoVLLtygNtaNah1PJzck67RplG5GPXmVkQr9QMkrp7qGtD@kPne6Pjj41PxfuZacBY2TU3nOXDEpS@MHgfzcmE28@KFrf0HvHUQMdxdWPeHHpoHvfwdwennsu8aEy1/s5XKZJLfDZa1aDdu6sBV4p8WzIeDBVkp7FWrqSWl8fNC9VzrbYrH@lq6oxzcV7JjCDVlQJkQztDp6Rnmn/MBMMjcI@MwVytlmEvN5NdY6qHVasMVGE2rGEmOWkRwHTaHkJthRFEzOqWlgB1OCRMA@GNxZOTBegVFjKCK@rhmjB0Ye8Wp4DErXBvpB5lYcJCJUDnJFbo25YnjB8NP7yvuSfeVcnTx3K5B@6JM8cyPEG@qj7EN/1OKQdAlX3BP1HiR30u55fKYe@jfQ1OJ8D1jem@gQb/nlsod32Z0V@JxSlEWL8hh6bStCed22t11zQf1V/dAQKq8tuJQi4tfJU1UOSKbcta0JLdmQ7sRqFWfOhpPDlcJHEoY7REWBgV6VvWvBb1KOy7uqhilZqzeDD2rU1moVkLuiEqcisywJ@WorWCIEva/sgy0gdIBkyU@S/ZVj8spczfDu4LyhaKjCjfYA0A8WLcaBnWhZkKc@5ti7WLtr8346AHj0MS4N2UQH56IGrjUkbOthZgq7Q0A2r1Wk83o2Q@l6NjB3PrZbr2rSPVs2I4J8uRSkbAgMZMcFB8@h/cJnLAH3PetNgaAglYFldCC7ZcujcuIWCwn23q10G@UbJRyi6F0TOT7FuYlVVvsNt/b3XfJcmr@o2op5tqJlAEtb9kQPyj0PSdaFNP13pFz@2dHyll6reXzanySLs7@B7AGF9/@p6nyR9ZPIemeX3a2RzuYc1RgeEZFhN3WiH85yO6mhCEptpKYCxde67wghimxolLHzIRXJK2ageWty0mw3XG1dqYqhzWQsUJJ0hvt6FBi/oQYUebTl3RGTaKvSFynkU3OeElKzmCdoxpyIVy9ewAL3fEgnHAHaLn8@uG4GJd/Fbexwclir2kSVqugaeMky9nMjs4G4w5P1JCshzyHsdy4a5WBjwch6GIanCMjSsixZnHyklBQRwOrzvN4OKDyyE6646mwfuRfN0zyPLD1vmWKsoMWKLGCm8w0mIgK7UylGcEsseVJU5nYY9cY6sTg/Go9G0GBvOcD2qGj0HnrjxuR74rUX69DcLGF@DSI2b3JGs0ZStnhTqZxUq9tUiJd8s6eKHoV8QoSDTpsiWXADZ@5B9hcEauAxT2KuKZbJSx4XQeYCOzWu2FlPeiP8WuAka7aUhnMRgJAkRwPYOT8W5mj5HMjUb6t3Bh83CIShi1KPGngpVjCxBssX0XnXl6soEHyNWRK1XPauwpQlEH4Yiko6wyR4NXJrlweac9IEUp3JA1Z82eVMLi3CbwAVRSmIcl2PP5NMp3HnA7xP9/BR9y2HCsvXmqoO/Pph5KT3o2mTH6eYr6BAopSmhx3Y3Gk2z989ouV1jCtJbphmHV8PQXNJgX1osP4Z8qz4h4PhowLhzEk6xmfYYB/4cO8@B/4a2q3n/2qWVNE4b3/7PTms7JiPqVip9Ft5P7BWvpO3VsBRec3rlehXaYTJevfKikVoJ08NqjBHjGxGsiNJqqVA9ZAQbC@oW8Udi3MRF3Y8vsRXFoMn6UwhIDnKgZodT5l7ZixW8AAzipV@KfT3LPRn7tHnWeI/nsXBFHTzBw "JavaScript (Node.js) – Try It Online") Sort `<different lines>*(<input length>-1)+<element length>` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 38 bytes ``` s->vecsort(s,a->[[1|l<-s,a!=l],#a])[1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN9WKde3KUpOL84tKNIp1EnXtoqMNa3JsdIFsRducWB3lxFjNaMNYqOqWYgVbhWglj9ScnHwdhfL8opwUJR0FDL6nQlZpcYlCen6JQkm-QnFipUJmiY5CBkgVQpF7fn5KUmWqDhEiSrFcBUWZeSUaaRrFmpoQtyxYAKEB) Based on [@l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/256505/9288). Takes a list of lines. --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 46 bytes ``` s->vecsort(matreduce(s)~,a->#a[1]*I-a[2])[1,1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN_WKde3KUpOL84tKNHITS4pSU0qTUzWKNet0EnXtlBOjDWO1PHUTo41iNaMNdQxjobpaihVsFaKVPFJzcvJ1FMrzi3JSlHQUMPieClmlxSUK6fklCiX5CsWJlQqZJToKGSBVCEXu-fkpSZWpOkSIKMVyFRRl5pVopAFdqAlxy4IFEBoA) Takes a list of lines. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Æṃ'LÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Odzeo@h@c93LHo/8PdWw63///vAZTK11Eozy/KSeFC4XgqZJUWlyik55colOQrFCdWKmSW6ChkgJRAVbjn56ckVabq4OUCAA "Jelly – Try It Online") For some reason, Jelly's mode atom insists on vectorising over a list of lines, so we need `'` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as an array of lines. ``` ü üÊÌcÌñÊ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&header=tw&code=/CD8ysxjzPHK&input=IldlJ3JlIG5vIHN0cmFuZ2VycyB0byBsb3ZlCllvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8gSQpBIGZ1bGwgY29tbWl0bWVudCdzIHdoYXQgSSdtIHRoaW5raW5nIG9mCllvdSB3b3VsZG4ndCBnZXQgdGhpcyBmcm9tIGFueSBvdGhlciBndXkKSSBqdXN0IHdhbm5hIHRlbGwgeW91IGhvdyBJJ20gZmVlbGluZwpHb3R0YSBtYWtlIHlvdSB1bmRlcnN0YW5kCk5ldmVyIGdvbm5hIGdpdmUgeW91IHVwCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bgpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91Ck5ldmVyIGdvbm5hIG1ha2UgeW91IGNyeQpOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZQpOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQpXZSd2ZSBrbm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nCllvdXIgaGVhcnQncyBiZWVuIGFjaGluZyBidXQKWW91J3JlIHRvbyBzaHkgdG8gc2F5IGl0Ckluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJlZW4gZ29pbmcgb24KV2Uga25vdyB0aGUgZ2FtZSBhbmQgd2UncmUgZ29ubmEgcGxheSBpdApBbmQgaWYgeW91IGFzayBtZSBob3cgSSdtIGZlZWxpbmcKRG9uJ3QgdGVsbCBtZSB5b3UncmUgdG9vIGJsaW5kIHRvIHNlZQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cApOZXZlciBnb25uYSBsZXQgeW91IGRvd24KTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkKTmV2ZXIgZ29ubmEgc2F5IGdvb2RieWUKTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UKTmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXAKTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duCk5ldmVyIGdvbm5hIHJ1biBhcm91bmQgYW5kIGRlc2VydCB5b3UKTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5Ck5ldmVyIGdvbm5hIHNheSBnb29kYnllCk5ldmVyIGdvbm5hIHRlbGwgYSBsaWUgYW5kIGh1cnQgeW91CihPb2gsIGdpdmUgeW91IHVwKQooT29oLCBnaXZlIHlvdSB1cCkKKE9vaCkKTmV2ZXIgZ29ubmEgZ2l2ZSwgbmV2ZXIgZ29ubmEgZ2l2ZQooR2l2ZSB5b3UgdXApCihPb2gpCk5ldmVyIGdvbm5hIGdpdmUsIG5ldmVyIGdvbm5hIGdpdmUKKEdpdmUgeW91IHVwKQpXZSd2ZSBrbm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nCllvdXIgaGVhcnQncyBiZWVuIGFjaGluZyBidXQKWW91J3JlIHRvbyBzaHkgdG8gc2F5IGl0Ckluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJlZW4gZ29pbmcgb24KV2Uga25vdyB0aGUgZ2FtZSBhbmQgd2UncmUgZ29ubmEgcGxheSBpdApJIGp1c3Qgd2FubmEgdGVsbCB5b3UgaG93IEknbSBmZWVsaW5nCkdvdHRhIG1ha2UgeW91IHVuZGVyc3RhbmQKTmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXAKTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duCk5ldmVyIGdvbm5hIHJ1biBhcm91bmQgYW5kIGRlc2VydCB5b3UKTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5Ck5ldmVyIGdvbm5hIHNheSBnb29kYnllCk5ldmVyIGdvbm5hIHRlbGwgYSBsaWUgYW5kIGh1cnQgeW91Ck5ldmVyIGdvbm5hIGdpdmUgeW91IHVwCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bgpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91Ck5ldmVyIGdvbm5hIG1ha2UgeW91IGNyeQpOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZQpOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cApOZXZlciBnb25uYSBsZXQgeW91IGRvd24KTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkKTmV2ZXIgZ29ubmEgc2F5IGdvb2RieWUKTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3Ui) ``` ü üÊÌcÌñÊ :Implicit input of array ü :Group & sort by value ü :Group & sort by Ê : Length Ì :Last element c :Flat map Ì : Last element ñ :Sort by Ê : Length :Implicit output of first element ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 7 bytes ``` vOÞMİÞg ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJQIiwiIiwidk/Dnk3EsMOeZyIsIiIsIltcIldlJ3JlIG5vIHN0cmFuZ2VycyB0byBsb3ZlXCIsIFwiWW91IGtub3cgdGhlIHJ1bGVzIGFuZCBzbyBkbyBJXCIsIFwiQSBmdWxsIGNvbW1pdG1lbnQncyB3aGF0IEknbSB0aGlua2luZyBvZlwiLCBcIllvdSB3b3VsZG4ndCBnZXQgdGhpcyBmcm9tIGFueSBvdGhlciBndXlcIiwgXCJJIGp1c3Qgd2FubmEgdGVsbCB5b3UgaG93IEknbSBmZWVsaW5nXCIsIFwiR290dGEgbWFrZSB5b3UgdW5kZXJzdGFuZFwiLCBcIk5ldmVyIGdvbm5hIGdpdmUgeW91IHVwXCIsIFwiTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duXCIsIFwiTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdVwiLCBcIk5ldmVyIGdvbm5hIG1ha2UgeW91IGNyeVwiLCBcIk5ldmVyIGdvbm5hIHNheSBnb29kYnllXCIsIFwiTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3VcIiwgXCJXZSd2ZSBrbm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nXCIsIFwiWW91ciBoZWFydCdzIGJlZW4gYWNoaW5nIGJ1dFwiLCBcIllvdSdyZSB0b28gc2h5IHRvIHNheSBpdFwiLCBcIkluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJlZW4gZ29pbmcgb25cIiwgXCJXZSBrbm93IHRoZSBnYW1lIGFuZCB3ZSdyZSBnb25uYSBwbGF5IGl0XCIsIFwiQW5kIGlmIHlvdSBhc2sgbWUgaG93IEknbSBmZWVsaW5nXCIsIFwiRG9uJ3QgdGVsbCBtZSB5b3UncmUgdG9vIGJsaW5kIHRvIHNlZVwiLCBcIk5ldmVyIGdvbm5hIGdpdmUgeW91IHVwXCIsIFwiTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duXCIsIFwiTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdVwiLCBcIk5ldmVyIGdvbm5hIG1ha2UgeW91IGNyeVwiLCBcIk5ldmVyIGdvbm5hIHNheSBnb29kYnllXCIsIFwiTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3VcIiwgXCJOZXZlciBnb25uYSBnaXZlIHlvdSB1cFwiLCBcIk5ldmVyIGdvbm5hIGxldCB5b3UgZG93blwiLCBcIk5ldmVyIGdvbm5hIHJ1biBhcm91bmQgYW5kIGRlc2VydCB5b3VcIiwgXCJOZXZlciBnb25uYSBtYWtlIHlvdSBjcnlcIiwgXCJOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZVwiLCBcIk5ldmVyIGdvbm5hIHRlbGwgYSBsaWUgYW5kIGh1cnQgeW91XCIsIFwiKE9vaCwgZ2l2ZSB5b3UgdXApXCIsIFwiKE9vaCwgZ2l2ZSB5b3UgdXApXCIsIFwiKE9vaClcIiwgXCJOZXZlciBnb25uYSBnaXZlLCBuZXZlciBnb25uYSBnaXZlXCIsIFwiKEdpdmUgeW91IHVwKVwiLCBcIihPb2gpXCIsIFwiTmV2ZXIgZ29ubmEgZ2l2ZSwgbmV2ZXIgZ29ubmEgZ2l2ZVwiLCBcIihHaXZlIHlvdSB1cClcIiwgXCJXZSd2ZSBrbm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nXCIsIFwiWW91ciBoZWFydCdzIGJlZW4gYWNoaW5nIGJ1dFwiLCBcIllvdSdyZSB0b28gc2h5IHRvIHNheSBpdFwiLCBcIkluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJlZW4gZ29pbmcgb25cIiwgXCJXZSBrbm93IHRoZSBnYW1lIGFuZCB3ZSdyZSBnb25uYSBwbGF5IGl0XCIsIFwiSSBqdXN0IHdhbm5hIHRlbGwgeW91IGhvdyBJJ20gZmVlbGluZ1wiLCBcIkdvdHRhIG1ha2UgeW91IHVuZGVyc3RhbmRcIiwgXCJOZXZlciBnb25uYSBnaXZlIHlvdSB1cFwiLCBcIk5ldmVyIGdvbm5hIGxldCB5b3UgZG93blwiLCBcIk5ldmVyIGdvbm5hIHJ1biBhcm91bmQgYW5kIGRlc2VydCB5b3VcIiwgXCJOZXZlciBnb25uYSBtYWtlIHlvdSBjcnlcIiwgXCJOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZVwiLCBcIk5ldmVyIGdvbm5hIHRlbGwgYSBsaWUgYW5kIGh1cnQgeW91XCIsIFwiTmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXBcIiwgXCJOZXZlciBnb25uYSBsZXQgeW91IGRvd25cIiwgXCJOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91XCIsIFwiTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5XCIsIFwiTmV2ZXIgZ29ubmEgc2F5IGdvb2RieWVcIiwgXCJOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdVwiLCBcIk5ldmVyIGdvbm5hIGdpdmUgeW91IHVwXCIsIFwiTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duXCIsIFwiTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdVwiLCBcIk5ldmVyIGdvbm5hIG1ha2UgeW91IGNyeVwiLCBcIk5ldmVyIGdvbm5hIHNheSBnb29kYnllXCIsIFwiTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3VcIl0iXQ==) ## Explained ``` vOÞMİÞg vO # [input.count(item) for item in input] ÞM # indices of maximal items İ # indexed into the input Þg # shortest by length ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 40 bytes ``` O` O^$#` $.& O^$#`(.+¶)(?=(\1)*) $#2 1G` ``` [Try it online!](https://tio.run/##7ZTPatwwEMbveoqBLFm7CYH0XkqgsOwleyyBUlZejS1lZU3QnzV@sT5AX2w7kjdtnZJbe1iam5nRfPrN9wl7jMbJ43GzFZuvi4utWNxcTl/VzdX3b3X18UP15bZ@V4vFxXtxu9oej59x6REcQYheug59gEhg6YDigRLsHQ0QNYJPFgNIpyAQKIK1uIM2WQs76nsTe3RxGWDQMsJ62fOIcXvjOqC26AyUrHLLCB3G3AzQeupZbwRieQ9dGsUaHlOIMEjnJERk8ZFHNRNkyRbRsqJYUYwSernH0k5OMXRkMnGPh6xEebwzh1P/aVa3fH8uKxrcrOGTA@mJ5cqWCgP6cnR26ue1Oz/OGkGO/EWqGXFWL2vwtQaLrE4nUfadAbO9DlDu9MmGlnw22BIvyr550Ch9drZBZL6dzp42KeZmDi4SJ6fHnFkmMFGsXTAKYUBoWHIKMMfyrNFRicUxwa90O9lPfEN5DhP6k50U77hu2rK1DHvgky8j@UQ52rJqX@x5Rmu4rQoc4lnFc06s1Yb09e@U9Wul@o@9rsG9qIhq9RfGzuh5/09/nTfWf8P6Aw "Retina 0.8.2 – Try It Online") Takes input as a list of newline-terminated strings. Explanation: ``` O` ``` Sort everything. ``` O^$#` $.& ``` Sort order of length, then reverse the result. The reverse in the next sort will then bring the shortest line of equal occurrence count back to the front. ``` O^$#`(.+¶)(?=(\1)*) $#2 ``` Sort by count of subsequent occurrences. Only one of each of the most frequent lines will actually sort last, but that doesn't matter because we only need one of them. The sort is stable, so the most frequent lines remain sorted in descending order of length. The result is then reversed, bringing the shortest most frequent line to the start. ``` 1G` ``` Keep only the first line. [Answer] # [Scala 3](https://www.scala-lang.org/), 40 bytes ``` s=>s.maxBy(l=>(s.count(Set(l)),-l.size)) ``` Returns a tuple from the comparison key, which are ordered lexicographically. [Attempt This Online!](https://ato.pxeger.com/run?1=fY6xbsIwGIR3P8WvLPyWjJcuqJIj2qXtnBEYXOKAqz82jf8AAfECfYUuWdp34m0aBEsXpruTPt3d929aWrIP_VlNa-uDKF0FF4MSDBzF1jZQPRbuc1Zw48NqYfKn0Jmflqvx5IzJ5EnXdv_cIZkck17GNjAWjpGkVGPSyR-clDf-azN0MAWsMMsy8eqIooJdbKj8H97go00Mq8jAEZLtwLOC9QW5ES8xlu-dU3cjgBh29PC81mlDnnE0DyMppThdH_X9Vf8A) [Answer] # [Factor](https://factorcode.org/), ~~62 61~~  60 bytes ``` [ [ length ] sort-with dup histogram '[ _ at ] supremum-by ] ``` [Try it online!](https://tio.run/##lVHBasMwDL3nKx6@9JL2A9YP6HrZZewUynAcJ/EaW6ktU9yRb8@c5TK6sTGBhJ70ENJTKxWTn1@ej0@HBwR9idopHSBDIBVgJfe7wJJNYJPx6DVzGr1xjECejetw1t7pAa1P2BfvBbKtcTHxqIeBSlzJD434s3zEWwyMjhhMCDLBcIl@IX/jHoiaOuny3421Mq2bQkgBUWdXN3EHljDdH9QSfRlZS/8Luv2EpmKaK1QYtOu4x@lTyO3V5LyJI/osNXVeWmwqvELywohZeBvttk44zVaOyD9R5938AQ "Factor – Try It Online") * `[ length ] sort-with` Sort by ascending length. * `dup histogram '[ _ at ] supremum-by` Find the most frequent element that is encountered first. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 49 bytes ``` ($input|group|sort C*,{-$_.Name.Length})[-1].Name ``` [Try it online!](https://tio.run/##fY5BCsIwFET3OcVfBKOSFjyAKLhQQbyAFak2bSOxPyS/lNL27LGKLty4fI9hZiw2yvlSGRO4aZ2@eVjCWrDdaFBCg85kv7CHe@0JCiQgBJ@2oEnCqwE/iS1idm2V/ItMrCHy1mgCkbhVUgnGeD6Od2HKdWVr6guHte09OoLNXHYRv8TH9KHig6oKKofZKVqc3yYM7Hu@hwnwPDwB "PowerShell – Try It Online") Input comes from the pipeline. `$input` is an automatic variable that enumerates all input that is piped to a function. The lines are passed to the cmdlet `Group-Object` which groups identical lines into GroupInfo objects with the properties Count and Name (the original line). The objects are then `sort`ed first by the Count property (how often a line was found), and then the negative (so both Count and Length can be sorted ascending) length of the line. Then the last element of the sorted array `[-1]` is taken, and its Name property returned. Output is implicit. Will return "Woah, love me do" (same length as "Love, love me do") for the Beatles because of the ascending sorting. [Answer] # [Go](https://go.dev), 140 bytes ``` import."strings" func f(s string)(O string){m,M:=-1,make(map[string]int) for _,l:=range Split(s,"\n"){if M[l]+=1;M[l]>m{O,m=l,M[l]}} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=1ZLBSgMxEIbBY55i2Et3MRXqSSqr54Klwh6k1GLTNtuGTTJLkrUsS9_AN_CyCD6Ej2Kfxt3GghXBkwcvmfzfzGQm8D-_rLB-y9kiYysOiglNhMrRuLMgVS54LVzavXh_OjDrjNArG5C00AtIQwueROHocKsUHfbjbo8qlvFQsXziE1OhXURSNPBAZT82TDcDk1wKF1oa3OsgqkQKw4mcnsa9yzZeqWpEVSxpK7ZbYrgrjN76nXYn5_sd2pXDCCpi-_HsBh85BdmcoDgskYyxgEzjBgaelliQQUdKYHLDSgtzDs4UnCQIueTMHnffIVsfgb9-P0HFUTc9uKd7PcdlCZpvfky2WorMD_7vvx_zb8BX4G9V67IJuuPa-V8S1zNCbhvnOanDxqlRRD6tU9c-fgA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` WS⊞υι≔Eυ⟦№υι±Lι⟧θ§υ⌕θ⌈θ ``` [Try it online!](https://tio.run/##7VRNj9MwEL3nV8ytjlR@wZ4qEKtI7LISB4QQBzeexKaOp7XHzebXl7G7C3QRNzhUkFM0z/P8PqL0VseetD@dZus8gurCPvMHji6Mqm3hISer8hpce9NsUnJjUHd6XyafX1MOfMbWcI@jZlTvMIxslWvbLzI8yNKDMLHacBcMPpbTb10w6rCGO/3opjypQyvPzen0EVcRIRAkjjqMGBMwgacjNp8owy7QDGwRYvaYQAcDicAQdM0Ghuw99DRNjicMvEowW83QrSZZcWEnZoCGyjNT9iasGEbkAiYYIk3CtwAJfYQxL00HX3NimHUIGhiFfJFVKwoK5YDohbG5JWYNk95hhbM4jIlFWXOPx8JEZX10xyd8fzH3cn8ZG5rDBRBzAB0lXFNdGkwY69GLU9@v7eNyASS9yBuZ7YIX82pDrnVYaW1@IpXcRWCJNwDq3j7FMFAsAXsSo5JbBIs6lmS3iKKvtyXTbeYCluKYpDm7lM6KAsdNF5IzCDPCVijPBZZanjlGqrUEUfCj3VFPZ31z/RzO0vf@zLiRuRuqa512ICdfVvKGSrXV6lTjeZa2FdhUcYhXVc81aVXvya5/Vtn@btT@4msN4cWkUbd/YO2KPu9/6a/zX@vf0Xp6dfTfAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: Port of @mousetail's original Python answer. ``` WS⊞υι ``` Input the lines of the song. ``` ≔Eυ⟦№υι±Lι⟧θ ``` Get the count and negated length of each line. ``` §υ⌕θ⌈θ ``` Output the line that has the maximum value of that. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-r`, 15 bytes ``` @Y-(_Ng)AE#_SKg ``` The `-r` flag reads the program arguments from lines of stdin rather than command-line args. [Attempt This Online!](https://ato.pxeger.com/run?1=zVZPbx01ED-zn2JUDgGpuXMrfSVpXkAlUlpFqKqq2fW8t-567ZXtfcty5GtwqYTgyvfh0_Abe1PgEuAA4pJk7Rl75vdnnB9-nOz08-tH5_HRm_c_zflw_tkvn39z_snbF8dPn158_Pb2y2Nd3Tbf__rR93taOJGJ9mT9kYKn3AsdosjCK9ntk1Mmx16aO5t7YorcWkNLcCeJ1ovGjSvN3khchGNz14unNBsj3q2IP84rtdJbb2iU-1Nb7oYknJubME1iKNpjn2meiBHWzWWtt4l6fCfiLoaU9BpZJTV7nCkpIQQRNtMr3zmhy8h-oBDpWZgTrvkqzFaeNPsSsgutbl0H0V937LLEJw0indHtVmhnnSshdmy-jnRh9GMn0duScpvlpKfRFEPLLTpbSnLPJ6FBpqzwlbIAZbObM3Eb8DP3jB8WnS9CXeTUa9k-ByCT49wNzVN0DBb2ZyNgXpWI1okY_QNIRbnnhdPUo-7m0np2uH9PUbpw9PY72YjqEHtQlK4s8O0tGWEnykigzIMkbB8KrGgiISfbjpydUkE9i3PAWJoLELvmXgtYw0yDD4sCvcSgnTkwVz57m-WxUoYPExZfDkl9iFlXnAZra_Ln03IfZlDd3KHldzOklQLZcUIW-4xzJPmzTCNnEPRwJdeafQjxKLn0v4RoaidKAXGtAKRqqgeiBNCLTFPWKJsePr-aY2E3FCpCuWSwuVN9415UDlafBweh0_PIPY-pin8PwXYWy7kQlbIUPVfWgZOKz3MWMtCFTzb4glQKQXP1Vm7N3GXktGu9hp1FJLwZRkqTMr2AVFRmGFCHAaHODkLXPEKvlxxj87IXJENh2FMljmrpcrPq_Mg-lVuzhmUcUS-6CY5jsKZuJobVt5LIcITEQ8Cy8nUvXCadFhBequqF4uFD4FkrgOQg4gJ-hkNLqqpspzoqgKw0BVSmowHazCGu1TX7zWIdwwSIPIYNJuz0XCoHGFLnSrsd53RcveznmAyq8jpWmlvN6MpZExYBxNQHTK62WN4Xe1Y5ZaWvmMkFztqNsUnGNhirA0lwKxp9FqAtcXTLRU0gmKOStcJB6v7_wkCFk_-3gV7vfcKIG4sPaBeFhzebq0rh24AMKNY6yMiJ1lwWMOhPWMuL9feWOgZkkAe9oI8nBHZz1eAC2B_Xc-AALshR1VFBs9nnkm39QYqptPg9KaUqDa1Zh68S4ZXjE-5b9K27ZZXljWhV7VowmvDCwdJHuLc6xOYzjNX2ZPHoIPkDAcWNmvFC-jjTO5Au22ugl-lLqVK5kg9zd3sq4JkzPCm1XRPxoEC6Bq9v6RIHAqZUX1K0fFXLhYlgwvLsAKmNzxgwLLx8m--Hlw82YQhgeIz6PMABOsYwo0hb9DavvwuO1D56yIyxo1OoA3_jX6r71T9U85y20YCVoUjjj3JuvtjQxN06SauqtdsxRIwQ6RgHlN4Sklx5BDUaikLZCui_bYG_cclDm_V_sd8A) ### Explanation ``` @Y-(_Ng)AE#_SKg g ; Lines of stdin (due to -r flag) SK ; Sort ascending according to this key function: _Ng ; Number of occurrences of this line in the input list -( ) ; Negated AE ; Placed in a list with #_ ; Length of the line Y ; No-op, necessary for parsing @ ; Get the first element of the sorted list ``` [Answer] # [Arturo](https://arturo-lang.io), 41 bytes ``` $[a][minimum arrange a=>size=>[size--a&]] ``` [Try it](http://arturo-lang.io/playground?fOTa7L) ``` $[a][ ; a function taking an argument a minimum ; get minimum element of arrange a=>size ; input sorted by ascending length =>[ ; by size ; length of -- ; set difference between a ; input & ; current line ] ; end minimum ] ; end function ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes ``` ŢṂaş ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FiuOLnq4synx6PwlxUnJxVDBBTdLopU8UnNy8nUUyvOLclKUdBQw-J4KWaXFJQrp-SUKJfkKxYmVCpklOgoZIFUIRe75-SlJlak6RIgoxUIsBwA) ``` ŢṂ Maximum by count aş Minimum by length ``` [Answer] # Mathematica, 59 bytes [Try it online!](https://tio.run/##7VZda9tAEHzXr1gcqBswlL42GBIaCIb0A/pQihDlJK10V0u74T6sitLf7u6dbCeI0KdCMeTN1szOzc6cjXrlNfbKm0rt9821@v5u/Z77ngmdz79gh5XP1eoeqfU6vyjW6w/qZz59fXOtildFkedvi@Jq75jaeyNjsIZf2eIrLi0CMThvFbVoHXiGjne4WGWLbxxgSzyAHA42dDKlqAbHUDNsIuMGmtB1UIkX43skv3QwaOVhs@xlytDWUAvcHNUGDl1NSw8t@og7aCz3ojoCyyEW2jBG7gZ@BOdhUEQKPMoRo0xrsRKFG8ROdCPxjr1X0KstJkagWnbw4jKCH3EXJTmKtGZ3oDzMoU68RKTmgeaYDQTKsuim1Wt0aBN7TjxZqOw4x5wa5RPX5YhzKO0mFgwmfR0e1aUbsRzzJ0BV6UNCDdvYQMdTAJKqBY3KxuhLRLFb6Rh6GfwBjxV7lo71GNuNbkzCNuRMjTAglKI9VR3bOyq1nNqjyc3jVWhVP9kd0vWZNnnoTro3ApkmpaHcFoT8THO3HO9B2r9PyR1tlsKok1HE82/xvN2//sR69dT35d@fXj638gpo9iTR7/7x/Pn@Xl7@7V7c/zf32e@rLPtsDfm8yU@vB0Wx/wM) ``` f@a_:=Commonest[Select[a,Length[#]==Max[Length/@a]&]][[1]]; ``` ]
[Question] [ [Sexy Primes](http://en.wikipedia.org/wiki/Sexy_prime) are pairs of numbers \$(n, n+6)\$ such as \$n\$ and \$n+6\$ are both prime You need to create a function which will take an integer, check for sexy primes from 0 to that integer, and return an array of arrays. For example, `listSexy(30)` must return `[[5,11], [7,13], [11,17], [13,19], [17,23], [23,29]]` or some equivalent. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the program with the shortest bytecount wins! [Answer] # MATLAB 32 ``` i=1:n;i(isprime(i)&isprime(i+6)) ``` n is your number [Answer] ## J, 34 33 31 32 39 37 characters ``` s=.[:(,.-&6)[:I.1([:*/p:)"1 i.,.6-~i. ``` Lost a character keeping both primes below the limit...and another 7 declaring a function. Usage: ``` s 100 11 5 13 7 17 11 19 13 23 17 29 23 37 31 43 37 47 41 53 47 59 53 67 61 73 67 79 73 89 83 ``` **Edit** Seems like a lot of the new answers are not creating functions, taking input or limiting both numbers in the pair to be below `n` - if I ignore those restrictions too I can get down to **28 characters**: ``` (,.6&+)I.*/"1[1 p:(i.,.6+i.) ``` [Answer] ## *Mathematica*, 35 ``` {#,#+6}&~Array~#~Cases~{__?PrimeQ}& ``` [Answer] ### GolfScript, 32 characters ``` ~),2>{:P{(.P\%}do(!},:L{6+L?)},p ``` Since the output format was not specified, the code above will print the lower prime of each pair. Thus a number `x` is included if `x` and `x+6` are both prime and both are below `n`. Input is given as single number on STDIN. ``` > 150 [5 7 11 13 17 23 31 37 41 47 53 61 67 73 83 97 101 103 107 131] ``` [Answer] # [Python 2](https://docs.python.org/2/), 137 132 126 122 118 ``` f=lambda x:not[y for y in range(2,x)if x%y==0] i=30 print [(x,y)for x in range(i)for y in range(i)if f(x)&f(y)&x-6==y] ``` [Try it online!](https://tio.run/##XcuxCoNADADQ3a/IUrmAglhwKORLxOHEpg3YnBw3JF9/4lRwf@/w8k061sq0x9@6RbCXpjI7cMrgIAo56ucdxs5QGOzhRMPSCD2H5siiBeZgnePF7c8Fb1@uzcGw5eDYWj8R@VLrCQ "Python 2 – Try It Online") Using list comprehensions, as well as the fact that `[] = False` `f(x)` actually returns all the factors of `x`, and you can then work out prime-ness from that. [Answer] ## C, 102 99 95 chars Returning an array in C is something you try to avoid. So the function `s` gets the limit `n` and a pointer to an array of integers, and fills it with the data. Each pair of sexy primes is placed in two positions in the array. So `o[0]=5`, `o[1]=11`, `o[2]=7`, `o[3]=13`. The function assumes the array is large enough. ``` x=7,l; p(){ return++l>=x/2||x*(x-6)%l&&p(); } s(int n,int*o){ for(;l=++x<=n;)p()?*o++=x-6,*o++=x:0; } ``` [Answer] # [K3 / Kona](https://github.com/kevinlawler/kona), 45 ``` {a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/x!'2_!x}'!x} ``` . ``` {a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/x!'2_!x}'!x}100 (11 5 13 7 17 11 19 13 23 17 29 23 37 31 43 37 47 41 53 47 59 53 67 61 73 67 79 73 89 83) ``` And the same solution in the current incarnation of K which is identical to the K3 solution except for the fact that it does not have an inbuilt mod operator, which adds about 14 chars for 59 ``` {a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/{x-y*x div y}[x;2_!x]}'!x} ``` [Answer] ## Python (~~93 90 99~~ 95) Yay for quick and dirty `isprime` functions! ``` a=lambda x:all(x%i for i in range(2,x));b=2 while b<input(): b+=1 if a(b)&a(b+6):print b,b+6 ``` [Answer] ## x86-Assembly (78 Bytes) This example uses Intel syntax. Besides, here the `fastcall` or `register` calling convention is used (the latter from 32-bit Delphi), so the parameter is in `ecx`. I also introduce a second parameter that points to a free space for the result and is saved in `edx`. A function for allocating memory space would be specific to the operating system and a transfer via the stack would be problematic, so I chose this option. ``` listSexy: mov ebp, esp ; 89E5 Save initial esp mov edi, edx ; 89D7 Save second parameter in edx ; Part One: Save all prime numbers from 3 to the limit on the stack ; (This takes 32 Bytes) xor eax, eax ; 31C0 set eax = 1 (shorter than mov eax, 1) inc eax ; 40 checkComplete: add eax, 2 ; 83C002 Go to next possible number (first is 3) cmp eax, ecx ; 39C8 Has the limit, i.e. the parameter, been skipped? jae partTwo ; 7316 mov ebx, esp ; 89E3 Check it against all previous prime numbers checkNext: ; which are stored between ebp and esp cdq ; 99 Clear edx for the later division push eax ; 50 Put the number on the stack cmp ebx, ebp ; 39E5 Has the check already completed? je partTwo ; 74F1 The comfirmed prime number remains on stack mov esi, [ebx] ; 8B33 Load a previous prime div esi ; F7F6 pop eax ; 58 test edx, edx ; 85D2 Is esi a divider? je checkComplete ; 74E8 add ebx, 4 ; 83C304 Let ebx point to the next possible divisor jmp checkNext ; EBEC ; Part Zwo: Check all prime numbers if they are sexy primes ; (This takes 39 Bytes) partTwo: mov ebx, ebp ; 89E5 Start with the first prime number, i.e. 3 NextPrime: sub ebx, 4 ; 83EB04 Let ebx point to the next prime number cmp ebx, esp ; 39E3 Has the last number been reached? It cant be sexy, ; since it has no successors here jmp Finished ; 761E mov edx, ebx ; 89DA Check all successors up to a distance of 6 mov eax, [ebx] ; 8B03 eax is the prime number whose successors are checked add eax, 6 ; 83C006 GoFurther: sub edx, 4 ; 83EA04 cmp eax, [edx] ; 8B02 jb NextPrime ; 72EB If the successor is too large, x can no longer be sexy ja GoFurther ; 77F7 If the successor is too small, take the next one mov eax, [ebx] ; 8B03 Load eax again (shorter than sub eax, 6) mov ecx, [edx] ; 8B0A Load the successor which makes eax a sexy prime mov [edi], eax ; 8907 Store both in their intended place mov [edi+4], ecx ; 894F04 add edi, 8 ; 83C708 jmp NextPrime ; EBDB Finished: mov esp, ebp ; 89EC Restore stack ret ; C3 ``` The opcodes (and thus the size of the instruction) are given in the comment. The function can be called from C with, for example ``` int n = 100; int resultList[50] = { }; listSexy(n, resultList); ``` The result list should be initialized with zero, since no final null byte sequence or similar is written into. Online working example: <http://tpcg.io/mEPb1Wy9> [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÅPãʒÆ7+ ``` [Try it online](https://tio.run/##yy9OTMpM/f//cGvA4cWnJh1uM9f@/9/EHAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w60BhxefmnS4zVz7f63O/2hDAx1jAx0Tcx1z01gA). **Explanation:** ``` ÅP # Push a list of primes smaller than or equal to the (implicit) input-integer ã # Create all possible pairs by taking the cartesian product with itself # (which will include inverted duplicates - i.e. both [5,11] and [11,5]) ʒ # Filter this list of pairs [a,b] by: Æ # Reduce it by subtracting: a-b 7+ # Add 7 # (only 1 is truthy in 05AB1E, so this will keep pairs that satisfy a-b+7==1) # (after which the resulting list of pairs is output implicitly) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 10 bytes *-2 thanks to @Fatalize* ``` ≥Iṗ-₆ṗ;I≜ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HnUs@HO6frPmpqA1LWno865zzctuD/f2OD/1EA "Brachylog – Try It Online") ### How it works ``` ≥Iṗ-₆ṗ;I≜ᶠ ᶠ find all … ≜ force number-finding of constraints that fulfill … (strictly not necessary, but otherwise constraints will be returned) ≥ any number less than the input I assign it to I ṗ must be prime -₆ṗ minus 6 must also be prime ;I append I again (so we have [I-6,I]) ``` [Answer] **Perl: 73 char** ``` sub p{(1x$_[0])!~/^(11+?)\1+$/}map{$x=$_+6;p($_)&&p($x)&&say"$_,$x"}2..<> ``` **usage:** ``` echo 30 | perl -E 'sub p{(1x$_[0])!~/^(11+?)\1+$/}map{$x=$_+6;p($_)&&p($x)&&say"$_,$x"}2..<>' ``` **output:** ``` 5,11 7,13 11,17 13,19 17,23 23,29 ``` [Answer] # Octave 39 Modified my MATLAB answer to comply with the new (annoying) rules. `n` is your value. ``` p=@isprime;i=1:n;[j=i(p(i)&p(i+6));j+6] ``` Can be tested [here](http://www.online-utility.org/math/math_calculator.jsp) [Answer] ## R, 83 characters ``` f=function(n){library(gmp);p=isprime;for(i in 1:n)if(p(i)&p(i+6)){print(c(i,i+6))}} ``` Usage: ``` f(150) ``` [Answer] ## Ruby ~~75~~ 74 The new version uses [Artem Ice](https://codegolf.stackexchange.com/users/4878/artem-ice)'s prime test method: ``` z=->x{(9..x).map{|i|[i-6,i]}.select{|a|a.all?{|r|(2...r).all?{|m|r%m>0}}}} ``` Online test: <http://ideone.com/yaOdn> [Answer] # Ruby, 99 88 86 84 82 78 ``` f=->x{(9..x).map{|n|[n-6,n]if[n,n-6].all?{|t|(2...t).all?{|m|t%m>0}}}.compact} ``` Sample output: `[[5, 11], [7, 13], [11, 17], [13, 19], [17, 23], [23, 29], [31, 37], [37, 43], [41, 47], [47, 53], [53, 59], [61, 67], [67, 73], [73, 79], [83, 89]]` [Answer] # J, 25 chars ``` (#~*/"1@p:~&1)(,+&6)"0 i. ``` `i.n` creates a range of [0,n) `(,+&6)"0` takes each integer `n` in the list and makes a pair `n, n+6` `(#~ condition)` is basically a `filter`, and the condition in this case, `*/"1@p:~&1`, just checks if a pair is composed solely of primes. [Answer] # C# (279 characters) Basically, it's Saumil's solution with a couple of tweaks. I don't have ~~enough~~ any reputation for commenting though, so... ``` using System;namespace X{public class P{static int l=100;static void Main(){F(0);}static bool I(int n){bool b=1>0;if(n==1){b=1<0;}for(int i=2;i<n;++i){if(n%i==0){b=1<0;break;}}return b;}static void F(int p){if((p+6)<=l){if(I(p+6)&&I(p)){Console.WriteLine(p+6+","+p);}F(p+1);}}}} ``` **Output:** ``` 11,5 13,7 17,11 19,13 23,17 29,23 37,31 43,37 47,41 53,47 59,53 67,61 73,67 79,73 89,83 ``` [Answer] ## JavaScript (~~140~~ 113 Characters) `t=(i,n)=>{for(n=i;n%--i;);return 1==i};s=(n,p)=>{for(p=[],i=2;i<n-6;i++)if(t(i)&&t(i+6))p.push([i,i+6]);return p}` Try `s(30)`. Updated to use the shorter primality test from [here](https://codegolf.stackexchange.com/a/91309/5000), and to use the new arrow notation. *Old version (140 characters):* `function t(n,i){for(i=2;i<n;i++)if(!(n%i))return!1;return!0}function s(n,p){for(p=[],i=2;i<n-6;i++)if(t(i)&&t(i+6))p.push([i,i+6]);return p}` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes Outputs in reversed order, because the K3 answer also seems to do that. ``` LεD6-‚}ʒpP ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f59xWFzPdRw2zak9NKgj4/9/QwAAA "05AB1E – Try It Online") # Explanation ``` L Length range ε Map: D Duplicate 6- Minus 6 ‚ Pair } Reverse the pair ʒ Filter: p Is_prime P in both items ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Rż+¥6ẒẠ$Ƈ ``` [Try it online!](https://tio.run/##ASwA0/9qZWxsef//UsW8K8KlNuG6kuG6oCTGh/8sw4fFkuG5mCRLKVn//zMwLCA0Nw "Jelly – Try It Online") ## How it works ``` Rż+¥6ẒẠ$Ƈ - Main link. Takes N on the left R - Range; R = [1, 2, ..., N] ¥6 - Previous 2 links as a dyad f(R, 6): + - Add 6 to each element in R ż - Zip together $Ƈ - Keep those pairs for which the following is true: Ạ - Are all elements... Ẓ - ...prime? ``` [Answer] # Excel, 131 bytes ``` =LET(x,SEQUENCE(A1),y,TRANSPOSE(x),z,x*(MMULT((MOD(x,y)=0)*1,x^0)=2),a,IFERROR(INDEX(z,x+{0,6}),),FILTER(a,MMULT(SIGN(a),{1;1})=2)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnC1DBGDIMcR3NdvZ?e=mhqbY1) ## Explanation * `=LET(` allows defined names within formulas. * `x,SEQUENCE(A1),` x = `1..A1` listed vertically. * `y,TRANSPOSE(x),` y = `1..A1` listed horizontally. * `(MOD(x,y)=0)*1` creates a matrix this is 1 if x mod y = 0 and 0 otherwise. * `MMULT(~,x^0)` sums the elements of each row with matrix multiplication. `x^0` is a vertical matrix of 1s. * `z,x*(~=2),` if the sum = 2 then `x` is prime and `z=x` else `z=0`. * `,a,IFERROR(INDEX(z,x+{0,6}),),` creates an array `a` where the first column is `z` and the second is `z` offset by 6 rows. * `FILTER(a,MMULT(SIGN(a),{1;1})=2)` returns the rows of `a` that have no zeros. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~104~~ 75 bytes *-29 bytes thanks to @emanresuA* ``` g=x=>--x>6&&g(x,(f=(n,t=2)=>t<n?n%t&&f(n,t+1):n>1)(x)*f(x-6)&&print(x-6,x)) ``` [Try it online!](https://tio.run/##FYpBCsIwEABf47KrSbEKRcTEuwc9@IJSTIiUTWmWsr4@trdhZr790pdhTpPY5VJrdOq8teo7gIhqMDhkI@5EzsuN77wTgLCpQ0tX9i2h0j6g2o4ApjmxbGyUqA6ZSx4/zZgjPt6vZ1Nk7TGFH0Y8H2ld/g) [Answer] ## C# 295 ``` using System;using System.Linq;namespace K{class C{public static void Main(string[]a){Func<int,bool>p=i=>Enumerable.Range(2,i-3).All(x=>i%x>0);Console.WriteLine("["+String.Join(",",Enumerable.Range(0,int.Parse(a[0])).Where(i=>i>9&&p(i)&&p(i-6)).Select(i=>"["+(i-6)+","+i+"]").ToArray())+"]");}}} ``` Online test: <http://ideone.com/4PwTW> *(in this test I've replaced `int.Parse(a[0])` with the actual int value, as I cannot supply command line arguments to programs running on ideone.com)* [Answer] # Mathematica - 69 48 chars Assuming m has been assigned a value ``` p=PrimeQ;Cases[Range@m,n_/;p@n&&p[n+6]:>{n,n+6}] ``` [Answer] # Scala (82) ``` def p(n:Int)=9 to n map(x=>List(x-6,x))filter(_.forall(l=>2 to l-1 forall(l%_>0))) ``` Sample output: `Vector(List(5, 11), List(7, 13), List(11, 17), List(13, 19), List(17, 23), List(23, 29), List(31, 37), List(37, 43), List(41, 47), List(47, 53), List(53, 59), List(61, 67), List(67, 73), List(73, 79), List(83, 89))` [Answer] # Factor 140 This language is fun and interesting. My first script. ``` :: i ( n -- ? ) n 1 - 2 [a,b] [ n swap mod 0 > ] all? ; :: s ( n -- r r ) 11 n [a,b] [ i ] filter [ 6 - ] map [ i ] filter dup [ 6 + ] map ; ``` Usage: ``` ( scratchpad ) 100 f --- Data stack: V{ 5 7 11 13 17 23 31 37 41 47 53 61 67 73 83 } V{ 11 13 17 19 23 29 37 43 47 53 59 67 73 79 89 } ``` [Answer] **PARI/GP (62 characters)** ``` f(a)=w=[];forprime(x=0,a,isprime(x+6)&w=concat(w,[[x,x+6]]));w ``` Example: ``` (00:01) gp > f(a)=w=[];forprime(x=0,a,isprime(x+6)&w=concat(w,[[x,x+6]]));w (00:01) gp > f(30) %1 = [[5, 11], [7, 13], [11, 17], [13, 19], [17, 23], [23, 29]] ``` [Answer] # Haskell (65 chars) ``` p n=[(x,x+6)|x<-[3..n-6],all(\k->all((>0).mod k)[2..k-1])[x,x+6]] ``` The output: ``` Prelude> p 100 [(5,11),(7,13),(11,17),(13,19),(17,23),(23,29),(31,37),(37,43),(41,47),(47,53),( 53,59),(61,67),(67,73),(73,79),(83,89)] ``` --- **About the [MATLAB answer here:](https://codegolf.stackexchange.com/a/6468/5021)** *(I spent all my rep on a bounty so can't comment just yet)*. Google says: " the Matlab's isprime function ... is based on the probabilistic Miller-Rabin". So it seems that the MATLAB entry should be disqualified. [Answer] ## R ~~85~~ 81 characters ``` f=function(n){m=2:n;a=m[rowSums(!outer(m,m,`%%`))<2];cbind(b<-a[(a+6)%in%a],b+6)} ``` Example run: ``` f(50) [,1] [,2] [1,] 5 11 [2,] 7 13 [3,] 11 17 [4,] 13 19 [5,] 17 23 [6,] 23 29 [7,] 31 37 [8,] 37 43 [9,] 41 47 ``` ]
[Question] [ Given a non-empty list of integers between 1 and 9 inclusive, find the longest contiguous sublist such that the number of occurrences of each element (of the sublist) within the sublist is equal (*not* the number of consecutive occurrences, just the total count). You may return any non-empty subset of the solutions. ## Examples ``` Input -> Output 1, 2, 3 [1, 2, 3] 1, 2, 2, 3, 3, 4 [2, 2, 3, 3] 1, 2, 3, 3, 4, 4, 3, 3, 2, 1 [3, 3, 4, 4], [3, 4, 4, 3], [4, 4, 3, 3] 1, 1, 1, 1, 1 [1, 1, 1, 1, 1] 1, 2, 3, 2, 1 [1, 2, 3], [3, 2, 1] 1, 2, 3, 4, 4, 3 [1, 2, 3, 4], [3, 4, 4, 3] 3, 2, 3, 4, 4, 3 [3, 4, 4, 3] ``` * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden, as usual * I/O may be in any reasonable format. You can do I/O with a string of digits since all inputs will be between 1 and 9, for example (this is mostly to allow regex solutions if anyone can figure that out). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 7 bytes ``` ⊇.ọtᵛ&s ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3w/1FXu97D3b0lD7fOViv@/z862lDHSMc4VkcBzAAygdAEwlUw0lEwBiMTMIKwgYKGUHkEQtFghC4A1a4AEjRGE4yNBQA "Brachylog – Try It Online") `s` generates all sublists of consecutive elements, though not in order of length, but in order of prefix (so `[1,2,3] [1,2] [1] [2,3] [2] [3]`). `⊇` on the other hand does generate longer sets first, but only guarantees element order, not that they are consecutive. So we check that later for +1 byte. ``` ⊇.ọtᵛ&s The (implicit) input [1,1,2,3] ⊇ has an (ordered) subset [1,2,3] . that is the output, ọ which elements grouped&counted by identity [[1,1],[2,1],[3,1]] tᵛ have the same number of occurences. 1 & The input [1,1,2,3] s has consecutive elements [1,2,3] that is the (implicit) output. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` ẆĠẈEƊƇṪ ``` [Try it online!](https://tio.run/##y0rNyan8///hrrYjCx7u6nA91nWs/eHOVf8f7lz8qGFu9MMdix7umP@ocVuYzuF2laOTHu6c8ahpTdajhjkKunYKQBVcD3dvOdwOFIv8/99QR8FIR8FYATeIhiqJ5YIwQGwwMsGiFiEPUw5VC0YQNlDQEKocIRmrA@ZB1YF4CC1goxAIpysRCMlyI3w6jKB2QdUhaYPajkUbkisB "Jelly – Try It Online") ## How it works ``` ẆĠẈEƊƇṪ - Main link. Takes L on the left Ẇ - All non-empty contiguous sublists of L, longest last ƊƇ - Keep those sublists S for which the following is true: Ġ - Group the indices of S by the elements Ẉ - Length of each E - All equal? Ṫ - Get the last (i.e. the longest) element ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9 7~~ 5 bytes ``` ►ṠË#Q ``` [Try it online!](https://tio.run/##yygtzv7//9G0XQ93LjjcrRz4////aEMdIx1jIDQBQhBtpGMYCwA "Husk – Try It Online") -2 using the return value of `Ë` in max by. -2 from Leo. ## Explanation ``` ►ṠË#Q Q all sublists (unsorted) ► max by: ṠË all elements of the list are equal by: (if all equal, returns len+1) # count of occurrences in in the list ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 86 bytes ``` f=(h,...t)=>new Set(c=[],h.map(x=>c[x]=-~c[x])).size<3?h:f(...t,h.slice(1),h.pop()&&h) ``` [Try it online!](https://tio.run/##fU9LDoIwFNx7iq7Ia1JKAFfG4iFcEhakFsEgbSxR4sKrY8GSGlNsJun7zEzmXcp7qfmtUX3YyZMYK2YANaGU9phlnXigo@iBs7wgNb2WCgaW8XwoWPiaPoypbp5inx7qXQWTytB023ABMTalkgpwENR45LLTshW0lWeoII8JSghKke8ZVxRFaOEUG692Ws3Y@rSOsCK32hmf2gzjRe62BZk7S5w6p/FZO6xf5bAeLvnrkNgsS@xfm3SxsWF9Nl9XjW8 "JavaScript (Node.js) – Try It Online") Use Breadth-First Search, so you may avoid comparing its length. A terrible \$O(n\cdot2^n)\$ time complexity. Luckly we only care about its length. Codes for checking equal number occurrence is copied from [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [answer](https://codegolf.stackexchange.com/a/225523/44718). --- # [Python 3](https://docs.python.org/3/), 63 bytes ``` f=lambda l,*t:l*(len({*map(l.count,l)})<2)or f(*t,l[1:],l[:-1]) ``` [Try it online!](https://tio.run/##fY/LCgIhFIb3PcWBNioW6LSS5kkGF9NlKHB0GGwR0bPbjCmniyU/cm6f/me4@pOzVQhdbdp@d2jBcOaVYcQcLbmxvh2IWe/dxXpu6J1uJXUjdIRNaSOUnm61EpqGYTxbTzrSCA6SQwWloymFJeQRvfiA5mLUpgBh/4tLUNQznooicdjUPGZpbs4QeX8T9XMBVMmO/IfK9Hv2iXyV@WSswL8sEB4 "Python 3 – Try It Online") This Python answer is based on [att](https://codegolf.stackexchange.com/users/81203/att)'s [answer](https://codegolf.stackexchange.com/a/225564/44718) by applying BFS to it. Comparing to JS, Python is good at creating sets, function auto bind, get length, array slicing when you are golfing. [Answer] # Scala, 84 bytes ``` _.tails.flatMap(_.inits)filter(l=>l.map(x=>l.count(_==x)).toSet.size<2)maxBy(_.size) ``` [Try it in Scastie!](https://scastie.scala-lang.org/J0DYmqnhQMaWF6Rz8u2hpg) ``` _.tails //All suffixes .flatMap(_.inits) //All prefixes of those suffixes (all subsequences) filter(l=> //Keep the ones where l.map(x=>l.count(_==x)) //The counts of all the elements .toSet.size<2 //Has 0 or 1 distinct elements )maxBy(_.size) //Find the biggest such subsequence ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ŒʒD¢Ë}éθ ``` [Try it online!](https://tio.run/##yy9OTMpM/V9W@f/opFOTXA4tOtxde3jluR3/df5HRxvqKBjpKBjH6ihAmSAeGJkgxKACYARhAwUNofIIhKLBCF0Aqj02FgA "05AB1E – Try It Online") ``` Œ # all sublists of the input ʒ } # filter by: ¢ # counts of each value D # in a copy of the sublist Ë # are all counts equal? é # sort the remaining sublists by length θ # take the last one ``` Alternatively, sort first, reverse and take the first sublist that satisfies the condition: ``` ŒéR.ΔD¢Ë ``` [Try it online!](https://tio.run/##yy9OTMpM/V9W@f/opMMrg/TOTXE5tOhw9/9anf/R0YY6CkY6CsaxOgpQJogHRiYIMagAGEHYQEFDqDwCoWgwQheAao@NBQA "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã kÈü üÊÊÉ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4yBryPwg/MrKyQ&input=WzEsIDIsIDMsIDMsIDQsIDQsIDMsIDMsIDIsIDFdCi1R) ``` ã kÈü üÊÊÉ :Implicit input of array ã :Subsections (sorted by length) k :Remove elements that return falsey (0) È :When passed through the following function ü : Group by value ü : Group by Ê : Length Ê : Length É : Minus 1 :Implicit output of last element in resulting array ``` [Answer] # [Python 3](https://docs.python.org/3/), 73 bytes ``` f=lambda l:l*(len({*map(l.count,l)})<2)or max(f(l[1:]),f(l[:-1]),key=len) ``` [Try it online!](https://tio.run/##hY7BToQwEIbPy1P0smlnt0ss9UTkSQiHqpBtHNoGuurG@OxY2JqSKNr8h3863z8z7urP1shp6ipU/eOzIljigWFr2MehV45h/mQvxnOET3gowA6kV@@sY1iLsgE@m/Ikgntpr1WIwfR21tgSUWY7zS2piDbu4hnko0PtGSWEcgHZzg3ahHJ/knKke82DK@6C61j7qpDRmh71kTYUgNscRz9oxwAmwUnBiSTbr45Ik93M7Bfd/8Km/jce2UU3Hz5FxFOz4UsVublKkWVU0uaVSavlxV@JIu6K3CoWt2/Hft6cyf/DK/wL "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes ``` ŒʒD¢Ë}éθ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6KRTk1wOLTrcXXt45bkd//9HG@ooGOkoGIORCRhB2EBBw1gA "05AB1E – Try It Online") ``` Œ all sublists ʒ keep those such that D duplicate ¢ count, vectorizes Ë all equal } é sort by length θ last ``` [Answer] # JavaScript (ES6), 108 bytes Returns the rightmost solution. ``` a=>a.map((_,n)=>a.map((_,i)=>(b=a.slice(i,i-~n))[new Set(b.map(x=>c[x]=-~c[x],c=[])&&c).size-2+n]?o=b:0))&&o ``` [Try it online!](https://tio.run/##fU9RD4IgGHzvV/DkYKGm9tSG/YgeHWtI2GgGLl25HvzrpobDNYzdBvd9d7fjxp6s5g9ZNb7SF9EXpGckZcGdVRCesUILIgcCc8KCupRcQIml3ymEMiVe4CQamE/ClqQ8aynxu/HCnGQUeR5HQS3fwo@3ih41yQ87NEx1z7WqdSmCUl9hAbMIgxiDBLgORQiEIZg1dOP0jqsJe5fXClbsxjvh@x6G0Wy3W4onZoQjsx5XtMX6ryzWy8V/E2LTZa79G5PMMaasK2bxq/4D "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map((_, n) => // for n = 0 to len(a) - 1: a.map((_, i) => // for i = 0 to len(a) - 1: ( b = // define b[] as the sub-array of length a.slice(i, i - ~n) // at most n + 1 starting at index i )[ // new Set( // build a set consisting of the number of b.map(x => // occurrences of each distinct entry in b[], c[x] = -~c[x], // using another array c[] to keep track of c = [] // these counts ) // the set will always include 'undefined' // because c[0] is never updated && c // ).size // which is why we expect its size to be 2 - 2 + n // make sure that b[new Set().size - 2 + n] ] // is defined (i.e. b[] is long enough and // the number of occurrences are all equal) ? // if so: o = b // update the output : // else: 0 // do nothing ) // end of inner map() ) // end of outer map() && o // return o ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 104 bytes ``` lambda x:max((a for i in range(len(x)+1)for j in range(i)if len({*map((a:=x[j:i]).count,a)})<2),key=len) ``` [Try it online!](https://tio.run/##RYzLDsIgEEX3fsUsGSVNLC4MkS@pXYwKSi2PEExojN@O1I3JzV2c@4hLfgQvjjHVogbBoefQ/PCTGDdGnetM7nIjKNJRYYzAhAQWrIdE/q7ZrD0ruNvjyqc/t2gNrOF76yi2oVRlmKQdsbuGl8@c8IOnHvlTL6r1sMZkfWamvWH9Ag "Python 3.8 (pre-release) – Try It Online") -1 thanks to @ophact -24 thanks to @pxeger -10 thanks to @hyper-neutrino [Answer] # [R](https://www.r-project.org/), ~~104~~ ~~98~~ ~~96~~ 95 bytes ``` function(L,n=seq(!L)){for(i in n)for(j in n)if(!sd(table(a<-L[i:j])+!1:2)&sum(T|1)<j-i+2)T=a;T} ``` [Try it online!](https://tio.run/##bYyxDoIwFEV3v4Iu5r1QhhYnpH/Qkc04INLkNVoChUn99qqlDhqTM5zce3OnYFQwi@tmGhxo7pTvR2Aa8WaGCSgjlzl8q12VDDB/hrk9XXpo60IfqLJHzJmoJG79coXmLrC2BeUSG9Xum0cw0IHgkpeIm9UzGSkju684ZZHVX6H4naT@z2G6SI3k8mOI4Qk "R – Try It Online") Ugly straightforward approach. Can't wait for a nice [R](https://www.r-project.org/) solution! *-6 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* *-1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)* [Answer] # [Haskell](https://www.haskell.org/), 92 bytes ``` last.sortOn l.filter((<2).l.nub.map l.group.sort).(>>=tails).inits l=length import Data.List ``` [Try it online!](https://tio.run/##hY5NboMwEIX3PoWFKsUW4CqkqxSz6qZSpB6AsjCJIVYHY2Hn@qX8uIKqpbFmMfPme35zFfZDAvSqMW3n8Itwgp2Udaji7z0I65gd9DeNgVUKnOwISRPKgOlbyRphBr3u2puZMMpIlnEnFFjKlFbOIuAgde2uKI5/BvSNUJpfWoSJilqaxtYITR75Lt/R9CGrpTspLREG6bDgnRQXEuRBGKowDIqAPpcrrZ01hE2ntCMSZEMqLCgpj8c8f9WuKGg0CgiPqf0@wkmED3j75R4p0NyM/VRPf7DL/hv37FRzP4h7jy/LIpomz43TYpm@WmrzyqVW4cl/jsRneW5l8@nbtt83o8N98wr/PFcgatvHZ2O@AA "Haskell – Try It Online") Either Haskell is *not* the language for this challenge, or I'm not the Haskeller for this challenge1. --- 1 Yup, I know, it's the latter. [Answer] # [J](http://jsoftware.com/), 38 33 bytes ``` 0{(1=&#[:=#/.~)\\.(\:#&>)@#&,<\\. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Dao1DG3VlKOtbJX19eo0Y2L0NGKslNXsNB2U1XRsgNz/mlypyRn5CgppCoY6CkZgZAxGJhAJoLiCkYIxnIOsAowgbKCgIUIDFGJoAqlSUMAQhhoElzBGl1D4DwA "J – Try It Online") -5 thanks to xash! [Answer] # JavaScript, 122 bytes ``` f=(n,p=t=n.length)=>n.find((e,i)=>i+p<=t&(l=n.slice(i,i+p)).every(x=>(z=m=>l.filter(w=>w==m).length)(x)==z(e)))?l:f(n,p-1) ``` One must marvel at the sheer length of counting the number of occurrences in a list. A recursive function which checks all lists of length `p` for one satisfying the OP's conditions, and if there exists one, return it, otherwise return `f(n,p-1)` Suggestions are welcome for golfing. [Answer] # [Factor](https://factorcode.org/), ~~63~~ ~~58~~ 56 bytes ``` [ all-subseqs [ histogram values all-eq? ] filter last ] ``` [Try it online!](https://tio.run/##dZFNT8MwDIbv/RUv91JpSU9w4Ii47II4VT2EKusipR@LXQSa8ttLmhat3YZjyXbyvLElH1TFnRs/3t/2r08gfRp0W2nK9Dc7RWgUHzNixYbYVARF1IVQu27oTVtfBOidZv7pnWkZz0lyThDsjB0EJDy29oBil0KkkOWKm0iJfEUHTszcFTqDeYwi3PgJlZHLg5dprPLocqqWdPPN3/E3k11821TcpcXSQ8b0SjJP6e9IbudchPI/4Rr1YwFl7SMNn2EJhALHsKOudqrBl7JDWMn0rE8vKHEwlrWDVcQox0b1yMZf "Factor – Try It Online") ``` [ ] filter last ! Select the last/largest.. all-subseqs ! ..subsequence.. histogram values ! ..whose elements occur.. all-eq? ! ..the same number of times. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 44 bytes ``` Last@*Select[Equal@@Counts@#&]@*Subsequences ``` [Try it online!](https://tio.run/##hY69CoMwFIX3PIUgOJR0MLq2BEq3DgVHyZCGSAWbYk0m0Ve3@ZMEWlvvhZyT@x1vHlTe@YPKltGlOSwXOki8q3jHmazPvaIdxqenEnLAaUb0RN0G3isuGB@W66sVsk73xwanJJsrRsU8gjGHCBYTdEJLXeVqrdFlTgRzd@0rMCg2Fje2iCyYlhwmCCZFsv3VHiHACaNtl1/YMF9xz9p2Wl/mHg9DAq3znHEhYn8VevOVoaPl6FcC@V2ei2J@@3bs882g@B@O8Dc "Wolfram Language (Mathematica) – Try It Online") Get all subsequences (ordered), select the ones with equal occurrences, take the last of those. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 71 bytes ``` Lw`.+ %(`$ ¶$` 1%O`. 1%L$`(.)\1* $.& )L$`^(.+)(¶.+)\2*$ $1 N^$` $.& 0G` ``` [Try it online!](https://tio.run/##HYyxDcJQDET7m8Mf@SeShe3sQBPBAlFkCgoaCoTEZhkgi/3454p38ll339fv/XlqK3yLNv9DRhQOwr5RQMsjJDlTsNRFB5BcUPNcWcbK@5ZcbCCQ4r5mo/@vudTUHGrmPqUlJ3dTaFcP7GSm8NMO "Retina – Try It Online") Link includes test cases. Takes input as a string of digits. Explanation: ``` Lw`.+ ``` Get all substrings of the input. ``` %(` )` ``` Loop over each substring. ``` $ ¶$` ``` Duplicate the substring. ``` 1%O`. ``` Sort the duplicate into order. ``` 1%L$`(.)\1* $.& ``` Get the run lengths. ``` L$`^(.+)(¶.+)\2*$ $1 ``` If the run lengths are equal, then keep the substring, otherwise keep nothing. ``` N^$` $.& ``` Sort all of the remaining substrings in descending order of length. ``` 0G` ``` Keep only the longest remaining substring. [Answer] # [Python 2](https://docs.python.org/2/), ~~140~~ 132 bytes -8 bytes thanks to @hyper-neutrino for space saving and replacing `def` with `lambda`! I was using python3 to code until I found that it works for Python2 too, not too much, just an iterative solution. ``` lambda n:max([r for r in [n[i:a]for a in range(len(n)+1)for i in range(len(n))if a-i>1]if len(set(r.count(s)for s in r))<2],key=len) ``` [Try it online!](https://tio.run/##XY3BDsIgEER/ZY9srCagp8b6I5TDqlSJ7dIAJu3XI3A0mcPMy0xm3dPbs8rbMOaZlvuTgPuFNqEDTD5AAMegWbueTM1UcyB@WTFbFowHiZW7f45uAjq6mzTFVBRtEuH08F9OIrZNbBvEqzLdx@5DaWFegyuF8i87UE3npotBzD8 "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes ``` FEθ✂θκFEι…ι⊕λF⁼⌊Eκ№κλ⌈Eκ№κλ⊞υκΦυ⁼Lι⌈EυLλ ``` [Try it online!](https://tio.run/##dY5BCsIwEEX3niLLBOpC212XRUGwUPAEIY5m6DSxaSJ6@pjU0oXgbmbe/49RWjplJcV4s47xVj74WLALoYI89EIIthIsWPNWBI2283IyysEAxsOVk1ijhzFImniLBocwzM0@NW0wPg85WbBWvv7SJOrCpHnID9SbzmFiRyQPLt8W/xnM3WuOP7IUWMhXJeoYd/uyqsq4fdIH "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of digits and outputs all maximal length substrings with the given condition. Explanation: ``` FEθ✂θκ ``` Loop over all nontrivial suffixes of the input. ``` FEι…ι⊕λ ``` Loop over all nontrivial prefixes of the suffix. ``` F⁼⌊Eκ№κλ⌈Eκ№κλ ``` Take the frequencies of the elements and check whether they are all the same. ``` ⊞υκ ``` Record all substrings that satisfy the condition. ``` Φυ⁼Lι⌈EυLλ ``` Output the longest such substrings. [Answer] # [Ruby](https://www.ruby-lang.org/), 69 bytes ``` ->r,*w{r,*w=w<<r[0..-2]<<r[1..-1]while r.map{|x|r.count x}.uniq[1];r} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165IR6u8GkTYltvYFEUb6OnpGsWCWIZAlmFseUZmTqpCkV5uYkF1TUVNkV5yfmleiUJFrV5pXmZhtGGsdVHt/wKFtOhoQx0FIzAyBiOT2Nj/AA "Ruby – Try It Online") [Answer] # [yuno (abandoned)](https://github.com/hyper-neutrino/yuno-abandoned/), 7 [bytes](https://github.com/hyper-neutrino/yuno-abandoned/wiki/Byte-count) ``` ッシュフェドゥッキッカ;テ ``` xxd using Jelly's codepage: ``` 00000000: 87a0 9a6d 6bfe 0b ⁷ɦȤmk“¿ ``` Disclaimer: some language features were added after this challenge. However, they weren't really made to be tailored to this challenge, all of these are things I'd planned previously. If I really wanted to, I could've reasonably made built-ins much more suited ot this challenge, but I have those on my wishlist right now as they're a lot more specific. ``` ッシュフェドゥッキッカ;テ Full Program ッシュ           All sublists, in increasing order of length then position    フェ      ;  Filter-lambda; keep elements that:      ドゥ       (duplicate top of stack)        ッキ     special count; if counting occurrences of a list that is not found, but any of its elements are, vectorize (recurses)          ッカ   all-equal?             テ last element ``` [Answer] # Python 3.8, 98 bytes Another not-very-successful python3 attempt ``` f=lambda l,i=0:(a:=l[i%(L:=len(l)):][:L-i//L])*(i%L<=i//L)*(len({*map(a.count,a)})<2)or f(l,i+1) ``` a less condensed version ``` def f(l, i=0): L = len(l) a = l[i%L:][:L-i//L] return a * (i%L<=i//L) * (len({*map(a.count,a)})<2) or f(l,i+1) ``` ]
[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/19010/edit). Closed 7 years ago. [Improve this question](/posts/19010/edit) In your language of choice, write a program that outputs exactly `Hello world!`. Each character in your program must be repeated *n* times - you choose *n*. For example, you might choose 2 for *n*. This means that every character used in your source code *must* be repeated that many times, or 0. If I were to choose 3 for *n*, this program would be valid: ``` ab(b(b(aa)));;; ``` Rules: * You cannot use any external resources * No user input can be provided * You must output *exactly* `Hello world!`, no more, no less. Newlines are the exception, they are optional. * *n* must be >= 2, to keep things interesting * It's highly discouraged to use comments to accomplish your goal. Popularity contest, ending in 14 days. Highest score answer at the end wins! [Answer] # Brainfuck n=57. 45 newlines removed thanks to ratchet freak ``` ++++++++++[>+++++++>++++++++++>+++<<<-]>++.>+.+++++++..+++.>++.<++++++++.--------.+++.------.--------.>+.---------------------------------[.............................................][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]<-<<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>< ``` A more readable version: ``` +++++ +++++ [ > +++++ ++ > +++++ +++++ > +++ <<< - ] > ++ . > + . +++++ ++. . +++ . > ++ . < +++++ +++ . ----- --- . +++ . ----- - . ----- --- . > + . ---------------------------------[.............................................][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]<-<<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>< ``` The last line (on the readable version) is for filling up the character count. They are not comments. The `[]` are `while(0)`s, and the `><`s are in essence no-ops [Answer] ## JavaScript ``` alert(("aaaeerrttt((,,,HHHoo wwwddd!!!))","Hello world!")) ``` This seemed a little too easy. [Answer] # Python 3, n = 3, no comments ``` dwwppHottedHen =print((("H[e]l1l1o\\ !w!orrilidn!\""[::2][:12])))== 2 ``` Not too hard for a Pythonist to understand. ;) (Hint: try `"abcdefghijk"[::2]` and see what it results in) By the way, a `HottedHen` is a warmed up chicken, if you were wondering. (The `dwwpp` before it stands for `drinking water with purple pancakes`, because that's what the hens were doing when I was writing it. Everyone knows that purple pancakes go well with water. Obviously.) [Answer] ## C, 54 ``` main(Hadmeinwurst015p){{!puts("Hello\40wor\154d!");;}} ``` [Answer] ## Golfscript - 32 New version with 2 of each used character - 32 - [Test online](http://golfscript.apphb.com/?c=OyJIZWxsbyB3b3JceDZjZCEiICdcSGV3cng2Y2QhJzs=) ``` ;"Hello wor\x6cd!" '\Hewrx6cd!'; ``` Old version - 39 - [Test online](http://golfscript.apphb.com/?c=OzsnSGVsbG8gd29ybGQhJyAgIidISGVld3dvcnJkZCEhXFxcIiI7) ``` ;;'Hello world!' "'HHeewworrdd!!\\\""; ``` EDIT: Updated since rules was updated saying it was discouraged with the use of comments [Answer] # Java - 1221 chars Each character is repeated `(int)'!'` number of times. ``` public class ncharacterHelloworld { public static void main(String[] args){ {; {; {; {; {; {; {; {; {; {; {; {; {; {; {; {; {; {; {; {;{;{;{;{;{;{;{;{;{;{;{ String pppppppppppppppuuuuuuuuuuuuuubbbbbbbbbbbbbbbllllllllllliiiiiiiiiiicccccccccccccaaaaaaaaaaaassssssssssssssnnnnnnnnnnnnnhhhhhhhhhhhhhhhhrrrrrrrrrrrrttttttttttteeeeeeeeeeeeeeHHHHHHHHHHHHHHHooooooooooooowwwwwwwwwwwwwwwdddddddddddddddvvvvvvvvvvvvvvvvmmmmmmmmmmmmmmmSSSSSSSSSSSSSSSgggggggggggggggyyyyyyyyyyyyyyyy="Hello world!", a=pppppppppppppppuuuuuuuuuuuuuubbbbbbbbbbbbbbbllllllllllliiiiiiiiiiicccccccccccccaaaaaaaaaaaassssssssssssssnnnnnnnnnnnnnhhhhhhhhhhhhhhhhrrrrrrrrrrrrttttttttttteeeeeeeeeeeeeeHHHHHHHHHHHHHHHooooooooooooowwwwwwwwwwwwwwwdddddddddddddddvvvvvvvvvvvvvvvvmmmmmmmmmmmmmmmSSSSSSSSSSSSSSSgggggggggggggggyyyyyyyyyyyyyyyy, u="\"=============================,,,,,,,,,,,,,,,,,,,,,,...............................",b="\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\\\\\\a",i,l,c,t,H,o,w,m;int[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]ffffffffffffffffffffffffffffffff; if(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!(!!true))))))))))))))))))))))))))))))) System.out.println(a); }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} } } ``` I got tired of putting all the `=` and `,` and the like in the code, so I ended dumping them all in a String; not a comment, a string. Every valid character is used for a variable name. [Answer] ## Windows Command Script - 33 bytes 3 of everything: ``` ecHo Hello world!% eHccwwrrdd!!%% ``` [Answer] # Windows Command Line - 42 Bytes n=3 ``` ecHo.Hello world! 2>^>2cceHwwrrdd!.. 2>^^! ``` ## Batch - 45 Bytes ``` @ecHo.Hello world! 2>^>2cceHwwrrdd@@..! 2>^^! ``` `2>` redirects stderr to a file called `>22cceHwwrrdd` - `>` is an invalid character for a file name - redirect the output of that error to a file called `^!`. Realized that I completely ignored `!` and `>`. Dang. [Answer] # **Ruby - 40 Chars** (n=2) ``` print "Hel\x6co World!"||'pintHe\x6cWd!' ``` [Answer] ## PHP - 30 bytes, *n = 2* ``` Hell<?='=s?<;^2s'^RSHSI2VReIV; ``` Shortest solution thus far. I may be able to reduce this by *2-4* more bytes. [Answer] ## PHP ``` <?print"H\145llo wor\154d!"; $Hwpintd<>!'$';?> ``` Shorter version (42 char): ``` <?print"H\145llo wor\154d!"; 'Hwd<pint?!'; ``` [Online page with that source](http://dev.twisted-gamers.net/test.php) [Answer] # Perl (51 bytes) ``` print'Hello world!'; ppriinnttHHeeowwdd; "'\"\\!!"; ``` [Answer] # C, ~~75~~ ~~56~~ 54 2 of everything ``` main(HWacdeimnprstux6) {{!puts("Hel\x6co\ World!");;}} ``` --- ``` main( ){puts("Hello Wor\x6cd!\0!;HWacdeimnprstux06{}");} ``` --- 3 of everything. ``` main(){puts("Hello World!\000!!;;HHWWaaddeeiimmnnpprrssttuu{}{}\"\()o");} ``` `Puts` stops reading after the first null byte (`\000`), and only outputs everything before it. [Answer] # JavaScript 40 (n=2) I took a slightly different approach to @eithedog, using the left over letters to act as a logic trigger, so that it was absolutely essential to use it to activate the `alert` function. `('Hawtd !')&&alert("He\x6c\x6co world!")` [Answer] **Python 2, 38** ``` deinptw=H=5; print"Hel\154o world\41"; ``` [Answer] ## R, 346 characters, *n* = 12 ``` cat((((((((((intToUtf8(c(40,69,76,76,79,0,55,79,82,76,68,1)+31+1+0+0+0+0+0+0+0+0++0*11111111[1]*22222222222[1]*33333333333[1]*44444444444[1]*5555555555[1]*6666666[1]*7777777[1]*888888888[1]*999999*9[1]*9[1]*9[1])))))))))),"\"\"\"\"\"\"\"\"\"\"\\aaaaaaaaaaaccccccccccfffffffffffiiiiiiiiiiinnnnnnnnnnnoooooooooootttttttttTTTTTTTTTTTUUUUUUUUUUU"[0]) ``` Characters used in this code: ``` ,"()[]*\+0123456789acfinotTU ``` [Answer] # [Jelly](//github.com/DennisMitchell/jelly), 16 [bytes](//github.com/DennisMitchell/jelly/wiki/Code-page) (non-competing) ``` “⁸ƒẹI4» “⁸ƒẹI4» ``` (+trailing newline) [Try it online!](http://jelly.tryitonline.net#code=4oCc4oG4xpLhurlJNMK7CuKAnOKBuMaS4bq5STTCuwo) (n = 2) NO COMMENTS AT ALL. I assure you. Just Link 1 and the Main Link. [Answer] ## Golfscript, 42 ``` ."Hello world!"'\\\'" HHeeowwrrdd!!'..;;; ``` [Test online](http://golfscript.apphb.com/?c=LiJIZWxsbyB3b3JsZCEiJ1xcXCciICBISGVlb3d3cnJkZCEhJy4uOzs7) [Answer] # Python: With 3 characters each. ``` print 'Hello world!'#He's aware#paints#Hipos!nddwt! ``` `nddwt` is a rhino! [Answer] **Javascript, 40** ``` alert("Hel\x6Co wor\x6Cd!", !('adtHw,')) ``` If I'm not mistaken every character appears twice (though I started seeing double, so I'm not sure) edit: And, if abusing the rules - **36**: ``` alert("Hel\x6Co wor\x6Cd!")( !wdatH) ``` (abuse = while output is given as a prompt, the console displays the error - don't know how to treat this). [Answer] # Bash, 39 ``` echo -e "H\r--w\"!wccdd!\rHello world!" ``` This *displays* exactly Hello world!, and is 39 chars if you omit the trailing newline (bash doesn't seem to need it). If you need a case-sensitive version, it becomes 42 chars: ``` echo -e "HhhH\r--w\"!wccdd!\rHello world!" ``` [Answer] # JavaScript (52 characters) ``` alert(['He\x6C\x6Co world!'][(!1,0)-0], +-1+"Hadtw") ``` Each character is used 2 times, and it doesn't use any comments! **Note:** *I posted this answer [here](https://codegolf.stackexchange.com/a/19589/15022) first.* [Answer] # Golfscript x4 -- No extra symbols -- Using all possible commands ``` 'HHHeeelWWWrrrd'!!! do do 'Hello world!' ``` I tried to do one that didn't have any extra symbols beyond what was absolutely necessary (though I could have chosen `"` instead of `'` or `"`) As a secondary goal I also wanted to put as few characters as possible into a string as possible, so I used the `!` operator as such, and I also squeezed in to `do` operators. [Answer] # Classic ASP (VBScript; 62 characters) ``` Hel<%REspOnsE.wRite Chr((0<0>-.6&"!")+&H6C+h-dinptO)%>o world! ``` Uses each character exactly 2 times! --- **Edit:** This code is a bit shorter: ``` Hel<%= Chr((0<0>we=6&"!")+&H6C+hd)%>o world! ``` And so is this: ``` Hel<%= CHr((0<1>wedC=8&"!&")++108)%>o world! ``` [Answer] # Turtlèd, n=3, (noncompeting) N=3, because of "Hello world!" having three `l`s. ``` '!' ' HHeeowwrrdd"Hello world!""! ``` **[Try it online](http://turtled.tryitonline.net/#code=JyEnICcgSEhlZW9XV3JyZGQiSGVsbG8gV29ybGQhIiIh&input=)** ## Explanation: ``` '! write exclamation mark ' ' write space twice on the same cell as exclamation mark HHeeowwrrdd balances chars in Hello world!, moves the pointer "Hello world!" Write Hello world! to grid "! Write the exclamation mark again, on top of the last one ``` [Answer] # Befunge 98 - 26 bytes Since I had to duplicate the `r` anyway, I figured I may as well make the source text read left-to-right rather than typical `gnirts` Befunge style. There's nothing particularly notable about this; I'm not sure if having code that simply isn't executed counts as a comment, but the six characters `Hel w!` are just ignored. ``` rHel w!@,dk"Hello, world!" ``` ]
[Question] [ The program should print every letter combination (lowercase or uppercase, it doesn't matter) in alphabetic order. It must start with `a` and the last printed combination should be `password`. The output should be: ``` a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ... passwora passworb passworc password ``` [Answer] ## Perl, 19 chars ``` say for a..password ``` Uses newlines as delimiters, per clarification above. Run with `perl -M5.010` (or just `perl -E 'say for a..password'`) to enable the Perl 5.10+ `say` feature. Per [meta](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), this doesn't count as extra chars. (If you insist on spaces as delimiters, `$,=$";say a..password` is only two chars longer. However, it's also *very* slow and wasteful of memory, to the point of being unusable in practice, since it tries to build the entire list in memory before printing it.) [Answer] ## Ruby, 33 chars (optimal but longer version) ``` ?a.upto('password'){|c|$><<c+' '} ``` I like the `'a'.upto('password')`; it tells you *exactly* what it's doing. Ruby is great and expressive like that. `:D` Of course, `print c,' '` would also be much clearer, but using `$>` is two characters shorter. ## Ruby, ~~29~~ 25 chars (slow version) ``` $><<[*?a..'password']*' ' ``` This one's shorter, but it prints all of the tokens at once, so it takes a long, long time to run! [Answer] ## Perl, ~~33~~ ~~32~~ 24 characters A solution in 32 characters: ``` $_=a;print$_++,$"until/passwore/ ``` Not much to say about this one. I could reduce this to 27 characters if I could use newlines instead of spaces to separate the entries. [Ilmari Karonen points out](https://codegolf.stackexchange.com/a/12619/4201) that `..` internally calls `++`, so a better solution (25 characters) would be: ``` print$_,$"for a..password ``` By taking advantage of Perl's command-line options, here's an equivalent 24-character solution: ``` perl -l40e 'print for a..password' ``` [The rules for counting perl flags](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions/274#274) is here, for those who aren't familiar with them. Of course, [Ilmari's 21-character solution](https://codegolf.stackexchange.com/a/12619/4201) is shorter still, but it requires a machine that can allocate an array of 129,052,722,140 strings. [Answer] ## Perl 6, 20 chars ``` say "a".../password/ ``` You don't need other things [Answer] # Python 2, 91 ``` b=lambda n:n*' 'and b(n/26-(n%26<1))+chr(~-n%26+97) i=0 exec"i+=1;print b(i);"*129052722140 ``` [Answer] ## PHP ~~38~~ ~~37~~ 36 characters ``` <?for($w=a;$w<passwore;)echo$w++,~ß; ``` You have to set the encoding to ISO 8859-1 and disable warnings. [Answer] # Ruby (40 characters) Interpret a string of a-z letters as a number in base 26, with a = 1, b = 2, ..., z = 26. So "password" can be thought of as the number N = ``` 16*(26**7) + 1*(26**6) + 19*(26**5) + 19*(26**4) + 23*(26**3) + 15*(26**2) + 18*(26**1) + 4*(26**0) ``` If we let `s = "a"` (that is: 1) and we make (N-1) calls to `s.succ!`, s will be `"password"` (N). In other words, N = 1 + (N-1). For an example that will run more quickly, to prove the calculation of N is correct, consider `"pass"` as the target, where N is ``` 16*(26**3) + 1*(26**2) + 19*(26**1) + 19*(26**0) ``` and ``` s = "a" (N-1).times { s.succ! } puts s #== "pass" ``` Since we want to print `"a"` too, we need ``` s = "`" N.times { print(s.succ! + " ") } ``` So back to the full "password". `N = 129052722140`, leaving: ``` s=?`;0x1e0c2443dc.times{$><<s.succ!+" "} ``` I hunted for a more compact form of `129052722140 == 0x1e0c2443db` but couldn't find one. (Updated to fix the lack of printing `"a"`, thanks to Cary.) [Answer] **Javascript, 73** Here is a 73 character version of @Briguys' code, which prints only letter combinations `for(i=s=0;1982613533018>i++;s=i.toString(36))/\d/.test(s)||console.log(s)` [Answer] ## APL(Dyalog), ~~46~~ 34 ``` {∇{'PASSWORD '≡⍞←⍵:→⋄⍵}¨⎕A∘.,⍵}' ' ``` Theoretically, it would print until PASSWORD, but I encountered a work space full error after ZZZZ: 5-dimensional array is just too awesome. EDIT: Must have been too long since I last fiddled with APL. How dare I missed the identity comparision (`≡`)!!! ### Explanation `{...}`: Declares a function which... `⎕A∘.,⍵`: Takes the outer product over concatenation (Every combination of an element of the left operand concatenated with an element of the right operand, just like Cartesian Product) between the 26 uppercase alpha (`⎕A`) and the argument (`⍵`) `{...}¨`: And for each element of the resulting set, plug that into a function which... `⍞←⍵`: prints it out `'PASSWORD '≡` and compare it with `'PASSWORD '` `→`: If the comparison returns true (`1`), then abort the program. `⍵`: Else just return the printed string. `∇`: Finally, the outer function recurse itself. (Then you are taking outer product over concat between the 26 alpha and the 26 alpha, which gives all the 2-letter combinations, and then outer product over concat between the 2-letter combinations and the 26 alpha, etc... Until you reach PASSWORD which triggers the abort) `' '`: The spark!! That kick-start the recursive function with the space character. [Answer] # Python 2 - ~~153 152 151~~ 149 bytes ``` from itertools import*;R=range for l in iter(chain(*[product(*((map(chr,R(65,91)),)*n))for n in R(1,9)]).next,tuple("passwore")):print ''.join(l) ``` Saved one byte by using UPPERCASE and one by using newlines instead of spaces. [Answer] ### Golfscript 41 For lack of `'z'+1 == 'aa'` logic Golfscript can't win this one. ``` 168036262484,(;{27base{96+}%' '+.96?0<*}% ``` * `168036262484,` create array from 0 to 168036262483 * `(;` drop the 0 * `{` .. `}%` iterate over array * `27base` convert element to base 27 array * `{96+}%` add 96 to each digit * `' '+` convert to string and add a space to the end * `.96?0<*` truncate string to zero if it contains char 96 [Answer] In Ruby, ~~39~~ 40. ``` a=&` 0x1e0c2443dc.times{$><<a.succ!+' '} ``` ..or `129052722140`. (Edit: formerly I had `129052722`. I had lost some digits cutting and pasting. Previous hex (`0x7B13032`) was for incorrect number.). Borrowed `a=?`` from @Doorknob to saves a character. [Answer] # Javascript: ~~57~~ 56 characters (thanks C5H8NNaO4) Here's a solution that includes numbers as possible characters ("0", "1", "2", .., "passwor9", "passwora", "passworb", "passworc", "password") ``` for(i=-1;i++<1982613533017;console.log(i.toString(36))); ``` [Here's a fiddle for testing](http://jsfiddle.net/briguy37/yCqW7/) (with only the last 100 iterations so it doesn't lock up your browser). [Answer] ## Haskell, 101 ``` main=putStrLn.concat.takeWhile(/="passwore ").tail.concat.iterate(\k->[x:y|x<-['a'..'z'],y<-k])$[" "] ``` [Answer] ## Befunge (72) ``` <_v#:/*2+67\+++88*99%*2+76: ^ >$>:#,_84*+,1+:0\:" Lr$W~"67++**1+***6+`#@_ ``` Prints strings 'a' to 'password' separated by spaces, then exits. Below is a version that prints only the first 9\*9 = 81 words ('a' to 'dd'), for comparison. The `99*` is the number of iterations to perform. ``` <_v#:/*2+67\+++88*99%*2+76: ^ >$>:#,_84*+,1+:0\:99*`#@_ ``` [Answer] ## JavaScript ~~80~~ 76 ``` for(i=s=0;s!="password";i++){s=i.toString(36).replace(/[0-9]/,'');console.log(s)} ``` [fiddle](http://jsfiddle.net/mendelthecoder/9Jnpf/) - stops at "pa". however this does repeat things. ]
[Question] [ This challenge is simple: Take a path to an `png` image file as input and overwrite that file with a copy of itself rotated 90 degrees clockwise. You may assume that the file has dimensions of 128x128 pixels. You may not use image metadata modifications (like Exif) to rotate the image; the pixels themselves must be transformed. ## Examples Input: [![A cat](https://i.stack.imgur.com/2iORu.png)](https://i.stack.imgur.com/2iORu.png) Output: [![A weird cat](https://i.stack.imgur.com/LiPrD.png)](https://i.stack.imgur.com/LiPrD.png) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. [Answer] # Bash/ImageMagick, 21 bytes ``` mogrify -rotate 90 $1 ``` Conveniently this command overwrites the source file, and does not need the image to be of any specific dimensions. [Answer] # [AutoHotkey](https://Autohotkey.com) + MSPaint, 77 Bytes ``` f(s){ run mspaint %s% sleep 999 click 189,116 sleep 200 click 26,13 send ^s } ``` Autohotkey is not a language that lends itself to golfing very well, though it is uniquely very good at pretending to be a user. This simply opens paint with the target image, clicks the Rotate, then 90 degrees buttons, then presses CTRL+S to save the image. [Video of it Running](https://i.gyazo.com/14731a8cdf526983aea0e97d90c8308a.mp4) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 8 bytes ``` YiIX!GYG ``` Unfortunately the online compilers cannot load/save images so [here](https://matl.io/?code=1%3A100+10+e+XJ++%25+Sample+image%0A%27Original%27D%0AlYG++++++++++++%25+Display+the+sample+image%0AlY.++++++++++++%25+Pause+for+1+second%0AXx%27Rotated%27D%0AJIX%21+++++++++++%25+Rotate+the+image%0AlYG++++++++++++%25+Display+the+rotated+image&inputs=&version=22.7.4) is a demo that uses an image defined within the interpreter itself. **Explanation** ``` % Implicitly grab the first input (the file path) as a string Yi % Read in the image IX! % Rotate 270 degrees counter-clockwise G % Grab the file path again YG % Write the rotated image to this file ``` [Answer] # NodeJS + [JIMP](https://www.npmjs.com/package/jimp), 74 bytes ``` require('jimp').read(n=process.argv[2]).then(x=>x.rotate(270,!1).write(n)) ``` The path to image must be passed as third arg: ``` node filename.js imageSrc.png ``` ## UPD 87 -> 84 Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the [tip](https://codegolf.stackexchange.com/questions/257892/rotate-an-image/257903?noredirect=1#comment569877_257903) to reduce bytes count ## UPD 84 -> 74 Thanks to [Jacob](https://codegolf.stackexchange.com/users/108687/jacob) for the [tip](https://codegolf.stackexchange.com/questions/257892/rotate-an-image/257903?noredirect=1#comment569884_257903) to reduce bytes count [Answer] # [Python](https://python.org/) + [Pillow](https://python-pillow.org), ~~64~~ 59 bytes ``` from PIL.Image import* open(p:=input()).rotate(-90).save(p) ``` *-5 thanks to @tsh* #### Commented ``` from PIL.Image import* # Import module open( # Open an image p:=input() # Input the filename and store in p ).rotate( # Rotate the image -90 # -90 degrees anti-clockwise # (= 90 degrees clockwise) ).save(p) # And save it back in the original file ``` [Answer] # MacOS [zsh](https://ohmyz.sh/) + [sips](https://ss64.com/osx/sips.html), 13 ``` sips -r 90 $1 ``` [sips (Scriptable Image Processing System)](https://ss64.com/osx/sips.html) is a lesser-known built-in command-line utility for image manipulation. Confusingly, nothing to do with [SIP (System Integrity Protection)](https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection). --- # MacOS [zsh](https://ohmyz.sh/) alias + [sips](https://ss64.com/osx/sips.html), 10 ``` sips -r 90 ``` Create the alias with `alias r=sips -r 90`, then run with `r test.png`. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 64 bytes Anonymous prefix lambda. ``` {b.MakePNG⎕NREPLACE,⍨⍵⎕NTIE-≡b.CBits←⌽⍉'CBits'⍎⍨'b'⎕WC'Bitmap'⍵} ``` `{`…`}` "dfn"; argument is denoted `⍵`:  `'b'⎕WC'Bitmap'⍵` create a Bitmap `b` from the file  `'CBits'⍎⍨` extract the **C**olour **Bits** from that  `⍉` transpose  `⌽` mirror  `b.CBits←` update `b`'s Colour Bits to that value  `≡` get the array nesting depth of that (returns 1)  `-` negate (returns −1)  `⍵⎕NTIE` use that as file handle to tie the file (returns −1)  `,⍨` self-concatenate (we need a list of file handle and start position, where −1 means current position, i.e. at the start of the file)  `b.MakePNG⎕NREPLACE` replace the file contents with a render of `b` to PNG file contents [Answer] # [Factor](https://factorcode.org/) + `image.processing.rotation`, 52 bytes ``` [ dup load-image 90 rotate swap save-graphic-image ] ``` Testing the function in Factor's REPL: [![enter image description here](https://i.stack.imgur.com/Trouz.png)](https://i.stack.imgur.com/Trouz.png) [Answer] # [Python](https://python.org/) + [opencv-python](https://opencv.org/), ~~84~~ 62 bytes ``` import cv2 cv2.imwrite(p:=input(),cv2.rotate(cv2.imread(p),0)) ``` [![Screenshot](https://i.stack.imgur.com/964nY.png)](https://i.stack.imgur.com/964nY.png) *-22 thanks to @Stef* Unfortunately for some reason when I do `from cv2 import*` it just doesn't work: [![Screenshot](https://i.stack.imgur.com/nI8nCm.png)](https://i.stack.imgur.com/nI8nC.png) #### Commented ``` import cv2 # Import module cv2.imwrite( # Write to a file: p:=input() # Get the filename as input and store in p cv2.rotate( # A rotated version of: cv2.imread(p), # The contents of p 0 # Rotated 90 degrees clockwise )) # Close the parentheses ``` [Answer] # Python + Pygame, 77 bytes ``` from pygame import* image.save(transform.rotate(image.load(a:=input()),90),a) ``` Guess in terms of golfiness [PIL/Pillow](https://codegolf.stackexchange.com/a/257899/91213) > Pygame > [OpenCV](https://codegolf.stackexchange.com/a/257897/91213) [Answer] # [Julia](http://julialang.org/), 46 bytes ``` using Images ~f=save(f,imrotate(load(f),π/2)) ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 58 bytes ``` %{$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)} ``` Input comes from the pipeline. TIO won't work, what with the file, so the following assumes the cat above was downloaded to C:\Temp. Try it in a PS 7 Console: ``` $path = 'C:\Temp\2iORu.png' $path | %{$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)} Invoke-Item $path ``` # Windows PowerShell, 78 bytes The System.Drawing assembly must be loaded, which costs 20 bytes as compared to Core. ``` %{Add-Type -A *.*wing;$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)} ``` Try it in a Windows PowerShell console: ``` $path = 'C:\Temp\2iORu.png' $path | %{Add-Type -A *.*wing;$p=[Drawing.Image]::FromFile($_);$p|% Ro* 1;$p.Save($_)} Invoke-Item $path ``` Pretty straightforward: Starts the `%` cmdlet (alias for ForEach-Object) Adds the assembly System.Drawing (not required in PS Core). Loads the image file from the pipeline (in `$_`) into $p. Then a bit of golfing can take place: `$p|% Ro* 1` pipes the image to % (ForEach-Object) and calls the image's method RotateFlip(RotateFlipType), with 1 being Rotate90FlipNone. Then the image gets saved to the original location. Invoke-Item shows the image in the default app for .png. You can of course leave out that line and open it with your favorite viewer. [Answer] # MATLAB/Octave, 33 bytes ``` @(x)imwrite(rot90(imread(x),3),x) ``` [Answer] # PHP 7.4.33 + [WideImage 11.02.09](https://wideimage.sourceforge.net/download/) - 88 bytes This relies on the WideImage library, which is an old library to manipulate images. ``` <?php include($x=WideImage)."/$x.php";$x::load($a=$argv[1])->rotate(90)->saveToFile($a); ``` You can use from PHP 5.2.0 to 7.4.33, but I've confirmed it works in 7.4.33 and 5.6.44. This is meant to be executed from a command line/shell. It does exactly what the code says: loads an image, rotates by 90º and overwrites the file. # How to test this Just follow these simple steps: * Install PHP 7.4.33 * Create a PHP file *somewhere* convenient * Put the code in that file * Download [WideImage](https://wideimage.sourceforge.net/download/) - DO NOT DOWNLOAD THE GITHUB VERSION * Extract the `lib` folder * Rename it to `WideImage` To run it, just execute something like `php -f file.php image.png`. [Answer] # [`feh`](https://feh.finalrewind.org/) image viewer, 1 `feh` is an image viewer for the Unix [X window system](https://www.x.org/wiki/), first developed in 1999. ``` > ``` From [linux.com](https://www.linux.com/news/cli-magic-feh-image-viewing): > > Type > to rotate an image 90 degrees clockwise, and < to rotate it 90 degrees counterclockwise. Your changes are immediately saved to the file. > > > ]
[Question] [ In elementary school, children learn about proper fractions, where the numerator is less than the denominator, and thus the value of the fraction is less than one. Later, they are taught about fractions where the value of the fraction is greater than one, and two different ways to express these fractions: mixed fractions and improper fractions. Given a mixed fraction, determine if it is equivalent to the improper fraction where the integer value and the numerator are concatenated together. For example, for input `1 3/4`, the improper fraction is `13/4`. ## Test Cases ``` 1 3/4 -> falsey 1 3/10 -> truthy 6 6/7 -> falsey 55 55/100 -> truthy 4 9/100 -> falsey 40 9/100 -> falsey 7 49/1000 -> falsey 9 1/2 -> falsey 999 999/1000 -> truthy 1 21/200 -> falsey 1 21/101 -> falsey ``` For input, you may take the integer part and the fraction part as separate inputs, but you may not take the fraction as input in two pieces, and you may not take it as a decimal value. You may drop the integer part (not take it as input) if you do not need to use it. [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` UsGXzU= ``` Input is a string. Output is `1` for truthy, `0` for falsey. [Try it online!](https://tio.run/##y00syfn/P7TYPaIq1Pb/f3VTUwVTE31DAwN1AA) Or [verify all test cases](https://tio.run/##y00syfmfEOH1P7TYK6Iq1Pa/S8h/dUMFY30TdS4wbWgAZJgpmOmbA2lTUwVTE6AQSMxEwRLGMoAzzRVMwEwQ21LBUN8IRFtaKgAxTNhQwQgojmAaGhiqAwA). ### Explanation ``` U % Implicit input. Convert to number(s): gives a vector of two numbers s % Sum of that vector G % Push input again Xz % Remove spaces U % Convert to number = % Equal? Implicit display ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~16~~ 12 bytes ``` {1+$_==1~$_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9pQWyXe1tawTiW@9n9xYqVCmoaSsb6JkqY1F5xnaIDENdM3R@KZmgBlkaUtCfBNwALIIob6RsjqLTEUGAFVoAsYGhgCBf4DAA "Perl 6 – Try It Online") Takes input as a string representing the fraction. Turns out Perl 6's dynamic typing can handle strings to rational fractions, who knew? So the string `"1/10"` when coerced to a number, returns `0.1` The anonymous code block simply checks if the fraction plus one equals one concatenated with the fraction. Thanks to [xnor's Python answer](https://codegolf.stackexchange.com/a/169262/76162) for showing me that the integer part doesn't matter. ### Old solution, ~~27~~ 26 bytes ``` {.nude[0]==.Int~[%] .nude} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ovrzQlNdog1tZWzzOvpC5aNVYBLFT7vzixUiFNw1DbWN9E05oLwTM0gHPNtM30zeE8U1NtUxOgNELeRNsSlW@AJmCubQIWQIhYahvqGyF4lpbaQIyqxFDbCKgGXcDQwFDT@j8A "Perl 6 – Try It Online") Takes input as a rational mixed fraction, and returns true or false. Returns false for the fourth test case because it can be simplified. ### Explanation: `.nude` returns a list of `[numerator, denominator]`. ``` { } # Anonymous code block .nude[0] # Check if the numerator of the mixed fraction == # Is equal to .Int # The integer part of the fraction ~ # Concatenated to [%] .nude # The numerator modulo the denominator # And return implicitly ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~17~~ 16 bytes ``` (.)+/1(?<-1>0)*$ ``` [Try it online!](https://tio.run/##NYi9DkBAEIT7fYopSA7hdrkjmwil16BQaBTi/c/5K2bmm@9Yz21fQmqmOcBUWWHFjH0pA2d5EoKgsY7uFqYWre3Ie3gXL5ODvssfdHAPMCnE1qSqiHmVoI7uB2G5AA "Retina 0.8.2 – Try It Online") Requires just the fraction part, so the linked test suite removes the integer from the test cases. Explanation: The improper concatenation is equal to the mixed number only if the denominator is a power of 10 and the numerator has one digit for every zero in the denominator. .NET's balancing groups are used to verify that sufficient digits exist. Edit: Saved 1 byte thanks to @sundar. [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` §·=r¤+r+ ``` [Try it online!](https://tio.run/##yygtzv6fG5xfnqqhraRrp6BU7PaoqfHQcp1HbRMetU0q1zy07f@h5Ye22xYdWqJdpP3//39DBWN9Ey4QaWjAZaZgpm/OZWqqYGoC5BpwmShYQmgDKMNcwQTMMOCyVDDUN@KytLRUAGKIkKGCEVAMxjA0MAQA "Husk – Try It Online") ### Explanation ``` §(·=r)(¤+r)(+) -- example arguments: "1" "3/10" § -- fork both arguments (¤ r) -- | read both: 1 3/10 ( + ) -- | and add them: 13/10 (+) -- | concatenate: "13/10" -- and do (· r) -- | read the second argument: 13/10 ( = ) -- | and compare: 13/10 == 13/10 -- : 1 ``` [Answer] # [Python 2](https://docs.python.org/2/), 43 bytes ``` lambda k:k.split('/')[1]==`10**k.find('/')` ``` [Try it online!](https://tio.run/##bc/RCoIwFIDh63qKdXVKhjqbisG67Am6W4MM08ZMxUzo6e0oJgrdDM7Hz85WfZpHWXhdJi5dHj9vSUzMwdivKtfNFhzYSaaEuDLXsoyd6iIZ8NqlZU00NbQluiBSMkpg73Cg5BTnr7uiZCTmop3r90ABUuCE88r30XyO3TzkiNFoU8rdfxoi8kEXHCEzx1tQ1COev/i3rX@ph/HyhlGZyyZVh/WqqnXRDF8HcQSabc2OStgIwFmAkq0QvSnadl8 "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~78~~ 65 bytes ``` function(n,e=function(a)eval(parse(t=sub(" ",a,n))))e("")==e("+") ``` [Try it online!](https://tio.run/##dc7RCsIgFIDh@57icLpR2thcuiFk72KhFAwXmwt6epOx1iwmiMjHr6cP9pQHO7qrv3eOuMyo5aKpeeqWPHQ/GOLVMF4IAmY6czQuQxCpUvE4IA2WIINjwZHuYV75GaxuB/PazcjKRaP5fvS3yWqoi2YrFAKEiOmnTUoOckU/JS9TTbABPuHq2S9KYEW1NZCUEuJe4mQgBlVMN/6ckJXsD8Mb "R – Try It Online") -13 bytes thanks to both Giuseppe and JayCe! [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╡ÄLσ` ``` [Run and debug it](https://staxlang.xyz/#p=b58e4ce560&i=1+3%2F4%0A1+3%2F10%0A6+6%2F7%0A55+55%2F100%0A4+9%2F100%0A40+9%2F100%0A7+49%2F1000%0A9+1%2F2%0A999+999%2F1000%0A1+21%2F200%0A1+21%2F101&a=1&m=2) Explanation: ``` +yj$e= Full program, implicit input + Add integer and fraction part y Push unparsed input j$ Split on spaces and flatten, i.e. Remove spaces e Evaluate = Check for equality ``` [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda k:eval(k+'+1==1'+k) ``` [Try it online!](https://tio.run/##bc9BC4IwFMDxc32KdXqKA51ORWEd@wTdlodFSjJTMRP69OspKgpdBu/Hn72t/fbPpg5MIW6mUq/7QxGd5oOqLO2Aw4Rg4GjbFE1HSqrpQMqaSMkogcDlQMlFVe88o2Qm5qFdu89EEVLkxtsqDNFCjt025IjJbGvKvX8aI/JJd5wgM9ffUTIinku8bBtf6mO8v2FW5rFVs/R4aLuy7q3x6yDOQAtL21TCSQDOAjI5CDFaRgfb/AA "Python 3 – Try It Online") For example, input `3/4` gives `3/4+1==13/4`. Instead of taking the whole part of the fraction, we just set it to `1` to test the mixed fraction equality. Test cases from Chas Brown. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes ``` ḍ{lᵛ&ht¬ị&t↔ị1} ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompkcdy5VKikpTlR7u6qwBcdISc4rBvNqHWyf8f7ijtzrn4dbZahklh9Y83N2tVvKobQqQNqz9/z9ayVjfRElHAUgZGoBoM31zEGVqCuSDBSz1DREsCMMEzAIzDfWNwFKWCCEjoBicZWhgqBQLAA "Brachylog – Try It Online") Takes the fractional part alone as a string input. Indirectly uses the same idea as my Julia answer - "the denominator is 10^{length of numerator}" can be said as "the denominator is a power of ten, and the length of the denominator is equal to the length of the numerator + the length of "/" (i.e. 1). ``` ḍ % split the input in half { } % and verify that lᵛ % each half has the same length (i.e. the string had even length) &ht¬ị % and the last character of the first half is % not a number (it should be "/") &t↔ị1 % and the second half when reversed is the number 1 % i.e. the denominator should be a power of 10 ``` --- Older answer: ### ~~15~~ 20 bytes ``` a₀ᶠịˢtl;10↺^.&a₁ᶠịˢh ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/FRU8PDbQse7u4@vagkx9rQ4FHbrjg9NaBwI0w44/9/JUMzfUMDAyUA "Brachylog – Try It Online") *(-1 byte thanks to @Fatalize, but unfortunately +6 bytes since I discovered bugs in the older method.)* Same idea as my [Julia answer](https://codegolf.stackexchange.com/a/169177/8774). [Answer] # [Julia 0.6](http://julialang.org/), 29 bytes ``` r->10^ndigits(num(r))==den(r) ``` [Try it online!](https://tio.run/##yyrNyUw0@59m@79I187QIC4vJTM9s6RYI680V6NIU9PWNiU1D8j4X1CUmVeSk6eRm1igkaajwKVhrK9voqMAJA0NdBRMLEG0AZBlaQllampq/gcA "Julia 0.6 – Try It Online") Based on the idea that the output should be true only when the denominator is a power of ten with as many zeros as there are digits in the numerator. Takes input as a `Rational` type, checks that the denominator is equal to 10 raised to the number of digits in the numerator. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 57 bytes ``` import StdEnv,Text $b#[u,v:_]=split"/"b =v==""<+10^size u ``` [Try it online!](https://tio.run/##dZBdS8MwFIav219xyHbRYaRNbScVc6eC4IWw3c1NsjYbhfSDJi3TH29M4uZGYTcJeZ7znkNOLjirddUUveBQsbLWZdU2nYKFKp7rAS/5QfnT7WTV4@Hhc01lK0qFQrT16UApQo83JNrI8ptDrxeKdcqfgOJSSaCwChBBGN2FCcKe98KE5DPse456BpPI8mXXH/Hc4nl4P6pOU8vTxNTbwLnetkXZEV8EkuiKsJ1R4sTIZNaQMB6NzjInzHXKnKe7T8QmM@51EiQi/2LtU2BCQPARsG5PMJgzxsAPLc8VL2ZmW1OLgNIL6Bapf/KdYHupb1/f9NNXzaoy/3u8C6Z2TVf9Ag "Clean – Try It Online") This one is a little shorter but breaks for large numerator/denominators. # [Clean](https://github.com/Ourous/curated-clean-linux), ~~77~~ ~~61~~ ~~60~~ 58 bytes *-1 thanks to [OMᗺ](https://codegolf.stackexchange.com/users/48198/om%E1%97%BA)'s tip on my other answer* ``` import StdEnv,Text $b#[u,v:_]=split"/"b =1<+[48\\_<-:u]==v ``` [Try it online!](https://tio.run/##dZBda4MwFIav9VeEtBeWpWhc7GZp7rbBYBeD9k6lpJoWIX4Qo3R/flni2rUIu0nI85z3HHJywVmtq6boBQcVK2tdVm0jFdiq4rUe0I6flTs/zJIeDet9RrtWlAr68OBSvHlIyHOa7jfLdZ9ROuitYlK5M6B4pzpAQeJBDBF89AlEjvPGRMcXyHVG6hiMA8t3sr/glcUr/2lSHUWWR8TU28Ct3raF8QXfBUjwj7CdIRnFxMTWYD@cjI7jUZjrmrlNHz8Rmsy011XgAP@JzKWACQG81GPyhBEwZ4gAP7c8V7xYmG3NLQKU3sFxkfo7Pwp26vTy/UO/fNWsKvPfx6dg6tjI6gc "Clean – Try It Online") This uses [Neil's method](https://codegolf.stackexchange.com/a/169171/18730), it's a bit shorter than doing it directly. There's some trickery with conversion overloading, where `1<+[48\\_<-:u]` converts `[Int]` to `[Char]` and then to `{#Char} (:== String)`, but `Int` directly to `String`. # [Clean](https://github.com/Ourous/curated-clean-linux), ~~91~~ 89 bytes ``` import StdEnv,Text t=toInt $a b#[b,c:_]=map t(split"/"b) #d=t(a<+b) =d/c==t a&&d-d/c*c==b ``` [Try it online!](https://tio.run/##dZBLa4NAEIDP@iuGNQRtNxitpli6t7YQ6KGQ3NJQRt0EYX2gk5L@@dpdmzRB6GV35/vmwU6mJFZ9WecHJaHEouqLsqlbghXlz9UnX8sj2SSoXlZkTxBSZ5Py7OFjK0psgNyuUQUxn6We7eSCXHy81U@R@5kQBDid5jP9vtFR2q8IW7IdINlRBwI2LgsYZ3d@xLhlvaDqpMdta6CWxsHc8HV7OOGFwQv/fpQdx4bHkc43BZd805YlJ3xVEM3/EaYziwYxMokxgR@ORifJIPR1rrlMHz4R6ppxr7MI5sGf2NoCUClw311s9wEHfYYc5LGRGcnc09uaGDFwEOLKDNvsv7Odwn3Xz5av/dNXhWWR/QZvCmlXt@UP "Clean – Try It Online") Defines a function `$ :: String String -> Bool` which extracts the numerator and denominator, string-concatenates the integer part and the numerator, and checks equivalence. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '/¡ćg°Q ``` Only takes the fractions as input. [Try it online](https://tio.run/##MzBNTDJM/f9fXf/QwiPt6Yc2BP7/b6xvaAAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Wqa7wqG2Sgrp95X91/UMLj7SnH9oQ@F/nf7S6sb6hgbqOuqkpkAYxLC0tQSwgU0FBAShrAhQz0zcHyUBVmMAUqBvqGwFJIyAF5gIZhgaG6rEA). **Explanation:** ``` '/¡ # Split the input by '/' # i.e. '3/10' → ['3', '10'] ć # Head extracted: # i.e. ['3', '10'] → 10 and 3 g # Take the length of the numerator # i.e. '3' → 1 ° # Take 10 to the power of this length # 1 → 10**1 → 10 Q # Check if that value equals the denominator # 10 and 10 → 1 (truthy) ``` **Or a more general explanation:** We have to validate two things: * Is the denominator a factor 10 (`1, 10, 100, 1000`, etc.)? * Does the length of the numerator + 1 equal the length of the denominator? + This second part is done by checking if the denominator as is, is equal to 10 to the power of the length of the numerator, which saves 2 bytes PS: If we could take the numerator and denominator as separated inputs, just 3 bytes would have been enough: `g°Q`. [Answer] # JavaScript, 26 bytes Takes input in currying syntax (`f(x)(y)`) where `x` is the integer and `y` is the fraction as a string. ``` x=>y=>x==eval(x+y)-eval(y) ``` [Try it online](https://tio.run/##dY@9DoIwFEZ3n4I0Dm0oP0WKYSibT@CIJG0EjAZbosS0UZ8dazFBB@9wc873DTf3JG7iur8c@yGQqm7Glo2aFYYVmrHmJjqofYMCRwaNeyWvqmvCTh1guSgJBqsoBRX@IIkdZxhk0dohpRhQaoupSTHIZ4m/bY1B6mzSHAMSJRPmVuyaS3ssse2PkZi8rQrPooew1NhUiBV8eddP78HDXtTbQVwGmCGfe8u7ebpsI2uYv5OHx/0WamS/ROFJHSXfyeDP7CRH4ws) [Answer] # Java 10, ~~107~~ ~~70~~ ~~67~~ 57 bytes ``` f->new Long(f.split("/")[1])==Math.pow(10,f.indexOf("/")) ``` Welcome to the world without `eval`.. -40 bytes by creating a port of [*@ChasBrown*'s Python 2 answer](https://codegolf.stackexchange.com/a/169178/52210). -10 bytes thanks to *@Shaggy* (I should have read *@ChasBrown*'s answer better and his use of `find` (`indexOf`)..) [Try it online.](https://tio.run/##jY@xboMwFEV3vuKJyUiNwWnSikZ07NSkQ7pFGRywE6eOjbBJiiq@nRpK1xjJsvR0j86770yvdHYuvrpcUmNgTYX6CQCEsqziNGew6UeAg9aSUQU52tpKqCPwaOWCNnCfsdSKHDagIIOOz14Vu8G7VkfEsSmlsCiMw2hH9lGWrak94VLfEEkeOBaqYN8ffMijrhe6V9YH6XSj9apFARdXa1y82wON/jrFMXxWtT01w7RtjGUXrGuLSwdaqZDCOQofY5I4@@outFw6yo@ladpzd8Ex@W/4RqVhzYun4sK7@il@9tebdsQkauG/dOBIPPcycwdNUDmMJGTE2qDtfgE) **Explanation:** ``` f-> // Method with String parameter and boolean return-type new Long(f.split("/")[1]) // Take the denominator as integer ==Math.pow(10, // And check whether it is equal to 10 to the power of: f.indexOf("/")) // the length of the numerator-String ``` [Answer] # [Haskell](https://www.haskell.org/), ~~47~~ 40 bytes *-7 thanks to [OMᗺ](https://codegolf.stackexchange.com/users/48198/om%E1%97%BA)* ``` f b|(u,v)<-span('/'<)b="/1"++('0'<$u)==v ``` [Try it online!](https://tio.run/##BcFBCoAgEADArywSuIuFSlf3MQpJkolkeurvNnP6dh05zxkhfNjXQW5r1ReUWjoKLLQVSqE00i2dmMe8fSrAUJ9UXkCMIHZtjSCaPw "Haskell – Try It Online") A port of my Clean answer using Neil's method. [Answer] # [Perl 5](https://www.perl.org/) -p, 23 bytes ``` $_=eval=~s/..//r eq$_+0 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3ja1LDHHtq5YX09PX79IIbVQJV7b4P9/I0N9QwODf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") Takes the fractional part alone as input (as allowed by OP), outputs 1 for true and nothing for false. ``` $_= # assign to be printed by -p eval # evaluate fraction to get 0.something, for eg. 0.54 =~s/..//r # remove the 0. part, giving 54 eq # string equality check $_+0 # after first coercing input to number to remove / and denominator ``` The decimal part taken by itself would be exactly equal to the numerator only when the denominator is the immediate next power of ten greater than the numerator, which is the condition we need to check for. [Answer] # Noether, 17 bytes ``` I#I"/"^WL1-%WL_=P ``` [**Try it online!**](https://beta-decay.github.io/noether?code=SSNJIi8iXldMMS0lV0xfPVA&input=OTk5CiI5OTkvMTAwMCI) ## Explanation So how does this work? Well, if you look at the test cases, the only true cases are when the denominator is a power of ten, \$10^a\$, where \$a\$ is the length of the numerator plus one (\$a = \lfloor \log\_{10} n \rfloor + 1\$, where \$n\$ is the numerator and \$\lfloor x \rfloor\$ represents the flooring function). ``` I# - Push the first input then pop it off the stack I"/"^ - Push the second input and split the string at "/" W - Convert the top (the denominator) of the stack from a string to a number L1- - Take the log 10 of the top of the stack and subtract 1 (a) % - Rotate the stack WL_ - Convert the top of the stack (the numerator) to a number, take the log10 and floor the result (b) = - Check if a and b are equal P - Print the top of the stack ``` [Answer] # [TeaScript](https://esolangs.org/wiki/TeaScript), 25 bytes First input is the fraction, second is the integer. *I just started in TeaScript so it might be golfed down a lot* ``` s"/")▒⌐ep(xs"/")░.n ``` [Try it online!](https://vihan.org/p/TeaScript/#?code=%22s%5C%22%2F%5C%22)%E2%96%92%E2%8C%90ep(xs%5C%22%2F%5C%22)%E2%96%91.n%22&inputs=%5B%22999%2F1000%22,%22999%22%5D&opts=%7B%22ev%22:false,%22debug%22:false,%22nox%22:false%7D) [Answer] # [R](https://www.r-project.org/), 53 bytes ``` function(n,x=el(strsplit(n,"/")))x[2]==10^nchar(x[1]) ``` [Try it online!](https://tio.run/##dc7dCsIgFMDx@55i2I1Cw4@2QsheZCwYY7LBsFAH9vQmUm0Wnjv58fcc7eWl9HJRvZ3uCqqDE8MMjdXmMU82vAEGCCHXsFYISm6qHzsNXUNb5CUER1wBtC/eU14L2c1meO4iUfK1IFYvdoxywudcVNeh@mRJxDfwEyWUSBVp899KFLPcEZyvWXIDC1FmUyBK6B/5Fw "R – Try It Online") Takes only the fractional part as input. As mentioned by xnor in a comment: > > This seems to be equivalent to "given an input that doesn't matter and > two numbers as a string separated by a slash, determine whether the > second number equals 10 to the power of the length of the first > number". > > > [Robert S.'s answer](https://codegolf.stackexchange.com/a/169176/80010) is less golfy but much more interesting than mine. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~67~~ ~~56~~ 55 bytes * Saved eleven bytes thanks to [O.O.Balance](https://codegolf.stackexchange.com/users/79343/o-o-balance). * Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` m;x(char*_){for(m=1;*_++;m*=10)*_*=*_^47;m=m==atoi(_);} ``` [Try it online!](https://tio.run/##ZY7BToNAEIbP8BRkDMnudhrYFoq4WXvyAYg9GglZQIksUOBQ0/TZkVI1a7z8M/nmm@RX6zelpkmLE1HvWc9Sei7bnmjJBUtXK6GZ5D5lKZMsfQ0ioaWWMhvbiqRUXKa7vCirpnAOT88H8oFHLOgw9qr7JAkeqej6qhlLAsTd5tRx7wdn/ei4ubOX1yTuQF8awOvfiSQUi2VIWeyhy4ahyOEByqyq54UKW2dVQ@jZtpaiidRZXbeKxPF8s2xrqcARtl4A6FMTcB@Q/5Adws6LDCUMEcJwlkwrQIhv6NcL/P8sQggWZsIYgXsbE8QzmuNb5Ea5zWz@eb4x7vOFXaYv "C (gcc) – Try It Online") [Answer] # Excel, 52 bytes ``` =10^FIND("/",B1)/10-MID(B1,FIND("/",B1)+1,LEN(B1))=0 ``` Ignores the Integer input. Basically: `IS Denominator = 10^LEN(Numerator)` --- For denominators limited to `<10^9`: 48 bytes: ``` =10^FIND("/",B1)/10-MID(B1,FIND("/",B1)+1,1E9)=0 ``` --- Bulk of logic is splitting on `/`. If input could be taken separately, 16 bytes: ``` =10^LEN(B1)-C1=0 ``` [Answer] # [Elixir](https://elixir-lang.org/), 81 bytes ``` fn b->[n,d]=String.split b,"/";String.to_integer(d)==:math.pow 10,byte_size n end ``` [Try it online!](https://tio.run/##LcixDoIwEADQX7l0gqQWCJum7k4OjsQQaq94CR5Newnqz5eFNz5c6EupBFsCgztdB9b@aR@SiGeT40ICTqtGXY6SdSQWnDFVvrb2/JnkbeK6Qddq9xMcM/0RGJB9ud0NcY74EgimUn3TtaouOw "Elixir – Try It Online") Might be able to get somewhere with `{n,"/"<>d}=Integer.parse b`, but not sure how. [Answer] # [2DFuck](https://gitlab.com/TheWastl/2DFuck), 86 bytes ``` ..!x..!...,,,,[>,,,,,,,,],,,,,,,,,[v!],[v!],[v!],![v!],,,[,,[v!],[v!],[v!],[v!]<,,,]r. ``` [Try it online!](https://tio.run/##M0pJK03O/v9fT0@xAoj19PR0gCDaTgcKYmEMnegyxVgkQhFMAoUxZECEDUhrkd7//8b6hgYA "2DFuck – Try It Online") Takes input without integer part. [Answer] # C (gcc/clang), ~~59~~ ~~49~~ 47 bytes ``` f(a,b){a=atoi(b=strchr(a,47)+1)==pow(10,b+~a);} ``` Port of [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown)'s Python 2 [answer](https://codegolf.stackexchange.com/a/169178/52210). Try it online [here](https://tio.run/##rZDLTsMwEEX3fMXgld2HHJeUklYWO76AJZuJFTeWnIdsR6hU5dMJTmilSqxo8G7Gd87cO2q5V6rvNcVFzo4oMTSG5tIHp0oXm@mGzQWTsm3eqUgW@fwT2e7UV2hqyuB4B/GpEh3MECRUaG2j6NPMm4@i0XT4YWw3qoym98jAFaFzNYifJufw6rpQHsZq2Noe4lYgD1wk5DzZOlMHTaNHBs9AwjjwVhPYAtFofTEUZ@0VYr2OjKmQLMsGyk2Ytguekkt1yfsyqra/A6cTrT7yzdSw/3Cw9PZ7XVEEX00krCJiso0IEYn4K@TUfyltce/7pa2@AQ). Ignores the integer part of the input. Thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) for golfing 2 bytes. Ungolfed: ``` f(a, b) { // function returning an int and taking a string as input; also declaring another string variable // this abuses the parameters as much as possible, omitting the type int and implicitly converting it to char * a = // return a truthy or falsey value based on atoi(b = strchr(a, 47) + 1) // the denominator (as integer; 47 is the ASCII code for '/') == pow(10, b + ~a); // is equal to 10 to the power of the length of the numerator-string } ``` [Answer] # ForceLang, ~~86~~ 78 bytes ``` set a io.readnum() set b io.readnum() set d number.parse a+b+"" io.write d=a+b ``` ]
[Question] [ Your task is to find out how often you need to "shuffle" a given list with the following operation until you get back the original list. ``` start with a list: (1 2 3 4 5 6 7 8 9) split it into the elements at odd and even indices (1 3 5 7 9) (2 4 6 8) concatenate these two list (1 3 5 7 9 2 4 6 8) ``` Input: A list Output: The number of iterations it takes until you get back the original list ## Examples ``` (1 2 3) -> (1 3 2) -> (1 2 3) => 2 (1 2 3 4 3 2 1) -> (1 3 3 1 2 4 2) -> ... => 3 (1 2 3 4 5 6 7 8 9 10) -> ... => 6 (1 2 3 4 5 6 7 8 9 10 11) -> ... => 10 "abab" -> "aabb" -> "abab" => 2 "Hello, World!" -> "Hlo ol!el,Wrd" -> ... => 12 (1 0 1 1 0 0 0 1 1 1) -> ... => 6 (1 0 0 1 1 1 0 0 0 0 1) -> ... => 10 (1 1 1 1 1 1 1) -> (1 1 1 1 1 1 1) => 1 ``` ## Rules * You can use lists of any type (that supports at least two distinct values) * You can assume the the list has at least two elements * The odd/even indices are determined using 1-based indexing * You have to apply the operation at least once * If your language has a built-in for finding fixed points consider adding a non-builtin solution as well * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` #{x@<2!!#x}\ ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs1KurnCwMVJUVK6ojeHiSos2VDBSMI6FMRRMgNhIwRBZwFTBTMFcwULBUsHQAJe4giFYi1JiUmKSEpjlkZqTk6+jEJ5flJOiqATRB1SmACINoCxDmDCUC5UygEkgwVgA6yonqg==) `{ ... }\` Iterate until reaching the first value again (or a fixed point). Collect intermediate values. `2!!#x` 2 mod range of length *x*. Sequence of alternating 0s and 1s the same length as *x*. `x@<` Grade up, then index into *x*. Sorts *x* by that sequence. `#` Length. Counts the number of intermediate results. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` µ¥zS ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNXpTJmZvb3Rlcj0maW5wdXQ9MSUyQzIlMkMzJTJDNCUyQzUlMkM2JTJDNyUyQzglMkM5JTJDMTAmZmxhZ3M9TA==) or [verify all test cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNXpTJmZvb3Rlcj0maW5wdXQ9JTVCMSUyQyUyMDIlMkMlMjAzJTVEJTIwJTNEJTNFJTIwMiUwQSU1QjElMkMlMjAyJTJDJTIwMyUyQyUyMDQlMkMlMjAzJTJDJTIwMiUyQyUyMDElNUQlMjAlM0QlM0UlMjAzJTBBJTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDUlMkMlMjA2JTJDJTIwNyUyQyUyMDglMkMlMjA5JTJDJTIwMTAlNUQlMjAlM0QlM0UlMjA2JTBBJTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDUlMkMlMjA2JTJDJTIwNyUyQyUyMDglMkMlMjA5JTJDJTIwMTAlMkMlMjAxMSU1RCUyMCUzRCUzRSUyMDEwJTBBJTVCMSUyQyUyMDAlMkMlMjAxJTJDJTIwMSUyQyUyMDAlMkMlMjAwJTJDJTIwMCUyQyUyMDElMkMlMjAxJTJDJTIwMSU1RCUyMCUzRCUzRSUyMDYlMEElNUIxJTJDJTIwMCUyQyUyMDAlMkMlMjAxJTJDJTIwMSUyQyUyMDElMkMlMjAwJTJDJTIwMCUyQyUyMDAlMkMlMjAwJTJDJTIwMSU1RCUyMCUzRCUzRSUyMDEwJTBBJTVCMSUyQyUyMDElMkMlMjAxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTJDJTIwMSU1RCUyMCUzRCUzRSUyMDElMEElMjJhYmFiJTIyJTIwJTNEJTNFJTIwMiUwQSUyMkhlbGxvJTJDJTIwV29ybGQhJTIyJTIwJTNEJTNFJTIwMTImZmxhZ3M9Q0w=) ``` µ¥zḞ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNXolRTElQjglOUUmZm9vdGVyPSZpbnB1dD0xJTJDMiUyQzMlMkM0JTJDNSUyQzYlMkM3JTJDOCUyQzklMkMxMCZmbGFncz1M) or [verify all test cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNXolRTElQjglOUUmZm9vdGVyPSZpbnB1dD0lNUIxJTJDJTIwMiUyQyUyMDMlNUQlMjAlM0QlM0UlMjAyJTBBJTVCMSUyQyUyMDIlMkMlMjAzJTJDJTIwNCUyQyUyMDMlMkMlMjAyJTJDJTIwMSU1RCUyMCUzRCUzRSUyMDMlMEElNUIxJTJDJTIwMiUyQyUyMDMlMkMlMjA0JTJDJTIwNSUyQyUyMDYlMkMlMjA3JTJDJTIwOCUyQyUyMDklMkMlMjAxMCU1RCUyMCUzRCUzRSUyMDYlMEElNUIxJTJDJTIwMiUyQyUyMDMlMkMlMjA0JTJDJTIwNSUyQyUyMDYlMkMlMjA3JTJDJTIwOCUyQyUyMDklMkMlMjAxMCUyQyUyMDExJTVEJTIwJTNEJTNFJTIwMTAlMEElNUIxJTJDJTIwMCUyQyUyMDElMkMlMjAxJTJDJTIwMCUyQyUyMDAlMkMlMjAwJTJDJTIwMSUyQyUyMDElMkMlMjAxJTVEJTIwJTNEJTNFJTIwNiUwQSU1QjElMkMlMjAwJTJDJTIwMCUyQyUyMDElMkMlMjAxJTJDJTIwMSUyQyUyMDAlMkMlMjAwJTJDJTIwMCUyQyUyMDAlMkMlMjAxJTVEJTIwJTNEJTNFJTIwMTAlMEElNUIxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTVEJTIwJTNEJTNFJTIwMSUwQSU1QiUyMmElMjIlMkMlMjJiJTIyJTJDJTIyYSUyMiUyQyUyMmIlMjIlNUQlMjAlM0QlM0UlMjAyJTBBJTVCJTIySCUyMiUyQyUyMmUlMjIlMkMlMjJsJTIyJTJDJTIybCUyMiUyQyUyMm8lMjIlMkMlMjIlMkMlMjIlMkMlMjIlMjIlMkMlMjJXJTIyJTJDJTIybyUyMiUyQyUyMnIlMjIlMkMlMjJsJTIyJTJDJTIyZCUyMiUyQyUyMiElMjIlNUQlMjAlM0QlM0UlMjAxMiZmbGFncz1DTA==) ``` µ¥^ḥ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNSU1RSVFMSVCOCVBNSZmb290ZXI9JmlucHV0PTElMkMyJTJDMyUyQzQlMkM1JTJDNiUyQzclMkM4JTJDOSUyQzEwJmZsYWdzPUw=) or [verify all test cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCNSVDMiVBNSU1RSVFMSVCOCVBNSZmb290ZXI9JmlucHV0PSU1QjElMkMlMjAyJTJDJTIwMyU1RCUyMCUzRCUzRSUyMDIlMEElNUIxJTJDJTIwMiUyQyUyMDMlMkMlMjA0JTJDJTIwMyUyQyUyMDIlMkMlMjAxJTVEJTIwJTNEJTNFJTIwMyUwQSU1QjElMkMlMjAyJTJDJTIwMyUyQyUyMDQlMkMlMjA1JTJDJTIwNiUyQyUyMDclMkMlMjA4JTJDJTIwOSUyQyUyMDEwJTVEJTIwJTNEJTNFJTIwNiUwQSU1QjElMkMlMjAyJTJDJTIwMyUyQyUyMDQlMkMlMjA1JTJDJTIwNiUyQyUyMDclMkMlMjA4JTJDJTIwOSUyQyUyMDEwJTJDJTIwMTElNUQlMjAlM0QlM0UlMjAxMCUwQSU1QjElMkMlMjAwJTJDJTIwMSUyQyUyMDElMkMlMjAwJTJDJTIwMCUyQyUyMDAlMkMlMjAxJTJDJTIwMSUyQyUyMDElNUQlMjAlM0QlM0UlMjA2JTBBJTVCMSUyQyUyMDAlMkMlMjAwJTJDJTIwMSUyQyUyMDElMkMlMjAxJTJDJTIwMCUyQyUyMDAlMkMlMjAwJTJDJTIwMCUyQyUyMDElNUQlMjAlM0QlM0UlMjAxMCUwQSU1QjElMkMlMjAxJTJDJTIwMSUyQyUyMDElMkMlMjAxJTJDJTIwMSUyQyUyMDElNUQlMjAlM0QlM0UlMjAxJTBBJTIyYWJhYiUyMiUyMCUzRCUzRSUyMDIlMEElMjJIZWxsbyUyQyUyMFdvcmxkISUyMiUyMCUzRCUzRSUyMDEyJmZsYWdzPUNM) --- > > Don't worry, the stack languages with single-byte uninterleave operators are going to be even shorter :P > > > lol #### Explanation ``` # Implicit input µ¥ # Collect while unique: z # Uninterleave into two pieces # [1,2,3,4,5,6] -> [[1,3,5],[2,4,6]] S # Then flatten the nested list # [[1,3,5],[2,4,6]] -> [1,3,5,2,4,6] Ḟ # Alternative flatten built-in # [[1,3,5],[2,4,6]] -> [1,3,5,2,4,6] ^ # Or, uninterleave and push separately # [1,2,3,4,5,6] -> [1,3,5] [2,4,6] ḥ # Then concatenate the two lists # [1,3,5] [2,4,6] -> [1,3,5,2,4,6] # Finally, the L flag takes the length # Implicit output ``` [Answer] # [J](http://jsoftware.com/), ~~26~~ 24 bytes ``` i.~_:0}(\:2|#\)^:(3<@^#) ``` [Try it online!](https://tio.run/##VYvLCoJQEIb3PcVPgpfI8RztOmRIQato0VaPEpFmm14gfXU7mWIxzDAz3/c/mjFZOUKGhSkEWLdL2J@Ph6akOmNR2Qn7LyNxUraDTZQaTuOMTjuCxrIilZm2Up1St0JLYzZUESkdkq7LOnzhIiRPeyVFvTIhT3vm1txTzB6jg7fr/YkcEj6CvwMzzLHAEiusIcXAhO7PFN0mB/RT/VN8E80b "J – Try It Online") Accepts numeric lists The maximum number of iterations until we return to the input is bounded by [Landau's function](https://en.wikipedia.org/wiki/Landau%27s_function) \$g(n)\$, and it can be shown that: $$ {\displaystyle g(n)\leq e^{n/e}} $$ For golf reasons, I simply round that to: $$ {\displaystyle g(n)\leq 3^{n}} $$ and iterate that many times. Note I could trade bytes for efficiency here and iterate until I see the input again, but this approach was shorter. * `(\:2|#\)` Apply the needed permutation -- equivalent to sorting down by `1 0 1 0...` * `^:(3<@^#)` Do that \$3^n\$ times, saving results * `_:0}` Convert the first item on the list, which is the input itself, to infinity, so that match will be skipped. * `i.~` Index of the input within that list. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ŒœẎ$ƬL ``` [Try it online!](https://tio.run/##y0rNyan8///opKOTH@7qUzm2xuf/4XbNyP//o6MNdRSMdBSMY3W4YEwdBRMwCWQbogub6iiY6SiY6yhY6ChYAuUNCCoAYpApSolJiUlKQNoD6JR8HYXw/KKcFEUliG6QIjAygCEIF2Y9ihiSKgOEEnQUGwsA "Jelly – Try It Online") Don't worry, the stack languages with single-byte uninterleave operators are going to be even shorter :P ``` Ƭ Repeat while unique, collecting all results: Œœ Split into odd and even-indexed elements, Ẏ$ and concatenate. L How many results are there? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` vDÅ≠})Ùg ``` [Try it online](https://tio.run/##yy9OTMpM/f@/zOVw66POBbWah2em//8fbahjpGOsY6JjqmOmY65joWOpY2gQCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/zKXcztPz6nVPDwz/b/O/@hoQx0jHeNYHQitYwLERjqGSHxTHTMdcx0LHUsdQwMcwjqGIA1KiUo6SklADKFBIh5AVioQ50BxPhCDoAIQh0P5RVC5FCBWVALbADRQB0QaQFmGUFEoDypjABVHgrGxAA) (the test suite uses the faster alternative `ι˜` instead of `Å≠`). **Explanation:** Although 05AB1E has an unshuffle builtin `Å≠` (even though `ι˜` does the same and is faster..), it unfortunately lacks a "*Repeat until unique*" builtin.. ``` v # Loop the (implicit) input-length amount of times: D # Duplicate the current list # (which will be the implicit input-list in the first iteration) Å≠ # Unshuffle it }) # After the loop: wrap all lists on the stack into a list Ù # Uniquify this list of lists g # Pop and push its length # (which is output implicitly as result) ι # Uninterleave it into a pair of lists ˜ # Flatten it to a single list ``` [Answer] # Google Sheets, 107 bytes `=let(d,torow(A:A,3),_,lambda(_,a,n,sort(let(b,torow(wrapcols(a,2),3),if(and(b=d),n,_(_,b,1+n))))),_(_,d,1))` Put the input in cells `A1:A` and the formula in `B1`. The formula is self-contained. Uses *singularize(wrap())* like the [Excel answer](https://codegolf.stackexchange.com/a/264442/119296) but does not depend on named functions or named ranges. [Try it](https://docs.google.com/spreadsheets/d/1P8-wj-Zkf0bw7PgVKYAbs53JNxvvQCaXgfNOROHGWWQ/edit#gid=0). [Answer] # [Python](https://www.python.org), 65 bytes ``` lambda s,j=1:j*((t:=s[:len(s)-1|1])==(t*2**j)[::2**j])or f(s,j+1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZHdToMwFMfjLU9xxlWLhVCYc5LUxLu9wS5wWYqDyNJRQmuyJb6JN0uMvoRPok9jC8wNnW1STs_5_85HeXmvd_pRVvvXgt2_PenCn37eCb7JVhwUWTOarD2EdMJUmoi8Qgr79JkuMGNIe5HnrXGaJPa7wLKBAhnmkuI-0VthfFsoK5C1YUOcOFASCQy2gapFqZEL7BZc7IB1lpVGElvJkiztPah5o0tdysoI_U6o2oDSTVkjnNLEpwsHdLNLQLHU2_AamTRE9fkxNtF8-5DXuhMoc68bW0kR0y0msm92_3XxgShEEGNbypgxRAez9Q6X6TtyuhCMrRboEYzBBsZ9giAIOiA-AlcwgWuYwg3Q8ET0q8LkPACUnmMMQEPH5RnPuufiPDtYre_PaodwZ7kQksBcNmI16vQzIUGKUS7IvFm5gyFoO7bpAewZ9tbZhk6n-BH2UPgf0k2BKJzsw8sOXAOi-4nf) ## How? This is based on the observation that in zero-based indexing the reshuffle can be written as n -> 2n mod N where N is the largest odd number not greater than the length of the input. (If the length is even the last point is a fixed point, so it can be ignored.) [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 6 bytes ``` ᶦ{ĭ,ᵖ≠ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FmsfbltWfWStzsOt0x51LlhSnJRcDJVZcHNutKGOkY5xLBeE1jEBYiMdQyS-qY6ZjrmOhY6ljqEBDmEdQ6AGpcSkxCQlLiWP1JycfB2F8PyinBRFJZAGoLwOiDSAsiCmw3lQGQOoOBKMhbgSAA) Nekomata has a single-byte uninterleave operator, but still can't beat Jelly, because it doesn't have a "repeat while unique" operator. ``` ᶦ{ĭ,ᵖ≠ ᶦ{ Repeat until failure: ĭ Uniterleave , Join ᵖ≠ Check if the result is unequal to the input ``` `-n` counts the number of iterations. [Answer] # Excel, 93 bytes Define: `a` as `=$A$1#` (*7 bytes*) `z` as `=LAMBDA(p,q,LET(x,TOCOL(WRAPROWS(p,2),2,1),y,q+1,IF(SUM(N(x<>a))=0,y,z(x,y))))` (*79 bytes*) Within the worksheet: `=z(a,0)` (*7 bytes*) `$A$1#` is a spilled, *vertical* range comprising the list entries. [Answer] # [R](https://www.r-project.org), 70 bytes ``` f=\(x,l=0,y=c(x[!0:1],x[!1:0]),`-`=list)`if`(-y%in%l,0,1+f(y,c(l,-y))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU5LCsIwFDyLi8J7OIG81oUEsvUSWogUA4GgxUZozuImLnoob2OKXcxnMTPM-_Msi3-km11eyavj9-TthWZEq5HtQPN5p430qCpG9wynnI1hSuyCd6RyE-5NhIbsPWUMFKEyM29rMl3HMWZaGySmqwFBiw6HihbCECN6pWrXG1uxlL_-AA) [Answer] # [Ruby](https://www.ruby-lang.org/), 55 bytes ``` ->l{k=*l;1.step.find{w=-2;l==k=k.map{k[w+=2]||k[w=1]}}} ``` [Try it online!](https://tio.run/##DcbRCsIgFAbgV9l1/UrHVivk9CLiRaOE0IW0DRnqs9u@q@@3jltz3MQjZM@HoEnOyztK9/m@cmKhdGD27OX0jNmbdGRlS9nDZGutLXbOGILCGT0uuGLADXfQCUTWtj8 "Ruby – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 31 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.875 bytes ``` yJ)↲ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+bD0iLCIiLCJ5SinihrIiLCIiLCJbMSwgMiwgM10gPT4gMlxuWzEsIDIsIDMsIDQsIDMsIDIsIDFdID0+IDNcblsxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5LCAxMF0gPT4gNlxuWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMV0gPT4gMTBcblsxLCAwLCAxLCAxLCAwLCAwLCAwLCAxLCAxLCAxXSA9PiA2XG5bMSwgMCwgMCwgMSwgMSwgMSwgMCwgMCwgMCwgMCwgMV0gPT4gMTBcblsxLCAxLCAxLCAxLCAxLCAxLCAxXSA9PiAxXG5cImFiYWJcIiA9PiAyXG5cIkhlbGxvLCBXb3JsZCFcIiA9PiAxMiJd) > > the stack languages with single-byte uninterleave operators are going to be even shorter > > > ~ some jelly answer, probably [Answer] # [R](https://www.r-project.org), ~~54~~ ~~52~~ 51 bytes *Edit: -3 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(x,y=x){while(sd((y[]=matrix(y,2,,T))-x))T=T+1;+T} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZLBToQwEEATj37FLF7a7EBo2V0xpnte7yR7UA8gEDepNkGMEOOXeEETP0q_xkLZtaCrF9uhTBveyzDw_FI0r7l4uy9zN3wPLkiFtajo48P1RmbkLiWkPr8UN3FZbCpSI0eMKHUrSiMRTdnpNHoy6MeBzMkVYQgcIaD0CNwlEAYBcNqnXJ_DcIgl8EOLQ5h1q86Z7QigxWe9y_M8wwb_ys4RFgjHCCHCiZb4vcUgo7IXf-P6Yj8rNM98LdCdCyN1dlsSJ07ixOmfduI4SRyTtcfwbfR9s_hVJqVCWKtCppOdaCUVKDnJJK6L1Bm8P9s1vi20C38bZrun-HEDBogl8X8xbBvQCcbx9fGsSYew-emaxtw_AQ) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes ``` ⊞υθW‹№υθ²⊞υ⭆²Φ§υ±¹﹪⁺κν²I⊖Lυ ``` [Try it online!](https://tio.run/##NY0xC8IwEEb3/opzu0Ac7OokFVGwUnBwDs3RFs9Ek4v672O0OH/ve68fTei94Zy7FEdMGh5qXb3GiQnwSDFi45OTedBQKwV/8CxhckNr7lhr2E0sFHAjB2fp/Z1PNBghXKlya71N7LHjFPGqwc0mVUpdcQg2JgpuqQ90IydkS9kNUio/KOc9MXsNFx/YLqq8fPIH "Charcoal – Try It Online") Link is to verbose version of code. Only works on strings. Explanation: ``` ⊞υθ ``` Push the string to the predefined empty list. ``` W‹№υθ² ``` Repeat until a second copy of the string is found. ``` ⊞υ⭆²Φ§υ±¹﹪⁺κν² ``` Shuffle the most recent string and push it to the list. ``` I⊖Lυ ``` Output the number of shuffles taken. 28 bytes to work on strings or lists: ``` ⊞υθW‹№υθ²⊞υΣE²Φ§υ±¹﹪⁺κν²I⊖Lυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iOSOxKDk_MWfBgqWlJWm6FjdnBpQWZ2iU6igUalpzlWdk5qQqaPikFhdrOOeX5pVAJHQUjDQ1FWAKg0tzNXwTCzSMdBTcMnNKUos0HEs881JSK0CSfqnpiSWpGoaaQE2--SmlOfkaATmlxRrZOgp5EHOAwJoroCgTaLhzYnGJhktqclFqbmpeSWoK0OK89BKgJWBFS4qTkouhzlweraRblqMUuyM62hBoio6CsY6CCZgEsg1jY7kgygA "Charcoal – Attempt This Online") Link is to verbose version of code. [Answer] # [sclin](https://github.com/molarmanful/sclin), 45 bytes ``` =$a $a"2/` tpose flat"itr1dp"$a !=`"tk* len1+ ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) Takes a list. For testing purposes: ``` [1 2 3 4 5 6 7 8 9 10 11] ; =$a $a"2/` tpose flat"itr1dp"$a !=`"tk* len1+ ``` NOTE: for string-based inputs, use e.g. `["a" "b" "a" "b"]`. ## Explanation Prettified code: ``` =$a $a. ( 2/` tpose flat ) itr 1dp ( $a !=` ) tk* len 1+ ``` * `=$a $a` Input list *a* * `(...) itr` generate infinite list from successive modifications of *a*... + `2/` tpose flat` chunk into pairs, transpose, flatten * `1dp` drop first item to prevent `tk*` from exiting early * `( $a !=` ) tk*` take while not equal to *a* * `len 1+` length + 1 [Answer] # JavaScript (ES6), 64 bytes Expects a list of positive integers. ``` a=>(g=a=>(g[a]^=i=-2)&&1+g(a.map(_=>a[!a[i+=2]|i%a.length])))(a) ``` [Try it online!](https://tio.run/##lY3LDoIwEEX3fkVdSNowEFvxtSg/0qCZINQapESIK/@9VlxIiMSYzNzM49zcC96xzW@m6aLangpXSocypVr2qjA7SCMjwYKAh5pifMWGHmWKao7KhFJkD7PAuCpq3Z0zxhhF5nJbt7Yq4spqWlLF/X02vgERQFbTHyBJr37mP6g1kA2QLZAdkL3Hl//yvr9lvKJ723vgg1VM4h9kYOKTjnF5yj0B "JavaScript (Node.js) – Try It Online") ### How? We can apply the shuffle by doing: ``` a.map((_, i) => a[!a[i * 2] | i * 2 % a.length]) ``` This code first collects all values at even (0-based) indices. When `a[i * 2]` is not defined anymore, it starts collecting values at odd indices. For golfing reasons, we rather start with \$i=-2\$ and do: ``` a.map(_ => a[!a[i += 2] | i % a.length]) ``` We stop as soon as the same array has been encountered twice and return the number of iterations. [Answer] # [Arturo](https://arturo-lang.io), 49 bytes ``` $->a[1x:a while[i:0arrange'x=>[i%2'i+1]x<>a][1+]] ``` [Try it!](http://arturo-lang.io/playground?yigxrb) ``` $->a[ ; a function taking an input a 1 ; push 1 -- this is our output (count) x:a ; assign a to x while[ ; while... i:0 ; assign 0 to i arrange'x=>[i%2'i+1] ; sort x by its indices' parities x<>a ; x doesn't equal a... ] ; end while predicate [1+] ; ...then increment the output ] ; end function ``` [Answer] # [Haskell](https://www.haskell.org/), 77 bytes ``` o(x:s)=x:e s o _=[] e=o.drop 1 a!b|a==b=1|0<1=1+a!(o b++e b) f a=a!(o a++e a) ``` [Try it online!](https://tio.run/##Xc6xCsIwEAbgPU9xKQ4JtWLW4HUT9AkcisiFplpaezXt0KHvHqsoiMvx8/3wczcaGt@2ka0t6JzlyxH@Jyuprd0/gABz@GqWH7vRX30Q1V/58chqsoPGyXoYBMMFi2UWeVMG7sEIkm4mRIdm3u4MmpSkYnBp6sFpUQHhG@gFpOOd6g4Q@lB3I6xAVZAclqd5DScObSkTHZ8 "Haskell – Try It Online") ]
[Question] [ ## Context We're at war! You need to transfer an important message to your general to inform them from an imminent assault. The thing is, your enemy knows a lot about cryptography : you will need to be more creative in order to encode your message... ## Task Create a program that accepts an ascii message as input, and outputs the encoded message. The message should be encoded this way : each character should get its ascii value shifted by its position in the message. For example, let's encode the message "Hello, world!" ``` H e l l o , w o r l d ! Original message 72 101 108 108 111 44 32 119 111 114 108 100 33 ASCII value 0 1 2 3 4 5 6 7 8 9 10 11 12 Place in the message 72 102 110 111 115 49 38 126 119 123 118 111 45 Encoded ascii (line 1 + line 2) H f n o s 1 & ~ w { v o - Encoded message ``` The message `Hello, world!` should be encoded as `Hfnos1&~w{vo-`. Sometimes the encoded ascii can go beyond printable character. In that case, the value loop back to 32 (read the rules for additionnal informations) ``` T h e r a n d o m g u y Original message 84 104 101 32 114 97 110 100 111 109 32 103 117 121 ASCII value 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Place in the message 84 105 103 35 118 102 116 107 119 118 42 114 129 134 Encoded ascii (line 1 + line 2) 84 105 103 35 118 102 116 107 119 118 42 114 34 39 Corrected encoded ascii (looped back to 32) T i g # v f t k w v * r " ' ``` `The random guy` is then converted into `Tig#vftkwv*r"'` Using the same strat, `zzzzzzzzz` will be converted into `z{|}~ !"#` (ascii values converted into `122 - 123 - 124 - 125 - 126 - 32 - 33 - 34 - 35`) ## Rules * The input message will be composed of printable ascii character (between 32 and 126) * The message should be encoded as described before. * The ascii values of the encoded message should be set between 32 and 126. * The first character of the message should be at position **0**. * If the new ascii value goes *beyond the limit*, it should loop back to **32**. * **Every** character should be encoded. This includes punctuation, spaces etc. * No standard loopholes allowed. * This is codegolf, so the shortest code wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` ⭆S§γ⁺κ⌕γι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKjiWeeSmpFRrpOgoBOaXFGtk6Cm6ZeSkgfqYmCFj//18FA/91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` S Input string ⭆ Map over characters and join ι Current character ⌕ Find position in γ Printable ASCII ⁺ Plus κ Current index § Cyclically indexed into γ Printable ASCII Implicitly print ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~55~~ 54 bytes Output is a list of characters. ``` lambda s,d=33:[chr((ord(c)-(d:=d-1))%95+32)for c in s] ``` [Try it online!](https://tio.run/##NcaxDsIgEADQ3a@4xdxdbE2UmCgJf@GmDhVEMBbIUYf685gOvumVeQo5qWOR5s21vYfx7gaonTNK6YsNQpTFkeWenDau3zGvT4eN2rPPAhZignpry@tyPIcHyJBcHuH5mbED/P6hXgEUiWkixO0rx0SeKjO3Hw "Python 3.8 (pre-release) – Try It Online") [Answer] # [J](http://jsoftware.com/), 22 bytes ``` (95|<:+#\)&.(_32+3&u:) ``` [Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/NSxNa2ystJVjNNX0NOKNjbSN1UqtNP9r/k9TUE9MSlbnAtIhGakKRYl5Kfm5CumllWChKhhQBwA "J – Try It Online") Almost word-to-word translation of [my dzaima/APL solution](https://codegolf.stackexchange.com/a/205572/78410). ### How it works ``` (95|<:+#\)&.(_32+3&u:) NB. Input: string S ( X )&.( Y ) NB. The "Under" operator; do Y, do X and undo Y _32+3&u: NB. Convert chars to codepoints and subtract 32 #\ NB. One-based index <:+ NB. Add to the codepoints minus 1 95| NB. Modulo 95 _32+3&u: NB. Undo this: add 32 and convert to chars ``` [Answer] # [R](https://www.r-project.org/), ~~56~~ 57 bytes ``` function(s)intToUtf8((utf8ToInt(s)-33+1:nchar(s))%%95+32) ``` [Try it online!](https://tio.run/##K/pfnJGZVmL7P600L7kkMz9Po1gzM68kJD@0JM1CQ6MUSIbke@aVAIV1jY21Da3ykjMSi4A8TVVVS1NtYyNNiAEaSh6pOTn5Ogrl@UU5KYpKmlxQ4ZKMVIWixLyU/FyF9NJKhHgVDCCEEoHM/wA "R – Try It Online") *Edit: thanks to Giuseppe for bug-spotting!* I am beginning to despise string manipulations in R, and the `intToUtf8()` / `utf8ToInt()` function names in particular... [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 21 bytes ``` {95|⍵+⍳≢⍵}⍢(¯32+⎕UCS) ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/qG@qp/@jtgkGXGlAUuN/taVpzaPerdqPejc/6lwEZNU@6l2kcWi9sZE2UGmoc7Dmf00uIAuoOE1BPSQjVaEoMS8lP1chvbRSHSFRBQPq/wE "APL (dzaima/APL) – Try It Online") Just trying out the experimental Under operator `⍢` because the task is screaming for it. ### How it works ``` {95|⍵+⍳≢⍵}⍢(¯32+⎕UCS) ⍝ Input: string S ⍢(¯32+⎕UCS) ⍝ Convert S to Unicode codepoints and subtract 32 { ⍵+⍳≢⍵} ⍝ Add the index to each char 95| ⍝ Modulo 95 ⍢(¯32+⎕UCS) ⍝ Undo the operation: ⍝ Add 32 and convert back to Unicode chars ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žQDIkā<+è ``` -1 byte by porting [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/205579/52210), so make sure to upvote him! I/O as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//6L5AF8/sI4022odX/P8frRSipKOUAcSpQKwAxEVAnAjEeUCcAsT5QJwLlUsH4lIgrlSKBQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn1lcOj/o/sCXSKyjzTaaB9e8d9L579Hak5Ovo5CeX5RTooiV0hGqkJRYl5Kfq5CemklVxUMAAA). **Explanation:** ``` žQ # Push the printible ASCII string builtin D # Duplicate it I # Push the input-list of characters k # Get each index in the ASCII string ā # Push the list [1, length] (without popping) < # Decrease it by 1 to make it a 0-based range [0, length) + # Add the values at the same positions in the lists together è # Index each into the ASCII string (0-based and with automatic wraparound) # (after which the resulting list of characters is output implicitly) ``` [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 32 bytes -1 byte thanks to @Abigail ``` s/./chr 32+($x++-32+ord$&)%95/ge ``` [Try it online!](https://tio.run/##K0gtyjH9n1upUmH9v1hfTz85o0jB2EhbQ6VCW1sXyMgvSlFR01S1NNVPT/3/3yM1JydfR6E8vygnRZErJCNVoSgxLyU/VyG9tPJffkFJZn5e8X/dAgA "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~48~~ ~~47~~ 46 bytes Saved a byte thanks to [640KB](https://codegolf.stackexchange.com/users/84624/640kb)!!! Saved a byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!! ``` i;f(char*s){for(i=32;*s;)*s++=(*s-i--)%95+32;} ``` [Try it online!](https://tio.run/##ZZDfaoMwFMbv@xRnDrf4D6ylFyVzN2OwB9hd9cKmxoapkSRVi7hXd7FVEXYghBy@3/edE@JlhAwDwxSRSyJsaXWUC8TCXYBtiS1bOk6IbOkxz7PMw97R/X4oElYiC7oN6LpzII4xhNAZUfsZRO3hQ5@94cL6vTN6vCJUKpWcqK80z7kLDRf5@WnEvi8piKQ88wKy620GWalsSNsqJWoGacnl9uW36Wru3UGWPddU/TS1LSLjdR0JpyulqThufd@PH229KyDtCky7@VhfbxBgcBw2bzeWVIJUN/TA3WlwFlt4UVRCm1BkmBK8d9BzPLQrBUX/WivIlFG5UK7@zDGyqJbIaWedCaEedI7uN/3wBw "C (gcc) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ ~~24~~ 22 bytes [SBCS](https://en.m.wikipedia.org/wiki/SBCS) -4 bytes thanks to @Adám; -2 bytes thanks to @ngn; Monadic function expecting a string: ``` ⎕ucs 32+95|⎕ucs-32-⍳∘≢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkGIFZpcrGCsZG2pWkNhKNrbKT7qHfzo44ZjzoX/U8DKnvU2/eoq/lR75pHvVsOrTd@1DYRqDI4yBlIhnh4Bv9PU1D3SM3JyddRKM8vyklRVOcCioRkpCoUJeal5OcqpJdWqgMA "APL (Dyalog Unicode) – Try It Online") Assumes `⎕IO←0`. How the 24-byter works: ``` 32(⎕ucs⊣+95|⊢--∘⍳∘≢)⎕ucs ⍝ monadic function taking a character vector on the right ⎕ucs ⍝ convert to unicode code points 32( ) ⍝ and then evaluate the expression with 32 as left argument and the code points as right arg -∘⍳∘≢ ⍝ do 32 minus (-) the range 0 1 ... [length of input string] (⍳∘≢) ⊢- ⍝ take the right argument (⊢) [the codepoints] and subtract the previous calculation from those [effectively adding the positions and subtracting 32] 95| ⍝ and take those numbers modulu 95. ⊣+ ⍝ Take the left (⊣) argument [32] and add it to the numbers we just did mod 95 ⎕ucs ⍝ and convert the new code points to characters. ``` @Bubbler has a similar answer but making use of an operator that hasn't been implemented in Dyalog APL yet, [check it out](https://codegolf.stackexchange.com/a/205572/75323). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes ``` {*\M!`^. ^. T`~p`p ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wv1orxlcxIU6PC4i4QhLqChIK/v/3SM3JyddRKM8vyklR5ArJSFUoSsxLyc9VSC@t5KqCAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` { ``` Repeat until the input is empty. ``` *\M!`^. ``` Output the first character. ``` ^. ``` Remove the first character. ``` T`~p`p ``` Cyclically increment the remaining characters. 12 bytes in [Retina 1](https://github.com/m-ender/retina/wiki/The-Language): ``` 1,Tv`~p`p`.+ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9QJ6Qsoa4goSBBT/v/f4/UnJx8HYXy/KKcFEWukIxUhaLEvJT8XIX00kquKhgAAA "Retina – Try It Online") Link includes test cases. Explanation: ``` v`.+ ``` Create overlapping matches that start at each character and end at the end of the string. ``` 1, ``` Ignore the match of the whole input. ``` T`~p`p` ``` Cyclically shift each character according to the number of times it was matched. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 19 bytes ``` {`c$32+95!x-32-!#x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qOiFZxdhI29JUsULX2EhXUbmi9n@auoaSR2pOTr6OQnl@UU6KopK1UkhGqkJRYl5Kfq5CemklUKAKBpQ0/wMA "K (oK) – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 80 60 bytes ``` s->{int i=0;for(char n:s)s[i]+=i-(n+i++>126?95:0);return s;} ``` [Try it online!](https://tio.run/##RZAxb8IwEIXn5FdcM9kKRLRSKzVRqKouXTqB1AExuIkJpsFGPodCUX57enECvcG@k57fd887cRRTc5B6V353h@arVgUUtUCED6E0XMIwUNpJuxGFhAXNQVBshV2tAdm14VkYtCQ8WHUUrpcts34c3NAJR9fRqBL25MkWzipd0UNhK@Qe4VknyEHLHw9mvHc4JUvIO5zOL7QDqHyWbYz1WNApclypdZyrKdOxiuP5/cPTy/NjOuOZla6xGjBrOxgrC6/dDe8kOiTmBaJ3WddmAp/G1uVdNIHod6y@X24lWKFLs4eqOUftvxVtA2Mc7wbpYMpvCg88o5P7xDQuoR/SrtbMi2OIIJ/TEfvYgw@jzAl6QeLMG0V9tVacGacawG3Ydn8 "Java (OpenJDK 8) – Try It Online") Thanks for help from [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Haskell](https://www.haskell.org/), 55 bytes ``` g '~'=' ' g c=succ c i!c=iterate g c!!i zipWith(!)[0..] ``` [Try it online!](https://tio.run/##NY29CsIwAAb3PMWXLmmhFOdCOisoDgoOpUNI0zbYn5AmiB189RhFb7tbbhDrXY1jCD3Yi3EGRnpIvnopIYmmkmunrHAKMVOqScc3bW7aDSnN6l1RNGESekZZ4nBGmpGvcUzCnJAa7y7OHmcU6DIC1Ej28bbkeCx2bGkSW47kOihYMbfLhN4/f3H78/EGVQXjrYqL8AY "Haskell – Try It Online") The TIO link has `f=`, but that doesn't contribute to the byte count because I defined it point-free. It's mostly there so that the code compiles. I didn't play around much with using a point-free definition instead of `!`, so that might be a place where some bytes can be shaved off. I just figured that the parens and dots would add up. I also want to get rid of the call to `iterate`, but I'm not sure how. I want something like `mtimes`... # [Haskell](https://www.haskell.org/) + `-XParallelListComp`, 55 bytes ``` g '~'=' ' g c=succ c f s=[iterate g c!!i|c<-s|i<-[0..]] ``` [Try it online!](https://tio.run/##NY1PC4IwAEfvfoqfXlRQ6SzapUuBUVCHQDyMOedo/mGbRCF99JZFvdt7l9cSfWVSWsvhP/3ch@9w0FxPlII6DXReCsMUMQxLd10x0yzWs8jicpUkVWU7InqkKXYHBKHztRwdGfcIxsmcjCp6JGhCByjhbZfXEOE2KFm73tIieOeWQZG@Hjrw6f6Ljz8fr7BeY5wUWxb2RRtJuLbx5UgUkZLJQmizGbrxDQ "Haskell – Try It Online") Unfortunately this isn't any shorter, but I thought it was a cool usage of a pragma. It seems most of the time that pragmas aren't too helpful in golfing. # Explanation ``` -- g gives the successor of each character according to the specification g :: Char -> Char -- the successor of '~' is ' ' (wrap around) g '~'=' ' -- all other characters have their normal successor g c=succ c -- (!) is an infix function that enciphers a character, given an int (!) :: Int -> Char -> Char -- iterate produces an infinite list of 'g' applied to 'c' repeatedly, -- and '!!' indexes into that list at index 'i'. This has the effect -- of applying 'g' to 'c' 'i' times. i!c=iterate g c!!i -- Point-free definition that applies '!' to each character of the input along with its index zipWith(!)[0..] ``` [Answer] # x86-16 machine code, IBM PC DOS, ~~17~~ 16 bytes **Binary:** Build `STL.COM` using `xxd -r`: ``` 00000000: b120 b408 cd21 2ac1 d45f 0420 cd29 e0f2 . ...!*.._. .).. ``` **Listing:** ``` B1 20 MOV CL, 32 ; set up offset / position counter CLOOP: B4 08 MOV AH, 8 ; use DOS API get char from STDIN function CD 21 INT 21H ; read input char into AL 2A C1 SUB AL, CL ; subtract offset D4 5F AAM 95 ; AL = AL % 95 04 20 ADD AL, 32 ; restore ASCII offset CD 29 INT 29H ; output AL to console E0 F2 LOOPNZ CLOOP ; keep looping until break, decrement CL ``` Standalone IBM PC DOS executable program. Input via `STDIN`, output to console. **Runtime:** [![enter image description here](https://i.stack.imgur.com/f8IWH.png)](https://i.stack.imgur.com/f8IWH.png) [Answer] # [Haskell](https://www.haskell.org/), ~~52~~ 51 bytes ``` zipWith(%)[-32..] n%c=toEnum$32+mod(fromEnum c+n)95 ``` [Try it online!](https://tio.run/##NYzLCoJAAEX3fsVNEhQfC6WFC1cRtCgQCgrMxaCOSvOQcSTy45sU6u7OgXM7Mj4bxgxFhoeZ@@HW6851vCJM4igqLeFUmZYHMfFtEvtc1i5Vkq@MyhdeujOc9GKJORnOcIdJX7Q6CUSgngUUsI/LvQzwkorVG3txAexr10ARUUuOdnr/5PzfyqX5VJSRdjThfZ/nXw "Haskell – Try It Online") --- # [Haskell](https://www.haskell.org/), 52 bytes ``` zipWith(%)[0..] n%c=snd(span(<c)$cycle[' '..'~'])!!n ``` [Try it online!](https://tio.run/##NYxBC4IwGIbv/opPSbaBjX5Anrx0KBAKCszDmE6l7XM4JfTQT28Z1HN7H3ifVrhHrbVXkMLdL529dmNLY1bsOC8DjGXqsKLOCqR7yTZylrouCBDOyYuULAzRG9Hh@jbCnoDaaTyPwxGBg2IBQAHRYe33CTz7QVdhtLoEoktbwyCw6g000/yTy5/vLv1bKi0a57e3LM8/ "Haskell – Try It Online") ### Explanation * `zipWith(%)[0..]` calls the infix function `%` on each character of the input string along with its index. * `cycle[' '..'~']` builds a list where the ASCII chars are repeated infinitely. * `span(<c)` partitions this list into a prefix of chars smaller than the current character `c` and a remainder. * `snd` drops the prefix, so only the list of ASCII chars starting with `c` remains. * `!!n` returns the `n`th element from that list. [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` ->s{i=33;s.map{((_1.ord-i-=1)%95+32).chr}} ``` Takes input and returns output as an array of characters. ### 44 byte version because TIO doesn't support ruby 2.7's `_1` syntax ``` ->s{i=33;s.map{|c|((c.ord-i-=1)%95+32).chr}} ``` [Try it online!](https://tio.run/##Nc5BDoIwFATQPaf4aLSAQILEhTF17QHYERZICzQiH4tCpMWrI5ow23mTjHxd31NOJ@/cKkHD8NT697RROtOWlfkomSc8Gtib42EX7m0/K@U4TrEBEJMLryp0oUdZMZO4QC55jW2w/fSqQ48k7l8NS35iUHr8gLlaL21UcpBpzfAOxes9k81DRaJYd/nz1neOXJExMRKfp1kJDEELF1DPywbyWMxvUtkmDiFAKaDBazZ9AQ "Ruby – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 22 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Full program. Requires `⎕IO←0` ``` ⍞(⊢⊇⍨95|⍳⍨+~⍋⊣)' '…'~' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@P@qdp/Goa9GjrvZHvSssTWse9W4GMrTrHvV2P@parKmuoP6oYZl6nfp/oOr/CmBQwOWRmpOTr6NQnl@Uk6LIBRMNyUhVKErMS8nPVUgvrQQA "APL (Dyalog Extended) – Try It Online") `' '…'~'` the printable ASCII range `⍞(`…`)` with the input as left argument, apply the following tacit function to that:  `⊣` the left argument (the input)  `⍋` the sorting permutation to sort according to the following order:   `~` the input without any printable ASCII, i.e. an empty string (this means leave all in current positions)  `⍳⍨` the indices of the input characters in the printable ASCII  `95|` division remainder when divided by 95  `⊇⍨` use those indices to select from:   `⊢` the printable ASCII [Answer] # Befunge-93, 25 bytes ``` :~:1+!#@_" "-+"_"%" "+,1+ ``` [Try it online!](https://tio.run/##S0pNK81LT/3/36rOylBbUdkhXklBSVdbKV5JFcjQ1jHU/v@/CgYA "Befunge-93 – Try It Online") Keeps the character count on the bottom of the stack. Then in a loop, reads a character at the time, subtracts 32 to the character, adds the character count, mods it with 95, adds 32 again, then prints the character. Finally, it adds 1 to the character count. [Answer] # T-SQL, 100 bytes Added some line changes to make it readable ``` DECLARE @x INT=0 WHILE @x<len(@) SELECT @=substring(@,2,999)+char((ascii(@)+@x-32)%95+32), @x+=1 PRINT @ ``` **[Try it online](https://data.stackexchange.com/stackoverflow/query/1247021/shift-the-letters-soldier)** [Answer] # [Ly](https://github.com/LyricLy/Ly), 25 bytes ``` ir84*sp[l-l,sp(95)%84*+o] ``` [Try it online!](https://tio.run/##y6n8/z@zyMJEq7ggOkc3R6e4QMPSVFMVKKCdH/v/v0dqTk6@jkJ5flFOiiIA "Ly – Try It Online") [Answer] # JavaScript, 77 bytes Iterative! ``` s=>[...s].map((c,i)=>String.fromCharCode((c.charCodeAt()+i-32)%95+32)).join`` ``` [Try it online!](https://tio.run/##bYq9CsIwFEZ3nyIO0oS2d1AEHVqQLu66idCQnzYlzS1JrejLxwq6iN9yPjin4xMPwpthzKdd1EUMRXkBgHCFng@UisywojyN3rgGtMe@armvUKpZgfj8w0hZavLNmq3223QGgw6Nq@so0AW0Ciw2lGiaHJW1mJE7eiuXCSNs8VucW0U8dxJ70twef5Pnd28bXw "JavaScript – Try It Online") --- # JavaScript, 77 bytes Outer recursive! ``` f=(s,i=0)=>s[i]?String.fromCharCode((s.charCodeAt(i)+i-32)%95+32)+f(s,i+1):'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P81Wo1gn09ZA09auODoz1j64pCgzL10vrSg/1zkjscg5PyVVQ6NYLxnKdizRyNTUztQ1NtJUtTTVBlLaaSADtA01rdTV/yfn5xXn56Tq5eSnayikaah7pObk5OsolOcX5aQoqmsqaHKhqwjJSFUoSsxLyc9VSC@txKqkCgZAsv8B "JavaScript – Try It Online") --- # JavaScript, 77 bytes Inner recursive! ``` s=>(F=i=>s[i]?String.fromCharCode((s.charCodeAt(i)+i-32)%95+32)+F(i+1):'')(0) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/2NZOw80209auODoz1j64pCgzL10vrSg/1zkjscg5PyVVQ6NYLxnKdizRyNTUztQ1NtJUtTTVBlLabhqZ2oaaVurqmhoGmv@T8/OK83NS9XLy0zUU0jTUPVJzcvJ1FMrzi3JSFNU1FTS50FWEZKQqFCXmpeTnKqSXVmJVUgUDINn/AA "JavaScript – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 42 bytes ``` s=>Buffer(s).map((c,i)=>(c+i-32)%95+32)+'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1s6pNC0ttUijWFMvN7FAQyNZJ1PT1k4jWTtT19hIU9XSVBtIaaur/0/OzyvOz0nVy8lP10jTUPJIzcnJ11Eozy/KSVFU0tTkQpMPyUhVKErMS8nPVUgvrQQq@A8A "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O+J_32ịØṖ ``` **[Try it online!](https://tio.run/##y0rNyan8/99f2yve2Ojh7u7DMx7unPb///8qGAAA "Jelly – Try It Online")** ### How? ``` O+J_32ịØṖ - Link: list of characters, S - e.g. "zzzzzzzzz" O - cast (S) to ordinal values [122,122,122,122,122,122,122,122,122] J - range of length (S) [ 1, 2, 3, 4, 5, 6, 7, 8, 9] + - add (vectorises) [123,124,125,126,127,128,129,130,131] 32 - thirty-two 32 _ - subtract [ 91, 92, 93, 94, 95, 96, 97, 98, 99] ØṖ - printable ASCII characters " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~" ị - index into (1-based & modular) "z{|}~ !"#" ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~46 50~~ 48 bytes ``` x;f(char*s){*s?*s=(*s+x++-32)%95+32,x=f(s+1):0;} ``` [Try it online!](https://tio.run/##dZDRboIwFIbvfYpjjVtLMRHJLiYzu/UBvFMuSGmRDFvSoqIMX50VFMOW7Nz87en3p/85bJYw1jRlIDDbR9oxpHLMp2NW2DG0pHTmL8j0/Y36C7dcCWyoR5bzoG5SWcAhSiVgAtUIbLV2cFK19cPtIoTVo91WhdY8y5QLZ6WzeIxcQGshlfFebufqpGaodgfsta@Wu1bf9Q3GOzT5DW32HHQkY3WA5HhpyU2aTE6i@DqfHL1Dr6ju6DroRCgNuM2c2mDzwMoH@FYoJYOcjxFkfiwsdohsZoZNoTMusR0sDbfzECh4hARPj31m@QV3Jhd6agDk2v4rMLLHDlrC1OykTdzdBqDAfzsDK0Ci/rf2IC9zzgoe38E72iXy@kT3rWheHLW0ixjVzQ8 "C (gcc) – Try It Online") [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 68 bytes ``` f(I,[H|T])->[(H+I-32)rem 95+32]++f(I+1,T);f(_,[])->[]. f(I)->f(0,I). ``` [Try it online!](https://tio.run/##HcpBC8IgGMbxu59Cdnpf1FEbHSrYed69iQwpXUK6cBsR9N1Nek5/Hn4uP22ahVtvOby2QooHyfX4VQbFoGFkUvQdZhfp@cT6zjBWATtyhVcPE9d/ZlpS31oeDlxiW6INCSakYiC0LiwX/85hc@ChUQ9Hs033JdJ5/zRY@Q8 "Erlang (escript) – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 9 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` éñÇöo♣j0♦ ``` [Run and debug it](https://staxlang.xyz/#p=82a480946f056a3004&i=%22Hello,+world%21%22%0A%22zzzzzzzzz%22&a=1&m=2) [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 68 bytes ``` FromCharacterCode@Mod[#&~Array~Length@#+#-1,95,32]&@*ToCharacterCode ``` Uses a little function composition to make it shorter, but other than that, does pretty much what it says on the tin. Converts the string to character codes, adds the proper offset to each, wraps around if needed using Mod (there's an optional argument for offset that I use here), then converts back to a string. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 19 bytes ``` 0&(⑻+:\~>[\~% +;],⑹ ``` [Try it online!](https://tio.run/##y05N///fQE3j0cTd2lYxdXbRMXWqCtrWsTqPJu78/z8kI1WhKDEvJT9XIb208r9uZtF/3ZwCAA "Keg – Try It Online") Woooo! I managed to beat APL somehow! This is a very literal interpretation of the challenge, except for the part where overflow values are decremented after modulusing. [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 20 bytes ``` '!v -1<,+ '%_'-\~@#: ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tPj/X12xjEvX0EZHW0FdNV5dN6bOQdnq//@QjFSFosS8lPxchfTSSgA "Befunge-98 (FBBI) – Try It Online") Initially pushes `d=33` on the stack. On every iteration, `d` is reduced by one and `(input-d)%95+32` is printed. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 29 bytes ``` VlQ=+Y-C@QN32;s.eC+%+bk95 32Y ``` [Try it online!](https://tio.run/##K6gsyfj/Pywn0FY7UtfZIdDP2Mi6WC/VWVtVOynb0lTB2Cjy/3@lkIxUhaLEvJT8XIX00kolAA "Pyth – Try It Online") ]
[Question] [ Given a set of letter grades, output the GPA (grade point average) of those grades, rounded to one decimal place. Valid grades and their corresponding value are the following: ``` A = 4 grade points A- = 3.7 grade points B+ = 3.3 grade points B = 3 grade points B- = 2.7 grade points C+ = 2.3 grade points C = 2 grade points C- = 1.7 grade points D+ = 1.3 grade points D = 1 grade point D- = 0.7 grade points F = 0 grade points ``` The formula for GPA is simply the average of the points values of the grades. The rounding scheme used should be [round half up](https://en.wikipedia.org/wiki/Rounding#Round_half_up) (i.e. less than 0.05 gets rounded down to 0 and greater than or equal to 0.05 gets rounded up to 0.1). The average should be unweighted (all inputs are treated equally). Note that the same grade can show up multiple times in the input, in which case each instance of that grade should be a separate element in the average. So for example, if the input was [A, B+, A, C-], the GPA is (4 + 3.3 + 4 + 1.7)/4 = 3.25, which rounds to 3.3. The program should take as input the grades to be averaged using whatever format is convenient, such as a list, or a string with a delimiter of your choice. Each input grade should be a single string (i.e. the letter components and +/- shouldn't be separate inputs). You can assume the input will always contain at least one grade. Note that grades may be repeated in the input. Output can optionally include the ".0" suffix in the event of an integer result but this is not required. This is code golf, so shortest solution in bytes wins. Test cases: ``` [A] => 4 [F, F, F] => 0 [D+, D-] => 1 [A, B, C, D] => 2.5 [A-, B-, C-, D-] => 2.2 [A, A-, B+, B, B-] => 3.3 [A, B+, A, C-] => 3.3 [C+, C+, A, C+] => 2.7 [A, B, F, F] => 1.8 ``` [Answer] # JavaScript (ES6), 67 bytes Returns a number. ``` a=>(a.map(([x,y])=>t+=940.5%(n++,'0x5'+x)%85+~~(y+3),n=t=0)|t/n)/10 ``` [Try it online!](https://tio.run/##fdDfCoIwFAbw@55CBGnj6JypZBcLSuklZBfD/lDYjJIwiF7dcmpJWrs4V@e37@McxFVckvP@lFsyW2/KLSsFmyNBjuKEUFyYN47ZPAc28yjxDSQBzDEt/DEU2Ah8eDzQDVxsSpYziu@5LbHt0DLJ5CVLNyTNdmiLYn2hc234YazZtuaNvsVKN7V28AFBeyKCajuy@lG1cEb9Vi@wrEao6EfWYkL8vrEUUjO0uomtmQznNBDema8/eG1c4v7oprYXTRbvdhsyoVoPOwga1Hab/rnB97Gbq5GgfAI "JavaScript (Node.js) – Try It Online") ### How? The purpose of the black-magic formula `940.5 % ('0x5' + x) % 85` is to turn a grade into its base value pre-multiplied by \$10\$ and with an offset of \$1/2\$ for the final rounding. | x | N = '0x5' + x | As decimal | 940.5 mod N | mod 85 | | --- | --- | --- | --- | --- | | A | 0x5A | 90 | 40.5 | 40.5 | | B | 0x5B | 91 | 30.5 | 30.5 | | C | 0x5C | 92 | 20.5 | 20.5 | | D | 0x5D | 93 | 10.5 | 10.5 | | F | 0x5F | 95 | 85.5 | 0.5 | We use the expression `~~(y + 3)` to add an additional offset of \$\pm 3\$ if the grade is followed by `+` or `-`. This evaluates to `~~NaN` (which is \$0\$) if there's no modifier. Given the sum \$t\$ of all these values, the GPA is given by \$\lfloor t/n\rfloor/10\$, where \$n\$ is the number of grades. --- # JavaScript (ES6), 76 bytes Original answer, returning a string. ``` a=>(eval(a.map(s=>s<'F'&&'14-0x'+s+[s[1]&&.3]).join`+`)/a.length).toFixed(1) ``` [Try it online!](https://tio.run/##fdDRCoIwFAbg@55CvNCNtWNmURcZlOFLyKBh0wxz0SR6e6upJWnt4lydb//POfEbV/E1u5S0kAdRJX7F/TUSN54jDmd@Qcpfq5Ud2pZluzM6udtEkUhFLrMs8BiGk8yKPdljh0MuirQ8YihlmN3FAbm4imWhZC4glylKUGRuTGYMP4wNxzFmo28RmmOjHWxATHpiR17bO9qPqoU76rd6gu1rBJp@ZC2mMO8bqpGeAe0mtmY6nNNA8s58/sFq44H3o5ve3jRZrNttyAR6Pegg0qC22@LPDb6P3VwNltUD "JavaScript (Node.js) – Try It Online") ### How? If the grade is `"F"`, we turn it into `"false"`. Otherwise: * we add the prefix `"14-0x"` * if this is a two-character grade, we add the suffix `"0.3"` Examples: * `"A"` is turned into `"14-0xA"` (\$14-10=4\$) * `"B+"` is turned into `"14-0xB+0.3"` (\$14-11+0.3=3.3\$) * `"C-"` is turned into `"14-0xC-0.3"` (\$14-12-0.3=1.7\$) [Answer] # Excel, ~~89~~ 84 bytes Saved 5 bytes thanks to [JvdV](https://codegolf.stackexchange.com/posts/comments/561216) ``` =ROUND(AVERAGE(IF(A:A=0,"",FIND(LEFT(A:A),"FDCBA")-1+IFERROR(--RIGHT(A:A)&.3,0))),1) ``` Input is in the first column. One grade per row. When you paste the formula, Excel will automatically add a leading zero so `.3` becomes `0.3`. * `ROUND(~,1)` will round the final result to one decimal place. * `AVERAGE(~)` will average the array we're about to calculate. * `IF(A:A=0,"",~)` will ignore all the blank cells below the input. Without this, the above solution produces around 1 million zeroes so that throws off the average a bit. * BASE VALUE: `FIND(LEFT(A:A),"FDCBA")-1` get the base GPA value of each letter from 0 - 4. * ADJUSTMENT VALUE: `IFERROR(--RIGHT(A:A)&.3,0)` + `RIGHT(A:A)&.3` combines the right-most character (which may be a letter) with `.3`. + `--~` tries to coerce that value into a number which throws an error if the right-most character was a letter since something like `--A.3` is not a number. + `IFERROR(~,0)` corrects all those errors to `0` instead. * When you add the base value and adjustment value (which may be negative), you get the GPA value for that letter grade. * All those grades are calculated individually and then averaged and rounded to one decimal place. [![Screenshot](https://i.stack.imgur.com/KmpO0.png)](https://i.stack.imgur.com/KmpO0.png) [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 38 bytes [SBCS](https://github.com/abrudz/SBCS) Anonymous prefix lambda taking a string argument of whatever format is convenient. ``` {1⍕(+/l,.3×-⌿'+-'∘.=⍵)÷≢l←0⌈5-⎕A⍳⍵∩⎕A} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzZ81DtVQ1s/R0fP@PB03Uc9@9W1ddUfdczQs33Uu1Xz8PZHnYtyHrVNMHjU02Gq@6hvquOj3s1AmUcdK0GcWgA&f=e9Q39VHbhDQF9WjHWHWuR3Cem44CCKGIuWjrKLjoogg56ig46Sg4A8VRhXWB4kDsrItNB1hWG6zTCdM4oIQjSCeKhDNQ1Bkqo43FBRC3AgA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) `{`…`}` "dfn"; argument is `⍵`:  `⍵∩⎕A` intersection of argument and uppercase **A**lphabet  `⎕A⍳` indices of those letters in the uppercase Alphabet (A=1)  `5-` subtract those indices from 5  `0⌈` maximum of 0 and those numbers  `l←` assign to `l`  `≢` count those  `(`…`)÷` divide the following by that:   `'+-'∘.=⍵` comparison table of signs vs the argument characters   `-⌿` subtract the bottom row from the top row   `.3×` multiply those differences by 0.3   `l,` prepend `l`  `+/` sum  `1⍕` format as string with 1 decimal [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, ~~302~~ 299 bytes ``` :a s/ // s/[A-D]/&aaaaaaaaaa/g y/ABCD/BCDF/ s/\+/aaa/ /-/{s/-//;s/a//;s/a//;s/a//} s/Fa/aF/ ta s/F/!F/ :b s/F/a/ s/(a+)(a*!)\1$/X\2\1/ tb s/!.*/\U&/ s/AA?/a/g /(a+)!\1$/s/a/X/ s/[a!]//g s/X{10}/Y/g s/$/I.0/ :c /X/y/012345678/123456789/ /Y/y/IJKLMNOPQ/JKLMNOPQ9/ s/X// s/Y// tc y/IJKLMNOPQ/012345678/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VZDJTsMwFEXF1l_hVFXV1nJvU6YOAuQkRJQyLpASNVmYMq3YJCyqql_CBoRgyf_A1_CeQxli5en63eP7LD--FNdXb9Oa3q_lz3evD-WN7n-uqaEVBSRAdWp0lKNhfz7cijlMEEagP2YkU-C-gMaioIJRAfu_LgmLLSzxJWfH8EgOL520HNK0qtW0ba-V-XUkWS_zCWXf67SRXTSYMWYPPN_BHoMcnrhrWi8HWQWShd9dInW6jnGnS3Nmgqg5un5vfWNza7uPlRjQrVNyxoeTo-OT07NzrMSAUxP3BCnVcib-Ur9J1Zu9H4x4XnYPubMrv5tPHxMjYklLREpGWhgZyFBGwmgZaBnqqsc7RU7gACUNOSJUMnRSuVOUUWV-AQ) **Explanation:** ``` # store dividend as unary "a" and divisor as unary "F" :a s/ // # removes all spaces s/[A-D]/&aaaaaaaaaa/g # for each of letters ABCD ten "a" are added y/ABCD/BCDF/ # each of letters ABCD are substracted to BCDE s/\+/aaa/ # for every + three "a" are added /-/{s/-//;s/a//;s/a//;s/a//} # for every - three "a" are removed s/Fa/aF/ # sort the string into format "aaaaaFFFFF" ta # now perform the division s/F/!F/ # transforms string to format "aaaaa!FFFFF" :b s/F/a/ # transforms string to format "aaaaa!aaaaa" s/(a+)(a*!)\1$/X\2\1/ # if there are more or equal "a" on left side than on the right append "X" to beggining tb # now do the rounding s/!.*/\U&/ # transorm "a" after "!" to "A" s/AA?/a/g # now the amount of "A" is divided by 2 /(a+)!\1$/s/a/X/ # check if the reminder is more or equal to half of divisor and if so, then add one more "X" s/[a!]//g # remove leftover characters # now the result is stored as unary "X" # conversion from unary to decimal s/X{10}/Y/g # convert every ten "X" to "Y" s/$/I.0/ # adds string for output "I.0" :c /X/y/012345678/123456789/ # for every "X" the "0" is increased /Y/y/IJKLMNOPQ/JKLMNOPQ9/ # for every "Y" the "I" is increased s/X// s/Y// tc y/IJKLMNOPQ/012345678/ # now the "I" is transformed to digit ``` [Answer] # [Python](https://www.python.org), 98 bytes ``` lambda i:round(sum(x*i.count(y)for y,x in zip("FDCBA-+",[*range(5),-.3,.3]))/len(i.split())+.01,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY3dasIwFMfv9xTBqxNzEicy2ApetCm-RJVRp50Hahr6AXavshth6Dv5Np7UboME_r_k__F99X17qNz5p1iuL11b6NfbtsyP210uKKqrzu2g6Y5wmpL5YGqhl0VVix5Pgpz4Ig-TVWqTWKsJZtM6d597eJGozQLNYiPlrNw7INP4klqQUpnnOc7luASh6j0UPYJvMvI18UgBFC3J-S5kkEb_-dZk8eYpW6EIh1WqUKSaRYwiQWGZAmgmvlb__w5vanAlvwHGOLgYLWs7svrrG1Ye23c) [Answer] # Python 3.8, ~~95~~ ~~93~~ 92 bytes ``` s=.01;i=0 for g,a,*_ in open(0):i+=1;s+='FDCBA'.find(g);exec(f's=s{a}.3') exit(f'{s/i:.1f}') ``` Input (stdin) ``` A B+ C D ``` Very straightforward. Open `stdin` with `open(0)`, then read each line with `for g`. Python has an annoying property where it leaves a trailing `\r` after each line, which we exploit in an f-string passed to `exec`. In case there's no appendix after grade, f-string becomes `s=s\r.3`, which is essentially a no-op. Very unsafe ;) [Answer] # Python 3, 93 bytes ``` lambda l:int(0.5+sum(3*(c=='+')-3*(c=='-')or'FDCBA'.index(c)*10for c in''.join(l))/len(l))/10 ``` Takes input as a list of strings (`['A', 'B+']`). [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~24~~ 29 bytes ``` .OmeS,0v++"14-0x"d?tld".3";.z ``` [Try it online!](https://tio.run/##K6gsyfj/X88/NzVYx6BMW1vJ0ETXoEIpxb4kJ0VJz1jJWq/q/39HLkddLidtLicuJ10uZ20uZy5nXS4XbS4XLhddLjcA "Pyth – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ON%7’»0_2¦€4ḋ10,3Æm+.Ḟ÷⁵ ``` A monadic Link that accepts a list of lists of characters and yields a number. **[Try it online!](https://tio.run/##y0rNyan8/9/fT9X8UcPMQ7sN4o0OLXvUtMbk4Y5uQwMd48Ntudp6D3fMO7z9UePW/4fbgVL//0dHqzuqx3LpRKu7qesowAiwgIs2iOOiC@E5gjhOIMIZLAwV1QULg0lnXQz1UGltuF4nFNPA4o5QvWBxZ7CQM5KENrr1cCfGAgA "Jelly – Try It Online")** ### How? ``` ON%7’»0_2¦€4ḋ10,3Æm+.Ḟ÷⁵ - Link: list of grades e.g. ['A-', 'B+', 'F', 'F'] O - ordinals (vectorises) [[65, 45], [66, 43], [70], [70]] N - negate [[-65, -45], [-66, -43], [-70], [-70]] %7 - mod seven [[5, 4], [4, 6], [0], [0]] ’ - decrement [[4, 3], [3, 5], [-1], [-1]] »0 - max with zero [[4, 3], [3, 5], [0], [0]] 2¦€ - from 2nd of each: _ 4 - subtract four [[4, -1], [3, 1], [0], [0]] ḋ10,3 - dot product with [10,3] [37, 33, 0, 0] Æm - mean 17.5 +. - add a half 18.0 Ḟ - floor 18 ÷⁵ - divide by ten 1.8 ``` --- If banker's rounding was used \$21\$ bytes is possible with `ON%7’»0_2¦€4Uḅ.3Æmær1` (`U` reverses each, `ḅ.3` converts from base \$0.3\$, and `ær1` uses Python's `round` to round to 1 decimal place). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε14sáC-.3y¦'\ìθ.VDd*}ÅA1.ò ``` -4 bytes by [semi-porting *@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/251902/52210) [Try it online](https://tio.run/##yy9OTMpM/f//3FZDk@LDC5119YwrDy1Tjzm85twOvTCXFK3aw62OhnqHN/3/H63kqKSj5KgLJJy0QQQIg3jOIJ4zCIN4LiCeCwiDeG5KsQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1sNTYoPL3TW1TOuPLRMPebwmnM79MJcUrRqD7c6Guod3vRf5390tJKjUqxOtJKbkg4Ug3gu2kCmiy6Y7QhkOgGxM0gIIqILEgIRzrqo6iAy2lAdTkgGgMQcITpAYs4gvjNcUBvFJqg7YgE). **Original 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` •H₁yΔи•.¥RA4£…+ -â¦ðмuIkèÅAòT/ ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcMij0dNjZXnplzYAWTrHVoa5GhyaPGjhmXaCrqHFx1adnjDhT2eOdmHVxxudTy8KUT///9oJUclHSVHXSDhpA0iQBjEcwbxnEEYxHMB8VxAGMRzU4oFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f9HDYs8HjU1Vp6bcmEHkK13aGmQo8mhxY8almkr6B5edGjZ4Q0X9lTmZB9ecbjV8fCmEP3/Ov@jo5UclWJ1opXclHSgGMRz0QYyXXTBbEcg0wmInUFCEBFdkBCIcNZFVQeR0YbqcEIyACTmCNEBEnMG8Z3hgtooNkHdEQsA). **Explanation:** ``` ε # Map over the (implicit) input-list: 14 # Push 14 s # Swap so the current grade-string is at the top á # Only keep its letters (removing a potential "+"/"-") C # Convert it to 'binary': "A"=10, "B"=11, "C"=12, "D"=13, "F"=15 - # Subtract it from the 14 .3 # Push 0.3 y # Push the current grade-string again ¦ # Remove its first character (the letter) '\ì '# Prepend a leading "\" θ # Pop and only keep its last character .V # Execute it as 05AB1E code # ("+"/"-" does what you'd expect; "\" discards the 0.3 from the stack) D # Duplicate the decimal d # Check if it's non-negative (1 if >=0; 0 if <0) * # Multiply that to the decimal to change the "F"=1 to 0 } # Close the map ÅA # Get the average of this list 1.ò # Round it to 1 decimal point # (after which the result is output implicitly) ``` ``` •H₁yΔи• # Push compressed integer 73343343343 .¥ # Undelta its digits with leading 0: [0,7,10,13,17,20,23,27,30,33,37,40] R # Reverse it: [40,37,33,30,27,23,20,17,13,10,7,0] A # Push the lowercase alphabet 4£ # Only keep its first four characters: "abcd" …+ - # Push string "+ -" â # Get the cartesian product of the two: ["a+","a ","a-",...,"d+","d ","d-"] ¦ # Remove the leading "a+" ðм # Remove all spaces from each string Il # Push the input-list, and convert each grade-string to lowercase k # Get the indices of each lowercase grade-string in the string-list we've created) # (-1 for "f", since it's not in the list) è # Use that to index into the earlier list of integers # (-1 wraps around to the last item, which is the 0) ÅA # Get the average of this list ò # Round it to an integer T/ # Divide it by 10 # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•H₁yΔи•` is `73343343343`. [Answer] # [C (clang)](http://clang.llvm.org/), ~~113~~ 96 bytes -17 bytes thanks to celingcat and jdt ``` k;i;main(j){for(;gets(&j);k++)i+=j%8<5?50-j%8*10:0,i+=(j>>=8)?132-j*3:0;printf("%.1f",i/10./k);} ``` [Try it online!](https://tio.run/##DcjdCoMgGADQex8jaGj2lS6CyFXsh72HSIo/uVHdjb36XHeHo0AFGU1KXlixSBuxIx/9WrEw877hkyPCU0osHVzeXdqpZXCg4Kxn5ZHYjePQkYk3Z3BF0zPxXm3cNc7yiuustDVnVe2J@KZ0BXQDdAf0APT8KR2k2RKE5Q8 "C (clang) – Try It Online") [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjcLs3UyrXMTM_M0sjSr0_KLNKzripMT89I0lFSLlXTUsjSts7W1NTO1bbNszA3sDc0tdA0NtLJUjUzNtDWy7Ows7A2NjXSNtcBsTSsDILIuKMrMKwEZoGeYpqSjkamdrW-kqZ-tb2igZ6BpXQuxGGr_gsUuXG4QJgA) Takes input as one grade per line. ## Explanation ``` gets(&j) ``` Read the string into a integer field `j`. This is perfectly valid in C, and is a compact way to read strings of upto 3 bytes long. ``` j%8<5 ``` Check for F ``` 50-j%8*10 ``` Extract the last byte from the string, this will be the letter (since little endian). 178-10\*char will be the letter grade, 40, 30, 20, 10 etc. ``` 0, ``` I think this just changed the operator precidence? Not sure. ``` i+=(j>>=8)?132-j*3:0 ``` Add or subtract 3 depending on the sign, since `+` is 43 and `-` is `45` ``` printf("%.1f",i/10./k) ``` Round and print the final number as a float. [Answer] # [Red](http://www.red-lang.org), 124 bytes ``` func[a][forall a[parse a/1[change p: skip(rejoin[max 69 - p/1 0" "])opt[skip insert" .3"]]a/1: do a/1]round/to average a .1] ``` [Try it online!](https://tio.run/##ZY/BasMwDIbvfQrh00ZIszAYLNBBmrIH2FXoIGJnTZvaxnHH3j6Vm6aD1SCj/7P0ywpGT19GI626aurOtkUm7FzgYQBGz2E0wEWJ7Z7ttwFfwXjs/VMwB9dbPPEvvL1DDr4o4UWBomfnI6YS6O1oQlSwflVEYlGBdsmKgjtbXUQRPyawmDKsS5pkqOF2D9GMEXAFclDVim7Zp7jPsZBdJnKX33UtcivRJPxH84TT1eSP9fNrduvc/jNLvJ47F94k1twfsofpyx8JfeitbHJyg56XUpsPBd01J5ou "Red – Try It Online") More readable: ``` f: func [a][ forall a [ parse a/1 [ change set g skip (rejoin [max 69 - g 0 space]) opt [skip insert " 0.3"] ] a/1: do a/1 ] round/to average a 0.1 ] ``` The input is a block (list) of strings. I modify each string in place by changing the letter with the corresponding grade value and optionally appending "0.3" after `+` or `-`. Then the string is replaced by its evaluated value. Finally I find and round the average of the block. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 90 bytes ``` T`L`4-0 \d 0$&$* 1 20$* \+ 6$* 1{6}- O`. 0+ $.&$*1$.&$*1,$.&$* \D*(1+),(\1)*1* $#2 .$ .$& ``` [Try it online!](https://tio.run/##NUw9C8IwFNzvVwSMpc0XSZHuaYIugotjhgh2cHEQN/G3x5e0wr13d@8d91rej@et7PtTLtd8zgdtke6wvOMCDqMlShJTdZ/pq4FLNrAS3FDCrVs1Qoqid3JQfXKDcAJ8N8JwQleKx1GxCkSpWNTwis2KBdLwmjRN0P9Pu8iWmNcoGV8TCKTC5uTWUnt/ "Retina 0.8.2 – Try It Online") Link includes test cases. Output always includes the decimal but omits the leading `0` on scores of less than `1`. Explanation: ``` T`L`4-0 ``` Translate uppercase letters to digits `A=4, B=4, C=2, D=1`, otherwise `0`. ``` \d 0$&$* ``` Convert to unary and prefix a marker `0` to keep count of the number of grades. ``` 1 20$* ``` Multiply by `20`. ``` \+ 6$* ``` Add 6 for a `+`. ``` 1{6}- ``` Subtract 6 for a `-`. ``` O`. ``` Collect the markers and scores together. ``` 0+ $.&$*1$.&$*1,$.&$* ``` Add the count to the sum (so that the division will round) and double the count. ``` \D*(1+),(\1)*1* $#2 ``` Divide the sum by the doubled count. ``` .$ .$& ``` Divide by `10`. [Answer] # [Knight](https://github.com/knight-lang/knight-lang) (v2.0-alpha), 81 bytes ``` O+++=s=n"";W=gP;=n+1n=s++*100&!?70=cA[g-69c*30&]g-44A]g s/=q/+/s n 5=t 10t'.'%q t ``` [Try it online!](https://knight-lang.netlify.app/v2#WyJPKysrPXM9blwiXCI7Vz1nUDs9bisxbj1zKysqMTAwJiE/NzA9Y0FbZy02OWMqMzAmXWctNDRBXWcgcy89cS8rL3MgbiA1PXQgMTB0Jy4nJXEgdCIsIkFcbkEtXG5CK1xuQlxuQi0iXQ==) The basic algorithm is as follows, with a few golfing optimizations added: ``` # Set `s` and `n` to the empty string. This could be any zero value,3 # but an empty string helps with `OUTPUT` ; + = s = n "" # Each grade is on a separate line ; WHILE = grade PROMPT ; = n + 1 n # increment the amount of grades # The grade part is `100 * (c == 'F' ? 0 : 69 - c)`, # ie the grade offset for normal grades, or `0` for `F`. ; = grade_part * 100 &(!? 70 = c ASCII [grade) (- 69 c) #nice # The modifier is `grade.len == 1 ? 0 : 30 * (44 - grade[1].ascii)` ; = modifier_part * 30 (& ]grade (- 44 ASCII ]grade)) # `s` will be coerced to an int the first tiem around. : = sum ++ grade_part modifier_part s # Calculate the average * 10. To accommodate the rounding rule, # we add five, then divide (`sum`, which is 100x a GPA) by ten. ; = avg / (+ /sum n 5) 10 # Now, simply output the number in the float format : OUTPUT ++(+ "" /avg 10) '.' (% avg 10) ``` ``` [Answer] # [PHP](https://php.net/), ~~165~~ 100 bytes Thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan) for the whopping 39% size reduction. ``` function($a){foreach($a as$v)$r+=strpos("FDCBA",$v[$l++*0])+($v[1]?$v[1]..3:0);echo round($r/$l,1);} ``` [Try it online!](https://tio.run/##TY/NToNAFIX3PMUNmaQzzhRLq9FYa20hTdy40R2Shp@hNEEgM7SamD6FCzc@nS9SL0OtTYDM@e65Zw51Xu9vp3VeWySDCeyzTZk066qkJGIfWaVklOR4hkiTLSOKT3Sj6kpTe@F785ktyDYgBedng5BxisINp@brOKObARvLJK9AVZsypUSdk0K4bLzbjy3rLV8XEijReGm2ko2mT8/@wyNj8GEBBCQSJA5xJt/rokol7cHkDnqiUetXXGJsjC6yUlEq9alLoEdvYiyJpYUr@m5nNT3wNxyw2yC7ZVW81E2kGmoc9ySjh8AuXJlkNGG7ZVLIqKQnUThtxToDyjvrBDiJWTfuwc/3Z8@4Cy07ZiP7Em1VmTQyBRLbxzj7pUSx2wezsK13YQULAe1j5MAKfC7A7xvlWsFMwFyAh8iQoXOJrI8QX69/dA6dofGaETc7824yckZdCtJZu/NPPUTeAfNDzNXflcdKrnP9Cw "PHP – Try It Online") ### Original Solution ``` function($a){$i='array_search';$g=str_split("FDCBA");$r=0;foreach($a AS$v){@$r+=eval("return {$i($v[0], $g)}".($v[1]?$v[1].".3;":";"));}die(round($r/count($a),1));}; ``` [Try it online!](https://tio.run/##HY7LCoMwFET3/YoQLiTBRyvdNQ1WW/oDXRaRoPEBouEahVL67VbdHGYYZhjb2OUa28YeoCKKLNXUF64deg5afKFVTCPqTz4ajUXDJNRqdJiPtmsdp8/HPU2okIDqJKsBjS6atUiSF8ziewP0lJl1xykaN2FP1kEO8/uU@QRq8aPh5qIs3hnS8CzphUoqhPyVreE4TH3JAY/FKtz2yI@2TC5Q8TdLmE9YEmxMvZ07ApYJufwB "PHP – Try It Online") This is my first time golfing in PHP, so I probably missed a few places where I could have been more efficient. ### Original Explanation PHP is completely and utterly broken, which is why golfing in it is so fun. We approach this problem by using a string and splitting it, using the index as GPA value. The `array_search` function grabs the proper GPA value for us. We then use the `+` or `-` in the input to add or subtract `0.3` to the GPA value and use a standard algorithm to find the average value. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` WS⊞υ⁺⌕FDCBA§ι⁰×·³⁻№ι+№ι-﹪%.1f∕ΣυLυ ``` [Try it online!](https://tio.run/##RU7dCoMgGL33KUQYfDKNxi53lUUQLAjaC0S6EkxHadvbO9vNzt3h/I7zsI5uMDG@Z20Uhsa@gu/9qu0ElOIubDMEhjsTNqi1lUDqqhQFYbjwjZXqA5rhnFKGH3pRG@TZleFW22QvXbD@kMmZJP1POaEHbqhLMx5aJ4NxQE7Z5Zl6K71rqaAPC4QUuys7@fThl4ixQAVH4owEEhxFvpsv "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated grade strings. Explanation: ``` WS ``` Repeat for each input grade... ``` ⊞υ⁺⌕FDCBA§ι⁰×·³⁻№ι+№ι- ``` ... calculate its value by looking up the letter in the string `FDCBA` and adjusting by `0.3` depending on the number of `+`s or `-`s. ``` ﹪%.1f∕ΣυLυ ``` Take the average and format it to one decimal place. [Answer] # Python 3, ~~168 150~~ 144 bytes ``` lambda n:int(sum([{'A':4,'A-':3.7,'B+':3.3,'B':3,'B-':2.7,'C+':2.3,'C':2,'C-':1.7,'D+':1.3,'D':1,'D-':0.7,'F':0}[i]for i in n])/len(n)*10+.5)/10 ``` Could save some bytes on the dictionary creation. Returns a float. ]
[Question] [ The challenge is simple: Read 3 letters from a system input¹ and convert them to numbers (`A-1, B-2, C-3...Z-26`)². Print each of those numbers in the order the letters were inputted in, each on a new line and then the sum of all 3 numbers, on its own line as well. NOTE: There will be no extra input characters, only 3 letters. However, the code must be case insensitive. This follows the standard rules of code golf, and the shortest byte count wins. ¹If your language does not support input, you may use from a file, or predefined variable instead. However, the program should be able to run any and all possibilities. ²The program should be able to take lowercase AND uppercase, and allow for a mix of lowercase and uppercase (e.g `wOq` or `ZNu`) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` O%32Ṅ€S ``` A full program that accepts a string of three letters and prints their alphabetic indices followed by their sum on four lines. **[Try it online!](https://tio.run/##y0rNyan8/99f1djo4c6WR01rgv///@@ekwYA "Jelly – Try It Online")** ### How? ``` O%32Ṅ€S - Main Link: list of characters, C O - cast to ordinals A:65 ... Z:90 / a:97 ... z:122 %32 - modulo 32 A:1 ... Z:26 / a:1 ... z:26 Ṅ€ - print each followed by a new line S - sum - implicit print ``` --- 9 if it had to be the *first* three of a string of letters ([Try it online!](https://tio.run/##y0rNyan8///hjsXG/qrGRg93tjxqWhP8//9/x6Rkl9Q094xMAA)): ``` ḣ3O%32Ṅ€S ``` ...or 12 if it had to both handle non-alphabetic characters, and take the *first* three *letters* ([Try it online!](https://tio.run/##AS4A0f9qZWxsef//ZsOY4bqg4bijM08lMzLhuYTigqxT////P0EhKmIuLi5jO2QrZT1B)): ``` fØẠḣ3O%32Ṅ€S ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `so`, 4 bytes ``` øA⟑, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzbyIsIiIsIsO4QeKfkSwiLCIiLCJaTnUiXQ==) Inspired by a -1 from @TheThunno ## Explained ``` øA⟑, øA # Char to alphabet index ⟑, # print each on newlines # the s flag sums the list and the o flag prints it even though implicit output gets disabled from the map ``` [Answer] # [Factor](https://factorcode.org/) + `combinators.extras`, ~~42~~ 35 bytes ``` 0 [ read1 32 mod dup . + ] thrice . ``` [Try it online!](https://tio.run/##Dcg9DsIwDAbQq3w7UgR0gwNULO2AOiEGk7iqRfODY0Q5feCNbyZvWdt0vQz9CVS9CHyOD0n0/@p4M6UKyXiyJl4RyRYUZbNvUUmGc9vjBmUKB3RHxBwQ3gUOO9xhi4pnuNY@4@sH "Factor – Try It Online") *-7 bytes thanks to @MarcMush* * `0` Push `0`, our sum, to the data stack. * `[ ... ] thrice` Call a quotation three times. * `read1` Read one code point from standard input. * `32 mod` Modulo 32. * `dup .` Output on its own line non-destructively. * `+` Add it to the sum. * `.` Print the sum. [Answer] # Google Sheets, ~~56~~ 53 Ending parens discounted. * Input is in A1 * B1 ``` =ArrayFormula(-64+CODE(UPPER(MID(A1,{1;2;3},1)))) or =ArrayFormula(-9+DECIMAL(MID(A1,{1;2;3},1),36)) ``` * C1 ``` =SUM(B:B) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 10 bytes Full program. Prompts via stdin and prints to stdout ``` +⌿⎕←⍪⎕A⍳⌈⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94L/2o579j/qmPmqb8Kh3FZDh@Kh386Oejke980Dy/xXAoICr3L@QS1dXlwvGj/IrBQA "APL (Dyalog Extended) – Try It Online") `⍞` prompt via stdin `⌈` uppercase `⎕A⍳` **i**ndices in uppercase **A**lphabet `⍪` make into column `⎕←` send to stdout `+⌿`‌ sum (and implicitly print to stdout) [Answer] # [Elixir](https://elixir-lang.org/), 70 bytes ``` &(IO.puts Enum.reduce &1,0,fn b,c->IO.puts b=b-(b>91&&96||64) c+b end) ``` [Try it online!](https://tio.run/##S83JrMgs@p9m@19Nw9Nfr6C0pFjBNa80V68oNaU0OVVBzVDHQCctTyFJJ1nXDqYgyTZJVyPJztJQTc3SrKbGzESTK1k7iSs1L0Xzf5qehnpUXqm65v//AA "Elixir – Try It Online") [Answer] # TI-BASIC, 135 132 bytes (on-calc) / 145 135 bytes (as text) -3 bytes thanks to MarcMush! ``` Input Str1 For(I,1,3 int(.5inString(" AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz",sub(Str1,I,1 Disp Ans A+Ans→A End A ``` ## Explanation * `Input Str1`: Take text input into string variable `Str1`. * `For(I,1,3`: Start a for-loop with variable I from 1 to 3 (TI-BASIC strings and lists are 1-indexed). * `int(.5inString(" AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz",sub(Str1,I,1`: Find the position of the current character of `Str1` in the alphabet string, divide it by 2 and find the floor of it to get the number of the uppercase or lowercase letter. Parentheses at the end of a line in TI-BASIC don't need to be closed, so using `.5` in front of `inString(` rather than `/2` behind it saves a couple bytes' worth of parentheses. * `Disp Ans`: Display what the previous line returned (`Ans`). * `A+Ans→A`: Add `Ans` to the sum (`Disp` doesn't return anything so `Ans` remains the same). * `End`: End of `For(` loop. * `A`: Implicitly print the sum (variable `A`) at the end of the program. [Answer] # [Perl 5](https://www.perl.org/) + `-pF`, 27 bytes -6 bytes thanks to [@Sisyphus](https://codegolf.stackexchange.com/users/48931/sisyphus)! ``` $\+=$;*say$;=31&ord for@F}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lRttWxVqrOLFSxdrW2FAtvyhFIS2/yMGttvr//6i80n/5BSWZ@XnF/3UL3P7r@prqGRroGQAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~67~~ ~~63~~ 53 bytes *-10 bytes by dingledooper* ``` i=[ord(c)%32for c in input()] *map(print,i+[sum(i)]), ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9M2Or8oRSNZU9XYKC2/SCFZITMPiApKSzQ0Y7m0chMLNAqKMvNKdDK1o4tLczUyNWM1df7/L/cvBAA "Python 3 – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 38 bytes ``` +++++++++++++>+++[>,.<<.>>[->+<]<-]>>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGxnYAXG0nY6ejY2enV20rp22TayNbqydnd7//@VGxgA "brainfuck – Try It Online") ## Explanation: The first 13 plus signs put the 'newline' character into cell 0. Then, I initialize cell 1 as a counter with a value of 3. Then there's the main loop. This loop will get a character in cell 2, display it, display the 'newline' character in cell 0, add cell 2 to cell 3, which holds the running sum, and repeat until cell 1 has a value of zero. When the loop is done, it displays the value in cell 3, which, if you've been following, holds the running sum of the characters. However, there is a problem with this last part: it displays the sum of the three characters as an ascii character, not an integer. I don't know if this is actually an issue since I technically displayed the sum, but just in case, I added a (long) routine to the end of the code that displays the sum as an integer. # [brainfuck](https://github.com/TryItOnline/brainfuck), 242 bytes ``` +++++++++++++>+++[>,.<<.>>[->+<]<-]>>+>>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]< ``` [Try it online!](https://tio.run/##dU5JCoAwDHxQbF8wzEdCDlUQRPAg@P6a1PWggYY0s2T6tUzLuA1zrfIu@lN2GcikJgoMyUghHxIQCJPG2qiiCeJD/NDKQuztLXLNv8IOvp6CgK9EBk/jwYJh0OYDu3j3BbfIjYFPC4cidlxFraUfdg "brainfuck – Try It Online") But wait, there's more. The routine I used only supports displaying eight bit numbers. This means that if I input 'abc' into the program, it displays: ``` a b c 39 ``` If you didn't catch it, the sum of the ascii values of 'a','b', and 'c' is not 39. However, it's equivalent if you add 255. This is because the value of the cell was only calculated to 8 bits by the routine I used. At this point, brainfuck had had its effect on my brain, and I didn't really feel like rewriting any more code in it. If I need to change my submission because of this issue or any other issue, let me know in the comments. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~5.5~~ 4.5 bytes ``` ;.@%$32+ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWK6z1HFRVjI20IVyo6ILFUX6lECYA) ~~Shorter than the Vyxal answer~~ not anymore but still doesn't cheat by storing information in flags. Nibbles is an awesome language. ``` ;.@%$32+ . For each character @ in the input: % Modulo $ the character 32 by 32 ; Take the result + and append its sum ``` *-1 byte by borrowing the modulo 32 trick from other answers* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ŒuO_64Ṅ€S ``` [Try it online!](https://tio.run/##y0rNyan8///opFL/eDOThztbHjWtCf7//3@5fyEA "Jelly – Try It Online") Full program which takes a three-character string of letters as the first command line argument. [10 bytes](https://tio.run/##y0rNyan8///kgqOTSv3jzUwe7mx51LQm@P//cv9CAA) to read from STDIN ## How it works ``` ŒuO_64Ṅ€S - Main link. Takes [a,b,c] (a string) on the left Œu - Convert to uppercase O - Ordinal _64 - Subtract 64 (A -> 1, B - 2 etc.) € - Over each: Ṅ - Print with a trailing newline S - Take the sum, and print implicitly ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 20 bytes ``` 0&(3|?84*%:. ,&+&)&. ``` [Try it online!](https://tio.run/##y05N///fQE3DuMbewkRL1UqPS0dNW01TTe///0SuJK5kAA "Keg – Try It Online") Why....why did I do this to myself? ## Explained ``` 0& ``` First of all, we put `0` into the register, because it is intialised as `None`. The register will be used to track the sum of the three letters. ``` (3| ``` Three times: ``` ?84*% ``` Take the next letter and modulo its ASCII value by 32. This trick is stolen from Jonathan Allen's Jelly answer, so go upvote that too. ``` :. , ``` Print the result of that modulo, followed by a newline (yes, newlines really do push newlines in Keg. This entire language is cursed, what did you expect?) ``` &+& ``` Push the value of the register, add the modulo'd index and then place that back in the register ``` )&. ``` Close the for loop and print the register raw. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` x=>[...[a,b,c]=[...x].map(z=>parseInt(z,36)-9),a+b+c].join` ` ``` [Try it online!](https://tio.run/##FcZLCoAgEADQfSdRtNkEQQvbd4YQnMx@mCMZEV7e6K3egQ8me@3xrgPNriyqvKofAWBEOUmr1f9Xw4mRZdVHvJIbws2ybFped1yimITVcNAeTGWKpZDIO/C0soWZzXnDefkA "JavaScript (Node.js) – Try It Online") ``` x=>[ // Define a function taking a parameter x, returning an array of... ... // Iterating over... [a,b,c]= // assign a, b and c to... [...x].map(z=> // x mapped to... parseInt(z,36)-9 // parse as base36, -9 to get charcode ), a+b+c // and the sum of all three ].join`\n` // Joined by newline ``` The trick is that parseInt is case-insensitive, saving a lot of bytes. [Answer] # Ruby, 36 Bytes ``` p $*.map{|c|p c.downcase.ord-96}.sum ``` [Answer] # [Julia 1.0](http://julialang.org/), 38 bytes ``` r=read(stdin).%32 println.([r;sum(r)]) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/v8i2KDUxRaO4JCUzT1NP1diIq6AoM68kJ09PI7rIurg0V6NIM1bz//9Ep2QA "Julia 1.0 – Try It Online") [Answer] # [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) 0.84, ~~107~~ 77 bytes This code expects 1 argument passed to the compiler, with the 3 characters used for input. Outputs the text directly and doesn't return anything. ``` {@eachargv.0}{@callord intoZ _}{@set%A.[__]Z 32}{@/}{@set+Y A}{@echoj"\n"A,Y} ``` This is quite a messy mess... But you can try it on <http://sandbox.onlinephpfunctions.com/code/825bbd653f036fce8cc12f639c982ec5eed793ea> (Please don't use PHP 8.0.0) Thanks [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) for the idea that saved me 30 bytes. --- **Ungolfed:** This should be a lot easier to read. ``` {@set numbers as 0, 0, 0} {@each argv.0 as letter key key} {@call ord into tmp letter} {@set% numbers.[key] tmp 32} {@/} {@set+ sum numbers} {@echo separator "\n" numbers, sum} ``` --- **Explanation:** I will explain how the golfed version works. * `{@eachargv.0}` - loops through the first argument. `argv` is an array with all passed arguments. The ungolfed version defines variables for the key as value: `{@each argv.0 as letter key key}`. The default names are `_` for the value and `__` for the key. * `{@callord intoZ _}` - calls the [function `ord`](https://www.php.net/manual/en/function.ord.php) passing `_` as a value and storing into `Z`. `Z` is the same as `tmp` in the ungolfed version. * `{@set%A.[__]Z 32}` - `set` is used to define a variable, and you can pass it a value. If you add a `%` before the variable, it calculates the remainder of the values (in this case, `Z` divided by 32). By magic, this handles letters A-Z and a-z, and maps them to A>1, B>2 ... Z>26. The result is stored into `A.[__]` (`numbers.[key]` in the ungolfed version). * `{@/}` - closes the `@each` loop * `{@set+Y A}` - `set` is used to define a variable, and you can pass it a value. If you add a `+` after, it indicates that it will receive the sum of all the passed values. In this case, it will sum all the numbers (`A`) and store into `Y`. The ungolfed version has `{@set+ sum numbers}`, which demonstrates a lot better the way it works. * `{@echoj"\n"A,Y}` - Outputs `A` and `Y`, joined by `"\n"`. The ungolfed version has `{@echo separator "\n" numbers, sum}`. `@echoj` is just a shorthand for `@echo separator`. All values are separated by `"\n"`, regardless of their type. This doesn't output a newline at the end! [Answer] # [PHP](https://php.net/) -F, 55 bytes ``` for(;$c=ord($argn[$i++])%32;$r+=$c)echo"$c ";echo"$r "; ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVkm3zi1I0VBKL0vOiVTK1tWM1VY2NrFWKtG1VkjVTkzPylVSSuZSsIawiIOv//6i80n/5BSWZ@XnF/3XdAA "PHP – Try It Online") Quite straightforward solution.. [Answer] # [Grok](https://github.com/AMiller42/Grok-Language), 35 bytes ``` j :zhq hx{y1py1pw*25xxY+zPY%*48py1p ``` [Try it Online!](http://grok.pythonanywhere.com?flags=&code=j%0A%3Azhq%0Ahx%7By1py1pw*25xxY%2BzPY%25*48py1p&inputs=aBc) Gets input, then starts moving left through the main program, which juggles the register, where the running sum is stored, and the stack, where the input and some calculations are stored. Once all letters are printed and added, execution moves up to the middle row, where the sum is printed and execution ends. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), 38 bytes ``` (Print@Column[y=LetterNumber@#];Tr@y)& ``` Doesn't seem to run in [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277XyOgKDOvxME5P6c0Ny@60tYntaQktcivNDcptchBOdY6pMihUlPtf3q0UlReqVIs138A), so here are some screenshots: [![enter image description here](https://i.stack.imgur.com/LdqTx.png)](https://i.stack.imgur.com/LdqTx.png) [![enter image description here](https://i.stack.imgur.com/RU873.png)](https://i.stack.imgur.com/RU873.png) *And here is a superior 32-byte approach given by att in the comments:* ``` Print/@##@*+##&@@LetterNumber@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6AoM69E30FZ2UFLW1lZzcHBJ7WkJLXIrzQ3KbXIQVntf3q0UlReqVIs138A) [Answer] # [jq](https://stedolan.github.io/jq/), 22 bytes ``` [explode[]%32]|.[],add ``` [Try it online!](https://tio.run/##yyr8/z86taIgJz8lNTpW1dgotkYvOlYnMSXl/3@lRKdkJQA "jq – Try It Online") quite useful that `.[]` prints numbers with newlines. [Answer] # [J](https://www.jsoftware.com), ~~32~~ 24 bytes ``` echo,.(,+/)32|3 u:1!:1[3 ``` Full program, -8 bytes thanks to [Conor](https://codegolf.stackexchange.com/users/31957/conor-obrien). [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboWO1KTM_J19DR0tPU1jY1qjBVKrQwVrQyjjSHSUFULFjuG-EOYAA) ``` echo,.(,+/)32|3 u:1!:1[3 1!:1[3 NB. read from stdin 3 u: NB. convert to char codes 32| NB. mod 32 (,+/) NB. monadic hook +/ NB. sum nums , NB. append sum to nums ,. NB. make a column echo NB. print ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 53 ~~60~~ bytes *-7 bytes thanks to @Julian* > > By encapsulating the first command in parenthesis, I was able to skip the second command which just printed $t and saved 1 byte. The other 6 bytes were from replacing ***$t='a','b','c'*** with ***$t=$args***. > > > ``` ($t=$args|%{[byte][char]$_%32});($t|measure -sum).sum ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0OlxFYlsSi9uEa1OjqpsiQ1Njo5I7EoViVe1dioVtMaKF@Tm5pYXFqUqqBbXJqrqQck/v//r56orqCeBMTJ6gA "PowerShell – Try It Online") **Explanation** ``` ($t= # $t will be set to an array of ints returned $args # 'a','b','c' is passed through aka $args | # pipes into the next command %{ # for loop [byte][char]$_ # accepts char and returns int (ie. [byte][char]'a' returns 97) %32 # x mod 32 returns position in alphabet }) # completes for loop and encapsulation ; # divider between commands ($t # passes the ints returned from the command above | # pipe into next command measure -sum # measures the array and adds the sum property ).sum # only returns the sum property ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 60 bytes ``` i,j;f(char*s){for(i=0;printf("%d\n",j=*s&31?:i),*s++;i+=j);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9TJ8s6TSM5I7FIq1izOi2/SCPT1sC6oCgzryRNQ0k1JSZPSSfLVqtYzdjQ3ipTU0erWFvbOlPbNkvTuvZ/bmJmnoZmNRdQZbl/oZKmNVdBaUmxhhKIBRSL8isFsWr/AwA "C (gcc) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` j+=%R32CMQs ``` [Try it here!](http://pythtemp.herokuapp.com/?code=j%2B%3D%25R32CMQs&input=%22ZNu%22&debug=0) [Answer] # [Red](http://www.red-lang.org), ~~58~~ 57 bytes -1 byte thanks to dingledooper! ``` func[a][s: 0 foreach c a[s: s + probe 1 * c % 32]print s] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85OjE2uthKwUAhLb8oNTE5QyFZIREkUKygrVBQlJ@UqmCooAUUVFUwNootKMrMK1Eojv2fpqBU7l@o9B8A "Red – Try It Online") Takes a 3-letter string as input. Iterates over the string, converts each character to an integer `(1 * c)` and maps it to `1-26` by `% 32`. Prints this at each step using `probe` (it returns a value) and updates the sum, which is printed at the end. ## Full program (works in Red console), ~~53~~ 52 bytes -1 byte thanks to dingledooper! ``` s: 0 foreach c input[s: s + probe 1 * c % 32]print s ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ≔ES﹪℅ι³²θ⊞θΣθIθ ``` [Try it online!](https://tio.run/##HYs5CoAwEAB7X2G5gdhoaSVWKYJC/MCioIGYO35/jTYDMzD7hXF3aIimlPRpQaIHYX3JKkdtT2C8le4oxsESD23RgK5p6FllYGOzlnRB4K0qNwT2hbplmDHl34k2sVD3mBc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔ES﹪℅ι³²θ ``` Map the input string into ASCII ordinals and reduce modulo 32. ``` ⊞θΣθ ``` Append the sum. ``` Iθ ``` Output everything in decimal. [Answer] # Excel, 65 bytes ``` =LET(n,ROW(1:4),a,MOD(CODE(MID(A1&" ",n,1)),32),IF(n=4,SUM(a),a)) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnF0ZoQH4IAt0Z75U?e=8VbbRN) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` Ëc %H pUx ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=y2MgJUgKcFV4&input=WyJaIiwiTiIsInUiXQ) ``` Ëc %H\npUx :Implicit input of character array Ë :Map c : Charcode %H : Mod 32 \n :Assign to variable U p :Push Ux : U reduced by addition :Implicit output joined with newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç32%€=O? ``` [Try it online](https://tio.run/##yy9OTMpM/f//cLuxkeqjpjW2/vb//yc7Vv3X1c3L181JrKoEAA) or [verify the entire alphabet at once](https://tio.run/##yy9OTMpM/X90X57t/8Ptxkaqj5rW2Prb//8PAA). **Explanation:** ``` Ç # Get the ASCII values of the characters in the (implicit) input-string 32% # Modulo each by 32 € # For-each over these integers: = # Print the integer with trailing newline (without popping) O # Take the sum of the list ? # And output it (without newline) as well ``` ]
[Question] [ ![Image of Hex Conversion Table w/ counter](https://www.tutorialspoint.com/ipv6/images/Hexadecimal_conversion_table.jpg) **Hexadecimal** is a base 16 counting system that goes from `0` to `f`. Your job is to make a counter that will display these numbers. **Example:** ``` $ python counter.py 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 ``` **Rules:** * The numbers may be separated by spaces, tabs, or new lines. * The minimum number you must go to is `30` (48 in decimal). + You may also make the program print numbers forever until it is stopped. * Letters may be in uppercase or lowercase (`A` or `a`). * No built in functions allowed (that directly affect hexadecimal conversions/counting). * Leading zeros are allowed * It may start from `1` or `0` * Shortest code wins! [Answer] # Pure [Bash](https://www.gnu.org/software/bash/), 26 Counts from 0x0 to 0x3F: ``` echo {0..3}{{0..9},{A..F}} ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I1@h2kBPz7i2GkRZ1upUO@rpudXW/v8PAA "Bash – Try It Online") [Answer] # CJam, ~~21~~ 14 bytes ``` A,_6,'Af++m*S* ``` Prints the numbers 00 to 9F. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=A%2C_6%2C%27Af%2B%2Bm*S*). ### How it works ``` A, e# Push [0 ... 9]. _ e# Push a copy. 6, e# Push [0 ... 5]. 'Af+ e# Add 'A' to each. This pushes "ABCDEF". + e# Concatenate. This pushes [0 ... 9 'A' ... 'F']. m* e# Cartesian product. This pushes [[0 0] ... [9 'F']. S* e# Join, separating by spaces. ``` [Answer] # Pyth - 12 bytes Uses cartesian product, and sorts at the end to get in correct order, then joins by spaces. Prints `00-ff` inclusive. ``` jdS^s+<G6UT2 ``` [Try it online here](http://pyth.herokuapp.com/?code=jdS%5Es%2B%3CG6UT2&debug=1). ``` jd Join by spaces S Sort lexiographically ^ 2 Cartesian product repeat twice s+ Append then concatenate entire list <G6 First six of alphabet UT Range 0-9 ``` [Answer] # Python 2, 52 ``` a=0 for b in'0123456789ABCDEF'*4:print`a`+b;a+=b>'E' ``` Prints `00` to `3F`. Takes advantage of the fact that the first digit `a` is always a number in this range. Loops through four cycles of the second digit `b`, incrementing `a` whenever the second digit is `F`. This is one char shorter than the more direct ``` for a in'0123': for b in'0123456789ABCDEF':print a+b ``` [Answer] ## JavaScript (ES6), 57 bytes Same approach as the Python ones I suppose. ``` for(i of c='0123456789ABCDEF')for(j of c)console.log(i+j) ``` [Answer] # TI-Basic, 63 bytes ``` :For(I,0,4,16⁻¹ :Disp sub(" 0123456789ABCDEF",1+16fPart(I),2 :Output(7,1,int(I :End ``` This is 63 bytes, according to the memory management screen on my calculator, a TI-84+. Make sure to start the program with a partially filled home screen! [Answer] ## **Befunge-93, 57 bytes** ``` <_v#-*44:+1,*84,g2:\,g2:\ ^ >$1+:9-!#@_0 0123456789ABCDEF ``` Prints numbers from `00`to `8F`. If you prefer your programs to run forever, the version below is non-terminating and will continually output all numbers from `00` to `FF`. ``` <_v#-*44:+1,*84,g2:\,g2:\ ^ >$1+:35*`!*0 0123456789ABCDEF ``` [Answer] # C, ~~78~~ 75 bytes ``` x(y){return y+48+y/10*7;}f(j){for(j=0;printf("%c%c ",x(j/16),x(15&j++)););} ``` We define a function `f()` to be called with no arguments for printing, and a helper function `x(int)`. This breaks at `FF`. Amazingly, this is one byte shorter than the more obvious: ``` char*s="0123456789ABCDEF";h(j){for(j=0;printf("%c%c ",s[j/16],s[15&j++]););} ``` *Warning: it is not recommended to run this code outside of a debug environment...* Testing: ``` int main(int argc, char** argv) { f(); return 0; } ``` Output: ``` 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 (...) ``` Of course, the more robust (and cheat-y) approach is this 34-byte function: ``` g(i){for(i=0;printf("%x ",i++););} ``` [Answer] # Pyth, 17 bytes ``` VJs++kUT<G6FYJ+NY ``` [Try it here](https://pyth.herokuapp.com/?code=VJs%2B%2BkUT%3CG6FYJ%2BNY&debug=0) ## How it works: ``` <G6 # "abcdef" UT # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] k # an empty string (so + means concatenation, not addition) s++ # join them all ("0123456789abcdef") J # call this J V # for each N in J... FYJ # for each Y in J... +NY # print N and Y ``` [Answer] # Javascript ES6, 67 62 bytes ``` (x=''.replace.bind('0123456789ABCDEF',/./g))(n=>x(o=>' '+n+o)) ``` [Answer] # J, 22 bytes ``` >{;~'0123456789abcdef' ``` Counts to `ff`. Prints an extra newline between each block of `0x10` numbers, like so: ``` ... 0d 0e 0f 10 11 ... ``` [Answer] # Mumps - 65 bytes ``` S Q="0123456789ABCDEF" F I=1:1:16 F J=1:1:16 W $E(Q,I),$E(Q,J),! ``` Nope... Mumps ain't dead yet! :-) [Answer] # CJam, 22 bytes ``` 1{_GbA,6,'af++f=oNo)}h ``` This runs forever, and thus is probably one of the rare times where it's a good idea *not* to include a permalink. [Answer] # TheC64Mini and Commodore BASIC (C64/128, PET, VIC-20, C16/+4) - 164 BASIC and Tokenized bytes used ``` 0 fOd=.to255:n=d:fOi=1to.stE-1:h%(i)=n/(16^i):n=n-(h%(i)*(16^i)):nEi:h$="" 1 fOi=1to.stE-1:ifh%(i)<10tHh$=h$+cH(48+h%(i)) 2 ifh%(i)>9tHh$=h$+cH(55+h%(i)) 3 nEi:?h$" ";:nEd ``` Prints a double-space after the hex number to nicely align the printing at 40/80 columns as well as the 22 columns on the VIC-20. [![Commodore Plus/4 Hex counter innit](https://i.stack.imgur.com/R5LSi.png)](https://i.stack.imgur.com/R5LSi.png) [Answer] # [Malbolge](https://www.lscheffer.com/malbolge.shtml), 900 bytes To be improved... ``` D'``@"\7}|X9E1gwuR21=p(:9%IZYEg}eA/ya>O_)([Zvotm3qponmfN+Lbg`ed]\"CB^W\Uy<;WVONSLp3ONMLEDhH*)?>b%A@?87[;:9876/S3,P0/.-&J$)"'~D|{"y?}|utyr8potmrqpi/mfN+Lbg`e^$bDZ_^]VzZSXQVUTSLp3ONMLEDhH*)EDCB;@?8\6|:32V6v.32+O)o'&J*)i'&%|Bcb~w|u;yxwvutVrkj0nmfN+iKg`_%cE[`Y}@V[ZYXWPtT6LKJImM/KJIBAe(D=<A:98\[;{32V6v.-,P0).',%I)"!E%|#"y?w_{ts9Zvutsrkpi/mfNjihg`e^$b[Z~X]\[ZYRv98TSLKoO10FKDh+GFE>CB;_?>=}|49870/.R2+*Non&%I#"!&%${A!~}_u;yxqpo5mrqpoh.lkdibgf_%]\[!_XW{[ZYXQPt7SRQPOHGkKJIHAF?cC<;@?8\6;492V6v.-,P*p.'K+$j"'~D|#"y~wv<]yxqvutsrk1onmfN+cba`&d]#DZ_^]VzTSXQVOs65QJINGkE-IBAe(D=<A:98\654981Uv.32+*)M-,%k#(!E}$#"!x>v{t:xwputm3kpoh.fN+Lbg`ed]\"!Y^]VzZYXQVOsS54JImMFKJIHAe?>C<`@?87[;{32V05.-2+O)o-,+$H('&}Cdzy~wv<]sxqvonm3k1oQmf,jihgfeG]#a`_X|V[TxXQPUTMLp3ONMLEDhH*)ED=a;@?>76;4X816/43,P*).',%I#i!&}|Bcb~w|u;yxwputm3qSong-kjihgfH%]\a`_XW{UTYXQuUTMRKPOHlFKDhBAe?>=B;_9>=6Z:981Uv.32+*)M-,%k#(!E%$#c!x>|u;yxZpo5srqSi/z ``` [Try it online!](https://tio.run/##bZJXd6JQFEZ/i1IUe8WOsWDvBRU1YEWCBuwawb/uHGBmVjJrXu7jXvvu7@xm27m8FVavV97G82/WSURThzHaL1zPnYA/pdjjMazMjmhBW2W89xnV5Aj7mL3Ip11wr8ifu3XDWZsL/Go5nVhz2ffBpH9PJgZMs9GtKcFmo16j85uSg0hTcyzzlo5Gxol4LBohvd2gq@Xzetx4BSWstmdefVjvaU09n@6HqAL0w14RvX/p7@g8z3LvU@aL7Q7bTL/3k07nc9kE0CekGg8GGPLiCQacTUK24RUHIdpwTM0u5s@rek7cb9fL@cQcpA@f4S5WBZ7DFvSYH2lvzJgdDQetU4@sVSvlXd0LbzazsudTyQxYT8aJh0l3gzvhsbmwMmG10JiKgPuVe5yOMRbox4Nkun@IG9N9zD6H0wnQO5dYFNyrctPvK1TzG2exQFPgzqWplKaGoAw06QScjob8iWNlxGrBMfSRsTw1TneH4mG9jLzxbKWlOBfWHAZcCzccPHT3dusU6XbarWapKIF7KVNIL3JJs0wiFPvj7lA8tqoT/TC6g/vzeklOgW66@81VF/MZjy@nyO/uPb1780iG25VyoyjR7h9lyDC4@/tGdwdRd7swCbFbaA2FH9yoy@MUv12VM9yMpLt/vxnLyFh1ZNC74ZDevWC4r9JULsmbN6N394U9bmNVt8uJluw2XMstv0z3I7iDdRDc27u1S@@@XhWnyIznhioz7t2gTL9X/@dmUjMoQ0WgzDDqJ70huEiHuSoiWnDt@80Y7vuu/Cm4JYNegu46ffDo98D9DPROFbpv9VWzunsKVo1RKZKN/68MhiILKGPQWVj1eNh3Re/X6/UL "Malbolge – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 2902 bytes Easy to outgolf, but worth giving a shot ``` +>+[<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<<[-]++++++++++++++++++++++++++++++++++++++++++++++++>[-]<[>+<<+>-]<[>+<-]<]>+<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>.>.>>>++++++++++++++++++++++++++++++++.[-]<<[-]<<[>>+<<<+>-]<[>+<-]>>>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<[<<<<+>>>>-]+>>[<<<<<<-<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[>>>>-<<<<[-]]>>>>>>[-]++<<[<<<<<+>+>>>>-]<<<<<[>>>>>+<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>[-]<[>+<<<+>>-]<<[>>+<<-]>>>>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++<<[<<<<+>>>>-]+>>[<<<<<<-<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[>>>>-<<<<[-]]>>>>>>[-]+++<<[<<<<<+>+>>>>-]<<<<<[>>>>>+<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>[-]<<[>>+<<<+>-]<[>+<-]>>>[<<<<+>>>>-]+>[<<<<<-<+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]>[>>>>-<<<<[-]]>>>>>>+++++<<[<<<<<+>+>>>>-]<<<<<[>>>>>+<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]>++++++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>[-]<[>+<<<+>>-]<<[>>+<<-]>>>[<<<<+>>>>-]+>[<<<<<-<+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]>[>>>>-<<<<[-]]>>>>>>++++<<[<<<<<+>+>>>>-]<<<<<[>>>>>+<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>+>>>+<<<<<<<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[-]<<<<<<]>++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>-----<<<[-]>>>[<<<+<+>>>>-]<<<<[>>>>+<<<<-]>>>>+++++>+<<<<<<<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[-]<<<<<<]>+++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>>-----<<[-]>>[<<+<<+>>>>-]<<<<[>>>>+<<<<-]>>>>+++++>+<<<<<<<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[-]<<<<<<]>++++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>+>[-]++++++++++++++++++++++++++++++++++++++++++++++++>>>+<<<<<<<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[-]<<<<<<]>+++++<<+<<[>>->+<<<-]>>>[<<<+>>>-]<[->+<<[>>>-<<+<-]>[<+>-]>>[<->[-]]<[<<<+>>>-]<]>>[-]<<<<[>>+>+<<<-]>>[<<+>>-]>[[-]>>>>[-]<[>+<<<+>>-]<<[>>+<<-]>>>[<<<<+>>>>-]+>[<<<<<-<+>>>>>>-]<<<<<<[>>>>>>+<<<<<<-]>[>>>>-<<<<[-]]>>>>>>++++++<<<<<<+>>>>[<<<<[-]<+>>>>>-]<<<<<[>>>>>+<<<<<-]>[<<<[-]>[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>[-]]>>>>>>[-]<<<<<<]<<<[>>+>+<<<-]>>[<<+>>-]>[[-]<<<[-]>[-]>>]<<] ``` [Try it online!](https://tio.run/##3VbbCsIwDP2gUL8g5EdCH1QQRPBB8PtnLm3XwdxgFzvMYF2z9OTkpKteXuf78/a@ProOCBiZSEZEDJGIEYFInph1KiYjbGKSYQGW5heKoLzSkwzRHKjcQ@Gu5JW9xZmbdaKBWpABaFBQTAnpo6OViYiTYpzkktczdjIkv5FBVcRN0RUKKmcjLZDgBStXd3ktbpwckOZaBLkaRs6ZeHMTrIBAhcHVepPP1lHeFlSyl4Vz@eus7o0zilPfffdnTQ@q5OGlHN@SQy14qEROwAMWX1SoxW0hAuX2/vpsmN6p2wp84E0GFcTa/CO9bdFXCmqpmpQPK@G50PZ4/9XaUYSmKnB@i201aCACLPkrtO/38PdHHUBWKENrbqBDnXt1RpnErvsA "brainfuck – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6, 40 bytes ``` ($l=0..9+'A'..'F')|%{$1=$_;$l|%{"$1$_"}} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0Mlx9ZAT89SW91RXU9P3U1ds0a1WsXQViXeWiUHyFRSMVSJV6qt/f8fAA "PowerShell – Try It Online") Starts at `00` and counts up to `FF`. [Answer] ## [MUMPS](https://en.wikipedia.org/wiki/MUMPS), 57 bytes ``` f i=1:1:48 w $tr(i\16,0),$e("0123456789abcdef",i#16+1),! ``` Output ``` >d ^xmsdgolf 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 .. 28 29 2a 2b 2c 2d 2e 2f 30 ``` Explanation ``` f i=1:1:48 ; loop from 1 to 48 w $tr(i\16,0) ; print i div 16, and ditch any zeros $e("0123456789abcdef",i#16+1) ; extract the nth character from the string, where n is i mod 16 + 1 ! ; crlf ``` [Answer] # Python 2, ~~66~~ 55 Bytes This should really have been the most obvious approach to me.. ``` a='0123456789ABCDEF' for x in a: for y in a:print x+y ``` **Old (66 Bytes)**: Technically this causes an error after `FF`, but it does reach `30`. ``` n=1;a='0123456789ABCDEF' while 1:print a[n/16]*(n>15)+a[n%16];n+=1 ``` I assumed string formatting wasn't allowed since I'm pretty sure it would go through base conversion, but if it was allowed, this would be 29 bytes: ``` n=1 while 1:print"%x"%n;n+=1 ``` [Answer] # Java, 104 bytes ``` char t[]="0123456789abcdef".toCharArray(),i;void f(){for(;i<99;)System.out.println(""+t[i/16]+t[i++%16]);} ``` If the `i<99` is removed, it still reaches 30, but eventually crashes. I'm not sure if that's acceptable. [Answer] ## J, 47 bytes ``` '0123456789abcdef'{~([:|:2 256$(]#i.),256$i.)16 ``` prints 00 to ff [Answer] # JavaScript ~~74~~ ~~72~~ ~~65~~ 60 ``` //for(i=0,a="0123456789ABCDEF";i++<49;)console.log(a[i>>4]+a[i%16]) for(i=0;i++<48;)console.log((i>>4)+"0123456789ABCDEF"[i%16]) ``` [Answer] # [Perl 6](http://perl6.org), 34 bytes The shortest that I can come up with that doesn't use any sort of conversion is: ``` put [X~] (|(0..9),|('A'..'F'))xx 2 # 34 bytes ``` prints `00` ... `FF` space separated in order. If you want more you can swap `2` for a larger number. (don't use a number bigger than 4 as it concatenates the values together before outputting anything, so it would use a significant amount of RAM ) --- Shortest that will never stop writing hex values ``` put [R~] (|(0..9),|('A'..'F'))[.polymod: 16 xx*]for 0..* # 56 bytes ``` --- If `printf` were allowed ``` printf "%X ",$_ for 0..* # 24 bytes ``` If a base conversion function were allowed ``` put .base(16)for 0..* # 21 bytes ``` [Answer] # Matlab: 47 bytes ``` q=[48:57,97:102,''];fliplr(char(combvec(q,q)')) ``` I don't know if it would be considered as counter. The code generates vector of hex numbers from `00` to `ff`. `q` is a string `'0123456789abcdef'` in `double` format. Combvec generates all possible pairs between `q` and `q`. Char converts it to string format and `fliplr` flips the columns to get: ``` 00 01 ... 08 09 0a 0b 0c 0d 0e 0f 10 11 ... fd fe ff ``` [Answer] ## C++14 - 135 ``` #include<string> #include<iostream> void f(){std::string a="0123",b="0123456789ABCDEF";for(char c:a)for(char d:b)std::cout<<c<<d<<" ";} ``` [Answer] # [jq](http://stedolan.github.io/jq/) 1.5: ~~65~~ 59 characters (56 characters code + 3 characters command line option.) ``` [range(10)]+"a b c d e f"/" "|{a:.[],b:.}|"\(.a)\(.b[])" ``` Sample run: ``` bash-4.3$ jq -n -r '[range(10)]+"a b c d e f"/" "|{a:.[],b:.}|"\(.a)\(.b[])"' | head 00 01 02 03 04 05 06 07 08 09 ``` [On-line test](https://jqplay.org/jq?q=[range%2810%29]%2B%22a%20b%20c%20d%20e%20f%22/%22%20%22|%7Ba:.[],b:.%7D|%22%5C%28.a%29%5C%28.b[]%29%22&j=null) (Passing `-r` through URL is not supported – check Raw Output yourself.) # jq 1.5: 56 characters (53 characters code + 3 characters command line option.) ``` [[range(10)]+"a b c d e f"/" "|"\(.[])\(.[])"]|sort[] ``` This produces correct output, however is not exactly a counter: it not generates the values in order, just sorts them after. [On-line test](https://jqplay.org/jq?q=[[range%2810%29]%2B%22a%20b%20c%20d%20e%20f%22/%22%20%22|%22%5C%28.[]%29%5C%28.[]%29%22]|sort[]&j=null) (Passing `-r` through URL is not supported – check Raw Output yourself.) [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 12 bytes ``` ∘.,⍨16↑⎕D,⎕A 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF ``` [Answer] ## Ruby, 64 bytes ``` h='0123456789abcdef'.split //;h.each{|i|h.each{|j|print i,j,?\s}} ``` Explanation: ``` h = '0123456789abcdef'.split // # Split string of hex chars at # matches of //, returns array # splits array by characters h.each { |i| # loop 1 h.each { |j| # loop 2 print i,j,?\s # print() can take multiple params, # and it is the same as printing # each one using a separate print(). # ?x is the same as 'x', so ?\s is # the same as "\s", which is " ". } } ``` [Answer] # Zsh, ~~44~~ 29 bytes ***-15***, via GammaFunction   [try it online!](https://tio.run/##qyrO@P8/w1aj2kBPz7JWoTpRTy@tVtM6NTkjX0ElLgOI/v8HAA) ``` h=({0..9} {a..f});echo $^h$^h ``` Original (44 bytes): `g=0123456789abcdef;h=(${(s::)g});echo $^h$^h` [Answer] # [Ahead](https://github.com/ajc2/ahead), 42 bytes Prints hex numbers starting at 0 forever. Will eventually overflow, though. ``` >t>:16;r Cvn:/61\< >$>:10/7*v ^oNndo++0'< ``` [Try it online!](https://tio.run/##S8xITUz5/9@uxM7K0My6iMu5LM9K38wwxoZLwU4FKGagb65VxhWX75eXkq@tbaBu8/8/AA "Ahead – Try It Online") ]
[Question] [ # Introduction Bob runs a deli. His deli serves sandwiches to its customers. However, it is a bit unusual. At Bob's deli, instead of telling Bob what they want, customers show Bob an ASCII art drawing of their sandwich. Bob must find the pattern in their sandwich so he knows what ingredients to prepare. However, Bob does not like picking out patterns. He wants you to write a program to help him do that. # Challenge You must write a function which, given the filling of a sandwich, will output a list of ingredients for Bob to prepare. You must find the pattern of ingredients in the filling, then output that pattern. * Input will be a string. It will never be empty, and it will only contain printable ASCII characters (characters 32 to 255). If your language has no method of input, input can be taken in the form of command line arguments or stored in a variable. * Output must be a string. If your language has no method of output (or you are running a function, not a full program) you may output through return code or through a variable. # Example I/O * `Input: |&|&|&|&` `Output: |&` * `Input: :&|:&|:&|` `Output: :&|` * `Input: ((&|((&|((&|((&|` `Output: ((&|` # Rules This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! [Answer] # [Python](https://docs.python.org/2/), 28 bytes ``` lambda s:s[:(s+s).find(s,1)] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYqjjaSqNYu1hTLy0zL0WjWMdQM/Z/eUZmTqqCoVVBUWZeiUKaRmZeQWmJhqbmf6UaNQhU4lKyUquBICBbQ0OtBhkrAQA "Python 2 – Try It Online") The length of the output is the first nonzero position starting from which `s` can be found in the doubled `s+s`. For example: ``` s = abcabcabc s+s = abcabcabcabcabcabc abcabcabc ^ s starting at position 3 (zero-indexed) ``` --- **46 bytes** ``` f=lambda s,p='':p*(s+p==p+s)or f(s[1:],p+s[0]) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRoVinwFZd3apAS6NYu8DWtkC7WDO/SCFNozja0CpWB8iNNojV/F@ekZmTqmBoVVCUmVcClM3MKygt0dDU/K9UowaBSlxKVmo1EARka2io1SBjJQA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` η¢Ï ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3PZDiw73//@voaFWg4wB "05AB1E – Try It Online") ``` η # prefixes of the input ¢ # count the number of occurences of each one within the input Ï # filter the input, keeping only indices where the above is 1 ``` Prefixes that stop short of the last repetition of the pattern can be found multiple times in the input, offset by a pattern-length. Thus, this ends up keeping only the last repetition of the pattern. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Ḋ;wḣ@ ``` [Try it online!](https://tio.run/##y0rNyan8///hji7r8oc7Fjv8P9z@qGlN5P//0Uo1ahCopMOloGSlVgNBYJ6GhloNMlaKBQA "Jelly – Try It Online") A slightly modified version of [xnor's answer](https://codegolf.stackexchange.com/a/195415/59487). Method: Given **S**, concatenates **Swithout the first character** with **S**, then finds the index of **S** in this new string, then takes the head. [Answer] # [J](http://jsoftware.com/), ~~22~~ 15 bytes ``` {.~1+]i.~#$&><\ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q/XqDLVjM/XqlFXU7Gxi/mtypSZn5CukKahraKjVIGN1LogUWEJdQdcKuyKImho1mIoaNQiEyVghNAOZEKT@HwA "J – Try It Online") No regex solution: ``` {.~ NB. take from the input this many chars: 1 + NB. 1 plus... i.~ NB. the first index of... ] NB. the input in this list: <\ NB. every prefix of the input... $&> NB. cyclically repeated to... # NB. the size of the input. ``` --- I could shave off two more bytes using a xnor's wholly different approach, but for the sake of variety I'll leave my original as the answer: ``` {.~1{]I.@E.,~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/q/XqDKtjPfUcXPV06v5rcqUmZ@QrpCmoa2io1SBjdS6IFFhCXUHXCrsiiJoaNZiKGjUIhMlYITQDmRCk/h8A "J – Try It Online") [Answer] # JavaScript (ES6), 25 bytes ``` s=>/(.+?)\1*$/.exec(s)[1] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k5fQ0/bXjPGUEtFXy@1IjVZo1gz2jD2f3J@XnF@TqpeTn66RpqGUo0aBCppanKhSVmp1UAQFjkNDbUaZAxU8h8A "JavaScript (Node.js) – Try It Online") ### Regular expression ``` +-------> 1st (and only) capturing group: 1 or more character(s), non greedily | +---> reference to the capturing group, repeated 0 to N times _|_ | +-> end of string / \/ \| /(.+?)\1*$/ ``` [Answer] # [Icon](https://github.com/gtownsend/icon), 50 bytes ``` procedure f(s) return s[1:1+find(s,s[2:0]||s)] end ``` [Try it online!](https://tio.run/##y0zOz/v/v6AoPzk1pbQoVSFNo1iTqyi1pLQoT6E42tDKUDstMy9Fo1inONrIyiC2pqZYM5YrNS8FSUtuYmaehiaXAhCUF2WWpGqkaSjVqEGgkiaahJVaDQRhyGhoqNUgY5ACkEUA "Icon – Try It Online") An [Icon](https://github.com/gtownsend/icon) port of [xnor's Python solution](https://codegolf.stackexchange.com/a/195415/75681). Don't forget to upvote his answer! [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 15 bytes ``` s/(.+?)\1*$/$1/ ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0NP214zxlBLRV/FUP///xo1COSyUquBIC4NDbUaZPwvv6AkMz@v@L9uTgEA "Perl 5 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 72 bytes ``` f(char*s){int n=1,p=1;while(s[p]|p%n)s[p]^s[p%n]?p=++n:++p;puts(s+p-n);} ``` [Try it online!](https://tio.run/##S9ZNzknMS///P00jOSOxSKtYszozr0Qhz9ZQp8DW0Lo8IzMnVaM4uiC2pkA1TxPEiAMSqnmx9gW22tp5VtraBdYFpSXFGsXaBbp5mta1/3MTM/M0NLmqudI0lBKVNK1BdEUFlJGIYCQiWEiCSBwgG4zgkpUQBOLX/gcA "C (clang) – Try It Online") **Explanation:** The algorithm is a simple brute force search, checking whether the entire string is a repetition of a pattern of length n=1,2,3,…. The non-golfed implementation could be as follows: ``` void f(char* s) { // try pattern length=1,2,3… for (int n = 1; ; n++) { // loop over the string (until null terminator) to see if // it's a repetition of the pattern int p = n; for (; s[p]; p++) { if (s[p] != s[p%n]) { // not a repeating pattern break; } } if (!s[p]) { // we've reached the end of the string, so it seems to be // a repeating pattern… but it's not a valid solution // if the pattern is cut off in the middle ("cutoff case"): // e.g. abc-abc-abc-ab if (p % n == 0) { // print and return: we can simply output the *last* // occurrence of the pattern, because it is followed // by the null terminator puts(s + p - n); return; } } } } ``` The golfed version is doing this in a single loop: ``` f(char* s) { int n=1,p=1; while (s[p]|p%n) // more verbosely, s[p] || (p%n != 0) // - Loop while we haven't reached the null terminator. // - If we have, keep going if p is not a multiple of n // (i.e. in the cutoff case). { s[p]^s[p%n]?p=++n:++p; // more verbosely, // if (s[p] != s[p%n]) { n++; p = n; } else { p++; } // - If the pattern is not repeating, increment the pattern // length n and start over. This also applies in the cutoff // case; in that case s[p] is the null terminator. // - Otherwise increment p and continue checking the string. } puts(s+p-n); } ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes ``` {m/(.+?))>$0+$/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzpXX0NP215T007FQFtFv/Z/cWKlQp0eUDItv0ghJzMvtfh/jRoEclmp1UAQl4aGWg0yBgA "Perl 6 – Try It Online") Standard regex solution, finding a non-greedy match that repeats for the whole string [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` sJEƇḢḢ ``` A monadic Link accepting a list of characters which yields a list of characters. **[Try it online!](https://tio.run/##y0rNyan8/7/Yy/VY@8Mdi4Do////ShoaajXIWAkA "Jelly – Try It Online")** ### How? ``` sJEƇḢḢ - Link: list of characters, S J - range of length (S) = [1,2,3,...,length(s)] s - (S) split into chunks (of each of these sizes) Ƈ - filter keep those for which: E - all equal? Ḣ - head Ḣ - head ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 12 bytes ``` (.*?)\1*$ $1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0NPy14zxlBLhUsFyLOyBkEA "Retina – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` η.ΔKõQ ``` [Try it online](https://tio.run/##yy9OTMpM/f//3Ha9c1O8D28N/P/fSq0GggA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3loZX/z23XOzfl0Lpi78NbA//X6vyvUYNALiu1Ggji0tBQq0HGAA). Or alternatively: ``` «¦sk>£ ``` [Try it online](https://tio.run/##yy9OTMpM/f//0OpDy4qz7Q4t/v/fSq0GggA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVnl4wuEJ9koKj9omKSjZ/z@0@tCy4my7Q4v/6/yvUYNALiu1Ggji0tBQq0HGAA). **Explanation:** ``` η # Get the prefixes of the (implicit) input-string .Δ # Get the first prefix which is truthy for: K # Remove all occurrences of this substring in the (implicit) input-string õQ # And check if what remains is an empty string # (after which the found prefix is output implicitly as result) « # Append the (implicit) input-string with itself ¦ # Remove the first character sk # Get the (0-based) index of the input-string in the earlier created string > # Increase this by 1 to make it a 1-based index £ # And only leave that amount of leading characters from the (implicit) input-string # (after which this is output implicitly as result) ``` [Answer] # [Red](http://www.red-lang.org), 51 bytes ``` func[s][copy/part t: append copy s s find next t s] ``` [Try it online!](https://tio.run/##K0pN@R@UmhIdy5Vm9T@tNC85ujg2Ojm/oFK/ILGoRKHESiGxoCA1L0UBJKZQDIRpmUBeXmoFUFKhOPZ/QVFmXolCmoJSjRoEKnHBhazUaiAISUxDQ60GGSv9BwA "Red – Try It Online") A [Red](http://www.red-lang.org) port of [xnor's Python solution](https://codegolf.stackexchange.com/a/195415/75681). Don't forget to upvote his answer! ## Using `parse`: # [Red](http://www.red-lang.org), 71 bytes ``` func[s][n: 0 until[n: n + 1 parse s[copy t n skip any t]]copy/part s n] ``` [Try it online!](https://tio.run/##TYoxCoQwFER7TzGkCMIWaptjbBt@IZpAcPkb8mMh5O4xIojMDMw8Jrm1ft1qqfOm@p0XK2TZYMTOOfyuyvhgQpyTOIhd/vFAblC2EDFzG0QXHNojQ8BUYwqc4aGKvqW6Bxldbr9Y3@vyjqon "Red – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 46 bytes ``` lambda s:re.match(r"(.+?)\1*$",s)[1] import re ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqihVLzexJDlDo0hJQ0/bXjPGUEtFSadYM9owlisztyC/qEShKPV/QVFmXolGmoZSjRoEKmlqcsEFrdRqIAhFVENDrQYZAyX/AwA "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, 18 bytes ``` ~/(.+?)\1*$/ $_=$1 ``` [Try it online!](https://tio.run/##KypNqvxfUFpSrJCZpqCip2CnYPi/Tl9DT9teM8ZQS0WfSyXeVsXw//8aNQjkslKrgSAuDQ21GmT8L7@gJDM/r/i/bgEA "Ruby – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ¯ÒU²ÅbU ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=r9JVssViVQ&input=IigoJnwoKCZ8KCgmfCgoJnwi) ``` ¯ÒU²ÅbU :Implicit input of string U ¯ :Slice to 0-based index Ò : Bitwise increment U² : Duplicate U Å : Slice off the first character bU : First index of U ``` # Alternative/Original Since posted by Aztecco. ``` ã æ@¶îX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yDmQLbuWA&input=IigoJnwoKCZ8KCgmfCgoJnwi) ``` ã æ@¶îX :Implicit input of string U ã :Substrings æ :First element that returns true @ :When passed through the following function as X ¶ : Test U for equality with îX : X repeated to length of U ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ã f@¥îX ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4yBmQKXuWA&input=InwmfCZ8JnwmIgotZw) ``` U.ã(). // all substrings f( // filtered by.. function(X, Y, Z) { return U == U.î(X) }) // item repeated till input.length == input ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ġ≡ᵛ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/8jCR50LH26d/f9/tFKNGgQq6ShZqdVAEJCtoaFWg4yVYgE "Brachylog – Try It Online") ``` ġ Split the input into substrings of equal length ≡ᵛ such that each substring is the output. ``` [Answer] # [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) [0.62](https://github.com/ismael-miguel/SimpleTemplate/tree/4ae2b64de636f98004eb938b8f1cbae7a872b9cf), 184 bytes Yeah ... This is a very long one ... It highlights the weaknesses of that specific version (check below for version 0.72). ``` {@setI 0}{@setC""}{@setA argv.0}{@do}{@setO"{@setc A.",I,"}"}{@callimplode intoO O}{@evalO}{@setC C,c}{@callimplode intoC C}{@incI}{@callstr_replace intoR C,"",A}{@untilR is""}{@echoC} ``` This is a huge mess, here's the ungolfed one: ``` {@set index 0} {@set chars ""} {@set arg argv.0} {@do} {@set code "{@set char arg.", index, "}"} {@call implode into code code} {@eval code} {@set chars chars, char} {@call implode into chars chars} {@inc by 1 index} {@call str_replace into result chars, "", arg} {@until result is equal to ""} {@echo chars} ``` Yes, those 5 lines inside the `{@do}` only do 2 things: 1. Get the character at the position of the `index` value. 2. Add the character into the variable `chars`, as a string. You can test the golfed and ungolfed versions on <http://sandbox.onlinephpfunctions.com/code/7f2065a193d2bd0920cc3a4523e4b0ebf7a72644> --- --- **Version 0.72**, 112 bytes This non-competitive version uses new features I've developed today, to allow me to do more with the language. First, here's the code: ``` {@setX}{@setC""}{@do}{@setC"#{C}#{argv.0.[X]}"}{@incX}{@callstr_replace intoR C,"",argv.0}{@untilR is""}{@echoC} ``` It looks like a mess! Lets clear it up: ``` {@set index 0} {@set chars ""} {@do} {@set chars "#{chars}#{argv.0.[index]}"} {@// NEW IN 0.72} {@inc by 1 index} {@call str_replace into result chars, "", argv.0} {@until result is equal to ""} {@echo chars} ``` Most of this has been explained in other answers, so, I will focus on this line: `{@set chars "#{chars}#{argv.0.[index]}"}`. This showcases 2 new features in the language and a bugfix: * Now you can get a value from an array based on the value of a variable * Now there's string interpolation, where `"#{chars}"` will interpret the `chars` variable and the result is a single string. Before, you would have to do `{@set chars chars, value2, ...}`, which makes an array instead of a string. * Previously, you could only access 1 member of an array/string. Currently, you can access as many deep in as you want. This meant that `{@echo argv.0.0}` would need to be written as `{@set arg argv.0}{@echo arg.0}`. The line `{@set chars "#{chars}#{argv.0.[index]}"}` replaces the previously mentioned lines inside the `{@do}`. You can try this on <http://sandbox.onlinephpfunctions.com/code/e2ab3d10c8224ee475cf4d4ca94fef7896ae2764> [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 10 bytes ``` ..2*1>\?)< ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0/PSMvQLsZe0@b/fyu1GggCAA "GolfScript – Try It Online") ## Explanation ``` . # Make a copy of the initial input .2* # Make another copy that has a double length 1> # Trunctuate the copy to without the first item \ # Swap the copy to below ? # Find the index of the input ) # Increment the index < # Slice the input so that the whole section emerges ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` ↑¹€tD¹ ``` [Try it online!](https://tio.run/##yygtzv7//1HbxEM7HzWtKXE5tPP///9KGhpqNchYCQA "Husk – Try It Online") Yet another port of [xnor's answer](https://codegolf.stackexchange.com/a/195415). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` dḢ?ḟ›Ẏ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJk4biiP+G4n+KAuuG6jiIsIiIsIlwiYWJjYWJjYWJjXCIiXQ==) Yet another port of xnor's answer [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` …θ§⌕A⁺θθθ¹ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO5Mjkn1Tkjv0CjUEfBscQzLyW1QsMtMy/FMSdHIyCntBgkXqgJwYaamprW//9bqdVA0H/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Adaptation of @xnor's answer. Explanation: ``` ⁺θθ Duplicate the input ⌕A θ Find all indices of the input § ¹ Skip the first index, which is always zero …θ Truncate the input to that length Implicitly print ``` [Answer] # [Wren](https://github.com/munificent/wren), 37 bytes Basically a port. ``` Fn.new{|a|a[0..(a+a).indexOf(a,1)-1]} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkFaal6xgq/DfLU8vL7W8uiaxJjHaQE9PI1E7UVMvMy8ltcI/TSNRx1BT1zC29n9wZXFJaq5eQVFmXokGSKtecmJOjoZSjRoEKmlqcuFSY6VWA0H4FGloqNUgY6Da/wA "Wren – Try It Online") [Answer] # R, 33 ~~36~~ bytes ``` sub("(.+?)\\1*$","\\1",scan(,"")) ``` [Try it online](https://tio.run/##K/qfpmCjq5BWmpdckpmfp1GsWV2cnJiHIqanp6dZ/L@4NElDSUNP214zJsZQS0VJRwlIK@mAVGvoKClpav6v5UrTUK9Rg0B1TS5lheKM/NKcFIX0zLJUhRo1BS6QAiu1GgjCUAEUA6vQ0FCrQcYYCkGC/wE) ]
[Question] [ We call a ***parens group*** the open paren `(`, its matching close paren `)` and everything inside them. A parens group or string is called ***parenthesly balanced*** if it contains either nothing or only 2 parenthesly balanced parens groups. For example: ``` The string "(()())()" is parenthesly balanced ( )() Because it contains exactly 2 parenthesly balanced parens groups ()() The left one is parenthesly balanced because it contains 2 parenthesly balanced parens groups (balanced because they are empty). The right one is parenthesly balanced because it contains nothing. ``` Likewise: ``` The string "(()(()))()" is not parenthesly balanced ( )() Because it contains a parens group that is not parenthesly balanced: the left one ()( ) The left one is not balanced because it contains a parens group that is not balanced: the right one () The right one is not balanced because it only contains one balanced group. ``` So, a parenthesly balanced string or parens group should either: * Contain nothing at all. * Or contain only and exactly 2 parenthesly balanced parens groups. It should contain nothing else. ### Task: Your task is to write a function or program that checks if a given string is a parenthesly balanced one or not. ### Input: Input will be a string or list of characters or something similar. You can assume that the string will only consist of the characters `'('` and `')'`. You can also assume that each open paren `(` will have its matching close paren `)`, so don't worry about strings like `"((("` or `")("` or `"(())("`... **Note:** As mentioned by @DigitalTrauma in his comment bellow, it's ok to subtitute the `()` combo by other characters (such as `<>`, `[]`, ...), if it's causing additional work like escaping in some languages ### Output: Anything to signal whether the string is parenthesly balanced or not (true or false, 1 or 0, ...). Please include in your answer what your function/program is expected to yield. ### Examples: ``` "" => True "()()" => True "()(()())" => True "(()(()(()())))(()())" => True "(((((((()())())())())())())())()" => True "()" => False "()()()" => False "(())()" => False "()(()(())())" => False "(()())(((((()())()))())())" => False "()(()()()())" => False "()(()(()())()())" => False ``` The last two examples really made a difference! Best of luck! [Answer] # [Japt](https://github.com/ETHproductions/japt) v2, 20 bytes ``` V="()"V¥iU1 eViV²1 V ``` [Test it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=Vj0iKCkiVqVpVTEgZVZpVrIxIFY=&input=IigpKCgpKCgpKCgoKSgpKCkoKSkoKCgpKCkpKCkpKSkpIg==) Everyone misunderstood the challenge at first and though that each pair of parentheses had to contain an *even* number of sub-pairs, when in fact the challenge actually asks for *0 or 2* sub-pairs. So here's my revised answer, using the same technique as before. We can still solve the challenge with recursive replacement. The thing is, instead of just removing all occurrences of `()()`, we need to make sure that there's nothing else in the same wrapper besides the `()()` (in other words, no `()()()()` or anything like that). We can do this by recursively replacing `(()())` with `()`. The new problem is that the input itself does not have one pair of outer parentheses (as that would make it not a parenthesly balanced string), forcing us to wrap it in an extra pair to fully reduce it. Finally, the end result for balanced strings is now `()` instead of the empty string, so we check for equality rather than just taking logical NOT of the output. [Answer] # sed 4.2.2, 30 ``` : s/(()())/()/ t /^()()$\|^$/q1 ``` [Try it online](https://tio.run/##bY3BCsIwDIbveYowCmsOErzqwReRwWYDLYxW3cDL3r2ShqkHQ0jy5ydfpnGJ9RXTLPiUMeCcspwxFJBbLNg51R1uyOW@8iKBp5S14yFjX0@wsPfkidgTwwo8qHLXbXD8ONbeMO4CoWSpoKaWdgLepibou7RQ8S/BCG3aF0b5MJX1g6Ddshf25g0). This returns a shell exit code of 1 for True and 0 for False. ``` : # label s/(()())/()/ # replace "(()())" with "()" t # jump back to label if above replacement matched /^()()$\|^$/q1 # exit code 1 if remaining buffer is exactly "()()" or empty # otherwise exit with code 0 ``` [Answer] # [Perl 5](https://www.perl.org/) -lp, ~~24~~ 22 bytes ``` $_=/^((<(?1)?>){2})?$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lY/TkPDRsPeUNPeTrPaqFbTXkX//38bOxs7LiABooEMCAvMsUMIQgCIgw1xQUwAs2ACEFPgZoLMQjLCDiYFscIGiQNVAiT@5ReUZObnFf/XzSkAAA "Perl 5 – Try It Online") Link includes test cases. Edit: Saved 2 bytes thanks to @JoKing. Explanation: Just a recursive regex. The outer capturing group represents a balanced string as a `<` followed by an optional balanced string followed by a `>`, twice. Note that most of the other answers are able to use `()`s but this costs an extra two bytes: ``` $_=/^((\((?1)?\)){2})?$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lY/TkMjRkPD3lDTPkZTs9qoVtNeRf//fw1NDU0uIAGigQwIC8zRRAhCAIiDDXFBTACzYAIQU@BmgsxCMkITJgWxAiz8L7@gJDM/r/i/bk4BAA "Perl 5 – Try It Online") Link includes test cases. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 28 bytes ``` Ẹ|~c["(",A,")(",B,")"]∧A;B↰ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuHTV1ydFKGko6jjpKmkDKCUgpxT7qWO5o7fSobcPDrRP@/1fS0NSAIE1NMPE/CgA "Brachylog – Try It Online") # Explanation ``` -- The string perfectly balanced iff Ẹ -- the string is empty | -- or ~c["(",A,")(",B,")"] -- the string can be written id the format of "($A)($B)" ∧ -- where A;B ᵐ -- both A and B ↰ -- are perfectly balanced ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~21~~, 20 bytes ``` é(Á)òÓ(“()()…)òø^()$ ``` [Try it online!](https://tio.run/##K/v///BKjcONmoc3HZ6scWiyhqaG5qFWEG9HnIamyv//GlAAFMeK/usW/zcyAAA "V – Try It Online") or [Verify all test cases!](https://tio.run/##K/v//3Df4ZUahxs1uQ5vOtyroaGpoampr6F5eJMHkL9DQ1OFK@vwpv//uUASIAKsgEsDwgJzNBGCEADiYENcCBOgGjQhpsJkIUbCLQAZjGQelPqvW/zfyAAA) ``` é( " Insert '(' at the beginning of the line Á) " Append ')' at the end ò ò " Recursively... Ó " Remove... ( " '(' “ … " (Limit the part that is removed to this section of the match) ()() " '()()' ) " ')' " (effectively, this replaces '(()())' with '()', but it's one byte shorter than the straightforward approach ø " Count... ^()$ " Lines containing exactly '()' and nothing more ``` Hexdump: ``` 00000000: e928 c129 f2d3 2893 2829 2829 8529 f2f8 .(.)..(.()().).. 00000010: 5e28 2924 ^()$ ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine, 48 bytes ``` A0 00 84 FD A2 00 B1 FB F0 0E C8 C9 29 18 F0 06 8A 48 E6 FD 90 EE B0 0A E0 01 90 06 E0 02 38 D0 01 18 A5 FD F0 09 C6 FD 68 AA E8 B0 F5 90 D7 60 ``` Expects a pointer to a string in `$fb`/`$fc` which is expected to only contain `(` and `)`. Clears C (Carry) flag if the string is "paranthesely balanced", sets it otherwise (which is a typical idiom on the 6502, set carry "on error"). Does nothing sensible on invalid input. Although the algorithm is recursive, it doesn't call itself (which would need more bytes **and** make the code position dependent) but instead maintains a recursion depth itself and uses "simple" branching. ### Commented disassembly ``` ; function to determine a string is "paranthesly balanced" ; ; input: ; $fb/$fc: address of the string ; output: ; C flag set if not balanced ; clobbers: ; $fd: recursion depth ; A,X,Y .isparbal: A0 00 LDY #$00 ; string index 84 FD STY $FD ; and recursion depth .isparbal_r: A2 00 LDX #$00 ; set counter for parantheses pairs .next: B1 FB LDA ($FB),Y ; load next character F0 0E BEQ .done ; end of string -> to final checks C8 INY ; increment string index C9 29 CMP #$29 ; compare with ')' 18 CLC ; and reset carry F0 06 BEQ .cont ; if ')' do checks and unwind stack 8A TXA ; save counter ... 48 PHA ; ... on stack E6 FD INC $FD ; increment recursion depth 90 EE BCC .isparbal_r ; and recurse .cont: B0 0A BCS .unwind ; on previous error, unwind directly .done: E0 01 CPX #$01 ; less than one parantheses pair 90 06 BCC .unwind ; -> ok and unwind E0 02 CPX #$02 ; test for 2 parantheses pairs 38 SEC ; set error flag D0 01 BNE .unwind ; if not 2 -> is error and unwind 18 CLC ; clear error flag .unwind: A5 FD LDA $FD ; check recursion depth F0 09 BEQ .exit ; 0 -> we're done C6 FD DEC $FD ; otherwise decrement 68 PLA ; get "pair counter" ... AA TAX ; ... from stack E8 INX ; and increment B0 F5 BCS .unwind ; continue unwinding on error 90 D7 BCC .next ; otherwise continue reading string .exit: 60 RTS ``` --- ### Example C64 assembler program using the routine: **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22parbal.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACp2qAIIB6rqeigCKIAIDcIqeiF+6kIhfwgqgiwBqndoAjQBKnioAhMHqvKhvuF/IT9oACEzIT+IELx8PuFAil/ySCwDskN8BDJFNDrpf7w59AGpf7F+/DfeKTTsdEpf5HRpQIgFuemz/AKpNOx0QmAkdGlAljJFPAgyQ3wCaT+kfzIhP7QsakApP6R/Hik07HRKX+R0ebMWGDG/rCaoACE/aIAsfvwDsjJKRjwBopI5v2Q7rAK4AGQBuACONABGKX98AnG/Wiq6LD1kNdgPiAAVFJVRQBGQUxTRQA=%22%7D,%22vice%22:%7B%22-autostart%22:%22parbal.prg%22%7D%7D)** [![screenshot](https://i.stack.imgur.com/2GAmX.png)](https://i.stack.imgur.com/2GAmX.png) **Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:** ``` .import isparbal ; link with routine above .segment "BHDR" ; BASIC header .word $0801 ; load address .word $080b ; pointer next BASIC line .word 2018 ; line number .byte $9e ; BASIC token "SYS" .byte "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes .bss linebuf: .res 256 .data prompt: .byte "> ", $0 truestr: .byte "true", $0 falsestr: .byte "false", $0 .code inputloop: lda #<prompt ; display prompt ldy #>prompt jsr $ab1e lda #<linebuf ; read string into buffer ldy #>linebuf ldx #0 ; effectively 256 jsr readline lda #<linebuf ; address of string to $fb/fc sta $fb lda #>linebuf sta $fc jsr isparbal ; call function bcs isfalse lda #<truestr ldy #>truestr bne printresult isfalse: lda #<falsestr ldy #>falsestr printresult: jmp $ab1e ; output true/false and exit ; read a line of input from keyboard, terminate it with 0 ; expects pointer to input buffer in A/Y, buffer length in X .proc readline dex stx $fb sta $fc sty $fd ldy #$0 sty $cc ; enable cursor blinking sty $fe ; temporary for loop variable getkey: jsr $f142 ; get character from keyboard beq getkey sta $2 ; save to temporary and #$7f cmp #$20 ; check for control character bcs checkout ; no -> check buffer size cmp #$d ; was it enter/return? beq prepout ; -> normal flow cmp #$14 ; was it backspace/delete? bne getkey ; if not, get next char lda $fe ; check current index beq getkey ; zero -> backspace not possible bne prepout ; skip checking buffer size for bs checkout: lda $fe ; buffer index cmp $fb ; check against buffer size beq getkey ; if it would overflow, loop again prepout: sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row output: lda $2 ; load character jsr $e716 ; and output ldx $cf ; check cursor phase beq store ; invisible -> to store ldy $d3 ; get current screen column lda ($d1),y ; and show ora #$80 ; cursor in sta ($d1),y ; current row lda $2 ; load character store: cli ; enable interrupts cmp #$14 ; was it backspace/delete? beq backspace ; to backspace handling code cmp #$d ; was it enter/return? beq done ; then we're done. ldy $fe ; load buffer index sta ($fc),y ; store character in buffer iny ; advance buffer index sty $fe bne getkey ; not zero -> ok done: lda #$0 ; terminate string in buffer with zero ldy $fe ; get buffer index sta ($fc),y ; store terminator in buffer sei ; no interrupts ldy $d3 ; get current screen column lda ($d1),y ; and clear and #$7f ; cursor in sta ($d1),y ; current row inc $cc ; disable cursor blinking cli ; enable interrupts rts ; return backspace: dec $fe ; decrement buffer index bcs getkey ; and get next key .endproc ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 113 bytes ``` p(a,r,e,n)char*a;{if(*a-40)return 1;for(r=1,e=0;e<2;r&=e++||*a==40)for(r*=n=p(++a);n+=*a++-40?~0:1;);r=r&&*a-40;} ``` [Try it online!](https://tio.run/##jZDLbsIwEEXX5SssI6IZ25ES2lVdw0@wzMYKTptFXWsIG16/HpyEPpCAZjS7OXPHx2X6XpZtG8AqUk55LD8sCav3dQXCpi8Zkmu25Fmuqy8CMrlyJtPuba4pMU7Kw0FYYyLXj4XxJoCUFrWXRlgpY8TylL3mGjUZSpI@VB/b6dpVtXdsBTsMVPumAl7wWfo83xScnRZsti48VzsVIoB68mlrD7ifPK2Ac/ZPYY8BAvJRWEfeRy/YwPUo3lr5xobqxreaRyxsm020iFbDfT7W5iH688xR2EXmrvivdCf7xwivlq6@EB6kHdsz "C (gcc) – Try It Online") # Explanation ``` p(a,r,e,n)char*a;{ // function and variable declaration if(*a-40)return 1; // string does not start with '(', thus is empty for(r=1,e=0;e<2; // r: return value, e: group id (look for exactly two groups) r&=e++||*a==40) // after the first group, a second shall follow for(r*=n=p(++a); // check that the group is itself balanced n+=*a++-40?~0:1;); // skip group r=r&&*a-40;} // additionally, after those two groups there shall follow none ``` [Try it online!](https://tio.run/##jZHdTuMwEIWvyVOMgih24oqW3atms/sSXPZmcCaNVWNHtkMpf69enJ9lqQRsR76J5psz50zkfCPl4dAyFE6QMFw26DIsngDg6grqzsigrAE0FdyjU3irCSqSGh32jQRUzTKc/1xwR6FzBpbFMOmDU2YDlSUPxob4jS7AToUGLtmlgNB0HpQHumvDPoHaOubKpaByUdCv66gxqLgVTLL3qDsSQCvYONu1oCpg2tptPwn0gDLoPYSdHdueJ@BmJeX583OGZRntwSSJdSAX1xPUyvkw8gIQPEkbU/oGtY6qWttdAqOxrDRly/IceTGKyIbkNopgGJQmSzFQ8KRruEWNRlIV501eZpjn8UB/XherZREV@utsVTtORZ@lm82GExYvMFXvs6pUf@HoZi/eXVtPH1L2yx0dWY7HNnQ4r6hWhuCGPfI2/ohQs3SdXsx/XPt1Cq@/4aJam1Q8ijYCvEjuUBnGn5KzG5am8J/iA8Y44@lJWE9@jU7YyA0o/2zkLzZW3/7spRFru@Bjiphq3J@emuZb9N3mSdgU5svg/0L3YT8k4kdDRydk36i9HN4A "C (gcc) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~26~~ 25 bytes ``` oo~`tnw52B5LZttnb<]XB10X- ``` [Try it online!](https://tio.run/##y00syfmf8D8/vy6hJK/c1MjJ1CeqpCQvySY2wsnQIEL3v5oLl7qChrqhb56Bnb16aZ56Rqx6UmJOYl5yaoqmekYGl0vIf3V1LnUNTQ1NEAUFQB5WBFEJkgYrAetAEYcoVAcA "MATL – Try It Online") Thanks to @ETHProductions' answer for the "replace (()()) with ()" idea, and @JungHwan Min's question comment for the idea of seeing the brackets as binary digits. Output is an empty array for truthy, a positive number for falsey - which I think is allowed by OP's comment: "Could be categories. i.e. truthy values to signal truthiness and falsy values to signal otherwise." If it's not, we can add `n` at the end for +1 byte, to have 0 as truthy output and 1 as falsey output. ### With comments: ``` o % Convert the parantheses to their ASCII codes % 40 for '(', 41 for ')' o % Parity - 1 for odd, 0 for even ~ % Not - change 0 to 1 and vice versa, so '(' is now 1 and ')' 0 % Input char array is now a binary array B ` % Do-while loop tn % Get the length of the array w % Bring the array B back on top 52B % Push the binary value of 52 on stack % [1 1 0 1 0 0] (equivalent to '(()())') 5L % Push the constant [1 0] for '()' Zt % Replace the sequence [1 1 0 1 0 0] in array B % with [1 0] tn % Get the length of the array after replacement b< % Has it decreased? If so, continue loop ] % end loop % Final value for balanced input will be % either [1 0 1 0] for the remaining outer '()()' % or an empty array [] for empty '' input XB % Convert the final binary array back to decimal 10X- % Set difference, remove 10 from that result % Result is [] empty array for balanced input, otherwise % some decimal number ≠ 10 for unbalanced input ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 78 71 bytes ``` f=s=>{var r=s.Replace("(()())","()");return r==s?s==""|s=="()()":f(r);} ``` [Try it online!](https://tio.run/##rZJBS8MwFMfv/RSPnBKY3d2aeRB2UhAVPIiHmKUjEBPJSwdj9rPXthlYUdtm7M8jp8cvv5cXiRfSedVIIxDhPjtk0AaDCFqCV2LjrNnD4x6Des/XlZVXGLy22wW8OWdW0JQc@eqwEx48x/xBfRghFSWUMsoYWRDKCCu8CpW3bQfHa@SckM/u7FrIZUk9K@oGjimyocHO6Q3cCW1pvPblFYTfIut7omuXo9@Ns@iMyp@9DupWW0VLSghjBUxmuYQnX6lZxN57kppIjO81Sk0iRmRPZf/S04gxHemvivS0qefspiWuhcH5q5nGpiEH053Psq/xladadrzhhtjvC06wZPSclt@fcgT7A1lndfMF "C# (.NET Core) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~82~~ 59 bytes ``` all(`elem`[0,2]).foldl(#)[0] b#'('=0:b (x:y:z)#_=y+1:z++[x] ``` [Try it online!](https://tio.run/##bU/bCsIwDH3vVwQn2DKV6WOhX@FjLdppq8NsFqt4@XjratGpGELIySHnJFvtdwYxWAHzoBHp0qCpl7IYThUb2z2ukWZMFoqU2YAORMFLQi/8ym8sW4hrPuG3PJcXFfRh40GAJAC93jBWyih7dxG8UILPCfthUsTJv3ypdfq00/xxSzudY3T60GZffLoiXaJIraumfcWdjrPjAfpwarBqjIcx1NqB3@7PqbMtF98m4b6yqDc@jFbOPQA "Haskell – Try It Online") I assume it can be golfed much further since it's my first time golfing in haskell, so any tricks or comments are more than welcome. **EDIT -** Thanks @nimi for saving **23 bytes** (more than 28% of the original submission :) [Answer] # JavaScript (ES6), 63 bytes Takes input as an array of characters. Returns **false** for parenthesly balanced, **true** for not parenthesly balanced. ``` a=>[...a,k=0].some(c=>c<')'?!(a[k]=-~a[k++]):a[k]=~5>>a[k--]&1) ``` [Try it online!](https://tio.run/##pZJBD4IgGIbv/QrjkHwzsA5dWtgPcRwYaStNmlhH/zqJHrINw9W3bwMO7/N@vHAVT6Flfbk3pFKnzOTMCJaklFKxLtiGU61uGZYskYcQwuMSi7TgjLTdEkUc9v2x3SVJtyGEr7ZgpKq0KjNaqjPOsUUhFHiKAwRxHOSi1NnCAcCAAf0JsIxpiBcwEHoIuGB@wFBW6Go0CQD3hdCsSJv6MZnoV4ZPPwz9j3/fk4/i97ficaTwQZvlD/hn//d3cDNGevMC "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array of characters; we are going to reuse it to [ // store the number of parenthesis groups at each depth ...a, // append all characters k = 0 // initialize k = current depth to 0 and append a value that will ] // be treated as a final closing parenthesis for the root level .some(c => // for each character c in this array: c < ')' ? // if c is an opening parenthesis: !( // increment the number of groups at the current depth a[k] = -~a[k++] // increment the depth ) // yield false : // else: a[k] = ~5 // make sure that the current depth contains either 0 or 2 >> a[k--] // groups, by shifting the 1-complement of 5 (101 in binary) & 1 // and testing the least significant bit // it resets the number of groups to 0 if the bit is not set // otherwise, it forces some() to return true // decrement the depth ) // end of some() ``` --- # Recursive, 54 bytes Using recursive replacements (like in [ETHproductions' Japt answer](https://codegolf.stackexchange.com/a/169770/58563)) is however significantly shorter. Takes input as a string. Returns **1** for parenthesly balanced, **0** for not parenthesly balanced. ``` f=s=>s==(s=s.split`(()())`.join`()`)?!s|s=='()()':f(s) ``` [Try it online!](https://tio.run/##nZHNDoIwEITvPgXuhd2DoFeT6quUIDUlhBKXePLdK6Um/rUobObU7LczmdbFteDyort@05pTZZUYxOLAQiALzrhrdC8RCYlkVhvdSiRJxzXfhpXUvad7hUy2NC2bpsoac0aFAMmPIUryPNmtPjh3EZZxY0iYy3lwZCl0I8r5cfshQYij79TwT0vbUEuTbIzz2Zb4jYo2HPdz0GtT9HZl0o9wtt/zM8Psg7N3 "JavaScript (Node.js) – Try It Online") --- # Recursive, 46 bytes This one throws a recursion error for not parenthesly balanced: ``` f=s=>!s|s=='()()'||f(s.split`(()())`.join`()`) ``` [Try it online!](https://tio.run/##lZFBDoIwEEX3nGLshpmFENemngWCoBBCCdOYGOHsSIEgYlVoJl207/fPn2bhLeSoSku9L9Q5bttEsjztuGYpXSQkt64TZI/LPNUBmhMKvEylRYAUUKtj1iCBQZ7gAbq6d3ukClZ57OXqgp2W6AgNRKGOrhjT4t5NwjR3DdE4jnkMhYA/i8D34TDSpiOxhe4jiHX0gPcKsikX9LAMZSsx0vP4NPUlVmQ2s5rF/in6EAw9bHLo6@u4LA6Gns@A3uR2B8L1Dq/vsIsmQfsE "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://perl6.org), ~~43 41~~ 37 bytes ``` {my rule f{\([<&f>**2]?\)};?/^<&f>**2$|^$/} ``` [Test it](https://tio.run/##lZFNb4JAEIbv@ysmG2p2rWJiGg9SsD20px5NL7UmBIeEdMUNC6aG8st66x@jy4cFG6K4mcN@vM@8M7MSIzHLE4Wwn5meRcj2AANvt0Gw81Tvo0Qg@OmKvd0PfGc4nL4vVjyzFpN1fTa@1sYky7X0IUYVgw0iCFH9fJtPr48vFilSL/WDRaRwQ7gtVdrH30U1MXaAwfwDD8wIQpnEfATzvSsSZAZ@SvRi3HDgkBKAQEFRWyP8U4yAVpem1B2Z/jZm9GZ8N1WUg@00OkqynFLouTS5jBIklHHG6bVEAV2mGqJCSoqfo1tEtQplV9COqmjvzp9doerWe2Et5NS9p0sZF0d24lLo2xPgnQn@u3B2jUvzKeexI/IL "Perl 6 – Try It Online") ``` {(my$f)=/\([<$f>**2]?\)/;?/^[<$f>**2]?$/} ``` [Test it](https://tio.run/##lZHPToNAEMbv@xSTDZqd2kLSmB6KUD3oyWPjxWpC6JAQF7phoZE0fTJvvhjypwo1pKWTOc1@v/lmZhUlclZkmmA7M32bsSiHa3@zJnCKnYhyI0DHWonXOyNwR6Pp22KFlr2w3tuCYe2LErpPSafggAxj0t9f5uPLw7PNqsbL8sFmSnox3NSq0iXYJAdi4oKA@QflwghjlaU4hvnWkxkJgz4V@SmtERB2DCDUUE3WCv8UY@BN0VTlPmYQpYJfTW6nmiM4bqvjbF9wDgOjJJdJRowLFMgvJSroPNUSDVJTeIruEE1Uyr7kPVPxwZs/eVIfVh@EdZBj94EudZ492ZFLpe9eAHsb/HdBcYlL@ymnsV/kBw "Perl 6 – Try It Online") ``` {$!=/\([<$!>**2]?\)/;?/^[<$!>**2]?$/} ``` [Test it](https://tio.run/##lZHPTsJAEMbv@xTDZjU7CG1CDAdqix705JF4EU2aMiSNpWy6LZEQnsybL1b7B91iGiiTOc1@v/lmZhUl0TjPNMFmbAUOY6stXAfrBYGb70TPtefy9U70vH5/9Dado@1M7XdTEPY@L4D7lHQKLkRhTPr7y3p8eXh2WNl0Vjw4TEV@DDeVqnBYrpMDMfRAwuSDtlKEscpSHMBk40cZSUGfioKUFggIOwYQaiinMsI/xQB4XbRUsYu1XKWSXw1vR5ojuJ7RcbbPOYeOUZCzJCPGJUrklxIldJ4yRI1UFJ6iG0QdpbItectUvPPmT36kD6t3whrIsXtHlyrPnuzIpdQ3L4CtDf67oLzExXzKaewX@QE "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter $_ $! = # store regex into $! (no need to declare it) / \( [ <$!> ** 2 # recurse into regex twice ]? # optionally \) /; ? # boolify (causes it to be run against $_) / ^ # beginning of string <$!> ** 2 # match using regex twice $ # end of string | # or ^ $ # empty string / } ``` [Answer] # [R](https://www.r-project.org/), 71 bytes ``` f=function(s,r=sub('(()())','()',s,f=T))'if'(r==s,s==''|s=='()()',f(r)) ``` [Try it online!](https://tio.run/##jZJLCsIwEIb3OcVQF5mBeAMjuNCVK60XsBjIppVMu1LPHptU1JS@hmEg8P3/PIjz3mjTlEVtqxJZOc3NFSUiIZFUEtvCyui8fVkj0WnNirWW8hlqwKQy6Ih8feOaYbMGUaAAyDIFM7HSW8hPl32gg9O0okfHCccVCd3hUUGDypTuIlBDmal0krk9A33YHc/fNaclKf7puNw95vhp@u6B/d@WUvGAO@FS99/RO8kETkKYyiGDLSH@I3q0FndnyxoBDDIBiZcQ/g0 "R – Try It Online") * porting of recursive Japt solution of @ETHproductions * -2 bytes thanks to @JayCe --- Another - longer - solution but interesting for the different approach # [R](https://www.r-project.org/), 85 bytes ``` g=gsub;!sum(eval(parse(t=g('\\)\\(',')-(',g('\\)','-1)',g('\\(','(2+',scan(,''))))))) ``` [Try it online!](https://tio.run/##tZM9T8MwEIZ3/4rDDLkTSSQYgSAxwMTEx5bFuE6IlDqRz2Gp@ttDnFRAqtJm4XSyZN/zvvZZtuv7Miu5e785426N5lPV2CrHBn1WYpTnlOcYxRElwzgtDLPkknazUMOriyhmrSzGUURT9BIJhySSQmjlUTrTcWVL8B8GWK0N6GZlQBXeOHCmrZUO1dGGwDfgDXtQdQ1asWG4zq0kEcpwm0DRWe2rxmKapsQisBzWhUYBIGUMJ@I8u4PX57eHQIdjHlfs0VNf8SJ6wkcFHVTO6SkCdShlPD/JqT4D/Xj/9PLd5nHJHN/tuNx9zL@vZt89sL@7pbn4gDvhUvefS58kR3ASomgcMlR2fHNMm8GidZX1uAH4l98BsCWxFaL/Ag "R – Try It Online") **Explanation :** Take the input string and replaces : ``` '(' with '(2+' ')' with '-1)' ')(' with ')-(' ``` then evaluates the resulting expression. If it's equal to zero is balanced, otherwise is not. The use of `sum` is only necessary to handle the empty string case, because its evaluation returns `NULL`. e.g. ``` ()(()()) => (2+-1)-(2+(2+-1)-(2+-1)-1) = 0 (()()) => (2+(2+-1)-(2+-1)-1) = 1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 65 bytes ``` #=={}||{1,1}==(#//.{a___,"(",i:1...,")",b___}/;1!=+i<3:>{a,1,b})& ``` [Try it online!](https://tio.run/##bY1BCoMwEEX3OUWagCR0mhC600aEXqD7UiSKYhZ2YbOLOXtamwoKHQbm/5nh/dG4oRuNs62JvWaRau3DPHsFKmjNqJTCm7qugTACNldCCCCcQPPZBVmogz7ayzkvvQEFTeBZ5AW6Tfbp7hSfStxX18FMpnXd9KroI8Oywh4hRAggwjjjv7nIpJP5er7bp1r8v06clcpW1i4h/a4pC31D5Jtryk3ZCIX4Bg "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~16~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` …(ÿ)…(()∞„()©:®Q ``` [Port of *@ETHproductions*'s Japt answer](https://codegolf.stackexchange.com/a/169770/52210) to fix the test case `()(()()(()())(()()))`. -2 bytes thanks to *@Adnan*. Based on [this comment of OP](https://codegolf.stackexchange.com/questions/169767/test-if-a-string-is-parenthesly-balanced/169812#comment409981_169767) I now use `()` as truthy value, and anything else as falsey. If both values need to be consistent instead of just one, it would be the old 16-bytes answer instead ([`…(ÿ)…(()∞„()©:®Q`](https://tio.run/##MzBNTDJM/W9o4ubpYq@k8KhtkoKS/f9HDcs0Du/XBFEamo865j1qmKeheWil1aF1gf91/mtoamhyAQkQDWRAWGCOJkIQAkAcbIiLC2IE2CSICMwYuKEgw5DM0IRJQexAWA6HSJYjeFCHcaE4B@5euBDcWGRNAA)), returning `0` for truthy and `1` for falsey test cases. [Try it online](https://tio.run/##MzBNTDJM/f//UcMyjcP7NUGUhuajjnmPGuZpaFr9d7EHMwIzlRSikxJzEvOSU1NilXQOr1ZSUIjOyy9RQBL8r6EJ1AsloKQmAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o4ubpYq@k8KhtkoKS/f9HDcs0Du/XBFEamo865j1qmKehafXfxR7MCMxUUohOSsxJzEtOTYlV0jm8WklBITovv0QBSfC/hqaGJheQANFABoQF5mgiBCEAxMGGuLggRoBNgojAjIEbCjIMyQxNmBTEDoTlcIhkOYIHdRgXinPg7oULwY1F1gQA). **Explanation** ``` …(ÿ) # Take the input (implicitly) and surround it with "(" and ")" : # Infinite replacement of: …(()∞ # "(()())" ("(()" mirrored) „() # with "()" # After the infinite replacement: return the result # ("()" for truthy; falsey otherwise) ``` --- (Old 18-bytes answer which failed for test case `()(()()(()())(()()))`..): ``` ΔD„()∞©6∍å_i®õ.:]Ā ``` [Try it online](https://tio.run/##MzBNTDJM/f//3BSXRw3zNDQfdcw7tNLsUUfv4aXxmYfWHd6qZxV7pOH/fw0Q0NTQBCMNTQhbEy4EAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W9o6ubpYq@k8KhtkoKSvdL/c1NcHjXM09B81DHv0EqzRx29h5fGZx5ad3irnlVt7ZGG/0p6YTr/NTQ1NLmABIgGMiAsMEcTIQgBIA42xMUFMQJsEkQEZgzcUJBhSGZowqQgdiAsh0MkyxE8qMO4UJwDdy9cCG4ssiYA). [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 27 bytes ``` 3>≢'<<><>>'⎕r'<>'⍣≡1⌽'><',⎕ ``` [Try it online!](https://tio.run/##jZDBagIxEIbv@xRzm0sFxZuEvEtwExsMu3Y3CqV4E63YlV569GD7DF4W@jLzIttZY9HCdtdhIEPm@//MRM1cL35WLp30xk7luR1XtP@wKa3f@xG9bkw1lLT9RCGkkBK5l6Hgs/ii7XFAb98oBT7wdcVwZVj2cpegOC2BigPMcw3@UYN@mtuFcjrxEJsETJqB17m3ySTytSkLWJ9xaagoR5hOkXarGI2yjs1L7mfLCBE6wsMgwno0vIcKO7RTATuTsklxoULU3abEy4vYNX0/TN9KBir4dnud8989f71q5HYD@Udz4yVFh9f1u5pJpn4A "APL (Dyalog Classic) – Try It Online") [Answer] # [Prolog](http://www.swi-prolog.org), 46 bytes ``` a-->p,p. a-->[]. p-->[l],a,[r]. f(X):-a(X,[]). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P1FX165Ap0CPC8SIjtXjKgDRObE6iTrRRUBumkaEppVuokaETnSspt7//2ka0Tk6qLAIjIkmgcYAAA "Prolog (SWI) – Try It Online") or [Verify all test cases!](https://tio.run/##KyjKz8lP1y0uz/z/P1FX165Ap0CPC8SIjtXjKgDRObE6iTrRRUBumkaEppVuokaETnSspt7//6oKJUWlqUBhEJcLROfoFOkAMSoXKogsjCwBlwZDHMqRIUw5kSTYGFWFtMSc4lSoo9Cci@pkVI1ovkAyG903MNdjd2YRdq3IHs7BJ41qHkwZAA "Prolog (SWI) – Try It Online") Uses lists of `l` and `r` as input, e.g. `"()()"` is tested as `f([l,r,l,r]).`. The first three lines are the grammar of valid strings in Prolog's [Definite Clause Grammar](https://www-users.cs.umn.edu/~gini/prolog/dcg.html) syntax. `a(A,B).` returns `true` when `A` is a list which follows the grammar and `B` is empty. Thus the main function `f` takes some `X` and checks whether `a(X,[])` holds. [Answer] # [Python 2](https://docs.python.org/2/), ~~73~~ 71 bytes ``` f=lambda s,P='(()())':P in s and f(s.replace(P,'()'))or s in['()()',''] ``` [Try it online!](https://tio.run/##dZAxD4IwEIVn@RW3Xc80Do4krC4OMrgREqpAJMFC2krir8eWQqQGmxt633t3r2n/No9OHsexTlrxvJUCNE8TZIwYEcYpNBI0CFlCzfRBVX0r7hVLOTJCok5ZsZEZOjtyxHysLTN8cHNZhsjhql5VzmHxBL1PWTMPJ06buj@Ob1W433Yn0epv/C9aZgLXVHNw4HV0nU5bNv9o9keYR9diHke7XjXSQGEKbr/ZEAe8nHHP3D1JBorGDw "Python 2 – Try It Online") [Answer] ## brainfuck, 50 bytes ``` ,[<+>[-[->>]<[-[--[>->,]]>>]<]<[>>],]<[--[>->]]<+. ``` Formatted: ``` , [ <+> [ -[->>] < [ - [ -- [ >->, ] ] >> ] < ] <[>>] , ] < [ -- [ >-> ] ] <+. ``` Expects a string of `(` and `)` without a trailing newline, and outputs `\x01` for true and `\x00` for false. (For legibility, you can e.g. add 48 `+`s before the final `.` to make it print `1` and `0` instead.) [Try it online](https://tio.run/##SypKzMxLK03O/v9fJ9pG2y5aN1rXzi7WBkTrRtvp2unExoL4QBEgpQOSAAvHxtpo6/3/rwEFmhqaWBEA) This maintains a stack with the number of groups at each depth, distinguishing characters by parity and checking whether the number of groups is in {0, 2} after each close parenthesis; if the condition is not met, consumes the rest of the input and sets a flag; then checks the condition again at the end of the program. If we are allowed to terminate the input stream with an odd character, we can omit the final check `<[--[>->]]` to save 10 bytes. (If `\n` weren't inconveniently even, I might have proposed this variant as the main answer.) (We could also save some bytes by changing the output format to `\x00` for true and non-`\x00` for false, which seems to be allowed (maybe accidentally) by the problem statement as written, but anyway it wouldn't be very interesting, and I prefer not to make that change.) [Answer] # Python2, ~~95~~ 94 bytes ``` f=lambda i:g(eval("(%s)"%i.replace(")","),"))) g=lambda i:len(i)in(0,2)and all(g(j)for j in i) ``` [Try it online!](https://tio.run/##dVBBCsIwEDw3r1gChV0IIj0KvfoCb@Ih2rSmxFiSVPD1tWmp1lbDXDIzy85O8wzXu826rsyNvJ0LCXpXoXpIgxxTTzzVG6caIy8KOXHBqQcRqz52oyxq0ha3IiNpC5DGYIU1lXcHNWgLmrqgfPCQwxE5FwAH1yoSLIF@CyGtqciu6JEfJPpnGV@UfmG1KBJ7afw8zQ/2PbzwDphyLCaiMA9Df5zjJfitseTEWCwwFifAKd@aELscityxpHHaBigx/mkydC8 "Python 2 – Try It Online") f() transforms the string into a nested tuple, which it passes to g(). g() recursively navigates the tuple and returns False if any element doesn't have exactly 0 or 2 children. Saved one byte by using string formatting. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~13~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ₧aaS▐îî»Å·╢ ``` [Run and debug it](https://staxlang.xyz/#p=9e616153de8c8caf8ffab6&i=%0A[][]%0A[][[][]]%0A[[][[][[][]]]][[][]]%0A[[[[[[[[][]][]][]][]][]][]][]][]%0A[]%0A[][][]%0A[[]][]%0A[][[][[]][]]%0A[[][]][[[[[[][]][]]][]][]]%0A[][[][][][]]%0A[][[][[][]][][]]&m=2) I saved two bytes when I realized the inputs can coincidentally be implicitly evalled as array literals. By removing the double quotes, the input is simplified. The general idea is to eval the input as an array literal, and recursively map the elements to check parethesly balance. If the final assertion ever fails, then there will be a subsequent pop on an empty stack. In stax, popping with empty stacks immediately terminates the program. Unpacked, ungolfed, and commented, it looks like this. ``` input is implicitly treated as array literals L wrap entire input stack in an array G jump to the trailing '}', and come back when done } terminate the program, the rest is a recursive call target {Gm map array on top of the stack by using the recursive call target % get the length of the mapped array 02\# is the length one of [0, 2]? |c assert value is truthy, pop if not ``` [Run this one](https://staxlang.xyz/#c=++++%09input+is+implicitly+treated+as+array+literals%0AL+++%09wrap+entire+input+stack+in+an+array%0AG+++%09jump+to+the+trailing+%27%7D%27,+and+come+back+when+done%0A%7D+++%09terminate+the+program,+the+rest+is+a+recursive+call+target%0A%7BGm+%09map+array+on+top+of+the+stack+by+using+the+recursive+call+target%0A%25+++%09get+the+length+of+the+mapped+array%0A02%5C%23%09is+the+length+one+of+[0,+2]%3F%0A%7Cc++%09assert+value+is+truthy,+pop+if+not&i=%0A[][]%0A[][[][]]%0A[[][[][[][]]]][[][]]%0A[[[[[[[[][]][]][]][]][]][]][]][]%0A[]%0A[][][]%0A[[]][]%0A[][[][[]][]]%0A[[][]][[[[[[][]][]]][]][]]%0A[][[][][][]]%0A[][[][[][]][][]]&m=2) [Answer] # Java 10, ~~99~~ ~~96~~ ~~95~~ 83 bytes ``` s->{s="("+s+")";for(var p="";!p.equals(s);s=s.replace("(()())","()"))p=s;return s;} ``` Port of my [05AB1E answer](https://codegolf.stackexchange.com/a/169807/52210) (so also returns `()` as truthy and anything else as falsey). [Try it online.](https://tio.run/##dVLBcoIwEL37Fds9JUPFuwz11lu92JvjIWJssTGk2eCM4/jtNBBQqQBMht23yb59eQdxEtPD7qfKlCCCD5HrywQg107avcgkLOsQYOVsrr8gY@FnvQHiiUeuE7@QEy7PYAkaUqho@nahFBlGFCHHZF9YdhIWTIqYvJhY/pZCEfP7KaXYSqN8H4aMccY5viLjyLlJKbHSlVYDJdcqqduYcqt8m7bbqch3cPR875QED2RnM/i0pfs@z5vQSXL@fF4fnPQzoWc/G9INwkcqwlMjQ1@/uotWZ3LyGBeli43n65RmLdJxfveyyH@cnxg/TzHQsxtheLp6qgf@fLAuTD6iz@0d0@cOtUIOKNjpdRP7lhqm8nzco/kaOzQbWqvm2pSO99xrJZXKeY/qOGMBH72btjZCD2PUhp13m4tZ4HorlNCZ3G1wjmtdOLgneMvwWv0B) **Explanation:** ``` s->{ // Method with String as both parameter and return-type s="("+s+")"; // Surround the input-String between "(" and ")" for(var p=""; // Previous-String, starting empty !p.equals(s) // Loop as long as the previous and current Strings differ ; // After every iteration: s=s.replace("(()())","()")) // Replace all "(()())" with "()" p=s; // Set the previous String with the current return s;} // Return the modified input-String // (if it's now "()" it's truthy; falsey otherwise) ``` `return s;` can be `return"()".equals(s);` if an actual boolean result was required. ]
[Question] [ For the purposes of this question, a deck of cards is formatted in this way: ``` [ "AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS", "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD", "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH", "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC", "J", "J" ] ``` Cards are always formatted as value, followed by suits. E.g. `AS` is the Ace of Spades. The two single J's are Jokers. We want to shuffle this deck of cards, but the shuffle must be Superb™. A Superb Shuffle™ is one in which: * No two cards (except Jokers) of the same suit are adjacent. * No card (except Jokers) is adjacent to one of the same value. * No card (except Jokers) is adjacent to one of an adjacent value (one higher or one lower in this order, A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A. Notice that Ace can not be adjacent to either a 2 or a King). * The Jokers can be in any position. * The definition of a Superb Shuffle™ *does not* require the cards to be in a different order each time they are shuffled. Which isn't very superb, but it is Superb™. Because that's Superb™. An example might be: ``` [ "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S", "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "4D", "8H", "QC", "AD", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C", "5S", "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H", "8C", "10S", "AH", "5C", "7S", "JD", "2C", "4S", "8D", "QH" ] ``` --- The challenge: * Write some code to execute a superb shuffle * Use any language. * The input can be **either**: + a deck of cards as described above *in the same order*, as an array or other list structure. + No input (the code generates a deck of cards in that order) * The output must be a full deck of cards in a Superb Shuffle™ as described above. * Attempt to perform your Superb Shuffle™ in the smallest number of bytes. * A link to an online interpreter such as [Try It Online](http://tio.run) is preferred, but optional. Happy shuffling! [Answer] # [Ruby](https://www.ruby-lang.org/), 31 bytes ``` ->x{(0..53).map{|r|x[r*17%54]}} ``` [Try it online!](https://tio.run/##Ncw9C4JQAIXhvV8hQlBRot0vHQpCB7lOl0ZxqMEtECEw1N9@q9danjMcePvn/eXbkz@ch3ETR5ES2@hx68apn4a63yVmrWQzz74L2rpeBUF4uYb7IDyiQIkKNRpMMcMkZiw6rD4SLAiiQIkKNRpMMSuWIGPRYfWVYkkRBUpUqNFgilm5FBmLDqvyX8wpokCJCjUaTDHLlyJj0WGV/4qWJ1w1jX8D "Ruby – Try It Online") ### Explanation: I'm picking one card, then skipping over the next 16 and start from the first card when I reach the last card of the deck. 17 and 54 are mutually prime, so I'm sure to pick all cards. The 17th position is guaranteed to be a different suit and the difference in value is at least 2: the 13th (or 15th) card has the same value and a different suit, so by skipping other 4 (or 2), the value is right. [Answer] # [Python 3](https://docs.python.org/3/), 21 bytes ``` lambda x:(x*17)[::17] ``` [Try it online!](https://tio.run/##NcwxC4JAAIbh3V9xOGk0ZOd5KjSEDnI3HY3mYIQUlEk42K@3eq3l@YYP3uE1Xh69nLvdcb6199O5FVMeTKtIh3WeR7qZh@e1H4MuqD0h/P3BXwt/ixJjVJigxhQzjDaMQYf2I8GSIEqMUWGCGlPMyiXIGHRov1KsKKLEGBUmqDHFrFqKjEGHtvoXC4ooMUaFCWpMMSuWImPQoS1@RcPje00Yzm8 "Python 3 – Try It Online") ### Explanation: The same idea as my Ruby answer, but even shorter in Python: I use 17 decks, and pick every 17th card. [Answer] # Japt, ~~6~~ ~~5~~ 4 bytes Splits the input array into sub-arrays of every 16th element and flattens. ``` óG c ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=80cgYw==&input=WyJBUyIsIjJTIiwiM1MiLCI0UyIsIjVTIiwiNlMiLCI3UyIsIjhTIiwiOVMiLCIxMFMiLCJKUyIsIlFTIiwiS1MiLCJBRCIsIjJEIiwiM0QiLCI0RCIsIjVEIiwiNkQiLCI3RCIsIjhEIiwiOUQiLCIxMEQiLCJKRCIsIlFEIiwiS0QiLCJBSCIsIjJIIiwiM0giLCI0SCIsIjVIIiwiNkgiLCI3SCIsIjhIIiwiOUgiLCIxMEgiLCJKSCIsIlFIIiwiS0giLCJBQyIsIjJDIiwiM0MiLCI0QyIsIjVDIiwiNkMiLCI3QyIsIjhDIiwiOUMiLCIxMEMiLCJKQyIsIlFDIiwiS0MiLCJKIiwiSiJd) [Answer] # Java 10, ~~72~~ 65 bytes ``` d->{var r=d.clone();for(int i=54;i-->0;r[i*7%54]=d[i]);return r;} ``` Similar as [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/167002/52210), but by using `i*7%54` on the result-array, instead of `i*17%54` on the input-array to save a byte. [Try it online.](https://tio.run/##VdJfa4JQGMfx@72KB2GgY0qb/xGDqItQFkiX0cWZ2jjNjnE8NiJ87c5@Rluin0c5@OUI7tmJmfviu88r1jT0wbi4PBFxoUq5Y3lJq@sj0VpJLr42W8r1@21hRMNaN1zD2SimeE4rEhRTX5jTy4lJknFh5VUtSt2IdrXUhy7x2HUibprTSSQ3/MV/dp1tXGz41ohkqVopSEZdH43ZY/tZDdlb/VTzgg7DHv82wYzbBs@NKg9W3SrrOCypSuj74dusVvHKmknJzo2l6vE1XVi5Lsqf@1eNieuhzdbaK2nv0IYOdKEHfRjAEL5NMBKYwfTqv@4CXWhDB7rQgz4MYLgYuxgJzGC6eOwu0YU2dKALPejDAIbLsYuRwAymy8fuHF1oQwe60IM@DGA4H7sYCcxgOn/oJljXOsO4/T1d/ws) **Explanation:** ``` d->{ // Method with String-array as both parameter and return-type var r=d.clone();// Result-String, starting as a copy of the input for(int i=54;i-->0; // Loop `i` in the range (54, 0] r[ // Set an item in the result-array at index: i*7%54 // Index `i` multiplied by 7, and then take modulo-54 ]=d[i]); // To the `i`'th item in the input-Deck return r;} // Return the result-Array ``` [Answer] # JavaScript, 35 bytes ``` x=>x.map((a,i)=>i%2?a:x[(i+20)%54]) ``` [Try it online!](https://tio.run/##NcxPi4JAAIbxe59ChGCGzSid8U9gsehBxpPsMTpMroVhGbWE395lH7fL7z288Fzsyz7rR3v/8Y722HTerf9uxlM6Dul2WF7tXQi7aGW6bef@zm6GvWg//JWca3WQY93fnn3XLLv@LE5iP3Mc9/PLXTiujwEq1BhihDEmuF4xBiss/6SYU8QAFWoMMcIYk3wqMgYrLPN3saCIASrUGGKEMSbFVGQMVlgW72JGEQNUqDHECGNMsqnIGKywzP6LhsedHaQcfwE "JavaScript (Babel Node) – Try It Online") Taking an array of deck as input, and replacing each odd value with another card that is "20 cards" away on the deck. [Answer] # JavaScript, 27 Another one based off of the ruby answer ``` d=>d.map((_,i)=>d[i*17%54]) ``` Edited in an obvious shortening [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~21 20~~ 18 bytes *Thanks to Brad Gilbert b2gills for -2 bytes* ``` {.[$++*17%$_]xx$_} ``` [Try it online!](https://tio.run/##NcwxC4JAAIbh3V9xiEVlSHZ65xENoYOc09EoIg05FUQtSvTbjV5zeb7hg/dxfd7UeB/EshPH8R3VQRhuYr0I2qbvg/YzHrpV7Qnhn87@Vvh7lJhgigo1Zmgw3jEWHVY/KRYUUWKCKSrUmKEppiJj0WFVzMWSIkpMMEWFGjM05VRkLDqsyrmYU0SJCaaoUGOGJp@KjEWHVf4vWh7fa9bR6zKMXw "Perl 6 – Try It Online") Yet another port of [G B's answer](https://codegolf.stackexchange.com/a/167002/76162). ~~Note that, while the global variable `$!` is not reset between functions, the value doesn't matter, since any order of the output is valid.~~ However, `$` *is* reset. ### Explanation: ``` { } #Anonymous code block xx$_ #Repeat size of inputted array (54) times .[ ] #Get from the inputted array, the value at index $++*17%$_ #The incremented variable, multiplied by 17, modded by size of the array ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā17*è ``` Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/167002/52210), so make sure to upvote him! -2 bytes by printing each card with a new-line delimiter instead of wrapping it to a result-list -2 bytes thanks to *@Mr.Xcoder* [Try it online.](https://tio.run/##Jcw9CgIxFEXhrYSUMsXE/LykDDPFkFTBUiwUXIi7cR@6rwyc13wXbnHW@Hy595z/j5PL7zvn3dh6s4uxV/QYMGJCwYwF3co0HNix7uTQY8CICQUzll1zTMOBHetBDj0GjJhQMGM5NMc0HNixbuTQY8CICQUzlk1zTMOBXR/FPE4) **Explanation:** ``` ā # 1-indexed length range [1 ... length_of_input_list (54)] 17* # `k`: Multiply each index by 17 è # And then replace each item with the 0-indexed `k`'th card of the input-list # (with automatic wrap-around) ``` [Answer] # T-SQL, 31 bytes ``` SELECT c FROM t ORDER BY i*7%54 ``` If you don't care about an extra column in the output I can get it down to **29 bytes**: ``` SELECT*FROM t ORDER BY i*7%54 ``` So you can verify my output is "Superb", here is the deck it produces: ``` J, 5H, 8S, KH, 3D, 8C, JD, AS, 6H, 9S, AC, 4D, 9C, QD, 2S, 7H, 10S, 2C, 5D, 10C, KD, 3S, 8H, JS, 3C, 6D, JC, AH, 4S, 9H, QS, 4C, 7D, QC, 2H, 5S, 10H, KS, 5C, 8D, KC, 3H, 6S, JH, AD, 6C, 9D, J, 4H, 7S, QH, 2D, 7C, 10D ``` (Generated using the new SQL 2017 addition, `STRING_AGG`): ``` SELECT STRING_AGG(c,', ')WITHIN GROUP(ORDER BY i*7%54)FROM t ``` The hard part for me was not the select code, it was populating the input table (which is [allowed for SQL per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341)). Because SQL is inherently unordered (it only guarantees a certain order if you include an explicit `ORDER BY` clause), I had to include that original order as a field *i* in the input table *t*. This also means I can use it to sort, using the same "relatively prime" factor/mod process everyone else is using. I found that `i*7%54` worked just as well as `i*17%54`. Here are the commands to set up and populate the input table *t*, based on [my solution to this related question](https://codegolf.stackexchange.com/a/166665/70172): ``` CREATE TABLE t (i INT IDENTITY(1,1), c VARCHAR(5)) --Insert 52 suited cards INSERT t(c) SELECT v.value+s.a as c FROM STRING_SPLIT('A-2-3-4-5-6-7-8-9-10-J-Q-K','-')v, (VALUES('S',1),('D',2),('H',3),('C',4))s(a,b) ORDER BY s.b --Insert Jokers INSERT t(c) SELECT 'J' INSERT t(c) SELECT 'J' ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s⁴ZẎ ``` **[Try it online!](https://tio.run/##DcohEsIwEEDRq/wjQNI2jezsip1EddbhMQwOhUThOAyDYLCcpFwkxD3xTsfz@dra5Xd7HbbPo23v5/deW1uc4ERncEZncpIzO9nZ75zirE51FiUoURmUUZmUpMxK1v6UoqxKVRYjGNEYjNGYjGTMRrb@jGKsRjUWIQhRGIRRmIQkzEKW/oQirELtoPwB "Jelly – Try It Online")** Turns out the way ~~everyone else~~ *everyone else except [The random guy](https://codegolf.stackexchange.com/a/167016/53748)* is doing it saves a byte :( Credit to [G B for their method](https://codegolf.stackexchange.com/a/167002/53748). --- The way I went... ``` ṙÐe20 ``` **[Try it online!](https://tio.run/##Dcq7EcIwEEDBVl4JRvJHCjV3wY0Uea4GJ4wboAJSUtoggtiVuBLhbIO9b/v@6P38vY/XFoZ@fj/Hs/VenOBEZ3QmZ3YWJznZuQ1OdVanOUUJSlRGZVJmZVGSkvV6SlVWpSnFCEY0RmMyZmMxkpHtekY1VqMZRQhCFEZhEmZhEZKQ5XpCFVahXaD@AQ "Jelly – Try It Online")** ### How? Fix every other card and intersperse it with a rotation of the deck left by 20 places (18 and 22 places also work; furthermore so does either direction of rotation as well as fixing either odd or even cards) ``` ṙÐe20 - Link: list of the card strings (lists of characters) 20 - place a literal twenty on the right Ðe - apply to even indices: ṙ - rotate left (by 20) ``` That is (using `T` for `10` and `rj` & `bj` for the `J`s): ``` input: AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC rj bj ṙ20: 8D 9D TD JD QD KD AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH AC 2C 3C 4C 5C 6C 7C 8C 9C TC JC QC KC rj bj AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS AD 2D 3D 4D 5D 6D 7D ṙÐe20: AS 9D 3S JD 5S KD 7S 2H 9S 4H JS 6H KS 8H 2D TH 4D QH 6D AC 8D 3C TD 5C QD 7C AH 9C 3H JC 5H KC 7H bj 9H 2S JH 4S KH 6S 2C 8S 4C TS 6C QS 8C AD TC 3D QC 5D rj 7D ``` [Answer] # PowerShell 3.0, ~~30~~ 26 Bytes ``` $args[(0..53|%{$_*17%54})] ``` -4 thanks to Mazzy Old code at 30 bytes ``` param($d)0..53|%{$d[$_*17%54]} ``` Another port of G B's method. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` Eθ§θ×¹⁷κ ``` [Try it online!](https://tio.run/##NczNCoJAGEbhvVcxuDIwyBydkVahCxsJktqFC6mgyP4luvspjzmL5/1g4OyO9XN3qxtrV8/TtfWW9d17@GLeLq77w6c7N6fL4eUFyhfn0e/NrN1uHSHc@dr1hTvFECVGGKNCjQkGE8ZgiUUnxYwihigxwhgVakyyvsgYLLHIhmJOEUOUGGGMCjUmeV9kDJZY5EMxpYghSowwRoUak7QvMgZLLNJ/0fDjOlVlx@/mCw "Charcoal – Try It Online") Link is to verbose version of code. Another port of @GB's Ruby answer. Explanation: ``` θ Input array E Map over elements κ Current index ¹⁷ Literal 17 × Multiply θ Input array § Cyclically index Implicitly print each result on its own line ``` [Answer] # [Red](http://www.red-lang.org), 44 bytes ``` func[a][append/dup a a 16 prin extract a 17] ``` [Try it online!](https://tio.run/##Lcy9CoMwAEXh3acIeYHWqvnpVnSQONmO4iBNhC4SRKFvbz1WLnzDHc4c/PYMvuuT8b6N6/Tuhr4bYgyTv/g1imFfqkScP5MI32Ue3guP7rdRdIkQ8vGSQt4ggxwKUKDBgIX0ig5aaHaOSEUEMsihAAUaDNjqiKCDFprqjNREIIMcClCgwYCtjwg6aKGpz0hJBDLIoQAFGgzY8oiggxaa8h9xvDLptx8 "Red – Try It Online") Another interpetation of G B's code. I append 16 copies of the deck to itself and then extract each 17th card. ]
[Question] [ Given an array of positive integers, output a stable array of the distinct prime factors of these integers. In other words, for each integer in the input in order, get its prime factors, sort them, and append any primes not already in the output to the output. # Test Cases ``` [1,2,3,4,5,6,7,8,9,10] -> [2,3,5,7] [10,9,8,7,6,5,4,3,2,1] -> [2,5,3,7] [100,99,98,1,2,3,4,5] -> [2,5,3,11,7] [541,60,19,17,22] -> [541,2,3,5,19,17,11] [1,1,2,3,5,8,13,21,34,45] -> [2,3,5,13,7,17] [6,7,6,7,6,7,6,5] -> [2,3,7,5] [1] -> [] [8] -> [2] [] -> [] ``` Output can be as an array or list of integers or strings, delimited output, or any other standard means of outputting an ordered list of numbers. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes Outputs as a list of Strings. ``` f˜Ù ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/7fScwzP//4821DHUMdIx1jHVsdAxNNYxMtQxNtExMY0FAA "05AB1E – Try It Online") # [2sable](https://github.com/Adriandmen/2sable), 3 bytes Yes, this also works in 2sable. Also returns a list of Strings. ``` f˜Ù ``` [Try it online!](https://tio.run/##MypOTMpJ/f8/7fScwzP//482NTHUMTPQMbTUMTTXMTKKBQA "2sable – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes *1 byte saved thanks to [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb).* ``` uṁp ``` [Try it online!](https://tio.run/##yygtzv7/v/ThzsaC////R5uaGOqYGegYWuoYmusYGcUCAA "Husk – Try It Online") --- # Explanation ``` uṁp Full program. p Prime factors of each. ṁ Map function over list and concatentate the result. u Unique. ``` [Answer] # Bash + GNU utilities, 37 * 21 bytes saved thanks to @muru (wow!) ``` factor|tr \ \\n|awk '!/:/&&!a[$0]++' ``` [Try it online](https://tio.run/##S0oszvj/Py0xuSS/qKakSCFGQSEmJq8msTxbQV1R30pfTU0xMVrFIFZbW/3/f1MTQy4zAy5DSy5Dcy4jIwA). [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` "@Yfvu ``` [Try it online!](https://tio.run/##y00syfn/X8khMq2s9P//aEMDAx1LSx1LCx1DHSMdYx0THdNYAA "MATL – Try It Online") Explanation: ``` " % Loop over input @ % Push the array element Yf % Prime factors v % Concatenate entire stack vertically (does nothing the first iteration) u % Stably get distinct (unique, in MATLAB terminology) elements. Does so every loop but this is code golf, not fastest code. ``` Interesting MATL tidbits: generally, all functions apply to vectors (arrays) just as easily. But in this case, the number of factors is variable for each input, and Matlab and by extension MATL generally only deal in square matrices, so I had to use a for loop `"`. Furthermore, MATL has two main concatenation operators: `h` and `v`, horizontal and vertical concatenation. Their behaviour differs significantly: `v` concatenates the entire stack, even if it has only one element like in our first iteration. `h` takes exactly two elements and will fail if only one is present, making it unsuitable for this application. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḋᵐ↔ᵐcd ``` **[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7odbJzxqmwIkk1P@/482NNCx1LHQMdcx0zHVMdEx1jHSMYz9HwUA "Brachylog – Try It Online")** # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḋᵐoᵐcd ``` **[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7odbJ@QDcXLK///RhgY6ljoWOuY6ZjqmOiY6xjpGOoax/6MA "Brachylog – Try It Online")** --- ## Explanation ``` ḋᵐ Map with prime decomposition (which returns the factors in reverse order). ↔ᵐ Reverse each (or oᵐ - order each). c Concatenate (flatten). d Deduplicate. ``` [Answer] # [Pyth](https://pyth.readthedocs.io), ~~5~~ 4 bytes ``` {smP ``` **[Try it here!](https://pyth.herokuapp.com/?code=%7BsmP&input=%5B541%2C60%2C19%2C17%2C22%5D&debug=0)** or **[Verify all test cases.](https://pyth.herokuapp.com/?code=%7BsmP&input=%5B541%2C60%2C19%2C17%2C22%5D%0A&test_suite=1&test_suite_input=%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%5D%0A%5B10%2C9%2C8%2C7%2C6%2C5%2C4%2C3%2C2%2C1%5D%0A%5B100%2C99%2C98%2C1%2C2%2C3%2C4%2C5%5D%0A%5B541%2C60%2C19%2C17%2C22%5D%0A%5B1%2C1%2C2%2C3%2C5%2C8%2C13%2C21%2C34%2C45%5D%0A%5B6%2C7%2C6%2C7%2C6%2C7%2C6%2C5%5D%0A%5B1%5D%0A%5B8%5D%0A%5B%5D&debug=0)** Alternative: `{sPM` --- # Explanation ``` {smP Full program with implicit input (Q). m Map over the input. P Prime factors. s Flatten. { Deduplicate. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 102 bytes ``` param($x)$a=@();$x|%{$a+=(2..($z=$_)|?{!($z%$_)-and'1'*$_-match'^(?!(..+)\1+$)..'}|sort)};$a|select -u ``` [Try it online!](https://tio.run/##DcZLCoMwEADQq1QYyUwdA/EDBRE9SKkMNuDCH2qp1Hj21Ld68/S1y9rZvvd@lkUGhJ1AyhqpgN2FB0hUYqI1wq@Ehlx1BFfDq7GMb2XUHZp4kK3t1AurALWO6GkiIK3V6dZp2egsQNxqe9tut/jjva/RsOGEU875wSblxHCacZbTHw "PowerShell – Try It Online") *(Borrows factorization idea from TessellatingHeckler's [answer](https://codegolf.stackexchange.com/a/140539/42963) over on "Get thee behind me Satan-Prime!")* Takes input as a literal array `$x`. Creates a new empty array `$a`. Loops over `$x`. Each iteration we loop from `2` up to the current number, checking whether that is a factor `-and` is prime, then `|sort` the output of that, and append it to `$a`. When we're done going through `$x`, we then output `$a` but `|select` only the `-u`nique numbers thereof. This exploits the fact that the uniqueify goes left-to-right, keeping the first occurrence, which matches the problem description. Those numbers are left on the pipeline and output is implicit. [Answer] # CJam, 11 bytes ``` {:mfe__&1-} ``` Function that takes array of ints and outputs array of ints. [Test Version](http://cjam.aditsu.net/#code=q'%2CSer~%7B%3Amfe__%261-%7D~'%2C*&input=%5B6%2C7%2C6%2C7%2C6%2C7%2C6%2C5%5D) [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 bytes ``` ḍ¦_u ``` [Try it online!](https://tio.run/##S0/MTPz//@GO3kPL4kv/pz5qm/g/2tTEUMHMQMHQUsHQXMHIKBYA "Gaia – Try It Online") --- # Explanation ``` ḍ¦ Prime factors of each. _ Flatten the list. u Remove duplicate elements. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes 1 byte thanks to clap. ``` ÆfFQ ``` [Try it online!](https://tio.run/##PYwrEsIwEIY9Z/lFNt2kyQXwSCYTCYLpBZAgwKNwXADNFN3hIO1Flu3yEPuY73/sNl23FxlO2@VKhvN0vL8u4/Oqdz32t@nwECmF4NGAERDRIiGDXMWikNM3KYoqsVo86MNVyMgJ/@SMAxOiA2m8hffm/DqC1pDmCQ2DzR2t9zeGrDzNq9Y3 "Jelly – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 4 bytes ``` MPs} ``` [Try it here!](http://pyke.catbus.co.uk/?code=MPs%7D&input=%5B541%2C60%2C19%2C17%2C22%5D&warnings=0&hex=0) --- # Explanation ``` MP Prime factors of each. s Flatten. } Deduplicate. ``` [Answer] # Mathematica, 64 bytes ``` Select[DeleteDuplicates[First/@FactorInteger@#~Flatten~1],#>1&]& ``` **input** > > [{100, 99, 98, 1, 2, 3, 4, 5}] > > > [Answer] # Haskell, 77 bytes ``` import Data.List x!y|y>x=[]|x`mod`y<1=y:(x`div`y)!y|1<2=x!(y+1) nub.((!2)=<<) ``` ### Explanation: * the `x!y` operator returns a list of all prime factors of `x` that are greater than or equal to `y` * the `(!2)` function returns a list of all prime factors of its argument * the function on the last line implements the required functionality [Try it online.](https://tio.run/##bY9di4JAFIbv51ecZC@UzkZjfiVOsMvuQmzQRZcROKKhbGWbtin4393Tl1l0YAY9z3l4z8Qy@4lWq7pO1tt0l8OHzGVvkmQ5KzplVY4KMV9Uhb9OQ7/0uChdtfDD5M8vNcLc00XRUcsu19hSbPZBT1U7uiY8T6vXMtmAgDBlQLWEOUcdB2igiRba6OAQeX8Bfhan@1X4HvkwP3IT7UVj9GnIoWGL2gZBHfmjYVK7bZAyxKGDTdozgfOWYxocrT5y2sdGXb@fP8LzWmfO@S0Lr4jSaDeOAwMN89mTCJN6i7ROb7qeJ4pNzSbnHjd950FrwOM8Y9dfcF1QP39BIszi9ABSAzECCa@XazwFVWOy7QdQgRQigFMJ2O7zWb6bbECZfisM7quCNI@j3SHJovboCyhfb@OJCwp0u6Bml2j6VuCcBEHUhoHG6n8) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḋᵐoᵐcd ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7odbJ@QDcXLK///RhgY6ljoWOuY6ZjqmOiY6xjpGOoax/6MA "Brachylog – Try It Online") ### Explanation ``` ḋᵐ Map prime decomposition oᵐ Map order c Concatenate d Remove duplicates ``` [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 3 bytes Yet another 3-byter (thanks to languages with auto-vectorization). ``` m{U ``` **[Try it online!](https://tio.run/##y8/INfr/P7c69P//aEMDHUsdCx1zHTMdUx0THWMdIx3DWAA "Ohm v2 – Try It Online")** --- # Explanation ``` m Prime factors. Auto-vectorizes over the input. { Flatten. U Uniquify. ``` [Answer] # [Japt](https://github.com/ethproductions/japt/), 6 bytes ``` mk c â ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=bWsgYyDi&input=WzEsMiwzLDQsNSw2LDcsOCw5LDEwLDExLDEyLDEzXQotUQ==) --- ## Explanation Implicit input of array `U`. Map (`m`) over it, getting the factors (`k`) of each element. Flatten (`c`), get the unique elements (`â`) and implicitly output. [Answer] # [Python 3](https://docs.python.org/3/), ~~128 125~~ 116 bytes This is a pure Python solution. No packages. *Thanks to Halvard for saving 9 bytes.* ``` def f(l):y=[k for i in l for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))];print(sorted({*y},key=y.index)) ``` [Try it online!](https://tio.run/##TcpLDsIgEADQq8ymCVMnRlr/2pM0XTQBdAKBBllAjGfH2JW7t3hLSc/g@1qVNmCEw2sZRgsmRGBgD26l/THO/qFFR7yRyAa4sXfZzs4J2@R15f9lEafbEtkn8QoxaSXebfmQ1WUoW/ZKZ8RqxCh3dKEznehIB9pTTx3JCesX "Python 3 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~133 127~~ 126 bytes ``` def f(l):y=sum([[k for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))]for i in l],[]);print sorted(set(y),key=y.index) ``` [Try it online!](https://tio.run/##TcpLCsMgEADQq8wmMNMOpab/30nERSDaDloTjIV4eku66vbxxpJfQ2xr7a0Dh4Gu5TF93qi1Bzck8CARUhefFluWtSJxII2/q1UXAvpm/q35f3kis6AsGAxrQ7cxScwwDSnbHiebsRB7Wx5lI7G3M1WHWm35wmc@8ZEPvOcdt6wM1S8 "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~142 138~~ 134 bytes ``` l=input();r=[] for i in sum([[k for k in range(2,i+1)if i%k<1*all(k%x for x in range(2,k))]for i in l],[]):r+=[i]*(i not in r) print r ``` [Try it online!](https://tio.run/##Tcw5DsMgEEDR3qeYxhJjTxHIvnASROEiTkYQQARLzumJ7CJK@/X006c8Y1C1es0hTUXgNWtjmzFmYOAA7@kljHGwBLeEPITHXSjiXiKPwK27yW7wXrh2XtX8rxyi/b28JWPxkntt2HaCIcSyYmxS5lAg12rkhs50oiMdaE872pIiab8 "Python 2 – Try It Online") Very surprised there was no Python answer yet. Working on golfing. [Answer] # [Deorst](https://github.com/SatansSon/Deorst), 16 bytes ``` EDkE]l1FeFPkEQE_ ``` [Try it online!](https://tio.run/##S0nNLyou@f/f1SXbNTbH0C3VLSDbNdA1/v//aEMDHUsdCx1zHTMdUx0THWMdIx3DWAA "Deorst – Try It Online") Done with help from @cairdcoinheringaahing in the [Deorst chatroom](https://chat.stackexchange.com/rooms/64858/deorst) (note that the solutions are different). --- # Explanation ``` EDkE]l1FeFPkEQE_ Full program. ED Push the list of divisors of each element. k Prevent the stack from reordering. E] Flatten the stack. l1Fe Remove 1s from the stack (because caird rushed and made 1 prime!) - Should be removed in future language releases. FP Keep the primes. k Prevent the stack from reordering. EQ Deduplicate. E_ Output the result. ``` [Answer] # [Deorst](https://github.com/SatansSon/Deorst), 16 bytes ``` EDkE]EQFPkl1FeE_ ``` [Try it online!](https://tio.run/##S0nNLyou@f/f1SXbNdY10C0gO8fQLdU1/v//aEMDHUsdCx1zHTMdUx0THWMdIx3DWAA "Deorst – Try It Online") Done with help from @Mr.Xcoder. This is way too long for a pseudogolfing language. ### How it works ``` EDkE]EQFPkl1FeE_ - Full program, implicit input: [1,2,3,4,5] ED - Get divisors. Vectorizes. STACK = [[1], [1,2], [1,3], [1,2,4], [1,5]] k - Turn off sorting for the next command E] - Flatten the stack. STACK = [1, 1, 2, 1, 3, 1, 2, 4, 1, 5] EQ - Deduplicate stack in place. STACK = [1, 2, 3, 4, 5] FP - Filter by primality 1 is considered prime. STACK = [1, 2, 3, 5] k - Turn off sorting for the next command l1 - Push 1. STACK = [1, 2, 3, 5, 1] Fe - Filter elements that are equal to the last element. STACK = [2, 3, 5] E_ - Output the whole stack ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` ǐfU ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLHkGZVIiwiIiwiWzU0MSw2MCwxOSwxNywyMl0iXQ==) ``` ǐ # prime factors f # flattened U # uniquified ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 4 bytes ``` mPs} ``` [Try it here!](http://pyke.catbus.co.uk/?code=mPs%7D&input=%5B10%2C9%2C8%2C7%2C6%2C5%2C4%2C3%2C2%2C1%5D&warnings=1&hex=0) ``` mP - map(factorise, input) s - sum(^) } - uniquify(^) ``` [Answer] # Octave, 61 bytes ``` a=input('');b=[];for c=a(a>1)b=[b setdiff(factor(c),b)];end;b ``` [Try it online!](https://tio.run/##DchLCoAgEADQq7RTYRYpfQixi4iL8QduNGzq@tZbvhYI3zQGmlKvhzhjQntjnc6tT8Egx1OKP/x0J4olZ54xUOs8CPDC6VSj9mPYdZGwzSAPkDso5T4 "Octave – Try It Online") [Answer] # MY, 17 bytes ``` ⎕Ḋḟ’⊢f(‘53ǵ'ƒf(ū← ``` [Try it online!](https://tio.run/##AT4Awf9tef//4o6V4biK4bif4oCZ4oqiZijigJg1M8e1J8aSZijFq@KGkP//WzEsMiwzLDQsNSw2LDcsOCw5LDEwXQ) ## How? * `⎕` evaluated input * `Ḋ` divisors (vectorizes/vecifies) * `ḟ` flatten * `’⊢f(‘` decrement, filter, increment (removes `1`) * `53ǵ'` the string `'P'` in MY's codepage, which is primality testing. Sadly `0x35=53` is the 16th prime number, and there's not a command for pushing `16` to the stack >\_< . * `ƒ` as a function * `f(` filter by that * `ū` uniquify * `←` output [Answer] # C++, 118 bytes ``` [](auto n){decltype(n)r;for(int m:n)for(int i=1,j;i++<m;){j=m%i;for(int x:r)j|=!(i%x);if(!j)r.push_back(i);}return r;} ``` Needs to be passed the input in a `std::vector<int>`, returns another `std::vector<int>` for output. [Answer] # J, 10 bytes ``` ~.(#~*),q: ``` I'm sure some clever J-er could make this shorter. [Answer] # [Actually](https://github.com/Mego/Seriously), 5 bytes ``` ♂y♂i╔ ``` [Try it online!](https://tio.run/##S0wuKU3Myan8///RzKZKIM58NHXK///RhgY6CpY6ChY6CuY6CmY6CqY6CiY6CsY6CkY6CoaxAA "Actually – Try It Online") Explanation: ``` ♂y♂i╔ ♂y prime factors of each element ♂i flatten ╔ deduplicate (stable) ``` [Answer] ## Python 2, ~~88~~ ~~119~~ 103 bytes Here we go. With the correct sorting. ``` def f(l,s=[]):[s.append(x) for x in sum([list(primefac(i)) for i in l],[]) if x not in s];print s from primefac import* ``` Apperently I can't get it to work on TIO, because the package is not supported. It does run on my machine tho. Here are my Test outputs: ``` f([1,2,3,4,5,6,7,8,9,10],[]) #[2, 3, 5, 7] f([10,9,8,7,6,5,4,3,2,1],[]) #[2, 5, 3, 7] f([100,99,98,1,2,3,4,5],[]) #[2, 5, 3, 11, 7] f([541,60,19,17,22],[]) #[541, 2, 3, 5, 19, 17, 11] f([1,1,2,3,5,8,13,21,34,45],[]) #[2, 3, 5, 13, 7, 17] f([6,7,6,7,6,7,6,5],[]) #[2, 3, 7, 5] f([1],[]) #[] f([8],[]) #[2] f([],[]) #[] ``` Somehow I was not able to make the function as a lambda-function. Whenever i try to return the list comprehention, it returns [None, None, ...]. If i am just overlooking something, could someone point that mistake out? Thanks for the feedback! --- Edit: Using Mr. Xcoders sorting algorithm I could cut down the code by 16 bytes. Thank you for that part. ``` from primefac import* def f(l):a=sum([list(primefac(i))for i in l],[]);print sorted(set(a),key=a.index) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 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") ``` ∪∘∊⍭ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1HHqkcdMx51dD3qXfs/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/T1MwVDBSMFYwUTBVMFMwV7BQsFQwNOACChsAWRZAETOgjAlQhZGCIVgYKG6pYGmB0AcUNTUxVDAzUDAE6jVXMDICqYPKmwLNMARqNlQwNlEwAak1A5sJwyARkLkWAA "APL (Dyalog Extended) – Try It Online") [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 7 bytes ``` &(p)u=; ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9fTaNAs9Tb1vr///@G/43@G/83@W/63@y/@X@L/5b/DQ0A "Braingolf – Try It Online") Oh look, it's *basically* a chain of 4 built-ins ## Explanation ``` &(p)u=; Implicit input from commandline args (.) Sandbox loop, sandboxes each item in a separate stack and runs the code within the loop. & Append the entire sandboxed stack when loop ends, rather than only the top of stack after each iteration p Prime factors u Unique = Print stack ; Suppress implicit output ``` # [Braingolf v2](https://github.com/gunnerwolf/braingolf), 5 bytes ``` &pu=; ``` [Try it online!](https://tio.run/##1TxZc9tG0s/UrxgpskGIhynZzkFZ8ic7TspVa8e1rtoXmgmHIChBIgEEB22Xwu@ve7t7bgCUSK@zVZuH0Jjp6enpe2Z6dM1XPA@yKC16cTILvwRJnBcszZIgzHN2xrLwzzLKwrYnmzz/dE/AzJ3uOfXIrj9yPg@h19v3FPQfWbgKs5xa/9@05tEijAtsPDSNl1kYzj5j40PTuExm0TwCFNA@ogm6GmlXIeqqwWM9TtL9On5fZFF8iaO9Dx@8LvMOvDFSvOCw0Be/vklmObvda9GwrAyKJGv72NAqrqK8v@KLEokfwZjWem@vxWez9hIAWDRn7X2CueI5NPnMDOinZX4FbadsvdfKwjwsECerYsReMRg6s7Aos5jlBS/CPo0h0p7baKM4WJSzkEYM2Zwv8hCRrM1y3hc8uKmuJ4qjIuKLfyGOhrXZ3eyvv8xaaRUAlXeRrKwQY3Hhxec0TObU57OzMxBZTmz2BEhrERasWKaAHEFOsQn/oRjZas2TjLURKoK2wSn8PMMBfZDmZXEF352OREUDBUMRILji2UvQ2IuiHfk@4QIuttYsBGawRtoO4nI5DbMDnyka8Jfo0IP2L7KMf@5HOf2KwSjRLPnIXmUZMHHyksdewUD@oLS3CLD2WJEgZ4KbfSa4tyxB96YhE9zoMo7YugwWK2josmlZsMukYIe3Np3rCVqR4K1ktSMi4gGINOBF23T4egkOsKUwcgjNoYSapGKKLguSMpZCRVGA0pWLQsuoSUQ0wpYO9q@gnzC6yppfRXPU@6FjGDC7kJqYTQh2RU0oR2kFopMobqVhePNfoXgUjR1iRxbdQi977ahz7I93on@vdRmtQqmOinAx@Zm0dvBxwosox0boaPaaCQqeFPwmbNPSAMnxbngJTjjqKhg2E4zUQ6dTeFiwCjVvjT2nhgGICbkk@VuXIXZKZtc0ktYInFvxTJAIk8EKZ@G0vJRurys/X8cz8P9DNoCGPCmzIByyEtrmURzOoC1KRV/4KSrMULLZfAhqgx8SZMmjmNyn@FwkSSo/CQxMaQZ@EtyqbEDODFkcfpRRpCtd/RtqV1NFMgDZk4tvz0O68oCn4cz08tmKx7gKcN74nQJw8Vv8iugXbetTwZokzQVjMLANGZja2bn20PtCfGp6X8YXFFE1xJzJSOLIXRLmS1fGOuDjYRrtcRwoVAYgDeUGJHvfITWRQ07EOuyYnSuVE6KSamPTRtbJF6wCaHt9xERKuiLetCdvw08FQwgW5eBX7YEjgh6vWZtc9tqf@IYDQgtG8iMd95WhWjBR2umoZR04TL6HizX@3zJJ78GL8DKKY2Sq4O0B5AkutOInJggmRm0WzIGRC/k4NZPEFiTLFBgbDg@E65XdigsiVAmetmqE6FXdyTUbl@9ASzSeZ7XaXJOKg16NuPx/rvKgQpBXuMgEmi67Rp/X1W7oGEd/vIJEUKjZNXj9Bi1jDx@ymmpcj/tLXgRX7UejQe@n8SNfBgk9Y@esaRAt5Zo0g7y@AJGma/NMKRFmWThSaYfCr2g7ZwMrPKmVpRx89muQlAIXnEUEbymdgHzlLX8ruqvpyltIMjjaUjSTycc@Ji4K1dqb6KAljS43VleVMcUb41eNn5ZRJ4OhQmP68yxZvpTm2udpuvjcjsvFostUEtJS2pf5yrL@cCyr5gMaqdFxCkANG499OXQyEhY//hBPtHHILuoZDcbriSFHmj2Rc1bzphtjIclM@qGR9j1EMGgWxLWzc2/kdVScvE6iuO11Pb/jjT1ffX6IPX89nvgmj70DrcUHwkkr9G0LOt3WT4kuK8JYnYSpozFlZfxbGmYctxMn0NUyEyh34r2NFnwWBSxdlJCuYOaCpn8y0Fly3/PvdSQnA7EWmoPXJpm8SWJrkllSThc4y@EtX/cn96PnYIXcmkHuEs6N8emcknLuLJyVQdhuc8jcCQ4RTB03OnknVyp2BUKoBwB24K8BzeGtwLg2bNiCTjFGidVHYfS@ShjLKLal0TveSRq94@2kIWfJy2mR8aBQEmHoDFhU5OFivp10ejtKh9Latt8kp952cup9azkdfZ2cAE0EztKI6ngw2M10cMCW4tKT5X@WPNvNgI7@UwM62k4wR99aMI@@SjCzaBXNQiOWpzvJ5Ol2AlGT0K@2nunnnWzn0beynTe8uOrPYQOUEdapv424Hn1rcf3@VeIKP6VJTEeCth19jSltbU1myoxH@ddK7@jobxHf0dGW8vv9W8vvwdf5wWRWOvnD8e6i29IJqpnoH8nXyu3B3yK2B1tK7cG3ltr5tsnjDlm64fxKr0ARmhUsmTsU35Xs9stYHCva6fqzb0ayc3B5J@VhPNuJbnWOp4nuNxBN@wu8YDAHcV/B5Z/LdBEFvLAITuJtKLWPP4jGbm1bNkJtHd9DzYnemnE6f9f7RrxcmLpNvusF/oG3T8UVj9kJGGG4zDXpXRZdxgmlKon0JcobmNOjtcWG9x9h86mNmoO8Dm@n6/sZIJaoeTDQPLhr0IBs53gr2GOCPdkK9oRgH28F@5hgn2wF@4Rgn24F@5Rgv98K9nuC/WEr2B8I9setYH8k2J@2gv2JYBc13V2E8X2Wb46xq15XHjAok@@CMkHTult1t3cRBgO0Ws0ag@PxvbnoJWzS8zDlAB8lsYmSu8VIK0LS2Uw9ct3jIsThxkqDE4OJOnS4q36RiNMgiHM5eCNYgqTKmCc2Kx@1ZtCWsNHhrcCBhyECXF4niGaadIaT6pOxmboDbNoCqusvCKVOjPu5phu00Hu0Q7ljENayLIj/uFjxSSegwY1vBfgcvDBaO5JHlKc4o7gvoIuFdurXdKZCg1qBPafWoXyzDokTt28kWy0y8MBoAUJgeNROKUsOze2Vr3ePSmZ2p5SRI4Xsv0Q@JWHo/8/sFIv@ic3JEog4YquKfv4axkgRBC0BJM9QMdGCb8gSw@JjCB5lIEPLqrZ@hGta979q2gc68V4qoK0eOgEwNRT33etFEFc/UX2GGPEc6Bu6GmV8HEZohaDOWrxVVYSNlR7aALab0Xdn5kzcuiWSM1MOpFA6KcvLLCRW4@qFKXK1lsNb@nUDN52nY7MyhVWNp9vzDCZ9Ldmm0Xc0Z4CFvWPg4bFOajT8Mzy0r4@22cx64nrCGXfeCOqgGpw6mUxUBOTllY8HrijgOmNUj@JNUOONLrTZcKyt77Dkt1AOcw6O05zp0Ur0vusuvIsFSBWmgQwOYVTgjJNeknqOqegqDpNvh9mluCATq1XzykBh8Emb28WHO1pO4SnQ91epvgdzVvusvtZKQ6@3KehqEHNTJrXfFloF9rRyFaB4qvjCFwsmzbTCEM8wRGNrZopFmOGNZmQtEqFXbcNuWVzNtSO236QCz5mqQ8Fb8nuC8ukGn6M9oEZs@R/0PLIEYzP/lAmpK5Hl9jc6VofcDtoaYrWTA/ptrocq1dluy3Z8p/9pchs7uBtnYjWkYYP35n@MLZ3/wJtuy5N/7nZ7tsF6CdW7pmvN/N7jB@KrHfzV4ZHsMTmmFSW8l8ky5aIGzw4eI1mrJjNqBQ25SQ0O0Cow5@CqTVVsr/4sAY@sRQJQH40dI@Ogab@08Txqu@MoYl/6dyaIQO8y/IVjfWROKXprhw1EucuJ033Z3TZxy1aKpio3weF68aQ0aehTZklfo2jsw6gIa7li2IRJ568otQIVQrpVDlUCxbIcvR@5JRx38EepzT@SJBWngZAFcqyOjNZGE2XBB1ZkvZSlEYPtij7sogq2uZSDSjJEHetIlbC29HQip7VLTCXsWMNioyGPqjn0p0wNrPIceR6Baz5TLS1a/ZBFXfkdxrOhKBqRLWuBxuUZnkPOYRbFNYRfq42I5LyuZBMZOH4qgCmkaDfi32udhJnCFpLmeBdln0dZXmxWZqoDpCq2Sg0XLYaqSkJZxkWY5FKQvRJz9TxRND870wU0FYyi8sk5C7f4oapRG3ItQgCuzMowpcQqWEZVrCYW22kKFQEhUJ8kbXP4uWsv4O1eqmJDvmhHXYv94hQWfMJ4myNhtRXFuLvvcO7hQ2o8l2mS9rnhrqRsfyCsiOF1Uqb1Jjw6ZlOXuFc7EkfUUJy/sLKI03r3i4Ykw/hOCbIp0XDRDBrGXqjtkoJTFY@6@M3Qc9HAS4WmIRiYgS82D3zRNFCTeKEUdl8R@aJSmGnVAOrgcy2Cz7UKPhc6@lyb0n0zx@h6bOGHrwbca0tJdFWgFv6wXhc4wppco3ymQrc/jxbgSNBPn7OgT7aNIoh8U4CHB0LuTYTZjKos6RfyrDjcc0b2Zabibs60MrKPPBe1uiy/icQtBNEQLHipcNlugXCG4rhoTcXPp3t78zIOCJud/ZCLhMwHD4Tx5jLGnzRZfObiKmXLUj5Rv6fYFNPBpGuDSCPl2TgTGuT@hq2BdCV6C4JMxY0KjiNV01GTqN0V1bEvVkmZ22gw1hjFotXThrXLr4pf0JqheYQo3iWQyQLX4fd0z040ENxONLbNM@5JM6zM4bmHsUt@hPbHK0@XoEoiZDSuZR9/eVaSZ0im5EN/yuTDyj3Egu2CVDsNWDdONfRQNBZbzky8lZy0ESISkUTg8wdR0UrnrzKB0HkOjgWrVihcBYTthepwa/pFaiTW0d1TLzGGRsptSOgxW6q5Bcp/8Jte2@jTR223RFuuE1DA3WFtYfHEkhqBky4DBRb8olEadj1hWOLvE44JHRIDxbkNFc9EelOngxIgy9EoUvatNjG79i@wzTq83UQqwHrkxZCmELd@ijxiBJ311fxazT81oTU9Q9uLrR2D1PXmGdjbpyLj4tUGWhc4rwyQfZKF4DSzVT5PbzwszywCSlb13KIAmUrM5bs/8HuzMMv6H7OogC2dnATYMPr5xa/jc@ZZ0vEY/OfB2tNQH3Fbj0tAqy2ipUDxSDJbf4hBMOR99FpNcbNaSjVj1nXo1rsbesXoWwu1lpGUhVyGKJm2OWvvzMW2VU7K7aA@3RTPm7aSvL6NJIT4OoqQ0eaxgoieOVqB26bR3mm3jQfGKU@k352LXvWQS/vbI6QI9peGjJg9wG1rJJyicWuxe7sTs0cy2LckbmH7kS6UltFNlIw7MHRJq9dHHZUFyRs/61KOCMQ3OSpy2beEkqHGVeE67X6ZluGjolYgjwnEO0QpNwzUC1Fk0IpEjLoByzndY8zi1jNmByNy3yg02ucTk27IST9gJ@TNoY8YlLrU6manqQJzU4e5IRhq7nQ08kg90HDeyzUsvrYNC8SsA4kxMoKrvLFzRMPpXIykId/A/LOktzb9fv/AcrYH78VjMbtt8iF2Xw@hfXfRR5Ga25CvxZNZeXZD2dSQVcr/hTAcF0/eVspLejh8mHZH9qCc8NicndmuqXJT9PqdoSJK15DJ4HdAz58C@xHVwHefQrk4SWDESnzI0Q4I0L6QolVDkLr3aQK9aTBOMMKrlAFmO/p705Mwwx3rcdlea28jE8ws9oMG8@jnrooP8/7G8szy3bY62Vjwuw42xJ7bqntwDjdwqLgVAaZ5h7eISz3AETDYQlsdYwFqW/EOf/AWjZgxi3I@XYTi9HYt3we2PXxCYmn3q09hUJJFqBOQ/QO/wVSkfHG@6hsmyfON5z02x/VzMUzuq0/vzav1wLeZbN6vBWbhiNO8@a8PVSy9mFGZtIIkLbcVWpfSBZU6Pol5aHTX3F3I029LBpufq@Emg5jX1bqsXlg3BP07lMsdIfnvM/v5YXVzI@cVbp2OpJI0HwVjaQXQUklUk5QiX038F9kl5A3wPx2VSbHV3uexDM9RnJb4ZkwFaCtxgMFYEqJxtHK6rMY7g8t@Xk6FkNvgQ0/02zoOzPV6K2@4Z84oyZ4t9tp7EjkgNwMMiboQyJ3vRF4u1t/KmdHVB3OvY/FYzvHpYKxVzMpwbRKB0xz3IGJOxS4R7Lh6t2fg10LsMhI0XeQ9syThN5dRmJsECitaUPYFaFVOmjQrsYPlyTeQv@MjSDbuHOp3kNZxArFB1HIxTx8dcHFPovIUvFnhToEWb7jmHRk6Ox3rYqaWAzRPf//s3I11u1JgPz@nqISPBr88TMuz0y@T0z3dJkOWUQ7Iy9w3pz065jZWV@b8MhT6RhxuVECUz/7eyyTLwqAQQ0CxDm/VngBYsRrho@Znc9w38GV4zkZJSlvcMUwJGU/OphkHipLFHDR5FtI9D6c9WxRb4xrR9iCVxEE21g1oZxHSuPgsHnoVVzjRcgmb3d4CJtv7TQwH6nur1irMpgn@0RbyxTn@JQ15RMOE9cNGB4TC8OwMEEV4FQD7NrwQAKeXA478O/lyH3Y6@IYaNt46zoHbuWLfydqFPvtZGGSO@@LHGFXihP68DT6zmZH9qmVjVKVrZ5A42oPNDmONjymTcGRrDkFsqd6JB5Kdx3qL5vD9ZCz@VElvfmBMs5mUJz5zJ1Q3L4vwLcgUnaKN@bFIHZXOzjH28NkvAP3@cxy01bAu88pi3vtRHE6a6ODQIHL1J77vBuzmlURyJXrqBrJ2m2cT/80UOua5YfzOaUSs0GFYoqoXqbt/DCYpFzNSKuSm1Iz9if7TFXZOqz3F6Z7Yn4gvgP3ypbf6cgz7scfsCXvKvmc/sB/ZT@x48G8 "JavaScript (Node.js) – Try It Online") Braingolf's v2 interpreter doesn't have the "sandbox loop" `(.)` implemented yet, however due to more consistent modifier behavior, it's not needed for this challenge, as the greedy `&` modifier works directly on the prime factors `p` instruction, causing it to factorize every item on the stack. [Answer] # [Factor](https://factorcode.org/) + `math.primes.factors`, 32 bytes ``` [ [ factors ] map-flat members ] ``` [Try it online!](https://tio.run/##hZHBTsMwDIbve4qfB1jVZE3XgsQVceGCOE0cwuRBRNpGSTiMac9e3LTVViGEpRzi/7N/Wz7ofex8//L8@PRwi0bHj8x501DIDkkJ2HeNM5Z89hWNNdFQwCf5lizeqSWvrfnW0XRtQKAY4DzFeOQebcTdanWCgMQGBRRKbFGhhshxBscN1vc4JVmxdB7gnPWKPyWnChYk1y9hxdkZZrpGXV15JHYJCzHxqhAocwieYAspJ/aKH4BxmpHhyuSDOc1OPJLApkAxeC02EMNcYrQq0wrzU7@tZNpCTf0v8jImeICq/yCZsL@gS69@hx3m477yyd36YHVEQ80bDam@Rquds0dkfH1L2vc/ "Factor – Try It Online") * `factors` Get the prime factors of a number. * `map-flat` Apply a quotation to each member of a sequence, collecting the (non-scalar) results in a flat sequence of the same length. * `members` Remove duplicates. ]
[Question] [ Your challenge is to print the input, wait any amount of time, print the input, wait twice the time you initially waited, print the input again, and so on. The initial delay must be less than 1 hour, and you must have an accuracy of +/- 5% in the subsequent delays. Other than that, there is no restriction on the delay time. Example: Input: `hi`. Output: `hi` (1ms pause) `hi` (2ms pause) `hi` (4ms pause) `hi` (8ms pause) `hi` (16ms pause), etc. Also allowed: `hi` (1 minute pause) `hi` (2 minute pause) `hi` (4 minute pause) `hi` (8 minute pause) `hi` (16 minute pause), etc. Input must be provided at the start of the program (STDIN, command-line parameter, function param, etc.) and will be a string. The initial delay can't be 0. [Answer] # Scratch, 8 blocks + 3 bytes [![set [n] to [1]; forever { say [x]; wait (n) secs; set [n] to ((n) * (2)) }](https://i.stack.imgur.com/bAA0P.png)](https://i.stack.imgur.com/bAA0P.png) Equivalent in Python: ``` import time n = 1 while 1: print("x") time.sleep(n) n = n * 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes Code: ``` [=No.W ``` Explanation: ``` [ # Start an infinite loop = # Print the top of the stack without popping No # Compute 2 ** (iteration index) .W # Wait that many milliseconds ``` [Try it online!](https://tio.run/nexus/05ab1e#@x9t65evF/7/v0dqTk6@jkJ4flFOiiIA "05AB1E – TIO Nexus") [Answer] # Python 3, ~~60~~ 56 bytes ``` import time def f(x,i=1):print(x);time.sleep(i);f(x,i*2) ``` Changelog: * changed recursive lambda to recursive function (-4 bytes) [Answer] ## Mathematica ~~34~~ ~~32~~ ~~30~~ 29 Bytes Original solution 34 Bytes: ``` For[x=.1,1<2,Pause[x*=2];Print@#]& ``` Shave off 2 bytes with Do ``` x=1;Do[Pause[x*=2];Print@#,∞]& ``` Shave off one more Byte with @MartinEnder's recursive solution ``` ±n_:=#0[Print@n;Pause@#;2#]&@1 ``` @ngenisis uses ReplaceRepeated recursion to shave off another byte ``` 1//.n_:>(Print@#;Pause@n;2n)& ``` [Answer] # Octave, ~~42~~ 41 bytes ``` x=input('');p=1;while p*=2,pause(p),x,end ``` Saved one byte thanks to rahnema1, `p*=2` is shorter than `p=p*2`. I can't believe I haven't been able to golf this down, but it was actually not that easy. * The input must be in the start, so the first part is impossible to avoid. * I need a number that gets doubled, and it must be initialized in front of the loop + It would be possible to use the input as a conditional for the loop, but then I would have to have `p*=2` somewhere else. + Pause doesn't have a return value, otherwise it could have been `while pause(p*=2)` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` `[[email protected]](/cdn-cgi/l/email-protection) ``` The first pause is 2 seconds. Try it at [MATL Online](https://matl.io/?code=%60GD%40WY.T&inputs=%27Hello%21%27&version=19.10.0). Or see a [modified version](https://matl.io/?code=%60Z%60DGD%40WY.T&inputs=%27Hello%21%27&version=19.10.0) that displays the time elapsed since the program started. (If the interpreter doesn't work, please refresh the page and try again). Or see a gif: [![enter image description here](https://i.stack.imgur.com/OmY9h.gif)](https://i.stack.imgur.com/OmY9h.gif) ### Explanation ``` ` % Do...while G % Push input D % Display @ % Push iteration index (1-based) W % 2 raised to that Y. % Pause for that time T % Push true. This will be used as loop confition % End (implicit). The top of the stack is true, which produces an infinite loop ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 113 bytes ``` interface M{static void main(String[]a)throws Exception{for(int i=1;;Thread.sleep(i*=2))System.out.print(a[0]);}} ``` [Try it online!](https://tio.run/nexus/java-openjdk#DcyxDoMgEADQX2GEDqTtShybdOlkN@NwwbNeghyBs9oYv536Ae9VioJ5BI/qtRcBIa@@TIOagaJuJVP8dD0YmTKvRT02j0mI4z5y1qdV1Nyce08ZYbAlICZNl@ZuTPsrgrPlRWw6E9HQXXvjjqPW@sQQ@A8 "Java (OpenJDK 8) – TIO Nexus") -60 bytes thanks to Leaky Nun! [Answer] # R, ~~50~~ 48 bytes ``` function(x,i=1)repeat{cat(x);Sys.sleep(i);i=i*2} ``` returns an anonymous function which has one mandatory argument, the string to print. Prints no newlines, just spits `x` out on the screen. `i` is an optional argument that defaults to `1`, waits for `i` seconds and doubles `i`. *-2 bytes thanks to pajonk* [Try it online!](https://tio.run/nexus/r#S7P9n1aal1ySmZ@nUaGTaWuoWZRakJpYUp2cWKJRoWkdXFmsV5yTmlqgkalpnWmbqWVU@z9NQz1RXfM/AA) [Answer] # Ruby, ~~34~~ ~~28~~ ~~23~~ 22 (+2 for `-n`) = 24 bytes 3 bytes saved thanks to Value Ink! 1 byte saved thanks to daniero ``` loop{print;sleep$.*=2} ``` Starts at `2`, then `4`, etc. ### Explanation ``` -n # read a line from STDIN loop{ } # while(true): print; # print that line sleep$.*=2 # multiply $. by 2, then sleep that many seconds. # $. is a Ruby special variable that starts at 1. ``` [Answer] ## [Alice](https://github.com/m-ender/alice), 16 bytes ``` 1/?!\v T\io/>2*. ``` [Try it online!](https://tio.run/nexus/alice#@2@ob68YU8YVEpOZr29npKX3/39iUjIA "Alice – TIO Nexus") (Not much to see there of course, but you can check how often it was printed within one minute.) ### Explanation ``` 1 Push 1 to the stack. The initial pause duration in milliseconds. / Reflect to SE. Switch to Ordinal. i Read all input. ! Store it on the tape. / Reflect to E. Switch to Cardinal. > Move east (does nothing but it's the entry of the main loop). 2* Double the pause duration. . Duplicate it. The IP wraps around to the first column. T Sleep for that many milliseconds. \ Reflect to NE. Switch to Ordinal. ? Retrieve the input from the tape. o Print it. \ Reflect to E. Switch to Cardinal. v Move south. > Move east. Run another iteration of the main loop. ``` [Answer] # R, ~~44~~ 43 bytes [Crossed out 44 is still regular 44 ;(](https://codegolf.meta.stackexchange.com/a/7427/59530) [This answer](https://codegolf.stackexchange.com/a/119650/59530) already provides a decent solution, but we can save some more bytes. ``` function(x)repeat{cat(x);Sys.sleep(T<-T*2)} ``` Anonymous function taking practically anything printable as argument `x`. Starts at 2 seconds and doubles every time afterwards. Abuses the fact that `T` is by default defined as `TRUE` which evaluates to `1`. ~~Also, as long as [this comment](https://codegolf.stackexchange.com/questions/119636/pause-twice-as-long/119713#comment293167_119636) still gets a green light from OP, we can make it even shorter, but I don't think it is in the spirit of the challenge.~~ Wait times of 0 are not allowed anymore. ``` function(x)repeat cat(x) ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 30 bytes ``` /(?:u<q.;1A>?ou2$/r;w;q^_q.\*/ ``` [Try it here](https://ethproductions.github.io/cubix/?code=Lyg/OnU8cS47MUE+P291MiQvcjt3O3FeX3EuXCov&input=aGkK&speed=1000) This maps onto a cube with side length 3. ``` / ( ? # The top face does the delay. It takes the stack element with the : u < # delay value, duplicates and decrements it to 0. When 0 is hit the q . ; # IP moves into the sequence which doubles the delay value. 1 A > ? o u 2 $ / r ; w # Initiates the stack with one and the input. For input hi this ; q ^ _ q . \ * / . . . # gives us 1, -1, 10, 105, 104. There is a little loop that prints . . . . . . . . . . . . # each item in the stack dropping it to the bottom until -1 is hit. . . . # Then the delay sequence is started om the top face . . . . . . ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 37 bytes ``` for((t=1;;t*=2)){ sleep $t;echo $1;}; ``` For some reason TIO won't show the output until you stop the program execution. [Try it online!](https://tio.run/nexus/bash#@5@WX6ShUWJraG1domVrpKlZrVCck5paoKBSYp2anJGvoGJoXWv9//9/j9ScnHwA "Bash – TIO Nexus") [Answer] # PHP, 31 bytes ``` for(;;sleep(2**$i++))echo$argn; for(;;sleep(1<<$i++))echo$argn; ``` sleeps 1, 2, 4, 8, ... seconds. Run as pipe with `php -nR '<code>'` Will work until the 63rd print (on a 64 bit machine), after that there will be no more waiting. Version 1 will yield warnings `sleep() expects parameter 1 to be integer, float given`, Version 2 will yield one warning `sleep(): Number of seconds must be greater than or equal to 0`. Insert `@` before `sleep` to mute the warnings. [Answer] # TI-Basic, 21 bytes ``` Prompt Str0 1 While 1 Disp Str0 Wait Ans 2Ans End ``` [Answer] # Python 3, 61 bytes ``` import time;i=1;x=input() while 1:print(x);time.sleep(i);i*=2 ``` Similar to @L3viathan's golf, but uses `while` loop [Answer] # CJam, 26 bytes ``` qKes{es1$-Y$<{W$o;2*es}|}h ``` Doesn't work properly on TIO. The first pause is 20 milliseconds. **Explanation** ``` q e# Push the input. K e# Push 20 (the pause time). es e# Push the time (number of milliseconds since the Unix epoch). { e# Do: es1$- e# Subtract the stored time from the current time. Y$<{ e# If it's not less than the pause time: W$o e# Print the input. ;2*es e# Delete the stored time, multiply the pause time by 2, push e# the new time. }| e# (end if) }h e# While the top of stack (not popped) is truthy. e# (It always is since the time is a positive integer) ``` [Answer] # C, 51 bytes ``` main(c,v)char**v;{puts(v[1]);sleep(c);main(2*c,v);} ``` # C, 35 bytes as a function ``` c=1;f(n){puts(n);sleep(c*=2);f(n);} ``` Takes input as a command line argument. [Answer] ## Batch, 62 bytes ``` @set/at=%2+0,t+=t+!t @echo %1 @timeout/t>nul %t% @%0 %1 %t% ``` This turned out to be a byte shorter than explicitly doubling `t` in a loop: ``` @set t=1 :g @echo %1 @timeout/t>nul %t% @set/at*=2 @goto g ``` [Answer] # JS (ES6), ~~44~~ ~~42~~ ~~40~~ ~~38~~ 36 bytes Crossed out 44 is still 44 ``` i=1,y=x=>setTimeout(y,i*=2,alert(x)) ``` Don't like alert bombs? ``` i=1,y=x=>setTimeout(y,i*=2,console.log(x)) ``` Technically correct, but loophole-abusing: ``` y=x=>(x&&alert(x),y()) ``` -3 bytes thanks to Cyoce, -2 thanks to Business Cat, -2 thanks to Neil [Answer] # [Reticular](https://github.com/ConorOBrien-Foxx/reticular), 12 bytes ``` 1idp~dw2*~2j ``` [Try it online!](https://tio.run/nexus/reticular#@2@YmVJQl1JupFVnlPX/f0YmAA "Reticular – TIO Nexus") ## Explanation ``` 1idp~dw2*~2j 1 push 1 (initial delay) i take line of input d duplicate it p print it ~ swap d duplicate it w wait (in seconds) 2* double it ~ swap 2j skip next two characters 1i (skipped) d duplicate input p print... etc. ``` [Answer] ## C#, ~~80~~ 79 bytes ``` s=>{for(int i=1;;System.Threading.Thread.Sleep(i*=2))System.Console.Write(s);}; ``` *Saved one byte thanks to @raznagul.* [Answer] # Python 2, 54 bytes Uses a lengthy calculation instead of timing libraries. ``` def f(x,a=1): while 1:a*=2;exec'v=9**9**6;'*a;print x ``` [Answer] # PowerShell, ~~35~~ ~~33~~ ~~30~~ 29 Bytes With a helpful hint from whatever and Joey ``` %{for($a=1){$_;sleep($a*=2)}} ``` ## Explanation ``` %{ # Foreach for($a=1){ # empty for loop makes this infinite and sets $a $_; # prints current foreach item sleep($a*=2)# Start-Sleep alias for $a seconds, reassign $a to itself times 2 }} # close while and foreach ``` Executed with: ``` "hi"|%{for($a=1){$_;sleep($a*=2)}} ``` [Answer] # Python 3, 49 bytes ``` b=input();x=6**6 while 1:print(b);exec("x+=1;"*x) ``` Uses the slight delay of the `+=` operation and executes it `x` times. `x` doubles by adding one to itself as many times as the value of `x`. It starts at `6^6` (46656) to stick to the maximum of 5% variation in the delay. [Answer] # [Perl 6](https://perl6.org), 39 bytes ``` print(once slurp),.&sleep for 1,2,4...* ``` [Try it](https://tio.run/nexus/perl6#VY5dC4IwGEbv9yseyNSFTfqgC8WrCLoL@gNhOWGg29imEdFvNz@i6PZ5zzm8jeVod@yWkhlUy40RBYdTyIsCTtQcQpbK1LkTSpL6AU8b3grV2JTY5gpthHQIvQvFkwADMFoZpLqn/fLlEcfZdBxmf386H5Jk1MNwcpY/mLKydmEwZ5sSAY36/H/rk391U0DJG4etGqNpxHxbca7Rf41VtI62jLFF1x0FeQM "Perl 6 – TIO Nexus") (`print` overridden to add timing information) ## Expanded: ``` print( # print to $*OUT once slurp # slurp from $*IN, but only once ), .&sleep # then call sleep as if it was a method on $_ for # do that for (sets $_ to each of the following) 1, 2, 4 ... * # deductive sequence generator ``` [Answer] # Common Lisp, 49 bytes ``` (do((a(read))(i 1(* 2 i)))(())(print a)(sleep i)) ``` first delay should be `1` second. [Answer] # Pyth, 7 bytes ``` #|.d~yT ``` Explanation: ``` # Infinitely loop .d Delay for T 10 seconds ~y and double T each time | print input every iteration, too ``` [Answer] ## TI-BASIC, 36 bytes Initial wait period is 1 second. ``` 1→L Input Str1 checkTmr(0→T While 1 While L>checkTmr(T End Disp Str1 2L→L End ``` [Answer] # Racket, 51 bytes ``` (λ(s)(do([n 1(* n 2)])(#f)(displayln s)(sleep n))) ``` ## Example ``` ➜ ~ racket -e '((λ(s)(do([n 1(* n 2)])(#f)(displayln s)(sleep n)))"Hello")' Hello Hello Hello Hello Hello ^Cuser break ``` ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. The story continues from [AoC2017 Day 11](https://adventofcode.com/2017/day/11). [Obligatory why me and not Bubbler link](https://chat.stackexchange.com/transcript/message/59839491#59839491) --- After having rescued a child process lost on a hexagonal infinite grid, you hear someone else screaming for help. You turn around, and unsurprisingly, there is another program looking for its *own* child process. "Help! It's gotten lost in an infinite octagonal grid!" Well, it's not *all* octagonal, obviously. Instead, it's actually a [4-8-8 tiling](https://en.wikipedia.org/wiki/Truncated_square_tiling): ![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/a5a2ff6c3d34fb5c64a446fe1561da5872821f00/images/PuzzlingSE/Misc/aocg2021_11.svg) An octagonal tile (X) has eight neighbors, indicated by eight directions (N, NE, E, SE, S, SW, W, NW). A square tile (Y) has only four neighbors in cardinal directions (N, E, S, W). The program gives you the path taken by the child process. The initial tile is an octagon. You try following the directions one by one, and ... something's wrong in the middle. "Look, it can't move diagonally from a square tile, you see?" Given a sequence of movements, determine if it is valid on the 4-8-8 grid, assuming the initial position of an octagon. **Input:** A list of strings entirely consisting of `N`, `NE`, `E`, `SE`, `S`, `SW`, `W`, `NW`. Or a single string containing these strings with a single delimiter (space, comma, newline, or any other char that is not one of `NESW`) in between. (If the input is `["N", "E", "NW", "NE", "E", "SE"]` then you can take it as e.g. `"N,E,NW,NE,E,SE"`) **Output:** A value indicating whether it is valid or not. You can choose to * output truthy/falsy using your language's convention (swapping is allowed), or * use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases Truthy: ``` [] ["S"] ["SW"] ["N", "E", "NW", "NE"] ["NE", "SE", "SW", "NW", "N", "E", "S", "W"] ``` Falsy: ``` ["N", "E", "NW", "NE", "E", "SE"] ["NE", "SE", "N", "E", "S", "SW", "NW", "W"] ["N", "NW"] ``` [Answer] # Regex (any), 27 bytes ``` ^((.\n.\n)*..\n?)*(.\n)*.?$ ``` Matches valid strings, taking input as a newline-separated string. There's probably a way to golf this regex. This version thanks to @AnttiP. # Javascript, 34 bytes ``` /^((.\n.\n)*..\n?)*(.\n)*.?$/.test ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFfP05DQyMmOCZYQVMLRFQb1WpqIQmAWPp6JanFJf81lPxcFYJdFfwUgJRCcLiCX7hCuJKm5n8A "JavaScript (Node.js) – Try It Online") ``` ^ From the start... ( )* Match 0+ times... ( )* Match 0+ times... .\n.\n A pair of 1-char strings ..\n? Followed by a 2-char string with possible separator (in case this is the end) ( )* This block will match 2-char strings until the end as long as the 1-char strings are paired (.\n)* Match any amount of . after this .?$ Match possible trailing . at the end ``` This relies on the fact that length 1 strings modify the parity of whether we're on an octagon or square, and whether diagonal (length-2 strings) are valid. ## Old version, 35 bytes ``` ^(((\S\S )*\S ){2})*(\S\S )*\S \S\S ``` Matches invalid strings, taking input space-separated. ``` ^ From the start... (( ){2})* Match an even number of times... (\S\S )* Possibly any amount of length-2 strings \S Followed by a length-1 string (\S\S )* Possibly match any amount of length-2 strings \S \S\S Match a length-1 string followed by a length-2 string. ``` [Answer] # [Python 2](https://docs.python.org/2/), 45, 44, 36 bytes (@Jonathan Allan) ``` lambda a:`a.title()`[1::2]>`a`[1::2] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHRKiFRrySzJCdVQzMh2tDKyijWLiERyvqfll@kUJJaXKKQmacQw6UABRrRsXC2TrRSsBIqNxyV76eko6DkCiL8wsGkK5o8WC4YQoYjqYPrCwYRhE2FK8djAZqhyPZhs8APWVDTCswsKMrMK9EAhYqOgrqunbqOQpqGUkyMkl5WfmYeWFxTU/M/AA "Python 2 – Try It Online") #### Older versions ``` lambda a:repr(a.title())[1::2]>repr(a)[1::2] ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHRqii1oEgjUa8ksyQnVUNTM9rQysoo1g4iCuX9T8svUihJLS5RyMxTiOFSgAKN6Fg4WydaKVgJlRuOyvdT0lFQcgURfuFg0hVNHiwXDCHDkdTB9QWDCMKmwpXjsQDNUGT7sFnghyyoaQVmFhRl5pVogEJFR0Fd105dRyFNQykmRkkvKz8zDyyuqan5HwA "Python 3.8 (pre-release) – Try It Online") ``` lambda a:(A:=repr(a.title())[1::2])>A.upper() ``` [Try it online!](https://tio.run/##hVCxCsIwEN39iiNLcxAL6iKBFjp07dKhQ9MhYoqVmoYYB78@0iilLaI3PO7de3cPzjzdZdCHo7G@TYTv5e10liA5zXhilbFUxq5zvaKI9Y7zfYNpFj@MUZaibwcLTt0ddBrEBj5F62bqWU1KsqTVkheEAclHKKqA@UoPWvnGauab9soR/l@d7D8CVkfned8CivkQeWiN7bSj41cYRNs0YtBSIgSJr0OnwxwR/Qs "Python 3.8 (pre-release) – Try It Online") #### Explanation (all versions) This expects a backslash- (or tab- or newline-) separated string and returns True for invalid and False for valid paths. It works by detecting odd-length stretches of single-character commands followed by at least one double-character command. The idea is essentially: if we had `X` for principal directions and `XY` for the others we could just concatenate take every other character and check for `Y`s. Almost as good is to `title`-case the input string which puts a capital instead of `X` and a small instead of `Y`. Now, I found no cheap way of getting rid of the delimiter, but almost as good we use backslash or tab or newline and apply `repr`. This replaces each separator with its two-character escaped representation such that they do not interfere with parity. It remains to check for any lowercase letters which we do by comparing with `upper` whether any differences with the non title cased inputs have survived the skipping step. [Answer] # [R](https://www.r-project.org/), ~~46~~ ~~43~~ 42 bytes *Edit: -1 byte thanks to pajonk* ``` function(s)any(cumsum(x<-nchar(s))%%2&x>1) ``` [Try it online!](https://tio.run/##K/qfl19SlpiTmWL7P600L7kkMz9Po1gzMa9SI7k0t7g0V6PCRjcvOSOxCCiqqapqpFZhZ6gJ16SRrKGpyYXEUwpWQhcIRxfxU9JRUHIFEX7hYNIVQwVYNhhChiOphOsMBhHEmAzXgNcSNIOR7cRuiV84Fn/CDAJL/gcA "R – Try It Online") Function `notvalid`: outputs `TRUE` if the path is not valid, `FALSE` if it's a valid path. **How?** If the path is valid, then 2-character moves (that can only be from an octagon) always move to an octagon; 1-character moves flip between octagons & squares. So, we're in a square if we've had an odd number of 1-character moves. Invalid moves are attempted 2-character moves from squares, so we need to check if any of these co-incide with positions after an odd number of 1-character moves. `any(...)` = is this question TRUE value at any position: `cumsum(x)%%2` = have we had an odd number of 1-character moves? `&x>1` = and, if so, is x currently 2? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ẈÄPƝḂẸ ``` A mondadic Link that accepts a list of lists of characters and yields `0` if valid or `1` if invalid. **[Try it online!](https://tio.run/##y0rNyan8///hro7DLQHH5j7c0fRw147/h9sfNa35/z86OpZLJ1opWAlChUNoPyUdBSVXEOEXDiZdoeJgsWAIGY4kD1cfDCJwmwJXhsVANEOQzUc20A/EiQUA "Jelly – Try It Online")** ### How? The only way to reach a square is via a sequence of an odd number of cardinal directions, after which if a diagonal direction is given the input is invalid. The cardinal directions are length one, while diagonal ones are length two. Thus if the cumulative sum of lengths of the input contains two odd numbers in a row it is an invalid instruction. ``` ẈÄPƝḂẸ - Link: instuctions Ẉ - length of each instruction Ä - cumulative sums -> odd when taken to a square given a valid prefix Ɲ - for neighbours: P - product (only odd * odd is odd) Ḃ - is odd? (vectorises) Ẹ - any? ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~33 32~~ 29 bytes ``` ->l{l.all?{|y|y[1]?l:[l=!l]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkcvMSfHvrqmsqYy2jDWPscqOsdWMSe2tvZ/gUJatJKSXnFBTmaJhr2OZiwXWCQYi1A4ppifjquOX7iOnysWKVedYCAKB8sDlQXroOrnUlYIz1fILC5RyE3NzEtVyE3MTUQzFKQLp8kQMyHmY3WZH4rofwA "Ruby – Try It Online") Look ma, no regex! ### How? Reuse l as a flag that is initialized with a truthy value, and translates as true->octagon, false->square. The sequence is invalid if we have to move diagonally (y[1] is true when y is 2 characters long) from a square (l is false). If y is only 1 character, we are moving from an octagon to a square or viceversa, so we have to flip the flag. This is enclosed in an array to make the operation return a truthy value. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` vL:‹$¦∷*a ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ2TDrigLkkwqbiiLcqYSIsIiIsIltcIk5FXCIsIFwiU0VcIiwgXCJTV1wiLCBcIk5XXCIsIFwiTlwiLCBcIkVcIiwgXCJTXCIsIFwiV1wiXSJd) There's got to be a better way to do this. Outputs reversed - 1 for invalid, 0 for valid, ``` vL # Lengths ¦∷ # Cumulative sums modulo 2, tracking when on a square and when not $ * # Multiplied by :‹ # Those same lengths decremented # Each one is only true when on a square *and* trying to move diagonally # Which is invalid a # Are any true? If so, there's an invalid one somewhere. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes ``` ⬤θ›³⁺﹪L⪫…θκω²Lι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEfBvSg1sSS1SMNYRyEgp7RYwzc/pTQnX8MnNS@9JEPDKz8zT8O5Mjkn1TkjvwCkPltTR6FcE0gYATFUVaYmCFj//x8dreTnqqSjoBQMIcNBpB@EBBEQURARrhQb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for valid, nothing for invalid. Explanation: An input is valid if the cumulative length modulo 2 plus the length of the current item never exceeds 2. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 bytes ``` ^(\w,?($|\w($|,)))*$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP04jplzHXkOlJqYcSOhoampqqfz/zxXMFRzO5afjquMXruPnyuXnqhMMROFgLlA0WAdJFsSHKYFIQhSClPiFAwA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The regular expression only matches valid movements, i.e. those that only contain paired or trailing orthogonal directions. 18 bytes if newlines are allowed as separators: ``` ^(.¶?($|.($|¶)))*$ ``` [Try it online!](https://tio.run/##K0otycxL/K@qEZyg8z9OQ@/QNnsNlRo9ID60TVNTU0vl/3@uYK7gcC4/HVcdv3AdP1cuP1edYCAKB3OBosE6SLIgPkwJRBKiEKTELxwA "Retina 0.8.2 – Try It Online") Link includes test suite that splits on comma for convenience. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 32 bytes ``` a->t=0;[t=[1-t,t*x][#d]|d<-a];t' ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXrsTWwDq6xDbaULdEp0SrIjZaOSW2JsVGNzHWukT9f2JBQU6lRrGCrp1CQVFmXgmQqQTiKCmkaRRrauooREfHAgmlYCUIFQ6h/ZR0FJRcQYRfOJh0hYqDxYIhZDiSPFx9MIjAbQpcGRYD0QxBNh/ZQKBIbKzmfwA "Pari/GP – Try It Online") Here `t` is the state of the current tile: `0` means octagon, `1` means square. When the direction has length 1, we just set `t` to `1-t`. If the length is 2, we multiply `t` by `x`, so `0` remains `0`, while `1` becomes a polynomial. If `t` is a polynomial, `1-t` and `t*x` are also polynomials. So invalid states are represented by polynomials. Finally, we take the derivative of `t`. The derivative of a constant is `0`, which is falsy. The derivative of non-constant polynomials are truthy. [Answer] # [Python](https://docs.python.org/3.8/), ~~48~~ 47 bytes ``` f=lambda a,o=1:o>1or a and f(a[1:],len(a[0])-o) ``` A recursive function that accepts a list of strings and returns an empty list (`[]`) if the input is valid or `True` if not. **[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRIVEn39bQKt/OML9IAcjLS1FI00iMNrSK1clJzQOyDGI1dfM1/6cBpUtSi0sUMvMUYrgUoEAjOhbO1olWClZC5Yaj8v2UdBSUXEGEXziYdEWTB8sFQ8hwJHVwfcEggrCpcOV4LEAzFNk@bBb4IQtqWoGZBUWZeSUaoFDRUVDXtVPXAQYdiKep@R8A "Python 3.8 (pre-release) – Try It Online")** ### How? `a` is our list of instructions. `o` starts off as `1` (`,o=1`) and is a flag that indicates whether we are on an octagon (`1`) or square (`0`), this is updated for the next iteration by subtracting the current flag value from the current instruction length (`len(a[0])-o`). If we try to go diagonally from a square then `o` becomes `2` (since \$2-0=2\$) and then the next iteration's evaluation of `o>1` causes a return value of `True`. We drop the first (now executed) instruction from `a` (`a[1:]`) in order to perform the next iteration and if we find ourselves with an empty list the instructions were valid and `or a` causes this empty list to be returned. [Answer] # [R](https://www.r-project.org/), 55 bytes ``` f=function(x,o=1)o>1||length(x)&&f(x[-1],nchar(x[1])-o) ``` [Try it online!](https://tio.run/##K/qfZgtEaaV5ySWZ@XkaFTr5toaa@XaGNTU5qXnpJRkaFZpqamkaFdG6hrE6eckZiUVAtmGspm6@5v80DRA/MbkktUjDQFOTC8jXUApWgrPC4Uw/JR0FJVcQ4RcOJl0RUmDhYAgZjqQEriUYROA1C64Su7FoRiHbgmasHxIf4Qqw6H8A "R – Try It Online") Port of [@Jonathan Allan's recursive answer](https://codegolf.stackexchange.com/a/238417/55372). Outputs flipped `TRUE/FALSE`. [Answer] # [Rust](https://www.rust-lang.org/), 80 56 bytes ``` |p:&[&str]|p.iter().fold(0,|a,b|a+a%b.len()^b.len()&1)<2 ``` [Try it online!](https://tio.run/##lVE9T8MwEN3zKy6WsGzVpMDYFpi6dsmQIQrIBVuyZNxgOzA0@e0hdqOoRGoRN7yT796HpbON87008MGVIRSOCQylhQcJj9C39QqX2HlbtXWmvLCEZvKg38kdaznbt3zBb/aZFoP0Zez4nm4e@uCyTqKZPFggytSNZ8CN@xaWgjKAy7gNRb7EW1pWDLxtBGWzOcrR5VVxebdDDNA2wK6IuL3Cjbz8hMWZZvLIA/wvbZLGYMm1@yN5lnb@keKaxUibMarxmKFqq4zXJiXouHru4PYJQh90v@@yngTLJXDnhPXpNDq9X8VnSrAkOCrpTNolXf8D "Rust – Try It Online") * -24 bytes by using fold and boolean operations (thanks @AnttiP) [Answer] # Python3, 82 bytes: ``` f=lambda x,s=0:((b:=len(x[0])==1)or s%2==0)and f(x[1:],s+b)if x else s%2==0 or s<2 ``` [Try it online!](https://tio.run/##dYw9C4MwFEX/yltK8mgGtUuRvtHVxcFBMkQ0VEhjMA7216d@IVLa5Vy493Lce3z29nZ3QwiajHrVjYJJeIpSzuuUTGv5VEUSiWLsB/CXhChCZRvQ8xCnUvhrjZ2GCVrj2/0Ay/WRBDd0duSm8yN/Kce1gKqSM1jBtii3zJkAli3Iy5XZ3q9dsbE87ce/WPDfctx@CL8kZ/9ZODdSImL4AA) [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 13 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ∨˝2|·×⟜»·+`≠¨ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oioy50yfMK3w5fin5zCu8K3K2DiiaDCqAoK4o2JKOKKouKJjcK3PkbCqCkg4p+o4p+o4p+pCuKLiCJTIgrii4giU1ciCiJOIuKAvyJFIuKAvyJOVyLigL8iTkUiCiJORSLigL8iU0Ui4oC/IlNXIuKAvyJOVyLigL8iTiLigL8iRSLigL8iUyLigL8iVyIKIk4i4oC/IkUi4oC/Ik5XIuKAvyJORSLigL8iRSLigL8iU0UiCiJORSLigL8iU0Ui4oC/Ik4i4oC/IkUi4oC/IlMi4oC/IlNXIuKAvyJOVyLigL8iVyIKIk4i4oC/Ik5XIuKfqQ==) Exact port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/238414/64121). There are a few things that can be varied, e.g. [`1∊1‿1⍷·≠`2|≠¨`](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKIijHigL8x4o23wrfiiaBgMnziiaDCqAoK4o2JKOKKouKJjcK3PkbCqCkg4p+o4p+o4p+pCuKLiCJTIgrii4giU1ciCiJOIuKAvyJFIuKAvyJOVyLigL8iTkUiCiJORSLigL8iU0Ui4oC/IlNXIuKAvyJOVyLigL8iTiLigL8iRSLigL8iUyLigL8iVyIKIk4i4oC/IkUi4oC/Ik5XIuKAvyJORSLigL8iRSLigL8iU0UiCiJORSLigL8iU0Ui4oC/Ik4i4oC/IkUi4oC/IlMi4oC/IlNXIuKAvyJOVyLigL8iVyIKIk4i4oC/Ik5XIuKfqQ==) works at the same length, but I couldn't find anything shorter. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39~~ 34 bytes ``` ->i{/^((.,){2}*(.\w,)*)*.,.\w/!~i} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6zWj9OQ0NPR7PaqFZLQy@mXEdTS1NLTwfI0lesy6z9X6CQFq2kFMsFpoPhjHAYy0/HVccvXMfPFS7gqhMMROFgUaBksA5IrbJCWmJOcSWaHpA0mkaIFoh2JEv8gOz//wE "Ruby – Try It Online") Method takes string with commas and returns true if the path is valid. The regexp looks for invalid path which is essentially an odd one-letter direction followed by a two-letter. Thanks to ovs for very useful suggestions and -5 bytes! Another less golfy but more interesting for me version doesn't work on TIO but takes arrays instead of strings and is 54 bytes: ``` f=->t{c=0;t.chunk{_1[1]?1:2}.all?{2>c+=_1*c+_2.size%_1}} p f[[]] p f[["S"]] p f[["SW"]] p f[["N", "E", "NW", "NE"]] p f[["NE", "SE", "SW", "NW", "N", "E", "S", "W"]] # falsy p f[["N", "E", "NW", "NE", "E", "SE"]] p f[["NE", "SE", "N", "E", "S", "SW", "NW", "W"]] p f[["N", "NW"]] ``` [Answer] **Turing Machine Code, ~~97~~ 77 bytes** ``` 0 _ _ r halt 0 * * r 1 1 _ _ r 2 1 * * r 3 2 * * r 3 3 _ _ r 0 3 * * r halt-r ``` [Try it online](http://morphett.info/turing/turing.html?05ec4019351b477aa51076226bd57fae) Takes space-separated input, thanks to AntiP for saving 20 bytes Haven't tested on my Java implementation yet [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ṁ%2Ẋ*∫mL ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY2qRg93dWk96lid6/P////o6FidaKVgJTAZDqb8lHSUXIHYLxxEuELEQALBYCIcLgVVFwzE2HVC5dGNQNaIMA5hBJAbGwsA "Husk – Try It Online") Approach based on [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/238414/95126). Outputs zero (falsy) for valid paths, non-zero (truthy) for non-valid paths. ``` mL # get the lengths of the input strings ∫ # and calculate the cumulative sum # (so odd numbers indicate we're in a square) Ẋ* # product of all adjacent pairs # (so odd numbers indicate a 2-character move # attempted from within a square) ṁ%2 # map 'modulo 2' to all elements (gets odd numbers) # and output sum (non-zero if any elements were odd) ``` [Answer] # Thue, 84 bytes ``` @::=::: S::=N E::=N W::=N aN,::=b aNN,::=a bN,::=a a,::=~1 b,::=~1 bNN::=~0 ::= a@,, ``` Takes comma-separated input [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` FreeQ[Or@@StringLength@#/. 1||1->3,1||2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9@tKDU1MNq/yMEhuKQoMy/dJzUvvSTDQVlfT8GwpsZQ185YB0gbxar9DwBKl0QrK@jaKaRFK8fGKqgp6DtwVVfX6nApVCsFK0HpcCjDT0lHQckVRPiFg0lXmARYMBhChiMpgGsIBhF4zIGrw2YkmjHINqAYCRSqrf0PAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # TypeScript Types, 107 bytes ``` type M<T,A=1,B=0,D="N"|"S"|"E"|"W">=T extends[infer C,...infer T]?C extends D?M<T,B,A>:A extends 1?M<T>:0:1 ``` Finally, one that didn't benefit from `//@ts-ignore`! [Try It Online!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAsgPAFQDQEEC8BGJAhNAGJAETQCIA5EgHxIGUqSBRegdRID40EoIAPYCAHYATAM4BtAJYCAZhABOUAMJIAdGqmyFCALoB+Rdz6DRUQrvjJsqNgC4Uh-sJFQM5xLbw2MAKG+hIUAh4UGiwcGLabN4A9NFQ8QB6un7g0AgYIWFitCSRMXGJyf5pAEyZ8Nk0rHmx8VBJKQEIAMzl4eQkSFCMnd1krF3kTDUF9UWpgQAsbdlkTIM0891VveQDfatLOYPVUbWFvsVQAGLBoRUdg1v9q3Obq4u5e6MNR8cZ5+13C9f3Cw-rNarXb5OqvCbHMqfWa3EH7MbeIA) ## Ungolfed / Explanation ``` // DiagA: whether non-orthogonal moves are currently allowed // DiagB: wtherer non-orthogonal moves are allowed in the other type of cell type Main<Arr, DiagA = 1, DiagB = 0, OrthoDir = "N" | "S" | "E" | "W"> = // Check the first string in Arr Arr extends [infer Dir, ...infer Rest] ? Dir extends OrthoDir // If it's orthogonal, switch the type of cell ? Main<Rest, DiagB, DiagA> : DiagA extends 1 // Otherwise, if diagonals are allowed, move into an octagonal cell (the default) ? Main<Rest> // Otherwise, return false : 0 // The array is empty; return true : 1 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ηJ€gü*Éà ``` Input as a list of strings. Outputs `1` for invalid grids and `0` or an empty string `""` for valid grids (only `1` is truthy in 05AB1E, so this falls under the "*output truthy/falsy using your language's convention (swapping is allowed)*" rule). Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/238414/52210). [Try it online](https://tio.run/##yy9OTMpM/f//3HavR01r0g/v0TrceXjB///RSn5KOkquQOwXDiJcobxgV6VYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c9u9HjWtST@8R@tw5@EF/3X@R0fH6kQrBSuByXAw5aeko@QKxH7hIMIVIgYSCAYT4XApqLpgIMauEyqPbgSyRoRxCCOA3NhYAA). **Explanation:** ``` η # Get the prefixes of the (implicit) input-list J # Join each inner prefix-list together to a single string €g # Get the length of each string ü # For each overlapping pair: * # Multiply them together É # Check for each whether it's odd à # And check if any were odd by leaving the maximum # (after which the result is output implicitly) ``` Empty or single-item inputs are `[]` after the `ü*`, which is why they result in an empty string `""`. ]
[Question] [ You are given two strings \$a\$ and \$b\$ consisting of characters from a to z in lowercase. Let \$n\$ be the length of \$a\$. Let \$m\$ be the length of \$b\$. Let \$a'\$ be the string \$a\$ repeated \$m\$ times. Let \$b'\$ be the string \$b\$ repeated \$n\$ times. Check whether \$a'\$ is lexicographically less than \$b'\$. Test cases: ``` a b ---> true ac a ---> false bekcka kwnfoe ---> true beztbest bestbe ---> false mcjaf mc ---> true akboe uenvi ---> true ``` Shortest code wins. Hint: there's a 13-byte JavaScript solution. Beat that! Competitive answers use the `a+b<b+a` approach. A proof of this approach can be found at <https://codeforces.com/blog/entry/91381?#comment-808323> [Answer] # [Python](https://www.python.org), 18 bytes ``` lambda a,b:a+b<b+a ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY9dDoIwDMffd4pmTyDDZ0PEk5CYFrc4B4OMoehVfCExegAv4Rm8jZA9SB_atP39-3F_tVd_bOz4UHnx7L1KN-8KazogoKAME9pSgqHx_QyQA-ccgSBN0x1410uGJWBIFVadZCRNaRDMxapGLjiSN0-y8zA7kktJXZ5QQV0upxqa1L20Z_2vTrvXXVtpH_HC8pgx1bj5TrHaCwfaQo1t1HkXIDHEGYPJWqetj1Q0kbFwMQvvjGOIPw) ### How? \$a+b \lesseqqgtr b+a \quad\Leftrightarrow\quad a+a+b \lesseqqgtr a+b+a \lesseqqgtr b+a+a \quad\cdots\quad\Leftrightarrow\quad m\times a+b \lesseqqgtr b+ m\times a \quad\Leftrightarrow\quad m\times a+b+b \lesseqqgtr b+m\times a+b \lesseqqgtr b+b+ m\times a \quad\cdots\quad\Leftrightarrow\quad m\times a+n\times b \lesseqqgtr n\times b+ m\times a \quad\Leftrightarrow\quad m\times a \lesseqqgtr n\times b\$ [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Let's give these strings some oo`ṁÞƑ` :) ``` ṁÞƑ ``` A monadic Link that accepts a pair of lists of characters, \$[b, a]\$, and yields `0` when \$a'=a\times n\$ is lexicographically less than \$b'=b\times m\$ where \$\times\$ is "repeat" or `1` if not. i.e. takes the strings in reverse order and results in the negative. **[Try it online!](https://tio.run/##y0rNyan8///hzsbD845N/P//f7R6YlKyuo4CiAKhZPVYAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hzsbD845N/P9w95ZDWx/u2PRw56zD7Q93dz9qmOOWmFOcCqRDikqB1FwdhywgR8HWTgHI0Yz8/z9RIYkrMVkhkSspNTs5O1EhuzwvLT8VyKsqSUotLlEAEUmpXLnJWYlpCrnJXInZSfmpCqWpeWWZXIkKicnJIO3JSQqJAA "Jelly – Try It Online"). ### How? We actually only need to check the first up to \$m+n\$ characters of the two augmented strings. This gets these by moulding each string like the input pair, e.g. `['ab', 'xyz']` gives `['ab', 'aba']` and `['xy', 'zxy']`. There is no need to flatten these before comparing them since their relative sort order is unaffected due to them having the same shape as each other. ``` ṁÞƑ - Link: pair of strings, X = [b, a] Ƒ - is X invariant under?: Þ - sort (the elements, e, of) X by: ṁ - (e) mould like (X) ``` ### Worked Example ``` a = 'abcdefgh' -> n = 8 b = 'pqrst' -> m = 5 X = [b, a] = ['pqrst', 'abcdefgh'] b ṁ X = ['pqrst', 'pqrstpqr'] ...this is the first n+m=13 characters of b', 'pqrstpqrstpqrstpqrstpqrstpqrstpqrstpqrst', split after m = 5 characters a ṁ X = ['abcde', 'fghabcde'] ...this is the first n+m=13 characters of a', 'abcdefghabcdefghabcdefghabcdefghabcdefgh', split after m = 5 characters (a ṁ X) < (b ṁ X) so the sorting, `ṁÞ`, reverses X checking for invariance with `ṁÞƑ` therefore gives 0 indicating that a' < b' ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 13 bytes ``` a=>b=>a+b<b+a ``` [Try it online!](https://tio.run/##BcFRDoAgCADQu/Clc3WC8C5g6AonLVsdn9476aVZ7uN6lmG7eEUnzIyZEm@cyIuNaV3Wbi3UACxalCAG0G9UE4jRfw "JavaScript (Node.js) – Try It Online") Probably the 13 byte JS solution mentioned in the challenge. Ports loopy walt's Python answer. [Answer] # [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes ``` f=AlphabeticOrder[#<>#2,#2<>#]& ``` [Try it online!](https://tio.run/##Lc5BCsIwEAXQvacICXQVCHSrFT2AKG5LF5M4oTGmLWmsYOjZY9O6@vMfDHwHoUUHwShISVfn19CCxKVe/QN9zQ5HVnJWLtEUaQDjR1KRGClY2SPlhL6xmwydOYnUqSfobE4tEKnEb5A4hkw5Jf7ZKgsZ7afT/YagMsB2rw90noW444R@xP3uAkOtyelEGCk4WYc0Qty86UL6AQ) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ₌Jp> ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwi4oKMSnA+IiwiIiwiXCJhXCIsIFwiYlwiID0+IDFcblwiYWNcIiwgXCJhXCIgPT4gMFxuXCJiZWtja2FcIiwgXCJrd25mb2VcIiA9PiAxXG5cImJlenRiZXN0XCIsIFwiYmVzdGJlXCIgPT4gMFxuXCJtY2phZlwiLCBcIm1jXCIgPT4gMVxuXCJha2JvZVwiLCBcInVlbnZpXCIgPT4gMSJd) A port of python is one byte shorter because of the niceness of parallel apply. ## Explained ``` ₌Jp> ₌ > # check whether J # the joining of the two strings > # is greater than p # the prepending of the two strings ``` For a more straightforward approach: ## [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` @Ṙ*ƒ< ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJ+IiwiIiwiQOG5mCrGkjwiLCIiLCJbXCJhXCIsIFwiYlwiXSA9PiAxXG5bXCJhY1wiLCBcImFcIl0gPT4gMFxuW1wiYmVrY2thXCIsIFwia3duZm9lXCJdID0+IDFcbltcImJlenRiZXN0XCIsIFwiYmVzdGJlXCJdID0+IDBcbltcIm1jamFmXCIsIFwibWNcIl0gPT4gMVxuW1wiYWtib2VcIiwgXCJ1ZW52aVwiXSA9PiAxIl0=) Takes input as a list of strings. ## Explained ``` @Ṙ*ƒ< @ # vectorised lengths Ṙ* # reverse that, and pairwise repeat the input strings that many times ƒ< # reduce by lexographic less than ``` [Answer] # [Julia 1.0](http://julialang.org/), 11 bytes ``` a\b=a*b<b*a ``` [Try it online!](https://tio.run/##TU1LDoIwFFzbU8wSCCzcW2M8hwl5rzySQimmLUq8PNaYKJtJ5j8sztJx3Ta6saaKT1zR1s8BSWJqDUWB9QhCnbNeYlGqA9XgGm2NFRrx7mwqfuFsXyhGCQl5EFrjTiFKcZ1nV6@lEt9tBEbTNGeksIgiA/rSnlwUxTKakTA@fT/LLsfySpxv8AGWfWUyA/WYzH515NxexD/sX30D "Julia 1.0 – Try It Online") Another port of loopy walt's [Python answer](https://codegolf.stackexchange.com/a/259989/97916). [Answer] # [Go](https://go.dev), 36 bytes ``` func(a,b string)bool{return a+b<b+a} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDBSsQwFMRj8xWPItKyqbh4EbEePQt71MV9qUmJTZOSpCu47Jd4KYIftX6NSbu6vSQzyczLZD6_ajMclh1WDdYcWpSayLYz1l-movXpP3HeSl27lGzRgii_ey-Km8O56HWVIWUw3efMGLWz3PdWAy7YHVvgftL-nF1E8fhElsOOOAe3JWwQGBRFcQ_e9pxgBThRgcpxwngTkkHzroXhMx3jH55x5yEujM8tbfWGAtpqPrVhwd1zvZWn0w0RxsILVVLzmMSiDg2sOiV95hyF9FmnMWciJFevY9iHEWXRkZMkfJuOzknwdLWmf3B5gtdrktioWnWhIZ-JWFce7I-RKh0ptRRsWYahe3Ksaxim_Rc) Port of Loopy's Python answer. ### [Go](https://go.dev), 81 bytes ``` import."strings" func f(a,b string)bool{return Repeat(a,len(b))<Repeat(b,len(a))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDBSsQwFMRj8xWPHqSBVBQvItajZ3WPurhJ96XEpklJUgWX_RIvi-BH-Cn6NSbtLttL8mbyZjLM51djdz89r1veIHRcGaK63rpwlssu5N9DkOXV78OB88Ep0_icyMHUIAvOBEwcFdbqjcMwOAOP2CMP8VWjKQSlN3tCjASndDsZ_52cjkbp34LChngP1xWsOAgoy_IWghuQ8Br4BCXXHonANsaF9t1Ii7M9gR9BoA-QDoFzSVe_cgldPXdtRVQPaN7UkV0RaR28MK0MpiSOm1jLotcqFN4zyJ9NnnJmUqFej2HvxqlICkqyWAgbldPC0_mSHcaL43i5JJlLW4s-dheKsUga5fcJapMgcwxcVUXTLdnXtdtN9z8) A more literal interpretation of the question. [Answer] # [Arturo](https://arturo-lang.io), 18 bytes ``` $[a b]-><a++b b++a ``` [Try it](http://arturo-lang.io/playground?yqDRpR) Port of loopy walt's [Python answer](https://codegolf.stackexchange.com/a/259989/97916). [Answer] # [C (gcc)](https://gcc.gnu.org/), 82 bytes ``` t;*p;*q;f(a,b){for(t=3,p=a,q=b;*p==*q&&t;!*++p?--t,p=b:0)!*++q?--t,q=a:0;t=*p<*q;} ``` [Try it online!](https://tio.run/##bVHLbsIwELzzFdtIoDwcNRT1UIzbQ9Vb/6BBlW0cmgbysikIlF9vuuQlQI2UtXdmPJuMpb@Wsq4NdXPqFjSyORHOKcpK27AZyRknBRNIMuYWk4mhd67n5S@@b5AT88A590XTF4zPA2qYmy/QqKrj1MCWx6ntwGkE@CDgglHafPKPJTA4vVvcIoBVNotQiUx4tz0agcqm2cpvHrXCRGTKquiNnejtRKtqarJPIxS3bhrdOq9m2an0J74wAnXIlTRq1TpNCQQEhjrthDJLtQH5xUsXq5KJKlu9FR7eHsLD0yu@jzjgsp/1YzBTsM@z4nSlDngsoN12ATo@qiyy@69w7jvAHRAKnteo@zSHCDhadak2giW95kXPi/940Ei3t36NK8SHVG4P5iVKItsKrfFGh/jH3Qb8ZxivYKzDFEFOQBDQZAhLM6aW3ZyqqaUyuzLFKEZV/SujDV/r2t//AQ "C (gcc) – Try It Online") *Based on [loopy walt](https://codegolf.stackexchange.com/users/107561/loopy-walt)'s [Python answer](https://codegolf.stackexchange.com/a/259989/9481)* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` ‹⁺θη⁺ηθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYIyCntFijUEchQ1NHAczO0FEo1NTUtP7/Pzc5KzGNKzf5v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if `a'<b'`, nothing if not. Explanation: Another port of @loopywalt's Python answer. ``` θ First string ⁺ Concatenated with η Second string ‹ Is less than η Second string ⁺ Concatenated with θ First string Implicitly print ``` There are four cases: * One of `a` and `b` is a repetition of the other. In this case, `a'=b'`, but `a+b=b+a`, so the result is correct. * One of `a` and `b` is the prefix of the other, but the other is a prefix of its repetition. In this case the tie between `a'` and `b'` can always be broken before the length of `a+b`. Suppose `a` is a prefix of `b` is a prefix of `a'`, then `a+b` is also a prefix of `a'`, and `b+a` is a prefix of `b'`, so the result is correct. * One of `a` and `b` is the prefix of the other. In this case the tie between `a'` and `b'` can always be broken before the length of the longer of `a` and `b`. Suppose `a` is a prefix of `b`, then `a+b` contains enough copies of `a` to break the tie with `b`, so the result is correct. * Otherwise, `a` and `b` break the tie anyway before the length of the shorter of the two, so again the result is correct. 6 bytes by using JSON input: ``` ‹ΣθΣ⮌θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYI7g0V6NQU0cBRAellqUWFacC@UBg/f9/dLRSbnJWYpqSjgKQoRQb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input pair Σ Joined ‹ Is less than θ Input pair ⮌ Reversed Σ Joined Implicitly print ``` 9 bytes for the naïve version: ``` ‹×θLη×ηLθ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMntbhYIyQzN7VYo1BHwSc1L70kQyNDU1NHASKYARcs1AQC6///c5OzEtO4cpP/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ First input × Repeated by η Second input L Length ‹ Is less than η Second input × Repeated by θ First input L Length Implicitly print ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ‚J`‹ ``` -1 byte porting [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/259989/52210), so make sure to upvote that answer well! [Try it online](https://tio.run/##MzBNTDJM/f//cNOjhlleCY8adv7/H62UmKyko5SoFAsA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/w02PGmZ5JTxq2Plf5390tFKiko5SklKsDpCVDGQmgplJqdnJ2SCZ7PK8tPxUqFhVSVJqcQlIPZBKgojmJmclpgGFcpMhZmQnAZXrKJWm5pVlQkQghsYCAA). **Original straight-forward 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` €gR×`‹ ``` [Try it online](https://tio.run/##MzBNTDJM/f//UdOa9KDD0xMeNez8/z9aKTFZSUcpUSkWAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/0dNa9KDDk9PeNSw87/O/@hopUQlHaUkpVgdICsZyEwEM5NSs5OzQTLZ5Xlp@alQsaqSpNTiEpB6IJUEEc1NzkpMAwrlJkPMyE4CKtdRKk3NK8uEiEAMjQUA). **Explanation:** Uses the legacy version of 05AB1E, built in Python, which allows for comparisons on strings. ```  # Bifurcate the (implicit) input-pair; short for Duplicate & Reverse copy ‚ # Pair the pair with its reversed pair J # Join each inner pair together to a string ` # Pop and push the strings to the stack ‹ # Check if the first is smaller than the second # (after which the result is output implicitly) €g # Get the length of each inner string of the (implicit) input-pair R # Reverse this pair × # Repeat the strings in the (implicit) input-pair that many times `‹ # Same as above # (after which the result is output implicitly) ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Porting [@JonathanAllan's Jelly answer](https://codegolf.stackexchange.com/a/260022/52210) gives an alternative 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer, which only works in the new version of 05AB1E. ``` Σδ∍}Q ``` [Try it online](https://tio.run/##yy9OTMpM/f//3OJzWx519NYG/v8frZSYrKSjlKgUCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3OLz2151NFbG/hf5390tFKiko5SklKsDpCVDGQmgplJqdnJ2SCZ7PK8tPxUqFhVSVJqcQlIPZBKgojmJmclpgGFcpMhZmQnAZXrKJWm5pVlQkQghsYCAA). **Explanation:** ``` Σ # Sort the (implicit) input-pair by: δ # Map over the (implicit) input-pair with the current string as argument: ∍ # Extend/shorten the current string of the map to the same length as the # current string of the sort-by } # After the sort-by: Q # Check if the sorted pair is equal to the (implicit) input-pair # (after which the result is output implicitly) ``` [Answer] # Excel, 12 bytes ``` =A1&B1<B1&A1 ``` Input is in the cells `A1` and `B1`. Excel uses `&` for concatenation. [![Screenshot](https://i.stack.imgur.com/OMfoS.png)](https://i.stack.imgur.com/OMfoS.png) [Answer] # Ruby, 35 b-bwytes = ̄ω ̄= `lambda{|a, b|"#{a}#{b}"<"#{b}#{a}"}` [Yiff yiff, this is a furrendly conversion of the python tail wag!](https://chat.stackexchange.com/transcript/message/63383017#63383017) [Answer] # [Thunno](https://github.com/Thunno/Thunno) `D`, \$ 8 \log\_{256}(96) \approx \$ 6.58 bytes ``` rZP.JAu< ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSi1LsgqWlJWm6FiuKogL0vBxLbSBcqOiCVdFKiclKOkqJSrEQEQA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSilLsds9qx_ioTKOoyqqSKB8lBV1dXTsFpSifpaUlaboWK4qiAvS8HEttINxFUd4QxoKblYkKSRDFJUWlqVyJyQqJEG5aYk5xKldSanZydqJCdnleWn4qkrqk1KqSpNTiEgUQkZSKrCU3OSsxTSE3GdnU7CSg7tLUvLJMhCjEBQA) Direct port of Kevin Cruijssen's 05AB1E answer, which is a port of loopy walt's Python answer. #### Explanation ``` rZP.JAu< # Implicit input rZP # Pair with reverse .J # Join each inner list Au # Dump onto stack < # Check if less than # Implicit output ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` ¶ $'¶$'$`¶$` O`.+¶ M`(.+)¶\1$ ^0 ``` [Try it online!](https://tio.run/##K0otycxL/P//0DYuFfVD21TUVRKAZAKXf4KeNlDMN0FDT1vz0LYYQxWuOIP//3OTsxLTuHKTAQ "Retina 0.8.2 – Try It Online") Explanation: Based on @loopywalt's Python answer. ``` ¶ $'¶$'$`¶$` ``` Create a list of `a+b`, `b+a`, `a+b`. ``` O`.+¶ ``` Sort the first two elements of the list. ``` M`(.+)¶\1$ ^0 ``` Check that the last two elements are different. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 5 bytes ``` <sQs_ ``` [Try it online!](https://tio.run/##K6gsyfj/36Y4sDj@//9opcRkJR0FpUSlWAA "Pyth – Try It Online") Port of [@loopyWalt](https://codegolf.stackexchange.com/a/259989/52210)'s python answer. Takes the input as a list of two strings `[a,b]`. ### Explanation ``` <sQs_Q # implicitly add Q # implicitly assign Q = eval(input()) < # lexicographically compare sQ # sum of Q s_Q # sum of the reversal of Q ``` [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 10 bytes ``` gt.*cx*^Rv ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYs1abbpJXpayRVacUFlEKGbzrmJmXkKtgop-VwKCgVFCioKadFKSjpKSrFI_MSkZKBQYhKaIFgsWSkWYtSCBRAaAA) Takes the input as a list with two values. I don't like this format so I also solved it with a good io format: # [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 14 bytes ``` ap<gt<<fmp*^mp ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNs8zcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRACXrq5Cmm1iQZ1NjpFCeomNjZtKbsHS0pI0XYsNIHEbkFhaboFWHEz4pmFuYmaegq1CSj6XgkJBkYKKQpqCUmJSshKIVEIRU4JIQDQuWAChAQ) Honorable mention to: ``` ap~<l2 gt<<F$mp ``` which is 1 byte longer. # [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 13 bytes ``` gt.*Uc mp*^Sw ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYv1abbpJXpaockKuQVaccHlENGbbrmJmXkKtgop-VwKCgVFCioKaQoaSko6SkqayAKJSclAscQkdFGwYLKSJsS0BQsgNAA) This uses a tuple with two values. It's a compromise between the two formats and is *slightly* shorter than the longer of the two. # [Haskell](https://www.haskell.org) + [hgl](https://www.gitlab.com/wheatwizard/haskell-golfing-library), 9 bytes ``` cb cx*^Rv ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYvVabbJSQrJFVpxQWUQkZvOuYmZeQq2Cin5XAoKBUUKKgpp0UpKOkpKsUj8xKRkoFBiEpogWCxZKRZi1IIFEBoA) This outputs a comparison (3 values) instead of a boolean (2 values). This is shorter than the first answer, however the output format isn't officially permitted in the challenge ([although I haven't got a "No" yet](https://codegolf.stackexchange.com/questions/259987/string-comparison/260066#comment572777_259987)). I actually prefer this format since it's generally more modular and fits in with the systems available in hgl (part of why this is shorter). The 14 byte answer can also be made to use this format by replacing `gt` with `cp`, but it makes no difference to the byte count. # Reflection The 10 byte and 9 byte answers are pretty tight. The 10 byte answer (and the 13 byte answer) could potentially be shorter if `on gt` were given a 2 byte name (`cb` is the 2 byte name of `on cp` and the reason the 9 byte answer is shorter), however it's a bit hard to justify that. A 3 byte name might be useful anyway. However I am really concerned with improving the 14 byte answer. The other answers are in my opinion an abuse of the format. This is a very simple challenge and if I were to encounter this challenge as a part of a larger challenge there's no way I would get the input in such a format. I'd get it in a format much more similar to what the 14 byte answer expects. The issue that blows up the size of that answer is that in order to thread through two separate arguments, both of which are used twice requires a good deal of glue. All the other answers benefit from only taking one input, making their glue much simpler. So what's missing? Well, I have trouble coming up with a good reusable way to combine any of the existing parts. `on gt` doesn't actually help in this one unlike the other ones. And it's hard to make a version of `on` that actually does help. However there are pretty much two salient functions here `gt` and `mp`. All the glue is just a way to combine two functions, so maybe all of it should just be one function. ``` gt+^$mp ``` This would actually make things shorter (a lot shorter) and since it does combine two arguments it seems plausible that it could be reused at some point in the future. It's not a slam-dunk, it's not a clear hole in the language, but it's about the best I can do in this case. [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes input as an array. ``` ¬<UÔ¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=rDxV1Kw&input=WwpbImEiICJiIl0gLS0tPiB0cnVlClsiYWMiICJhIl0gLS0tPiBmYWxzZQpbImJla2NrYSIgImt3bmZvZSJdIC0tLT4gdHJ1ZQpbImJlenRiZXN0IiAiYmVzdGJlIl0gLS0tPiBmYWxzZQpbIm1jamFmIiAibWMiXSAtLS0%2bIHRydWUKWyJha2JvZSIgInVlbnZpIl0gLS0tPiB0cnVlCl0tbVI) (Includes all test cases) [Answer] # [Factor](https://factorcode.org/), 36 bytes ``` [ 2dup append -rot prepend before? ] ``` [Try it online!](https://tio.run/##bZC9boNAEIR7P8XkAaBwmUh2GaVJY7myUuwdewo5uDv2lqAY8ewEguQiohlpv9HO/jiyGmW@Xt7eX59BOUebkYRVf5LUQZG56zlYzmhJP8soFQs8S@AG3YCXw3johhEEgwlPKIriBJWeN2oX44EdNXnjhr31BD8EF3mnz/BdDWfFKob3Ilr7RW7RvaneLKnL1t/1P3eabzhWfQKlxKFCIVHXa/8Kwy4Kn/Exu@0Rp5YSyvkX "Factor – Try It Online") ``` ! "ac" "a" 2dup ! "ac" "a" "ac" "a" append ! "ac" "a" "aca" -rot ! "aca" "ac" "a" prepend ! "aca" "aac" before? ! f ``` [Answer] # [C (gcc)](https://gcc.gnu.org/) `-m32`, 78 bytes This is a comparison function, it outputs \$a + b \lesseqqgtr b + a\$, where \$+\$ is string concatenation. ``` f(a,n,b,m){int c[4][n+m];wcscmp(wcscat(wcscpy(c),b),wcscat(wcscpy(c+2,b),a));} ``` [Try it online!](https://tio.run/##ZZLLboMwEEX3fMWIKhIE00fSLiqSbKruuu8ioMo2JnEBg7DzaKL8eunwStMUwcwwHN@xruH@ivO6ThxKFGEkd49SGeDLx2ipvDwKdlzzvHSaRE2byi@Hu4S55KrnTZomdd3gVN9IxbNNLGCmTSyL2/XCslDXyqlUzraQsWsdLcArK9QKxkZo80GXEczh@GZTmwBG3iYmUp7SvjwYhmT7kvNPmnRgygphn4JrPTbosQ5rY7pTCdKdnEa5XqxNG6G2clBqbBD7UnAj4k7JfyCA90XyH3qYF0qja2taYRA8FdUyQgubVXa4f52E@@cXfJ5wzOX7dBiWFBU4zUSpYrHHZfdBX85Ay4MoEmfYi3vXN8bnTgCe19IudK7@OkFRq3e3JaLgCmADwP4BzX40fm7@DTzkTCiH4sEPNcOT/sMKZM@OXYuVFSKJY4f2KNMh@tAX4C9gFMNIhwqblAAjoMnZRT2fi6ifc2pjJcymUmiQdaq/eZLRla79fDqp/XdV@DIvM8ml@QE "C (gcc) – Try It Online") ]
[Question] [ # Challenge: Given an array of non-negative whole numbers numbers ~~in the range of `0 to Infinity`~~, Check whether all of them are primes or not. (You can take input as a string too if you want) # Input: Input: An array of numbers Output: The array with every element replaced by one of these: ``` -1 -----> If 0, 1 1 -----> If it is a prime number greater than 1 the highest factor -----> If that number is not prime ``` Return either -1 (0, 1), 1 (for primes >= 2) or the highest factor of given number (for non-primes) # Examples: ``` [1, 2, 3, 4, 10, 11, 13] ---> [-1, 1, 1, 2, 5, 1, 1] [100, 200, 231321, 12312, 0, 111381209, 123123] ---> [50, 100, 77107, 6156, -1, 1, 41041] ``` # Note: Input will always be valid, i.e it will consist only of numbers and decimals are not tested for. The array can be empty, if so, return the empty array. # Restriction: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins. # LeaderBoard : Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=163882,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆḌṪ€o- ``` A monadic link accepting a list of non-negative integers and returing a list of integers greater than or equal to -1. **[Try it online!](https://tio.run/##y0rNyan8//9w28MdPQ93rnrUtCZf9////9GGBgY6CkZgwtjQ2MhQR8EQyDDSUQCKGBoaGlsYGhlYQgWNYwE "Jelly – Try It Online")** ### How? Note that: * All primes have a single proper divisor (one) * All composites have multiple proper divisors (one plus the others) * No number has itself as a *proper* divisor * Jelly's get-proper-divisors atom, `ÆḌ`, yields a list of proper divisors in ascending order * Zero and one have no proper divisors (they are neither prime, nor composite) * Applying Jelly's tail atom, `Ṫ`, to an empty list yields zero * No number has a proper divisor of zero (let alone being the maximal one) * All non-zero numbers are truthy in Jelly, while zero is falsey ``` ÆḌṪ€o- | Link: list of integers e.g. [ 0, 1, 2, 5, 10, 5183] ÆḌ | proper divisors (vectorises) [[],[],[1],[1],[1,2,5],[1,71,73]] Ṫ€ | tail €ach [ 0, 0, 1, 1, 5, 73] - | literal minus one o | logical OR (vectorises) [-1,-1, 1, 1, 5, 73] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes *Saved 1 byte thanks to @Dennis* ``` :ÆfṂ€$~~ ``` [Try it online!](https://tio.run/##y0rNyan8/9/qcFvaw51Nj5rWqNTV/f//P9rQwEBHwQhMGBsaGxnqKBgCGUY6CkARQ0NDYwtDIwNLqKBxLAA) or [run all test cases](https://tio.run/##y0rNyan8/9/qcFvaw51Nj5rWqNTV/T/cDmT8/x@tEG2oo2Cko2Cso2Cio2BoAMRAAUPjWB0uBaCcAVDACEwYGxobgWSADKBysDpDYwtDIwNLqKBxrEIsAA) ### Commented We take advantage of the fact that both `nan` and `inf` become `0` in Jelly when a bitwise NOT is applied to them. ``` :ÆfṂ€$~~ - main link, taking the input list ÆfṂ€$ - treat these two links as a monad: Æf - get the lists of prime factors (0 --> 0; 1 --> empty list; prime --> itself) € - for each list, Ṃ - isolate the minimum prime factor (turns empty lists into 0) : - divide each entry by its minimum prime factor (0/0 --> nan; 1/0 --> inf) ~~ - bitwise NOT x2 (nan or inf --> 0 --> -1; other entries are unchanged) ``` [Answer] # R, ~~68~~ 62 bytes ``` Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan()) ``` A solution using only base R, no libraries! Thanks to Giuseppe for golfing away 6 bytes. Uses `scan` to read in a space separated list of numbers, `%%` to identify which are factors. `v` then contains a vector of all factors in ascending order (including 1 and n). This has the nice property that when we `rev`erse `v`, the number we want will be in the second place, avoiding an expensive call to `length` or `tail`(if `n` was prime, `v` contains `n 1`, else it contains `n (factors in descending order) 1`). Example output (TIO link [here](https://tio.run/##K/r/3zexQCOtNC@5JDM/TyNPs7rMtii1TKM8IzM5QyNPVVXD0CpP09bWQFPTWikzTUkjz8ZIR9dQpyzaKFazVqc4OTFPQ1Pzv6GCkYKxgomCqYKZgrmChYLlfy4A)): ``` > Map(function(n,v=rev(which(!n%%1:n)))"if"(n<2,-1,v[2]),scan()) 1: 0 1 2 3 4 5 6 7 8 9 11: Read 10 items [[1]] [1] -1 [[2]] [1] -1 [[3]] [1] 1 [[4]] [1] 1 [[5]] [1] 2 [[6]] [1] 1 [[7]] [1] 3 [[8]] [1] 1 [[9]] [1] 4 [[10]] [1] 3 ``` If you think a list is not an acceptable return type, then swap out `Map` for `sapply` and add 3 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~11~~ ~~9~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ñε¨àDd<+ ``` -3 bytes thanks to *@Emigna*, changing `©d1-®+` to `Dd<+` and `€¨€à` to `ε¨à`. Only my second 05AB1E answer, ~~so can definitely be golfed~~. [Try it online.](https://tio.run/##MzBNTDJM/f//8MRzWw@tOLzAJcVG@//h9f@jDXUUjHQUjHUUTHQUDA2AGChgaGRsCBQ0BIoaxAIA) **Explanation:** ``` Ñ # Divisors of each item in the input-list (including itself) # [1,2,10,3] → [[1],[1,2],[1,2,5,10],[1,2,3]] ε # For each: ¨ # Remove last item (so it's now excluding itself) # [[1],[1,2],[1,2,5,10],[1,2,3]] → [[],[1],[1,2,5],[1,2]] à # And get the max # [[],[1],[1,2,5],[1,2]] → ['',1,5,2] D # Duplicate the list d # Is it a number (1 if it's a number, 0 otherwise) # ['',1,5,2] → [0,1,1,1] < # Subtract 1 # [0,1,1,1] → [-1,0,0,0] + # Add both lists together # ['',1,5,2] and [-1,0,0,0] → ['-1',1,5,2] ``` [Answer] # [J](http://jsoftware.com/), 21 bytes ``` _1:`(%{.@q:)@.(>&1)"0 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/4w2tEjRUq/UcCq00HfQ07NQMNZUM/mtyKXClJmfkK6QpGCoYKRgrmCgYGigYGioYGsPFDQwUjEDY2NDYCCgBpI0UQGoMjS0MjQwsISLG/wE "J – Try It Online") ## Explanation: `(>&1)"0` is each number greater than 1? `@.` if not, return `_1:` `(%{.@q:)` if its 2 or greater, divide `%` the number by the first `{.`of the prime factors `q:` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes After golfing, ended up being almost identical to, and just as short as, Jonathan's solution. ``` ®â¬ÌªJ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ruKszKpK&input=WzAsMSwyLDMsNCw1LDYsNyw4XQ==) --- ## Explanation ``` ® :Map ⬠: Proper divisors Ì : Get last element (returns null if the array is empty) ª : Logical OR J : -1 ``` [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda l:[max([k for k in range(1,n)if n%k<1]+[-1])for n in l] ``` [Try it online!](https://tio.run/##NYuxDsIwDER3vsILaiJSqY4ZaAX8SMgQBIGqrVtVGeDrQ6yK4U7n87vlm94zU46XWx7DdH8EGDs3hY9yA8R5hQF6hjXw66nQsO4j8H44oz@4Gr0WgoUYfZacJDsEA7aIio5F2IiVFsmb8m7ktpsTkhUeS5LNhiKd0Dbtvyff7QCWteekkqnqa2WiSlrnHw "Python 3 – Try It Online") For `0` and `1` `range(1,n)` is empty, therefore the code evaluates to `max([]+[-1]) = -1`. For prime numbers, the only divisor in the [1, n) is `1`, which is the desired output. --- # [Coconut](http://coconut-lang.org/), 50 bytes ``` map$(n->max([k for k in range(1,n)if n%k<1]+[-1])) ``` [Try it online!](https://tio.run/##FchLDoMgFEbhrfyDNoH4iFcdVjeCDIiRhqAXQ2nSQfeOOPjO4KxhDfxN2U5LPsz5ENzMh/kJ5WFDhIdjRMPvTVDN0lnw079IV6ohLWVWhBp9MRRjQd2dcmnQ@M@wd87oOLXt7j4pXw "Coconut – Try It Online") [Answer] # Java 8, ~~105~~ ~~103~~ 87 bytes ``` a->{for(int i=a.length,n,x;i-->0;a[i]=n<2?-1:n/x)for(n=a[i],x=1;++x<n;)if(n%x<1)break;} ``` Modifies the input-array instead of returning a new one to save bytes. [Try it online.](https://tio.run/##ZZBBboMwEEX3PcVsKoFiXAxdtDWk6gGaTZZRFhNiUhMyRGBSIsTZqTF0UVXyyPLXH/83U@ANg@J4HrMSmwY@UVP/AKDJqDrHTMFmegLcKn2EzLP6bg/oSysOtuxpDBqdwQYIUhgxWPd5VU9G0CnyUtHJfDFindRBsA4l7vQ@pSR6D8QbPXX@ZKZ0UlmXCrladQlJX@cePXaJ8A@1wrMcRjmHXdtDacOWTAd1scje1tSaTg5t5jWqMR6pb3DEvWARi9kzEyETgol4cBP8t4Uhi6aKRRxZn70jNrWI@EVE4eusLN1/53cs7rvfHc0gxDMPl7TtvTHqwqvW8KvlNSV5hd0/b40u@Udd473hpppnsU1LyjD@AA) **Explanation:** ``` a->{ // Method with integer-array parameter and no return-type for(int i=a.length,n,x;i-->0; // Loop backward over the array a[i]= // After every iteration: change the current item to: n<2? // If the current item is 0 or 1: -1 // Change it to -1 : // Else: n/x) // Change it to `n` divided by `x` for(n=a[i], // Set `n` to the current item x=1;++x<n;) // Inner loop `x` in range [2,`n`) if(n%x<1) // If `n` is divisible by `x`: break;} // Stop the inner loop (`x` is now the smallest prime-factor) // (if the loop finishes without hitting the `break`, // it means `n` is a prime, and `x` and `n` will be the same) ``` [Answer] ## Haskell, ~~52~~ 49 bytes ``` map(\x->last$[d|d<-[1..x-1],mod x d<1]++[-1|x<2]) ``` [Try it online!](https://tio.run/##JYsxEoMgEAC/coVFMt453NFiPoIUjEh0goaJKSh8e4iZFLtb7ez3x5RSjf1QV58vQ6HbPPnQWOKjGHFta8MRDNlCjIWk6xyuzwAFgmF3Padlgx7ya9ne0EAEq5BRkDWyUig/NGth5LPyt3b1M8bk73ulMecv "Haskell – Try It Online") ``` map -- for each element in the input array \x-> -- apply the lambda function last -- pick the last element of the following list [d|d<-[1..x-1] -- all d from 1 to x-1 ,mod x d<1] -- where d divides x ++[-1|x<2] -- followed by -1 if x<2 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` m(|_1→hḊ ``` [Try it online!](https://tio.run/##yygtzv7/P1ejJt7wUdukjIc7uv7//x9tqGOkY6xjomNooGNoqGNoDGQY6BiBsLGhsRFQBEgb6RhAaONYAA "Husk – Try It Online") ### Explanation ``` m(|_1→hḊ Implicit Input [1,2,3,4,10] m( Map each element Ḋ List of divisors [[1],[1,2],[1,3],[1,2,4],[1,2,5,10]] →h Penultimate element [0,1,1,2,5] |_1 If falsy then -1 [-1,1,1,2,5] ``` [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 23 bytes ``` @{Max&-1!Divisors@_@-2} ``` [Try it online!](https://tio.run/##SywpSUzOSP2fZmX736HaN7FCTddQ0SWzLLM4v6jYId5B16j2v19qakpxtEpBQXJ6LFdAUWZeSUhqcYlzYnFqcXSajkI0lwIQRBvqKBjpKBjrKJjoKBgaADFQwNA4VgcqawAUMgITxobGRiA5IAOoAazS0NjC0MjAEipoHMsVG/sfAA "Attache – Try It Online") 29 bytes, pointfree: `@(Max&-1@Last@ProperDivisors)` 24 bytes, also pointfree: `@(Max&-1@`@&-2@Divisors)` This simply gets the second-to-last divisor of `n` then takes the max of it and `-1`. The second-to-last element in an array with less than two elements is `nil`, and `Max[-1, nil]` is `-1`. `@` simply vectorizes this function, making it apply to each atom. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` {fkt|∧_1}ˢ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG04vK/1enZZfUPOpYHm9Ye3rR///R0YY6CkY6CsY6CiY6CoYGQAwUMDSO1Yk2NADyjMCEsaGxEUgYyACqBSsyNLYwNDKwhAoax8YCAA "Brachylog – Try It Online") The following explanation is mostly phrased imperatively for the sake of brevity, and does not accurately reflect Brachylog's declarative nature. ``` { Start of inline predicate. Implicit input to the predicate. f Create a list of all of the input's factors (including itself). k Remove the last item of this list so that it no longer contains the original number. t Take the last item of the list with the last item removed. Implicitly unify the output with the aforementioned last item. | If that failed, because one of the lists was empty... ∧ discarding the input, (there's probably some obvious reason ∨ won't work here but I don't know what it is) _1 unify the output with -1 instead. } End of the inline predicate. ˢ For every item of the input, unify it with the predicate's input and get a list of the corresponding outputs. ``` I decided I'd learn Brachylog so I could have some fun with code golf while hoping to learn some of the behavior of actual Prolog through osmosis, and I'm really enjoying it so far, even if I'm not entirely sure how the execution control characters work. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes ``` Divisors[#][[-2]]/._Part:>-1&/@#& ``` [Try it online!](https://tio.run/##LYpBCsIwFESvMrTQ1a/tz3ehgqULD9B9CBLEYhatkAY3IWePsbiYYebxFhtez8UG97B5xjXf3Mdtb7/p2mjdKmO6w32yPlyGlpturJs8ebcGXRMqtAMqwlxcgwbdiBiZoAhCOBK4LymAJREi9@WqvYRF/XgZRd4tlhOr/vyHklL@Ag "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org/) + `numbers`, ~~88~~ 79 bytes Thanks to the comments for some advice mainly about how to make submissions. ``` function(y)sapply(y,function(x)"if"(x<2,-1,prod(numbers::primeFactors(x)[-1]))) ``` Uses the product of all prime factors except the smallest one, and the fact that the product of elements of an empty vector is defined to be `1`. [Try it online!](https://tio.run/##PcvBCsMgEATQX5GcVljBXS9tyLk/EXpIbAShUdEE4tdbD6GHgeExk5sTkxLNncEePgaosiwpfStU/NslB@8GuCZGRZhy/EA493XLZRxT9vv2WuwRc@nDWdFbStkcWCCtkXsEGzJMKKgXRtGFiMyDWD9vNP3yAw "R – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü±p╞Ö*«òτ♀╣â▀ ``` [Run and debug it](https://staxlang.xyz/#p=81f170c6992aae95e70cb983df&i=[0,+1,+2,+3,+4,+5,+6,+7,+8]&a=1) Explanation (unpacked): ``` m|fc%c{vsH1?}U? Full program, implicit input-parsing m Map |fc%c Get factorisation and length of it (0 and 1 yield []) { } ? If length != 0: v Decrement ? If still != 0: sH Last element of factorisation ? Else: 1 Push 1 ? Else: U Push -1 ``` Pseudocode inside map: ``` f = factorisation(i) l = length(f) if l: if --l: return f[-1] else: return 1 else: return -1 ``` [Answer] # Pyth, 12 bytes ``` me+_1f!%dTSt ``` [Try it here](https://pyth.herokuapp.com/?code=me%2B_1f%21%25dTSt&input=%5B0%2C+1%2C+2%2C+3%2C+4%2C+10%2C+11%2C+13%5D&debug=0) ### Explanation ``` me+_1f!%dTSt m Q For each number d in the (implicit) input... Std ... get the range [1, ..., d - 1]... f!%dT ... take the ones that are factors of d... +_1 ... prepend -1... e ... and take the last. ``` [Answer] # [J](http://jsoftware.com/), 14 bytes ``` 1(%0{q:,-)@>.] ``` [Try it online!](https://tio.run/##PYrBCkBAFEX3vuKmNBR69z0LpsiPWMkkG1nLtw9SFqdb554tprUL6D1cicsLPCQyz@Q8fFkV41BPsUiQLPO6I4BQGBpQQIL2exHoi9H0OZ5VvA2tpUr3GYs3 "J – Try It Online") For every number n take the maximum of (n,1) instead. Append the negated number to the list of its prime factors (empty list for 1), and divide the number by the first item in the list. ### Also 14 bytes ``` (%0{q:) ::_1"0 ``` [Try it online!](https://tio.run/##PYoxCoNQEAV7TzEIYoQg@3Yt4kLOYiH5hDQhdcjZfxTBYngwb161HfvCPemv/NJIrF46@35yIHNRa3VoaB7r801BOMGEDAnF6c3wnVD4dmzr7I3iJrf5MFH/ "J – Try It Online") Divide every number by the first of its prime factors. 0 raises a domain error with `q:`, and we look for the 0th item in an empty list for 1 — that’s an error as well. For any number that errors, return −1. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ ~~11~~ 8 bytes ``` ®/k v)ªÉ ® // For each input number, /k v // return the number divided by it's first prime factor, )ªÉ // or -1 if such a number doesn't exist (the previous result is NaN). ``` [Try it online!](https://tio.run/##y0osKPn//9A6/WyFMs1Dqw53/v8fbaCjYKijYKSjYKyjYAJkg/hAAUPjWAA) Shaved off those three pesky bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy). [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~61~~55 bytes -6 bytes thanks to @shaggy ``` _=>_.map(_=>eval('for(v=_/(d=_>>1);v!=~~v;v=_/--d);d')) ``` [Try it online!](https://tio.run/##XctBCsMgFATQfU9hV/FDTP3aTRG9SCkiUUuLjSEpLnN1q9tuZoYH83bF7fP2Wr9syT7UqKvVxk4ft9I2QnGJDjFvtGh7oV5bYxBUOevjKKobYx6UHwDqnJc9pzCl/KSR3lE8AE7/SEbCR4KiNXLe84pCchQdJYqbxHarPw "JavaScript (Node.js) – Try It Online") --- # Explanation : ``` _ => // input i.e : the original array _.map( // map over all elements of the array eval(' // eval a string for(v=_/(d=_>>1); // set v = _ / _ >> 1 and set that to d v!=~~v; // and keep going until v !== floor(v) v=_/d--); // to _ / d again (d was changed) d' // return d )) // end eval and map and function ``` **This is still for old code haven't updated this.** # ES5 friendly as well: ``` const primeOrNot = function(input) { // the function with argument input return input.map(function(value) { // returns the array after mapping over them d = Math.floor(value * 0.5); // multiply each element by 0.5 and floor it for(let v = value / d; v != Math.floor(v);) { // for loop goes until v!=~~v d --; // subtract one from d v = value / d; // set v again to value / d } return d; // return d }) }; ``` [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 49 * 9 bytes saved thanks to @Cowsquack ``` factor|sed '/:$/c-1 /: \w+$/c1 s%: %/% y/ /#/'|bc ``` ### Explanation * `factor` reads input numbers from STDIN, one per line and outputs in the format `<input number>: <space-separated list of prime factors (ascending)>` * `sed` processes this as follows: + `/:$/c-1` The input numbers 0 and 1 have no prime factors and are replaced with `-1` + `/: \w+$/c1` Numbers with one prime factor (themselves) are prime. Replace these with `1` + `s%: %/%` Replace `:` with `/`. This builds an arithmetic expression to divide the (non-prime) input number by its smallest prime factor to give the largest factor + `y/ /#/` Remove the list of other (unneeded) factors (by commenting out) * `bc` Arithmetically evaluate and display [Try it online!](https://tio.run/##JckxDoMwFAPQ3afIQIREBT/@v0Obs7BAaMWGRCp14e4hiMGy9TxPeS3lO6Xfth/5s7hWYiOpJ7IMXXTj/9EIBdlH58VXdUMn0h5zKoVQGJ5gAAlaHQF6xWhapbbiOmkvanjfYic "Bash – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~61~~ 59 bytes ``` lambda x:[max(k for k in[-1]+range(1,n)if n%k<1)for n in x] ``` [Try it online!](https://tio.run/##FclBCoAgEADAr@wlUDJogwiiXmIejLLE3EQ82Out5jrhSedNXTHzUi7t101DHqXXmTkwdwQHlmSDqo6ajp2hIG4NUOUm5P/T95BVCdFSYoZJ7MUgWoGK8/IC "Python 2 – Try It Online") --- **Improvements** * 61 to 59 bytes by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). [Answer] # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` x=>x.map(a=>(f=t=>a%--t<1?t:f(t))(a)) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/e9m@7/C1q5CLzexQCPR1k4jzbbE1i5RVVe3xMbQvsQqTaNEU1MjUVPzf3J@XnF@TqpeTn66hptGtKGOgpGOgrGOgomOgqEBEAMFDI1jgQoB "JavaScript (Node.js) – Try It Online") Recursive, stack overflow for large input # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` x=>x.map(a=>eval('for(t=a;a%--t!=0;);t')) ``` [Try it online!](https://tio.run/##DcpBDkAwEEDRq9RCTJNWFLtmLF1CLCaUkDJCI25fXfzNy9/ppWe6tyvok2cXe4wfdl950AWEnXvJQ7HwDQHJUq51yLCy0oZCyjjx@bB3pecVehiMErUSjRKtEqZKJTDNmMYf "JavaScript (Node.js) – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 37 bytes ``` a->[if(x<2,-1,x/divisors(x)[2])|x<-a] ``` [Try it online!](https://tio.run/##LYrBCgIxDER/JeyphRSbxIPCuj9SeihIpSBauiIV/PeaXTzMMPNmamrF3erIcBnJLaFk02dGR9gP1/Iu67OtptvA0X777FIcqdb7xyRwC9RWHi@N01YmyCZZixACITCCIBwRyKsUkESdyGvl3YSEN65Bz/uL5ETsz38oMdrxAw "Pari/GP – Try It Online") [Answer] # [Racket](https://racket-lang.org/), 105 bytes ``` (λ(L)(map(λ(n)(if(< n 2)-1(p n(- n 1))))L))(define(p n d)(if(= d 1)1(if(=(modulo n d)0)d(p n(- d 1))))) ``` [Try it online!](https://tio.run/##lU3LDcIwDL13iidxwD4g4oQDSLBBlwgkQRVtWhWYjh1YKSRpF8CS5feVZ3t7@Ffa9DbeMVeyv9qnT/T9UMs02KmgyNQFOiNC805oQqRdJsJ5WmZyPnTRFx2uRi9w2ZUKaRjdux@rp9itbbe0Oa1lhL9ectNQwJYEGgYHiIIIxGRj0ZWCLmvE6Gzkq1EyYo6i1WlRcjz9AA "Racket – Try It Online") [Answer] # [Befunge-98 (FBBI)](https://github.com/catseye/FBBI), 39 bytes ``` j&:!+f0p1-1:::' -:!j;3k$.nbj;-\%!!j:1+a ``` [Try it online!](https://tio.run/##JYg7CoAwEAWv8gJ@ConkZS10cxUbA1GIIDaeP0Yshhkmpv25jmSXuZTcqRl2d9NSVXtYNTnI2YxXzMGurTFZOWylEB6CCXQgQanh4D@E4uup9nC/5QU "Befunge-98 (FBBI) – Try It Online") Ends with the `&` when there are no more numbers. This causes the program to stall for 60 seconds until TIO ends the program. This is unavoidable for Befunge-98, at least on TIO because both interpreters do this. After hitting play, you can stop the program after a bit in order to see what would be output if you did wait the minute. --- Essentially, for every new number, if it is 0, it turns it into a 1. Then it puts a -1 onto the stack followed by a number that starts from 1 and counts up until it reaches the input number, in which case it prints out the second number on the stack (-1 for an input of 0 or 1, and the highest factor for others). Every time through the loop, we add the value of the iterator to the stack behind it if (`input % iterator == 0`). This means that when we get to the input, we just have to throw away the iterator and print. Then, we clear the stack with `n` and return to the read input function. I may expand of the explanation later, we'll see... [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 33 bytes ``` %(`^0|^1$ -1 \d+ $* ^(1+)\1+$ $.1 ``` [Try it online!](https://tio.run/##JYgxCoBADAT7fUeE00PJJj7nOBS0sLEQS/8eTyyGGeba7@NcI7q0VH0qBSNRtgwZUBNzX5gFMjGCMDhmUEGC3kJhH063dpoN@ttf "Retina 0.8.2 – Try It Online") Link includes those test cases that aren't too slow. Explanation: ``` %(` ``` Loop over each input number. ``` ^0|^1$ -1 ``` Special-case 0 and 1. ``` \d+ $* ``` Convert to unary (doesn't affect -1). ``` ^(1+)\1+$ $.1 ``` Replace each number with its largest proper factor in decimal. [Answer] # [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 75 bytes ``` (load library (q((L)(map(q((N)(i(l N 2)(- 1)(/ N(min(prime-factors N))))))L ``` [Try it online!](https://tio.run/##HcwxDsMgEETRPqeYcrawkoUcw@IOJA7SSmAT7ManxyS/etU/bD2z7bV35i0uyPZqsZ03Lkj8krOwxPpTEBozApxwggrvCCy2sjYrnynF97G1HUH@zZ0JHOcDDygcPJ7QQYX6gSHn1Yn0Cw "tinylisp – Try It Online") (Contains 4 extra bytes to give the anonymous function a name so we can call it in the footer.) ### Ungolfed/explanation Observe that returning 1 for prime \$n\$ and the largest factor less than \$n\$ for composite \$n\$ can be combined into returning \$n/p\$ where \$p\$ is the smallest prime factor of \$n\$. ``` (load library) Library gives us map, -, /, min, and prime-factors functions (lambda (L) Anonymous function, takes a list of numbers L (map Map (lambda (N) Anonymous function, takes a number N (if (less? N 2) If N < 2 (- 1) -1; else (/ N N divided by (min the minimum (prime-factors N))))) of the prime factors of N L))) ... to L ``` ]
[Question] [ Your task is to write a program that runs in two different languages, and does the following: * In one language, it palindromizes a given string. + Take the string. `abcde` + Reverse the string. `edcba` + Remove the first character. `dcba` + Glue it onto the original string. `abcdedcba` * In another language, it depalindromizes a given string. + Take a string palidromized by the above method. `abcdedcba` + Get the characters from the start to the middle. `abcde` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest **characters** (not bytes) wins. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language 1/Language 2, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby/Python, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl/C, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish)/Python, 121 bytes ``` ``` var QUESTION_ID=98776,OVERRIDE_USER=12537;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) / [MATL](https://github.com/lmendo/MATL), ~~10~~ 9 characters ``` 9LQ2/)%¹û ``` In 05AB1E this [palindromizes](http://05ab1e.tryitonline.net/#code=OUxRMi8pJcK5w7s&input=YWJjZGU). In MATL it [depalindromizes](http://matl.tryitonline.net/#code=OUxRMi8pJcK5w7s&input=J2FiY2RlZGNiYSc). ### Explanation in 05AB1E This part of the code does nothing (globally): ``` 9L Pushes array [1, 2, ... 9] Q Consumes the array, takes the input implicitly, and produces no output 2/ With no further input to take implicitly, this gives no output ) Wrap stack into an array: gives an empty array % Consumes that array and, with no further input to take implicitly, gives no ouput ``` This is the part that does the work: ``` ¹ Push input again û Palindromize. Implicitly display ``` ### Explanation in MATL This is the part that does the work: ``` 9L Push array [0, 1j] Q2/ Add 1, divide by two: transforms into [1/2, (1+1j)/2] ) Use as index into implicit input. [1/2, (1+1j)/2] is interpreted as 1/2:(end+1)/2, which is rounded to 1:(end+1)/2. So this takes elements from first to half, including both. Implicitly display ``` This is ignored: ``` %¹û Everything after '%' is a comment ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E) / [Jelly](http://jelly.tryitonline.net/#code=xZNzMuG4osK5w7s&input=&args=J2hlbGxvbGxlaCc), 6 characters Palindromizes in 05AB1E. Depalindromizes in Jelly. ``` œs2Ḣ¹û ``` [Try it in 05AB1E](http://05ab1e.tryitonline.net/#code=xZNzMuG4osK5w7s&input=aGVsbG8) **05AB1E Explanation** ``` œ # compute powerset of input s # swap (does nothing) 2 # push 2 Ḣ # does nothing ¹û # palindromize input ``` [Try it in Jelly](http://jelly.tryitonline.net/#code=xZNzMuG4osK5w7s&input=&args=J2hlbGxvbGxlaCc) **Jelly Explanation** ``` œs2 # split input in 2 chunks (first chunk is larger for odd length strings) Ḣ # head, take first ¹û # does nothing ``` [Answer] # Scala / Javascript, 106 bytes ``` /*\u002A/print(args(0)+args(0).reverse.tail)//*/ /*/**/ alert((s=prompt()).slice(0,-s.length/2))//\u000A*/ ``` Palindromizes in scala and depalindromizes in javascript. Try it on [ideone](https://ideone.com/dKYXux) (scala) - Warning: wrong syntax highlighting Try it on [jsfiddle](https://jsfiddle.net/L2j6ypx6/) (javascript). ### Explanation: Scala, like java, processes unicode escapes before everything else, so scalac sees the code like this: ``` /**/ //\u002A is as asterisk, results in an empty block comment print(args(0)+args(0).reverse.tail) //scala code //*/ //a line comment /* //scala supports nested block comments, so this comment... /* */ alert((s=prompt()).slice(0,-s.length/2)) // //\u000A (newline) inserted here */ //...ends here ``` The javascript gets parsed like this: ``` /*\u002A/print(args(0)+args(0).reverse.tail)//*/ //block comment /* //a block comment... /* */ //...ending here, no nesting alert((s=prompt()).slice(0,-s.length/2)) //code //\u000A*/ //line comment ``` [Answer] # Python 3 / JavaScript, 83 chars *Saved 2 bytes thanks to @LevitatingLion* ``` 1//2;x=input();print(x+x[-2::-1]);""" x=prompt();alert(x.slice(0,-x.length/2))//""" ``` Python [palindromizes](http://ideone.com/c1Xn1S), JavaScript [depalindromizes](https://jsfiddle.net/nqkfb9qt/). I tried keeping more code constant between the two, but I couldn't figure out a good way to sneak `.slice` into Python. Here's an alternate method: ``` 1//2;prompt=input,alert=print x=prompt();1//2;x+=x[-2::-1]);""" x=x.slice(0,-x.length/2))//""" alert(x) ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/) / [MATL](https://github.com/lmendo/MATL), 18 characters ``` r_W%(; "j9LQ2/)%"; ``` In CJam this [palindromizes](http://cjam.tryitonline.net/#code=cl9XJSg7CiJqOUxRMi8pJSI7&input=YWJjZGU). In MATL it [depalindromizes](http://matl.tryitonline.net/#code=cl9XJSg7CiJqOUxRMi8pJSI7&input=YWJjZGVkY2Jh). ### Explanation in CJam Working part: ``` r Read string _ Duplicate W% Reverse (; Remove first element ``` Dummy part: ``` "j9LQ2/)%" Push this string ; Remove it from the stack Implicitly display both strings obtained previously ``` ### Explanation in MATL Dummy part: ``` r Push random number between 0 and 1 _ Negate W 2 raised to that %(; Comment (ignored) ``` Working part: ``` " For each element in the array at the top of the stack. Since it is a number, which is the same as a length-1 array, the following is executed once j Input string 9L Push array [0, 1j] Q2/ Add 1, divide by 2: transforms into [1/2, (1+1j)/2] ) Use as index. [1/2, (1+1j)/2] is interpreted as 1/2:(end+1)/2, which is rounded to 1:(1+end)/2. So this takes elements from first to half, including both ``` Another dummy part: ``` %"; Comment (ignored) Implicitly display the previously obtained string ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟 / Javascript ES6, 55 chars ``` this._?Σ(`ï+ï.Ħ⬮.Đ1`):(x=prompt()).slice(0,-x.length/2) ``` `[Try it here (ES6 browsers only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=asdf&code=this._%3F%CE%A3(%60%C3%AF%2B%C3%AF.%C4%A6%E2%AC%AE.%C4%901%60)%3A(x%3Dprompt()).slice(0%2C-x.length%2F2))` Palindromizes in 𝔼𝕊𝕄𝕚𝕟, depalindromizes in Javascript ES6. I though this was going to be easy, since 𝔼𝕊𝕄𝕚𝕟 compiles to ES6 and most of ES6 can be run in 𝔼𝕊𝕄𝕚𝕟. Apparently, I'm completely wrong. # Explanation `this._` checks to see if variable `_` exists in the global scope; 𝔼𝕊𝕄𝕚𝕟 uses Lodash and therefore has `_` stored, but pure ES6 doesn't. The 𝔼𝕊𝕄𝕚𝕟 segment - `Σ(`ï+ï.Ħ⬮.Đ1`)` - evaluates from string the code that palindromizes input. Normally, the code would be `ï+ïĦ⬮Đ1`, but I put the dots in to *make the compiler happy*. The Javascript segment - `(x=prompt()).slice(0,-x.length/2)` - depalindromizes a string from a prompt. --- I was going to use a function (so I didn't have to deal with `prompt`), but 𝔼𝕊𝕄𝕚𝕟's evaluation function didn't like that, so I used `prompt` and no function to *make the compiler happy*. [Answer] # JavaScript ES6 / JavaScript ES3, 143 bytes ``` function(x){'use strict';function a(){return x+x.split('').reverse().slice(1).join('')}{function a(){return x.slice(0,-x.length/2)}}return a()} ``` Palindromizes in JavaScript ES6, depalindromizes in JavaScript ES3. *Non competing*, it's just a try to make a polyglot for two versions of the same language. In ES3 functions are allowed in blocks, but as blocks don't define scopes the new function just replaces the first function. In ES5 strict mode it fails because it don't allow functions to be defined in blocks. In ES6 it's allowed and, because blocks now define scopes, the first function isn't replaced. Tested in Internet Explorer 5 (emulated) for ES3 and Node.JS and Firefox for ES6. [Answer] # [Jelly](//github.com/DennisMitchell/jelly) / CJam, ~~15~~ 14 chars ``` q_,2./m]<e#¶ŒB ``` -1 char thanks to 42545 (ETHproductions) [Try it online! (Jelly) (Palindromization)](//jelly.tryitonline.net/#code=cV8sMi4vbV08ZSPCtsWSQg&args=YWJjZGU) [CJam interpreter (Depalindromization)](//cjam.aditsu.net#code=q_%2C2.%2Fm%5D%3Ce%23%C2%B6%E1%B9%96%E1%B9%9A%E1%B9%AD&input=abcdedcba) Jelly explanation: In Jelly, `¶` is the same as `\n`, so this is what Jelly sees: ``` q_,2./m]<e# ṖṚṭ ṖṚṭ Main link. Arguments: z Ṗ Pop Ṛ Reverse ṭ Append ⁸ (implicit) z ``` CJam explanation: In CJam, everything after `e#` on a line is a comment. So, this is what CJam sees: ``` q_,2./m]< Code q All input _ Duplicate , Length 2. 2.0 / Float division m] Ceil < Take ``` [Answer] ## Perl / JavaScript, 73 bytes Perl returns a palindrome and JavaScript 'de-palindromizes' the input string. ``` s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg ``` ### JavaScript Assumes the string is a valid palindrome already. All the work happens in the first section: ``` s=prompt();console.log(s.slice(0,-s.length/2)); ``` Stores input in `s`, then returns the first half (rounded-up) of the string. The rest of the script is pointless variable assignments: ``` eg=1;t=eg;s=$=reverse$_=eg ``` Try it here: ``` s=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg ``` ### Perl Must be run with `-pl`, eg: ``` perl -ple 's=prompt();console.log(s.slice(0,-s.length/2));eg=1;t=eg;s=$=reverse$_=eg' <<< 'test' # returns testtset ``` The code is basically two substitutions (`s///`), but using `=` as the delimiter instead of `/`: ``` s/prompt();console.log(s.slice(0,-s.length\/2));eg/1;t/eg;s/$/reverse$_/eg ``` The first, replacing `prompt();console.log(s.slice(0,-s.length\/2));eg` (which, admittedly will mess up your string if it contains something like `"prompt;console.logs.slice0,-s.length/2;eg"`...) with `1;t` which is `eval`ed, returning `t`, the second replaces the end of the string (`$`) with `reverse$_` which is then also `eval`ed and appends the original source string reversed. [Try it online!](https://ideone.com/e9Ggnv) [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E)/[V](http://github.com/DJMcMayhem/V), 14 bytes ``` û,ò"Bx$xh|ò"bP ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w7ssw7IiQngkeGh8w7IiYlA&input=YXNmYWRnYXNkZw) Palindromizes in 05AB1E [Try it online!](http://v.tryitonline.net/#code=w7ssw7IiQngkeGh8w7IiYlA&input=YWJjZGVkY2Jh) Depalindromizes in V, using [this answer](https://codegolf.stackexchange.com/a/98378/59376) from DrMcMoylex. [Answer] # Python 2 / [Nim](http://nim-lang.org), ~~76~~ 74 bytes ``` #[ s=input();print s+s[-2::-1]#let s=stdin.readLine;echo s[0..s.len div 2] ``` Palindromizes in Python, depalindromizes in Nim. Abuses comment syntax. Python and Nim both use `#` for comments. Python doesn't support block comments at all (except for multiline strings with `"""`), but Nim does with `#[ comment ]#`. We abuse this to comment out the Python (at the beginning) for Nim, then use the trailing `]` in the Python to start the Nim code, looking like a comment for Python. The Python code requires its input surrounded with quotes. The Nim code doesn't have this restriction. Tested on Python 2.7.8 and Nim 0.14.2. [Ideone it! -- Python 2, palindromizing](http://ideone.com/NUZkHa) ~~Ideone it! -- Nim, depalindromizing~~ Apparently the version of Nim Ideone uses (0.11.2) doesn't support multiline comments. Works on Nim 0.14.2. [Answer] # [Jelly](//github.com/DennisMitchell/jelly) / Pyth, ~~15~~ 14 chars ``` <Q.EclQ2*0"¶ŒB ``` [Credit where credit is due.](/questions/98776/palindrome-polyglot/98784?noredirect=1#comment240125_98784) [Try it online! (Jelly) (Palindromizes)](//jelly.tryitonline.net#code=PFEuRWNsUTIqMCLCtsWSQg&args=YWJjZGU) [pyth.herokuapp.com (Pyth) (Depalindromizes)](//pyth.herokuapp.com?code=%3CQ.EclQ2%2a0%22%C2%B6%E1%B9%96%E1%B9%9A%E1%B9%AD&input=%22abcdedcba%22) (trailing newline) [Answer] # Japt / JavaScript, 63 chars Lesson of the day: Japt/JavaScript polyglots are always a bad idea... ``` $Oq=1;$Oq &&0 alert(($U=prompt()).slice(0*$U,-$U.length/2));$Uê ``` ## JavaScript The first line sets the variable `$Oq` to 1, then performs a no-op with `$Oq &&0`. The second line prompts the user for an input string, assigning it to the variable `$U`, then slices it from index `0*$U` (always 0) to index `-$U.length/2`. This performs the necessary depalindromization; the result is then `alert`ed. The program ends on a ReferenceError because variable `$Uê` is not defined. ## [Japt](http://ethproductions.github.io/japt/?v=master&code=JE9xPTE7JE9xICYmMAphbGVydCgoJFU9cHJvbXB0KCkpLnNsaWNlKDAqJFUsLSRVLmxlbmd0aC8yKSk7JFXq&input=ImFiY2RlIg==) In Japt, anything between dollar signs is inserted directly into the transpiled source code. Other than that, each lowercase letter transpiles to e.g. `.q(`, unless the previous char was another lowercase letter, in which case it becomes `"q"`. A space is transpiled to `)`, and all missing parens are automatically added. The above program transpiles roughly to: ``` Oq=1;O.q()&&0 .a("l".e("r".t((U=prompt()).slice(0*U,-U.length/2))));U.ê() ``` This is then executed as JavaScript. `Oq=1;` sets the variable `Oq` to 1. This is never used again, so it's a no-op. `O.q()` is a function that clears STDOUT and returns `undefined`; this is falsy, so the entire `&&0 .a("l".e(...` part is not executed. The only part that really matters is `U.ê()`. Implicit input puts the input string in `U`, `.ê()` turns it into a palindrome, and implicit output sends the result to STDOUT. --- If function entries are allowed, the following will work for 34 chars: ``` X=>($X=X).slice(0,-X.length/2);$Uê ``` The first part defines an ES6 function, but it's still a full program in Japt. [Test it online!](http://ethproductions.github.io/japt/?v=master&code=WD0+KCRYPVgpLnNsaWNlKDAsLVgubGVuZ3RoLzIpOyRV6g==&input=ImFiY2RlIg==) [Answer] # Java / Brainfuck, 71 bytes ``` /*+[,>]<[<]>[.>]<<[.<][*/a->a.substring(0,Math.ceil(a.length()/2d));//] ``` Palindromizes in BF, depalindromizes in Java. For the sake of clarity, this is what matters to the BF interpreter: ``` +[,>]<[<]>[.>]<<[.<][->,..] ``` where the last loop containing characters from the Java lambda is skipped because the pointer points to a null character at that point. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) / Java 8, 102 chars ``` //¹ûq interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}} ``` [Palindromize in 05AB1E.](https://tio.run/##MzBNTDJM/f9fX//QzsO7C7ky80pSi9ISk1MVfKuLSxJLMpMVyvIzUxRyEzPzNIJLijLz0qNjEzWrgyuLS1Jz9fJLS/QKgIIlGonRBrF6xaVJxWA1GgY6YIGc1Lz0kgwNTX0jbUNNTeva2v//E5OSUwA) [Depalindromize in Java 8.](https://tio.run/##Hco9DoIwFADg3VN0bKO26OoZnBgJw@uP@FBekT5IDOFgxk0PVg3rl6@FCfaxD9T6W87GfF7f92ODxGG4gAviPCcGRiemiF50gCRLHpCaqgY1l8/EodNxZN3/kSVURa3TaNN6ZLFb4R6o4atU5rg9KHValpwzWOedhR8) **Explanation 05AB1E:** ``` // # No-ops ¹ # First input û # Palindromize it q # Terminate the program interface M{static void main(String[]a){System.out.print(a[0].substring(0,a[0].length()/2+1));}} # No-ops ``` **Explanation Java 8:** ``` //¹ûq // No-ops interface M{ // Class static void main(String[]a){ // Mandatory main-method System.out.print( // Print to STDOUT: a[0].substring(0, // The substring of the input-argument from index 0 to a[0].length()/2+1));}} // the length of the input integer-divided by 2 plus 1 ``` ]
[Question] [ Inspired by [a recent challenge involving Fibonacci numbers](https://codegolf.stackexchange.com/questions/217137/pascals-fibonacci-triangle/) in which [OEIS](https://oeis.org/) was mentioned, I would like to present a challenge of creating a function that generates a wide array of different linear integer sequences, depending on user input. Specifically, the user should provide three inputs: 1. the kernel (a representation of the [recurrence relation](https://en.wikipedia.org/wiki/Recurrence_relation)). More about this below. 2. the starting value of every 'seed' needed for the sequence, and 3. the number of integers to generate and display. For example, the [Fibonacci sequence](https://oeis.org/A000045) has two members in the kernel and needs two starting seeds (0, 1). Then \$F(n) = F(n-1) + F(n-2)\$. The [Padovan sequence](https://oeis.org/A000931) has *three* members in its kernel and needs three seeds, (1,0,0). Then \$F(n) = F(n-2) + F(n-3)\$. I am not going to mandate the format of the 'kernel' input, though the natural form would be, I think, a list of the same length of the list of seeds, composed of integers corresponding to the weight to give to each of integers in the previous row. This means that the kernel of the Fibonacci sequence, which adds together the previous two numbers, can be represented as (1,1). By contrast, the kernel of the Padovan sequence, which ignores the first member of the previous row and adds the second and third terms, can be represented as (0,1,1). Your code should be able to handle an arbitrary number of seeds and lists of arbitrary length. For each sequence, the number of members of the kernel and the length of the seed list should be the same positive integer. For the sake of this challenge, assume all members of the kernel and all seed values are integers (though I suspect that most of the responses to this challenge will work for all real numbers). Similarly assume the required sequence length will be a positive integer. My examples below use (parentheses) to encapsulate lists, but use whatever notation is most natural to your programming language. **Examples!** For the Fibonacci sequence, your function should take three inputs like ``` (1, 1), (0, 1), 10 ``` (that's kernel, seed, and sequence length), and generate ``` (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) ``` For the Padovan sequence, input like ``` (0, 1, 1), (1, 0, 0), 20 ``` should generate ``` (1, 0, 0, 1, 0, 1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37) ``` The [Perrin Sequence](https://oeis.org/A001608) takes input like ``` (0, 1, 1), (3, 0, 2), 10 ``` to produce ``` (3, 0, 2, 3, 2, 5, 5, 7, 10, 12) ``` For edge cases, ``` (1, 1), (0, 0), 5 ``` should produce ``` (0,0,0,0,0) ``` and ``` (-1, 0, 1, 0), (0, -1, 0, 1), 20 ``` should produce ``` (0, -1, 0, 1, -2, 2, -1, -1, 3, -4, 3, 0, -4, 7, -7, 3, 4, -11, 14, -10). ``` I suspect there are going to be some extremely concise responses to this. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` LinearRecurrence ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yczLzWxKCg1ubSoKDUvOfV/QFFmXkm0sq5dmoODcqxaXXByYl5dNVd1taGOYa1OtQGINDSo1QGKANlgMUMdAx2giBGqqDFQ1AiuFqYbyDMFC@iCdBmC@EBRCAdsBFftfwA "Wolfram Language (Mathematica) – Try It Online") Given the OP's background, I suppose this isn't too much of a surprise. [Answer] # Kakoune, 62 keystrokes ``` <a-l>"ndd<a-l>S "hddQxy<a-p><a-p>_S a*<c-r>h+<a-;> <backspace><esc><a-h>|bc k<a-i>ndd<a-j>Q:ex<tab> <c-r>nq K<a-x>d%<a-s><a-h>w<a-l>d<a-j> ``` (note the trailing spaces on line 1 and 2) Assumes the input in the following format, with the cursor at the start of the buffer: ``` number of items kernel separated with spaces in reverse seed separated by spaces ``` Gives the output as the numbers space separated. Here is a video of the solution in action, with a few minor human errors :) [![asciicast](https://asciinema.org/a/h9hMifsx15lRPcmtOrW0AkDvG.svg)](https://asciinema.org/a/h9hMifsx15lRPcmtOrW0AkDvG) [Answer] # [Factor](https://factorcode.org/), 38 bytes ``` [ [ 2dup v. prefix dup pop . ] times ] ``` [Try it online!](https://tio.run/##bY8xD4IwEIV3fsWLe0nBuOAPMC4uRhfC0NQzEIXWthIN4bdjgVQGvUsu7959N7yrkE6Z4XTcH3YZKoUbmYbuqIUrpxG3NBIW2pBzb22qxsHS40mNJItttD9ksNIIJ8so6nDukPjuR8H/yq9gyWRzv/XhkwecByr1cr24feDY8plwzJUGgcUDNvg9@@qHHDnSy1Ojjcd41@qFcdNKI0YBV9U@YeGxFWNshTl7AalqrSxhTUKWkHcSZvgA "Factor – Try It Online") Takes the inputs in the order of `kernel seed(reversed) length`, and prints out the desired sequence to STDOUT, one item per line. The seed must be of a sequence type that supports `pop` method, e.g. a `vector`. ``` [ ! ( kernel seed length -- kernel seed' ) [ ! inner quotation ( kernel seed -- kernel seed' ) 2dup v. ! evaluate next item using vector dot product prefix ! prepend to seed dup pop . ! remove the last item from seed and print ] times ! run the above `length` times ] ``` --- # [Factor](https://factorcode.org/), 45 bytes ``` [ [ 2dup reverse v. suffix unclip . ] times ] ``` [Try it online!](https://tio.run/##bY/NDoIwEITvPMXEO6RgvOgDGC9ejCfCoalLaOSn9odoCM@OtSAH4zbZrzs7c9iSC9vp6Xo5nY97yA530i3VaLitQkt6@jgMlCZrX0rL1sLQw1EryOAQnc57GKG5FVUUDRiQ@jd6sj@/L@M0iMwPYwix1cCCOmDrmS1xtnCJzaGUIVS2EKsC7PC78zVOOXJkN6egqSdtCH0C48pSPuFaUUuFBAWsbPxlhXdv4jjeYL65gOga1fnQlrioIGrienoD "Factor – Try It Online") Taking the seed in the given order costs 8 bytes for `reverse<space>` which is needed for dot product, but 1 byte can be saved by replacing `dup pop` with `unclip`. [Answer] # [Haskell](https://www.haskell.org/), ~~54~~ 49 bytes ``` g k(x:r)n=take n$x:g k(r++[sum$zipWith(*)k$x:r])n ``` [Try it online!](https://tio.run/##ZYzBCoMwEETvfsUcPCQ1QmLpReon9NxDyCEHqSG6SGJBSv89VUMvLSzM7rydGWz0/Tim9IBnaxs4dYv1Pahc290KVaXjcypfbr67ZWAn7jcSDKc0WUfoMNn5hjk4WqC3BCIIbzAvoiCOaw1dgGkllBHQ8hAlucgmtpE72DWvzT88H7D5Sea@4@OSXZkjAvUX1vlWubeAMekD "Haskell – Try It Online") Use as `g kernel seed n`. Previously, the function `g` only took the seed and the kernel as input and recursively build the sequence as an infinite list, with a second function truncating this infinite sequence to the given length with `take n`. However, it turns out we can just incorporate this truncation into `g` because of lazy evaluation, saving 5 bytes. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes Inputs are the seed, then the kernel and the number of integers last. Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -2 bytes! ``` λ£³ā₆*O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3O5Diw9tPtL4qKlNy////2gDHQVdQx0FIGUYy2VkwBUN4wHJWAA "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvj/PzmxRMFOITk/JVUvMSlVwcZGj@vc7kOLD20@0vioqU3Ln0uPi6s8IzMnVaEoNTFFITmxOJUrJZ9LAQhSkzPyFZRUQEJKCjUKJUUK6tbqCuoxeepAnn5@QYl@fnFiUmYqlIJbAtSfl/r/f7SBjoJhrLWhgXW0IYjFBaKAYgax1kZAMZAsRNgYLGwEUYoQhig1hesG8nUhJhhCTIDxQOq4AA) The challenge reads like it's made for the recursive list generation builtin `λ` ;) `λ£` takes the seed and the number as input and generates the first terms of the sequence starting with the values from the seed. `²ā₆*O` is executed to generate each `a(n)`: `²` pushes the second input, the kernel. `ā` pushes the range `[1,2,...,len(kernel)]`. For each `k` in this range `₆` gets the previous value `a(n-k)` to get the new list `[a(n-1), a(n-2), ..., a(n-len(kernel))]`. `*` multiplies this element-wise with the kernel. `O` sums up all values to generate `a(n)`. --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes First input is the number of integers, then the the seed and the kernel last. ``` FDŠR*Oª}¹£ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fzeXogiAt/0Orag/tPLT4/38jA65oAx0FXUMdBSBlGMsVDWMCyVgA "05AB1E – Try It Online") 1 byte longer without `λ`. ``` F } # iterate input times D # duplicate the current sequence (initially: seed) Š # triple swap -> stack: [sequence, kernel, sequence] R # reverse the current sequence * # multiply element-wise with the kernel O # take the sum ª # append the new value to the sequence ¹£ # take as many numbers as required ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~72~~ ~~67~~ 64 bytes Takes as input \$k\$, \$s\$ and \$n\$, which are the kernel, seed, and number of integers to display, respectively. ``` lambda k,s,n:s[exec("s+=sum(map(int.__mul__,s[::-1],k)),;"*n):n] ``` [Try it online!](https://tio.run/##ZY/dboMwDIXveQqrV8lmpiS0Y2PiSRhCbKNqVUjRAvt5euY4Kes0KZGPT@zPzvg9Hc42W/bl89K3w8tbCyd0aAtXdV/dq9i429LNgxjaURztdNc0w9w3DbqqKFJd40lKfNrcWFnYevk8HPsOdJEQAxyChRK6j7anznGehJQJnOdp/O@O78QWexHbJJQlV8ql0gg0BioVolYJSz4GIUPYITxQSsqQl23rtcL3UaRMkTTUGjN@XjGBFGBb5uUIj@STpe8D1tCILP@Lzphh4lYxY4phSgBp32Hq5Ponfp0ds34PVaTrVioWXpy4/pVDKiztDX9pbLrloIKi2Wl@@VSq/XgWqv4B "Python 3 – Try It Online") ### [Python 3](https://docs.python.org/3/), 72 bytes ``` f=lambda k,s,n:len(s)//n*s or f(k,s+[sum(map(int.__mul__,s[::-1],k))],n) ``` [Try it online!](https://tio.run/##ZY/RboMwDEXf@Qo/JptZk0DLisSXIISYRtWqEFADnfb1zHEo6zQpKNcX@1xn/J7Og02W5VR0Tf/x2cAVHdq8a61wcrezLw6GG5wE2a@lm3vRN6O42Omtrvu5q2t0ZZ7HusKrlBVauXydL10LOo@IBA7BQgHtveloaJwnIWUEwzyN/93xRljhk3hMQlFwp1xKjUAJUKpwaxWx5GMQEoQ9wjuVpAx5SVptHX6ObqoUSUOja8W/N0wgBVjKvAzhSD5Z@hCwhiKS7C86YYZZt1orphimBJD2E6aKnl/i19kz6/dQR7xtpdbGh7Ou/@SQCkt7w38UG6d8qaAoO84ej4q1j2ehqh8 "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 28 bytes ``` 0{"1(}.@],1#.]*1>@{[)^:(0{[) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DaqVDDVq9RxidQyV9WK1DO0cqqM146w0DIDUf02u1OSMfAUNQwNrQwVDTYU0oEZDqJgRWEzBACQKpBQMUNRCxI2B4kb/AQ "J – Try It Online") There are a lot of ugly mechanics in this solution, even though the underlying "power of" verb `^:` solves the problem nicely. The issue is that we have only two arguments in J, and have to get 3 pieces of information into the verb, so have to make one of the arguments do double duty, and then waste a lot of bytes de-structuring. J902 has the `F:` conjunction which expresses recurrences naturally, but you have use the awkward and verbose "terminate fold" `Z:` to express "n iterations". The other approach I tried was to create the powers of the appropriate matrix (the recurrence as the top row, stacked on the identity matrix with the last row cut off), and multiply those by the seed. Also a nice solution, but requires enough mechanics that I couldn't get the byte count down. ## [J](http://jsoftware.com/), another approach, 29 bytes ``` 0{"1(}.@],1#.*)/@|.\@(0}#&>/) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DaqVDDVq9RxidQyV9bQ09R1q9GIcNAxqldXs9DX/a3KlJmfkKwDVGyqkKWgYGljrWBkqGMKEDYESBiAJI6iEggFMyhgoYYSsByj1HwA "J – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Full program. Prompts for seed (reversed of OP's), then required length, then kernel (OP's). ``` ⎕(⌽⊣≢⍛↓(⊢,⍨⊣+.×≢⍛↑)⍣⎕)⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jvqkaj3r2Pupa/Khz0aPe2Y/aJms86lqk86h3BVBMW@/wdJj4RM1HvYuByjWBGKT3vwIYFHABtWsY6CgYanIZGnBpGIJZyHJAEaC0gSaXEVAapBBDhTFYhRHEAKwqIAaYYjMeKHVoPcQOQ4gdcC5IEwA "APL (Dyalog Extended) – Try It Online") `⎕(`…`)⎕` apply the following tacit function with kernel and seed as left and right arguments:  `(`…`)⍣⎕` prompt for required length, and apply the following tacit function that many times:   `≢⍛↑` take length-of-kernel elements from the (reversed) seed/list   …`+.×` dot product with:    `⊣` the kernel   `,⍨` append:    `⊢` the seed/list  …`≢⍛↓` drop as many elements as there are elements in:   `⊣` the kernel  `⌽` reverse --- Old solution using a function kernel: ## [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ([SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")) Anonymous infix lambda, taking seed as right argument and required sequence length as left argument. Prompts for kernel as a prefix function that takes a list as argument and computes the next term. ``` {⍺↑,∘⎕⍨⍣⍺⊢⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8f9KhtQvWj3l1ApK13eLrGo85FEJ7mo7aJj3r2PurdWvsfrKBtos6jjhmP@qY@6l3xqHcxSKhrEVg6DWjGo96@R13Nj3rXPOrdcmi9MUhz39TgIGcgGeLhGfzf0EAhTUHDQEfBUJNLwxBEBXFxGYEFgTyguAFQHCQNlYKoNwZLGaFKmUJNMsAwCSh4aD3EOJA1cDZIbRAA "APL (Dyalog Unicode) – Try It Online") (with helper operator to make kernel input easy) `{`…`}` "dfn"; left and right arguments are `⍺` and `⍵`:  `⊢⍵` on the seed  …`⍣⍺` apply the following function as many times as terms required:   `,∘`…`⍨` catenate self with result of applying the following function:    `⎕` get kernel function from console  `⍺↑` take as many terms as required [Answer] # ARM Thumb-2, strict ruleset, 34 bytes Machine code: ``` 4563 d90d 4664 2700 000a 3c01 5705 f912 6b01 fb06 7705 d8f8 7017 3101 3b01 e7ef 4770 ``` Overcommented assembly with C-callable wrapper (not part of score, just for testing with C) ``` // Now with C-style comments because no ARM syntax highlighting .syntax unified .arch armv6t2 .thumb // Params (note kernel_length is r12, not r2) // int8_t *kernel: kernel (test case order) ker_p .req r0 // int8_t *seed_out_ptr: seed/output array out_p .req r1 // uint32_t kernel_length: Kernel length in elements ker_len .req r12 // uint32_t seq_length: Sequence length in elements seq_len .req r3 // Local temps // Clobbers r4-r7. i .req r4 // Loop counter j .req r2 // seq_p copy for loop k_co .req r5 // Kernel coefficient f_i .req r6 // F(n - i) dot_p .req r7 // Dot product // Custom calling convention, hence the dot. See below for a C wrapper. .globl .linear_gen .type .linear_gen, %function .thumb_func .linear_gen: .Lmain_loop: // Loop while seq_len > ker_len cmp seq_len, ker_len bls .Lmain_loop.end // Loop backwards from kernel_length to 0. mov i, ker_len // Initialize dot product at 0 movs dot_p, #0 // Make a copy of the pointer movs j, out_p .Ldot_product_loop: // Decrement loop counter subs i, #1 // Load kernel coefficient ldrsb k_co, [ker_p, i] // Load F(n - i), incrementing the pointer as we go. (wide insn) ldrsb f_i, [j], #1 // dot_p += f_i * k_co (wide insn) mla dot_p, f_i, k_co, dot_p // loop while i is > 0 (mla doesn't affect flags) bhi .Ldot_product_loop .Ldot_product_loop.end: // Store the dot product into out_p[kernel_length]. // We can just reuse j because the loop will leave it at // this point. strb dot_p, [j] // Increment out_p adds out_p, #1 // Decrement seq_len subs seq_len, #1 // loop b .Lmain_loop .Lmain_loop.end: // return bx lr #ifdef C_WRAPPER // C wrapper .global linear_gen .type linear_gen, %function .thumb_func // void linear_gen(int8_t *kernel, int8_t *seed_out, uint32_t kernel_len, uint32_t sequence_len); linear_gen: // save callee saved registers push {r4-r7, lr} // fix parameters mov ker_len, r2 // call the function bl .linear_gen // restore registers and return pop {r4-r7, pc} #endif // C_WRAPPER ``` C signature (for wrapped version) ``` void linear_gen(int8_t *kernel, int8_t *seed_out, uint32_t kernel_len, uint32_t sequence_len); ``` The arrays are `int8_t *` as it is the easiest type to work with due to how offsetting works, but the algorithm would work with any integer type. This version is VERY awkward from an implementation standpoint. Specifically, these are the issues: * The kernel is in the opposite order of the seed, requiring one pointer to index forwards and the other to index backwards. Thumb doesn't have negative register indexing. + This extra pointer pushes us to use a high register which is very restrictive in what you can do with narrow instructions. * The sequence length is always greater **or equal** to the kernel length. This requires the comparison to be *before* the loop. Now, let's bend the rules a tiny bit to make things **significantly** less awkward. * The kernel order is **reversed** from the test cases. + This simplifies indexing, saving 4 bytes. - We only need one counter, removing a `movs` - This also allows us to keep everything in low registers, meaning we can still index the `strb`, with `ker_len` instead of `j`. - We can use the narrow form of `ldrb` in the loop. * The sequence length is always **greater than, never equal** to the kernel length. + This means we can move the branch to the bottom, saving 2 bytes. + Don't know why this isn't the case...running zero times is a little silly, and none of the test cases show the length being equal to the sequence length. Under this altered ruleset, we save 6 bytes and can be a lot more orthodox in the parameters, storing them in the traditional `r0, r1, r2, r3` instead of `r0, r1, r12, r3`. ## ARM Thumb-2, altered ruleset (non-competing?), 28 bytes Machine code: ``` 1a9b 0014 2700 3c01 5705 570e fb06 7705 d8f9 548f 3101 3b01 d8f3 4770 ``` Commented assembly (Differing lines marked with `// <`) ``` // Now with C-style comments because no ARM syntax highlighting .syntax unified .arch armv6t2 .thumb // Params // int8_t *kernel: kernel (reversed from test case order) ker_p .req r0 // int8_t *seed_out_ptr: seed/output array out_p .req r1 // uint32_t kernel_length: Kernel length in elements ker_len .req r2 // <- not r12 // uint32_t seq_length: Sequence length in elements (> kernel_length) seq_len .req r3 // Local temps // Clobbers r4-r7. i .req r4 // Loop counter k_co .req r5 // Kernel coefficient f_i .req r6 // F(n - i) dot_p .req r7 // Dot product // custom calling convention. See linear_gen for a C wrapper. .globl .linear_gen .type .linear_gen, %function .thumb_func .linear_gen: // Subtract kernel_length from sequence_length to get // the iteration count. subs seq_len, ker_len // <- since ker_len is a low reg now, we can subtract .Lmain_loop: // Loop while seq_len > ker_len // cmp seq_len, ker_len // <- we no longer need the branch at the top, // bls .Lmain_loop.end // <- because we know it is never equal // Loop backwards from kernel_length to 0. movs i, ker_len // Initialize dot product at 0 movs dot_p, #0 .Ldot_product_loop: // Decrement loop counter subs i, #1 // Load kernel coefficient ldrsb k_co, [ker_p, i] // Load F(n - i) ldrsb f_i, [out_p, i] // <- not wide insn, just register+register // dot_p += f_i * k_co (wide insn) mla dot_p, f_i, k_co, dot_p // loop while i is > 0 (mla doesn't affect flags) bhi .Ldot_product_loop .Ldot_product_loop.end: // Store the dot product into out_p[kernel_length] strb dot_p, [out_p, ker_len] // <- Instead of j, we can use ker_len. Same size. // Increment out_p adds out_p, #1 // Decrement seq_len subs seq_len, #1 // Loop while not zero bhi .Lmain_loop // <- Use flags from subs for loop .Lmain_loop.end: // return bx lr #if 1 // C wrapper .global linear_gen .type linear_gen, %function .thumb_func // void linear_gen(int8_t *kernel, int8_t *seed_out, uint32_t kernel_length, uint32_t sequence_length); linear_gen: // save callee saved registers push {r4-r7, lr} // fix parameters // mov ker_len, r2 // <- kernel_len is already r2 // call the function bl .linear_gen // restore registers and return pop {r4-r7, pc} #endif ``` ***Technically***, we could go further and say that the sequence\_length should not include kernel\_length for another 2 bytes, but that is DEFINITELY pushing it. 😂 [Answer] # [Haskell](https://www.haskell.org/), ~~70~~ 65 bytes ``` f k s n=take n$foldl(\a t->a++[sum$zipWith(*)(drop t a)k])s[0..n] ``` [Try it online!](https://tio.run/##ZU3LCsIwELz7FXPoIbGppIo39Qv05MFDDLKtLS1t02IigvjvNTUeBGHZnQczW5FtirYdxxINLMzWUVPARGXfXlt2JrhkR3Gs7L2LnvVwql3F5pxdb/0AB@KN5lbJxcLosaPaYIuOhsMFw90d3W1voGzVPxCVIGTI8QIjkYmcY5OoGZhKRaqFktNOJRdBgh@pBSYoA1z@m6uPufTwNzk538w6qDJEBJLwyt8P9cy3zqD1@AY "Haskell – Try It Online") * saved 5 thanks to @Laikoni ``` take n$ - return n elements foldl(...)s - fold adding to seed [0..n] - index of first seed to use(had to add n because infinite list didn't worked) (\a t->a++ - again, add to seed [sum[x*y|(x,y) - sum of terms zip(drop t a)k]- make pairs dropping t elements from list ``` [Answer] # [Scala](https://www.scala-lang.org/), ~~75~~ 71 bytes *-4 bytes thanks to [user](https://codegolf.stackexchange.com/users/95792)!* ``` k=>n=>1.to(n-k.size)./:(_)((x,_)=>x:+(x.reverse,k).zipped.map(_*_).sum) ``` [Try it online!](https://tio.run/##jY4/a8MwEMV3f4ob71pHtVy6GGTomCFTx1KMaivgyFFUSwkmpZ/dlewGpxBKp/v3u/eeq2Unx8P7TtUeNrI1oAavTOPg2Vr4TABOsoPt0dR5AS/q43Vt/BuIEkKN5Xq19KMWpRElZ/6AZqWZa8@K2EOBFSEOaUWiHIp7HFivTqp3KtXEzq21qmF7abG6q4i5455GgEZtJ3vUi38K7nowRUxDIOacqAkNoaMkpLd9a3xncJIIL8hT4JTGb8zmlmdEt8h4XuDQhkUWpvxf/OPE53/o/04SlZ9ug6vZm8/QD39ZXgIlX8n4DQ) [Answer] # [Zsh](https://www.zsh.org/), ~~87~~ 81 bytes *-6 bytes thanks to @pxeger*. *-6 bytes for a score of **75 bytes** by taking the kernel in reverse*. ``` K=(${(Oa)=1}) # Use "K=($=1)" if kernel is reversed S=($=2) repeat $3-$#S S+=$[`printf +%s\*%s ${S[-$#K,-1]:^K}`] <<<$S ``` ~~[Try it online!](https://tio.run/##TcmxCsIwFIXhPU9xwdsmsQZyKy6SPEEGh4y1QocWXUJpioOlzx4TXFwOfOf/xGeahBTJWYGbuA3S0i6Zz7KtZMs4j8MKeFZ48DAvr7BOoN4QoKni/VhFwM13ObqTov76cHtd@8ZiF3pmjEGfJGMTcALiwHVZ0v@H5nApVgS5FubzBw6tTl8 "Zsh – Try It Online")~~ [Try it online! (81 bytes/original input)](https://tio.run/##TcmxDsIgFIXhnae4ibcBrCTcGhcDT8DgwFhr2qGNLqYpnSQ8O0JcXE7ynf8TnnkRMmZnBUZxm6SlJJkvsp1k27zO0w54Vnjw4FuL/bhur/e@QNuE@7EJgNH3pbqTouH6cGkcmDEGfU6MLcAJiAPXdUnD/6M5XKoVQcmV5fyBQ6fzFw "Zsh – Try It Online") [Try it online! (75 bytes/reversed kernel)](https://tio.run/##TYm9DoMgGEV3nuIm/QyiJQGbLg08ASOjtbGDpF0aI041PjtCunS5P@d84yuFWmzJ2ZqsFsyX7gRbpnl6rqCLpJOHby3147y8P2tAW8V7U0XQ5vts3Vnq4fZw@zgwYwz5tDMWwDU0B1cltcI/URzX8rODgvxBWXaenUoH "Zsh – Try It Online") Takes the lists as space-delimited. ``` kern=(${(Oa)=1}) # = split on $IFS, (Oa) reverse order seed=($=2) # = split on $IFS repeat $3-$#seed;{ # repeat's argument is interpreted arithmetically tmp=(${seed[-$#kern,-1]:^kern} # zip the last len(kern) arguments of seed with $kern printf -v next +%s\*%s $tmp # next='+s_(n-1)*k_1+s_(n-2)*k_2 ...' seed+=$[next] # interpret $next arithmetically, append to $seed } <<< $seed # output seed array ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 8 bytes ``` Ṛḋ⁵ṭƲ⁴¡ḣ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlkPd3Q/atz6cOfaY5seNW45tPDhjsX///@PNtBR0DXUUQBShrH/jQz@R8N4QDIWAA "Jelly – Try It Online") Takes three arguments in this order: seed, number of repetitions, kernel. ## Explanation ``` Ṛḋ⁵ṭƲ⁴¡ḣ Main dyadic link (third argument can't be accessed tacitly) ¡ Repeat [on the first argument, the seed] ⁴ (second argument) times Ʋ ( Ṛ Reverse ḋ Dot product ⁵ with the third argument, the kernel ṭ Append that to the first argument Ʋ ) ḣ Take the first (second argument) items [because we produced too many terms] ``` [Answer] # [R](https://www.r-project.org/), 62 bytes ``` function(k,s,n)for(i in 1:n){show(s[1]);s=c(s[-1],rev(k)%*%s)} ``` [Try it online!](https://tio.run/##bY5PCwIhEMXv@ylkYcEJF3SjS7HXzt1jD2ZKsqGhtkHRZzdx/1AQyPic@fnmuajaqO5GBG0N7oknBpR1WCNtENsaePmLfWB/ZB3sfCuSqllHnBxwD9Wq8vCON6dNwOVen6zhQugSCoUFZoQBQQLTfDMKxQQe@NkO3EwYTbN0MppEetKkmy9cuiT@0OtMN7/mT@msXxKgOUI23SzUlfuAgkxFcC8nvB7XsxHOv@bWmCh@AA "R – Try It Online") [Answer] # [Raku](http://raku.org), 50 bytes ``` {@^k;(|@^s,{sum @k Z*@_[@_-1…@_-@k]}…*)[^$^z]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iEu21qjxiGuWKe6uDRXwSFbIUrLIT7aIV7X8FHDMiDlkB1bC2RpaUbHqcRVxdb@L06sVFByy0zKz0tMTs60UlDSUUjTsDFUMLTTUbAxAFOGBprWCmB1AYkp@WWJeVYKClB1QAUQlYYKBgoGQIaRgeZ/AA "Perl 6 – Try It Online") * `@^k` (the kernel), `@^s` (the seed), and `$^z` (the count of elements to return) are the parameters to the function. * `(|@^s, { ... } … *)` is an infinite sequence starting with the flattened seed array. The brace expression is a function which generates successive elements; it takes the entire list of previous elements in the `@_` variable. * `@_[@_-1 … @_-@k]` is the last N elements of the sequence so far, in reverse order, where N is the size of the kernel list. * `sum @k Z* @_[...]` computes the sum of the kernel zip-multiplied with the previous N elements of the sequence. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 90 67 bytes -Thanks to mazzy yet again for putting me to shame with a 23 byte save!! ``` $r,$s,$l=$args;for(;$l-$s.Count){$s+=&{$r|%{$a+=$_*$s[--$i]};$a}}$s ``` [Try it online!](https://tio.run/##XZBha8IwEIa/91cccko7ryNpdTpKQfAHbGwfRcTVuLllrUtaNqj97d01VmHLcbnc8T7vQY7FtzL2TWnd4r7Ks/JQ5GndoiG0hDrFrXm1yb4wfoI6RHu7LKq8DGq043RUozkNa9yOU9zcoF2FIR7WTYLbpkHbNp638D3ywRckSQYEfkyCIn5IQQCuoZhzyjEjHsoo@AtI1gh@RB3gGpIuu4gcPnHwPbMk7yji8Zzi2dmndxGuuKWiJ2Om5iTjDogn/9TdximBoD4CL4ATDKH2gA9@KJMrTYBWqR0XrXK@1c9RZaXaQQq4OQuNspUueTC6/u2FPsOOddrVo11Wtiw@H17e2Wa9qOG5yjJlLeOD3mkAofri7rJqkMDTZcVV03hN@ws "PowerShell – Try It Online") [Answer] # [C (tcc)](http://savannah.nongnu.org/projects/tinycc), ~~99~~ 98 bytes ``` t,i;f(k,s,n,z)int*k,*s;{for(;n--;s[z-1]=t)for(t=i=!printf("%d ",*s);i<z;s[i]=s[++i])t+=s[i]*k[i];} ``` [Try it online!](https://tio.run/##bVDLasMwELznK1xDwXJGxHq4TlH9JcaHkhIQJm6I1EtCvt3dteIE2iBhaWdnZkfeybjbTVOEd/tiQMCIs/BjLAeUwV3236fCjVK60J2l6tsoGImtb1@OJ6Lti/z1K8uJK5z/OBPN923o1mvfi7huuSwH@rjrROxsUF3fXhTU1a24DnNd3etBp35Gu1o4C1Y9sME84c2YmXl64dmFt5BsGvhwqm9AGiDvxAWXqcH43Dh8@jErxGWV0f9SCPSYClq4408MRZ4Lt8o2m46eREvDoMYWykArGNvPIo2goSuYvyKFCixMYpazgSWLBu9QGuqNffQWpklWBsHw/H9WhkxYrEnMcuIonTQWgS2fRL6tRKsRak5p722ZkkmORXfaBtKCR9HRQDZzWqkoOx9kdJ1@AQ "C (tcc) – Try It Online") * saved 1 thanks to @ceilingcat. * essentially moves the seed array along the sequence, printing the first element, n times. f(k,s,n,z) - input: kernel, seed, number, length of k,s {for(;n--;s[z-1]=t) - repeat n times, updating last seed with next term for(.. i<z;s[i]=s[++i]) - loop trough k,s swapping s back printf("%d ",\*s) - and printing first seed t+=s[i]\*k[i] : accumulate next term [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` Fζ⊞ηΣEθ×κ§⮌ηλI…ηζ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo0pTIaC0OEMjQ0chuDRXwzexQKNQRyEkMze1WCNbR8GxxDMvJbVCIyi1LLWoOFUjQ1NHIUcTBKy5Aooy80o0nBOLgURlck6qc0Z@AcicKrD0///R0QY6CoZAFKujEG2sowDkGQGZhgax/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fζ ``` Generate `l` more terms: ``` ⊞η ``` Push to the seed... ``` ΣEθ×κ§⮌ηλ ``` ... the dot product of the kernel and the reversed seed. ``` I…ηζ ``` Print the first `l` terms of the seed (it's slightly golfier to generate extra unwanted terms). [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ↑⁴¡ȯΣz*²↔⁰ ``` [Try it online!](https://tio.run/##yygtzv7//1HbxEeNWw4tPLH@3OIqrUObHrVNedS44f///0YG/6N1DXUMdIA49n@0gQ6EEwsA "Husk – Try It Online") ``` ↑⁴ # first n=arg3 elements of ¡ȯ ⁰ # list created from repeatedly applying to arg1 and appending results: Σ # sum of z* # elementwise products of ² # arg2, and ↔ # reverse of arg1 ``` [Answer] # [Julia](http://julialang.org/), 46 bytes ``` g(k,s,n)=try s[1:n]catch;g([0;k],[s;s'k],n)end ``` [Try it online!](https://tio.run/##ZU/BCoMwDL33K3JbC1Faxy4Tv6T0IG5zmZKJrbB9vVPDDm4h8JL38kLymHqq3WueW91hRDZVGt8QvTtzaOrU3MtWe1t2AX0s42FBNle@zMTDlCJU4BVo79AFBG83cNagkLCkXYUVpSz@xeMmFj9O2bdNnIS1YkHIvmImvZO9Kih1e45AQAxyn4IlhpE49azJ7NpWU57nZk8atT73AQ "Julia 1.0 – Try It Online") ]
[Question] [ One way to represent a natural number is by multiplying exponents of prime numbers. For example, 6 can be represented by 2^1\*3^1, and 50 can be represented by 2^1\*5^2 (where ^ indicates exponention). The number of primes in this representation can help determine whether it is shorter to use this method of representation, compared to other methods. But because I don't want to calculate these by hand, I need a program to do it for me. However, because I'll have to remember the program until I get home, it needs to be as short as possible. ## Your Task: Write a program or function to determine how many distinct primes there are in this representation of a number. ## Input: An integer n such that 1 < n < 10^12, taken by any normal method. ## Output: The number of distinct primes that are required to represent the input, as outlined in the introduction. ## Test Cases: ``` 24 -> 2 (2^3*3^1) 126 -> 3 (2^1*3^2*7^1) 1538493 -> 4 (3^1*11^1*23^1*2027^1) 123456 -> 3 (2^6*3^1*643^1) ``` This is [OEIS A001221](https://oeis.org/A001221). ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [MATL](https://github.com/lmendo/MATL), ~~4~~ 3 bytes *-1 byte thanks to Luis Mendo* ``` YFz ``` [Try it online!](https://tio.run/##y00syfn/P9Kt6v9/QyMA) ``` YF Exponents of prime factors z Number of nonzeros ``` Original answer: ``` Yfun ``` [Try it online!](https://tio.run/##y00syfn/PzKtNO//f0MjAA "MATL – Try It Online") A ver`Yfun` answer. ``` (Implicit input) Yf Prime factorization u Unique n Numel (Implicit output) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes another pretty boring answer... ``` fg ``` A full program accepting a numeric input and printing the result **[Try it online!](https://tio.run/##MzBNTDJM/f8/Lf3/f0NTYwsTS2MA "05AB1E – Try It Online")** ### How? ``` fg - implicitly take input f - get the prime factors with no duplicates g - get the length - implicit print ``` [Answer] # Mathematica, 7 bytes ``` PrimeNu ``` Yup, there's a built-in. # Mathematica, 21 bytes ``` Length@*FactorInteger ``` The long way around. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 2 bytes Yet another pretty boring answer... --- J. Allan ``` ḋl ``` [Try it online!](https://tio.run/##S0/MTPz//@GO7pz//w1NjS1MLI0B "Gaia – Try It Online") * `ḋ` - Prime factorization as **[prime, exponent]** pairs. * `l` - Length. [Answer] # Python 2, 56 bytes ``` f=lambda n,p=2,k=1:n/p and[f(n,p+1),k+f(n/p,p,0)][n%p<1] ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~31~~ 30 bytes ``` &`(?!(11+)\1+$)(11+)$(?<=^\2+) ``` Input is in unary. *Thanks to @MartinEnder for golfing of 1 byte!* [Try it online!](https://tio.run/##K0otycxL/B@Tos2lovVfLUHDXlHD0FBbM8ZQW0UTzFLRsLexjYsx0tb8/9/QyAwA "Retina – Try It Online") (includes decimal-to-unary converter) ### How it works Since the program consists of a single regex with the `&` modifier, Retina simply counts the amount of *overlapping* matches. The input is assumed to consist of **n** repetitions of **1** and nothing else. The negative lookahead ``` (?!(11+)\1+$) ``` matches at locations between **1**'s that are *not* followed by two or more **1**'s (`11+`), followed by one or more repetitions of the same amount of **1**'s (`\1+`), followed by the end of input (`$`). Any composite number **ab** with **a, b > 1** can be written as **b** repetitions of **a** repetitions of **1**, so the lookahead matches only locations followed by **p** repetitions of **1**, where **p = 1** or **p** is prime. The regex ``` (11+)$ ``` makes sure **p > 1** by requiring at least two **1**'s (`11+`) and stores the tail of **1**'s in the second capture group (`\2`). Finally, the positive lookbehind ``` (?<=^\2+) ``` verifies that the entire input consists of **kp** occurrences (**k ≥ 1**) of **1**, verifying that **p** divides the input. Thus, each match corresponds to a unique prime divisor **p**. [Answer] # Bash + GNU utilities, 33 * 1 byte saved thanks to @Dennis ``` factor|grep -Po ' \d+'|uniq|wc -l ``` [Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYGSiYGKmYGgExKbGFiaWxkC2sYmpmbVCSj6XAhCkJmfkK6jAtdQo/E9LTC7JL6pJL0otUNANyFdQV4hJ0VavKc3LLKwpT1bQzfmfkp@X@h8A). ### Explanation ``` factor| # Split input into prime factors grep -Po ' \d+'| # group factors onto lines uniq| # remove duplicates wc -l # count the lines ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly) a pretty boring answer... ``` ÆFL ``` A monadic link taking a number and returning a number **[Try it online!](https://tio.run/##y0rNyan8//9wm5vP////DU2NLUwsjQE "Jelly – Try It Online")** ### How? ``` ÆFL - Link: number, n ÆF - prime factorisation as a list of prime, exponent pairs L - length ``` [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 2 bytes ``` ml ``` [Try it online!](https://tio.run/##y8/INfr/Pzfn/39DU2MLE0tjAA "Ohm v2 – Try It Online") The two built-ins are right next to each other in the documentation lol. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes Yet another pretty boring answer... --- J. Allan ``` Æv ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9n///8NTY0tTCyNAQ "Jelly – Try It Online") A built-in. [Answer] ## [Alice](https://github.com/m-ender/alice), 10 bytes ``` /o \i@/Dcd ``` [Try it online!](https://tio.run/##S8zJTE79/18/nysm00HfJTnl/39DU2MLE0tjAA "Alice – Try It Online") ### Explanation ``` /o \i@/... ``` This is just the standard framework for linear arithmetic-heavy programs that need decimal I/O. The actual program itself is then just: ``` Dcd ``` Which does: ``` D Deduplicate prime factors. Does what it sounds like: for every p^k which is a divisor n, this divides n by p^(k-1). c Push the individual prime factors of n. Since we've deduplicated them first, the number of factors is equal to the value we're looking for. d Push the stack depth, i.e. the number of unique prime factors. ``` [Answer] # JavaScript 45 bytes \*For @SEJPM request an explanation : what im doing here is this- im going from 2 - n (which changes, and eventually will be the biggest prime factor)- now if the current number divide n i want to count it only once(even though it can be a factor of 2\*2\*2\*3 - 2 is counted once)- so the "j" comes to the picture, when j is not specified in the call of the funcion - j will receive the value of "undefined" , and when n%i == 0 then i call the function with j=1 in the next call) - and then i only add 1 when j equals undefined which is !j + Function(n/i,i,(j=1 or just 1)). i dont change i in this matter becuase it may still be divisible by i again(2\*2\*3) but then j will equal 1 and it will not count as a factor. hope i explained it well enough. ``` P=(n,i=2,j)=>i>n?0:n%i?P(n,i+1):!j+P(n/i,i,1) console.log(P(1538493)==4); console.log(P(24)==2); console.log(P(126)==3); console.log(P(123456)==3); ``` if the last prime is very big than it will have max call stack- if its an issue i can make an iterative one [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~7~~ 5 bytes *Thanks to Martin Ender for 2 bytes off!* ``` {mF,} ``` Anonymous block (function) that expects the input number on the stack and replaces it by the output number. [Try it online!](https://tio.run/##S85KzP1fWPe/OtdNp/Z/XcF/IxMA) Or [verify all test cases](https://tio.run/##S85KzP1fWPe/OtdNp/a/asH/aCMTBUMjMwVDU2MLE0tjINvYxNQsFgA). ### Explanation ``` { } e# Define block mF e# List of (prime, exponent) pairs , e# Length ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ḋdl ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO7pSc//8NjYxNTM3@RwEA "Brachylog – Try It Online") ### Explanation ``` ḋ Prime decomposition d Remove duplicates l Length ``` [Answer] # Pyth, 3 bytes ``` l{P ``` [Test suite](https://pyth.herokuapp.com/?code=l%7BP&test_suite=1&test_suite_input=24%0A126%0A1538493%0A123456&debug=0) Length (`l`) of set (`{`) of prime factors (`P`) of the input. [Answer] # [Husk](https://github.com/barbuz/Husk), 3 bytes ``` Lup ``` [Try it online!](https://tio.run/##yygtzv7/36e04P///4amxhYmlsYA "Husk – Try It Online") ### Explanation ``` p -- prime factors u -- unique elements L -- length ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 2 bytes Yet another pretty boring answer... --- J. Allan ``` yl ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/78y5/9/QwsDAA "Actually – Try It Online") The first character can be replaced by `w`. [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 bytes ``` P}l ``` [Try it here!](https://pyke.catbus.co.uk/?code=P%7Dl&input=180&warnings=0&hex=0) [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ 67 bytes *1 byte removed thanks to @Mr.Xcoder* ``` lambda n:sum(n%k<all(k%j for j in range(2,k))for k in range(2,n+1)) ``` This times out for the largest test cases. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqrg0VyNPNdsmMSdHI1s1SyEtv0ghSyEzT6EoMS89VcNIJ1tTEySWjSyWp22oqfm/oCgzr0QjTcPQyAzIAwA "Python 3 – Try It Online") [Answer] # R + numbers, ~~30~~ 14 bytes *16 bytes removed thanks to @Giuseppe* ``` numbers::omega ``` Also, here is the [Try it online!!](https://tio.run/##K/qfpmCj@z@vNDcptajYyio/NzU98X@ahqGR5n8A) link per @Giuseppe. [Answer] # [Convex](https://github.com/GamrCorps/Convex), 3 bytes ``` mF, ``` [Try it online!](https://tio.run/##S87PK0ut@P8/103n////hkbGJqZmAA "Convex – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 5 bytes I don't know why it is called nu in Mathematica but omega in Pari/GP. ``` omega ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D8/NzU98X9iQUFOpUaegq6dQkFRZl6JApCtBOIpKaRp5Glq6ihEG5noKBgamQEJU2MLE0tjEM/YxNQsVvM/AA "Pari/GP – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 58 bytes *-4 bytes thanks to @Laikoni* ``` f n=sum[1|x<-[2..n],gcd x n>1,all((>)2.gcd x)[2..x-1]] ``` [Try it online!](https://tio.run/##LYyxCoMwFEX3fsUbHBLQQLSFVlTo0KFzR3EINWoweUqSFgv997SKd7lw7uUMwo1S66DMPFkPj4/z0rAbvpWd0Ej0pJf@antHQwdYupep@XcpkjplDJu4f7awAFY8FloTUtGUbYiu@5LwpglGKCyhnQ6wRfxdUCSwa3c6W4U@6oBYKVqIYFhru@Y53NHTEPgpOx8vGfwA "Haskell – Try It Online") **Explanation** Essentially generates all primes at most as large as `n` and filters them for being a factor of n and then takes the length of the result. ``` f n= -- main function sum[ ] -- output the length of the list 1|x<-[2..n], -- consider all potential primes <=n -- and insert 1 into the list if predicates are satisfied gcd x n>1, -- which are a factor of n all( )[2..x-1] -- and for which all smaller numbers satisfy (>)2. -- 2 being larger than gcd x -- the gcd of x with the current smaller number ``` [Answer] # Japt, ~~5~~ 4 bytes ``` â èj ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=4iDoag==&input=OA==) Get the divisors (`â`) and count (`è`) the primes (`j`). [Answer] # [ARBLE](https://github.com/TehFlaminTaco/ARBLE), 28 bytes ``` len(unique(primefactors(n))) ``` [Try it online!](https://tio.run/##SyxKykn9/z8nNU@jNC@zsDRVo6AoMzc1LTG5JL@oWCNPU1Pz////hiYA "ARBLE – Try It Online") *This is a very literal solution* [Answer] # [Dyalog APL](https://www.dyalog.com/), 17 bytes ``` ⎕CY'dfns' ≢∪3pco⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdPzc1PfH/o76pzpHqKWl5xepcjzoXPepYZVyQnA8UBSn5D1bDZWSiwMUFYRoamSmAAJxvamxhYmmMJG9sYmoGAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~63~~ 55 bytes A much more interesting answer... -8 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) (use an argument with a default for the post-adjustment of the result of primes from `0` to `1` -- much better than a wrapping lambda!!) ``` f=lambda n,o=1:sum(n%i+f(i,0)<1for i in range(2,n))or o ``` A recursive function taking a positive integer, `n`, and returning a positive integer, the count. **[Try it online!](https://tio.run/##TcmxCoAgEIDhuZ7ilsAjhxJapB7GSOugTjEbenrLpqYf/i/cafOscnbTbo55McDST70@r0NwQ60TJDsce@cjEBBDNLxaoSQjvsvnAsme6W@gBtR1FSJxEgUluK@I@QE "Python 2 – Try It Online")** Really inefficient, don't even bother with the other test cases. [Answer] # J, 12 bytes ``` {:@$@(__&q:) ``` `q:` is J's prime exponents function, giving it the argument `__` produces a matrix whose first row is all nonzero prime factors and whose 2nd row is their exponents. We take the shape `$` of that matrix -- rows by columns -- the number of columns is the answer we seek. `{:` gives us the last item of this two items (num rows, num columns) list, and hence the answer. [Try it online!](https://tio.run/##RY5BCsIwEEX3OcWniE2ClmYmjRqoFA/gEdqFNIgbkS7Fs8ekUhuYMPBm/ptHDBNajxqp4tt3m04Ow/blVVSiqFCG1pfY4eMRJiGulwpkMb/9GQRJPWvujZqRIbcgzsgkRPrwxw0f7YkztpBpSxuTPsod1bTOEdvGrTEuG7Szs0eMt/szmTllMFrIUNQqH5Xli@GXEL8 "J – Try It Online") [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 67 bytes ``` n->{int c=0,p=1;for(;p<n;)if(n%++p<1)for(c++;n%p<1;n/=p);return c;} ``` [Try it online!](https://tio.run/##NU/LboMwELznK0aRkECAW0ISNXWI1GMPVQ9RT1EOLo/IlKwtY1IhxLdTk7aHfc2OdnZqcROx0iXVxddu0t1nI3PkjWhbvAlJGBbAH9paYV25KVng6nb@0RpJl9MZwlza4E4FaneQdVY2rOoot1IReyX7QcL077o0wiqDCtlE8WGQZJFnj5HOEl4p43O9Jx7IyicvDPU@CWYwD0NOnps4PWQ64Ka0nSHkfJz4XdGR4M@n6BlUfsO1p/OA1TpCstq6tEmf1rt0ntL1Zovx/1Xg2Le2vDLVWaadF1v5S69AfIBXeLSMQBEqJrRu@pfWufApCH41x8Uc4/QD "Java (OpenJDK 9) – Try It Online") [Answer] # Javascript ES6, 56 chars ``` n=>eval(`for(q=2,r=0;q<=n;++q)n%q||(n/=q,r+=!!(n%q--))`) ``` Test: ``` f=n=>eval(`for(q=2,r=0;q<=n;++q)n%q||(n/=q,r+=!!(n%q--))`) console.log([24,126,1538493,123456].map(f)=="2,3,4,3") ``` ]
[Question] [ Inspired by digital roots, the prime factoral root of a number is the number that emerges when you take the prime factors of a number, add them together, and repeat the process on the resulting number, continuing until you end up with a prime number (which has itself as its only prime factor, and is thus its own prime factoral root). The prime factoral root of 4 is 4, as 2\*2=2+2, and this is the only non-prime prime factoral root of an integer greater than 1 (which is another special case, as it has no prime factors). The OEIS sequence formed by prime factoral roots is [A029908](http://oeis.org/A029908). For example, the prime factoral root of 24 is: ``` 24=2*2*2*3 2+2+2+3=9=3*3 3+3=6=2*3 2+3=5, and the only prime factor of 5 is 5. Therefore, the prime factoral root of 24 is 5. ``` ## Your Task: Write a program or function that finds the prime factoral root of an input integer. ## Input: An integer, input through any reasonable method, between 2 and the largest integer your language will support (inclusive). Specifically choosing a language that has an unreasonably low maximum integer size is not allowed (and also violates [this standard loophole](https://codegolf.meta.stackexchange.com/a/8245/69331)) ## Output: An integer, the prime factoral root of the input. ## Test Cases: ``` 4 -> 4 24 -> 5 11 -> 11 250 -> 17 ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` import Data.Numbers.Primes until=<<((==)=<<)$sum.primeFactors ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRz680Nym1qFgvoCgzN7WYK822NK8kM8fWxkZDw9ZWE0hrqhSX5uoVgKTdEpNL8ouK/@cmZuYp2CoAxfJKFFQUchMLFNIUoo1MdBQMDXUUjEwNYv8DAA "Haskell – Try It Online") ### Explanation `until=<<((==)=<<)` takes a function `f` and applies it to input `x` until a fix point is reached, that is `f x` equals `x`. `primeFactors` returns the list of prime factors of a number, `sum` yields the sum of a list of numbers. *But wait, why does* `until=<<((==)=<<)` *the job and looks so weird?* If we assume `f=sum.primeFactors`, a more natural definition would be `until(\x->f x==x)f`, because `until` takes a predicate (a function which returns a boolean), a function which has the same input and return type (e.g. `Int -> Int`) and value of this type, and then applies the function to the value until the predicate is fulfilled. `until(\x->f x==x)f` is the same as `until(\x->(==)(f x)x)f`, and as it holds that `g (h x) x` is the same as `(g=<<h)x`, we get `until(\x->((==)=<<f)x)f`. After [Eta conversion](https://en.wikipedia.org/wiki/Lambda_calculus#.CE.B7-conversion), this becomes `until((==)=<<f)f`. But if we now treat `(==)=<<` as a function which is applied to `f`, we can see that `until(((==)=<<)f)f` is again of the form `g (h x) x`, with `g=until`, `h=((==)=<<)` and `x=f`, so it can be rewritten to `(until=<<((==)=<<))f`. Using the `$` operator to get rid of the outer parentheses and substituting `f` with `sum.primeFactors` yields the solution from above. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` FÒO ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7fAk////jUwNAA "05AB1E – Try It Online") **Explanations:** ``` FÒO F Loops <input> times + 1 Ò List of prime factors w/ duplicates O Total sum of the list -- implicit output ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ω(Σp ``` [Try it online!](https://tio.run/##yygtzv7//3ynxrnFBf///zcyAQA "Husk – Try It Online") Explanation: ``` ω( -- apply the following function until the result no longer changes (fixpoint) Σ -- sum p -- the list of primefactors ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 3 bytes ``` usP ``` [Try it here.](http://pyth.herokuapp.com/?code=usP&input=250&debug=0) Explanation: ``` usPGQ The trailing GQ is implicit PG Get prime factors s Sum u Q Repeat until returned value no longer unique starting with the input ``` [Answer] # [Python 2](https://docs.python.org/2/), 84 bytes ``` f=lambda n,d=2:n>1and(n%d and f(n,d+1)or d+f(n/d)) i=input() exec'i=f(i);'*i print i ``` [Try it online!](https://tio.run/##FY1RCsIwEET/9xRLQJpYQRPan0o8hReo3YQu1G0JKerpY/o1zGN4s/3yvIor00rBK6VK9Mv4ftGIciHvBnnYUUjLibAmRl1xa82akNparmQMsGfZ9qwNhG@YGvZRs7k3Z4YtsWTkUsXwmXkJ@Ex7GADxWOJxWjpwHVgLrr/9AQ "Python 2 – Try It Online") [Answer] # Java 8, ~~175~~ ~~144~~ ~~142~~ ~~141~~ ~~139~~ 101 bytes ``` n->{for(int i=n;i-->0;)n=f(n,2);return n;};int f(int n,int d){return n>1?n%d<1?f(n/d,2)+d:f(n,d+1):0;} ``` -38 bytes porting *@ovs*' Python answer, so make sure to upvote him as well! [Try it online.](https://tio.run/##PVDLboMwELz3K1aRKtnCUEyTCy7kC5pLjmkOLjaVU7IgY1JVyN9ObdJW2of2MaPZvcibTPtB40V9Lk0nxxFepcH5AcCg07aVjYZDLNcGNCRGpCJ0fPBgB0CoYMG0ntvernNToTBpWueCYtUSZAUVVrvJIqDwIq60dyIWo6Lz37Tme3xUL3wfUE8q4BJVRgKVcFrmwi8Aw/TemQZGJ11It94ouAbJ5OiswY/TGSS96/1XU6L@iupP57lgz2zLdoxzVmxZscs9XXcBjt@j09esn1w2BCLXITHJpnxzmyTC41cIzTALH6C/5/vlBw) ``` n->{ // Method with integer as both parameter and return-type for(int i=n;i-->0;)// Loop the input `n` amount of times: n=f(n,2); // Change `n` that many times by calling the recursive method // with n,2 as parameters return n;} // Then return the potentially modified `n` as result int f(int n,int d){ // Separated method with 2 integer parameters & integer return // (`d` is 2 when we initially call this recursive-method) return n>1? // If input `n` is larger than 1: n%d<1? // If `n` is divisible by `d`: f(n/d // Divide `n` by `d` ,2) // Do a recursive call with n/d,2 as parameters +d // And add `d` to its result : // Else: f(n,d+1) // Do a recursive-call with the next `d` by using n,d+1 as // parameters : // Else: 0;} // Simply return 0 ``` **Original ~~175~~ ~~144~~ ~~142~~ ~~141~~ 139 bytes answer:** ``` n->{for(int i,t=n,x;;n=t){for(i=2;i<t;)t=t%i++<1?0:t;if(t>1|n<5)return n;for(t=0,i=1;i++<n;)for(;n%i<1;t+=x)for(n/=x=i;x>9;x/=10)t+=x%10;}} ``` -1 byte thanks to *@Nevay* -2 bytes thanks to *@ceilingcat* **Explanation:** [Try it online.](https://tio.run/##PVBBbsJADLzzCgsJKasskKXkUJylLygXjpTDNoTKFByUGJqK5u3pbkBItmWPR9aMD@7qxuW54MPuu8uPrq7h3RHfBgDEUlR7lxewCmMPQB6Fygo90vr0UYsTymEFDBY6Hi9v@7LqaaTFsm4Q2Yq6o3aGlAkqsTKiOM7MW7IQpH0kS/PHWaqqQi4VA2Ogi000WYOByagChDyizKDEtulnntrGEjbLV2ym1iQqbEYmwbbtcODlnS@fRy/vofJa0g5O3mG0lor4a7MFp@72nqoXXPwEs5vtzeiZftFznWrj27mepUmrejbA@reW4jQpLzI5@1Ny5Iji4eJDhjFP/J/U40lt9w8) ``` n->{ // Method with integer as both parameter and return-type for(int i, // Index-integer `i` t=n, // Temp integer `t`, starting at the input `n` x; // Temp integer `x` ; // Loop indefinitely: n=t){ // After every iteration, replace `n` with the value `t` for(i=2;i<t;) // Inner loop `i` in the range [2,t): t=t%i++<1? // If `t` is divisible by `i`: 0 // Set `t` to 0 : // Else: t; // Leave `t` the same if(t>1 // If `t` is not 0 or 1 (it means it's a prime), |n<5) // or if `n` is below 5 (for edge-cases n=1 and n=4) return n; // Return `n` as result for(t=0, // Reset `t` to 0 i=1; // Reset `i` to 1 i++<n;) // Inner loop `i` in the range (2,n]: for(;n%i<1; // Inner loop as long as `n` is divisible by `i`: t+=x) // After every iteration: Increase `t` by `x` for(n/=x=i; // Reset `x` to `i` // And divide `n` by `i` x>9; // Inner loop as long as `x` contains more than 1 digit: x/=10) // After every iteration, remove the trailing digit of `x` t+=x%10;}} // Increase `t` with the trailing digit of `x` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ÆfS$¡ ``` Explanations: ``` Æf list of prime factors S sum $¡ repeat n times ``` [Try it online!](https://tio.run/##y0rNyan8//9wW1qwyqGF////NzI1AAA "Jelly – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina), 30 bytes ``` {+`(\1|\b11+?\B)+$ $1;$#1$* ; ``` Input and output in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary). [Try it online!](https://tio.run/##K0otycxL/K@qkaCnzaWi9b9aO0EjxrAmJsnQUNs@xklTW4VLxdBaRdlQRYvLmuu/pnsCl95/Iy5jLhMuUy5DQy4jEy4jUwMA "Retina – Try It Online") (Performs decimal/unary conversion for convenience.) ### Explanation ``` {+`(\1|\b11+?\B)+$ $1;$#1$* ``` The `{` instructs Retina to run the entire program in a loop until a full pass fails to modify the string, i.e. until a fixed point is reached. Consequently, the program itself computes one step of summing the prime factors of the current value. This stage itself computes the prime factorisation of the input. The `+` is similar to `{` but loops only this stage until it stops changing the string. The regex tries to match the final run of `1`s by repeatedly matching the same substring (i.e. the factor). The way this is done is a bit convoluted due to the forward reference `\1`. On the first iteration, group `1` hasn't captured anything yet, so `\1` fails unconditionally. Instead, we have to match `\b11+?\B` which is the smallest possible substring that starts at the beginning of the run, contains at least two `1`s and doesn't cover the entire run. Subsequent iterations will not be able to use this alternative again, due to the `\b`. So on all further iterations, we're matching `\1`, i.e. the same substring over and over again. This process has to hit the end of the string exactly (`$`) to make sure we've captured and actual divisor. The benefit of using this somewhat tricky approach is that group `1` will have been used exactly **n/d** times, i.e. what remains after dividing out the divisor **d**. We replace this match with **d** (`$1`), a separating `;` and **n/d** (`$#1$*`, which inserts `$#1` copies of `1`, where `$#1` is the number of captures made by group `1`). This process stops once the final run in the string is itself a prime, because then the regex no longer matches. ``` ; ``` All we need to do to sum the primes is to remove all the separators. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 4 bytes ``` ·ΘoΣ ``` [Try it online!](https://tio.run/##y8/INfr//9D2czPyzy3@/9/I1OA/AA "Ohm v2 – Try It Online") **Explanation:** ``` ·Θ evaluate the block until the result returned has already been seen Σ sum o the full prime factorization ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 7 bytes ``` ⌠w♂πΣ⌡Y ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9Rz4LyRzObzjecW/yoZ2Hk//9GJgA "Actually – Try It Online") Explanation: ``` ⌠w♂πΣ⌡Y ⌠ ⌡Y do this until output stops changing (fixed-point combinator) w factor into [prime, exponent] pairs ♂π product of each pair Σ sum of products ``` [Answer] # [R](https://www.r-project.org/) + [pracma](https://cran.r-project.org/web/packages/pracma/pracma.pdf), 53 bytes ``` function(n){for(i in 1:n)n=sum(pracma::factors(n)) n} ``` [Try it online! (r-fiddle)](http://www.r-fiddle.org/#/fiddle?id=EgzwI0sK&version=1) R doesn't have a prime factors builtin, but numerous packages (`pracma`, `numbers`, etc.) do, so I picked a conveniently short one. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes This answer uses one of Jelly's many prime factorization builtins, and the quick for `repeat until the results are no longer unique`. ``` ÆfSµÐL ``` **[Try it online!](https://tio.run/##y0rNyan8//9wW1rwoa2HJ/j8///fyAQA "Jelly – Try It Online")** [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes *Uses [scottinet's idea](https://codegolf.stackexchange.com/a/144401/36398) of looping more times than needed. Thanks also to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for a pointing out a mistake, now corrected.* ``` t:"Yfs ``` [**Try it online!**](https://tio.run/##y00syfn/v8RKKTKt@P9/I1MDAA) ### Explanation ``` t % Take input (implicit). Duplicate :" % Do the following that many times Yf % Array of prime factors s % Sum of array % End (implicit). Display (implicit) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 124 bytes ``` function f($a){for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}} for($x=$args[0];$l-ne$x){$l=$x;$x=(f($x))-join'+'|iex}$x ``` [Try it online!](https://tio.run/##HYzBCgIhFEX3fUXBi/Eh0jTQSvySaCGh0wvR0IkemN9u0vLec@59pY/L5eFC6N2/432jFPdegMXqUxZAZtFg1bqdsZIXh0GOQIgVaPQnA9RcKG5EKVtru/@IDdi8lut80xBUdMDDDwZYDyTGOyOqZ6I4yelLjhtw7325zD8 "PowerShell – Try It Online") PowerShell doesn't have any prime factorization built-ins, so this uses code from my answer on [Prime Factors Buddies](https://codegolf.stackexchange.com/a/94323/42963) (the top line) to perform the factorization calculations. The second line is the meat of this program. We take input from `$args` into `$x`, then `for` loop until `$l` is `-n`ot`e`qual to `$x`. (The first iteration, `$l` is `$null` and `$x` is an integer, so we'll loop at least once). Inside the loop, we set our `$l = $x` to determine if we've hit the end of the loop or not. Then we get the factors of `$x` with `f($x)`, `-join` those together with `+` and `|iex` them (short for `Invoke-Expression` and similar to `eval`). That's stored back into `$x`. Thus, we've hit the "end" where the prime factorization summed together is back to itself. Then, we simply place `$x` on the pipeline and output is implicit. [Answer] # Mathematica, 35 bytes ``` #//.x_:>Tr[1##&@@@FactorInteger@x]& ``` [Try it online!](https://tio.run/##Dcy7CsIwFADQ3a8IDXTxah/oUmm5iAqCgkO3EErsQ4NtAkmGQOm3x@6HMwn3la0NtWG@eUjreFGeR93@2NyVFzn1ykqtLPoFau3EyGrxHnt29c6I1jEPcpt2HGYJT6mwWzjnp81QBpoke98U1fpmlMaIeFu9Nnfl@k9v0PM4vIxUjlEgEdlVJAIyIOUxSZDM@QFIlgHJj@kS/g "Mathics – Try It Online") (Mathics does not support `Tr`. I have to implement it manually) [Answer] # [Ruby](https://www.ruby-lang.org/), 63 bytes ``` ->n{n.times{n=n.prime_division.map{|x|x.reduce:*}.sum};n} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tbg6zzZPr6AIyIxPySzLLM7Mz9PLTSyorqmoqdArSk0pTU610qrVKy7NrbXOq/1fUFpSrKBkYqWgXJ0WbRJbq8QFETGCChkhiRkaQsQMDZHUmRpAFZoaAEX//8svKAFaWfxftwjsCAA "Ruby – Try It Online") Uses the `-rprime` flag for +6 bytes to make use of [Prime#prime\_division](https://ruby-doc.org/stdlib-2.3.0/libdoc/prime/rdoc/Prime.html#method-i-prime_division). `prime_division` returns pairs of `[prime, exponent]` (for example, for 24 we have the factors `[2, 2, 2, 3]` so it gives `[[2, 3], [3, 1]]`) so in each step we just multiply the members of those pairs together and sum the results. [Answer] # Javascript (ES6), 63 bytes ``` f=n=>(q=(p=(m,x)=>m<x?0:m%x?p(m,x+1):x+p(m/x,x))(n,2))^n?f(q):q ``` ``` <input id=i type=number min=0 value=0 oninput="o.innerText=f(i.value)"> <p id=o></p> ``` ## Ungolfed: ``` f=n=>( // Recursive function `f` p=(m,x=2)=>( // Recursive function `p`, used to sum prime factors m<x? // If m (the number to be factored) is less than x (the current 0 // iteration), return 0 :m%x? // Else if m doesn't divide x p(m,x+1) // run the next iteration : // Else (if m divides x) x+p(m/x,x) // Divide m by x and repeat the current iteration ), q=p(n), // Set q to the sum of the prime factors of n q^n? // If q != n then f(q) // repeat f with q : // else q // return q ) ``` [Answer] # [Factor](https://factorcode.org/), 33 bytes ``` [ [ factors Σ ] to-fixed-point ] ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoVeal5mcn5IK4RQUZeamFuulgZUVKyTn5yZl5iWC2QVFqSUllUAFeSUKxamFpal5yanFCtZc1QomCkYmCoaGCkamBgq1/6MVohVg@s8tVohVKMnXTcusSE3RLcgH6Y39n5tYoFBckpicrfcfAA "Factor – Try It Online") * `to-fixed-point` Apply a quotation to an object until it stops changing. * `factors Σ` Sum of prime factors. ]
[Question] [ The [divisors](https://en.wikipedia.org/wiki/Divisor#Definition) of a natural number form a [poset](https://en.wikipedia.org/wiki/Partially_ordered_set) under the [relation](https://en.wikipedia.org/wiki/Relation_(mathematics)) of "a divides b?", \$a | b\$. This challenge is to produce the number, \$C\$, of non-empty [chains](https://en.wikipedia.org/wiki/Total_order#Chains) of such posets for natural numbers, \$N\$. This is [A253249](https://oeis.org/A253249) in the Online Encyclopedia of Integer Sequences. That may sound complicated, but it's not really, let's look at an... #### Example For \$N=28\$ the divisors are \$\{1, 2, 4, 7, 14, 28\}\$ and the number of non-empty chains is \$C(28) = 31\$. The non-empty chains are these subsets of those divisors: $$\{1\}, \{2\}, \{4\}, \{7\}, \{14\}, \{28\}$$ $$\{1, 2\}, \{1, 4\}, \{1, 7\}, \{1, 14\}, \{1, 28\}, \{2, 4\},$$ $$\{2, 14\}, \{2, 28\}, \{4, 28\}, \{7, 14\}, \{7, 28\}, \{14, 28\}$$ $$\{1, 2, 4\}, \{1, 2, 14\}, \{1, 2, 28\}, \{1, 4, 28\}, \{1, 7, 14\},$$ $$\{1, 7, 28\}, \{1, 14, 28\}, \{2, 4, 28\}, \{2, 14, 28\}, \{7, 14, 28\},$$ $$\{1, 2, 4, 28\}, \{1, 2, 14, 28\}, \{1, 7, 14, 28\}$$ These chains are those non-empty subsets of \$\{1, 2, 4, 7, 14, 28\}\$ such that all pairs of elements \$\{a, b\}\$ satisfy either \$a|b\$ or \$b|a\$ - that is one is a divisor of the other. Since \$2\$ does not divide \$7\$ **and** \$7\$ does not divide \$2\$, no chain has a subset of \$\{2, 7\}\$. Similarly no chain has a subset of either \$\{4, 7\}\$ or \$\{4, 14\}\$. Furthermore the empty chain, \$\emptyset = \{\}\$, is not counted. #### I/O You may take input and give output using [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") [defaults](https://codegolf.stackexchange.com/tags/sequence/info). \$N\$ is guaranteed to be a positive integer, \$N \ge 1\$. #### Tests The first \$360\$ values are: ``` 1, 3, 3, 7, 3, 11, 3, 15, 7, 11, 3, 31, 3, 11, 11, 31, 3, 31, 3, 31, 11, 11, 3, 79, 7, 11, 15, 31, 3, 51, 3, 63, 11, 11, 11, 103, 3, 11, 11, 79, 3, 51, 3, 31, 31, 11, 3, 191, 7, 31, 11, 31, 3, 79, 11, 79, 11, 11, 3, 175, 3, 11, 31, 127, 11, 51, 3, 31, 11, 51, 3, 303, 3, 11, 31, 31, 11, 51, 3, 191, 31, 11, 3, 175, 11, 11, 11, 79, 3, 175, 11, 31, 11, 11, 11, 447, 3, 31, 31, 103, 3, 51, 3, 79, 51, 11, 3, 303, 3, 51, 11, 191, 3, 51, 11, 31, 31, 11, 11, 527, 7, 11, 11, 31, 15, 175, 3, 255, 11, 51, 3, 175, 11, 11, 79, 79, 3, 51, 3, 175, 11, 11, 11, 831, 11, 11, 31, 31, 3, 175, 3, 79, 31, 51, 11, 175, 3, 11, 11, 447, 11, 191, 3, 31, 51, 11, 3, 527, 7, 51, 31, 31, 3, 51, 31, 191, 11, 11, 3, 703, 3, 51, 11, 79, 11, 51, 11, 31, 79, 51, 3, 1023, 3, 11, 51, 103, 3, 175, 3, 303, 11, 11, 11, 175, 11, 11, 31, 191, 11, 299, 3, 31, 11, 11, 11, 1007, 11, 11, 11, 175, 11, 51, 3, 447, 103, 11, 3, 175, 3, 51, 51, 79, 3, 175, 11, 31, 11, 51, 3, 1471, 3, 31, 63, 31, 31, 51, 11, 79, 11, 79, 3, 703, 11, 11, 51, 511, 3, 51, 11, 175, 31, 11, 3, 527, 11, 51, 11, 31, 3, 527, 3, 191, 51, 11, 31, 175, 3, 11, 31, 527, 3, 51, 3, 31, 51, 51, 11, 2175, 7, 51, 11, 31, 3, 175, 11, 79, 79, 11, 11, 703, 11, 11, 11, 191, 11, 175, 3, 175, 11, 51, 3, 527, 3, 11, 175, 31, 3, 51, 11, 1023, 11, 51, 11, 831, 31, 11, 11, 79, 11, 299, 3, 31, 31, 11, 11, 1471, 3, 31, 11, 175, 11, 175, 15, 79, 51, 11, 3, 175, 3, 175, 79, 447, 3, 51, 11, 31, 51, 11, 3, 2415 ``` #### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so try to make code in as few bytes as possible in your language of choice. Your score is the number of bytes of your program or function. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ ~~9~~ 7 bytes ``` ÆḌƬFLḤ’ ``` [Try it online!](https://tio.run/##dVQ7TgMxEL0KoqbwZ2cdX4CKa6RBuQAdooCGC1DRUOYA20fiHpuLGDz22G9sRcomsT2f99487/PxdHpJ6fK@b5@/58enffu5vn6ly8f17bxv3/cp@dUk@3Dn@RP425a1Jd6oK2/bGe@oXW/h5D8rtsxcpAZR@VmhCj/Gq8o5uUd726vnoGgLSg0j50gu4LCBOqG87Soq0rBlCUiwL0FvP1RHJhV520dV8rMsQXOq/aiToF7ewylXiFat/dCBMrmgJ5TVFxEckaaD8HliSviJ3UENuWsv9TndAl4Qv7FHIhjsO37S5WXJWeixQR4ZPcojimYUxvXhEtquwmS5lS9RAIXAxTi5vjjZhBs1KoqigfGTQ6nG3LKQsFhC124FK40q1DoBSZUe2kSl/zCEUUbZlzuAZ@MVk0DSM5YUx/Fhqt8IixGbMaexxNFfg8YNKtJDyuwE5HgYr5IAwEGrYeMYtFf4D02XWYHNZ/IuQB0g3i2W/gA "Jelly – Try It Online") ``` Ƭ Loop while unique: ÆḌ Recursively vectorizing proper divisors (empty list if 1). ƬF Deep flatten the full history of results, L take the length, Ḥ double (to account for the chains including the original n), ’ and decrement (to not double count the trivial chain of just {n}). ``` [Answer] # [Python 3](https://docs.python.org/3.8/), 45 bytes ``` f=lambda n,d=1:d//n or-~f(d)*(n%d<1)+f(n,d+1) ``` [Try it online!](https://tio.run/##dVTLTsMwEDzDV/iClNCiZuNs3VT0Y4pCoBK4VdQLF349xI@1dx0hNW3tfXhmdpzbz/3zavXhNs3zePo6f78NZ2W3wwmOw25n1XV6@R2roX6u7NPwCvVmrJboBup5vE7KqotV09l@vFewbaE@Pj7cpou9LzlqSazrGbZK@4/x3xDWgH4jrjSkmN8RuxpYZKnqU6VrEpMw/OxZF/80WnR2xTlbQ@7uknoIKCUMV0O1DAcYzITcdhtRoYRNS4aEn4vsbF1050wi8rTPVXFP1xnJKZ6HmQTm9ppFfYcexFoXJ6AjZ@SEnPokQoso6XD4fmJC@BW7gxhy1p76@3JgeJn4iT0nwpN1xo@yPS19FfdYIQ@NnstDijoUTZuHi9x2EaaXW/iSCyAQtH2/cn1wcmP@6RFRBA0avXIoxpz/LEQsOpO12zMrlSrEPoaTCmdIE4XziyGUMtI@3QEeK68YJaKcMZW0Pt@s@ifCZMRkzNVY@tJfhcYJKqfHKXsncI6H8ioRAD5oMWw@BukV/wdXl1mAdTF6F3AdWH7bAf4B "Python 3.8 (pre-release) – Try It Online") **51 bytes** ``` f=lambda n:1+sum(1+f(d)for d in range(1,n)if n%d<1) ``` [Try it online!](https://tio.run/##dVTLbsIwEDy3X5FLpURwyMZZTFD7MVRpWqRiUKCHfn1aO9541hESAex9eGZ2nOvv/evizP46TtPw9n08v/fHwh1oc/s5l7QZyr4aLmPRFydXjEf3@VHS1lWnoXAv/StVkw86DJodVYfnp@t4cvfSbYuhdFU10bYw4WPDN81r4rARV4aWWNhRu4Yg8l/VLZW@SUzi@WcHXcJTG9XZF6dsQ6m7T@poRqlh@BqpBRxkORHy201ExRq2LAEJnstwtsm6I5OIfNlHVfzTtlZziudxIsGpvYFo6NCRWpvsBPbkrJ6QV19EaJg1HYQfJqaEX7HbqyEn7aV/KCfAC@Iv7JEIJpuEn3V7WYYq9Fgmj4we5RFFPYq6ScNltF2EGeRWvkQBFIKm61aun51c2wc9IopZg9qsHMox55GFhEVrk3Y7sFKuQuxjkdR8hjbRfH42hFxG2Zc7gLH8ikki6xlLSRPy7ar/QliMuBhzNZYu91em8QIV6SHl4ATkuM@vkgDAQath4xi0V8IfXl1mBdbH5F2AOkB@0xL/AQ "Python 3.8 (pre-release) – Try It Online") [Answer] # [R](https://www.r-project.org), 44 bytes ``` `?`=\(n,d=1)`if`(d<n,(n?d+1)+(1+?d)*!n%%d,1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3dRLsE2xjNPJ0UmwNNRMy0xI0UmzydDTy7FO0DTW1NQy17VM0tRTzVFVTdAw1IXq2pGkYGmhyFScWFORUahhaGRnopEGlFiyA0AA) Port of [@xnor's Python answer](https://codegolf.stackexchange.com/a/265927/55372). [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 6 bytes ``` ĎSᵉti¦ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FquO9AU_3NpZknlo2ZLipORiqPCCm0aGXEZcxlwmXKZcZlzmXBZcllyGBlyGhlyGRlyGxlyGJlyGplyGZlyG5lyGFlyGllxGBhCtAA) ``` ĎSᵉti¦ Ď Divisors S Find a subset such that ᵉt removing the first element ¦ is divisible by i removing the last element ``` `-n` counts the number of solutions. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` ÑæʒRüÖP}g< ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8MTDy05NCjq85/C0gNp0m///DU0A "05AB1E – Try It Online") ``` Ñ # divisors of N æ # subsets ʒ # keep those such that R # when reversed üÖ # whether each term divides the previous one? P # all } g # and take the length < # -1 ``` [Answer] # [Rust](https://www.rust-lang.org), ~~63~~ 54 bytes ## (#2) Thanks to @att for the massive –9 bytes! ``` fn f(n:i64)->i64{(1..n).fold(1,|a,d|a-(1>>n%d)*!f(d))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZTPTsMgHMcP3voUbMmSH13LxvwTU7e-yLIY5kpC0tKl0HmAvoN3LzvoA_g4-jRCW52HJeoyDhB-4fvhE1p4fqlqpfcfF29cooIJCRiZSYjyTCOOFiiwMqlvrqypVYaEzipdlrlKkvAOKCELiQkXuSuD3Vg52iwWU0y25WNWqUwDJkLq8t7H4LBQWUX60jarilozLUqpYIYJy3OwO7tbTlfpbklX1vp-5OeejMlDWUvHjWnzT7E5PZPXyBuF31qOez6rs5q47yn5FFofHKeuN97hmELBtn5Gxxw2DqLqAnAL4PRUQJLMXSAFPO5U-OwkEi_zDdDIsmht2XjdW13-jXUIeyDrkB3h6jjhR0Bw1GLMV7LJcpUZ1nwR6D8Ih_y0GbOecP2rA9CYksLdScfBOIT-VFpCOHmtNY9v3288y5FESxLHSSwGmqYeEw66Y-jTT0HAywoJJCTyf-jsFpkA9W1buXuSywEMOZgGu-fANMMIichtKDC-axc2QTv8QnEM00RoeCz6vY0r9177fTd-Ag) # [Rust](https://www.rust-lang.org), 63 bytes ## (#0) Originally based on [@xnor's Python answer](https://codegolf.stackexchange.com/a/265927/109946). Straightforward functional implementation of their idea. ``` fn f(n:u64)->u64{(1..n).filter(|d|n%d<1).fold(1,|a,d|1+a+f(d))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZTPbsIgHMcPu_UpmIkJ9A-Kc4upf_Ygxiw4S0LSUlOoO0DfYfddPGwPsMfZnmbQVt3BxOnkAOEXvh8-oYW396KUavt988kEyCgXEAHd80GaKMDAFHhGxOXD0OhSJoCrpFB5nso49seQYDwVCDOe2jI0KyO6q-m0j_A6f0kKmSiIMBcqf3IxeFgojcRtaZ0UWamo4rmQcIAwTVNoNmYz7y9mmzlZGOP6rps7MsLPeSksNyLVmWITciWvrjPy91qWez2rq5rY7ylYH9Y-KJrZXjuHYwoZXbsZCRhcWYgsM4hqACOXAuJ4YgMziIJGhQ0uIrE8XUESGhouDQ2WrdXd31iHsAPSBtkQhscJvwKcgRqjd8kqSWWiabUjkDMIh3y_CmhLuD_pAElEcGbvpOUg5MP2VGqC3_soFYtGX4-O9Y_zaDGvnsfyAnDABXC_6mAEtAfati7shUnFLewwqCtk3wVddULAQ7szR2hcL6y8ejhBsQxdhaBzLLrfxpZbr-22GX8A) # [Rust](https://www.rust-lang.org), 63 bytes ## (#1) Works just like #0, but the filter is inlined into the fold. ``` fn f(n:u64)->u64{(1..n).fold(1,|a,d|if n%d<1{1+f(d)}else{0}+a)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=rZQ7bsIwHIeHbjmFi4Rk52EwpRUKjx4EocqUWLKUOCh26GDnDt27MLQH6HHa09ROAnRAolAy2PJf_n3-5Efe3otSqu33zScTIKNcQAR0zwdpogADU-AZEZcPQ6NLmQCukkLleSrj2B9DgvFUIMx4asvQrIzorqbTPsLr_CUpZKIgwlyo_MnF4GGiNBK3pXVSZKWiiudCwgHCNE2h2ZjNvL-YbeZkYYxru27syAg_56Ww3IhUZ4pNyJW8us7I32tZ7vWsrmpiz1OwPqx9UDSzrXYOxxQyunYjEjC4shBZZhDVAEYuBcTxxAZmEAWNChtcRGJ5uoIkNDRcGhosW6u7v7EOYQekDbIhDI8TfgU4AzVG75JVkspE02pHIGcQDvl-FdCWcH_SAZKI4My-SctByIftrtQEv_dRKhaNvh4d6x8uLebV81heAA64AO6qDkZAe6D91oV9MKm4hR0GdYXsf0FXnRDw0K7MERrXEyuv7k5QLENXIegci-6XseXWa7tt-h8) Previous attempts and ideas can be found in the ATO links. It took me a while to realize that the descriptive symbolic idea of using itertools, powerset and so on looks extremely cool but just isn't suited for code golf at all if less readable solutions exist. They all work the same way, with the exception that the first two functions evaluate recursively lazily and the last one eagerly (Infinite recursion is prevented by not calling the closure when the iterator is empty, providing this as a base case). The performance difference is noticeable. ~~I'm sure there must be a way to golf one of these even further (more likely the latter two than the former).~~ It's quite likely that the golfing potential has now been exhausted. [Answer] # [Uiua](https://www.uiua.org/), 18 bytes ``` ∧+1+1∵(|1↬2)⊚=0◿⇡. ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oinKzErMeKItSh8MSDihqwyKeKKmj0w4pe_4oehLgoKZiAyOAriiLVmICsxIOKHoSAyMA==) ``` ∧+1+1∵(|1↬2)⊚=0◿⇡. input: a positive integer n ⊚=0◿⇡. proper divisors of n: ◿⇡. n modulo (each of) range of n ⊚=0 indices of zeros ∵(|1↬2) recurse on each +1 add 1 to each result ∧+1 sum the results and add 1 ``` [Answer] # JavaScript (ES6), 35 bytes *-11 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!* Returns the \$n\$-th term. ``` f=(n,d=n)=>d--&&f(n,d)-!(n%d)*~f(d) ``` [Try it online!](https://tio.run/##FYxBCsIwEEX3PcUItcy0RlBwVcezNDSJKGFG2uImpFePcfXfg8d/269d5@X12Yyo86UERjk5FuKHM6brwl/JHFCOjvo9oKMSdMHoNxBguIx17gzXW4VhIEgNwKyyavTnqE@cLLZJMtW2TfWN8kRjk8sP "JavaScript (Node.js) – Try It Online") Or [try a faster version](https://tio.run/##FcvBCsIwDADQXwkDR4JtmAgelE78DhEpyyobWzI6Ebz461WP7/DG@Iprl4fl6dWkLyUFVCdBKbTifV2nP8mjbuTcHD8Jhah0pqtNPU/2wCszX3KOb9wfGrrxHBfEuwMlCC38OmxhR8SjDYqVg4roVL4) (36 bytes) that generates the 360 first values listed in the challenge. ### Commented ``` f = ( // f is a recursive function taking: n, // n = input d = n // d = current divisor candidate ) => // d-- && // if d is not 0 (decrement it afterwards): f(n, d) - // do a 1st recursive call with the updated d !(n % d) * // test whether d is a divisor of n // if not, ignore the result of ... ~f(d) // ... a 2nd recursive call with n = d // (otherwise, increment the final count) ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 37 bytes ``` f=(n,p=n)=>--p?f(n,p)+!(n%p)*-~f(p):1 ``` [Try it online!](https://tio.run/##FYxBCsIwEEX3PcUIFWaMESq4aR29SkObiBImoS1uQnr1GFf/PXj8j/madVrecdMSZluKY5RzZCF@aB2f7m@kDijHSCe9O4zUd8WFBb3dQIChG@rcGa63CkoRpAZgCrIGby8@vHA02CbJVNs21UPKIw1NLj8 "JavaScript (Node.js) – Try It Online") Found independent, I'd just leave it here [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes ``` .+ $* +%M!&`^|(1+$)(?<=^\1\1+)|$ ¶ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS1vVV1EtIa5Gw1BbRVPD3sY2LsYwxlBbs0aF69C2//8NuYy4jLlMuEy5zLjMuSy4LLkMDbgMDbkMjbgMjbkMTbgMTQE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` .+ $* ``` Convert to unary. ``` +%M!&`^|(1+$)(?<=^\1\1+)|$ ``` Calculate \$ A253249(i) = 1 + \sum\_{j|i} 1 + A253249(j) \$. The `+%` repeatedly processes inner terms until they become empty. The `!&` outputs overlapping matches. The `(1+$)(?<=^\1\1+)` matches factors of \$ i \$, and the leading and trailing empty match applies the two \$ 1 + \$ terms somehow... not quite sure how that works, but I'm not complaining. The result is actually the number of newlines generated by the repeated factorisation. ``` ¶ ``` Convert to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` FN⊞υ↨Eι∧¬∧κ﹪ικ⊕§υκ¹Iυ ``` [Try it online!](https://tio.run/##FcwxDsIwDEDRnVN4tKUwVEgsnQpTh1a9QkiMWjV1qiRG3D6Q6Q9P@m61yUUban3HBDjKqWXW48UJiWDRvKIaeNjMONkTNwODeJxjwdbdwBS9hthgJyIDo7jEB0thj0MZxfO3HRr@taP@sqRNCj5tLqhEfa23e1evn/AD "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first \$ n \$ values starting at \$ N=0 \$ whose value is considered to be \$ 0 \$. Explanation: \$ A253249(i) = \sum\_{j|i} 1+A253249(j) \$ where \$ 0 \$ is considered to divide any integer. ``` FN ``` Loop \$ n \$ times. ``` ⊞υ↨Eι∧¬∧κ﹪ικ⊕§υκ¹ ``` Calculate \$ A253249(i) \$ using the above recurrence relation. ``` Iυ ``` Output the results. 22 bytes for a 1-indexed version: ``` FN⊞υ⊕↨Eι∧¬﹪⊕ι⊕κ⊕§υκ¹Iυ ``` [Try it online!](https://tio.run/##XYyxDsIwEEN3viLjRSoSCImFqTBlaNVfCMmhRqSXKrlD/H1IN2CxZD/bbrbZJRtrfaSswNAqPMpyxwxaq0nKDNIpQy7jgsTo4WoLwmBXCJ3qycOYGIbkJSb4rgX9O3tq/Zf0bMjje/vfYKPHppfdlAMx3GxhkOZrPZ0Pdf@KHw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first \$ n \$ values. Explanation: \$ A253249(i+1) = 1 + \sum\_{j+1|i+1} 1+A253249(j+1) \$. ``` FN ``` Loop \$ n \$ times. ``` ⊞υ⊕↨Eι∧¬﹪⊕ι⊕κ⊕§υκ¹ ``` Calculate \$ A253249(i+1) \$ using the above recurrence relation. ``` Iυ ``` Output the results. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 31 bytes ``` f(n)=sumdiv(n,d,1+if(d<n,f(d))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboW-9M08jRti0tzUzLLNPJ0UnQMtTPTNFJs8nSApKamJkTVTZW0_CKNPAVbBUMdBWMDHYWCosy8EqCAkoKuHZAAGQJTCzMZAA) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~79~~ 38 bytes ``` f=->n{1+(1...n).sum{|r|1[n%r]*-~f[r]}} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6v2lBbw1BPTy9PU6@4NLe6pqjGMDpPtShWS7cuLbootrb2P0ja0MBAUy83saC6prCmQCEtujC29j8A "Ruby – Try It Online") [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), ~~43~~ 28 bytes Saved 15 bytes thanks to the comment of @alephalpha --- Golfed version. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2Yb899QO6Qo2lBb2UDfwTe/uMTBJbMsszi/qNhBOVbtf0hiUk5qdEBRZl5JdKaOgpKCrp2Cko5CWnRmbKyOQjVQyFBHwdigNvY/AA) ``` 1+Tr[1+#0/@Most@Divisors@#]& ``` Ungolfed version. [Try it online!](https://tio.run/##NcvBCoJAFIXhfU9xUIiiCZV2ldGiTTsXQovLJaZSvKAj6NBGfPbpBrU7/Ievs76pOuvlaUOoyd0Z@xw6GDlu4huaXvKWsR9GDZff1Hs2KHtvW1pl2OBaU4wjnFEas0HKayyRnPHHzIdFaR9tRcUgzpMYRNieEH2FsJJJU2awS2cO4QM) ``` f[n_] := f[n] = With[{divisors = Divisors[n]}, Total[(1 + If[# < n, f[#], 0]) & /@ divisors]]; Table[Print[i, " -> ", f[i]], {i, 1, 30}] ``` [Answer] # [Haskell](https://www.haskell.org), 38 bytes ``` f n=1+sum[1+f d|d<-[1..n-1],mod n d<1] ``` A simple port of @xnor's [python answer](https://codegolf.stackexchange.com/a/265927) [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9XSFPJsDbWLS3OjDbXTFFJqUmx0ow319PJ0DWN1cvNTFPIUUmwMYyGq1-cmZubZFhRl5pWopCkYWUBEYWYBAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) v1.4.5 [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` â à ®ä!v × ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.5&flags=LXg&code=4iDgIK7kIXYg1w&input=Mjg) Thanks to @Shaggy for saving 5 bytes by using an older version of Japt ( improvements specified inside parens ) ``` â divisors( now sorted ) à combinations( now without empty combination ) ® map by ä map each consecutive pair of a combination !v divisible? ( now with argument swapped by prepending ! to function argument) × multiply reduce -x flag to output the sum ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~119~~ 118 bytes ``` L=[1...n] D=L[mod(n,L)=0] d=D.count F=D[mod(floor(2k/2^{[1...d]}),2)=1] f(n)=∑_{k=1}^{2^d-1}0^{mod(F[2...],F).total} ``` [Try It On Desmos!](https://www.desmos.com/calculator/rwbvnz3yko) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/snsg5dz5ji) Port of [Command Master's answer](https://codegolf.stackexchange.com/a/265921/96039), so make sure to go upvote that answer as well! [Answer] # APL (Dyalog Unicode), ~~51~~ ~~45~~ 44 bytes ``` +/((∘.≤⍨⍳∘⍴)≡0=∘.|⍨)¨¯1↓{,⊃∘.,/⍵,¨⊂⊂⍬}(∪⊢∨⍳) ``` The index origin is set to 1 (⎕IO←1). The number to be analyzed is entered to the right of the code. [Try it on TryAPL.org!](https://tryapl.org/?clear&q=%2B%2F((%E2%88%98.%E2%89%A4%E2%8D%A8%E2%8D%B3%E2%88%98%E2%8D%B4)%E2%89%A10%3D%E2%88%98.%7C%E2%8D%A8)%C2%A8%C2%AF1%E2%86%93%7B%2C%E2%8A%83%E2%88%98.%2C%2F%E2%8D%B5%2C%C2%A8%E2%8A%82%E2%8A%82%E2%8D%AC%7D(%E2%88%AA%E2%8A%A2%E2%88%A8%E2%8D%B3)28&run) With credit to [ngn's prior challenge answer](https://codegolf.stackexchange.com/a/154678/119285) for the short powerset code segment. ]
[Question] [ # Introduction This challenge was inspired by a seemingly simple task requested at work that couldn't easily be done in Microsoft Teams. At least not from what we could find! ## Task Your task, if you choose to accept it, is to output the last week day of **any month** in **any year**. ## Input You can input the desired month/year in whatever format you like, but it must take in an input. Having these hard-coded into the calculations **doesn't count!** Input examples include but are not limited to: * `08/2023` * `October 1678` * `1/2067` ## Output Your output must be the last week day of the month in the below format: ***Tuesday 31st*** ## Test cases | Input | Output | | --- | --- | | `10/2023` | `Tuesday 31st` | | `February 2017` | `Tuesday 28th` | | `09/1674` | `Friday 28th` | | `1/2043` | `Friday 30th` | ## Assumptions / Stipulations * You can assume the inputs are always in a workable format and not null * Calendar is the [Gregorian Calendar](https://en.wikipedia.org/wiki/Gregorian_calendar#:%7E:text=The%20Gregorian%20calendar%20is%20the,replacement%20for%2C%20the%20Julian%20calendar.) * Monday, Tuesday, Wednesday, Thursday and Friday are all week days. Saturday and Sunday are NOT valid week days for this task * You can ignore public holidays PS. I got the test cases from [timeanddate.com](https://www.timeanddate.com/calendar/?year=2043) ## Current Winner (28th November 2023) > > PHP - [Kaddath](https://codegolf.stackexchange.com/users/90841/kaddath) - 55 Bytes > <https://codegolf.stackexchange.com/a/266340/91342> > > > [Answer] # Bash and GNU Date, ~~84~~ 83 bytes Thanks to [gildux](/users/104387) for shaving 1 byte. ``` s=(1 2) m=1$1+month date -d$m-$((s[`date -d$m +%w`]+1))day +%A\ %eth|sed s/1th/1st/ ``` Input format is the month name and year as a single word, e.g. `October2023` or `sep2026`. An English locale (such as the standard `C` locale) is required for the day names to be in English. You might need to unset `TZ` environment variable to get proleptic Gregorian dates. --- ### How it works 1. **`m=1$1+month`**: Create a `date` input that is one month later than the start of the target month (ie. the first day of the following month). GNU Date allows us to omit all the spaces, which is helpful. 2. **`date -d$m +%w`**: Obtain the day of week of the first day of the following month. 3. **`$((s[…]+1))`**: We'll need to back up one day, plus an additional day if following month starts on Sunday (weekday 0) or an additional two days if it starts on Monday (weekday 1). The array `s` is incomplete; the arithmetic works because empty string concatenates with `+1` to give the result we want. 4. **`date -d$m-$((…))day +%A\ %eth`**: Format that last working day, appending `th` to give a candidate ordinal. 5. **`|sed s/1th/1st/`**: Rewrite `31th` as `31st`. The last working day must be in the range 26th...31st, so there are no `nd`s or `rd`s to consider. --- ### Full demo ``` #!/bin/bash last-working-day() { s=(1 2) m=1$1+month date -d$m-$((s[`date -d$m +%w`]+1))day +%A\ %eth|sed s/1th/1st/ } test "$*" || set -- $(for i in {0..35}; do date -d 1jan00+${i}month +%b%Y; done) for i do printf '%s: %s\n' $i "$(last-working-day $i)" done ``` Output (no args): ``` Jan2000: Monday 31st Feb2000: Tuesday 29th Mar2000: Friday 31st Apr2000: Friday 28th May2000: Wednesday 31st Jun2000: Friday 30th Jul2000: Monday 31st Aug2000: Thursday 31st Sep2000: Friday 29th Oct2000: Tuesday 31st Nov2000: Thursday 30th Dec2000: Friday 29th Jan2001: Wednesday 31st Feb2001: Wednesday 28th Mar2001: Friday 30th Apr2001: Monday 30th May2001: Thursday 31st Jun2001: Friday 29th Jul2001: Tuesday 31st Aug2001: Friday 31st Sep2001: Friday 28th Oct2001: Wednesday 31st Nov2001: Friday 30th Dec2001: Monday 31st Jan2002: Thursday 31st Feb2002: Thursday 28th Mar2002: Friday 29th Apr2002: Tuesday 30th May2002: Friday 31st Jun2002: Friday 28th Jul2002: Wednesday 31st Aug2002: Friday 30th Sep2002: Monday 30th Oct2002: Thursday 31st Nov2002: Friday 29th Dec2002: Tuesday 31st ``` [Answer] # [PHP](https://php.net/), -F 55 bytes ``` <?=date('l jS',strtotime("$argn+1month last weekday")); ``` [Try it online!](https://tio.run/##DczRCsIgGIbh813FjwTbKJnaaMSqnXUDnXZizJrlVPQfo5vPPPweeD8/@ZROw3mUqKrSwPtW7iIGdKhnVZGNDC@75bOzOIGREWFV6jPKL6nrPg2XXJK7JT00jVUrGG0VPF0ACUHJUT6MAregX3Kn88O8GNQ@o7bZYhJM7ClnhWC8o0wU/NC1lB3zbrP/nEftbEz0@gc "PHP – Try It Online") Input is in "yyyy-mm" format in my example, but `strtotime` supports many formats It's so rare that PHP is competitive! I knew one day would be the glory of this pile of unconsistent mess, that I came to like golfing with ;) I needed to add one month because using `strtotime` without a day number returns the first day, and `last` is actually a relative term (opposite of `next`). Probably still golfable, still searching for edge cases where it could not work (relative month `+1 month` can be broken I think, `-1 month` is for sure) NOTE: my first version was 4 bytes shorter `++$argn." last weekday"`, I liked it because it uses PHP's string increment, but even if it works with the tests cases, it will fail for December -> "2023-12" would give "2023-13" and `strtotime` is not really clever [Answer] # [Factor](https://factorcode.org) + `math.text.english`, 110 bytes ``` [ last-day-of-month dup weekend? [ friday< ] when dup day-name swap day>> dup ordinal-suffix [I ${} ${}${}I] ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU87TsNAEO1zilfQ2opNRPhEhg65oUFUlovBO4utrHfN7loOQpyExg05AZfJbdjEkoM0o5n33ny_95Iqb-x42L8850-Pt6hIsRZk5yRm_aYaV6MlX8eed35mqKrYOWMdtmw1KzTas-2MIs-oTPvaaArDXRyaLDncLRbpMr1EskSCjQhVWSCSNdIzTq7WK9z811ehYcY_vZfR9UEXUOR8JOgjMjJqjfY1RN9hYN6Gs-9RQNomyBuUGGrWJ_VYrqlluIFOKMtOvLEinKoi10vZ7FDkuPj8OnqwvEQ5bf0toFUYFz7rjGO89yQeJmkcp_gH) Takes a timestamp (date object) as input. * `last-day-of-month` get the last day of the month * `dup weekend?` is it a weekend? * `[ friday< ] when` then change it to the Friday before * `dup day-name` get the day name ("Monday", "Tuesday", etc.) * `swap day>>` get the day number of the month * `dup ordinal-suffix` get its ordinal suffix * `[I ${} ${}${}I]` interpolate it all together and print [Answer] # [Python](https://www.python.org), 129 bytes ``` from datetime import* def f(y,m,d=31,s="st"): try:q=date(y,m,d);1/(q.weekday()<5);print(f'{q:%A %d}{s}') except:f(y,m,d-1,"th") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY_BCoJAGITvPsUiiLuxlquWtWbQo0i7ixLqqn-UiIeeo4uXeqfepkQ7dPuYGYaZx0u3kJbFMDwvoJzt-67qMkciAQlZLlGW67KGhSGkQgq3NKci9hltYrMBk3ADQd3yKh7zk0sitsLV8irlWSQtJvs1iXSdFYCV3VXcOiJL9F3T28RA8naSGvjc6zBqQmqSechBYc_1fMpcYozIQuqNxDZhQHeTFnzticbgH04tv1sf) [Answer] # JavaScript (ES6), 129 bytes *-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* *-2 thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* Expects `([year, month])`, as integers. ``` f=(D,d=31,s="st")=>(q=new Date([...D,d])).getDate()>9&&q.getDay()%6?q.toLocaleString("EN",{weekday:"long"})+' '+d+s:f(D,d-1,"th") ``` [Try it online!](https://tio.run/##bc1BC4IwAAXge79iDLIN52gqisLqYrfo0jE6DJ1mjS3bKCL67cvqWMf3Ph7vKK7C1pf@7CJtGul9y1FFGp4wYjm0DmK@QAPX8gYq4STaUUpH32NMO@k@FV4UQTB84x3habYcqDNrUwslt@7S6w7B1QaSx03KUyPuJVRGd/CJwxmYhU1oy/Z9GTEC3QFiXxttjZJUmQ61aBfP44Sw@fg4@RGWExD/EZblKQHF302aEMBG8S8 "JavaScript (Node.js) – Try It Online") Or **[126 bytes](https://tio.run/##bc1BC4IwAAXge79iDNIN53AaicLs4rFbR@kwdJolW7qRSPTbzeqYx/c@Hu8qHsKUQ3u3vtKVnOeao5xUPGLEcGgsxDxDPVdyBLmwEhWU0sXPGNNG2m@Fs8Rx@l@cEN7uDz21@qhL0cmTHVrVoIA8RylvlZhS2GnVwBf2XOB6lWfS@vPnMwLtBeK51MroTtJON6hGRRiEEWHBcrf5ExYTEK4I28c7ApLVzS4igC0yvwE)** if we assume a default English locale. ### Commented ``` f = ( // recursive function taking: D, // D[] = [year, month] d = 31, // d = day, starting at 31 s = "st" // s = suffix, initialized to "st" ) => // ( q = new Date([ // build the date q for: ...D, // the year and month stored in D[] d // the day d ]) // ).getDate() > 9 // if the resulting day is greater than 9 && // (i.e. we didn't overflow to the next month) q.getDay() // and the 0-based day-of-week index % 6 ? // is neither 0 or 6 (Sunday / Saturday): q.toLocaleString( // return the name of the day "EN", { // obtained with toLocaleString() weekday: "long" // set up to English } // ) + // ' ' + // followed by a space d + // followed by the day s // followed by the suffix : // else: f(D, d - 1, "th") // recursive call with d - 1 and s = "th" ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~99 89~~ 102 bytes ``` ->y,m{(1..4).find{|d|(A=Date.new y,m,-d).wday<5} A.strftime"%A %d#{A.day>30?'st':'th'}"} require'time' ``` [Try it online!](https://tio.run/##XcrRCoIwFIDh@z3FUOQ42IZHDSLSEHoRa5MGKjUnIuqzL72s2///7PiYfVN4Uc68W2KUMmeyMb1aVrXGVXGvnZa9nui@uVBMTqqer6eNVHJwtnGm00FU0UiFSyX3VWbJDQYHF3Av2IKNWP0ZjdVwSPBva3pHG/ms2zamaYI5R2Q8IAENaVFSOJJAFOkZyD9OM44J@4GpyBCI/wI "Ruby – Try It Online") **Explanation** Anonymous function tacking year and month as numbers. We find which of the last 4 days of month ( checking backwards using -d ) are wdays (week days 0-indexed) less than 5 saving each time date object in constant A for later use. When it's found loop is stopped so A is the last weekday of the month. Then we format the output, we can only have 31st or XXth. [Answer] # POSIX shell, 168 bytes Not the shortest possible with the shell, but it doesn't use any bashism and is funny (see explanation bellow.) ``` cal $@|tail -2|awk 'NF>1{split("S Mon Tues Wednes Thurs Fri",d) a=6;if(NF==1){b=$1-2}else if(NF==7){b=$6}else{a=NF;b=$NF} print d[a]"day",(b==31)?b"st":b"th"}'|tail -1 ``` With the following limitations: * months are given as integer only, not strings (January or jan for example) * separator is changed from slash to blanks (i.e. `1 2043` instead of `1/2043`) which is natural shell arguments separator ### Explanation We can use the POSIX [`cal`](https://manpages.ubuntu.com/manpages/jammy/man1/cal.1posix.html) to visually catch the last weekday. ``` $ # for February 2017 $ cal 2 2017 February 2017 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ``` The last week is on the visually shown last line (but there's an extra blank line), so with POSIX [`tail`](https://manpages.ubuntu.com/manpages/jammy/man1/tail.1posix.html) (for golfing purpose, `tail -n -2` is shorten `tail -2`) ``` $ # last week of February 2017 $ cal 2 2017 | tail -n -2 26 27 28 ``` Finally we should pick the last day… Because the column position vary, [`awk`](https://manpages.ubuntu.com/manpages/jammy/man1/awk.1posix.html) is a better candidate than [`cut`](https://manpages.ubuntu.com/manpages/jammy/man1/cut.1posix.html) here (But one can prefer `perl` or some other scripting langage, but I'm trying to use commands that should be always available), hence the following script: ``` BEGIN { # on start, create array of days names split("Su Mo Tu We Th Fr Sa", d) } NF > 1 { # on filled line, print last column name and value print d[NF],$NF } ``` If the script is put in file `LastDay.awk`, our chaining become: ``` $ # last day of February 2017 $ cal 2 2017 | tail -n -2 | awk -f LastDay.awk Tu 28 ``` However, note that the first column is Sunday, and we need to deal with boundaries. The modification is: ``` BEGIN { # on start, create array of days names split("S Mo Tu We Th", d) } NF > 1 { # check last column if (NF==7) { print "Fr",$6 # Saturday: we read the previous field } else if (NF==1) { print "Fr",($1-2) # Sunday: we count two days less } else { print d[NF],$NF # Week-Day: pick column name and value } } ``` For golfing purpose, * I try to use ternary operator (which is an expression that expects three other expressions) without success * Initial array creation is not done in `BEGIN` but each time, and rule is evaluate in any case… * Replace `$1 $2` with `$@` (thanks Toby Speight for the comment) and remove extra spaces But, in order to comply with the output requirements, we have to add more characters for days. ``` NF > 1 { split("S Mon Tues Wednes Thurs Fri", d) if (NF==7) { # sat print d[6] "day",$6 } else if (NF==1) { # sun print d[6] "day",($1-2) } else { # non w-e print d[NF] "day",$NF } } ``` For compliance, we have to deal with ordinals too. To avoid repeating ourself many times, let's opt for assignments and put formatting at end. ``` NF > 1 { split("S Mon Tues Wednes Thurs Fri", d) if (NF==7) { # sat a=d[6] b=$6 } else if (NF==1) { # sun a=d[6] b=($1-2) } else { # non w-e a=d[NF] b=$NF } print a "day", (b==31)?b"st":b"th" } ``` ### Addendum Well, `cal 12 2001` shows that there wasn't simply a blank line as I believed, the formatting is for six weeks… Then, before invoking AWK, our selection should be changed so: ``` - cal $1 $2 | tail -n -2 + cal $1 $2 | grep -v '^ *$' | tail -n -1 ``` Alternatively, the AWK output (`Friday 28th` and `Monday 31st`) must be filtered though `tail -n -1`. Either add 14 characters before (and save `NF > 1` condition), or add 10 characters after (and keep 4 characters condition). Fifty-fifty, so it's a matter of taste. [Answer] # Python3, 153 bytes ``` from datetime import* T=timedelta(1) def f(m,y): d=date(y+(m>11),m%12+1,1)-T while d.weekday()>4:d-=T return d.strftime('%A %d')+['th','st'][d.day>30] ``` [Try it online!](https://tio.run/##XYzLCoMwFET3@YpsJElNizdKX6DQf@iudCHcBKVGJb2l@PU2QgvS5Zw5M@NEzdDnxzHMswuD51iTpdZb3vpxCLRh13KJaDuqJSiG1nEnvZ7UmXEsF11OqfQVgNI@AZOCBrW9Mv5u2s5y3L2tfWA9SVUVZ9yWsQmWXqGP1ZOCW96lSC48QaHSm6BGaPEkcb/hLs6qPLvPY2h7kk5Cpk1mcqXYj5gI4LACJw37Q7ECEI1iPQHzfwLwJfMH) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~137~~ 136 bytes ``` ≔I⪪S/θ≔⁻⁺×¹²⊟θ⊟θ²θ≔EE²⁻θι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷θ≔⊟θη≔⊟θθ≔⁻⁺²⁸﹪⁻θη⁷∨¬θ⊗¬⊖θθ§⪪”⟲1U↘ዬ@²¦À≧≡FGv_E✂₂↘” ⁺θηday Iθ§⪪stth²‹θ³¹ ``` [Try it online!](https://tio.run/##dVHJasMwEL33K4ROI3CJt9JAT6GmYGhSgw09lBxcW9gCW14khfbr3fESQ9z2oGXmPb2Z0cvKtM@atBqGg1KikPCcKg1xWwkNoWyNjnUvZAHMInRHGR4de7pbuEchjYKowi0RNVfguBaJmha6kbhe3M2rtJ0WcmeBziJi5B2b3FQNxKaGj1DqQFxEzkFYxN/bNuInXqSaww3kuAghtuFvM457k1m69bDJsXl/rT1TR8EHdsb9cTPxPJNFyt@pv//F3a/a67DlVfith1Ojp9dBYz4rnk9xwLOe11xqjPED2bWHCJ3QcNChzPnX4hElKC9JYrgi7zyXeCSl6RV56QVFzwhly5BTYbbK0Dz9RvAaTrZ37L8qSuuSzk6@cjWJec6oNgzOzrV9b7i/VD8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses my code for Zeller's congruence from my answer to [ASCII Calendar Planner](https://codegolf.stackexchange.com/q/173800/). ``` ≔I⪪S/θ ``` Split the date on `/`. ``` ≔⁻⁺×¹²⊟θ⊟θ²θ ``` Convert to months since March 1, 1 BC. ``` ≔EE²⁻θι﹪Σ⟦÷ι⁴⁸⁰⁰±÷ι¹²⁰⁰÷ι⁴⁸÷ι¹²÷×¹³⁺⁴﹪ι¹²¦⁵⟧⁷θ ``` Use a modified Zeller's congruence to extract the day of the week of the first day of next month and this month as a list. ``` ≔⊟θη≔⊟θθ ``` Extract the list entries into variables to save bytes. ``` ≔⁻⁺²⁸﹪⁻θη⁷∨¬θ⊗¬⊖θθ ``` Calculate the last working day of the month. ``` §⪪”...” ⁺θηday ``` Output the day of the week. ``` Iθ ``` Output the day of the month. ``` §⪪stth²‹θ³¹ ``` Output the ordinal suffix. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 104 bytes ``` S½⌊Ḃ÷dN„4/?›13*5/⁰14=[¹›₁1"4*₁JḊ÷¬∧∨28:›"i|30⁰⇧5%₂+]:£Wf⌊∑7%:¥∇2<[›-6]⇩`°⋏ ß₀ †ƛ ßɖ »£`⌈ið„:31=«⟇'Ḋ«½iW∑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJTwr3ijIrhuILDt2RO4oCeNC8/4oC6MTMqNS/igbAxND1bwrnigLrigoExXCI0KuKCgUrhuIrDt8Ks4oin4oioMjg64oC6XCJpfDMw4oGw4oenNSXigoIrXTrCo1dm4oyK4oiRNyU6wqXiiIcyPFvigLotNl3ih6lgwrDii48gw5/igoAg4oCgxpsgw5/JliDCu8KjYOKMiGnDsOKAnjozMT3Cq+KfhyfhuIrCq8K9aVfiiJEiLCIiLCIyMDIzXG4xMSJd) | [All test cases](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwiU8K94oyK4biCw7dkTuKAnjQvP+KAujEzKjUv4oGwMTQ9W8K54oC64oKBMVwiNCrigoFK4biKw7fCrOKIp+KIqDI4OuKAulwiaXwzMOKBsOKHpzUl4oKCK106wqNXZuKMiuKIkTclOsKl4oiHMjxb4oC6LTZd4oepYMKw4ouPIMOf4oKAIOKAoMabIMOfyZYgwrvCo2DijIhpw7DigJ46MzE9wqvin4cn4biKwqvCvWlX4oiRIiwiIiwiMjAyMywgMTBcbjIwMTYsIDE0XG4xNjc0LCA5XG4yMDQyLCAxMyJd) Takes the year and the month (one-based) seperately. January and February are considered the 13th and 14th months of the previous year. Vyxal has no Date/Time built-ins, so this uses a variation of [Zeller's Congruence](https://en.wikipedia.org/wiki/Zeller%27s_congruence). ``` S½⌊Ḃ÷dN„4/?›13*5/⁰14=[¹›₁1"4*₁JḊ÷¬∧∨28:›"i|30⁰⇧5%₂+]:£Wf⌊∑7%:¥∇2<[›-6]⇩`°⋏ ß₀ †ƛ ßɖ »£`⌈ið„:31=«⟇'Ḋ«½iW∑ S½⌊Ḃ÷dN„4/?›13*5/ ­⁡​‎‎ ## First Part of Zeller's Congruence Formula⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌­ S½⌊ # ‎⁡Split year into two halves [century, year of the century] Ḃ # ‎⁢Bifurcate, push this and its reverse ÷dN # ‎⁣Push each item to stack, multiply the year of the century by -2 „ # ‎⁤Rotate stack ([century, year of the century] is on top) 4/ # ‎⁢⁡Divide both by 4 ?›13*5/ # ‎⁢⁢Multiply month + 1 with 13/5 ⁰14=[¹›₁1"4*₁JḊ÷¬∧∨28:›"i|30⁰⇧5%₂+]­⁡​‎‎ ## Calculate number of days in month⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁣⁡⁣‏‏​⁡⁠⁡‌⁣⁡​‎⁠⁠‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌⁣⁣​‎‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁣⁡⁢‏⁠‏​⁡⁠⁡‌­ ⁰14=[ ] # ‎⁡‎⁡If month is 14 (February) ... [ | # ‎⁢‎⁢Leap year calculation: ¹› Ḋ # ‎⁣Does year + 1 divide ... ₁1"4*₁J # ‎⁤... [400, 4, 100] (Pair [100, 1] * 4 and join 100) ÷¬∧∨ # ‎⁢⁡‎⁢⁡Split on stack, logical not, and, or ¬∧∨ # ‎⁢⁢[ (year + 1 divides 4 and not 100) or (year + 1 divides 400) ] 28:›"i # ‎⁢⁣Index into [28, 29] | ] # ‎⁢⁤‎⁢⁤Calculate days for other months: ⁰⇧5%₂ # ‎⁣⁡((Year+2) % 5) % 2 == 0 ⁰⇧5%₂ # ‎⁣⁢Maps [1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1] for months 3 to 13 (March=3, ..., January=13) 30 + # ‎⁣⁣Add result to 30 :£Wf⌊∑7%­⁡​‎‎ ## Second Part of Zeller's Congruence Formula⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌­ :£ # ‎⁡Save a copy of number of days in month in register Wf⌊∑ # ‎⁢Wrap terms in list, take floor and sum all terms 7% # ‎⁣Result modulo 7 (Returns weekday as Saturday=0, Sunday=1, ...) :¥∇2<[›-6]⇩`°⋏ ß₀ †ƛ ßɖ »£`⌈i­⁡​‎‎ ## Calculate workday (as day of the week and month)⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏⁠‎⁡⁠⁢⁣⁡‏⁠‎⁡⁠⁢⁣⁢‏⁠‎⁡⁠⁢⁣⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏⁠‎⁡⁠⁢⁤⁡‏‏​⁡⁠⁡‌­ :¥∇ # ‎⁡Push the number of days in the month (register), weekday, weekday 2<[ ] # ‎⁢If weekday < 2 (Saturday or Sunday) ›-6 # ‎⁣Subtract weekday+1 from number of days in month (last workday), Push 6 (Friday) `°⋏ ß₀ †ƛ ßɖ »£` # ‎⁤Compressed string of workdays ⇩ ⌈i # ‎⁢⁡Index workday-2 into list (Monday=0, Tuesday=1, ...) ð„:31=«⟇'Ḋ«½i­⁡​‎‎ ## Day of the Month formatting⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁤​‎⁠‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌­ ð„ # ‎⁡Push space and rotate stack :31= # ‎⁢Is the day of the month 31? (Returns 1 or 0) «⟇'Ḋ«½i # ‎⁣Compressed string "thst", halve and index into string W∑ # ‎⁤Join all values in the stack (workday as day of the week, space, workday as day of the month) ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 118 bytes ``` param($y,$m)for(;!((($k=Date "$y/$m/1"|% *hs 1|% *ys(--$d))|% d*k)%6)){}"{0:dddd} {0:dd}"-f$k+('st','th')[$k.Day-ne31] ``` [Try it online!](https://tio.run/##ZY1db4IwGIWv6a9413SjdWXyYXQfMSHRebtlemfMwqAERcTRmo0gv50Vp85kvaGc5@k52/xLFDIR67UV5oVoSDysmm1QBBklJScZi/OCPl1RSkk6HAdKACZll2RdB@@voZNIcNpvKallkYgx/RN1UnbdZ6yqcWU/RvrUcLjU2IpJektNqUxuqsRkc5LejYPS2gjPWTQ1Qj5FBvepT13b9Tg4NuOAZzsho6AEz5EKs7PgDDi4l9y9V8mZO/1Bj8NDyyfF8h927V7bf4E9@4AZ7GGSF89BmFgvHysRKqiQQZSQahRIwYGI761ORQRDIO8alSIodJzlG5W02UnVqBByt1Y6vCExHMSjh4z563S0kyrPfkcWvl4xprswFFK2Lcenlvj8W9QGnul2CHU9vtwCa5UvN4C7WDtvp9VjCTJqVKPmBw "PowerShell Core – Try It Online") Takes in two parameters, `$y`ear and `$m`onth, returns a `string`. Less golfed: ``` param($y,$m) for(;(($k=(Date "$y/$m/1").AddMonths(1).AddDays(--$d)).DayOfWeek-in"Saturday","Sunday")){} "{0:dddd} {0:dd}"-f$k+('st','th')[$k.Day-ne31] ``` Finds the last day of the month, while it is a Saturday or a Sunday, check one day before Then formats the date [Answer] # Google Sheets / Microsoft Excel, 76 bytes `=let(d,workday(eomonth(A1,)+1,-1),text(d,"dddd d")&if(day(d)=31,"st","th"))` Put the month and year in cell `A1` in one of the formats specified in the question (or any other valid date format), and the formula in `B1`. The formula gets the first day of the *next* month and then finds the previous weekday before that, which is the same as the last weekday of the specified month. The day number of the last weekday of a month will never end in `2` or `3`, so it is enough to add `st` when the day is `31` and use `th` with any other date. The formula is for Google Sheets, but I tested it in the most recent version of Microsoft Excel for the web and it seems to work the fine there as well. The Google Sheets [epoch](https://webapps.stackexchange.com/a/153710/269219) is 30 December 1899. The formula will work with dates from January 1900 to December 99999. In Microsoft Excel, the range of valid dates seems more limited, and formula will work from January 1900 to November 9999. | input | expected | formula | | --- | --- | --- | | 10/2023 | Tuesday 31st | Tuesday 31st | | February 2017 | Tuesday 28th | Tuesday 28th | | 09/1674 | Friday 28th | #NUM! | | 1/2043 | Friday 30th | Friday 30th | [Answer] # [C (gcc)](https://gcc.gnu.org/), 270 250 bytes ``` char*s[]={"Mon","Tues","Wednes","Thurs","Fri","sth"};l(y){return y/4-y/100+y/400;} f(m,y){int d,p=l(y);y-=d=m<3;d=6+y+p+(31*(m+=12*d-2))/12; d+=y=31-(12652612>>(m*2-2)&3)+(m>11&p-l(y));d%=7;y-=p=d&d/4*3; printf("%sday %d%.2s\n",s[d-p],y,s[5]+(y<31));} ``` [Try it online!](https://tio.run/##VY/NasMwEITveQpjcJAsqdZK/iEoyrG33gI9JD4EK64NlWvk5CCCn92VWxroZXc@ZphlG/bRNMvSdBeXTqdaP@K3ryGm8fF@ncJ6v5rhRxy7u1v3q@vDnG5dPKtP5PHDXW93N0Q@y5nPgHMSFOdq3rTI0uD3wy0ydNRrWHmmjbZ7qYwuiScjQRJSZIkGkRomMM5AKEO01xIYAlEWogRxOCCbimBvJSbIHgC2I1v7sDKJrtbWUZutyfJUqs3owskWxclkLj5KTPIipnN4aToZNtbUB1HUBPm9hFAwL/bSDwg/NlEUtaiisCskVr8EnAounigCQfVHOwpllT@jwcv/JTkPNC/f "C (gcc) – Try It Online") Doing it the hard way - a bunch of mod 7 math to count extra days since the first Monday of Year 0. `p=l(y)` returns the number of leap years since 0. `d=m<3` is true for Feb and March `y-=d...m+=12*d-2` sets `m` to the month, where Mar is 1 and Jan and Feb are 11 and 12 of the prior year. `d=6+y+p+31*m/12` sets d to the number of extra days between the first Monday in year 0 and the last day of the prior month. (the 31\*m/12 gives the correct pattern of +3s and +2s) `(m>11&p-l(y)` is 1 if it's February of a leap year `12652612` is "31-days" for each month encoded in 2 bits, so `y=31-(12652612>>(m*2-2)&3)+...` sets y to the last day in the query month. `d+=y...;d%=7` gets the day of the week (0==Mon) for the query. `p=d&d/4*3` sets p to the days needed to truncates Sat/Sun to Fri (4) `y-=p` fixes the last day of the month `s[d-p]` is the day string, 2 characters from `s[5]+(y<31)` is "st" or "th" [Answer] # (Pure) [Zsh](https://www.zsh.org/), 126 bytes ``` zmodload zsh/datetime s=strftime for d ({31..9})$s -sT %A\ %dth `$s -r %F $1-$d`&&[[ $T = [^S]*$d\th ]]&&break <<<${T/1th/1st} ``` [Try it online!](https://tio.run/##NcqxCoMwFEDRPV/xhhi0EM1TqQg6dOkP1E0ttcSQ0oqQZFL89tQK3Q6Xu1jtVRiFfplm@ZkHCYvViRzc6F7TSGxtnVEH1WxAQrhmGMflFlEL3DYQXDoIpNPw@AUDwRUociofjLUt0AZqaO@3/kRlt099z9jTjMObVFVF1yZBpxO0bvMRIQpSkWZcZH@hOIQFF@kuPBc5F@XR8v1D/wU "Zsh – Try It Online") Using the builtin `strftime` rather than any external programs. ``` zmodload zsh/datetime # "strftime" is long enough that setting $s and using $s twice is shorter than "strftime" twice. s=strftime # start at the 31st of the month, count downward for d ({31..9}) # Get the timestamp of "YYYY-MM-DD" with strftime -r (reverse/strptime) # and find "Nameofday DDth" from timestamp. (-s)ave in $T $s -sT %A\ %dth `$s -r %F $1-$d` && # if Nameofday begins with an S or we end up on a different day of month # (like 02-31 converted to 03-03), keep going. [[ $T = [^S]*$d\th ]] && break # Fix suffix <<<${T/1th/1st} ``` [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 66 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {⊃'Dddd DDoo'(1200⌶)⊃⌽w/⍨0≠6|7|w←∊{0::⍬⋄,¯1 1 ⎕DT⊂⍵}¨(⊂⌽⍵),¨25+⍳6} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U1azukpKSouDikp@vrmFoZGDwqGebJlD4Uc/ecv1HvSsMHnUuMKsxryl/1DbhUUdXtYGV1aPeNY@6W3QOrTdUMFR41DfVJeRRV9Oj3q21h1ZogFg9e4EcTZ1DK4xMtR/1bjarBQA&f=S1MwNFAwMjAy5kpTMAIyDM2BDEsFQzNzEyDDEChiYgwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) woo-hoo. Shaggy waiting room. Takes date as `m y`. [Answer] # [Go](https://go.dev), 234 bytes ``` import(."fmt";."time") func f(m,y int)string{M,e:=Month(m),"th" t,W:=Date(y,M,31,0,0,0,0,UTC),(Time).Weekday for w:=W(t);t.Month()!=M||w<1||w>5;{t=t.Add(Hour*-24);w=W(t)} if t.Day()>30{e="st"} return Sprintf("%s %d%s",W(t),t.Day(),e)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VVHbbtNAEBWP3a-YrmRpF02NL4GWhI1UkSJeUlXUKA-AkBWvUyv4UnusYLn-El6iSrzxQ_AJfAW7dQBVK-1lZs7ROWe_3W_K_Y8qXm_jjYY8zorvLaUnZz9_Z3lV1iRcnubEZy6nLNdcsrQt1pCKHDvICpIN1Vmx6Zeop2pZFnQjcomcbjgjXE3VIiYtOlxi6KN3WO-j1xJFZOiku9J6m8QdS8sadlO1EiRn5I5E8lgt7-52r3yzzZ_PelLknieJeFu29dOTYCJnuwfAwLIUyF3EnZDz0Ou14g3xgdWa2rqA68oopFRwpwEncRqOFoQHAGo5jI5_PampqzREYDy1a4KeHeVlgZ2Oa2uVHemvFYx-2TDmYPMS0kySbqiBqYIPn6Ke9b6HgReEyKNWN8YfhL6VhKwPTMM__d8IzkxWtvES_RenE-Rv6uxR3TeASfivHnpjfWDsyvr6UgiulILr6PxdBOZmv8iE-RnJyqnjwnzrqK5n8fqhmApyrTNyrTdp4yu3U5OuMaiUGZrBcbmFHq7-JucFyTPHmySg5uDcgnBuJTj0seAIIxWMXAgGbR-GCQ2phMEofSQULi4XcBDKDtHv9-P5Bw) ### Explanation ``` import(."fmt";."time") func f(m,y int)string{M,e:=Month(m),"th" // start the date off at the 31st of the month, regardless of the month t,W:=Date(y,M,31,0,0,0,0,UTC),(Time).Weekday // subtract 1 day while... for w:=W(t); // the months don't match, or t.Month()!=M // the day is not a weekday ||w<1||w>5;{t=t.Add(Hour*-24);w=W(t)} // replace "31th" with "31st" if t.Day()>30{e="st"} return Sprintf("%s %d%s",W(t),t.Day(),e)} ``` [Answer] # bash and BSD date, 96 bytes As an alternative to [Toby Speight's answer](https://codegolf.stackexchange.com/a/266286) but using BSD implementation instead of GNU one ``` s=(1 2) m="-v$2y -v$1 -v+1m -v1d" date $m -v-$((s[`date $m +%w`]+1))d +%A\ %eth|sed s/1th/1st/ ``` It has the following limitations: * months can be integers only, not strings (`October` or `sep` for example) * separator is changed from `/` to blanks which is natural shell arguments separator There's certainly room for tweaking. [Answer] # [Python](https://www.python.org), 152 bytes Since there is already multiple python answers I've tried to use the calendar library since I never used it before. It just uses the fact that the object monthcalendar gives weeks of the month and days of those weeks as a 2d array ->then just a check for highest number in the first 5 days of last week. ``` from calendar import * def f(y,m,d=31,s="st"): if d in monthcalendar(y, m)[-1][:5]: print(day_name[weekday(y,m,d)],str(d)+s) else: f(y,m,d-1,s="th") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TU9LCoMwFNx7ioerpI3QKEIVvECvIFJCk1SpSSRJKd6k0I2b9k69Tf1Cl_Nm3nxen673tdHD8L57GR2_T2mNggtrhebMQqM6Yz3sAi4kSNQTRXiRUOKK0PkQ5wE0Ejg0GpTRvt7-RiEoXEa0KvO0GlXQ2UZ7xFl_1kyJ8iHEbQSLIa6I8xZxvHc4ANE6kW9Z0Rzl6xCv_U7SWBipKbKcNBjmy4Qt01eBaJalJD7E8cKoP4bQBE9tZvPVcVv-Aw) [Answer] # [C#](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 143 bytes ``` (y,m)=>new[]{DateTime.DaysInMonth(y,m)is{}z?z:z,z-1,z-2}.Select(x=>new DateTime(y,m,x).ToString("dddd dd")+(x>30?"st":"th")).First(x=>x[0]!=83) ``` Explanation ``` f = (y, m) => // lambda that takes year and month new[] { // create new implicitly typed array DateTime.DaysInMonth(y, m) // get number of days in month is {} z ? z : z, // hack to set variable z to this value inline z-1, z-2 // add the 2 days previous to z } // array contains the last 3 days of the given month in descending order .Select( // transform the elements of the array x => new DateTime(y, m, x) // create new datetime with the given year and month .ToString("dddd dd") // convert to string and format + (x > 30 ? "st" : "th")) // add "st" if is the 31st, "th" otherwise .First( // get first element that matches condition x => x[0] != 83) // first character is not "S" (i.e not day isn't saturday or sunday) ``` [Try it online!](https://tio.run/##lVNtT9swEP7eX3FYk7BFyPqCBmtpEVA6sTFtWqvtA/DBJG7rLcRd7EDSkN/enV3aBtRNmqU4Z99zzz13lwR6P9ByMUjj4FjGxgO3aZPIeNKDMXRhQXPvnnV7sXi8vi363IiRvBd@n@f6Mv6sYjN1AKmLcn4yb8@9@X4Dn2bpD0UkAkMzFwurSIv2MuaP1NBloSTEBWFI2B7Neq36CdGGtImZEsb8gUy0o8iu67c73aMWW3RqNSeXrvSyjeAJCs6gi8pp5l8acd/wYGk0GcY98ASM0AZRTpIMjFQxT/JtZJTVihrgKoA2682WB406eskoFTrkObQaqBNKb4NpHHrQrEKaR1hFBdJ4d3jgwXsLGSRyG6JZP7CJKohW3SFqJer/kho68VwJtpzag5IhKKv9@hY0s4UPc43V@n3JJ7HSRgba74u7dOL/SKQRVzIWdFmf/1HJmO56u1gwQzbHNaPq7icO7T/IrBBtODrBUaDG41MPznrUTcmZMPaqzV7ehR7cKRWBiqN8OFWPAy4jjZMZ80iLVe/txGZcaxGip95xd2OVCB5MgVrnr4cZjg1Ctuyg21eBIpthFCL87zxKRWftPIOJMpvjsiEuz@bSJPna3tDahbFWJrXEn0TOOi@8z2r3uhbnX/xOsRyKShicQAPaqyKqcNiGJV9Ph0OCAWRwenlFNlHl2gq4sW24yAIxs70Fwf4pORRjnkaGnrGtGoT/QZhRPhO08neyauK1KcdAd14O7ukJdl5V8Tc15yrWKhKVr@gNGdPiuZ8lg30orKYSKDK24YYU@C5viGdH6s74xjMj7HVflvu2DLafF/0lswjLt0Xon6s0NuWKZBX0TfDQxeB9ufgD "C# Try It Online") ]
[Question] [ Given a set of positive integers \$ S \$, output the set of all positive integers \$ n \$ such that \$ n \$ can be made by summing a subset of \$ S \$ in more than one different way, i.e., that are the sums of more than one subset of \$ S \$. To be clear, a subset of \$ S \$ means that you can't use numbers from \$ S \$ more than once. ## Example For example, given \$ S = \{2, 3, 5, 6\} \$, the following numbers can be made: * \$ 2 = \sum\{2\} \$ * \$ 3 = \sum\{3\} \$ * \$ 5 = \sum\{5\} = \sum\{2, 3\} \$ * \$ 6 = \sum\{6\} \$ * \$ 7 = \sum\{2, 5\} \$ * \$ 8 = \sum\{2, 6\} = \sum\{3, 5\} \$ * \$ 9 = \sum\{3, 6\} \$ * \$ 10 = \sum\{2, 3, 5\} \$ * \$ 11 = \sum\{5, 6\} = \sum\{2, 3, 6\} \$ * \$ 13 = \sum\{2, 5, 6\} \$ * \$ 14 = \sum\{3, 5, 6\} \$ * \$ 16 = \sum\{2, 3, 5, 6\} \$ Of these, only \$ 5 \$, \$ 8 \$, and \$ 11 \$ can be made in more than one way. Therefore, `[5, 8, 11]` is the output. ## Rules * The input will be non-empty and contain no duplicate numbers * Output may be in any order, but it must not contain duplicate numbers * You may use any [standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases ``` [1] -> [] [4, 5, 2] -> [] [9, 10, 11, 12] -> [21] [2, 3, 5, 6] -> [5, 8, 11] [15, 16, 7, 1, 4] -> [16, 20, 23, 27] [1, 2, 3, 4, 5] -> [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 15 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` (1=⊒)⊸/·⥊(∾∾+)˝ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKDE94oqSKeKKuC/Ct+KliijiiL7iiL4rKcudCgriiJjigL8x4qWKRsKoIOKfqArin6gx4p+pCuKfqDQsIDUsIDLin6kK4p+oOSwgMTAsIDExLCAxMuKfqQrin6gyLCAzLCA1LCA24p+pCuKfqDE1LCAxNiwgNywgMSwgNOKfqQrin6gxLCAyLCAzLCA0LCA14p+pCuKfqQ==) --- # [BQN](https://mlochbaum.github.io/BQN/), 19 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` (1=⊒)⊸/<+´∘ר⟜⥊⟜↕2¨ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKDE94oqSKeKKuC88K8K04oiYw5fCqOKfnOKliuKfnOKGlTLCqAoK4oiY4oC/MeKlikbCqCDin6gK4p+oMeKfqQrin6g0LCA1LCAy4p+pCuKfqDksIDEwLCAxMSwgMTLin6kK4p+oMiwgMywgNSwgNuKfqQrin6gxNSwgMTYsIDcsIDEsIDTin6kK4p+oMSwgMiwgMywgNCwgNeKfqQrin6k=) `2¨` A 2 for each value in the input array. `↕` Indices of an array of shape 2 × ... × 2. These are all combinations of 0's and 1's of the length of the input. `⥊` Flatten into a list of lists. `< ר` Multiply each of the indices with the input element-wise. `+´` Take the sum of each result. `(1=⊒)⊸/` Keep only elements which occur the second time. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ 33 bytes ``` Set@@@Gather[Tr/@Subsets@#]⋃{}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE7875@W5hCcWmJlVZxaUpRYzpVm@x/IdXBwcAcpKooOKdJ3CC5NAsoWOyjHPupurq5V@x9QlJlXEq2sa5cGFFOrC05OzKur5qo2rNXhqjbRMdUxAjEsdQwNdAwNdQzBPCMdY6CEGYhpaKpjaKZjrmOoY1LLVfsfAA "Wolfram Language (Mathematica) – Try It Online") ``` Tr/@Subsets@# subset sums Gather[ ] group by value Set@@@ drop first per group and join ⋃{} union (unique) ``` In normal usage, `Set` is just assignment, e.g. `Set[a,1]` ~ `a=1`, returning the assigned value. Importantly, * It always returns that assigned value, even when the assignment target is invalid, and * When called with ≠2 arguments, it reasonably interprets that as assigning a target to a `Sequence` of the remaining arguments, i.e. `Set[a,1,2]` ~ `a=Sequence[1,2]`. (On a side note, Mathics does *not* do this, possibly because `Set` already has `SequenceHold`) Together, these mean that `Set` can (usually) replace `##2&` to save one byte. [Answer] # [R](https://www.r-project.org), 66 bytes ``` \(S,t=table(unlist(Map(\(i)combn(S,i,sum),seq(!S)))))names(t[t>1]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3nWI0gnVKbEsSk3JSNUrzcjKLSzR8Ews0YjQyNZPzc5PygNKZOsWluZo6xamFGorBmiCQl5ibWqxREl1iZxirCTVpT5pGsoahpqayAibQtVOIjuUCKTDRUTDVUTBCV4ZQYKmjYGgAxIZAjKQMpMDIEKLESEfBGGyMGYoxICVAQQuQZohCQyDX0ExHwRxI6SiYwFSDFIKEjYD2GAFNMjKPhfhhwQIIDQA) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ṗṠsĠ~Ḣvh ``` [Try it online](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZfhuaBzxKB+4biidmgiLCIiLCJbMTUsIDE2LCA3LCAxLCA0XSJd) or [run all test cases](https://vyxal.pythonanywhere.com/#WyJQaiIsIsabIiwi4bmX4bmgc8SgfuG4onZoIiwiO1rGm2AgPT4gYGoiLCJbWzFdLCBbNCwgNSwgMl0sIFs5LCAxMCwgMTEsIDEyXSwgWzIsIDMsIDUsIDZdLCBbMTUsIDE2LCA3LCAxLCA0XV0iXQ==). `sĠ~Ḣvh` is the shortest way I can think of to keep only duplicates, so... `~Ḣvh` could alternatively be `vḢfU` for same byte count. ## How? ``` ṗṠsĠ~Ḣvh ṗ # Powerset of (implicit) input Ṡ # Sum of each s # Sort Ġ # Group consecutive identical items ~ # Filter for: Ḣ # Remove the head (this means if it is only one item long, it will be falsey, else truthy) vh # Get the first item of each ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 69 bytes ``` a=>(g=([v,...a],s=0)=>v?g(a,s+v)|g(a,s):(g[s]=-~g[s])-2||print(s))(a) ``` [Try it online!](https://tio.run/##bY/BTsMwDIbvfQrfmmhutoSxjVUpJ54i8sGqaBma1qmZclnh1YtTLoCw9Muxv/@P5HdOHNvxdL1V6TB3fmbfqN6rkNAYw4TRb7Rv0nOvGOMq6Wl56KPqQyRffeamKzdN1/F0uamotWI916EACJbgVyGs1xAooy3CI4Kjf9ATgt2IrCgbvpGzC3QID0t0Rz9yMh9yYrFYmewOYS8NYSu@bMkbJ986ibs9FVSYbhhfuH1TDL6Bu0Tb4RKH86s5D70qQwkrYFFJpa6FdnJY/ccliw89fwE "JavaScript (V8) – Try It Online") ### Commented ``` a => ( // a[] = input array g = ( // g is a recursive function taking: [v, // v = next value ...a], // a[] = remaining values s = 0 // s = sum ) => // v ? // if v is defined: g(a, s + v) | // do a recursive call where v is added to s g(a, s) // do a recursive call where s is left unchanged : // else: (g[s] = -~g[s]) // using g as an object, increment a counter for // the sum s -2 || // if this is the 2nd time we reach this sum: print(s) // print it )(a) // initial call to g ``` [Answer] # [J](http://jsoftware.com/), 28 19 bytes ``` [:~.@(#~1-~:)(,,+)/ ``` [Try it online!](https://tio.run/##PY0xC8IwEIX3/IqHgkkwTXuXNm0DhYLg5OTqKC3i4mDn/PWYYnU4OL5377tn2lk5YwiQMKgQ8hQWp@vlnG4h2lHtIxUxaGXMUZdJi2V6L4PFdH@8RlWEgypD1Ji1EC0a9PCgCjU6OBCDCGsBBM6gRiOk3Mh/yxQslAlM@kv61ZGrxKLL4U/CxpnGeEEeXIEduN1c@cajzV/q9AE "J – Try It Online") *-9 thanks to ovs for the `(,,+)/` trick for calculating all subset sums!* * `(,,+)/` All subset sums * `[:(#~1-~:)` Keep only repeats * `~.@` Dedup [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ŒP§œ-Q$Q ``` [Try it online!](https://tio.run/##y0rNyan8///opIBDy49O1g1UCfx/uP3opIc7Z2hG/v8fbRiroxBtoqNgqqNgBGJa6igYGgCxIRCDBYx0FIzB0mYgniGQYWimo2AOpHQUTMBCOkY6xjomOqaxAA "Jelly – Try It Online") ## How it works ``` ŒP§œ-Q$Q - Main link. Takes S on the left ŒP - Powerset of S § - Sum of each $ - To the list of sums: Q - Deduplicate œ- - Set difference Q - Deduplicate ``` [Answer] # [Desmos](https://desmos.com/calculator), 96 bytes ``` n=L.length S=[total(floor(mod(i/2^{[0...n]},2))L)fori=[0...2^n-1]].sort f(L)=S[S[2...]=S].unique ``` [Try it on Desmos!](https://www.desmos.com/calculator/3ldqmbxun8) ### How it works Conceptually similar to [Steffan's Vyxal solution](https://codegolf.stackexchange.com/a/247334/68261) but lacks builtins :) ``` S=[total(floor(mod(i/2^{[0...n]},2))L)fori=[0...2^n-1]].sort for i=[0...2^n-1] # Powerset of input as bitmasks total(floor(mod(i/2^{[0...n]},2))L) # Sum of each .sort # Sort f(L)= S[ ] # Filter for: S[2...]=S # Next element is equal to current element .unique # Remove duplicates ``` Note on the slice comparison: `S[2...]` is the list `S` except for the first element. Since broadcasting takes the shorter list, `S[2...]=S` is equivalent to `S[2...n]=S[1...n-1]`, or `[{S[i+1] = S[i]} for i=[1...n-1]] = 1`. [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 33 bytes ``` ${{_~x>1}\Unique@x}##Sum=>Subsets ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@1@lujq@rsLOsDYmNC@zsDTVoaJWWTm4NNfWLrg0qTi1pPi/X2pqSnG0SkFBcnosV0BRZl5JSGpxiXNicWpxdJqOQjSXAhBEG8bqQBgmOgqmOgpGMK6ljoKhARAbAjFc0EhHwRiszAwmYgjkGJrpKJgDKR0FE7gw0CSwWpCpsVyxsf8B "Attache – Try It Online") *Happy 1,000 answers on this site to me?* ## Explanation ``` ${{_~x>1}\Unique@x}##Sum=>Subsets pure function Subsets get all Subsets Sum=> and map Sum to each subset ## then ${ } x = the set of subsets sums Unique@x get those unique sums { }\ and filter each sum _~x ...by counting how often it appears in x >1 ...and asserting it is more than 1 ``` ## Other approaches Unfortunately, while there are a few builtins which have similar behavior, wrangling them into a manageable format proves to be too verbose. **50 bytes:** `Flat@Betail@{Commonest[_,1:#_]^^nil}##Sum=>Subsets` **39 bytes:** `${{_&Count!x>1}\Unique@x}##Sum=>Subsets` **38 bytes:** `First=>{_@1@1}\Positions##Sum=>Subsets` **37 bytes:** ``@&0=>{_@1@1}\Positions##Sum=>Subsets` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 48 bytes ``` a->[k-1|c<-Vec(prod(i=!k=0,#a,1+x^a[i])),c>#k++] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LU1BCsIwEPzK2l5SuoGm1qpg-wwvIUqoRkJFQ2lBwZ94KYj4Jn_jJvWwuzOzM7vPj9Od3Z_c-DJQvYfe8NU307yWLRePZsO3x4a57npgtpq1VYaxRpHedlpalSTY1HGbpuqfG7Rz5zvTwGtwnb30BCNPIjBMkx2kFIp6gbBAyD1cI4iMSlAFIUeYh3XpmSAgSoQlDYQiSJQMHn9FqWR6Po7T_AE) Using generating functions. For input \$\{a\_1,\dots,a\_n\}\$, finds all \$k\$s such that the coefficient of \$x^k\$ in \$\prod\_{i=1}^n(1+x^{a\_i})\$ is greater than \$1\$. [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 37 bytes ``` [ all-subsets [ Σ ] map duplicates ] ``` [Try it online!](https://tio.run/##RY5NDoIwFIT3PcVcQGIVMOoBjBs3xhVhUUqNjVAqbReGcBrv45Xq8yc4q5kvLzPvLKTv@ng67g@7DVrhL4ns2kobQVhL90XBaNnVCrZX3t9tr42HU7egjFSOnHfYMjYwkAZwjD@XIsNiSmvwOTgH/6MFlnSST5ln4DlWVJESG1ksIJpm5kL1GSnwfKCknyzqYBsthaf9Mr6B80Jek/gC "Factor – Try It Online") [Answer] # [Python](https://www.python.org), ~~79~~ 75 bytes -4 bytes thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)! ``` def f(a,*o): for x in a: for d in*o,0:o.count(v:=x+d)==1!=print(v);o+=v, ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LYwxDoJAEEV7TjFW7MJgWEBUzJ5ASztCQWQJJIQlBBDPYkOjd-I2DmAx-fP-zP_vb_PqCl1P06fvcuc0XzOVQ85StDSPDMh1CyOUNaQEK2VElkY30vuH7uuODZEc7YxLKXayacvF4RdtywH_lc6zKCsF97ZXawlTQ1qxsm76jnHOydpipmNaPt9C03yLRWLEAcIBwaPtjCBcGkGzsIfgr8eQQJCKEOFIghAsDqXWj6Uh2Up_) --- # [Python 2](https://docs.python.org/2/), 102 bytes Much longer, but more fun ;) (and much [faster](https://tio.run/##HYtBCoMwEEX3nmI2imKhSZaOc5gutIaUOMyk1ELw6jEtPPjw@I@/adujK0XJIpNp1l3gAB8r/E79MDUgpJ3O89GdnPm/ipxJUDP9PIbawWfzrwWk/sGvIK2bWHxMEKqQOzkMI9lS5BGfS29v1pjhAg)) ``` s=1;p=0 for x in input(): r=s&s<<x&~p|p<<x&~s;p|=r;s|=s<<x;k=0 while r: if r%2:print k r/=2;k+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY5NboMwEIX3nOJtGjeJo2KTf-MbdNldlFViFEQElg0KkVAv0g2bqlJvxG06hkoevZnn-Wbm68c-61tVyv73Ul0NNBhj302drfZD5rVQVsdRVjm0yEt6tqlf58cITvuZT9N29mk7O6pXttNO-U4HXxXE4XHL7waO-pFncC_yaF1e1ijIcG9aqmKpxf-2OS2OJuDDNSYwpjUXhLMon0C2YotkAvrh_STO0WnNseGQlB04REwhKEItOZLxc0uFIBVbjh0Jxzo4RI0dYcJ5GvoH) [Answer] # [Haskell](https://www.haskell.org/), 120 bytes ``` g(s,d)i=(i:s,if i`elem`s&&i`notElem`d then i:d else d) f c=snd.foldl g([],[])$map(sum.zipWith(*)c)(sequence[[0,1]|_<-c]) ``` [Try it online!](https://tio.run/##XYsxT8MwFIT3/IobqspGj6oupYiIjAxMHTtYFonil@YJxwk4XRD/PU27keF0@r7TtVX64hCmrpKIPMfHEUpndyrg@wwYfiSOWKGBNe4/7wnPhN3CvhLMdo6Zs9x2hKf76bAYzOzMgfAyF2HvprNK5LUUSvJE0kBKDtyVab2WMvbj@w08xpYjJPfgkBheZw3qIkW/afrgA87KOrJOr7pqUOnSbX5lOMnYqgdda5X4@8KxZmu3ZNzf59tj7fQ0XQE "Haskell – Try It Online") * `g :: ([Int], [Int]) -> Int -> ([Int], [Int])` is a straightforward function which keeps track of all 'seen' integers in the first list in the tuple, and all 'duplicates' in the second list. * `sequence [[0,1] | _ <- c]` generates the Cartesian product of *n* copies of `[0, 1]`, where *n* is the length of the input, i.e. it generates all permutations of 0 and 1 with length *n*. * `map (sum . zipWith (*) c)` takes the dot product of each of these permutations with the input, which generates all possible sums (plus a stray zero, which is inconsequential, since the input is positive). [Answer] # [SageMath](https://www.sagemath.org/), 123 bytes Golfed vesrion. [Run it on SageMathCell!](https://sagecell.sagemath.org/?z=eJxNUE1rAjEQvS_sf3h4MaFRGmsVBT16rr0ua4k6keBusiRZaBH_e5OcHBjm8817zJU0NFN86ymO3jZ3aOdxFz2MBdmxJ68iscG7K5NvX677s643qvs29saOR4Hp75TPb2QZP50L9pyRis8vjrQ2F0M2BhYG5QPtDqoLxLnR6Peyrau6MnYY409nQgzYoWlkK9AsBT4FFjndCMj35DJ5aSwEPsp4lSuZErkSWKcgsCythCw7-UqbSLIolUW9cG3rCskGb2xkevJQT8z2eORPPCf8H1VOT9Y=&lang=sage&interacts=eJyLjgUAARUAuQ==) ``` def f(a):return[k for k,m in enumerate(prod(1+PolynomialRing(QQ,'x').gen()^b for b in a).coefficients(sparse=False))if m>1] ``` Ungolfed vesrion. [Run it on SageMathCell!](https://sagecell.sagemath.org/?z=eJx9UtFqwjAUfR_sHy7uwZZFWZxzbKAvA2Fv01fREuqNhtakJKlziP--m1RdYWOFkPSce885ae8aJUil11nhEpG-3t4APXfwZlF4BAGVKb-02SlRglV60_BzGMPHlZgTnsxmDLqHbtoUHKhg3t-gTgi4aooyr8sg67cIRKIVnnpB1jr3yuimkIjsgpBMZc064XAPh5XIFEhjIexKg2hpT-kKUTY3KKXKFWrvwMj_rWKxI5O2Z78tkbhKWIfjqSgdtvzefVBEMHu0v30FhbHoa6sjV_T2oqzRxfCfW5Vv_2ixlDN-9KAnNPDGqgjxFkVsLVjTEy6Put7FCElziRSUPLMT4MtL0nOKwgVA6ar2Wamcj6ILvmSwGDJ4YjAIxxcG_IEWpxWBAYPHSI_CG6cDHzF4po3BMELUGWuCyjK6xh8UErbczmNV0QT5RHaO4gS9CRx_5u7USb8B7OfCqg==&lang=sage&interacts=eJyLjgUAARUAuQ==) ``` def find_ks(a): # Create a polynomial ring R = PolynomialRing(QQ, 'x') x = R.gen() # Calculate the generating function gen_function = prod(1 + x^a_i for a_i in a) # Find the coefficients of the generating function coeffs = gen_function.coefficients(sparse=False) # Iterate over the coefficients and return the k-values for which the coefficients are greater than 1 ks = [k for k, coeff in enumerate(coeffs) if coeff > 1] return ks input_lists = [[1], [4, 5, 2], [9, 10, 11, 12], [2, 3, 5, 6], [15, 16, 7, 1, 4], [1, 2, 3, 4, 5]] for a in input_lists: print(f"{a} -> {find_ks(a)}") ``` Using generating functions. For input \$\{a\_1,\dots,a\_n\}\$, finds all \$k\$s such that the coefficient of \$x^k\$ in \$\prod\_{i=1}^n(1+x^{a\_i})\$ is greater than \$1\$. [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 12 bytes ``` R@)++JNB\\NB ``` [Try it online!](https://tio.run/##SyotykktLixN/V@tpGunZG2tG1uU@D/IQVNb28vPKSbGz@l/aUFtuM//aMNYBUyga6cQHcsVbaKjYKqjYBSLTc5SR8HQAIgNgRiuAiRnZAiUNdJRMAZrNotF1QkUsgDpAqoxBLINzXQUzIGUjoJJLFwNSNAIaLYR0Agjc5BKIA02EOQgZLugQkBrwMYATUZ1FgA "Burlesque – Try It Online") ``` R@ # All subsequences )++ # Map sum J # Dup NB # Remove duplicates \\ # List elements in set A not in B NB # Remove duplicates ``` [Answer] # [Python 3](https://docs.python.org/3/), 106 bytes ``` g=lambda s:{s}|{q for n in s for q in g(s-{n})} def f(s):*q,=map(sum,g(s));*map(q.remove,{*q}),;return{*q} ``` [Try it online!](https://tio.run/##HY7LDoIwEEX3fEWXLRmN5WWE8CWEBYYWSaSlLZho7bdjx9WcMzdzM@t7e2iVH8fUPoflPg7E1d6FrzdEaksUmRVxfzSIE3UnrwILySgkkdSxOjXQLsNK3b5AjBlrUlRztmLRLwE@NYFBY8W2W4VyYJvDtq7jPXQFlJDFeQN@Ac6Bo2SQx3UViZfAK7gChwINMIknfV8nhKx2VhuVVFr9EcqJDR9gxw8 "Python 3 – Try It Online") Requires a `frozenset` as input. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` æOТ≠ÏÙ ``` [Try it online](https://tio.run/##ASEA3v9vc2FiaWX//8OmT8OQwqLiiaDDj8OZ//9bMiwzLDUsNl0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w8v8D084tOhR54LD/Ydn/tf5Hx1tGKujEG2iY6pjBGJY6hga6Bga6hiCeUY6xkAJMxDT0FTH0EzHXMdQxwTM1QHJAbXFxgIA). Or alternatively: ``` æO{Åγ≠Ï ``` [Try it online](https://tio.run/##yy9OTMpM/f//8DL/6sOt5zY/6lxwuP///2gjHWMdUx2zWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w8v8qw@3ntv8qHPB4f7/Ov@jow1jdRSiTXRMdYxADEsdQwMdQ0MdQzDPSMcYKGEGYhqa6hia6ZjrGOqYgLk6IDmgtthYAA). **Explanation:** ``` æ # Get the powerset of the (implicit) input-list O # Sum each inner list Ð # Triplicate it ¢ # Pop the top two, and get the counts of each item ≠ # Check which counts are NOT 1 (thus >= 2) Ï # Only keep those values from the remaining list Ù # Uniquify it # (after which the result is output implicitly) æO # Same as above { # Sort them Åγ # Pop and run-length encode this list, pushing the list of values and # list of counts as two separated lists ≠Ï # Same as above # (after which the result is output implicitly) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ⊇ᶠ+ᵐ{⊇Ċ=}ᶠhᵐd ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NtC7Qfbp1QDWQe6bKtBXIzgNyU//@jDU11DM10zHUMdUxi/0cBAA "Brachylog – Try It Online") ### Explanation ``` ⊇ᶠ Find all subsets of the input +ᵐ Compute the sum for each of these subsets { }ᶠ Find all: ⊇Ċ= Subset of 2 elements which are equal hᵐ Get the head of each of these subsets d Remove duplicates (necessary if 3 or more subsets sum to the same number) ``` There are other similar approaches which are also 13 bytes, such as [`⊇ᶠ+ᵐọ{t>1&h}ˢ`](https://tio.run/##ATMAzP9icmFjaHlsb2cy///iiofhtqAr4bWQ4buNe3Q@MSZofcui//9bMTUsMTYsNywxLDRd/1o) or [`⊇ᶠ+ᵍ{l>1&h+}ˢ`](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NtC7Qfbu2tzrEzVMvQrj296P//aENTHUMzHXMdQx2T2P9RAA). [Answer] # [Desmos](https://desmos.com/calculator), 148 bytes ``` L=[∑_{n=1}^{2^{l.length}-1}bfori=[0...l.total]] b=\{\total(l\mod(\floor(2n/{2^{[l.\length...1]}}),2))=i,0\} K=[0...L.\length]\{L>1,0\} f(l)=K[K>0] ``` [Try It On Desmos!](https://www.desmos.com/calculator/b6jdvu714l) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/4yph7pr3ik) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` ⊞υ⁰FAF⁺υι⊞υκIΦ⌈υ‹¹№υι ``` [Try it online!](https://tio.run/##NYvBCsIwEETvfsUeN7CCWvTSY0EQFHIvPYRSaTBtJJsV/36NLZ3bzHvTjy710QVVKzyiEBxMvXvGBHib35LRGFiaDcJ/7Muwqa@i2uTnjI3jjFcf8pDw4b5@kgnFENwHZjwSNFGKtd5LatW2PRFUBGeCS9fp/hN@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⊞υ⁰ ``` Start with `0` as the sum of the empty subset of `S`. ``` FA ``` Loop over the elements of `S`. ``` F⁺υι⊞υκ ``` Add the element to all of the existing sums and append the results. ``` IΦ⌈υ‹¹№υι ``` Output the values that occur more than once. [Answer] # [Python 3.8](https://docs.python.org/3.8/), 152 bytes *-5 bytes thanks to `ovs`, -4 bytes thanks to `pxeger`, and -2 bytes thanks to `AndyB`* Outputs a set of numbers or an empty `set()` if the condition is not met. ``` lambda s:(r:=range(len(s)))and{T(l)for j in r for l in c(s,j+1)if T(T(k)==T(l)for i in r for k in c(s,i+1))>1} from itertools import*;c=combinations;T=sum ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RY9NbsIwEIX3nGKWdmskTCktQeYU2aVZmBC3Q_wT2WZRVb1Iu4mE6J24DXYoYjGaN8_fPNu_f_1n_HB2OCrxdjpENX09_2hptjsJoSC-EF7a95bo1pJAKZV291USTZXzsAe04CFLnWVDAts_cooKSlKSjgpxQ_GOdjcUE0o3_HuivDOAsfXROR0ATe98fFg3onFmi1ZGdDasSxEO5v-FXQ4KOaiqeM2gWjB4ZjDPcsWAz1LxVKMxZ_A0Hi_zxJPgSwYvqTFYjFbaHJmcUtfFBKD3aCNR-cvXK4fh2i8) [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` à mx ü lÉ câ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=4CBteCD8IGzJIGPi&input=WzIgMyA1IDZdCi1R) [Answer] # [Zsh](https://www.zsh.org/), 75 bytes ``` for i;a=({$i,}+0$^a) for s ($a)((++S[s])) for s ("$S[@]")((++k,s>1))&&<<<$k ``` [Try it online!](https://tio.run/##PYuxCoMwGIT3PMUhQfMTB3@rltKk9B0cxUIWqQi2mE4tffY0cehwHPfd3dvfw6RIhemxYT47qz5yLr@6kjdHIkEPJR0ppXU/@JH@MJP9cB2zvVlKf2GiPDfGyCU8t3l9obDWFiTEBI5q0KKOfgJXYAanUOMQcZcmLbjDEYwmpb2Jl/AD "Zsh – Try It Online") Accidentally out-golfed my old [power set implementation](https://codegolf.stackexchange.com/a/190818/86147), whoops! :) ``` for i a=({$i,}+0$^a) # Recursively generate sum strings (e.g.: +0+02+0+04) for s ($a) ((++S[s])) # Count how many times a sum occurs for s ("$S[@]") ((++k,s>1))&&<<<$k # If sum $k is bigger than 1, print $k. ``` [Answer] # T-SQL, 114 bytes Using a table variable as input ``` WITH D(s,b)as(SELECT*FROM @ UNION ALL SELECT S+Q,L FROM @,D WHERE b<l)SELECT s FROM D GROUP BY s HAVING SUM(1)>1 ``` **[Try it online](https://dbfiddle.uk/?rdbms=sqlserver_2019l&fiddle=e98cbd8474daa9eef4012c6c53b3a83a)** [Answer] # Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 17 bytes ``` (!!1)~<<bg<fo<<ss ``` ## Explanation * `ss` get all subsequences * `fo` sum them * `bg` group like elements * `(!!1)` get the second element from each group `(!!1)~<<bg` appeared in [this answer](https://codegolf.stackexchange.com/a/256322/56656) previously as a way to get all elements that appear more than once. ## Reflection If you click on the linked answer you can see in that answer I said: > > `(!!)` should have a prefix function, and a bunch of versions with the index prefilled. I noticed this earlier but still didn't fix it, and now it's coming back to haunt me. > > > Well guess what, I *still* haven't fixed it, and it's still losing me bytes. On top of that the fact that I've used the exact same code `(!!1)~<<bg` now in two different answers is probably a good indicator that it should receive a standalone function. [Answer] # [Arturo](https://arturo-lang.io), 58 bytes ``` $=>[powerset&|map=>sum|tally|select[k,v]->v>1|map[k,v]->k] ``` [Try it](http://arturo-lang.io/playground?ensA85) [Answer] # [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ü÷┬┼╔ª8┐b▼¶╦S╟ ``` [Run and debug it](https://staxlang.xyz/#p=81f6c2c5c9a638bf621f14cb53c7&i=%5B2,3,5,6%5D) definitely golfable, cant seem to find any way to right now unpacked: # [Stax](https://github.com/tomtheisen/stax), 16 bytes ``` S{|+mX{x#1=!fu|u ``` [Run and debug it](https://staxlang.xyz/#c=S%7B%7C%2BmX%7Bx%231%3D%21fu%7Cu&i=%5B2,3,5,6%5D) ``` S{|+mX{x#1=!fu|u # whole program taking input array S S # powerset of S { m # across this powerset, map... |+ # sum { f # and filter it by X x# # the count of the element in the summed powersets =! # is not equal to 1 # 1 u # uniquify |u # uneval, produces string representation of array (no idea if this is required or not, otherwise stax outputs the array as an array of charcodes) ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~131 129~~ 123 bytes *saved 2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)* ``` *c,i,j;f(*a,n){for(i=n,j=1;i--;)c=calloc(j+=a[i],8);for(i=n*j,*c=1;j;)i?c[i%j+a[i/j]]+=c[--i%j]:c[--j]>1&&printf("%d ",j);} ``` This leaks horribly. [Try it online!](https://tio.run/##XVJNj5swED3Dr5il2sgG08bp7vbDS/bUXnvsgaLKdSBr1zERIVLbVf566QwEJeqJ8Zs3b96zMbnxOmyHITXCCqcalmoR@EvTdswWQbhCKpvnipvCaO9bw1xW6NJW4j1XZ1LqRGqQ5xS3T6a0ty5DxhtXVVlhyjxHoPpIhavWcrHYdzb0DUtuN5AIx9VpeGWD8cdN/XjoN97@eP28jq8gpG//gza2JWSnbWD8JY5QENA3WBVH5ll3kHobagFp3/6sA3718Re2DvZP/b0HBIzea2P73wJ8HWjofIYCiNQ2DCU5NjQiuyn4zCEYkwOjHdheqm3dU80W09YFLiCPgcNNAZ@@fFZNV9fMcA7oNcKN4xSWowx6wzONKmCjYXLRd1hST0AC30LCuYKJuZxkIjvTPDvHXAqQS7KHzQbYJVRBMSG9zsaJNcbr6imfvlwLZAVcx0ViiQpZViGfLjk6ze7Jxc38pCUkaNPC43it/PLSGEIA/hSoMOrNnQryNYxTpEcWcHBiHPsD9sfOKT4NMr6De1jFHzAiSAlyFa/gLUIPsbwH@QDvQMJdLIFQpP41jdfbw5B/DW1ud3tvMcw/ "C (clang) – Try It Online") ]
[Question] [ At time of writing, my reputation is \$16,256\$. As I [noted in chat](https://chat.stackexchange.com/transcript/message/55626072#55626072), > > Oh cool my rep is the concatenation of two powers of 2: 16,256 > > > Or even the concatenation of a power of 2 and its square, which is much more interesting > > > which then spawned a [CMC](https://chat.stackexchange.com/transcript/message/55626081#55626081) about checking if a number has this property. --- Given an integer \$n > 0\$, considered a decimal integer, and a power \$r > 1\$, return two distinct values which determine whether \$n\$ can be expressed as the concatenation of a power of \$r\$ and its square or not. For example, \$n = 16256\$ and \$r = 2\$ returns true (the concatenation of \$2^4\$ and \$(2^4)^2\$), while \$n = 39\$ and \$r = 2\$ does not. Note however that \$n = 39\$, \$r = 3\$ *is* true. The power of \$r\$ may be \$0\$, meaning that \$n = 11\$ is true for all \$r\$ The power of \$r\$ will always come "before" its square, so \$n = 62525, r = 5\$ is false. You will never get an input \$n\$ where its validity depends on ignoring leading \$0\$s or not (for example \$101\$ is true for all \$r\$ if ignoring leading \$0\$s and false otherwise). However, you may still get inputs with the digit \$0\$ in (e.g. \$n = 1024, r = 2\$) where leading \$0\$s have no bearing on the validity of \$n\$ being such a concatenation. Input and output may be in [any accepted method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. ## Test cases ``` n r 1 39 3 1 525 5 1 864 8 1 16256 2 1 11 r 1 416 7 0 39 2 0 15 5 0 1024 4 0 62525 5 0 ``` Feel free to suggest more test cases. [Answer] # [APL (Dyalog Unicode)](https://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 infix lambda, taking \$r\$ as left argument and \$n\$ as right argument. Requires `⎕IO←0` (zero-based indexing). ``` {⍵∊(⊢⍎⍤,⍥⍕¨×⍨)⍺*⍳⌊⍟⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/6sf9W591NGl8ahr0aPevke9S3Qe9S591Dv10IrD0x/1rtB81LtL61Hv5kc9XY965wPV1v5PA@oDKe1qftS75lHvlkPrjR@1TQSaGBzkDCRDPDyD/6sbWqlzGSukKQCBsSWXKZhlamTKZQFmWZiZcBkBWYZmRqZmXIYQdYaGYDEIyxjOUjcAGmUO5poYmsGUwA1VMDTlMgGxDA2MTMBihkZAiwA "APL (Dyalog Extended) – Try It Online") (Dyalog Extended as polyfill for version 18.0) `{`…`}` "dfn", `⍺` is \$r\$ and `⍵` is \$n\$:  `⍟⍵` natural log of \$n\$ (to avoid overflow)  `⌊` round that down  `⍳` **ɩ**ntegers zero through one less than that  `⍺*` raise \$r\$ to those powers  `(`…`)` apply the following monadic function to that:   `×⍨` multiply those with themselves (i.e. square them)   `⊢`…`¨` for each unmodified argument and its corresponding square:    `⍥⍕`… stringify the argument and its square before     `⍤,` concatenating them, and then      `⍎` evaluating the result  `⍵∊` is the original argument a member of that?     [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` ÝmεDn«}¹å ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8Nzcc1td8g6trj208/DS//8NDQwMQBgIuAwNAA "05AB1E – Try It Online") This is a *little* inefficient, so don't try the larger falsey test cases. **Commented:** ``` # implicit input, n first, r second Ý # inclusive range from 0 to n m # raise r to all of these powers ε } # map over the powers ... D # duplicate power n # square it « # and concatenate ¹ # push the first input (n) å # is this in the list? ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~63~~ \$\cdots\$ ~~56~~ 54 bytes Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!! Saved a byte porting [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s golf of [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s [JavaScript answer](https://codegolf.stackexchange.com/a/211509/9481)!!! Saved 2 bytes thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)!!! ``` f=lambda n,r,p=1:p>n or(n-int(f'{p}{p*p}'))*f(n,r,r*p) ``` [Try it online!](https://tio.run/##VZDRbsMgDEXf8xV@C45cqRBIu0j0R7Y9tFuiVeoAESZ1Qnx7RlA0JTz5HtnY97rf8GVNO8@jfly/b59XMOTJad67iwHrmTncTWBjHV2KrnGpRmxGtjT5xuEchilMoIFVkB9j7Qu1SBxp1UooUltw7iSdt4B3QnUkdojvP5G8oxPS8R/kLWKreVmy0UchSe6IWC9ZEFZPzeq3H3GSHzWVgrc1VqP1EGiAu4Hiqy/D2Ws2GEq9WDU2QEkAC3J@Dcj0KhFEn@BwgTgliM/Xm7UPNqHWw3tObv4D "Python 3 – Try It Online") Returns a falsey if \$n\$ can be expressed as the concatenation of a power of \$r\$ and its square or truthy otherwise. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes Takes `r` as input and `n` as output. Unifies if truthy, otherwise fails. ``` ;A^gj^₂ᵗc ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6OmpodbOx51LFcqKSpN1VN6uKvzUccKpbTEnGIIr/bh1gn/rR3j0rPiwGqnJ///Hx1trKNgbBmrE22qo2BqZApkWOgoWJiZABlGOgqGZkamZkAmUJGhIZA211EwMTSDyMF0GYI0mQBpAyMTiAhQE9CkWAA "Brachylog – Try It Online") ### How it works ``` ;A^gj^₂ᵗc with implicit r as input ;A^ r^some number gj [r^some number, r^some number] ^₂ᵗ [r^some number, r^some number^2] c concatenated is the output n ``` [Answer] # [R](https://www.r-project.org/) + pryr, ~~43~~ 39 bytes *Edit: -4 bytes thanks to pajonk* Or **[R](https://www.r-project.org/), [43 bytes](https://tio.run/##dc7RCsIgFIDh@z2F0I3CCfRMbUW@yobIgt0chzqip7cIIhjz@uOHP9UlTyFS8GVa43NOrj42CmWJxAmS8PTi5Nzqc5klz/dzGrm8kYA8ohD7mPdX6AVjJ6a6PRk0YBo2WA1Dw5RFYwFbqkBJ2UCtLFy@JruDU2yQ@o0ekEQNuoGfUfyn9Q0)** ``` pryr::f(any(n==paste0(s<-r^(0:n),s^2))) ``` [Try it online!](https://tio.run/##dc5BCoMwEEDRvacIdJPAFDJjktrQXEUJYqGbKIkgnj4thVIQZ/348HN9lWGc0xjXYZm3KYe65D17/5Qx7TKFsMSyTlqWxzX3UvukoPSklDqGsr1Dq4S4CGyOZMmCZaxzBjrG0JF1QJwioNYMGnRw@5puTk6JIfyNnpAmA4bBzyj90/oG "R – Try It Online") A nice function that is naturally short thanks to [R](https://www.r-project.org/)'s vectorization. `s<-r^(0:n)` generates a vector of all powers-of-`r` from 0..`n` (the `<-` here is an [R](https://www.r-project.org/) assignment operator, similar to `=`), `paste0(s,s^2)` generates a character vector of all these powers `paste`d onto their squares (the `0` in `paste0` instructs the function not to use a space in the concatenation), `any(n==...)` finally checks to see whether `n` is equal to any of the elements of the vector, conveniently coercing `n` into character form to do this. `pryr::f(...)` is a shorter way to express `function(n,r)` (from the `pryr` library), that 'guesses' the arguments using the body of the function definition (presumably by the order-of-appearance of unassigned variables: I can't actually find any explanation in [the manual page](https://rdrr.io/cran/pryr/man/f.html), but anyway it seems to work...!). [Answer] # JavaScript, ~~47~~ ~~44~~ 38 bytes ``` n=>g=(r,x=1)=>x<n&&[x]+x*x==n|g(r,x*r) ``` -6 bytes thanks to Arnauld. [Try it online!](https://tio.run/##fc7PCoJAEIDxu08xJ5mxPzq6awaNLxIdxFQK2Q2N2EPvvhUFQWXnH3x8x@pSjfVwOJ0Xxu4b34o3UnaCw9wJk5RuY8Jw63YzFzkRc@0eEg3ka2tG2zfL3nbYIgBka8KMCOIYOPhUnWpCPaVFrgiLKQXmP2XFOeHqqUnw8yqdVH5ffSkn6f1KvdTfAA) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÆVpXã¥X+²s ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=xlZwWMOjpVgrsnM&input=MzkKMw) ``` ÆVpXã¥X+²s :Implicit input of integers U=n and V=r Æ :Map each X in the range [0,U) VpX : Raise V to the power of X à :End map £ :Map each X ¥ : Test U for equality with X+ : X appended with ² : X squared s : Converted to a string :Implicit output of sum of resulting array ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 52 bytes ``` #^2+10^IntegerLength[#^2]#&[#2^0~Range~#]~MemberQ~#& ``` [Try it online!](https://tio.run/##Vc07C4MwEMDx3U9xEHBphiQ@aoeCS4dCC32MIUIq52MwBckm5qunoYitt/3uDv6Dth0O2va19s3Rk0rsOKvOxmKL4wVNazsZlorEkoiKuYc2LTqi3BWHF453R2J/G3tjZVOWp7p7S6JU7J61Nm6KIMwEkBwoJDNdmImMQrayyFMKxUrOKQDfUmwoWODilOcU9uv5W/p9A/8vcSZCKZ2j2fsP "Wolfram Language (Mathematica) – Try It Online") [Answer] # [PHP](https://php.net/), 63 bytes ``` function($n,$r){while($n>$b=($a=$r**$x++).$a*$a);return$n==$b;} ``` [Try it online!](https://tio.run/##TZDdSsNAEIXv9ykOZSA/XSRJk1iNa@mFolCw0MsYShoTUpFNTFIUxGePkxo0N8ueM3Pmm926rPubVV3WQlCXt10LhVgIIMbiSmIh4SKRZx14gUQwMZahL7GcGG7oBaGEN7VcFhJwWZ8N3@WOSwlnbBgoHHD@Ar@Qf@14TPEnDkPGTZxEiCTizQvVFyeddcdKm6QlNdbXR3l8y1nc0kGZlCpqbJs@53PrglKbUitq8u7UaNJK0SH67iNRVE2eZqWJ8SPSlm@wmJlnZYXXttL7XGfVC4/tLInZczeToHdFxZCJ@UV8ugkmNSg1lLwEKxjb9W5n4BrG/fpxY0hsH7b7u6dN1P8A "PHP – Try It Online") Or... put another way... ### [PHP](https://php.net/), 63 bytes ``` function($n,$r){while(0<$b=$n<=>($a=$r**$x++).$a*$a);return$b;} ``` [Try it online!](https://tio.run/##TZBda8IwFIbv8yveyYG2ehhttM6tZuLFhgNhgpeuSO1S6hhp11Y2GPvtXdR99Cbkfc4bnkPKvGynszIvhaBG100NhY0QwAbDa8aQESDmUw5lyAg7YDIeMSYdEIxlOGbILgpsYJzBiYwCW7li@L@Vo0d2cnDW/GdfWs@oQ6xG/pWEiCO7fKba7GDSZl8YlwxT5X2@5/tX7fpT2ikyU3XrUqKo6vfpYzDwLinpU@JFlW4OlaFd9NVGIisqnaS5i5@/SGp7g2elOs0LvNSF2WqTFs/apcZj9J6aHoPeFGXHNxs/ZnsGMTozXKjjSMaYwVnN12sHN3Du5w9Lh7FarLZ3j8uo/QY "PHP – Try It Online") Can't seem to get away from this number... ### [PHP](https://php.net/), 63 bytes ``` function($n,$r){while($n>$a=$r**$x.$r**($x++*2));return$n==$a;} ``` [Try it online!](https://tio.run/##TZBRa4MwFIXf8ysOJaC2YWiqrpvLSh82VihM6KOTIi5ix4hOLSuM/XZ37WTzJck59558N6nLur9b12XNGO9027VQSBgDEixvBJYCHlJx0YEMBIKJsQp9gdXE8EIZhAJyankkBOCRvhi@Rx3XAu7YMFAo4P4FfiH/2pVE8ScOQcZJ3JSxNKLJC9UXJ5N3x8rY3AjeOF@f5fFdk7jnmeLNfM7PV8Nm8/NiMZeOEzW6OzWGG6V4Fn33ESuqRmd5aWP8iKylExxi6rys8NZW5qBNXr3StZ0jMHvpZgL8Q/FiyCT0Ilq9FJMalBpKMsUaVrzZ7y3cwnrcbHeWQPwUHx6ed1H/Aw "PHP – Try It Online") [Answer] # Javascript (V8), ~~63~~ ~~60~~ ~~59~~ ~~53~~ ~~51~~ 43 bytes *-3 from Neil* *-2 and -8 from Shaggy* ``` n=>r=>[...n+n].some((_,i)=>[p=r**i]+p*p==n) ``` Takes input via currying: `f("16256")(2)`. Works quickly and for all values within the safe integer limit (\$2^{52}-1\$). Returns `true` or `false`. ### Old ``` n=>r=>[...n+n].map((a,i)=>[s=r**i]+s*s).indexOf(n) ``` ``` n=>r=>[...Array(+n)].map((a,i)=>""+(p=r**i)+p*p).indexOf(n) ``` [Answer] # [Rust](https://www.rust-lang.org/), ~~72~~ 70 bytes ``` |n,r|(0..n).any(|i|format!("{}{}",r.pow(i),r.pow(2*i))==n.to_string()) ``` [Try it online!](https://tio.run/##pU7LTsMwELznK5ac7MpYEEQPLumBA7@BAnGQVWdt@aG0SvLtwY6gjcSRvezszuzMuujDEr0EH1ohlBFi9FJ3DKyTOrZSiN18KIoOoW8UEgpjAam0DPlCIdSQj1ZM6OEPuXauzedpy/YxgFYo/U2Rpyy5alBAfKqSYKU4ynMglEccXGO3IDjVp2Yb5@Vmfwtz/zW6OnUCXs35pb0gvCFJpiw7U7g/wocx@pgyEi8EyoEsEzI3kQfOkfIGL2RSU2dc34Q7Uo7zOJfMcWsGougPqHaK0rpGHsy7T8/gF6F0ydm/P9i0DBpXg5JBR5CBo4mdl8d99bwvqqz6Bg "Rust – Try It Online") A port of [ovs's 05AB1E answer](https://codegolf.stackexchange.com/a/211507/85922). Thanks to ovs for helping save 2 bytes! [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 96 bytes ``` N =INPUT R =INPUT N Z =R ^ X Y =EQ(N,Z Z ^ 2) 1 :S(O) X =LE(Z,N) X + 1 :S(N) O OUTPUT =Y END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/n9NPwdbTLyA0hIszCMby44xSsA1SiFOI4OKMVLB1DdTw04lSiAIKGGkqGHJaBWv4a3JxRijY@rhqROn4aSpEKGhDxP00ufw5/UNDgKYo2EZyufq5/P9vYWbCZQwA "SNOBOL4 (CSNOBOL4) – Try It Online") Prints 1 for Truthy, and an empty line for Falsey. ``` N =INPUT ;* Input n R =INPUT ;* input R N Z =R ^ X ;* set Z = R^X (X starts as "" or 0) Y =EQ(N,Z Z ^ 2) 1 :S(O) ;* If N = Z concatenated to Z^2, set Y = 1 and goto O X =LE(Z,N) X + 1 :S(N) ;* If Z <= N, increment X and goto N, else: O OUTPUT =Y ;* print Y, which is '' unless N == Z Z^2 END ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 11 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` r#mÆ‼░²░+l╧ ``` [Try it online.](https://tio.run/##y00syUjPz0n7/79IOfdw26OGPY@mTTy0CUho5zyauvz/f0NDBSMuIGFoACYNuYwtFYy5TI1MFUy5LMxMFCy4DEFMoKgRl4mhmYI5l6GBkYmCCQA) (The two test cases with the largest \$n\$ are timing out.) **Explanation** ``` r # Push a list in the range [0, (implicit) input `n`) # # Take (implicit) input `r` to the power of each value in this list m # Map over this list, Æ # Using the following five commands: ‼ # Apply the following two commands on the stack separately: ░ # Convert the value to a string ² # Square the value ░ # Convert the squared value to a string a well + # Concatenate the two strings together l # After the map: push the first input `r` as string ╧ # And check if this string is in the list # (after which the entire stack joined together is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Uses the evaluation (`V`) trick from [Unrelated String's](https://codegolf.stackexchange.com/users/85334/unrelated-string) [answer](https://codegolf.stackexchange.com/a/211540/53748) - go give an upvote! ``` *⁹ŻżḤ$¤Vċ ``` A dyadic Link accepting an integer \$r>1\$ on the left and an integer \$n>0\$ on the right which yields `1` if \$n\$ can be expressed as the concatenation of a power of \$r\$ and its square, or `0` if not. **[Try it online!](https://tio.run/##ASAA3/9qZWxsef//KuKBucW7xbzhuKQkwqRWxIv///8z/zk4MQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/1/rUePOo7uP7nm4Y4nKoSVhR7r/H16u/6hpzf//0dHGOgrGlrE6CtGmOgqmRqYgloWOgoWZCYhlpKNgaAhiGMMYJjCGuY6CiaEZVBHcBENTmCIDI5PYWAA "Jelly – Try It Online") (large \$n\$ excluded due to speed). ### How? ``` *⁹ŻżḤ$¤Vċ - Link: r; n ¤ - nilad followed by link(s) as a nilad: ⁹ - chain's right argument, n Ż - zero-range -> [0,1,2,...,n] $ - last two links as a monad: Ḥ - double -> [0,2,4,...,2n] ż - zip -> [[0,0],[1,2],[2,4],...,[n,2n]] * - (r) exponentiate (that) (vectorises) V - evaluate (e.g. [9,81] -> 981) (vectorises) ċ - count occurrences (of n) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` Ḷ*@ż²$Vi⁸ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm1aDkf3HNqkEpb5qHHH/8PLj8191LQm8v//aGNLHeNYnWhTI1MdUyBtYWaiYwGkDQ11LC0tgQwTQzMdcyANVGcEEocoMzQwMtExiQUA "Jelly – Try It Online") *-1 thanks to Jonathan Allan* Elided the two larger test cases for the sake of being able to run. Adapted from my own answer to the CMC. I've also attempted to adapt one of HyperNeutrino's cleverer answers, but it comes out to the same length on account of needing `Ḷ` to handle the `[11, r]`: # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` ḶżḤ$*@Vi⁸ ``` [Try it online!](https://tio.run/##y0rNyan8///hjm1H9zzcsURFyyEs81Hjjv@Hlx@b@6hpTeT//9HGljrGsTrRpkamOqZA2sLMRMcCSBsa6lhaWgIZJoZmOuZAGqjOCCQOUWZoYGSiYxILAA "Jelly – Try It Online") I save on an `@` and an `⁸` by reversing the arguments, but then it takes 2 bytes to handle an exponent of 0, taking it right back up to ~~10~~ 9: # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` *Ɱ;1ż²$Vi ``` [Try it online!](https://tio.run/##y0rNyan8/1/r0cZ11oZH9xzapBKW@f/wcodjcx81rYn8/z/a2FLHOFYn2tTIVMcUSFuYmehYAGlDQx1LS0sgw8TQTMccSAPVGYHEIcoMDYxMdExiAQ "Jelly – Try It Online") [Answer] # [Rockstar](https://codewithrockstar.com/), 129 bytes ``` listen to N listen to R X's0 O's0 while N-X let X be+1 P's1 Y's0 while X-Y let P be*R-0 let Y be+1 let O be+P+""+P*P is N say O ``` [Try it here](https://codewithrockstar.com/online) (Code will need to be pasted in, with `n` on the first line of input and `r` on the second) ]
[Question] [ Some two-dimensional esolangs, such as [Forked](//git.io/Forked), and some non-esolangs, such as [Python](//python.org), can sometimes require spaces before lines of code. This isn't very golfy. Also, I'm lazy and writing a 2d lang that needs lots of spaces before code. Your task is to write a tool that makes these languages golfier. Of course, this will not be perfect; it cannot be used, for instance, when a number is the first character on a line of source. However, it will generally be useful. # Challenge You will write a program or function that either... * ...takes one argument, a filename or a string, or... * ...reads from standard input. Your program will act like [`cat`](https://en.wikipedia.org/wiki/Cat_%28Unix%29), except: * If the first character on any line is a number, your code will print *x* spaces, where *x* is that number. * Otherwise, it will simply be printed. * As will every other character in the input. # Test cases Input: ``` foo bar foo bar 1foo bar foo bar foo bar 2foo bar foo bar foo bar foo bar ``` Output: ``` foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar ``` --- Input: ``` --------v 8| 8| 80 8, 7& ``` Output: ``` --------v | | 0 , & ``` --- Input: ``` foo bar bar foo foo bar ``` Output: ``` foo bar bar foo foo bar ``` --- Input: ``` 0123456789 1234567890 2345678901 3456789012 4567890123 ``` Output: ``` 123456789 234567890 345678901 456789012 567890123 ``` # Rules * Output must be exactly as input, except for lines where the first character is a number. * Your program cannot append/prepend anything to the file, except one trailing newline if you desire. * Your program may make no assumptions about the input. It may contain empty lines, no numbers, Unicode characters, whatever. * If a number with more than one digit starts a line (e.g. `523abcdefg`), only the first digit (in the example, 5) should turn into spaces. # Winner Shortest code in each language wins. Have fun and good luck! [Answer] # [Retina](https://github.com/m-ender/retina), 9 bytes ``` m`^\d $* ``` [Try it online!](https://tio.run/##K0otycxL/P8/NyEuJoVLRUvh//@0/HyFpMQiBSjNZYgmAJcwwiEBV8ClCwVlXBY1YGTAZaHDZa7GxQVTAlUO53MZGBoZm5iamVtYcsFZBlxwliEXnGXEBWcZAwA "Retina – Try It Online") Note: Trailing space on last line. [Answer] # [Cubically](https://github.com/aaronryank/cubically), ~~69~~ 66 bytes ``` RBR3B~(+50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}}(-6>7?6&@7+70-4~)6) ``` [Try it online!](https://tio.run/##Pck7CoAwEADRPgeRxBDczWdXQVQ8gjdQK8HWQiS5etQm1TyY/dqOfT3PO@dlXtycpA7Q80iPDn74awCs5vRJTqFGgw0qijFKQ/@vJtYMxidFKmdA63wgbjtRBKIIRZEVRe4F "Cubically – Try It Online") ## Explanation: First we do this initialization: ``` RBR3B ``` To set up this cube: ``` 533 004 000 411223455441 311222331440 311222331440 555 555 200 ``` The most important thing about this cube is that face `5` sums to 32, which is the value required to print spaces. Coincidentally, it also happens to be fairly short for all other computation. After that is done: ``` ~( . . . ) Takes the first input, then loops indefinitely +50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}} Handle leading digit: +50<7?6{ } If input is greater than 47 ('0' is 48) +54>7?6{ } And input is less than 58 ('9' is 57) Then input is a digit -002+7 Set notepad equal to value of input digit ~ Take next input (only convenient place for it) ?6{ } If the notepad isn't 0 ( )6 While the notepad isn't 0: @5 Print a space *1-1/1 Decrement the notepad by one Leading digit handled (-6>7?6&@7+70-4~)6 Handle rest of line: ( )6 While the notepad isn't 0: -6>7?6& Exit if End of Input @7 Print the next character +70-4 Set notepad to 0 if it was a newline ~ Take the next character ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~15~~ 13 bytes -2 bytes thanks to @Zgarb ``` mΓo+?oR' i;±¶ ``` [Try it online!](https://tio.run/##yygtzv7/P/fc5Hxt@/wgdYVM60MbD237//@/Ulp@vkJSYpEClOYyRBOASxjhkIAr4NKFgjIuixowMuCy0OEyV@PigimBKofzuQwMjYxNTM3MLSy54CwDLjjLkAvOMuKCs4y5lAA) Uses the same technique as @Jonathan Allan ### Explanation ``` ¶ -- split input into a list of lines m -- apply the following function to each line Γ -- deconstruct the string into a head and a tail o+ -- prepend to the tail of the string ... ? ± -- if the head is a digit (n) oR' i -- the string of n spaces -- else ; -- the head of the string -- implicitly print list of strings line-by-line ``` [Answer] # JavaScript (ES8), ~~38~~ 37 bytes ``` a=>a.replace(/^\d/gm,a=>''.padEnd(a)) ``` ~~I don't think it can be improved much more.~~ *Saved 1 byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)* - Use ES8 features. [Answer] # [Python 2](https://docs.python.org/2/), ~~98~~ ~~74~~ ~~67~~ 65 bytes *-24 bytes thanks to Jonathan Allan. -7 bytes thanks to Mr. Xcoder.* ``` for i in open('f'):print' '*int(i[0])+i[1:]if'/'<i[:1]<':'else i, ``` [Try it online!](https://tio.run/##Pc09DsMgDAXg3aewWBzatAXSX5SeJGLoAIqliqAEKe3pabow@Rvee07fPE7RlOw/GZ8ohAClTXe@XG/3B1QpqNJQZaCqg606aHvQDmDlPOKUfGwoUIu0ksTXgsFiOK4zZ9/838kSphkZOdastGnmmAlpt52GB@XknrdZx4FO1PNgtevJkn8vHrkt5Qc "Python 2 – Try It Online") Takes input in the file named `f`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~24~~ 21+1 = ~~25~~ 22 bytes Uses the `-p` flag. -3 bytes from GB. ``` sub(/^\d/){"%#$&s"%p} ``` [Try it online!](https://tio.run/##KypNqvz/v7g0SUM/LiZFX7NaSVVZRa1YSbWg9v9/XSgo47KoASMDLgsdLnM1rrT8fIWkxCIuIFYAsmH8f/kFJZn5ecX/dQsA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` v0y¬dićú}, ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/zKDy0JqUzCPth3fV6vz/H61UnJmXnpOqkJyRWGSvpKNUAcXOGanJ2XpAhldpcYlCVWpRPkjWAIrhsq65BSWVCjmZeakgaQiCSsYCAA "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 95 bytes ``` lambda y:'\n'.join(re.sub('^\d',lambda x:' '*int(x.group()),z)for z in y.split('\n')) import re ``` [Try it online!](https://tio.run/##LYxBCoMwEEX3OcWsOpmShkIXFcGbhIKibVM0iWMsRnr3tBYff/f4L6T49O6Sx8rkvh6atoZUonGoX946yZ2e5kbizbSodr@UCHi0LspFP9jPQRKple6eYQXrIOkp9DbKrUIk7BA8R@AuB95Oo0REcdp5i@Lz31kUSlwP4ieJ8hc "Python 3 – Try It Online") -4 bytes by stealing the regex idea from ThePirateBay [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` V⁶ẋ Ḣǹe?ØD; ỴÇ€Yḟ0 ``` A monadic link taking and returning lists of characters, or a full program printing the result. **[Try it online!](https://tio.run/##y0rNyan8/z/sUeO2h7u6uR7uWHS4/dDOVPvDM1ysuR7u3nK4/VHTmsiHO@Yb/P//X11dPS0/XyEpsUgBSnMZognAJYxwSMAVcOlCQRmXRQ0YGXBZ6HCZq3FxwZRAlcP5XAaGRsYmpmbmFpZccJYBF5xlyAVnGXHBWcZAZwMA "Jelly – Try It Online")** ### How? ``` V⁶ẋ - Link 1, make spaces: character (a digit) V - evaluate as Jelly code (get the number the character represents) ⁶ - a space character ẋ - repeat Ḣǹe?ØD; - Link 2, process a line: list of characters Ḣ - head (get the first character and modify the line) - Note: yields zero for empty lines ØD - digit characters = "0123456789" ? - if: e - ...condition: exists in? (is the head a digit?) Ç - ...then: call the last link as a monad (with the head as an argument) ¹ - ...else: identity (do nothing; yields the head) ; - concatenate with the beheaded line ỴÇ€Yḟ0 - Main link: list of characters Ỵ - split at newlines Ç€ - call the last link (1) as a monad for €ach Y - join with newlines ḟ0 - filter out any zeros (the results of empty lines) ``` [Answer] # [Perl 5](https://www.perl.org/), 13 + 1 (-p) = 14 bytes ``` s/^\d/$"x$&/e ``` [Try it online!](https://tio.run/##K0gtyjH9/79YPy4mRV9FqUJFTT/1//@0/CIuw6TEIi6jpMQqrqScxAwu4/KMzCoQ/19@QUlmfl7xf11fUz0DQ4P/ugUA "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` unlines.map g.lines g(x:r)|x<';',x>'/'=(' '<$['1'..x])++r g s=s ``` [Try it online!](https://tio.run/##dYrbCoJAEIbv5ykGlFbxkIdKK@2mF/C@utjCNmldw0MI2bNvILYXQcPAfP/8340295xz@XI05FSwjrIc91mGmvOGkhYCUyxEm9f00qKOR9kJXoi8cUv6QOaODMzoN7U59AnZErvfkTlJDYIk0Q/EJ67bn0zLqoFhkzZSXqsKz7TG6YL/81BF8KdQAjjTPCEexvUgtiGaAXyVSVcZPD8IF8tVFK9BkQeKfFAUgKLwAw "Haskell – Try It Online") The first line is an anonymous function which splits a given string into lines, applies the function `g` to each line and joins the resulting lines with newlines. In `g` it is checked whether the first character `x` of a line is a digit. If this is the case, then `['1'..x]` yields a string with length equal to the value of the digit `x` and `' '<$` converts the string into as many spaces. Finally the rest of the line `r` is appended. If `x` is not a digit we are in the second equation `g s=s` and return the line unmodified. [Answer] # [Python 2](https://docs.python.org/2/), ~~76 72~~ 68 bytes *-4 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)*! @DeadPossum suggested switching to Python 2, which saved 4 bytes too. Just thought it's nice to have a competitive full program in Python 2 that does not *explicitly* check if the first character is a digit. This reads the input from a file, `f`. ``` for i in open('f'): try:r=int(i[0])*" "+i[1:] except:r=i print r, ``` [Try it online!](https://tio.run/##PYzLCsIwEEX38xVDFibRKNWNJdAvKV2IJHY2SUgHY8F/j/GBl7s7h5NWnmM41YUzhdsghNj/dof@@XkHvYHzpiGAQjxjTC4o6aWRRWq8LOgtIPpDycROfUsaqo8ZCSn8fd00zqvNAwVWNHaT3goUOxqPdgJ0j6tL/KaAqTUYs6n1BQ "Python 3 – Try It Online") (courtesy of [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)) [Answer] # [Java 8](http://docs.oracle.com/javase/8/docs/), 105 99 97 93 bytes *Saved few more bytes thanks to Nevay's suggestion,* ``` s->{int i=s.charAt(0);if(i>47&i<58)s=s.substring(1);while(i-->48)s=" "+s;System.out.print(s);} ``` [Answer] # [R](https://www.r-project.org/), ~~138~~ 128 bytes *-9 bytes thanks to CriminallyVulgar* ``` n=readLines();for(d in grep("^[0-9]",n))n[d]=gsub('^.?',paste0(rep(' ',eval(substr(n[d],1,1))),collapse=''),n[d]);cat(n,sep=' ') ``` This is pretty bad, but it's a bit better now... R is, once again, terrible at strings. [Try it online!](https://tio.run/##NcpBCoMwEEDRfU4R3MwMjMXYboqEXqA3EIVoogiShMT2@mmFdvfh/VSK18kZ@9y8y0jdEhJauXm5JhexGvumvg8VeyLf20Gv@TUhjJcHcDT5cA2eG0hg9zY7fjUfCc@VFSsi4jnsu4nZaQDiE6ibzYGes4saBFBR7fUmzDRbsYQgJ5OE@kf7i/IB) [Answer] # [Japt](https://github.com/ETHproductions/japt/) (v2.0a0), ~~11~~ 10 bytes Japt beating Jelly *and* 05AB1E? That doesn't seem right! ``` r/^\d/m_°ç ``` [Test it](https://ethproductions.github.io/japt/?v=2.0a0&code=ci9eXGQvbV+w5w==&input=IjAxMjM0NTY3ODkKMTIzNDU2Nzg5MAoyMzQ1Njc4OTAxCjM0NTY3ODkwMTIKNDU2Nzg5MDEyMyI=) --- ## Explanation Implicit input of string `U` ``` r/^\d/m ``` Use Regex replace (`r`) all occurrences of a digit at the beginning of a line (`m` is the multiline flag - the `g` flag is enabled by default in Japt). ``` _ ``` Pass each match through a function, where `Z` is the current element. ``` ° ``` The postfix increment operator (`++`). This converts `Z` to an integer without increasing it for the following operation. ``` ç ``` Repeat a space character `Z` times. Implicitly output the resulting string. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` Ḣ⁶ẋ;µ¹µḣ1ẇØDµ? ỴÇ€Y ``` [Try it online!](https://tio.run/##AU0Asv9qZWxsef//4bii4oG24bqLO8K1wrnCteG4ozHhuofDmETCtT8K4bu0w4figqxZ////IjdIZWxsb1xuOVdvcmxkIVxuLS0tXG5cbmhpIg "Jelly – Try It Online") -5 bytes total thanks to Jonathan Allan's comments and by looking at his post # Explanation ``` Ḣ⁶ẋ;µ¹µḣ1ẇØDµ? Main link ? Ternary if if: ḣ1 the first 1 element(s) (`Head` would modify the list which is not wanted) ẇ is a sublist of (essentially "is an element of") ØD "0123456789" then: ẋ repeat ⁶ ' ' Ḣ n times where n is the first character of the line (head) ; concatenate the "beheaded" string (wording choice credited to Jonathan Allan) else: ¹ Identity (do nothing) µ µ µ Link separators ỴÇ€Y Executed Link Ỵ Split by newlines € For each element, Ç call the last link on it Y Join by newlines ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~16~~ 15 bytes ``` jm.x+*;shdtdd.z ``` **[Try it online!](https://tio.run/##K6gsyfj/PytXr0Jby7o4I6UkJUWv6v9/XSgo47KoASMDLgsdLnM1AA "Pyth – Try It Online")** --- # Explanation ``` jm.x+*;shdtdd.z - Full program that works by reading everything from STDIN. .z - Read all STDIN and split it by linefeeds. m - Map with a variable d. .x - Try: *;shd - To convert the first character to an Integer and multiply it by a space. + td - And add everything except for the first character d - If the above fails, just add the whole String. j - Join by newlines. ``` Let's take an example that should be easier to process. Say our input is: ``` foo bar foo bar 1foo bar foo bar foo bar 2foo bar foo bar foo bar foo bar ``` The program above will do the following: * `.z` - Reads it all and splits it by newlines, so we get `['foo bar foo bar', '1foo bar foo bar foo bar', '2foo bar foo bar foo bar foo bar']`. * We get the first character of each: `['f', '1', '2']`. * If it is convertible to an integer, we repeat a space that integer times and add the rest of the String. Else, we just place the whole String. Hence, we have `['foo bar foo bar', ' foo bar foo bar foo bar', ' foo bar foo bar foo bar foo bar']`. * Finally, we join by newlines, so our result is: ``` foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 9 bytes ``` ç^ä/x@"é ``` [Try it online!](https://tio.run/##K/v///DyuMNL9CsclA6vVPj/38DQyNjE1MzcwpILzjLggrMMueAsIy44yxgA "V – Try It Online") ### Explanation ``` ç / ' On lines matching ^ä ' (Start)(digit) x ' Delete the first character @" ' (Copy Register) number of times é ' Insert a space ``` [Answer] # [Cubically](https://github.com/aaronryank/cubically), 82 bytes ``` R3D1R1D1+0(?6{?7@7~:1+2<7?6{+35>7?6{:7-120?6{(B3@5B1-0)6}:0}}}?6!@7~-60=7&6+4-3=7) ``` Note: This will not work on [TIO](https://tio.run/##PcsxCoQwEIXhPrewWZQQmMmYGQ2rEfEE3kCtFmwtRLJXz2abVO97xX9c@@fYzvNOaaUFV1xQQx34CTLJ16O2b8lPkxv/68WghYx6psnNaKDh6CHGGLjKgWEY5MW6NTRIkxKgpdaxdL0qAlWEqsiqIvoB). To test this, use the [Lua interpreter](https://github.com/Cubically/cubically-lua) with the experimental flag set to true (to enable conditionals). There's currently a bug with conditional blocks on the TIO interpreter. When using the TIO interpreter, you should replace `?6!` with `!6` and `&6` with `?6&`, which keeps the byte count the same. ``` R3D1R1D1 Set the cube so that face 0 has value 1 and the rest of the values are easy to calculate +0 Set the notepad to 1 so that it enters the conditional below ( Do ?6{ If the notepad is 1 (last character was \n or start of input) ?7@7 Output the current character if it's \n ~ Get the next character :1+2<7?6{ If the input is >= '0' +35>7?6{ If the input is <= '9' :7-120 Set the notepad to the input - '0' ?6{ If the notepad isn't 0 ( Do B3@5 Output a space B1-0 Subtract 1 from notepad )6 While notepad > 0 } End if :0 Set notepad to 1 } End if } End if } End if ?6!@7 If the notepad is 0 (did not attempt to print spaces), print current character ~ Get next character -60=7&6 If there is no more input, exit the program +4-3=7 Check if current character is \n, setting notepad to result ) Repeat forever ``` This isn't as short as the other Cubically answer, but I thought I'd give this a try anyway :D [Answer] # [><>](https://esolangs.org/wiki/Fish), 60 bytes ``` !^i:0(?;::"/")$":"(*0$. v"0"- >:?!v1-" "o ;>:o>a=&10&?.i:0(? ``` [Try it online!](https://tio.run/##S8sszvj/XzEu08pAw97aykpJX0lTRclKSUPLQEWPq0zJQEmXy87KXrHMUFdJQSmfy9rOKt8u0VbN0EDNXg@s6f9/XSgo47KoASMDLgsdLnM1AA "><> – Try It Online") ### How It Works: ``` ..i:0(?;... Gets input and ends if it is EOF ... ... ... .^......::"/")$":"(*0$. If the inputted character is a digit go to the second line ... Else go to the fourth ... ... .... If it was a digit v"0"- Subtract the character "0" from it to turn it into the corresponding integer >:?!v1-" "o And print that many spaces before rejoining the fourth line ... .^.. On the fourth line, .... Copy and print the input (skip this if it was a digit) ....v If the input is a newline, go back to the first line. ;>:o>a=&10&?.i:0(? Else get the input, ending on EOF ``` [Answer] # Gema, 21 characters ``` \N<D1>=@repeat{$1;\ } ``` Sample run: ``` bash-4.4$ gema '\N<D1>=@repeat{$1;\ }' <<< 'foo bar foo bar > 1foo bar foo bar foo bar > 2foo bar foo bar foo bar foo bar > > --------v > 8| > 8| > 80 > 8, > 7&' foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar foo bar --------v | | 0 , & ``` [Answer] # PHP, 83 chars ``` preg_replace_callback('/^\d/m',function($m){return str_repeat(' ',$m[0]);},$argv); ``` ]
[Question] [ Given a non-empty set of strings and a list of strings, find out how many times the set occurs in the list, i.e. how many times you could create the set with items from the list. Every element from the list can only be used once. > > Hint: a set is an unordered list of unique items. > > > Default [input/output rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. No external libraries allowed. Compiler/Interpreter standard libs are okay. This is code golf, so shortest solution counts. --- Test cases: ``` ["apple", "banana"], ["apple", "pear", "apple", "banana", "banana"] => 2 ["apple", "banana"], ["apple", "pear", "apple", "banana", "apple"] => 1 ["apple", "banana", "pear"], ["apple", "banana", "kiwi", "apple"] => 0 ["coconut"], [] => 0 ``` --- **EDIT:** removed a sentence stating that the input params are defined in local scope. This contradicts the default IO rules linked above. [Answer] # Python, 30 bytes ``` lambda s,l:min(map(l.count,s)) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQrJNjlZuZp5GbWKCRo5ecX5pXolOsqfm/oCgzr0QhTSNaKbGgICdVSUdBKSkxDwiVYnUUkAQLUhOLQDS6KiT1mlxUMAwihGyWgY6CoY6CiRHICChbR8FIRwHEjtX8DwA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁼þSṂ ``` **[Try it online!](https://tio.run/nexus/jelly#@/@occ/hfcEPdzb9//8/Wj2xoCAnVV1HPSkxDwjVY5GEClITi4AUmgqEUgA "Jelly – TIO Nexus")** ### How? ``` ⁼þSṂ - Main link: list theSet, list theList þ - outer product using the dyadic operation: ⁼ - is equal? (non-vectorising) S - sum (vectorises) (yields the number of times each element of theSet appears in theList) Ṃ - minimum (can only make the minimum as a multiple) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ ~~5~~ 4 bytes ``` ċ@€Ṃ ``` [Try it online!](https://tio.run/nexus/jelly#@3@k2@FR05qHO5v@//@vlFhQkJOqpKOglJSYB4RKSCIFqYlFIBpdCYIFAA "Jelly – TIO Nexus") The first argument of the program is the set, and the second argument is the list. **Explanation** ``` ċ@€Ṃ ċ@ -- Create a link which finds the number of occurrences of its left argument in its right argument (the list) € -- Map this link over each element in the first argument of the program (the set) Ṃ -- Minimum value of this. ``` *-1 byte thanks to @ETHproductions* *-1 byte again thanks to @ETHproductions* [Answer] ## JavaScript (ES6), 56 bytes ``` f=(n,h)=>Math.min(...n.map(c=>h.filter($=>$==c).length)) ``` [Try it online](https://tio.run/nexus/javascript-node#@59mq5Gnk6Fpa@ebWJKhl5uZp6Gnp5enl5tYoJFsa5ehl5aZU5JapKFia6dia5usqZeTmpdekqGpaf0/OT@vOD8nVS8nP10jTSNaKbGgICdVSUdBKSkxDwiVYnUUkAQLUhOLQDS6KiT1mppcVDMTIkSMkTBzUI1GSGZnlmeimPgfAA) [Answer] ## JavaScript (ES6), 64 bytes ``` (s,l)=>l.map(e=>m[s.indexOf(e)]++,m=s.map(e=>0))&&Math.min(...m) ``` Assumes both `s` and `l` are arrays of objects. Uses JavaScript strict equality for comparisons, so for instance `[] === []` is false. [Answer] ## [Haskell](https://www.haskell.org/), ~~37~~ 34 bytes Thanks to @Laikoni for shaving off three bytes. ``` s#l=minimum[sum[1|y<-l,y==x]|x<-s] ``` Call with `(set::[a]) # (list::[a])` where `a` is any type deriving `Eq`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` q~f{\e=}:e< ``` [Try it online!](https://tio.run/nexus/cjam#@19Yl1Ydk2pba5Vq8/9/tFJiQUFOqpKCUlJiHhAqxSoghApSE4uAFJoKhFIA "CJam – TIO Nexus") **Explanation** ``` q~ e# Read and eval the input f{\e=} e# Map each item in the set to the number of times it appears in the list :e< e# Find the minimum of the resulting list ``` [Answer] # Mathematica, 24 bytes ``` Min[#/.Rule@@@Tally@#2]& ``` Pure function taking two lists as arguments in the suggested order and returning a nonnegative integer. `Tally` counts how many occurrences of every symbol occur in the input list, and `#/.Rule@@@` converts each element of the input set into the corresponding number of occurrences. [Answer] # T-SQL, 62 ~~59~~ bytes Previous version didn't work for sets with no matches ``` select top 1(select count(*)from l where l=s)from s order by 1 ``` With s and l as tables and columns named the same as the table ``` select top 1 -- return only the first result (select count(*) -- count of rows from l -- from table l where l=s) -- for each l equal from s -- to each from s order by 1 -- sort by count ascending ``` [Answer] ## Swift, 39 bytes ``` s.map{w in l.filter{$0==w}.count}.min() ``` explanation: `s.map{}` goes through each word in s and will produce an array of counts `w in` names the mapped word for use in the next filter `l.filter{}` aplies a filter to the l array `$0==w` is the filter condition matching word w `.count` gives the number of elements of l that met the condition `.min()` returns the lowest count in the mapped result [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 9 bytes ``` ⌊/+/⎕∘.≡⎕ ``` [Try it online!](https://tio.run/nexus/apl-dyalog-classic#e9TRnvb/UU@Xvrb@o76pjzpm6D3qXAhk/X/U0f4/jcvc0NTyUc829WilxIKCnFQlHQWlgtTEIhANF0hKzANCJFasOjZ9CElSjYUIkWUqwpDszPJMIg2DuQbVUBQtyfnJ@XmlJUAlAA "APL (Dyalog Classic) – TIO Nexus") `⎕` get evaluated input (list of strings) `⎕∘.≡` get evaluated input (non-empty set of strings) and create equivalency table `+/` add across `⌊/` minimum across [Answer] # [Perl 6](https://perl6.org), ~~37~~ 18 bytes ## 37 ``` {+(($_=@^a⊍@^b)≽@a)&&.values.min} ``` [Try it](https://tio.run/nexus/perl6#pZFBSsQwGIX3OcVPkJIwmaIuXFg69BDuHEcy8ReKmSQ0yaiEHkDBI3mZuUiN1qIdcCUh5OflvY/wEj3C/qJUFdk9Q6FsNGFplYodGoUe6iEtGDu5rZuNPLy@NZstP7y8N5IXRbmXOqIvd63phxxuAvrg4bIGRgDYNZXOaaQC6FaavOiNgF@iQ9l9nseumf@ci3@yRinbz/5CTfk58ufyoX1sZ6TTiaSssiaGr@S3zisSc6NXuYqKOC0NLMZeKnJvu6mj5QrY2gtY67zxyaEKeMchZWzr4fgTmBeaC5h8@SnJlw473QtIepygXkGaHD0l/fAB "Perl 6 – TIO Nexus") Expanded: ``` { +( # turn into a 0 if False ( $_ = # store into $_ the result of @^a ⊍ @^b # use the baggy multiplication operator ) ≽ @a # is that the baggy superset of the set ) && # if that is True .values.min # get the minimum value from the Bag in $_ } ``` See [Sets, Bags, and Mixes](https://docs.perl6.org/language/setbagmix) for more information. --- ## 18 ``` {@^b.Bag{@^a}.min} ``` [Try it](https://tio.run/nexus/perl6#pZDBSgMxEIbveYohB9nFdKkePLhsKT5Db7ZCGkdZTJOwSWpLyLOvo2vQLXiSEGaYfPMR/ugRjneNatnhDFfKRhMWVqk4oFHooRvT@mnfPMhXqjI3h97kkch1QB883HdQMYDqkUvnNHIBfC8NHb4T8GvoUA6f9ZKa8be1@KdrGhF@85eq7M@VP49v/Xs/My2LSVllTQxfm9/zumWR4ttQFC1zWhq4nnJp2YsdSkaLFVRbL2Cr6eLJoQr4XEMibe/hMvHKC10LKBx9JfnG4aCzgKSnDroVpEJkzvL4AQ "Perl 6 – TIO Nexus") Explanation: `@^b.Bag` create a [Bag](https://docs.perl6.org/type/Bag) from the values `{@^a}` key into that Bag (returns a list of counts) `.min` get the minimum value of the resulting list --- [Answer] # Axiom, 42 bytes ``` f(a,b)==reduce(min,[count(x,b)for x in a]) ``` test code and results ``` (28) -> f(["1","2"], ["1", "2", "1", "1", "7"]) (28) 1 Type: PositiveInteger (29) -> f(["apple","banana"],["apple","pear","apple","banana","banana"]) (29) 2 Type: PositiveInteger (30) -> f(["apple","banana"],["apple","pear","apple","banana","apple"]) (30) 1 Type: PositiveInteger (31) -> f(["apple","banana","pear"],["apple","banana","kiwi","apple"]) (31) 0 ``` [Answer] # C++, ~~203~~ 201 bytes *Thanks to @Quentin for saving two bytes!* ``` #import<vector> #import<string> using T=std::vector<std::string>; int f(T S,T L){for(int j,b,i=0;;++i)for(auto s:S){for(b=j=0;j<L.size();++j)if(L[j]==s){b=1;L.erase(begin(L)+j);break;}if(!b)return i;}} ``` [Try it online!](https://tio.run/nexus/cpp-gcc#pY6/bsMgEIfn8hSULKBYUbsG20/gLd7aDuDg6JwYLP60Ui2e3cV2o6adIvUYDn738emmDfSDsT5/V403tkTXt/MW9KlEwaWG68L5436/Qvly/wY4Au1xS2t8yGpcsbE1ls5Rl8kMiifOt1tgcyiCN9jtDysiiy4Nu7zaOfhUlCWsY9DS6qV7KwrHRlk882qnrHCKSnUCTSuWEC6tEmceE/oomVU@WI2BxzhtQDeXcFQ4B5OWU6Ivl916kf4yNCKcalm9McHjPE9bj0QMw0WRDBMpdDokZvgmHJSwc/9L3fBsNpFXTdADXuq/4jW623uV/fb/DM/wAXdoG9MYHfyiiYyjOH0B) [Answer] # PHP, 74 Bytes ``` <?foreach($_GET[0]as$v)$t[]=array_count_values($_GET[1])[$v];echo+min($t); ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/b547f48335cb3dc8eb502a528ef481c069d2cd9c) # PHP, 108 Bytes ``` <?[$x,$y]=$_GET;echo($a=array_intersect)($x,$y)==$x?min(($a._key)(array_count_values($y),array_flip($x))):0; ``` [Testcases](http://sandbox.onlinephpfunctions.com/code/a33ac8d1b9f8409f25dddbd733dcd162344d51bb) [Answer] # Pyth, 5 bytes ``` hS/LF ``` Takes the list first and the set second. [Test suite.](http://pyth.herokuapp.com/?code=hS%2FLF&input=%5B%22apple%22%2C+%22pear%22%2C+%22apple%22%2C+%22banana%22%2C+%22banana%22%5D%2C%5B%22apple%22%2C+%22banana%22%5D&test_suite=1&test_suite_input=%5B%22apple%22%2C+%22pear%22%2C+%22apple%22%2C+%22banana%22%2C+%22banana%22%5D%2C+%5B%22apple%22%2C+%22banana%22%5D%0A%5B%22apple%22%2C+%22pear%22%2C+%22apple%22%2C+%22banana%22%2C+%22apple%22%5D%2C+%5B%22apple%22%2C+%22banana%22%5D%0A%5B%22apple%22%2C+%22banana%22%2C+%22kiwi%22%2C+%22apple%22%5D%2C+%5B%22apple%22%2C+%22banana%22%2C+%22pear%22%5D%0A%5B%5D%2C+%5B%22coconut%22%5D&debug=0) Explanation: ``` F Expand the input into l and s (not literally, since those are function names in Pyth, but...) L for d in s: / Count instances of d in l L Package all the results as a list S Sort the results smallest-first h grab the smallest element ``` [Answer] # C#, 36 bytes ``` f=(n,h)=>n.Min(c=>h.Count(x=>x==c)); ``` `n` and `h` are `string[]` and the output is an `int`. [Try it online!](https://dotnetfiddle.net/PCmbMW) This answer is inspire by @ovs and @Alberto Rivera's logic. Thank you! [Answer] # Java, 135 bytes ``` int f(List<String> s,List<String> l){int n=0,i=0;while(i<s.size()){if(!l.remove(s.get(i++)))break;if(i==s.size()){n++;i=0;}};return n;} ``` This is my first code golf challenge and answer, so not sure about the format. Does it need to be a full compiling program? Do I need to define the parameters? Suggestions appreciated. **EDIT**: wrapped code in a function. Thanks @Steadybox [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` v²y¢})W ``` [Try it online!](https://tio.run/nexus/05ab1e#@192aFPloUW1muH//0crJRYU5KQq6SgoJSXmAaFSLBeSWEFqYhGSHJIqAA "05AB1E – TIO Nexus") ``` v } # For each item in the first list... ²y¢ # Count the occurances in the second list. )W # Take the minimum occurrence count, return. ``` [Answer] # Java, 114 Bytes ``` <T>int a(Set<T>b,List<T>c){int m=2e32;b.stream().map(i->{int j=java.util.Collections.frequency(c,i);m=j<m?j:m;});return m;} ``` Tio coming soon **Explanation** * creates local variable m. * maps the set to a stream. * for each element, if the number of occurances of the element in the list is less than m, m is set to that value. * returns m, which is the number of complete versions of the set [Answer] **R 54 Bytes** ``` f<-function(s,l) min(table(factor(l[l%in%s],levels=s))) ``` Explanation: creating a table of the counts of only the values in the list that also appear in the sublist. I then turn the variable into a factor in order to generate zeros if a value that appears in the sublist does not appear in the list. Finally, I take the minimum of the counts. [Answer] ## R, ~~61~~ ~~57~~ 44 bytes ``` print(min(sapply(s,function(x)sum(l%in%x)))) ``` ~~Anonymous function.~~ Apparently you don't have to define a function for this challenge. *Saved 13 bytes thanks to count.* Explanation: `sum(l%in%x))` returns the number of times a string in `s` is found in `l`. `lapply(s,function(x))` applies that to each string in `s` separately and returns a list of sums. `min()` returns the smallest from that list. [Answer] # JavaScript (ES6), 59 bytes ``` a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0 ``` --- ## Try it ``` f= a=>b=>a.reduce((x,y)=>(l=b.filter(s=>s==y).length)>x?x:l)|0 console.log(f(["apple","banana"])(["apple","pear","apple","banana","banana"])) console.log(f(["apple","banana"])(["apple", "pear", "apple", "banana", "apple"])) console.log(f(["apple","banana","pear"])(["apple","banana","kiwi","apple"])) console.log(f(["coconut"])([])) ``` ]
[Question] [ A *palindrome* is a string that is the same forwards and backwards, such as "racecar". Write a program in some language L, that takes any program P1 in language L as input, and outputs a palindromic program P2 in language L that does the same thing as P1. You do not need to worry about handling input programs with syntax errors. This is **code golf**, so the solution with the fewest number of bytes wins. [Answer] # Perl, 55 54 bytes ``` undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a; ``` Reads program source from stdin and writes to stdout. Result of running on itself: ``` undef$/;$a=<>."\n__END__\n";print$a,scalar reverse$a; __END__ __DNE__ ;a$esrever ralacs,a$tnirp;"n\__DNE__n\".><=a$;/$fednu ``` [Answer] # Java, 225 bytes ``` class c{public static void main(String[]a){String s="";java.util.Scanner r=new java.util.Scanner(System.in);while(r.hasNext())s+=r.nextLine()+"\n";s=s.replace("\n","//\n");System.out.print(s+new StringBuilder(s).reverse());}} ``` Output on itself (when prettified beforehand): ``` class c {// public static void main(String[] a) {// String s = "";// java.util.Scanner r = new java.util.Scanner(System.in);// while (r.hasNext()) s += r.nextLine() + "\n";// s = s.replace("\n", "//\n");// System.out.print(s + new StringBuilder(s).reverse());// }// }// //} //} //;))(esrever.)s(redliuBgnirtS wen + s(tnirp.tuo.metsyS //;)"n\//" ,"n\"(ecalper.s = s //;"n\" + )(eniLtxen.r =+ s ))(txeNsah.r( elihw //;)ni.metsyS(rennacS.litu.avaj wen = r rennacS.litu.avaj //;"" = s gnirtS //{ )a ][gnirtS(niam diov citats cilbup //{ c ssalc ``` [Answer] # Python 2, 68 bytes ``` import sys x=''.join(l[:-1]+'#\n'for l in sys.stdin) print x+x[::-1] ``` Doesn't work if run from IDLE, because you need to generate an EOF character to stop the program from waiting on input. Output when run on itself: ``` import sys# x=''.join(l[:-1]+'#\n'for l in sys.stdin)# print(x+x[::-1])# #)]1-::[x+x(tnirp #)nidts.sys ni l rof'n\#'+]1-:[l(nioj.''=x #sys tropmi ``` Thanks to Greg Hewgill for helping to hammer out problems and to golf. [Answer] # GolfScript, ~~10~~ 9 bytes ``` " }"+.-1% ``` Quite similar to [minitech's solution](https://codegolf.stackexchange.com/a/31448), but it works well with newlines. It relies on GolfScript's funny (and undocumented) behavior to ignore an unmatched (and uncommented) `}`, as well as everything that follows it. It will fail if the input contains an unmatched `{`, but that would technically constitute a syntax error. ### How it works ``` " }" # Push the string "\n}". + # Concatenate it with the input string. . # Duplicate the modified string. -1% # Reverse the copy. ``` # Example ``` $ echo -n '1{"race{car"} > {"foo\"bar"} > if#' | golfscript make-palindrome.gs 1{"race{car"} {"foo\"bar"} if# }} #fi }"rab"\oof"{ }"rac{ecar"{1 $ echo '1{"race{car"} > {"foo\"bar"} > if# > }} > #fi > }"rab"\oof"{ > }"rac{ecar"{1' | golfscript race{car ``` [Answer] ## x86 machine code on DOS (`.com` file) - 70 bytes Dealing with .COM files, creating a palyndrome is easy - since the COM "loader" just puts the content of the file at address `100h` and jumps there, the program must already hardcode its end somehow and ignore everything after it, so we can just append the reverse of the first N-1 bytes (only caveat: if the program somehow tries to do tricks with the length of file everything breaks). Here is the hex dump of my `.COM`-palyndromizing `.COM`: ``` 00000000 31 db 8a 1e 80 00 c6 87 81 00 00 ba 82 00 b8 00 |1...............| 00000010 3d cd 21 72 30 89 c6 bf ff ff b9 01 00 ba fe 00 |=.!r0...........| 00000020 89 f3 b4 3f cd 21 3c 01 75 18 b4 40 bb 01 00 cd |...?.!<.u..@....| 00000030 21 85 ff 75 e5 89 f3 f7 d9 88 ee b8 01 42 cd 21 |!..u.........B.!| 00000040 eb d8 47 74 f0 c3 |..Gt..| ``` It takes the input file on the command line, and writes the output on stdout; the expected usage is something like `compalyn source.com > out.com`. Commented assembly: ``` org 100h section .text start: ; NUL-terminate the command line xor bx,bx mov bl, byte[80h] mov byte[81h+bx],0 ; open the input file mov dx,82h mov ax,3d00h int 21h ; in case of error (missing file, etc.) quit jc end ; si: source file handle mov si,ax ; di: iteration flag ; -1 => straight pass, 0 reverse pass mov di,-1 loop: ; we read one byte at time at a bizarre memory ; location (so that dl is already at -2 later - we shave one byte) mov cx,1 mov dx,0feh mov bx,si mov ah,3fh int 21h ; if we didn't read 1 byte it means we either got to EOF ; or sought before the start of file cmp al,1 jne out ; write the byte on stdout mov ah,40h mov bx,1 int 21h ; if we are at the first pass we go on normally test di,di jnz loop back: ; otherwise, we have to seek back mov bx,si ; one byte shorter than mov cx,-1 neg cx ; dl is already at -2, fix dh so cx:dx = -2 mov dh,ch mov ax,4201h int 21h jmp loop out: ; next iteration inc di ; if it's not zero we already did the reverse pass jz back end: ret ``` Tested on itself and the [solutions](https://codegolf.stackexchange.com/a/31405/9298) to a previous question seems to work fine in DosBox, some more extensive testing on "canonical" DOS executables will follow. [Answer] ## GolfScript, 8 ``` .-1%'#'\ ``` Doesn’t handle newlines, but nobody uses those in GolfScript. [Answer] # Bash+coreutils, 39 bytes ``` f="`cat` exit" echo "$f" tac<<<"$f"|rev ``` Reads from STDIN and outputs to STDOUT: ``` $ cat hello.sh #!/bin/bash echo 'Hello, World!' $ ./palin.sh < hello.sh #!/bin/bash echo 'Hello, World!' exit tixe '!dlroW ,olleH' ohce hsab/nib/!# $ ``` [Answer] # Javascript (*ES6*) Multi-line - 71 Kinda sorta stole [Quincunx](https://codegolf.stackexchange.com/users/9498/quincunx)'s comment method here: ``` alert((x=prompt().replace(/\n/g,'//\n')+'/')+[...x].reverse().join('')) ``` # Single line - 49 ``` alert((x=prompt()+'/')+[...x].reverse().join('')) ``` [Answer] # C++, 214 209 bytes ``` #include<cstdio> #include<stack> int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}} ``` Result of running on itself: ``` #include<cstdio>// #include<stack>// int main(){std::stack<char>s;int c;while((c=getc(stdin))>EOF){if(c=='\n')for(int i=2;i;i--)s.push(putchar('/'));s.push(putchar(c));}while(s.size()){putchar(s.top());s.pop();}}// //}};)(pop.s;))(pot.s(rahctup{))(ezis.s(elihw};))c(rahctup(hsup.s;))'/'(rahctup(hsup.s)--i;i;2=i tni(rof)'n\'==c(fi{)FOE>))nidts(cteg=c((elihw;c tni;s>rahc<kcats::dts{)(niam tni //>kcats<edulcni# //>oidtsc<edulcni# ``` [Answer] # Brainfuck, 749 without whitespace (not golfed) This produces brainfuck programs which mirrored palindromes, i.e. they are are mirror images of themselves. ``` ++++++++++ [->++++>+++++++++<<]>+++.>+..<.>++. >>>>+[>,]<-[+<-] >[ [-<+<<+>>>] +<-------------------------------------------[-<+>>[-]<]>[-<<<.>>>] +<<-[->+>[-]<<]>>[-<<<.>>>] +<-[-<+>>[-]<]>[-<<<.>>>] +<<-[->+>[-]<<]>>[-<<<.>>>] +<--------------[-<+>>[-]<]>[-<<<.>>>] +<<--[->+>[-]<<]>>[-<<<.>>>] +<-----------------------------[-<+>>[-]<]>[-<<<.>>>] +<<--[->+>[-]<<]>>[-<<<.>>>] <[-]>> ] <<<<[<] <--.<.>++..--..<.>++. >>[>] <[ [->+>>+<<<] +>-------------------------------------------[->+<<[-]>]<[->>>.<<<] +>>-[-<+<[-]>>]<<[->>>.<<<] +>-[->+<<[-]>]<[->>>.<<<] +>>-[-<+<[-]>>]<<[->>>.<<<] +>--------------[->+<<[-]>]<[->>>++.--<<<] +>>--[-<+<[-]>>]<<[->>>--.++<<<] +>-----------------------------[->+<<[-]>]<[->>>++.--<<<] +>>--[-<+<[-]>>]<<[->>>--.++<<<] >[-]<< ] <--.<.>++..<. ``` Given a program it outputs ``` +[[+]PROGRAM[+]][[+]MIRROR[+]]+ ``` with `PROGRAM` and `MIRROR` replaced by the program (without non-brainfuck characters) and its mirror image. [Answer] # C 168 ~~175~~ Correctly handles escaped newline inside source code **Edit 1** fixed bug when last newline missing **Edit 2** fixed bug when line inside comment ends with `*`: add a tab char before the `//` comment (and golfed more) ``` b[999999];main(c,z){char*p,for(p=b;(*p=c=getchar())>=0;z=c,p++)c-10||(z-92?*p++=9,*p++=47,*p++=47,*p=c:(p-=2));*p=47;for(p=b;*p;)putchar(*p++);for(;p>b;)putchar(*--p);} ``` C99 Standard, valid code, many warnings **Ungolfed** ``` b[999999]; // working buffer ~ 4M on 32 bit machine, max source size // c is current char, z is previous char, main(c,z) // z start as argv pointer, will be out of char range { char *p; for(p = b; (*p=c=getchar()) >= 0; // while testing EOF copy char to buffer set c variable z=c, p++) // at end loop increment p and set previous = current { c-'\n' || // if newline (z - '\\' // check if escaped ? *p++='\t',*p++='/',*p++='/', *p=c // if not escaped, add tab,/,/ and newline : (p-=2) // if escaped, drop both escape and newline ); } *p='/'; // if last newline missing, will add a comment anyway for(p=b;*p;) putchar(*p++); // ouput buffer for(;--p>=b;) putchar(*p); // outbut buffer reversed } ``` [Answer] # C# - 174 ``` using System;using System.Linq;class c{public static void Main(){var a="";var b="";while((a=Console.ReadLine())!="")b+=a+"//\n";Console.Write(b+string.Concat(b.Reverse()));}} ``` Test Input: ``` using System; using System.Linq; class c { public static void Main() { var a = ""; var b = ""; while ((a = Console.ReadLine()) != "") b += a + "//\n"; Console.Write(b+string.Concat(b.Reverse())); } } ``` Test Output: ``` using System; using System.Linq; class c { public static void Main() { var a = ""; var b = ""; while ((a = Console.ReadLine()) != "") b += a + "//\n"; Console.Write(b+string.Concat(b.Reverse())); } } // } // } // ;)))(esreveR.b(tacnoC.gnirts+b(etirW.elosnoC // ;"n\//" + a =+ b // )"" =! ))(eniLdaeR.elosnoC = a(( elihw // ;"" = b rav // ;"" = a rav // { // )(niaM diov citats cilbup // { // c ssalc // ;qniL.metsyS gnisu // ;metsyS gnisu ``` [Answer] ## PHP, 96 bytes ``` function a($b){ echo $c = "a('$b')" . strrev("a)'" . $b . "'("); $d = substr($c, 0, strlen($b) + 5); eval("$d;"); } ``` **Sample Usage:** ``` a('apple'); // echoes a('apple')('elppa')a until your bytes get exhausted ``` This is nothing clever. It's just a simple piece of code that does the job... I was in a mood for playing. I do know that this code is rife with bad programming practices! Finally, I will gladly accept any criticism and edits to this code! [Answer] # Cobra - 134 ``` class P def main i=List<of String?>(Console.readLine.split('\n')) print '/#\n[i.reversed.join("\n")]\n#/#\n[i.join("\n")]\n#/' ``` [Answer] # Racket 133 ``` (require srfi/13)(let((r read-line)(w display))(let l((i(r)))(when (not(eq? eof i))(w i)(w";\n")(l(r))(w"\n;")(w(string-reverse i))))) ``` Ungolfed (but still very imperative): ``` (require srfi/13) (let recurse ((instr (read-line))) (when (not (eof-object? instr)) (display instr) (display ";\n") (recurse (read-line)) (display "\n;") (display (string-reverse instr)))) ``` Output when given the ungolfed version as input: ``` (require srfi/13); (let recurse ((instr (read-line))); (when (not(eof-object? instr)); (display instr); (display ";\n"); (recurse (read-line)); (display "\n;"); (display (string-reverse instr)))); ;))))rtsni esrever-gnirts( yalpsid( ;)";n\" yalpsid( ;))enil-daer( esrucer( ;)"n\;" yalpsid( ;)rtsni yalpsid( ;))rtsni ?tcejbo-foe(ton( nehw( ;)))enil-daer( rtsni(( esrucer tel( ;)31/ifrs eriuqer( ``` ]
[Question] [ What general tips do you have for golfing in Befunge? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Befunge (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] When using a multi-line loop, try to use as much of it as possible: ``` >1234....v ^ < ``` vs ``` >1234v ^....< ``` [Answer] Need to drop a value after a conditional (e.g. because the other path depends on the value, but this one doesn't)? Instead of using `>$` or `$<`, take advatage of the fact that you know the truth value of the variable and use `_` instead to both change direction and pop stack. ### Example ``` '* : v >$ .. @ Prints number in binary followed by the original decimal number. > :2%\2/ :!#^_ \. ``` gets turned into ``` '* : v _ .. @ Since we know that the topmost value on the stack will be 0, we combine `>$` into `_`. > :2%\2/ :!#^_ \. ``` [Answer] Don't forget that `0` is always on the stack. For example, this means that, with an empty stack, `g` is equivalent to `00g` and `p` is equivalent to `000p`. [Answer] If you need to push a number larger than 15, use `'` to fetch the ASCII value of the next character: ``` '* ``` to push 42 rather than: ``` 4a*2+ ``` [Answer] Instead of using `|`, requiring another line (often with many extra spaces), try using `j`. For example: ``` 01-`j@more code here ``` would stop if the number on top of the stack was negative and continue onward otherwise. If you need multiple characters, use `n*j` where `n` is the number of characters you need when the value passed to `j` is `0`. Example: ``` 01-`4*j01-*more code ``` which would negate a negative number. [Answer] In Befunge-93, if the first thing you're pushing onto the stack is a string, you can often get away with dropping the opening quote. For example this: ``` "!iH",,,@ ``` could be simplified to this: ``` !iH",,,@ ``` [Try it online!](http://befunge.tryitonline.net/#code=IWlIIiwsLEA&input=) What's happening is the interpreter first tries to execute the characters in the unquoted string. The `!` performs a harmless *not*, and the `i` and `H` are not valid instructions, so they're ignored (although on some implementations you may get a warning). When the `"` is encountered, that is considered the start of the string, but because there is no closing quote, it wraps all the way around the playfield until the `"` is encountered a second time. What ends up pushed onto the stack is then this: ``` ,,,@ ···72 spaces··· !iH ``` Since we only care about the last few characters, though, none of that other stuff matters. So after the quote, we then finally get to execute the three `,` commands, writing out the message, and the `@` command, which exits. Note that this won't typically work in Befunge-98, since an unrecognised instruction will cause the interpreter to reflect instead of ignoring it. [Answer] In Befunge-93, the character input command (`~`) can often be used as a shortcut for -1, since that is the value it returns on EOF. As an example, the code below will output -1: ``` ~.@ ``` [Try it online!](http://befunge.tryitonline.net/#code=fi5A&input=) This is not recommended in production code, since when run in an interactive environment, the program would pause and wait for user input. And obviously if the user were to input something, the result would no longer be -1. That said, the rule on PPCG is that [a program may assume an empty input stream](https://codegolf.meta.stackexchange.com/a/7172/62101), and that's how it would typically be run on [TIO](http://befunge.tryitonline.net). Also note that you aren't necessarily precluded from using this trick just because your program needs to read something from the input stream. You just have to make sure you process your inputs up front, after which all future uses of `~` should return -1. [Answer] In Befunge-93, it can often be advantageous to flatten a loop into a single line, with the loop section of code being executed in both directions. For example, consider the code below, which outputs the letter `a` eight times: ``` "a"9>1-:#v_@ ^\,:\< ``` This can flatten be flattened into a single line by interspersing the loop sequence with bridge instructions (`#`): ``` "a"9>1#\-#,:#:>#\_@ ``` [Try it online!](http://befunge.tryitonline.net/#code=ImEiOT4xI1wtIyw6Izo+I1xfQA&input=) If you're just looking at the non-whitespace characters, you may get the impression that this is longer than the the original. But once you take into account the linefeed and the additional padding required in the two line version, you actually end up saving four bytes. In this particular case, the code be compressed even further by noting that that sequence `:#:` can simply be replaced with `:`. ``` "a"9>1#\-#,:>#\_@ ``` [Try it online!](http://befunge.tryitonline.net/#code=ImEiOT4xI1wtIyw6PiNcX0A&input=) In fact, any time you have the same instruction repeated on either side of a `#` command, you can simplify that to just the one instruction, so this is something you should always be looking out for when flattening a loop. To understand how this works, it can help to write out the loop sequence twice, once with all the characters following the `#` removed (i.e. what happens when executing left to right), and once with the characters preceding the `#` removed (i.e. executing right to left). ``` "a"9>1#\-#,:>#\_@ >1 - :> _ ; executing left to right > \ ,: \_ ; executing right to left ``` You can clearly see now how this matches the original two line version of the code. [Answer] Use the direction of the IP when dealing with `_` or `|`, rather than using an extra character for `!`. Real example (from [this post](https://codegolf.stackexchange.com/a/12755/9498)): ``` #v~ ,>:!#@_ ``` Can be changed to ``` #v~ :<,_@# ``` [Answer] Don't forget that `0k` does not execute the next instruction. This means that instead of doing: ``` ;some boolean test;!jv;code if false; ;code if true;< ``` You can save a character by doing ``` ;some boolean test;kv;code if false; ;code if true;< ``` [Answer] Output by exit code, where this is an allowed output form. If the challenge asks you to print one number, you can save a byte by ending the program with `q` instead of `.@` [Answer] Don't forget about the `k` operator. Instead of `"!dlroW olleH",,,,,,,,,,,,@`, do `"!dlroW olleH"bk,@`. Note that `k` does the operation *on the cell that it is at* so `9k,` would print not 9 times but 10; 9 times with the `k`, and once with `,`. [Answer] When pushing small numbers onto the stack, you can probably figure out easily enough that `45*` will get you `20`, and `67*` will get you `42`. When it comes to larger numbers, though, you really need a program that can calculate the most efficient representation for you. The easiest option for this is Mike Schwörer's [online interface for BefunRep](https://mikescher.github.io/Befunge_Number_Representations/). You simply type in a number and it'll spit out an equivalent Befunge representation. It's not always the most optimal, but it's close enough, and it's almost certain to be better than anything you could come up with by hand. The online system is limited to numbers in the range 0 to 16777215, so if you need anything larger than that, you'll want to download the [standalone BefunRep utility](https://github.com/Mikescher/BefunRep) and run the calculations yourself. If you're programming in Befunge-98, another option to consider is [Fungify](https://deewiant.iki.fi/projects/fungify/). In general it isn't nearly as optimal as BefunRep, but for some of the lower numbers, where hex digits and single quote characters are most effective, it can sometimes produce better results. [Answer] ## Merge branches as soon as possible If two or more code branches are merging together and they all end with the same sequence of instructions, you can merge them immediately before the instructions they have in common. This is a fairly common circumstance to be on the lookout for. As an example, I have this subprogram for reading input onto the playing field from my self-interpreter: [![Befunge program](https://i.stack.imgur.com/furPP.png)](https://i.stack.imgur.com/furPP.png) Notice that three different branches are coming together at the marked cell, each of which wants to write to the playing field. The one on the top right is `520p` to put 5 at (2,0). The top left is `00p` to put the computed value at (0,0). And on the right (and below) is `20p` to put the computed value at (2,0). Since all of these instructions end with `0p`, I save at least 4 bytes by merging the branches first and then doing `0p` afterwards. [Answer] # Use String Mode to Allow the IP to Pass Through Other Code If you need the IP to get from here to there and there's a bunch of existing and unmovable code in the way in every direction, just push a 0, go into string mode, pass through the code, come out of string mode, and pop all the garbage before continuing. This trick employed in Wim Rijnder's Wumpus here: [![IP passing through code in string mode](https://i.stack.imgur.com/zn5iQ.png)](https://i.stack.imgur.com/zn5iQ.png) (Yes, it would have been more efficient to put the quotes closer to the actual code there, but this is golf--we don't care about speed!) This trick requires you to be able to spare at most 2 cells on this side and at least 3 on the other side, but it might end up saving space in the long run if writing yourself into a corner that requires this trick ends up greatly compressing the rest of the program. (In particular it could save you from having to write in a low-code-density "lane" for the IP to travel down.) ]
[Question] [ Generate a cipher given a number and string Your task is simple. Given a string `s` and a number `0 <= n <= 9` as inputs, insert a pseudo-random printable ASCII character between each character of the string `n` times. Such that for each character of `s` there are `n` random characters between them. Spaces should be trimmed. **Input:** * string `s` phrase to encrypt in the cipher * integer `n` in the range of `0 <= n <= 9` **Example:** Input: ``` The treasure is here 2 ``` Output: > > **T**!0**h**32**e**F4**t**0i**r**lk**e**hm**a**7y**s**#0**u**\*&**r**\*h**e**!2**i**H^**s**B,**h**!@**e**0)**r**$h**e** > > > --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins! Good Luck and have fun! [Answer] # C#, ~~141~~ 131 bytes Pretty similar to [@Geobit's](https://codegolf.stackexchange.com/users/14215/geobits) [Java answer](https://codegolf.stackexchange.com/a/100732/59170), except longer currently :( ``` (I,n)=>{var R=new System.Random();var o="";int i,r;foreach(var c in I)if(c>32)for(i=r=0,o+=c;i++<n;){r=R.Next(33,127);o+=(char)r;}return o;}; ``` Full lambda stuff: ``` Func<string, int, string> a = (I,n) => { var R=new System.Random(); var o=""; int i; foreach(var c in I) if(c>32) for(i=0,o+=c;i++<n;o+=(char)R.Next(33,127)); return o; }; ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes ``` ð-vy²FžQ.RJ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w7AtdnnCskbFvlEuUko&input=VGhlIHRyZWFzdXJlIGlzIGhlcmUKMw) **Explanation** ``` ð- # remove spaces from input string v # for each char in the string y # push the char ²F # input-2 number of times do: žQ.R # push a random ascii character J # join to string ``` [Answer] ## Java 7, ~~132~~ 124 bytes ``` String f(int n,char[]a){String o="";int i;for(char b:a)if(b>32)for(i=0,o+=b;i++<n;o+=(char)(33+Math.random()*94));return o;} ``` Nothing fancy, just a double loop like you'd expect. Outer to loop the string, inner to fill in randoms: ``` String f(int n,char[]a){ String o=""; int i; for(char b:a) if(b>32) for(i=0, o+=b; i++<n; o+=(char)(33+Math.random()*94)); return o; } ``` [Answer] ## Pyke, ~~12~~ ~~11~~ 9 bytes ``` d-FQV~KHs ``` [Try it here!](http://pyke.catbus.co.uk/?code=d-FQV%7EKHs%28%3C&input=2%0AThe+treasure+is+here) ``` d- - remove spaces from input F - for i in ^: QV - repeat (number) times: ~KH - random_from(printable) s - sum(^) ``` Trailing random characters is fine according to OP. [Answer] # Octave, 43 bytes ``` @(s,n)[s(s>32);33+94*rand(n,nnz(s>32))](:)' ``` This takes a string `s` and an integer `n` as input. A string in Octave is simply an array of characters. `s>32` is a logical map with `1` for any non-space characers. The code appends a matrix with `n` rows and the same number of columns as `s(s>32)` has, containing floating point numbers between 33 and 126. It is implicitly rounded to integers and converted to ASCII-characters when it's concatenated with the string `s`. `(:)'` straightens this to a horizontal array of characters. **[Test it here!](https://ideone.com/Z9eqmt)** [Answer] # Python 2, ~~123~~ ~~122~~ ~~118~~ ~~114~~ 98 Bytes Man, I wish `random` wasn't so expensive (and that we didn't have to filter for spaces). Now we have big savings from being allowed to have cipher characters at the end :) Anyways, here ya go: ``` from random import* f=lambda s,n:s and(' '<s[0])*eval('s[0]'+'+chr(randint(32,126))'*n)+f(s[1:],n) ``` [Answer] # JavaScript (Firefox 30+), 96 bytes ``` (s,n)=>s.replace(/. */g,x=>x[0]+String.fromCharCode(...[for(_ of Array(n))Math.random()*95+32])) ``` Pure ES6 is two bytes longer: ``` (s,n)=>s.replace(/. */g,x=>x[0]+String.fromCharCode(...[...Array(n)].map(_=>Math.random()*95+32))) ``` --- Here's a really cool approach which is sadly 26 bytes longer: ``` (s,n)=>String.raw({raw:s.split` `.join``},...[for(_ of s)String.fromCharCode(...[for(_ of Array(n))Math.random()*95+32])]) ``` [Answer] ## R, 97 bytes Unnamed function taking inputs `x` (string) and `n`. ``` function(x,n,l=nchar(x))for(i in 1:l)cat(substr(x,i,i),if(i<l)intToUtf8(sample(32:126,n)),sep="") ``` [Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=M67CrzsX&version=1) [Answer] ## [CJam](http://sourceforge.net/projects/cjam/), ~~21~~ 18 bytes ``` lS-(ol~f{{95mrSc+\}*} ``` [Try it online!](http://cjam.tryitonline.net/#code=bFMtbH5me3s5NW1yU2MrfSp9&input=VGhlIHRyZWFzdXJlIGlzIGhlcmUgCjI) Prints `n` random trailing characters. ### Explanation ``` lS- e# Read line and remove spaces. l~ e# Read and evaluate another line. f{ e# For each character (passing in N)... { e# Do this N times... 95mr e# Push random integer in [0, 95). Sc+ e# Add to space character, giving a random printable ASCII character. }* } e# All characters remaining on the stack are printed implicitly e# at the end of the program. ``` [Answer] # Bash, 124 bytes Pure *bash* + *coreutils*, no control flow structures, no sub-languages, no "eval" **Golfed** ``` E() { N=${1// /};paste <(fold -1<<<$N) <(tr -cd "\\40-\\176"<\/dev\/urandom|head -c$(($2*${#N}-$2))|fold -$2)|tr -d '\t\n';} ``` **Test** ``` >E "The treasure is here" 2 TkZhf(e&Rt@FrS,edha+-sJTuh.rX@eVKi+3s<7hftey8r*/e ``` [Answer] **Q/KDB+, 39 36 34 Bytes** ``` raze{""sv(raze x;`char$40+n?87)}prior s (,/)({""sv((,/)x;`char$40+n?87)}':)s ``` ``` (,/)({""sv((,/)x;10h$40+n?87)}':)s ``` Variables in use: ``` s:"The treasure is here" n:2 ``` This uses the [prior](http://code.kx.com/wiki/Reference/prior) adverb, which applies the function to it's left between each item to the right and its predecessor. (Essentially, applies function to the left between each character on the right.) Generate n random numbers between 40 and 126 then convert them to a character equivilent: (q seems to only have characters for these) ``` `char$40+n?87 //Possible characters. ()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` Example output: ``` TVghrveVp Rpti+r0sea3a9nsIjuRXrAReJ; +di=ys`{ ikhKTe4trTZesz ``` **EDIT:** Saved 3 bytes by converting q's raze into (,/) using the k notation and similarly changed prior to `: Thanks to @slackwear for the update, shaved 2 bytes :) [Answer] # Java 8, 114 bytes ## Golfed ``` (n,s)->s.chars().forEach((c)->{if(c>32)for(int i=0;i<=n;)System.out.print((char)(++i==1?c:33+Math.random()*94));}) ``` Lambda that accepts an Integer and a String. Inspired by the Java 7 answer, double loop using some Java 8 Stream syntax (`String.chars`) to save a few bytes. ### Input ``` 3, "Hello world!" ``` ### Output ``` HfKIedb3l<-Ul%}vod"Bw\"|oa`%rH-}l/-{dMS;!B#X ``` [Answer] ## Scala, ~~95~~ 94 Bytes ``` def c(s:String,i:Int)=s.filter(_>32).mkString(scala.util.Random.alphanumeric.take(i).mkString) ``` Nothing overly fancy, besides the use of mkString on a String. It treats the string as a list of characters, and allows me to insert a separator between them. My separator is the appropriate number of randomly generated alphanumeric characters. [Answer] ## ><> (Fish), ~~107~~ ~~106~~ 103 bytes ``` <v}:{r&" " 1xv+ 2<v+ v}< <~v!?=&:&: 6.>ol2-?!;a :{{:}l1-[rv v2< <1x|!}:}-1<v!?:{{:o-+ ^3<v ~}}r]~< .40< ``` [Try it online!](https://fishlanguage.com/playground/CiTc8AhATYkuXvdAC) It isn't super random, but it is random. Just place the string and integer on the stack (Example: "Hello world!", 5). ``` Input: "Hello world!", 5 Output: H^\^]^eceeedldcdeclgfffhowhhfggojkkkkrdccedl]]\]\d ``` ## Full Explanation This is a slightly older version of the code, until I update the explanation. It's mostly the same, just maybe a bit easier to read: ``` < v}:{r&" " +1xv +2<v } :&:<~ v!?=& ?!;a6.>ol2- :{{:}l1-[rv v2< <1x|!}:}-1<v!?:{{:o+* ^3<v ~}}r]~< .43< ``` We'll pretend the string parameter is `s` and the integer parameter is `i`. ``` < v}:{r&" " ``` The `<` tells the fish to immediately move left, which wraps around to `" "`, which adds a space characted to the stack. Then the fish travels over `&`, which adds the space to the register. `r` reverses the stack and `{:}` shifts the stack to the left (putting `i` on the end of the stack), copies the value on the end of the stack, then shifts it to the right. `v` tells the fish to begin moving downwards. ``` +1xv +2<v } ``` `x` tells the fish to move in a random direction, ultimately resulting in the fish going right and continuing downwards, or pass over `1+` or `2+` beforehand. These add 1 or 2 respectively to the number on the end of the stack. If the fish travels upwards, it hits `v` again and travels back down. `}` shifts the stack to the right, then having `i` at position 1 on the stack and this new variable at position 0 (we'll call it `m`). ``` :&:<~ v!?=& ``` This section is a function, let's call it **whitespaceTrimmer**. It begins where the `<` is. It simply strips spaces that're on the end of the stack (so the beginning of the string) until it runs into a non-space character. So immediately the fish swims into a `<` and must travel to the left. It then runs into `:&:&` which copies the value on the end of the stack, places the space from the register onto the end of the stack, copies it, then places it back onto the register. Then the fish hits `=?!v ~`, or more specifically, `=`, which pops the last two values (the two we just created) off of the stack, compares them, places a 1 on the end of the stack if they're equal, and a 0 on the end of the stack if they're different. The `?` pops the new value off the end of the stack, if it is 0 it doesn't execute the next instruction, which in this case is `!`, it instead executes `v`, which orders the fish to move downwards (exiting the function). If it is 1 however, then it has found a space, so it executes the `!` which is a trampoline, and that causes the fish to skip the next instruction, which is a `v`, so the fish continues. In front of the fish, it sees `~` which tells it to pop the last value off the stack (confirmed to be a space), then the fish continues, and runs the function again. ``` ?!;a6.>ol2- ``` The fish is immediately told to swim right by a `>`, then output the last character on the stack by `o` (which, the first time this is run, is the first character of `s`). It gets the length of the stack from `l`, places a `2` on the end of the stack, then `-` causes 2 to be subtracted from `l`. It hits `?!;` which, remembering what `?` does, causes the fish to skip the `!` if the stack is empty, and land on `;`, which ends the program. Following if there are still characters on the stack, we execute `!` which causes the fish to bounce over the `;` and execute `a6.`, which stores `a` (AKA `10`), and `6` on the end of the stack, which are `x, y` coordinates for `.`, which pops them off the end of the stack, then teleports the fish to `10, 6`, and execute the instruction to the right of that postion (as the fish is swimming right). This is less complicated than it sounds when you realise `y` position 6 is the line below this one. `x` position 10 is then `v`, and to the right of that is , which is a no-op. This causes the fish to continue swimming right and actually begin execution at the beginning of the line... ``` :{{:}l1-[rv v2< <1x|!}:}-1<v!?:{{:o+* ^3<v ~}}r]~< .43< ``` So this is the function that adds the random text in between the characters. It's a bit of a mouthful, but that's just because I tried to make it a little bit extra random. Let's call this **genRandomChars**. The `:{{:}l1-[rv` is actually the setup for the function, and less-so part of the actual function itself. The fish first swims over `:{{` which copies the value on the end of the stack, then shifts it to the left twice. If you recall that `i` was at postion 1 on the stack, then you'd know `i` is now on the end of the stack. The fish then swims over `:}` which copies `i`, and shifts the stack to the right, placing `i` both at the beginning and end of the stack. `l1-[` has the fish place the length on the end of the stack, subtract 1 from it, then `[` creates a new stack, moving `l-1` (stack length minus 1) values to the new stack (so just leaving `i` on the old stack). Then the fish simply hits `rv` which reverses the stack again (I think creating a new stack reverses it for some reason), and orders the fish to swim downwards once more, truely beginning the function at the `<` below. So currently the end of the stack has `m` and our temporary `i`, which we'll call `ti`. Immediately the fish swims over `1-}`, which subtracts 1 from `ti` and moves it to the beginning of the stack. Then `:}` which simply copies `m` and moves it to the beginning of the stack (putting `ti` at stack position 1). This is when we hit this little thing: ``` v2< <1x|! ^3< ``` This is actually dead simple. The `!` causes the fish to skip `|` and execute `x`. Remembering what `x` does, we remember this makes the fish move in any 4 directions. `|` is simply a mirror, and causes the fish to swim back to `x`. So basically, the fish will place 1, 2, or 3 onto the end of the stack, and continue moving left, wrapping around. The fish then executes `*+o` which causes the last two values on the stack to be popped off, multiplied together, and the result push back on, then the same thing with addition, then the final value is popped off the stack and outputted with `o`. Our stack is now relatively normal again containing just [`m`, `ti`, `s`]. `:}}:` causes the value on the end of the stack (basically `s` position 0) ot be copied, then the stack is shifted to the right twice (placing `ti` on the front again), then `ti` is copied. `?!v` should be pretty easy to understand by now. Basically if `ti` is 0 then we exit the function with `v`, otherwise we execute `!` and skip `v` (doing another loop). If `ti` is 0 and we are done outputting slightly random characters, then we execute `v` and see: ``` v ~}}r]~< .43< ``` Nothing too fancy here. We remove `ti` from the stack via `~`. Then `]` is new, it pops all our values off the stack and places them on the old stack! Because of the reversal issue we reverse with `r`, then shift the stack right twice with `}}~`, shufting the stack to the right, giving us [`m`, `i`, `s`], the `~` is to remove the extra duplicated `s[0]` from earlier in the function as we'd need it if we were doing a loop (but we're not, we're exiting). `v` tells the fish to swim down and into `>34.` (inverted to show execution order), which tells the fish to simply swim left and into `3, 4` (because the `.` is a jump!). `3, 4` is actually just to the right of the beginning `whitespaceTrimmer`, which is perfect because we are travelling left. Following all this logic we can follow the fish until the stack is ultimately empty and program exits just after `whitespaceTrimmer` is executed. [Answer] # Perl 5, 81 bytes ``` ($_,$n)=<>;chomp;y/ //d;$\=chop;print map{$_,map{chr 33+int rand 94}1..$n}split// ``` I hope the following helps you understand what the one-liner does: ``` ($_, $n) = <STDIN>; # Reads in the string into $_, # and the number into $n, from standard input. # (<STDIN> works slightly different from <>.) chomp($_); # Removes the newline from the string. $_ =~ tr/ //d; # `Tr/`ansliterates ASCII space characters # into nothing, effectively `/d`eleting them. $\ = chop($_); # Chop()s off the last character out of $_ and # appends it to the output when print()ing. # (Perl always prints $\ after you call print().) print( map { # Each element of [List 1] will be mapped to: $_, # -- Itself, and # (When mapping, each element is available as $_.) map { # (`map` resembles `foreach` but returns a list.) chr( # -- A random ASCII character, in the range 33 + int(rand(94)) ) # from 33 (!, hex 21) to 126 (~, hex 7E) } 1..$n # ...$n times! (Over the range 1 to $n, actually.) } split(//, $_) ); # [List 1] is $_, split() into characters. ``` [Answer] ## Clojure, ~~126~~ ~~123~~ ~~118~~ ~~122~~ 117 bytes ``` (defn c[m n](apply str(remove #(=\space %)(mapcat #(apply str %(for [_(range n)](char(rand-nth(range 32 127)))))m)))) ``` Maps over the message, inserts random characters in, then concatenates the result. The instructions suggest that all spaces should be stripped from the result string. If only spaces from the original message are supposed to be stripped, I can change that. Ungolfed: ``` (defn cipher [message n] (apply str (remove #(= \space %) (mapcat #(apply str % (for [_ (range n)] (char (rand-nth (range 32 127))))) message)))) ``` [Answer] # Python 3, 127 Bytes ``` import random a,b=input(),input() print(''.join([x+''.join([chr(random.randint(33,126))for c in range(int(b))]) for x in a])) ``` Probably way longer than necessary, but this is mine golfed so far. [Answer] # PHP, 96 bytes Takes String as argument 1 and Number as argument 2 ``` for(;($s=str_replace(' ','',$argv[1]))[$j]>'';)echo$i++%($argv[2]+1)?chr(rand(33,127)):$s[$j++]; ``` [Try it online](http://sandbox.onlinephpfunctions.com/code/8457d3a90be6e22fc664d1267a1a8d30319326f2) [Answer] # Python 3, 133 Bytes ``` from random import * c=int(input()) print(''.join([i+''.join([chr(randint(33,126))for i in range(c)])for i in input().strip(' ')])[:-c]) ``` [Answer] # Node.js, 88 bytes ``` (s,n)=>s.replace(/./g,c=>c!=" "?c+crypto.randomBytes(n).toString`base64`.substr(0,n):"") ``` Example outputs: ``` f("The treasure is here", 2) // THphdwekAtMArbSeU1aDTsZWuqnr2yek1iyUsKshqXewvrVCeTi f("The treasure is here", 2) // TYshlcep6t4Iru7e29aQ1sl/uvQrlzeSJihysDhhOLe1urpte1m ``` [Try it online!](https://repl.it/E6ER/0) [Answer] # C, ~~102~~ 100 bytes -2 bytes for skipping `continue`. ``` i;f(char*s,int n){do{while(*s==32)++s;putchar(*s);i=n;while(i--)putchar(32+rand()%95);}while(*s++);} ``` Ungolfed: ``` i; f(char*s,int n){ do{ while(*s==32)++s; putchar(*s); i=n; while(i--) putchar(32+rand()%95); }while(*s++); } ``` Usage: ``` main(){ char a[]="A A A"; f(a,3); } ``` ]
[Question] [ Given the equation of a polynomial and an x-coordinate find the rate of change of the point at that x-coord on the curve. A polynomial is in the form: axn + axn-1 + ... + ax1 + a, where a ϵ Q and n ϵ W. For this challenge, n can also be 0 if you don't want to have to deal with special cases (constants) where there is no x. To find the rate of change at that x-coord, we can get the derivative of the polynomial and plug in the x-coord. ### Input The polynomial can be taken in any reasonable form, but you must state what that format is explicitly. For example, an array of the form `[..[coefficient, exponent]..]` is acceptable. ### Output The rate of change of the point at the x-coord given. ### This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. ### Examples ``` [[4, 3], [-2, 4], [5, 10]] 19 -> 16134384838410 [[0, 4]] 400 -> 0 [[4, 0], [5,1]] -13 -> 5 [[4.14, 4], [48, 2]] -3 -> -735.12 [[1, 3], [-5, 0]] 5.4 -> 87.48 ``` [Answer] # Mathematica, 6 bytes ``` #'@#2& ``` (Beat **THAT**, ~~MATL~~ and 05AB1E) The first argument must be a polynomial, with `#` as its variable and with `&` at the end (i.e. a pure function polynomial; e.g. `3 #^2 + # - 7 &`). The second argument is the x-coordinate of the point of interest. **Explanation** ``` #' ``` Take the derivative of the first argument (`1` is implied). ``` ... @#2& ``` Plug in the second argument. **Usage** ``` #'@#2&[4 #^3 - 2 #^4 + 5 #^10 &, 19] (* The first test case *) ``` > > `16134384838410` > > > [Answer] # [MATL](http://github.com/lmendo/MATL), ~~8~~ 6 bytes ``` yq^**s ``` Input is: array of exponents, number, array of coefficients. [Try it online!](http://matl.tryitonline.net/#code=eXFeKipz&input=WzMgNCAxMF0KMTkKWzQgLTIgNV0) Or verify all test cases: [1](http://matl.tryitonline.net/#code=eXFeKipz&input=WzMgNCAxMF0KMTkKWzQgLTIgNV0), [2](http://matl.tryitonline.net/#code=eXFeKipz&input=WzRdCjQwMApbMF0) [3](http://matl.tryitonline.net/#code=eXFeKipz&input=WzAgMV0KLTEzCls0IDVd), [4](http://matl.tryitonline.net/#code=eXFeKipz&input=WzQgMl0KLTMKWzQuMTQgNDhd), [5](http://matl.tryitonline.net/#code=eXFeKipz&input=WzMgMF0KLTUuNApbMSAtNV0). ### Explanation Consider example inputs `[3 4 10]`, `19`, `[4 -2 5]`. ``` y % Take first two inputs implicitly and duplicate the first % STACK: [3 4 10], 19, [3 4 10] q % Subtract 1, element-wise % STACK: [3 4 10], 19, [2 3 9] ^ % Power, element-wise % STACK: [3 4 10], [361 6859 322687697779] * % Multiply, element-wise % STACK: [1083 27436 3226876977790] * % Take third input implicitly and multiply element-wise % STACK: [4332 -54872 16134384888950] s % Sum of array % STACK: 16134384838410 ``` [Answer] # Julia, ~~45~~ ~~42~~ ~~40~~ 37 bytes ``` f(p,x)=sum(i->prod(i)x^abs(i[2]-1),p) ``` This is a function that acceps a vector of tuples and a number and returns a number. The absolute value is to ensure that the exponent isn't negative, which necessary because Julia annoying throws a `DomainError` when raising an integer to a negative exponent. [Try it online!](http://julia.tryitonline.net/#code=ZihwLHgpPXN1bShpLT5wcm9kKGkpeF5hYnMoaVsyXS0xKSxwKQoKdXNpbmcgQmFzZS5UZXN0CkB0ZXN0IGYoWyg0LCAzKSwgKC0yLCA0KSwgKDUsIDEwKV0sIDE5KSA9PSAxNjEzNDM4NDgzODQxMApAdGVzdCBmKFsoMCwgNCldLCA0MDApID09IDAKQHRlc3QgZihbKDQsIDApLCAoNSwgMSldLCAtMTMpID09IDUKQHRlc3QgZihbKDQuMTQsIDQpLCAoNDgsIDIpXSwgLTMpIOKJiCAtNzM1LjEyCkB0ZXN0IGYoWygxLCAzKSwgKC01LCAwKV0sIDUuNCkg4omIIDg3LjQ4CnByaW50bG4oIlRlc3RzIHBhc3MhIik&input=&debug=on) (includes all test cases) Thanks to Glen O for a couple of corrections and bytes. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 11 bytes Saved one byte thanks to Adnan. ``` vy¤<²smsP*O v For each [coefficient, power] in the input array y Push [coefficient, power] ¤< Compute (power-1) ² Push x value (second input entry) sms Push pow(x, power-1) P Push coefficient * power ( = coefficient of derivative) * Push coefficient * power * pow(x, power-1) O Sum everything and implicitly display the result ``` [Try it online!](http://05ab1e.tryitonline.net/#code=dnnCpDzCsnNtc1AqTw&input=W1sxLCAzXSwgWy01LCAwXV0KNS40) Floating point precision is Python's. I currently swap stack values twice, maybe there is a way to avoid it and save some bytes. [Answer] # Python 3, 41 bytes *6 bytes removed thanks to [@AndrasDeak](https://repl.it/EVVA)! In fact, this answer is now more his than mine...* *Thanks also to [@1Darco1](https://codegolf.stackexchange.com/users/36671/1darco1) for two corrections!* ``` lambda A,x:sum(a*b*x**(b-1) for a,b in A) ``` Anonymous function that accepts a list of lists with coefficients and exponents (same format as described in the challenge) and a number. [Try it here](https://repl.it/EVVA). [Answer] # R, 31 bytes ``` function(a,n,x)sum(a*n*x^(n-1)) ``` Anonymous function that takes a vector of coefficients `a`, a vector of exponents `n`, and an `x` value. [Answer] # Matlab, 27 bytes This is an anonymous function that accepts a value `x` and a polyonmial `p` in the form of a list of coefficients, e.g. `x^2 + 2` can be represented as `[1,0,2]`. ``` @(x,p)polyval(polyder(p),x) ``` [Answer] ## JavaScript (ES7), 40 bytes ``` (a,n)=>a.reduce((t,c,i)=>t+i*c*n**--i,0) ``` `a` is an array of the coefficients in ascending exponent order with zeros included e.g. *x*³-5 would be represented by `[-5, 0, 0, 1]`. [Answer] # MATLAB with Symbolic Math Toolbox, 26 bytes ``` @(p,x)subs(diff(sym(p)),x) ``` This defines an anonymous function. Inputs are: * a string `p` defining the polynomial, in the format `'4*x^3-2*x^4+5*x^10'` * a number `x` Example use: ``` >> f = @(p,x)subs(diff(sym(p)),x) f = @(p,x)subs(diff(sym(p)),x) >> f('4*x^3-2*x^4+5*x^10', 19) ans = 16134384838410 ``` [Answer] ## R, 31 27 bytes Unnamed function taking two inputs `p` and `x`. `p` is assumed to be an R-expression of the polynomial (see example below) and `x` is simply the point of evaluation. ``` function(p,x)eval(D(p,"x")) ``` It works by calling the `D` which computes the symbolic derivative w.r.t. `x` and the evaluates the expression at `x`. **Example output** Assuming that the function is now named `f` it can be called in the following way: ``` f(expression(4*x^3-2*x^4+5*x^10),19) f(expression(0*x^4),400) f(expression(4*x^0+5*x^1),-13) f(expression(4.14*x^4+48*x^2),-3) f(expression(1*x^3-5*x^0),5.4) ``` which respectively produces: ``` [1] 1.613438e+13 [1] 0 [1] 5 [1] -735.12 [1] 87.48 ``` [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr/), 20 bytes ``` a(f,n)=subst(f',x,n) ``` For example, `a(4*x^3-2*x^4+5*x^10,19)` yields `16134384838410`. [Answer] # C++14, ~~165~~ ~~138~~ ~~133~~ ~~112~~ 110 bytes Generic Variadic Lambda saves a lot. -2 bytes for `#import` and deleting the space before `<` ``` #import<cmath> #define A auto A f(A x){return 0;}A f(A x,A a,A b,A...p){return a*b*std::pow(x,b-1)+f(x,p...);} ``` Ungolfed: ``` #include <cmath> auto f(auto x){return 0;} auto f(auto x,auto a,auto b,auto...p){ return a*b*std::pow(x,b-1)+f(x,p...); } ``` Usage: ``` int main() { std::cout << f(19,4,3,-2,4,5,10) << std::endl; std::cout << f(400,0,4) << std::endl; std::cout << f(-13,4,0,5,1) << std::endl; std::cout << f(-3,4.14,4,48,2) << std::endl; std::cout << f(5.4,1,3,-5,0) << std::endl; } ``` [Answer] # Haskell, 33 bytes ``` f x=sum.map(\[c,e]->c*e*x**(e-1)) ``` Usage: ``` > f 5.4 [[1, 3], [-5, 0]] 87.48000000000002 ``` [Answer] ## dc, 31 bytes ``` ??sx0[snd1-lxr^**ln+z2<r]srlrxp ``` Usage: ``` $ dc -e "??sx0[snd1-lxr^**ln+z2<r]srlrxp" 4.14 4 48 2 _3 -735.12 ``` [Answer] # [DASH](https://github.com/molarmanful/DASH), 33 bytes ``` @@sum(->@* ^#1- :1#0 1(sS *)#0)#1 ``` Usage: ``` ( ( @@sum(->@* ^#1- :1#0 1(sS *)#0)#1 ) [[4;3];[_2;4];[5;10]] ) 19 ``` # Explanation ``` @@ #. Curried 2-arg lambda #. 1st arg -> X, 2nd arg -> Y sum #. Sum the following list: (map @ #. Map over X #. item list -> [A;B] * ^ #1 - :1#0 1(sS *)#0 #. This mess is just A*B*Y^(B-1) )#1 #. X ``` [Answer] # Scala, 46 bytes ``` s=>i=>s map{case(c,e)=>c*e*math.pow(i,e-1)}sum ``` Usage: ``` val f:(Seq[(Double,Double)]=>Double=>Double)= s=>i=>s map{case(c,e)=>c*e*math.pow(i,e-1)}sum print(f(Seq(4.0 → 3, -2.0 → 4, 5.0 → 10))(19)) ``` Explanation: ``` s=> //define an anonymous function with a parameter s returning i=> //an anonymous function taking a paramater i and returning s map{ //map each element of s: case(c,e)=> //unpack the tuple and call the values c and e c*e*math.pow(i,e-1) //calculate the value of the first derivate }sum //take the sum ``` [Answer] # Axiom 31 bytes ``` h(q,y)==eval(D(q,x),x,y)::Float ``` results ``` -> h(4*x^3-2*x^4+5*x^10, 19) 161343 84838410.0 -> h(4.14*x^4+48*x^2, -3) - 735.12 ``` [Answer] ## Python 2, 39 bytes ``` lambda p,x:sum(c*e*x**~-e for c,e in p) ``` `lambda` function takes two inputs, `p` and `x`. `p` is the polynomial, given in the example format given in the question. `x` is the x-value at which to find the rate of change. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes ``` p->x->eval(p') ``` ### Usage: ``` ? (p->x->eval(p'))(4*x^3 - 2*x^4 + 5*x^10)(19) %1 = 16134384838410 ``` [Try it online!](https://tio.run/nexus/pari-gp#TY3BCoAwDEPvfkVvtsqk1Qp60E8RPCgIIkNE/PvZgcJOCU1es8IAwbvxceNyzzv6nII/t@PCFbV4pgYc1KYKJbSmwoTSE2V/iWNIqMzJMZL8E4ROmjSsRL@P2pmprZDm8s1G2NbaSonCCw "Pari/GP – TIO Nexus") [Answer] # C, 78 bytes ``` f(int*Q,int*W,int S,int x){return Q[--S]*W[S]*pow(x,W[S]-1)+(S?f(Q,W,S,x):0);} ``` [Answer] ## Clojure, 53 bytes ``` #(apply +(for[[c e]%](apply * c e(repeat(dec e)%2)))) ``` The polynomial is expressed as a hash-map, keys being coefficients and values are exponents. [Answer] # Casio Basic, 16 bytes ``` diff(a,x)|x=b ``` Input should be the polynomial in terms of `x`. 13 bytes for the code, +3 bytes to enter `a,b` as parameters. Simply derives expression `a` in respect to `x`, then subs in `x=b`. [Answer] # Dyalog APL, ~~26~~ ~~25~~ 23 bytes ``` {a←⍺⋄+/{×/⍵×a*2⌷⍵-1}¨⍵} ``` Takes polynomial as right argument and value as left argument. [Answer] # APL(NARS), 6 chars ``` {⍵⊥⍺}∂ ``` For the input of polynom the list $$ a\_n a\_{n-1} ... a\_1 a\_0 $$ means polynom $$ a\_n X^n+a\_{n-1} X^{n-1} ... a\_1 X+a\_0 $$ ``` f←{⍵⊥⍺}∂ 5 4 f ¯13 5 5 0 0 0 0 0 ¯2 4 0 0 0 f 19 1.613438484E13 0 0 0 0 0 f 400 0 0 f 400 0 4.14 0 48 0 0 f ¯3 ¯735.12 1 0 0 ¯5 f 5.4 87.48 ``` ]
[Question] [ You are the owner of a restaurant. You are opening in a new area in Cartesia where there is only one main road, known as the y-axis. You want to place your restaurant such that you minimize the total distance from your restaurant and each of the houses in that area. **Input**: The input will be ``` n, the number of houses house1 house2 house3 ... houseN ``` where each house is a coordinate in the form `x y`. Each unit represents one kilometer. You can take input as a string or provide a function that takes the input, in whatever format you choose, as its arguments. **Output**: The y-coordinate of your restaurant (remember, it will be located on the y-axis). Actually, it will be located on the side of the road, but the difference is negligible. Essentially, if nth house is `h_n` and `D` is the distance function, then you want to find `k` such that `D(h_0, (0, k)) + D(h_1, (0, k)) + D(h_2, (0, k)) + ... + D(h_n, (0, k))` is minimized. Note that distance is calculated as though the customer travels in an exactly straight line from their house to the restaurant. That is the distance from `(x, y)` to your restaurant is `sqrt(x^2 + (y - k)^2)`. The output should be accurate to at least 2 decimal places. Output can be printed as a string or can be returned from the function. Example input/output: ``` Input: 2 5.7 3.2 8.9 8.1 Output: 5.113013698630137 ``` The total distance in this example is about `15.4003` kilometers. This is code golf -- shortest code wins. P.S. I'm also interested in a mathematical solution that isn't just brute force. It won't win the code golf but it'll get some upvotes. Here is how I did the example problem: Let point A be located at A(5.7, 3.2) and B at B(8.9, 8.1). Let the solution point at (0, k) be C. Reflect A over the y-axis to make A' at (-5.7, 3.2). The distance from A' to C is equal to the distance from A to C. Therefore, the problem can be reduced to the point C such that A'C + CB is minimized. Obviously, this would be the point C that lies on the line A'B. I don't know if this would generalize well to 3 or more points. [Answer] # C, ~~315~~ 302 bytes ``` t,i;double o,w,h,x,y,k,a,b,c;double g(N,S)double N,S[][2];{for(t=0;t<N;t++)k+=S[t][1];k/=N;for(i=0;i<9;i++){o=w=h=0;for(t=0;t<N;t++)x=S[t][0],y=S[t][1],a=y-k,c=k*k-2*k*y+x*x+y*y,o+=-a/sqrt(x*x+a*a),w+=x*x/pow(c,1.5),h+=3*x*x*a/pow(c,2.5);a=h/2;b=w-h*k;c=o-w*k+a*k*k;k=(-b+sqrt(b*b-4*a*c))/h;}return k;} ``` This is far from pretty, and it's not short either. I figured since I'm not going to win the length contest, I can try to win the (theoretical) accuracy contest! The code is probably an order of magnitude or two faster than the bruteforce solution, and relies on a bit of mathematical tomfoolery. We define a function `g(N,S)` which takes as input the number of houses, `N`, and an array of houses `S[][2]`. Here it is unraveled, with a test case: ``` t,i; double o,w,h,x,y,k,a,b,c; double g(N,S)double N,S[][2];{ /* Initially, let k hold the geometric mean of given y-values */ for(t=0;t<N;t++) k+=S[t][1]; k/=N; /* We approximate 9 times to ensure accuracy */ for(i=0;i<9;i++){ o=w=h=0; for(t=0;t<N;t++) /* Here, we are making running totals of partial derivatives */ /* o is the first, w the second, and h the third*/ x=S[t][0], y=S[t][1], a=y-k, c=k*k-2*k*y+x*x+y*y, o+=-a/sqrt(x*x+a*a), w+=x*x/pow(c,1.5), h+=3*x*x*a/pow(c,2.5); /* We now use these derivatives to find a (hopefully) closer k */ a=h/2; b=w-h*k; c=o-w*k+a*k*k; k=(-b+sqrt(b*b-4*a*c))/h; } return k; } /* Our testing code */ int main(int argc, char** argv) { double test[2][2] = { {5.7, 3.2}, {8.9, 8.1} }; printf("%.20lf\n", g(2, test)); return 0; } ``` Which outputs: ``` 5.11301369863013732697 ``` **Warning: Knowledge of some calculus may be required for a complete understanding!** So, let's talk about the math. We know the distance from our desired point `(0, k)` and a house `i`: ![Definition of D_i](https://i.stack.imgur.com/YNsyh.gif) And thus the total distance `D` from `n` houses can be defined as follows: ![Definition of D](https://i.stack.imgur.com/KZzgY.gif) What we would like to do is minimize this function by taking a derivative with respect to `k` and setting it equal to `0`. Let's try it. We know that the derivatives of `D` can be described as follows: ![Derivative of D](https://i.stack.imgur.com/5TKXH.gif) But the first partial derivative of each `Di` is pretty bad... ![Derivative 1 of Di](https://i.stack.imgur.com/nR0DE.gif) Unfortunately, even with `n == 2`, setting these derivatives to `0` and solving for `k` becomes disastrous very quickly. We need a more robust method, even if it requires some approximation. *Enter Taylor Polynomials.* If we know the value of `D(k0)` as well as all of `D`'s derivatives at `k0`, we can rewrite `D` as a Taylor Series: ![Definition by Taylor Series](https://i.stack.imgur.com/vPBs1.png) Now, this formula's got a bunch of stuff in it, and its derivatives can get pretty unwieldy, *but we now have a polynomial approximation of* `D`! Doing a little bit of calculus, we find the next two derivatives of `D` by evaluating the derivatives of `Di`, just as before: ![Derivative 2 of Di](https://i.stack.imgur.com/sYvkq.gif) ![Derivative 3 of Di](https://i.stack.imgur.com/3MXcT.gif) By truncation and evaluating the derivatives, we may now approximate `D` as a 3rd degree polynomial of the form: ![Approximate form of D](https://i.stack.imgur.com/5e4Nb.png) Where `A, B, C, D` are simply real numbers. Now *this* we can minimize. When we take a derivative and set it equal to 0, we will end up with an equation of the form: ![Approximation of D'](https://i.stack.imgur.com/Vvw7M.png) Doing the calculus and substitutions, we come up with these formulas for `a, b, and c`: ![Value of a](https://i.stack.imgur.com/76qp3.png) ![Value of b](https://i.stack.imgur.com/NCWAV.png) ![Value of c](https://i.stack.imgur.com/LXBju.png) Now our problem gives us 2 solutions given by the quadratic formula: ![Value of k](https://i.stack.imgur.com/YiJ4n.png) The entire formula for `k` would be a massive burden to write out, so we do it in pieces here and in the code. Since we know that the higher `k` will always result in the minimum distance of our approximate `D` (I have a truly marvelous proof of this, which the margin of this paper is insufficient to contain...) we do not even have to consider the smaller of the solutions. One final problem remains. For accuracy purposes, it is necessary that we begin with a `k0` that is at least in the ballpark of where we expect the answer to be. For this purpose, my code chooses the geometric mean of the y-values of every house. As a fail-safe, we repeat the entire problem again 9 times, replacing `k0` with `k` at every iteration, to ensure accuracy. I haven't done the math about how many iterations and how many derivatives are truly necessary, but I've opted to err on the side of caution until I can confirm accuracy. If you made it through that with me, thank you so much! I hope you understood, and if you spot any mistakes (of which there are likely many, I'm very tired), please let me know! [Answer] # TI-BASIC, 20 ``` fMin(sum(abs(iX-Ans)),X,~E99,E99 ``` Takes input on the homescreen of your TI-83 or 84 series calculator in this form (You can type a `2:` first, which would be ignored): ``` {5.7+3.2i,8.9+8.1i}:[program name] ``` If the houses are always less than a billion km away from the origin, E99 can be replaced with E9 for a size of 18 bytes. Were there a golfing language based on Mathematica, it could win this challenge in 10-14 bytes. [Answer] # Mathematica, 42 bytes ``` k/.Last@Minimize[Tr[Norm[#-{0,k}]&/@#],k]& ``` This is an anonymous function taking a list of pairs as the house coordinates and returning the desired y coordinate. It's a fairly straightforward implementation. We map `Norm[#-{0,k}]&` onto each house coordinate (which computes the distance to an undetermined point `{0,k}` on the y axis) and sum them all up with `Tr[...]` (for trace, which is equivalent to `Total` for 1-d lists). Then we use the convenient `Minimize` to find the minimum of this sum in `k`. This gives a result of the form `{distance, {k -> position}`, so we need `k/.Last@` to extract the `position` we're looking for. [Answer] # Pyth, 33 bytes ``` hosm.a,d,0NQcR^T3rhKSms*^T3ekQheK ``` This is the brute force solution: It orders all possible locations of the restaurant, with a resolution of .001 km, by their total distance from the houses, then selects the one with the least total distance. It takes the house locations as a list of 2 entry lists of floats on STDIN. [Demonstration.](https://pyth.herokuapp.com/?code=hosm.a%2Cd%2C0NQcR%5ET3rhKSms*%5ET3ekQheK&input=%5B%5B5.7%2C+3.2%5D%2C+%5B8.9%2C+8.1%5D%5D&debug=0) The resolution could be set anywhere from 1e-2 km to 1e-10 km at the same code length, but with exponential slowdowns in runtime. I feel like this could be golfed some more, I'll look at it again later. [Answer] # Python 2, 312 ``` from math import*;A,L,p=[map(float,raw_input().split()) for i in range(input())],lambda a:a[1],0.001 def R(m,M,s): while m<=M:yield m;m+=s m=min(A,key=L)[1];M=max(A,key=L)[1];r=(m+M)/2;s=r-m while s>p:D={y:sum([sqrt(X*X+(Y-y)**2)for X,Y in A])for y in R(r-s,r+s,s*p)};r=min(D,key=D.get);s*=p;m=r-s;M=r+s print r ``` [Answer] # R, ~~145~~ ~~143~~ 126 Lots of golfing room left on this I suspect. Pretty much a brute force method. I would like to find a nicer way to do this. I though Geometric Means might help, but alas no. ``` r=sapply(seq(min((p=matrix(scan(),nr=2))),max(p),.001),function(X,p)c(X,sum((p[1,]^2+(p[2,]-X)^2)^.5)),p);r[1,order(r[2,])[1]] ``` **Test run** ``` > r=sapply(seq(min((p=matrix(scan(),nr=2))),max(p),.001),function(X,p)c(X,sum((p[1,]^2+(p[2,]-X)^2)^.5)),p);r[1,order(r[2,])[1]] 1: 5.7 3.2 3: 8.9 8.1 5: Read 4 items [1] 5.113 > ``` As a matter of interest, if there is just two houses to consider the following will return an acceptable result. However it falls over on three. I can't take it any further at the moment, but I thought some of the brains here might be able to do something with it. ``` p=matrix(scan(),nr=2);weighted.mean(p[2,],sum(p[1,])-p[1,]) ``` [Answer] # MATLAB, 42 If it is OK to take input as ``` I=[5.7 3.2 8.9 8.1] ``` then this statement ``` fminunc(@(y)sum(hypot(I(:,1),I(:,2)-y)),0) ``` returns `5.113014445748538`. Shamelessly stealing Thomas Kwa's method, you could get it down to 30 at least: ``` I=[5.7+3.2i 8.9+8.1i]; fminunc(@(y)sum(abs(I-i*y)),0) ``` ]
[Question] [ We have a challenge to [calculate the hyperfactorial](/q/235964/39490) and one to [count the trailing zeros of the factorial](/q/79762/39490), so it seems logical to put them together and count the trailing zeros in the hyperfactorial. As a recap, the [hyperfactorial](https://en.wikipedia.org/wiki/Hyperfactorial) of a number, H(n) is simply Πiⁱ, that is, 1¹·2²·3³·4⁴·5⁵·…·nⁿ. It can be defined recursively as H(n) = nⁿH(n-1) with H(0) = 1. This is integer sequence [A002109](https://oeis.org/A002109). Your task is to write the shortest program or function that accepts a non-negative integer `n` and returns or prints the number of trailing zeros in H(`n`) when represented as a decimal number (i.e. the corresponding entry from sequence [A246839](https://oeis.org/A246839)). `n` will be in the range of integers in your language; H(`n`) might not be. That means your **program must terminate** given any non-negative `n` that's valid in your language (or 2³² if that's smaller). Some test cases: | input | output | | --- | --- | | 0 | 0 | | 4 | 0 | | 5 | 5 | | 10 | 15 | | 24 | 50 | | 25 | 100 | | 250 | 8125 | | 10000 | 12518750 | [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 38 bytes ``` f=lambda n:n and(f(m:=n//5)-m*~m//2)*5 ``` [Try it online!](https://tio.run/##DchBCsMgEEbhfU4xyxmZoLERSiAnCV1YgjRQ/4hk002vbnx8q1d@1@fE41lqa2n9xvzeI2EBReycOC8rrA0yZvPP1noxoZV64GKzMTQxRNJZCXSABnY66axBJ6d@Vh@6vlxPXtJu "Python 3.8 (pre-release) – Try It Online") ## How? Calculates the number almost directly only recursing to correct for higher powers of 5 in the base: $$\begin{align} f(n) & =\sum\_{i=5,10,...,n} i+\sum\_{i=25,50,...,n}i+\sum\_{i=125,250,...,n}i+... \\ & =5 \sum\_{i=1}^\left\lfloor\frac n 5 \right\rfloor i + 25 \sum\_{i=1}^\left\lfloor\frac n {25} \right\rfloor i + 125 \sum\_{i=1}^\left\lfloor\frac n {125} \right\rfloor i + ... \\ & = 5 \sum\_{i=1}^\left\lfloor\frac n 5 \right\rfloor i + 5 f\left(\left\lfloor\frac n 5 \right\rfloor\right) \\ & = 5 \frac{\left\lfloor\frac n 5 \right\rfloor\left(\left\lfloor\frac n 5 \right\rfloor+1\right)}2 + 5 f\left(\left\lfloor\frac n 5 \right\rfloor\right)\end{align}$$ [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` f=n=>n&&f(~-n)+g(n)*n g=n=>n%5?0:-~g(n/5) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i5PTS1No043T1M7XSNPUyuPKx0sqmpqb2ClWwcU0zfV/J@cn1ecn5Oql5OfrpGmYaCpyYUqYoIhYoohYoipzQhTn5EpFiEDLIYBgabmfwA "JavaScript (Node.js) – Try It Online") -3 bytes from Arnauld # [JavaScript (Node.js)](https://nodejs.org), 29 bytes ``` f=n=>n&&f(n=n/5|0)*5-n*~n/2*5 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i5PTS1NI882T9@0xkBTy1Q3T6suT99Iy/R/cn5ecX5Oql5OfrpGmoaBpiYXqogJhogphoghpjYjTH1GpliEDLAYBgSamv8B "JavaScript (Node.js) – Try It Online") Port of loopy walt's [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` IΣE⊕N×ι⌕⮌X⁰↨ι⁵¦⁰ ``` [Try it online!](https://tio.run/##HYpBCoMwEEWvkuUEUhDBlbsWCl0o0nqBMQ40YKJMEj3@GP2r93jf/pHtiovIwC4keGFM8MseOtzgEyyTp5BoLrzl1Gc/EYPWRo3OUwRn1NuFGb60E0eCYT1Kr4x6YrFSG32dK32vFakbeezLCQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input integer ⊕ Incremented E Map over implicit (inclusive) range ι Current value × Times ⁰ Literal integer `0` X Vectorised raise to power ι Current value ↨ Converted to base ⁵ Literal integer `5` ⮌ Reversed ⌕ Find index of ⁰ Literal integer `0` Σ Take the sum I Cast to string Implicitly print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 49 bytes ``` g(n){n=n%5?0:-~g(n/5);}f(n){n=n?f(~-n)+g(n)*n:0;} ``` [Try it online!](https://tio.run/##XVDbboMwDH3vV1hISEkJKrBF68pYH6Z9xeABhYShbaEikYaG6KePmUtRu0i27JNzTmILvxRiGEqiaacT7fJjcPDP2O44jXu1wEdFzr6m3kjb6kMQ90OlLXzllSYUug3gGQErjX3LIIEuYHDPgDMIsYqwjPgYwQjg6eNVI9uTFFYWqy6YdRgLncE@HOWYwv0Dv4hFrY0F8Z43W8xSfMhm9nDS9jVK28cXDO4wuO7vnEWt6gbI@H6lC9miLIiX8glM9SNrRS4/o7sF2K5IDJ43selkNm9g3QK6TZuYGFl8c2nwUhFLb1GJ6LqI/7JTgxRFHLcA/xkwuybVOJdlYNg6OlokYLLFuN/0w69Qn3lpBv/7Dw "C (gcc) – Try It Online") *Port of [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) [JavaScript answer](https://codegolf.stackexchange.com/a/263600/9481)* [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` f=lambda n:n and f(n-1)+g(n)*n g=lambda i:i%5<1and-~g(i/5) ``` [Try it online!](https://tio.run/##VYvLCsIwEEX3/YoBETKValPMokU/ptqHA82kJNNFN/56rItiHLhwLvfMvMrLcRXJzs4LhDVkW86hF98/Fx/I8USWROkyz2uMw31q7aNrgRuGljsYFBcaT6NizDkb95kaOpqb3oziPSq6GIyzJxY1qBIx2/masElYp1KVWpX5K1/vAL@37RChACHbB3CLxA8 "Python 2 – Try It Online") ## [Python 2](https://docs.python.org/2/), 39 bytes ``` f=lambda n:n and(f(n/5)-n/5*~(n/5)/2)*5 ``` [Try it online!](https://tio.run/##VYvBCsMgDIbvfQqPRlhrZR5W6MO4tWWBGkXTQy97dSeDgQ0kfD/5/njyO5Ap6GNILPKZu7p9XjmtryNlDLSjR5ajVuoBZZt355@LEzSRcLTITdJg4VaP@vxwMKBsiQmJ61MDdH@@N2wbHlvJtJaxl6AvpToA5Qs "Python 2 – Try It Online") Port of loopy walt's Python answer. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 30 bytes ``` n->sum(i=1,n,i*valuation(i,5)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboW-_J07YpLczUybQ118nQytcoSc0oTSzLz8zQydUw1NSGKbjonFhTkVGrkKejaKRQUZeaVAJlKII6SQppGnqamjkK0gY6CiY6CqY6CIZBlBGSaANlGpgYgASCIhRq1YAGEBgA) Based on Michel Marcus's code on the OEIS page. [Answer] # [C (gcc)](https://gcc.gnu.org/), 31 bytes *port of loopy walt's [Python answer](https://codegolf.stackexchange.com/a/263606/112488).* ``` f(n){n=n?(f(n/=5)-n*~n/2)*5:0;} ``` [Try it online!](https://tio.run/##TVDLasMwELz7KwZDQEpk/GhE07puD6VfkfgQFDkVbeVgGWpq3E@vu1ESJws77Aw7i0Yq2is1jhWzvLeFfWE0xYXkkZ3/2jjjc/mY5MNobBt8bY1lPOgDUJFA2GrXrksU6BOBpYAUSGnKaEQmPRClShOqQXgroLuDVq3eTdbkZKU@7tOywCo9HiBIV/fyajUCrYAT0LlXVG1dC/W@bQi0@tDNulwv/d1w071lm@7hlVqGArf8LhxO/qpuwAytJzkMnuDMj64rdgzG4zOZe5ZjsTAc/fkhFJ5c/gNMmU@iI5Hs/KpoUqbAt6uHhj6xYuFM7hA9Y7bDzG1seAl4iUP@Aq48XxyCYfxT1ed278bo@x8 "C (gcc) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 34 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.25 bytes ``` ɾ:5Ǒ* ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBPXMiLCIiLCLJvjo1x5EqIiwiIiwiNVxuMTBcbjI0XG4yNSJd) -7 bits thanks to emanresu ## Explained ``` ɾ:5Ǒ*­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‏​⁢⁠⁡‌­ ɾ # ‎⁡The range [1, input] : # ‎⁢Duplicated 5Ǒ # ‎⁣With the multiplicity of 5 of each number * # ‎⁤Multiply that by the original list # ‎⁢⁡The s flag sums the list 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ọ€5ḋR ``` A monadic Link that accepts a non-negative integer, \$n\$, and yields the number of trailing zeros of the hyperfactorial, \$H(n)\$. **[Try it online!](https://tio.run/##y0rNyan8///h7t5HTWtMH@7oDvr//7@hARAAAA "Jelly – Try It Online")** ### How? As the hyperfactorial's input increases, each time \$n\$ reaches a multiple of five [\$n\nu\_5(n)\$](https://en.wikipedia.org/wiki/P-adic_valuation "Wikipedia") more zeros are added. ``` ọ€5ḋR - Link: non-negative integer, n € - for each {i in [1..n]}: ọ 5 - {i} order of multiplicity of {5} R - range {n} -> [1..n] ḋ - dot-product ``` [Answer] # [Desmos](https://desmos.com/calculator), 47 bytes ``` f(k)=∑_{n=1}^knlog_5(gcd(n,5^{ceil(log_5n)})) ``` [Try It On Desmos!](https://www.desmos.com/calculator/tmk6nq0lyo) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/ijoz3m8l5y) It can be `f(k)=∑_{n=1}^knlog_5(gcd(n,5^n))` but that quickly runs into inaccuracies even for smaller inputs. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LDmTªPγθg< ``` -6 bytes thanks to *@lyxal*. Actually calculates \$H(n)\$ and counts the amount of trailing 0s, so this is a much slower approach. Still valid though, since the new 05AB1E is built in Elixir, which has an infinitely large integer and is only limited by memory (in the legacy version of 05AB1E, built in Python, it would be valid as well for the same reason). [Try it online](https://tio.run/##yy9OTMpM/f/fxyU35NCqgHObz@1It/n/38jUAAA) or [verify (almost) all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H5fckEOrAs5tPrcj3ea/zv9oAx0THVMdQwMdIxMdI1MgMtAxNTCIBQA). **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] D # Duplicate it m # Take the power of the values at the same positions: [1**1,2**2,3**3,...] Tª # Append a 10 to this list P # Take the product γ # Group adjacent equal digits together in substrings θ # Pop and keep the trailing part of 0s g # Pop and push its length < # And decrease it by 1 # (after which the result is output implicitly) ``` The `Tª` and `<` are only there for inputs in the range \$0\leq n<4\$. For \$n\geq5\$ it works fine without it. These three bytes also have loads of alternatives (i.e. [`LDmP0«γθ¦g`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H5fcAINDq89tPrfj0LL0/zr/ow10THRMdQwNdIxMdIxMgchAx9TAIBYA); [`LDmPγθgDi0`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H5fcgHObz@1Id8k0@F@r8z/aQMdEx1TH0EDHyETHyBSIDHRMDQxiAQ); [`LDmPγθgD≠*`](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H5fcgHObz@1Id3nUuUDrv87/aAMdEx1THUMDHSMTHSNTIDLQMTUwiAUA); etc.), but I've been unable to find anything shorter thus far. ### Original ~~16~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach: ``` ƒNÐ5sm¿5.n*O ``` Port of [*AidenChow*'s Desmos answer](https://codegolf.stackexchange.com/a/263619/52210), so make sure to upvote that answer as well! [Try it online](https://tio.run/##MzBNTDJM/f//2CS/wxNMi3MP7TfVy9Py///fyNQAAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/Y5P8Dk8wLc49tN9UL0/L/3@tzv9oAx0THVMdQwMdIxMdI1MgMgBygCAWAA). **Explanation:** ``` ƒ # Loop `N` in the range [0, (implicit) input-integer]: NÐ # Push three copies of `N` to the stack N 5sm # Pop one, and push 5 to the power `N` N ¿ # Pop this and another `N`, and push their Greatest Common Divisor 5.n # Take log_5 of that value N * # Multiply it by the remaining `N` O # Sum all values on the stack together # (after which the result is output implicitly) ``` 05AB1E lacks the convenient `multiplicity`-builtin that the Jelly and Vyxal answers have, ~~although I still have the feeling this can be shorter with another approach, since the `5sm` and `5.n` are rather verbose.~~ EDIT: which was indeed correct. [Answer] # Excel, 68 bytes ``` =LET(a,SEQUENCE(A1),IFERROR(SUM(N(TEXTSPLIT(PRODUCT(a^a),,0)="")),)) ``` Input in cell `A1`. Fails for `A1>7`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 47 bytes ``` .+ $*¶ $.`$*#$.`$* +%`^(#+)\1{4}\b $'¶$1 A`# 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0Xr0DYuLhW9BBUtZTDJpa2aEKehrK0ZY1htUhuTxKWifmibiiGXY4Iyl@H//wZcJlymXIYGXEYmXEamQGQAAA "Retina 0.8.2 – Try It Online") Link includes Link includes faster test cases (since it calculates in unary internally, it times out TIO after about `3000` and probably runs out of memory anyway after about `30000`). Explanation: ``` .+ $*¶ $.`$*#$.`$* ``` Generate a range from `0` up to and including the input, in duplicated unary, once using `#` and once using `1`. ``` %`^(#+)\1{4}\b $'¶$1 ``` For each entry that has a multiple of `5` `#`s, remove them leaving the `1`s, and then append an entry with the number of `#`s divided by `5`, but with the original number of `1`s. ``` +` ``` Repeatedly process any new entries that have a multiple of `5` `#`s. ``` A`# ``` Remove all entries that weren't a multiple of `5` `#`s. (If they were, the `#`s would have been removed.) ``` 1 ``` Count the number of trailing zeros. Retina 1 can do the whole calculation in decimal, allowing it to quickly compute the result for `10000`, although it does take 65 bytes: ``` .+ *¶ $.` +%`.*50*$ $.(*2* ~["L$`^¶$.("|""L$rm`0*$ $.($:&*$&)$*_ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9Pm0vr0DYuLhW9BC5t1QQ9LVMDLRUgT0PLSIurLlrJRyUh7tA2IF@pRgnIKcpNgMqrWKlpqahpqmjF//9vwGXCZcplaMBlZMJlZApEBkAOEAAA "Retina – Try It Online") Link includes test cases. Explanation: ``` .+ *¶ $.`,$.` ``` Generate a range from `0` up to and including the input. ``` +%`.*50*$ $.(*2* ``` Double any value that ends in 5, 50, 500 etc. as many times as necessary so that it does not. ``` ["L$`^¶$.("|""L$rm`0*$ $.($:&*$&)$*_ ``` Multiply each original value by the number of trailing zeros, then generate a command that calculates the sum of those products. The intermediate multiplication allows use of a capture on the right which would otherwise have to be wrapped. The match is performed right-to-left so that values with trailing zeros are only matched once but matches without trailing zeros are also matched so that the match index will give the original value. ``` ~` ``` Execute that command. [Answer] # [Scala 3](https://www.scala-lang.org/), 48 bytes Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/263606/110802) in Scala. ``` n=>{if(n<1)0 else{val m=n/5;(f(m)+m*(m+1)/2)*5}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NU_LSsNAFN3nK46li5k2pUk0ILEpuBR0Ja6ki2nNlJHMrcxMBQnzJW6yUfCT-jfemDpw3_ecc-fz2-9Uqy7708Vh-9rsAh6UIXRJAryrFrq6o1Cv2aH-Oga9uD5lVK87owWtcpmhaX3TDZu2pmV5I7Swcm5nws5zuSzkrIzxjPsBXhoNy_xCub2vcOuc-nh-DM7QfiMrPJFhGRYHRnU62m3jPPfujQ8iS5GnuEpRcsJFwWlRDjZMMn7yD6oPDoKwWvwTyDMn8MZaQfiJmFKKace_kFFiMuJiMlhMxoP7foy_) ]
[Question] [ Given as input a positive nonzero integer `n` >= 10 and a sequence of digits `0-9` (which may be taken as a string or a list), find the first contiguous subsequence of digits in the sequence that sums to `n` and output the start and end indexes. You may use zero- or one-based indexing. If no such subsequence exists, your program may output any *constant* value. ## Examples These examples use zero-based indexing. ``` Input: 10 123456789 Output: 0 3 Input: 32 444444444 Output: 0 7 Input: 15 123456789 Output: 0 4 Input: 33 444444444 Output: No solutions ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program wins! [Answer] # Excel (ms365), 155 bytes Assuming list as input and 0-indexed output: [![enter image description here](https://i.stack.imgur.com/era3A.png)](https://i.stack.imgur.com/era3A.png) Formula in `C1`: ``` =LET(x,TOCOL(B:B,1),y,COUNT(x),REDUCE("No solutions",SEQUENCE(y),LAMBDA(a,b,IFERROR(HSTACK(y-b,y-b+MATCH(A1,SCAN(0,DROP(x,y-b),LAMBDA(c,d,c+d)),0)-1),a)))) ``` The idea here is to use `SCAN()` to iterate from each element in reversed order in column B and `MATCH()` the value in `A1` against each resulting array. If found, then `HSTACK()` both the current iteration and the position the element is found. Unfortunately this process is rather verbose in Excel, but fun to attempt this challenge nonetheless. --- [![enter image description here](https://i.stack.imgur.com/f7aiC.png)](https://i.stack.imgur.com/f7aiC.png) [![enter image description here](https://i.stack.imgur.com/P6Rtn.png)](https://i.stack.imgur.com/P6Rtn.png) [![enter image description here](https://i.stack.imgur.com/rycXl.png)](https://i.stack.imgur.com/rycXl.png) [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 126 bytes ``` i01:}r[l0$>:?v~]}r4[{:}]=?v1+$:@$:@l5-$-)?v20. /[-2lr@@+@:$@/ ;n+oan:$/-3lr1;?=-2l:+1~/ \}]r1-a0. \[}]r20. ``` [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTAxOn1yW2wwJD46P3Z+XX1yNFt7On1dPT92MSskOkAkOkBsNS0kLSk/djIwLlxuL1stMmxyQEArQDokQC8gICAgO24rb2FuOiQvLTNscjE7Pz0tMmw6KzF+LyBcblxcfV1yMS1hMC4gICAgICAgICAgICAgICAgIFxcW31dcjIwLiIsImlucHV0IjoiMTEiLCJzdGFjayI6IjEsIDUsIDYiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9) ## Explanation [![enter image description here](https://i.stack.imgur.com/wBkMA.png)](https://i.stack.imgur.com/wBkMA.png) Takes the array of characters as the initial value of the stack and the target as the input over STDIN. Outputs nothing if no solution exists, and an exclusive range if it does. `i01` push the target value, the start of the range, and the length to the stack. `:}r[l0$>:` Push the top "length" elements of the stack to a new stack. Set it's length, that's the amount of elements we want to compare. `@$:@+@@rl2-]}]r1-a0.` This adds the top of the stack to the accumulator, rotates the stack, then subtract one from the number of remaining rotations necessary. `~]}` pop 0, the remaining number of rotations, and combine the stack back with the previous. Now the sum of the top N elements of the input are on top of the stack. `r4[{:}]=` Copy the target sum to the end of the input. ``` =?v \$:nao+n; ``` If the sum equals the target, output. `1+$:@$:@15-$-)?v` Add one to the length. If it's greater than the remaining length of the list go down. `~1+:l2-=?;` Add one to the starting value. If it's greater than the length of the input exit. `1rl3-[}]r` Set the length back to 1. Shift the rest of the stack over one so it starts at the second position. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ā<ã.Δ¹sŸèOQ ``` Inputs in the order `sequence, n`. 0-based output; will output `-1` if no result can be found; and `[i,i]` if `n` is a single digit that's present in the input-`sequence`. [Try it online](https://tio.run/##AScA2P9vc2FiaWX//8SBPMOjLs6UwrlzxbjDqE9R//8xMjM0NTY3ODkKMTA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6KGV/4802hxerHduyqF1xUd3HJ55eIV/ROD/Wp3/0dGGRsYmpmbmFpY6hgaxOtEmMKBjbITKNQZyEYpNYmMB). **Explanation:** ``` ā # Push a list in the range [1, length of the first (implicit) input sequence] < # Decrease each by to make it a 0-based [1,length) ã # Cartesian power of 2 to get all possible pairs of this list .Δ # Find the first pair that's truthy for: ¹ # Push the first input-sequence again s # Swap so the current pair is at the top Ÿ # Pop and push a list in the range of this pair Ù # Uniquify this list (in case the pair was [a,a]) è # Index each into the first input-sequence O # Sum these digits together Q # Check if this sum is equal to the second (implicit) input # (after which the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 11 bytes ``` ẏ:Ẋ'ƒṡ¹İ∑⁰= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJnIiwiIiwi4bqPOuG6iifGkuG5ocK5xLDiiJHigbA9IiwiIiwiMTIzNDU2Nzg5XG4xMCJd) A simple little approach. ## Explained ``` ẏ:Ẋ'ƒṡ¹İ∑⁰= ẏ: # The range [0, len(input)), twice. Ẋ # cartesian product of the two lists and sort to get the first ' # get all items of that where ƒṡ # the list turned into an inclusive range between the two numbers ¹İ # indexed into the sequence of numbers ∑⁰= # summed equals n # g flag gets the smallest pair ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 75 bytes ``` f=lambda v,l,a=0,b=1:v==(q:=sum(l[a:b]))and(a,b-1)or f(v,l,a+(q>v),b+(q<v)) ``` [Try it online!](https://tio.run/##VY7NDoIwEITvPMXGC11dExB/sLG8CPHQKkQSaGupjT491r@De9nk29mZsQ9/MboorZumVvRyUGcJgXqSIiMlch6EYFcuxtvA@lpydUSU@swkqWWOxkHL3uoFu1YBScV9CIiTb0Y/goCa5RlBmq@K9Wa7K/cpErBiFdH6Nx9U/KNj0kbzQA46DW8znoB3D25dp33MdJTCsoKUXgXq@SAtiwdyGAsm0NxPjfVf8UwbGE1/852JXobPKL7j9AQ "Python 3.8 (pre-release) – Try It Online") Switched to a list of integers instead of a string for -9 bytes old: ``` f=lambda v,l,a=0,b=1:v==(q:=sum(map(int,l[a:b])))and(a,b-1)or f(v,l,a+(q>v),b+(q<v)) ``` [Try it online!](https://tio.run/##VY7NDoIwEITvPMXGC924JCL@YGN5EeOhVYgk0JZSG3l6rH8H9zLJl5nZsZO/GV2U1s1zIzrZq6uEQB1JsSIlch6EYAMX471nvbSs1Z66k@TqjIhSX5kkleVoHDTsHVuyoQpIKuoxIM6@Hv0IAk4sXxGk@brYbHf78pAiASvWEW1@90HFPzonTSwP5KDV8C7jCXg3cevilvjTUQpZBSm9BjjEBOrHpbb@a1hoA6Pp7r41MW/4gl6u@Qk "Python 3.8 (pre-release) – Try It Online") Takes an integer and a string as input. Returns a tuple with start and end index if a solution is found, and an error if not. [Answer] # JavaScript (ES6), 64 bytes *-1 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects `(n)(array)`. Returns either `[start, end]` or *false*. ``` n=>a=>a.some((_,i)=>a.some((v,j)=>j<i||(s-=v)?0:o=[i,j],s=n))&&o ``` [Try it online!](https://tio.run/##fc5NDoIwEAXgvafoirTJCLQFQWP1Bl6AEEMQTAlSY5EVd68NEH@6cGY2L/leMk0xFLp8yHu/7tSlMrUwnTgU9nytbhXGZ5DkkwZobGr2chyxXouBHMOdEpmEJgctOkI8T5lSdVq1ld@qK64xDQnOKDDgEEEMG0gghW1OCAoCFCK@@uWcWR6Bs2@euJz/4SeFLH320lacHuXTV3T6KQU679LjKHI4ihce5@hrZs4QMy8 "JavaScript (Node.js) – Try It Online") ### Commented ``` n => // n = target sum a => // a[] = array of digits a.some((_, i) => // for each digit at index i in a[]: a.some((v, j) => // for each digit v at index j in a[]: j < i || // if j is less than i (s -= v) // or subtracting v from s ? // does not result in 0: 0 // do nothing : // else: o = [i, j], // set o = [i, j] and exit s = n // start with s = n ) // end of inner some() ) // end of outer some() && o // if successful, return o[] ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 15 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ðÊï æÈrõ xgU ¶V ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8MrvIObIcvUgeGdVILZW&input=WzEsMiwzLDQsNSw2LDcsOCw5XQoxMA) ``` ðÊï æÈrõ xgU ¶V :Implicit input of digit array U and integer V ð :0-based indices of elements of U that are truthy under Ê : Factorial ï :Cartesian product with itself æ :First element/pair that returns true when È :Passed through the following function r : Reduce by õ : Inclusive range x : Reduce by addition after gU : Indexing each into U ¶V : Is equal to V? ``` [Answer] # R 4.1, ~~78 bytes~~ ~~71 bytes~~ 65 bytes ## v1.2 65 bytes -5 bytes thanks to [pajonk](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n/256617?noredirect=1#comment577984_256617): 1. -4 for pointing out that `F <- F + 1;k <- m[, F];sum(s[k:k[2]])` can be expressed as `sum(s[(k <- m[, F <- F + 1]):k[2]])`. This also means you can lose the curly braces as the expression is on one line, and you do not need semi-colons. 2. -1 because `while(a!=b)` can actually be expressed as `while(a-b)`. This is safe as negative numbers are also `TRUE` when coerced to `logical`. (And also -1 byte by pointing out I had miscounted.) ``` \(s,n,m=combn(seq(s),2)){while(sum(s[(k=m[,F<-F+1]):k[2]])-n)0 k} ``` [Attempt This Online!]<https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6FjcdYzSKdfJ0cm2T83OT8jSKUws1ijV1jDQ1q8szMnNSNYpLczWKozWybXOjddxsdN20DWM1rbKjjWJjNXXzNA24smuhBrkpK4SkFpcoJCcWpxZzpWkYWlnqKBgaaAKZRakFGiZgjo6CsZEmXNIUQ9JYE2LaggUQGgA>) ## v 1.1 71 bytes ``` \(s,n,m=combn(seq(s),2)){while({F=F+1;k<-m[,F];sum(s[k:k[2]])!=n})0 k} ``` -7 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n#comment567896_256617) Two changes: 1. Not replacing `seq()` with the unary `-` as it's only being used once (I was using it twice before and failed to notice that was no longer the case). 2. Replacing `j` with `F` is yet another ludicrous thing that R allows you to do that I would never have tried in the vein of [these](https://codegolf.stackexchange.com/questions/4024/tips-for-golfing-in-r/162674#162674) coercion tips by @rturnbull (link from Giuseppe - thanks). For non-R uses, `T` and `F` are built-in aliases for TRUE and FALSE. This means you can do this: ``` T == TRUE # TRUE F == FALSE # TRUE F == TRUE # FALSE F <- F+1 F == FALSE # FALSE F == TRUE # TRUE ``` I have no idea why this is allowed in R but it's saved 5 characters compared with initialising `j`. ## v.1.0 78 bytes ``` \(s,n,`-`=seq,j=0,m=combn(-s,2)){while({j=j+1;k<-m[,j];sum(s[k:k[2]])!=n})0 k} ``` [Attempt this online](https://ato.pxeger.com/run?1=m72waMGSNAUb3aWlJWm6Fjf9YjSKdfJ0EnQTbItTC3WybA10cm2T83OT8jR0i3WMNDWryzMyc1I1qrNss7QNrbNtdHOjdbJirYtLczWKo7OtsqONYmM1FW3zajUNuLJroaa6KiuEpBaXKCQnFqcWc6VpGFpZ6igYGmgCmUWpBRomYI6OgrGRJlzSFC5pBZEz1oQYtmABhAYA) ### How? This is a function which expects a vector, `s` and a target value `n`, as arguments. Basically it does this: 1. Uses `combn()` to create a `m`, a matrix of all possible length 2 combinations of the indices of `s`. E.g. `combn(1:5,2)` produces: ``` [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 1 2 2 2 3 3 4 [2,] 2 3 4 5 3 4 5 4 5 5 ``` 2. Loops through the columns of this to subset `s`, using row 1 as the start index and row 2 as the end index. 3. Breaks the loop if the subset adds up to `n`. It exits with an error if there is no solution. I wasn't entirely clear if an error counts as a constant, but [this nice Python answer](https://codegolf.stackexchange.com/questions/256556/find-the-first-run-of-numbers-summing-to-n/256572#256572) behaves in the same way, which I took as a green light. 4. There are a couple of golfing tricks both from [Giuseppe](https://codegolf.stackexchange.com/a/138046/115882). Taking advantage of how `seq(s)` behaves if `s` is a vector and reassigning the unary `-` with ``-` = seq`, means we can do `m = combn(-s, 2)` instead of the positively verbose `m = combn(seq_along(s), 2)`. The test cases are included in the footer of ATO link. Only my second Code Golf answer ever so very interested in any suggestions / improvements. [Answer] # [Perl 5](https://www.perl.org/) List::Util, 82 bytes ``` sub{$s=pop;($i,$j)=($_%@_,int$_/@_),$s-sum(@_[$i..$j])||return($i,$j)for 0..@_*@_} ``` [Try it online!](https://tio.run/##XZFbT4NAEIWf5VdMmmkBs70BvQhZ3XcvfdGn2mxqC4ZKF8JCjGn718WhYGPcl8mZ75zZyW4W5smk2n9hxCtdvh1Q8yzNAgtjhjubWyi7QrJYFSiHQtoMdV@Xe0vIJcaDAe5W9vGYh0WZqzYSpTmMBgMhr4U8VYFB2jIAljAeMRg7rjeZzuY3wG@BtAsrdoauw8D7PS2cXaD7D5ZqG0YtdCjpOt547k6mbg29NmkfiAPsvyxUDJNYF7R8sc6phGprc4EyaB0gasx1lsTFcNiYg0taU8AGDj2MLNHMUXaDs5xeJoJOtz/VJDc@4Iaqoqqo1ma/GU7qc61I/dmBeu/puUXyVXWYcUXPzxsH9HqAIanaeAdm@mGCD@bT4hkW92ZgnKrvNCviVOmq//hQX@S/FHHC6Xd@AA "Perl 5 – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` KEhfqQs:KhTheT^UK2 ``` [Try it online!](https://tio.run/##K6gsyfj/39s1I60wsNjKOyMkIzUkLtTb6P9/QwOuaEMdBSMdBWMdBRMdBVMdBTMdBXMdBQsdBctYAA "Pyth – Try It Online") Takes n, sequence as separate inputs. Outputs [start, end] or an index error if no sequence exists. ### Explanation ``` # implicitly assign Q = eval(input()) KE # assign K = eval(input()) ^ 2 # cartesian product of two copies of UK # range(len(K)) f # filter this on lambda T s # sum of :KhTheT # slice K from first element of product to second element plus 1 qQ # equals Q h # take the first element (this will give us the indices if they exist or an index error if they don't) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Jṗ2r/ị³S=ʋƇḢ ``` [Try it online!](https://tio.run/##ATUAyv9qZWxsef//SuG5lzJyL@G7i8KzUz3Ki8aH4bii////WzEsMiwzLDQsNSw2LDcsOCw5Xf8xNQ "Jelly – Try It Online") Full program, that takes a list of digits and an integer \$n\$, and outputs the 1-indexed indices, or `0` if there's no solution. ## How it works ``` Jṗ2r/ị³S=ʋƇḢ - Main link. Takes a list of digits D on the left, and n on the right J - Indices; [1, 2, ..., len(D)] ṗ2 - Cartesian square ʋƇ - Filter the indices on the dyad f([i, j], n): r/ - Range; [i, i+1, ..., j-1, j] ị³ - Index into D S - Sum = - Does that equal n? Ḣ - Take the first pair, or zero if there's no solution ``` [Answer] # [C (clang)](http://clang.llvm.org/), ~~90~~ 88 bytes ``` i;j;a;f(*s,n){for(a=i=-1;s[++i]*a;)for(a=n,j=i;a*s[j];)a-=s[j++]-48;*s++=!a*i-1;*s=j-1;} ``` [Try it online!](https://tio.run/##lVJtb5swEP7eX3FFSmUMaCWkayvP@zLtW/9BQJHnHB0ZcRJM1WxR/vrYgWGhXSp1Fi/2Pc/dPXdnHelSmcemKcRKKJEzbkPjH/JNxZQsZBQLOw@CIuNK@M5owpUshOJ2vsqEryJJmyDIotmd4DYI5KXiBblxK1f0OzaFqWGtCsN8OFwArdZQo60XZp6BhEN8HUIypTc5ioHAHcM6xoMXT5PZzcfbu3svhAdvNqxXp5M/4H6LusblEIJy0BPF5yjoKEkIt8TqGXpjbA36u6o4fVH/wMrRvHT/dZru77/Qe0MCxudkkECtAtYmKcwS9@R2LfrtJ7DFL9zk7KTQhw@DkY@sAqjxrc/QuEG4oXh9Azs8E2OYw27A7TkcSoJnwIE9a1uiYTsfAoj9V0G@PeU5EdeqLDealSN4jWu9/claQgi7EMZY7szmZTTAhaVYo5mc04ULHJPwX1IOrI10KWmQ46YMEbbKtnm40y67tFdXXSnzOHMWFC/cthU55swzcrIMwcrUm5Q29SD6DK1hsoSJTQ2N2XS1cld1HzH8ezPazNmo6CNgafF9Ev9D0Fkxb2o4TaVC7AbTow6psH6qDN3Mi2PzW@elerRN9PwH "C (clang) – Try It Online") *Saved 2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to a wide charater string of the sequence and \$n\$. Returns the first and last position in the array referenced by the input pointer or \$-1\$ if no sum exists. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 25 \log\_{256}(96) \approx \$ 20.58 bytes ``` LRDZ!gAu1+:z0sAISz1=kAJ0~ ``` Takes a list of digits, then a number. Outputs 0 if it doesn't find the subsequence. #### Explanation ``` LRDZ!gAu1+:z0sAISz1=kAJ0~ # Implicit input LR # range(len(input)) DZ! # Cartesian product with itself g k # Filter for items where the following is truthy: Au # Dump the pair onto the stack 1+ # Add one to the last one (because of how Thunno's range works) : # Range between the two numbers sAI # Indexed into z0 # The first input (this will return a list) S # The sum of this list z1= # Equals the second input? AJ # After the filter, get the first item of the list 0~ # If the list was empty, push 0 ``` #### Screenshots [![Screenshot 1](https://i.stack.imgur.com/1edRmm.png)](https://i.stack.imgur.com/1edRm.png) [![Screenshot 2](https://i.stack.imgur.com/u5efjm.png)](https://i.stack.imgur.com/u5efj.png) [Answer] # [Desmos](https://desmos.com/calculator), 79 bytes ``` L=[1...l.length] T=[0^{(l[I...E].total-s)^2}(I,E)forE=L,I=L] f(s,l)=T[T.x>0][1] ``` \$f\$ returns a point `(I,E)` that has the starting index `I` and the ending index `E` as the \$x\$ and \$y\$ coordinates, respectively, and returns the answer one-indexed. For no solution, \$f\$ returns the point `(undefined,undefined)`. Note that because of the limitations of Desmos, this will not work for input lists longer than \$100\$ elements. [Try It On Desmos!](https://www.desmos.com/calculator/3cyneucbqz) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dmv2bd8yol) [Answer] # [C (clang)](http://clang.llvm.org/), 76 bytes Takes a list of digits and a number as input and returns \$[start, end)\$. ``` i;j;f(*l,s,n){for(i=j=0;n<0|s/~j*n;)n-=n>0?l[j++]:-l[i++];l[1]=j;*l=n?-1:i;} ``` ## How it works ``` i;j; // start and end of the sliding window, respectively. f(*l, s, n) { // input a list of integers, its size and the number. for( // main loop i = j = 0; // start with i = 0 and j = 0 (empty window) n < 0 | // the sum of elements in the window exceeds n, we will remove elements in the next iteration s / ~j * n;) // j < l and the sum of elements does not match n n -= // subtract from n: n > 0 ? // if n > 0 ... l[j++] // increase the window size. : // else (n < 0) ... -l[i++] // decrease the window size. ; // end main loop l[1] = j; // l doubles as return placeholder. l[1] is the end of the window. *l = // l[0] is: n ? // if n != 0 ... -1 // there was no solution, set it to -1. : // else (n == 0) ... i; // we found the solution, set it to the start of the window. } ``` [Try it online!](https://tio.run/##hVJNb5tAED2bXzGiSgR4acDGie01yaHqoVKkHnvAqHJgScbdLBYLjVXX/elxd/lwoZXSkZZh5s28fTOQuAnfiMfTCemWZpbDiSTCPmR5YWG4DT0qVt5PefVr6whqCzcUt94dj7bjcbx0eYTKUx75cbilDg/FnesvkR5P71AkvEoZrGSZYv7@6dYYpDg@DHMvydOm0CkDRWk8b1BY33NMbeNggLIkF7IEXQNO986Sb6yIYgjhAOZ6/3Gy3i8@qDMzySCemnCkNYuidkomy6@yaTNG96Y/mQaz65v5wiQ6DDprwrfRxfzmehZMJ755VHHNLBSzNi3K9whMJwT8mfJT5T3QdWy/Y0nJ0k4FgKrrjusrPxvWsa4uUNhc423doq5DApyAIOA8VFlGjXpU9f3AQtXmUUBYgcQfLM@gmR6uurhdB4XxGG1odq1NqM52HozpOa0vUMhLItNqZ7WrxNimxmhXqO1mlvlJ7KpyCRcpXHC5FmatTPfZf2hqcbwRp6GIx1oBt43RqI3BDSGY91osDTST9pgwA6u3T4zVqJ59hrV1wj5X5VlZI8xpKLs/yWmmC2FAGPduY1yy/3CTf/nrifyYDDpbe/tuuLzsugcY@0tXVjBm9XZ8rJ8FK6tCqB0bx9NrkvHNozy5X0Tu4vOOY4Llbw "C (clang) – Try It Online") [Answer] # [Julia](https://julialang.org), ~~69~~ ~~65~~ 47 bytes ``` ~=:;y^x=argmax(k->sum(x[k])==y,(q=keys(x)).~q') ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjf162ytrCvjKmwTi9JzEys0snXtiktzNSqis2M1bW0rdTQKbbNTK4s1KjQ19eoK1TWh2mY6FGfklyvEaRga6ChEG-oY6RjrmOiY6pjpmOtY6FjGanLBFBgbARWY6KBBJAWGpoRMMMZhAheKIwyAmk1joQ6E-Q8A) Uses 1-based indexing. Prints the range `1:1` if no solution exists. * -4 bytes thanks to MarcMush: Replace `1:length(x)` with `keys(x)` * -18 bytes (!!) thanks to MarcMush: Improve range generation [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` NθI⌊ΦEη⟦κ⌕EηΣ✂ηκ⊕μ¹θ⟧⊕↨ι⁰ ``` [Try it online!](https://tio.run/##VYqxCsIwFEV3vyLjexDBqFVLN4VCh4rQURxiGujDJLZp4u/HKDh4hwOHc9UgvXpKk1LjxhjO0d61hwmrxcWTC3CSc4CWHNlooSYTcm3lCANn1wdnNbn@511@dIaU/khujVNeW@2C7sEiZwIxc8Ib/rejnDUQZyv8rkpJFEysN9titz@Uafkybw "Charcoal – Try It Online") Link is to verbose version of code. Outputs `None` if there is no solution. Explanation: ``` Nθ First input as a number η Second input E Map over digits κ Current index η Second input E Map over digits η Second input ✂ ¹ Sliced from κ Outer index to μ Inner index ⊕ Incremented Σ Take the sum ⌕ Find index of θ First input ⟦ ⟧ Make into list Φ Filtered where ↨ι⁰ Last element ⊕ Is not `-1` ⌊ Take the minimum (first if it exists) I Cast to string Implicitly print ``` [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 69 bytes ``` [| n s | s length iota 2 [ last2 s subseq Σ n = ] find-combination ] ``` [Try it online!](https://tio.run/##hVDLTgMxDLz3K@YHGtHdlqfgirhwQZyqHtzUaaNmk5B4D6jdr@F/@KXFqCAOCGHLcxiPRxo7spLK@Pz08Hh/jY5kZ2zq1j6S0t5WVH7pOVqu2HOJHJALi7zm4qOc9H30Nm0YIVkKFXqefeBipDCbXFKmLYlP0eg6TNk5tgKqNan7zeQwgdYBs7NPQIMWcyxwjgtc4goDhi9B2yjMf/WPYLb4z6H902EYl0dEVBx1Aset7OCTkLotEahKo3zt1/oNvL@p8hYrOB830@9vaUCsRncKdtdRRhWyezN@AA "Factor – Try It Online") Returns a 0-based start index and 1-based end index. Returns `f` if there is no solution. [Answer] ## C99: ``` int main() { int x = 22; int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}, n = sizeof(a) / sizeof(int); int i = 0, j = 0, s = 0; while ((s < x && j < n) || (s > x && i < n)) s += s < x ? a[j++] : -a[i++]; printf("found: %d, i: %d, j: %d", s == x, i, j - 1); return 0; } ``` The algorithm actually takes 66 bytes: ``` inti=0,j=0,s=0;while((s<x&&j<n)||(s>x&&i<n))s+=s<x?a[j++]:-a[i++]; ``` [Try it!](https://tio.run/##PY7bbsJADETf@YoRVdGu4rQQeuES4EMQD1EuxRHdVNlERQW@PfXutvhl7NHYPnn8kefDA5v81BclUtsV3DwdtwObDp8ZG6VxGUHKGWdskCTr@5ztD@JcZoSEMCe8EF4Jb4R3woKwvBGMBCz/lE2lMo3n/162dbhzP8aSnBLqINZJSHwf@VRCKYtUCCYTiaQwGtcrxNsGj72n/YIri0ge@42dcNZRdMAKcbZn6dYjn/tq5W@lxlXTm2KFx4LAQWonY0@xwVlsxxVj9sfcll3fGsd3G4Zf) [Answer] # [Haskell](https://www.haskell.org/), 71 bytes ``` x#y=take 1[[s,e]|i<-[[0..length x-1]],s<-i,e<-i,sum[x!!i|i<-[s..e]]==y] ``` [Try it online!](https://tio.run/##HcrRCsIgFADQX3FbDw5UctVLzC@R@yB0SZm6sWvkoH836uU8He9owRhbq8NhiluQaWtJIHzCLK09KxUxP4tnVWoAQbMMAn/QK9nadeH/SCkEMOaAllzIZttDLqfkNr6jeyh@7/tx5OTXN9PT5XobBz21Lw "Haskell – Try It Online") # [Haskell](https://www.haskell.org/), 77 bytes ``` x#y=take 1[[s,e]|let m=length x-1,s<-[0..m],e<-[s..m],sum[x!!i|i<-[s..e]]==y] ``` [Try it online!](https://tio.run/##JcjdCsIgFADgV3FbFwpOsh@CyCcRLw50SJna2DFysHe3qLuPzwNNGGNrdVhNgQmZtpYkui1iYclEzI/iWR21pNto90olJ/Er@oleydauC1v4FzpnzOpagpDNvIRcdglmviDcFb/2vRCc/PPN9OF4Oovh0j4 "Haskell – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~58~~ 56 bytes Returns `nil` if no subsequence is found. -2 bytes thanks to [Value Ink](https://codegolf.stackexchange.com/users/52194/value-ink) ``` ->n,a{(b=*0...a.size).product(b).find{a[_1.._2].sum==n}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3LXTt8nQSqzWSbLUM9PT0EvWKM6tSNfUKivJTSpNLNJI09dIy81KqE6PjDfX04o1i9YpLc21t82profp7ChTcog0NdBSiDXWMdIx1THRMdcx0zHUsdCxjY7lAksZGQEkTHTQIlTQ0xaPT0BBdEmakMXYjIW5asABCAwA) [Answer] # [Arturo](https://arturo-lang.io), 79 bytes ``` $[n,a][l:-size a 1loop 0..l'x[loop x..l'y[if n=sum slice a x y->return[x,y]]]0] ``` [Try it](http://arturo-lang.io/playground?YqZrIB) Returns `[start end+1]` or `0` if there's no solution. [Answer] # [Scala](https://www.scala-lang.org/), 91 bytes Golfed version. [Try it online!](https://tio.run/##PY5Ba8MwDIXv/hWiJ5sZQ7rtEnBhsMsOPZWdSihqaqcejtvZymCM/vZMzsp0ENKT3scrPUacL8cP1xNsMST4EUJ8YQTfypec8Xv/lqjT3JTd7NznXvKooe4d2Fmirgc0IZ1C74rxEWmLV1nsRhaYEoUIaKJLA52V8SGSy9JVR4lskEW7h0aZMo3WkjIjW1k7KKVmgJPzMHIoiXkoLfzl2VEOaehUC@8pEFhODFw1c5rGo8uFtVWzfnx6Xi28g8HyGobAeLosjH8DMdhVRrNetCujKSbp5R2l7y9K8f0mxG3@BQ) ``` (a,t)=>a.indices.flatMap(s=>(s until a.length).filter(e=>a.slice(s,e+1).sum==t).map((s,_))) ``` Ungolfed version. [Try it online!](https://tio.run/##VVA9a8MwEN3zK45MEnUFTtvF1EMgS4dOplMwRbZlVUWWU@lcCMW/3b0ocmi16O7eB/cutNLKZRmbT9UivErj4GezAehUD71xXTU10nt5Doy@AvaX@vjisM4ApdcKC6COF1CpryOjMot9DSX5AL1@9KkCCCRBeL4H8hJkbloVEqRcdwGujMmhsZFkldP4kTimj7NgScciM4u6O8i5CNMAZZmWioIZzkbZDv5QOQHzGm@gsJRKhzVWhd44XVOYN2fwluBbWnDT0CgfaLbNdw@PT1sxyBN7FzIcjDbIBY7R4ya47kH8fBdnJ7JG69j/mybb9ZY87Tcvyy8) ``` object Main { def findSubarrays(arr: Array[Int], target: Int): Seq[(Int, Int)] = { for { start <- arr.indices end <- start until arr.length if arr.slice(start, end + 1).sum == target } yield (start, end) } def main(args: Array[String]): Unit = { val numbers = "12345".map(_.asDigit).toArray val target = 12 println(findSubarrays(numbers, target)) } } ``` ]
[Question] [ Mr. William Shakespeare wrote plays. A lot of plays. In this [tarball](https://web.archive.org/web/20121019174006/http://sydney.edu.au/engineering/it/%7Ematty/Shakespeare/shakespeare.tar.gz) containing every single one of his works, each one of his plays is one long file. It needs to be split into Scenes for a stage production. Because actors are impatient, your code needs to be as short as possible. ## Task: Your task is to write a program or function to split the plays contained in [this file](https://web.archive.org/web/20121019174006/http://sydney.edu.au/engineering/it/%7Ematty/Shakespeare/shakespeare.tar.gz) into separate files, numbered sequentially starting from `1`, where each one contains a scene. You should retain all whitespace and titles. ### Input: Input will be a single play via `stdin`, or the filename as a parameter. You can choose. The play will look something like: ``` TITUS ANDRONICUS DRAMATIS PERSONAE SATURNINUS son to the late Emperor of Rome, and afterwards declared Emperor. BASSIANUS brother to Saturninus; in love with Lavinia. TITUS ANDRONICUS a noble Roman, general against the Goths. MARCUS ANDRONICUS tribune of the people, and brother to Titus. LUCIUS | | QUINTUS | | sons to Titus Andronicus. MARTIUS | | MUTIUS | Young LUCIUS a boy, [...] ACT I SCENE I Rome. Before the Capitol. [The Tomb of the ANDRONICI appearing; the Tribunes and Senators aloft. Enter, below, from one side, SATURNINUS and his Followers; and, from the other side, BASSIANUS and his Followers; with drum and colours] SATURNINUS Noble patricians [...] ACT I SCENE II A forest near Rome. Horns and cry of hounds heard. [Enter TITUS ANDRONICUS, with Hunters, &c., MARCUS, LUCIUS, QUINTUS, and MARTIUS] TITUS ANDRONICUS The hunt is up, the morn is bright and grey, The fields are [...] ACT II SCENE I Rome. Before the Palace. [Enter AARON] AARON Now climbeth Tamora [...] ``` ### Output: The output should look something like this: ``` ACT I SCENE I Rome. Before the Capitol. [The Tomb of the ANDRONICI appearing; the Tribunes and Senators aloft. Enter, below, from one side, SATURNINUS and his Followers; and, from the other side, BASSIANUS and his Followers; with drum and colours] SATURNINUS Noble patricians... ``` ``` ACT I SCENE II A forest near Rome. Horns and cry of hounds heard. [Enter TITUS ANDRONICUS, with Hunters, &c., MARCUS, LUCIUS, QUINTUS, and MARTIUS] TITUS ANDRONICUS The hunt is up, the morn is bright and grey, The fields are... ``` ``` ACT II SCENE I Rome. Before the Palace. [Enter AARON] AARON Now climbeth Tamora ... ``` etc. Output either into numbered files, or to the `stdout` stream (returning for functions) with a deliminator of your choice. ## Bonuses: * 10% If you save the bit before Act 1 into file `0`. Note: It must not break if the bit before Act 1 is empty. * 15% If you can take both `stdin` and a file path parameter inputs * 20% If you can output both into files and to `stdout` / return. * ~~**200 reputation** if you can make the smallest SPL program.~~ This bounty has been awarded. ## [Leaderboards](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet) Here is a [Stack Snippet](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet) to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table><script>var QUESTION_ID=68997,OVERRIDE_USER=43394;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d\.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;</script> ``` [Answer] ## [Shakespeare Programming Language 1.2.1](http://shakespearelang.sourceforge.net/), ~~930~~ ~~895~~ 887 - 10% = 798.3 bytes ``` G.Ajax,a.Puck,a.Page,a.Ford,a.Act I:a.Scene I:a.[Enter Ajax and Puck]Puck:Open thy mind.Ajax:Open thy mind.[Exit Puck][Enter Page]Ajax:Open thy mind.SCENE II:b.[Exeunt][Enter Puck and Ajax]Ajax:Am I as fat as the sum of the cube of a big big cat and a cat?Puck:If not,let us return to scene III.Am I as fat as the sum of you and a big cat?[Exit Puck][Enter Page]Page:If not,let us return to scene III.Am I as fat as the sum of the sum of the cube of a big big cat and a big big big big cat and a big big cat?[Exit Page][Enter Ford]Ajax:If not,let us return to scene III.You is a big big big big big big cat.Speak thy mind.Scene III:c.[Exeunt][Enter Ajax and Puck]Puck:Speak thy mind.You is as fat as I.[Exit Ajax][Enter Page]Page:You is as fat as I.Puck:Open thy mind.Is you as fat as a hog?[Exit Page][Enter Ajax]Puck:If not,let us return to Scene II.Speak thy mind.Ajax:Speak thy mind. ``` Ungolfed and rewritten in Sharkspearean language: ``` Four Gentlemen of Verona. Ajax, a master code-golfer with years of experience. Puck, a young Java programmer and a strong believer in object-oriented design patterns. Page, a rapscallion of ill repute. Ford, a car manufacturer. Act I: A one-act masterpiece. Scene I: In which many minds are opened, possibly via the consumption of psychadelic drugs. [Enter Ajax and Puck] Puck: Open thy mind. Ajax: Open thy mind. [Exit Puck] [Enter Page] Ajax: Open thy mind. SCENE II: In which things are compared. [Exeunt] [Enter Puck and Ajax] Ajax: Am I as hairy as the sum of the cube of a furry purple chihuahua and a summer's day? Puck: If not, let us proceed to scene III. Am I as half-witted as the sum of you and a cunning squirrel? [Exit Puck] [Enter Page] Page: If not,let us proceed to scene III. Am I as delicious as the sum of the sum of the cube of a warm healthy hamster and a proud handsome charming noble nose and a big old aunt? [Exit Page] [Enter Ford] Ajax: If not, let us proceed to scene III. You are the cube of a tiny small pony. Speak thy mind. Scene III: In which minds are spoken. [Exeunt] [Enter Ajax and Puck] Puck: Speak thy mind. You are as smelly as I. [Exit Ajax] [Enter Page] Page: You are as oozing as I. Puck: Open thy mind. Are you as disgusting as a Microsoft? [Exit Page] [Enter Ajax] Puck: If not,let us return to Scene II. Speak thy mind. Ajax:Speak thy mind. ``` In C-like psuedocode: ``` Scene_I: Ajax = getchar() Puck = getchar() Page = getchar() Scene_II: if(Ajax != 'A') goto Scene_III if(Puck != 'C') goto Scene_III if(Page != 'T') goto Scene_III Ford = '@' putchar(Ford) Scene_III: putchar(Ajax) Ajax = Puck Puck = Page Page = getchar() if(Page != -1) goto Scene_II putchar(Ajax) putchar(Puck) ``` Requires the input file contains at least 3 characters. Uses "@" as a delimiter and reports results to stdout. I'm taking the 10% bonus since the part before the first scene will be before the first "@", much like Martin Büttner's solution above. The way it works is to put a "@" if it sees three characters "ACT" in a row. Note this means it would transform "ENACTED" into "EN@ACTED". This can be fixed at the cost of a few hundred bytes, but luckily it seems every "ACT" in the given plays (at least the few I checked) was the beginning of a scene. Tested with the 1.2.1 SPL linked above. I'm not sure if it will work on the web interpreter. The script used for testing was: ``` #!/bin/bash set -e SCRIPT_DIR=`dirname "$0"` cd "$SCRIPT_DIR" spl/bin/spl2c <splits.spl >splits.c gcc -O2 -Wall -Wno-unused -I./spl/include -L./spl/lib -lm -lspl -o splits splits.c ./splits <measureforemeasure >measure.split.txt ``` The "esoteric" parts of the SPL once you get past the syntax are the shuffling of variables on "stage" (generally, you only want to have two characters on stage at a time) and the representation of constant numbers. There are 6 word lists of import that come with the distribution: positive adjectives, neutral adjectives, negative adjectives, positive nouns, neutral nouns, and negative nouns. A positive/neutral noun (ie plum or stone wall) is 1, and a negative noun (ie flirt-gill or Microsoft) is -1. Positive/neutral adjectives (ie embroidered or bottomless) multiply the number by 2, and negative adjectives (ie fat-kidneyed or fatherless) multiply by -2. The word lists are sadly rather limited, with only 10-20 entries each. At my next meeting, I'll be suggesting we move all our production code to Shakespeare because it's far more expressive than Scala. [Answer] ## [Retina](https://github.com/mbuettner/retina), 9 - 10% = 8.1 bytes Byte count assumes ISO 8859-1 encoding. ``` ¶ACT =$0 ``` Inserts a `=` (as a delimiter) in front of every `ACT` that is preceded by a linefeed and followed by a space. [Try it online!](http://retina.tryitonline.net/#code=wrZBQ1QgCj0kMA&input=) (But you'll have to copy in the input yourself due to its size.) [Answer] # awk, 51 \* .9 \* .85 \* .8 = 31.2 Splits into multiple files. Outputs on `stdout` separated by a `=`. ``` /^ACT/{f++;$0="="$0}{system("echo \""$0"\">>"f*1)}1 ``` [Answer] # JavaScript ES6, 28 - 10% = 25.2 bytes ``` s=>s.replace(/\nACT/g,"=$&") ``` Not even the JS shell has file I/O so this can't qualify for the -20% bonus [Try it online here](http://vihanserver.tk/p/esfiddle/?code=f%3D%20s%3D%3Es.replace(%2F%5CnACT%2Fg%2C%22%3D%24%26%22)%3B%0A%0Af(%22%3CINPUT%20HERE%3E%22)) (you'll have to paste the input in yourself) [Answer] ## Perl, 66 - 10% - 20% = 47.52 bytes ``` BEGIN{open(S,">0");}++$?,open(S,">$?"),print"=\n"if/^ACT/;print S ``` Added one for the `-p` option. [Answer] # Ruby, 30 - 10% - 15% = ~~23.715~~ 22.95 bytes Splits input on `$`. 15% bonus applies because Ruby redirects `$<` to point at the file passed into `ARGV` by default if it's supplied, or `STDIN` if not. -1 byte by leveraging `gsub` similar to @Downgoat ES6 solution but I'm still leveraging the hope that `ACT` only ever appears at the ACT labels and not inside any other word, just because ``` $><<$<.read.gsub("ACT","$ACT") ``` Also, my **41.004** (originally 67) byte solution that also does file output. Starring probably the only time the `each` command saves bytes over `map` in Ruby, because `each` returns the array passed in unadulterated after running its block, unlike `map`. ``` i=-1;$><<$<.read.split(/(?=ACT)/).each{|s|open("#{i+=1}",?w)<<s}*?$ ``` ]
[Question] [ This challenge is to golf an implementation of SKI formal combinator calculus. # Definition ## Terms `S`, `K`, and `I` are terms. If *x* and *y* are terms then `(xy)` is a term. ## Evaluation The following three steps will be repeated until none of them apply. In these, x, y, and z must be terms. `(Ix)` will be replaced by `x` `((Kx)y)` will be replaced by `x` `(((Sx)y)z)` will be replaced by `((xz)(yz))` # Input A string or array, you do not have to parse the strings in the program. The input is assumed to be a term. If the simplification does not terminate, the program should not terminate. # Examples `(((SI)I)K)` should evaluate to `(KK)` (`(((SI)I)K)` > `((IK)(IK))` > `(K(IK))` > `(KK)`) The evaluation order is up to you. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest program in bytes wins. [Answer] # [Seed](https://github.com/TryItOnline/seed), ~~5925~~ ~~5909~~ ~~5890~~ 5871 bytes ``` 112 15005947709794001551745957934844387741963949195277224222942941175436326514584950738591687605839219554765312673139412565708303623220949435523970322376797353146959745711905510018709836078812043106050834210308953675588904375331147958460963516014023707270232815615580191475313492822637836797632954281710946191499605228074932238550384395938117947060215994891322895044239528628512342238908241756883576002309136458318426853695392342134155539648665540277527361486373315204318620925711966035942972301024071758707541614676997726343666069365960926312389921620411476834005712809293274727572041778318193400305675046336765396855687333907497840274069746276373367369703580554409090562378751245676511475863473197371503596617476237367564859524783860932491719480838743775854752937582631478472858805293525550579186499439467601324049079649702705638149237726903715713198300458483396210318594205002535699020033101313998794049241761482893215545820063264328229881143576843458089686528082309939218920676760397200190753211539050612871378253300234981486827195149285993539318712648895148239989077967469145906695695725639268359301194662154392742578020810701834214158736314590623136502888397978749532810617946493901929092720143858186563905545327303571180219726465764878181781793186557115346627825930278330900621009385247050349799814637325838873386273620292889508639528760077557546022550893317195975075676364661558122052118325128379943533068090012220829021399689156629396236283055797200153622175538248583908589003663439918426202812570956934037616313978141038436250235826227599001867803787753289942830662970049826887648134355967676874394598303565162564098091962321618997451086001894320616183844450949745111961097935961422054551097993708497261609312619851867552774875820025258452120004909524068566821412865560838149303210060349938961761533503092020673002416898086436041943447125182745611224019177109739446600864677559430466121929945756146084077508406141217714924746215384101090025498044684775465393706427360635410805944030744216263012281416728398396416831795019051695841375796012411932982781478577883259595757903277557013560339885004421095676988158159396051716905851695868846217163033650855582743560777135998979147462531018626808123024651044752899172971002767697839239729810707234489951369936874749971224648800779627289820691653942304035510887312581099887291489063786961615815819042632926041887143023442493367191018860931124256737065291117513395597390330436919578761534024220110023138771538795599121937519406552355650683399790256516607065531496732816853693448215404786400970519966206258869445999493937332453168572772112997760870010241144983948646532970556412494478470874278789858188343190563017173944011190771623840595351509754982449024750394701519531006485472627145366830956667859501091417380696397464590991791308983349002274205858210760481683412352685066760822807899782234565255719233842430215301267239587428773746177871165689901600646208417243654576703937071967370788826253003884731359674397195313538272303293175867053889097207394492875065268350307339622671904542995950940807603665603392360313488803906413379430184051083670651885004729854473727892899327473728338289015477022005098264171173287148216655347470405522687318205669926969047603404427022940081372422043277056357622857655043121570602934088962243851150034231358205417695570313960867608351649616601597171103712920006771227684820533564475176054040787432340472274329195572428023594055583381411302879259043579364074516131781566192239762614111449269891788954603213847889168431350014116352332568495719218713235740892206829549462198325993188837102069283539752183758065423840683800603399859637684399037099221818564860203439420354868316030912624198686770619813926501773589831388435439912756367101921385867304769841318242527202174699712749989890549100618766195763093033777895223312002305430160001275541120625668816562872370554533240740711308545492566622447387847129184675258840061167986941835187326795163219815464893135818120045226688158342762111189020715287040929632731150621861797218443116943858771703314057252808040194719272221568604757655663698552989990229004273536247930781680140083595248339872510398208349681626516323634002414520180187717671833484137244164128541147709523893558998899056288656978386170358563298472726263463417577850405538930616250768204180320433714120300698104642831290348733321737432889366924916049752215841193779080800636674778497915959708337417182273764342346866774775653756058911256185185873508680869141984524483214089280934429062520714358784586525050484207441645220993262882342756100509032546437508737632994769953343557031259340876734256731175957719696115684088124816754110816835876004771979087627144264947341007701385546122301660045006701955256463852124008422794869017906021119668922855196994038408121927354830095485511684485897883093363153061118792730884544102569938337293922496429629026756031491789824151232745788879429878141955008264934544729922641571626500646801646006325177424332041649880615834179528840475135442387961477263271755349703111900050322015750046110520113769061873773224255260567367037977307039933923712455102299122383393934719598954896540671632062855631877929121978543395229931810235373538276109853789473509980161486544938872377251787271170167749722788024574615673100600339991716767083485020637569393181718479956878303006973117799848008281819831255077962986793387572680394422233339861138992427628320726864707782719207666267011154525035418875867304015403972370212699575463083434809323275089626152829749877006988525385406485549790996313807504116069326092250060019527246837345192885824159103450484754359747938657719239950929657439192593009675109091074171048468653400294437717256292360536782184532950229108298749236074423546534432582236295463728400904674225389451924335046169486189781521045046285871978796304537708669530610470217951827243335780340661190275411840673425107286839355369264896654238856744240956275 ``` [Try it online!](https://tio.run/##LZhLcmQ3DASv4qW04w8EcQYvdQXPCXz/kDPRjpnQaLrfI0GgqlDgv3/@/PP7O@f6a8YYUSdzVNYZY0bMPFGRtc87Z7/MM@vuOjUrVuZaZ61Vh79zZpx997oxT7xTMXK/qHlf3hFv1@KdOHljz3VzT5aZK27keHvsu/Zag5XPjli7cvD/nTcrN2@cW1EEk3PWIC6ie8T59h353lzj7DnYh7XOmmOPV7FvRrxXfJex95wni8ju4Agx75hnsMPIlfy73ozLid@YxYNsuU@tt9bdyS6EwdkqDs/lJM7rY1VsudYbecpwX8TY72xi3Y@MkEyCWjOqzqvJI4Q1zuF8sd5dL@YiXl6s8dYhhfe9HSSMiAYvXFK55zvrPo7DkcrnCY1I@c89716SOqgF9dh38sFOzhqdEbYYtTpp944dVipZeY51RrIdOaRsk/du3ioqejdV5OFb@wbHKz6ZBkj9WO2YxUuSgUpOTl6Lk@chiZF@nWnAs3xij6AE49xNAq/xkiDwsPcuU5bPyA975bkrO3KQcS0@heBgZxR/AnDkS5J1woWMITjoAUXAIwEuZ7sXtKaPWnhSA3LXIZzHKfYCszkpAwh5CSJYATQG4fObh@RRjvFAzPDTWKSYQxZZpNAU1RwNinjGIXyST5xgJy61Bivb7NUwnJwEBqqHTHic9orJ@SwAGB0rdpDuscgRuJ2SoZ6kYx1yaB2BygY5wRI8JrHOFo8F3OcRJACNL0H6fRc4gSAwUxLt1RoES7gQibfhDIhec1ID9r8UjhDzEccWaqeeyHmLDIVnIVIysIuYqTK5fH7OBoTJWhyeikGAqHGBJX8TKrM10AD7A8Cdy6GRhKLCQPBx2DdHwlsRDIDBgVl3iUUCboz1QD/aQ63RDylJqGSFTBP3BGrAjfNwfMpEXdxSmPBsoiECnX3ABCEjLMSdPDb5kR4FqqQ5MDQPT6D8SwqKBFMhYPKEDCkiJVlmRVAuSPiELXwi6DUWGZLJYFAiy1fwFFAJtoMbakJdTWaB/xS0UPm2vkxkLijFY1nqsFNsWYf7jIOvSRQnXWLiohpBtCWE2BlMsc2npgjCWnA4NtLxVNjBT5aAv5C4qnWDYNkSkbVKkBJJnVe8kZQzW63uIvVbEixYXAbxLgWTc8IG7h93No4E08WTpIPsIkSodTXUJFVRTcUcVUcs4CAKjYwZO@oBLJXwSdrcgmODUj8miHNC8fdrxWraguT0PKbrqPgWBLmmtVDeKadBJjQLow3bEeVusiy4@w5J5ne5qg6QXhL5RN4SCFcdAOpEa@WvFaf87EiCKAcQAGxDHkkRNPJxFqSAjkMThHoHZrA38KZxULZj50ibQ5IIqj18/AoMHh@Wf4lhkgQiQBZHETb@cw3Ll@W/YkgIj/JMIbGClNM1IHwKMXlJXzliEWFAv8ezcVNcVPWo03cLJCt8kbRNUZArjgAoga0tdF57ISIAnFA1DohmIy5LXOQLdFyElu2fR8hSIxytInUo2nvomJsJLHoHqgS2Q6CyeLI8Tf@zC2DxRHxGsuU5XSDMm0slh6bQyErad3kwVESYBh9ALhTlxJOt0GoANBMQUrAl5gCxHRFAVGsLve3QaNEqmggNDEyiJDxPdRSx0dKFhFBLKos5IZd040HqhJgkp6isRUCPVdE85Aki3BKp0YfEUCzNwBIJPIYcqaGHFmP/AgXE300HWKB9IIhy0VOmJmmSPBABRkgGTfrqpWCaqKMdivfp@eAo9BMH6fMleKgW0GMtHBIQRsltLmRurKYc6fRLVBVOqp8f22BS1OJBYeEkAKVEiAviQLoJFeywQymz9mDa7PbV1OJxBo0BaIX7Gge6zxFQR3QjD64G1Tkqy9hDeRJsIr3VKo3ebxEnJvEccmNIcmoBUoE52KUf0sQRS8WF5dkGYmz90yRUITHs6DRoykfTQOMQGqB3UaoQ0@gMnXM/yooqAyQ7i3jBRqHHJOrIJbuRyCQhg0Mdc4SdIp96LDTOk7alU634jR579QLUddEBqPLW0UkwuEUtPS2V2myp@6HD0Jd4eaBRBE2S4Vny2kXHQO1o@rJc4wKaKbyshxY/HY2yp5Zmn3sr73o2Er11bCzAR8DSLtDZpBmRrBvdfNWANhxLJGJAsHySGHVFJXQEOMZmMP1k6HIJgJCIFGSmSjUtCWQAy6w6P0yXYvgxQqa0JRPb9m3lZWtWKJSjA/ClfdoiODR431oN4adRxbFRUVbHNOsDUU9wAVUxTgjGMbyjqriOIwgdJpsSR/0RQ2SQ6vCTLguuqERbbFsbSeE7vcF0lMFmmD630FKV6mXjo75dZGeAI62RP/hotJo3eE3XQLYRDT2W79MOrgI0HWUIcOhQ9jLWFFHUxuHGUJ@ttDximBgwCfzIATbcQcRZCgra5y62L506aGJLEUPyfFx6kQ86f2oy6BN0KIDn/6amj0PBRJ4kG0AS6jtuiU/dGmEFnpoawe7nyFKqb7Wa64IgJAKq/FE69A9dpQWDLIp9mo/g6HVL1O6Bxt1es/S2MArTAas12OR96DRgFF3o2V6ubRNmIBPFB6Rx2KOn1hCSQpOQi1Os72iXgue4yqYGb2rs7LjHlgIiQQgKqumjgZzbWq6kP30oR1MXOLU5BBPsbYuhp5A4crp1AHAnRDVsHG4GGmYLHxLy5CrVcQ5sH6m7T2cjRYMPKIUaA6zA@lPdAAgEwXGonMft6bGlhk4hBaphHh2IDuHBw8ZTDcTpnAojwf7tdglCKToVxwyRSsSeUEAXJuHqaIUx3z9NMELsCM5m1e4XfKbDA0jDeuv@hwbkCAMwCS/IPmlspmAISSesI2uOHdjLoX3QQjIUIxnKoAOxtNAu2VdICzKwbZWEihfVWPTBMO6nTRGHQS6cxQmHGqqy7SrI17QnvOiJUfvpEEnXerbW6qHu6eCrJ7TZI1/YVp3ClHn24C@SRzWjRcMFdIz4VRDptIlyqQ0Amr2AHqCmeZNyoE2hQGdPm2Bny1I2Rv7KWZDciHzy9Nr6YAyGSaTb0wOIWJ@J@dbCc3xeRyBoByyEB4Qn2DEe9En6A/TxkoMOD1ymltTxxgFBz2hnKg0pfZhYmpz4Yi2Dw09YetggvMJRjrGTxgSrsrMYXowgtybM8V/32CLL4YXX1kMa19ZcOseDY425eueUw4YUZ3@siB4Erth/ED9honLSvSmvdwEIvy0xeqo5Pmdmstsuvgc1YaWpkxqylQAQSunl46FyDrVQ938dp1gZVKHhqWOgTbCcdyJ9J6FKsYaxoJlqz2uTnOoJ5US9/FrZc8QpTenQZW078JU56dOcAK4S1nKu3tbLmQna4nthk/OUlwJDazR1JoDXyxfduy04vRp5PRMRPAF70u2aLMQ6YDmy8d89Hcjzs8dymkJqCgSiDYVuepvbWu2lRNg4OI/amk40fcuyskc37xB2uyEr6hUY@9hvOduQXHCJpKlxQHR74UZurxcrtmcaNp8OPUV1S0/vSGAtFC/rIo/5c3oWtZvQI@lgVzOuCHoh45BPFtthQrWjQfV973HsZjs/JsSpDD9J9o7Yhsdj9o0TZysH5L4CIR/8Zuvn2/SWh9KTFOLSITUEbS7dXbyTcXpUYCD50ms7p/be8A1xKm@MHCold8PXwfw8a6Sk2k0cudvZo8PIGXlGFK@25nhBub1wQmNmX2O16MLD4SMXPwLXvfjgA5Ve/EKLIw2drd7L/1uSDqcvVGgWwFqeOY5tgyd8L5koq8O/nZzaY43BA0RRlqACWTT3QlpxIYNO4riy8F6t79yWN24rOkF9x8rgQnMGidM7h2jc0vX4QInwztV7UQ5NGbI9amn2wHxoImf1NcfAUjpC05tHK5kve23UOk6WtgIOeVbbQq9Onw1Hex@CaXon4bWMXztk7h5EeZE2uLya0KnoBp0vgC@c8LzVgR/naYp/lYApjUnPVC6OEHyKjNwgyeALNHipJL/hjo2/es52me1NEkHT8OHMasHSsbS6cbalC7HN0PC8t0Jj2tTQWoz6ODLw1u/v19ffXz8/398/3/8B "Seed – Try It Online") Made possible thanks to [Abigail](https://codegolf.stackexchange.com/users/95135/abigail)'s `perl` answer. Inspired by [HighlyRadioactive](https://codegolf.stackexchange.com/users/87986/highlyradioactive)'s comment. Last iteration was golfed with bx6. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~666~~ ~~616~~ ~~518~~ ~~483~~ 476 bytes Who doesn't love classy, Arthur Whitney-styled code? No regular expressions involved, only clever parsing and evaluation. PS: Yes, obviously, a few bytes can be shaved off, but for the artistic style of the obfuscated code, I'll keep them. Also for the byte count :p. Also, this code utilizes undefined behaviour in hope that nothing will break (hopefully). @ceilingcat insisted on golfing it down from 666 bytes, so here is the golfed version: ``` #define J putchar #define H O->a #define G H->a #define K O->b typedef struct x{struct x*a,*b;int q;}Y;Y*O;z=1;A(q){O=calloc(6,4);O->q=q;}h(Y*O){Y*u;O=H&&H->q==2?z=K:H&&G&&G->q==1?z=H->b:H&&G&&G->a&&!G->a->q?u=A(3),(u->a=A(3))->a=G->b,(u->b=A(3))->a=H->b,u->a->b=u->b->b=K,z=u:(O->q==3?H=h(H),K=h(K):0,O);}r(x){Y*O;x=getchar()-73;x=x+33?A(x?x!=10:2):!getchar(K=r(H=r(O=A(3))))+O;}q(Y*O){O&&J(O->q["SKI "],O->q-3||J(41,q(K),q(H),J(40)));}main(){Y*O=r();for(;z;O=h(O))z=0;q(O);} ``` [Try it online!](https://tio.run/##TVDBjoIwEL37FegmZAZLAmJ2E5ou8STaQw@ezGYPwKKYuCosJCzKt7vTGnWTtm/ee9OZaTN3m2XX68tXvtkdcmtpnZo6K5JqcFdiS7nvyYPOrfg/ldpNB/XvKSfF@qmrJqut9nwPnIQ5Kd8daqvk/ZqvHcU74fMZlHhWIkv2@2MGr2yKnOqUgpIKoCQ8r52GKxHbdqx1MYk6IUOic1pG8UkhL32KiW0PNZAdNWIGATJoiJsQdUBuarT0qekarDHXUqEtjZJ1ognBzCSCKBYFxMgkgcTQYwp5X0Grp1S8FdvcfBmg@xYQbcdBEM2gjdqh8L1wguHwniFFBTFtdeuPOFa8L28vVra9NB0/Riu5sEafTBM3uFyWMPVZSa3poDGIenSV99/J7gBmCCqJfHOsgHf0awUoxE54vAQ96fUKAHKBdK4WqNEAPgSJ@Ac "C (gcc) – Try It Online") [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 63 bytes ``` #//.{{I,x_}->x,{{K,x_},y_}->x,{{{S,x_},y_},z_}->{{x,z},{y,z}}}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfX6@62lOnIr5W165Cp7raG8TUqYRxq4NhfJ0qkFh1dYVOVa1OdSWQrK1V@x9QlJlX4pDmAFbpWQtC3rX/AQ "Wolfram Language (Mathematica) – Try It Online") God, I love pattern matching in Wolfram Language. Represents `(xy)` as `{x,y}` (a list of two elements). Alternatively, if we represent `(xy)` with `x>y`, we can do it in **55 bytes**. ``` #//.{I>x_->x,(K>x_)>y_->x,((S>x_)>y_)>z_->(x>z)>(y>z)}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X1lfX6/a064iXteuQkfDG8jQtKuEcDSCoTxNuyqgiEaFXZWmnUYlkKxV@x9Ympla4hBQlJlX4pAWDVLrqQlC3rH/AQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Rust Macros](https://www.rust-lang.org/), 480 441 bytes ``` macro_rules!s{({I$($t:tt)+}$s:tt)=>{s![{$($t)+}$s]};({K$x:tt$y:tt$($t:tt)*}$s:tt)=>{s![{$x$($t)*}$s]};({S$x:tt$y:tt$z:tt$($t:tt)*}$s:tt)=>{s![{$x$z($y$z)$($t)*}$s]};({($($c:tt)*)$($t:tt)*}{$($r:tt)*})=>{s![{$($c)*}{{$($t)*}$($r)*}]};({$($c:tt)*}{{$($t:tt)*}$($s:tt)*})=>{s![{$($c)*$($t)*}{$($s)*}]};({$($c:tt)*}{})=>{concat!($(s![$c]),*)};(($($t:tt)*))=>{concat!("(",s!($($t)*),")")};($t:tt)=>{stringify!($t)};($($t:tt)*)=>{s![{$($t)*}{}]};} ``` [Try it online!](https://tio.run/##fZHNaoQwFIX3fYokzeJe66ItXc0w3Q8uXQ4ySJgpgsaSRBgNPrvNVcdaaYtifs53zj2gaawbHvnJXFRjbFHrc1lUhWMHJl6eX99ENlS5MvXZNOXFcuvBHyVIt3MOn3ppaT28e8tPnq7Hu6zfg0/kLWiypc/MRxv@NjqiuyNdObp/bR3IVnb40w7hqEYev51UykzbVU1Fir/bAxGWMWOJmOV5PEwFthlzAJ3sLwkjrWqtcsdDueCTKsM4wsDBko5rSoCILYcpGGOBguCJpNHOFPqjuLacAFKWlPU/oNmhTD9cNavyQgP6B8Y@g9eVmlMRAEjZEelNMMP9Rg5aeJI/BZaS1A9f) The macro takes in tokens and spits out a string literal. Input is in a flattened, left-associative format as seen on Wikipedia. Make sure there is some whitespace between combinators when using it. ungolfed: ``` macro_rules! ski { ({I $($t:tt)+} $s:tt) => {ski![ {$($t)+} $s]}; ({K $x:tt $y:tt $($t:tt)*} $s:tt) => {ski![ {$x $($t)*}$s] }; ({S $x:tt $y:tt $z:tt $($t:tt)*} $s:tt) => {ski![ {$x $z ($y $z) $($t)*} $s ]}; ({($($c:tt)*) $($t:tt)+}{$($r:tt)*}) => {ski![ {$($c)+} {{$($t)*} $($r)*} ]}; ({$($c:tt)*} { {$($t:tt)*} $($s:tt)* }) =>{ski![ { $($c)* $($t)* } {$($s)*} ]}; ({$($c:tt)*} {}) => {concat!($(ski![$c]),*)}; (($($t:tt)*)) => {concat!("(", ski!($($t)*), ")")}; ( $t:tt) =>{stringify!($t)}; ($($t:tt)*) => {ski![ {$($t)*} {}]}; } ``` Macros declared with `macro_rules` perform substitution based on rules similar to a regex-based substitution. The general strategy is here is an execution stack, where the instructions are being stored and executed, and a call stack, which is a stack of execution stacks and is used to traverse into functions created with `()`. Rule number ten serves as the entry point to the macro, matching on all inputs and setting up the call and execution stacks in the form `{instructions}{}`. Note that matched pairs of brackets count as a single token, and closing brackets stop greedy matches. Rule one implements the `I` combinator. It matches when the call stack is `I` followed by one or more instructions. It simply passes on all the matched instructions. Rule two implements the `K` combinator. It behaves similarly to `I` but uses two arguments instead of one. Rule three is the same but for `S`. Rule four implements traversing into parentheses by pushing the instructions remaining on the execution stack after the parentheses onto the call stack, and replacing the call stack with the instructions in the parentheses. Rule five catches an edge case by stopping infinite recursion when there are no instructions after the parentheses. was made redundant by an earlier bug fix and removed. Rule six is when the execution stack can't be simplified and there are more instructions on the call stack, the instructions in the top execution stack on the call stack are concatenated on the bottom of the main execution stack. Rule seven is when the execution stack can't be simplified and the call stack is empty. Here all the tokens are split, fed back into this macro for stringification, and concatenated. Rule eight is where I say I lied because parenthesized groups need further evaluation because that strategy I had above evaluated these groups lazily. This rule simply feeds the instructions in the parentheses back into the original macro and concatenates parentheses around the results. Rule nine is our terminal rule, where the tokens passed in are stringified and returned. Assuming the recursion limit is removed and rustc gets unlimited memory this is a proof of turing completeness for rust's macro system (not the only one- rust's macros are trivially ℒ-hard, a macro that binds an inputted `$` can create and execute arbitrary macros). A playground link that lets you view the ungolfed macro's expansion steps is below. [Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=996c3ded4ca69d2dcc05a89ae634e620) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~127~~ 124 bytes Full program. No use of regex. ``` ∊{0=≡⍵:⍵ 1⌽')(',∇¨⍵}{0=d←|≡⍵:⍵ 'I'≡⊃⍵:⊃⌽⍵ (2≤d)∧'K'≡⊃⊃⍵:⊃⌽⊃⍵ (3≤d)∧'S'≡⊃∊⍵:x y,⍥⊂¨⊃⌽(((s x)y)z)←⍵ ∇¨⍵}⍣≡⍎⍕{3⍴''''⍵}¨@{⍵∊⎕A}⍞ ``` [Try it online!](https://tio.run/##VU@9agJBEO73KbbbGVAw2gUELY8r9wmEwxBY8MDG80yTQDwPV9JoZ0AU4gNoI9jom8yLnLNrzp9hlmG@n9mZTmyqUdIxvbfivKDvnxTI7n0ekJ/Pa7//kGSXMu6ZpPtujKBsHBeU5WmtSZMV86/8xAtNjwpBVZg@bZ2L@YgHjx5EKlCuy788wGV6dDDUabKJkLI/FZaCJ41vBDRuMl3KstzJBjKp8BX5J//sHQDQlwNMcIi8gjPf1iK79hvNyM7TBtmd4nDEadtK3cE8cjZvs@6XrxwX0kcseKQOMMAQxR0KQWtE/QhBGGCp/S@IdzNeAA "APL (Dyalog Unicode) – Try It Online") The program has three distinct parts: * Input handling * Evaluation * Output formatting ### Input handling This part transforms the traditional SKI notation into a nest APL data structure. ``` ⍎⍕{3⍴''''⍵}¨@{⍵∊⎕A}⍞ ``` `⍞` prompt for one line of input text   E.g. `"(((SI)I)K)"` `@{`…`}` **at** locations where:  `⍵` the argument characters  `∊` are members of  `⎕A` the uppercase Alphabet `{`…`}¨` replace each one by:  `3⍴` a cyclical **r**eshape into length 3, of  `''''⍵` the string consisting of a quote character (`'`) and the argument character   E.g. `["(","(","(","'S'","'I'",")","'I'",")","'K'",")"]` `⍕` stringify (this forces the now nested array into a flat space-separated string)   E.g. `"((( 'S' 'I' ) 'I' ) 'K' )"` `⍎` evaluate as APL code   E.g. `[["SI","I"],"K"]` ### Evaluation This part simplifies the data structure according to the three given rules. ``` {0=d←|≡⍵:⍵ 'I'≡⊃⍵:⊃⌽⍵ (2≤d)∧'K'≡⊃⊃⍵:⊃⌽⊃⍵ (3≤d)∧'S'≡⊃∊⍵:x y,⍥⊂¨⊃⌽(((s x)y)z)←⍵ ∇¨⍵} ``` `0=`…`:` if 0 equals `d←` the variable `d` which is (assigned for later use) `|≡⍵` the absolute depth (maximum nesting level) of the argument:  `⍵` return the argument as-is (this ensures the continuation of already evaluated parts) `'I'≡`…`:` if `"I"` matches `⊃⍵` the first element of the argument  `⊃⌽⍵` return the last element of the argument (lit. the first of the reversed; this implements `(Ix)` → `x`) `(2≤d)∧`…`:` if 2 is less than or equal to the depth (`d`), AND `'K'≡⊃⊃⍵` if `"K"` matches the first element of the first element of the argument:  `⊃⌽⊃⍵` return the last element of the first element of the argument (lit. the first of the reversed first; this implements `((Kx)y)` → `x`) `(3≤d)∧`…`:` if 3 is less than or equal to the depth (`d`), AND `'S'≡` if `"S"` matches `⊃∊⍵` the first element of the **e**nlisted (flattened) argument:  `(((s x)y)z)←⍵` destructure the argument into individual variables  `⊃⌽` pick the last element (lit. first of the reversed) from that (`z`)  `x y,⍥⊂¨` pair up each of `x` and `y` with that (this implements `(((Sx)y)z)` → `((xz)(yz))`) `∇¨⍵` otherwise, call self on each element of the argument ### Output Formatting Here, we transform the data structure back into traditional SKI notation. ``` ∊{0=≡⍵:⍵ 1⌽')(',∇¨⍵} ``` `0=≡⍵:` if zero is equal to the depth of the argument (i.e. it is a single character)  `⍵` return that as-is `∇¨⍵` otherwise, call self on each element of the argument `')(',` prepend `")("` `1⌽` cyclically rotate one character from the front to the rear. [Answer] # perl -p, 135 bytes ``` 1 while s/\((I)(?<T>[SKI]|\((?&T)(?&T)\))\)|\(\((K)((?&T))\)(?&T)\)|\(\(\((S)((?&T))\)((?&T))\)((?&T))\)/$1?$2:$3?$4:"(($6$8)($7$8))"/e ``` [Try it online!](https://tio.run/##K0gtyjH9/99QoTwjMydVoVg/RkPDU1PD3ibELjrY2zO2Bsi3VwvRBBMxmkAEFAGKeWtCxIECUCmwOFAmGEkGg6GvYmivYmSlYmyvYmKlpKGhYqZioamhYg4kNZX0U///1wAa4Knpqemt@S@/oCQzP6/4v24BAA "Perl 5 – Try It Online") Just a regexp applying the three rules. Reads a string from `STDIN`, applies all the rules until there's nothing to apply, writes the result to `STDOUT`. `(?<T>[SKI]|\((?&T)(?&T)\))` is a recursive pattern recognizing a term. The rest of the pattern is just a mechanically translation of the given rules. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 171 bytes ``` {T`()`<> <<<S((\w|(<)|(?<-3>>))+)>((\w|(<)|(?<-6>>))+)>((\w|(<)|(?<-9>>))+>) <<$1$7<$4$7> <<K((\w|(<)|(?<-3>>))+)>(\w|(<)|(?<-5>>))+> $1 <I((\w|(<)|(?<-3>>))+)> $1 T`<>`() ``` [Try it online!](https://tio.run/##K0otycxL/P@/OiRBQzPBxo7LxsYmWEMjprxGw0azRsPeRtfYzk5TU1vTDkXQDJugJVjQThNohoqhirmNiomKOchAb@zmIYmZQnRyqRhy2XhiVQ2SCgG6D@jK//81gCDYU9NT01szWBMA "Retina 0.8.2 – Try It Online") Explanation: ``` {` ``` Repeat the transformations until there are no more available. ``` T`()`<> T`<>`() ``` Temporarily switch `()`s with `<>`s to avoid having to quote numerous `()`s. ``` <<<S((\w|(<)|(?<-3>>))+)>((\w|(<)|(?<-6>>))+)>((\w|(<)|(?<-9>>))+>) <<$1$7<$4$7> ``` Process `S` operations. (The last capture includes the trailing `>` in order to avoid repeating it in the replacement.) ``` <<K((\w|(<)|(?<-3>>))+)>(\w|(<)|(?<-5>>))+> $1 ``` Process `K` operations. ``` <I((\w|(<)|(?<-3>>))+)> $1 ``` Process `I` operations. The `(\w|(<)|(?<-[N]>>))+` construct is an example of a .NET regex balancing group. It tries to match characters, but it's only allowed to match `>`s if it's already seen the same number of `<`s. (`N` needs to be replaced with the number of the `(<)` capturing group. As written it fails if the `<>`s aren't balanced correctly, but you can use conditional regex to check for that.) [Answer] # [Wolfram Language](https://www.wolfram.com/language/), 44 bytes ``` s[a_][b_][c_]:=b@c//a@c;k[a_][b_]:=a;i@a_:=a ``` This defines them as actual functions in Wolfram, so `s[i][i][k]` returns `k[k]`, etc. [Try it online!](https://tio.run/##y00syUjNTSzJTE78/784OjE@NjoJiJPjY61skxyS9fUTHZKts2HiVraJ1pkOifFA@n9AUWZeSXRxdGYsCGXHxv4HAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 92 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔDŒʒ„)(©S¢Ë}ʒÁ®Å?y®S¢O_~}©vy"(Iÿ)"y:}®ãvy`"((Kÿ)ÿ)"yθ:}®3ãvy`"(((Sÿ)ÿ)ÿ)"yĆ1.I`"((ÿÿ)(ÿÿ))": ``` 05AB1E has no regex, so uses a brute-force approach using all valid substrings. Because of this, it's extremely slow for larger test cases. Executes in the order `(Ix)` → `((Kx)y)` → `(((Sx)y)z)`. [Try it online](https://tio.run/##yy9OTMpM/f//3BSXo5NOTXrUME9T49DK4EOLDnfXnpp0uPHQusOt9pWH1gFF/OPrag@tLKtU0vA8vF9TqdKqFii5uKwyQUlDwxsoAhY8twMkbAwT1wiGSIDljrQZ6nmCRA/vB/IhpKaS1f//IHWemp6a3pr/dXXz8nVzEqsqAQ) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/3NTXI5OOjXpUcM8TY1DK4MPLTrcXXtq0uHGQ@sOt9pXHloHFPGPr6s9tLKsUknD8/B@TaVKq1qg5OKyygQlDQ1voAhY8NwOkLAxTFwjGCIBljvSZqjnCRI9vB/Ih5CaSlb/a2t1/oOUemp6anprcmkg2MEgnrenJkwESmlq/tfVzcvXzUmsqgQA). **Explanation:** ``` Δ # Continue until the result no longer changes: D # Duplicate the current string # (will use the implicit input-string in the first iteration) Œ # Take all its substrings ʒ # Filter those substrings by: „)( # Push ")(" © # Store it in variable `®` (without popping) S # Convert it to a list of characters: [")","("] ¢ # Count each in the substring Ë # Check that the counts are equal for both }ʒ # After the filter: filter once more: Á # Rotate the substring once towards the left ® # Push string ")(" from variable `®` Å? # Check if the rotated substring starts with this y # Push the substring again ®S¢ # Count the [")","("] again O_ # Check that the sum of both counts is 0 ~ # Check if either of the two was truthy }© # After the filter: store it in variable `®` (without popping) v # Loop over each valid substring: y # Push the substring "(Iÿ)" # Push this string, with the `ÿ` automatically filled with # the substring y # Push the substring again : # Replace all "(Ia)" with "a" }® # After the loop: push the list of valid substrings again ã # Take all pairs of valid substrings v # Loop over these pairs: y` # Pop and push the pair separated to the stack "((Kÿ)ÿ)" # Push this string, with the `ÿ` automatically filled again yθ # Pop and push only the last substring of the pair: [a,b] → b : # Replace all "((Kb)a)" with "b" }® # After the loop: push the list of valid substrings again 3ã # Take all triplets of valid substrings this time v # Loop each each triplet: y` # Pop and push the triplet separated to the stack "(((Sÿ)ÿ)ÿ)" # Push this string, with the `ÿ` automatically filled again y # Push the current triplet again Ć # Enclose; append its own head: [a,b,c] → [a,b,c,a] 1.I # Get the 0-based 1st permutation: [a,b,c,a] → [a,b,a,c] ` # Pop and push the quartet separated to the stack "((ÿÿ)(ÿÿ))" # Push this string, with the `ÿ` automatically filled again : # Replace all "(((Sc)b)a)" with "((ca)(ba))" # (after which the result is output implicitly) ``` [Answer] # [Scala 3 (compile-time)](https://dotty.epfl.ch/), 113 bytes ``` type A=AnyKind type S[X[a<:A]<:[b<:A]=>>A]=[Y[z<:A]]=>>[Z<:A]=>>X[Z][Y[Z]] type K[X<:A]=[Y<:A]=>>X type I[X<:A]=X ``` [Try it in Scastie](https://scastie.scala-lang.org/3BmcMDVOT0eqrYq0onHQAQ) It works at compile time and it doesn't exactly return a value (you can check it with `=:=` or other mechanisms), but Dotty's type system is Turing-complete (Scala 2's too, actually). Pretty straightforward - it uses higher-kinded types and curried type lambdas like functions. Ungolfed (and modified slightly for clarity): ``` type S = [X <: [a <: AnyKind] =>> [b <: AnyKind] =>> AnyKind] =>> //X is a type lambda with 2 parameters (curried) and returning a type of any kind [Y[z <: AnyKind]] =>> //Y is a type lambda taking one parameter and returning a type of any kind [Z <: AnyKind] //Z is a type of any kind =>> X[Z][Y[Z]] //The result of Skyz, as defined in the question type K = [X <: AnyKind] =>> [Y <: AnyKind] =>> X type I = [X <: AnyKind] =>> X ``` `SIIK` or `(((SI)I)K)` would be written as `S[I][I][K]`. --- ### With match types, 200 bytes ``` final class S final class K final class I type R[T]=T match{case(((S,x),y),z)=>R[((x,z),(y,z))]case((K,x),y)=>R[x]case(I,x)=>R[x]case(a,b)=>R[a]match{case`a`=>(a,R[b])case _=>R[(R[a],R[b])]}case T=>T} ``` *Thanks to @[HTNW](https://stackoverflow.com/users/5684257/htnw) on SO for helping me with this* [Try it in Scastie](https://scastie.scala-lang.org/gHUFkF6JQ4esDYN4fZExug) A term `(xy)` is represented as the tuple `(x,y)`. --- ### Using literal types, 164 bytes ``` type R[T]=T match{case((('S',x),y),z)=>R[((x,z),(y,z))]case(('K',x),y)=>R[x]case('I',x)=>R[x]case(a,b)=>R[a]match{case`a`=>(a,R[b])case _=>R[(R[a],R[b])]}case T=>T} ``` [Try it in Scastie](https://scastie.scala-lang.org/gLDKg0KaRdeqelpXGSENng) This one uses literal-based singleton types (the `Char`s `'S'`, `'K'`, and `'I'`). --- ### Slightly unethical version, 158 bytes ``` type R[T]=T match{case(((0,x),y),z)=>R[((x,z),(y,z))]case((1,x),y)=>R[x]case(2,x)=>R[x]case(a,b)=>R[a]match{case`a`=>(a,R[b])case _=>R[(R[a],R[b])]}case T=>T} ``` Same approach as above, but this time, S is the singleton type of `0`, K is `1`, and I is `2`. [Try it in Scastie](https://scastie.scala-lang.org/rpzSpDOaR56lHF38U46y0w) [Answer] # [KamilaLisp](https://github.com/kspalaiologos/kamilalisp), 137 bytes ``` (defmacro f(x)(match x((a b c)(S a b c)[(tie a c b c)/ 2])((a b)(K a b)a)(a(I a)a)((a b)(a b)(tie(f a)(f b)))(x)))(def g $(iterate /= f)) ``` Ungolfed: ``` ;; SKI calculus implementation using KamilaLisp macros (defmacro ski (x) (match x ((a b c) (S a b c) [(tie a c b c) / 2]) ((a b) (K a b) a) ((a) (I a) a) ((a b) (a b) (tie (ski a) (ski b))) (x) )) ;; iterate /= => fixed point (def ski-red $(iterate /= ski)) ;; an example expression (println@ski-red '(S I I K)) ``` [Answer] # [Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 138 bytes ``` fmod F is sort T . ops S K I : -> T . op __ : T T -> T . vars x y z : T . eq I x = x . eq (K x)y = x x . eq ((S x)y)z = (x z)(y z) . endfm ``` ``` Maude> red ((S I)I)K . reduce in F : ((S I) I) K . rewrites: 3 in 0ms cpu (0ms real) (~ rewrites/second) result T: K K ``` [Answer] # [Haskell](https://www.haskell.org/), 83 bytes ``` data T=S|K|I|T:$T e(x:$y)=e x!e y e x=x I!x=x K:$x!_=x S:$x:$y!z=x!z!(y!z) x!y=x:$y ``` [Try it online!](https://tio.run/##ZU29CoMwEN7zFBfIEIf2AYRsXcStydCtHOaqUhvBSBvFZ296QqFDh/vu4/u56zDeaRhy9jgjOGO3eqs2VyonSKdSLYUhSJJgEbxNEpXcsS5Vklcmlgmn5GqSXKVmUogkF7OL2dPUP/vQQh/ijKEhsN34Aif@jTOhZ@OBfQDD8kwTNjMoiHvjCMQzcSZrrS2UCqrih3Xxbm4DtjEfLpbveRzGQKfvkw8 "Haskell – Try It Online") ]
[Question] [ Write a program that takes a string and outputs all the characters in alphabetical order. Spaces and symbols can be ignored or deleted, but the upper- and lowercase letters must remain the same case. Sample input: ``` Johnny walked the dog to the park. ``` Sample output ``` aaddeeeghhhJklnnoooprtttwy ``` Rules: • Any language • Shortest code wins. [Answer] ### GolfScript, 24 / 6 characters ``` {26,{65+.32+}%?)},{31&}$ ``` Example: ``` > Johnny walked the dog to the park. aaddeeeghhhJkklnnoooprtttwy ``` If the input is restricted to printable ascii the code can be shortened by three characters using `{95&.64>\91<&},` as filter. Can be tested [here](http://golfscript.apphb.com/?c=OyJKb2hubnkgd2Fsa2VkIHRoZSBkb2cgdG8gdGhlIHBhcmsuIgoKezI2LHs2NSsuMzIrfSU%2FKX0sezMxJn0kCg%3D%3D&run=true). The can-be-ignored version is even shorter (6 chars): ``` {31&}$ ``` and yields output ``` > Johnny walked the dog to the park. aaddeeeghhhJkkl.nnoooprtttwy ``` [Answer] # GNU core utils - 25 characters (29 dropping symbols) ``` fold -1|sort -f|tr -d \\n ``` Example (from GNU bash 3): ``` $ echo "Johnny walked the dog to the park."|fold -1|sort -f|tr -d \\n .aaddeeeghhhJkklnnoooprtttwy <<no trailing newline>> ``` From the question: > > Spaces and symbols **can** be ignored or deleted > > > I chose to leave them in! To retain only alphabetic characters, replace `fold -1` with `grep -o \\w` for +4 characters. ``` grep -o \\w|sort -f|tr -d \\n ``` Thanks to Firefly for recommending `grep -o` over `sed`, and Wumpus for `fold -1`. ;-) [Answer] ## C, 121 This is quite long compared to other entries, but it does not rely on any built-in sorting or ToLower functions: ``` j;main(k){char s[99],*p=s;gets(s);while(*p){j=p-s-1;k=*p++;while(j>=0&&(s[j]|32)>(k|32))s[j+1]=s[j--];s[j+1]=k;}puts(s);} ``` More readable version: ``` j; main(k) { char s[99], *p=s; gets(s); while(*p) { j = p-s-1; k = *p++; while(j >= 0 && (s[j]|32) > (k|32)) s[j+1] = s[j--]; s[j+1] = k; } puts(s); } ``` This is an implementation of insertion sort with a case-insensitive comparison between elements (using the `|32` bitwise operation). This is because in ASCII encoding uppercase letters and lowercase letters only differ by the 25 bit. [Answer] # Ruby - 33 Chars ``` $><<gets.chars.sort(&:casecmp)*'' ``` [Answer] **PowerShell : 39** ``` $([string[]][char[]](Read-Host)|sort)" #With spaces and symbols ``` Result ``` .aaddeeeghhhJkklnnoooprtttwy ``` **C# : 100** ``` Console.Write(new string(input.ToCharArray().OrderBy(a=>char.ToLower(a)).ToArray()).Trim('.',' ')); ``` Result ``` aaddeeeghhhJkklnnoooprtttwy ``` [Answer] ## Perl6: 26 characters Sorts output uppercase first, then lowercase, deletes symbols/whitespace ``` say [~] sort comb /\w/,get ``` If whitespace/symbols in output may be ignored too, this is only 21 characters. ``` say [~] get.comb.sort ``` This sorts case-insensitively, keeps symbols (26 chars) ``` say [~] get.comb.sort: &lc ``` [Answer] # APL 16 ``` ⍞←A[⍋48|⎕av⍳A←⍞] Johnny walked the dog to the park. aaddeeeghhhJkklnnoooprtttwy. ``` [Answer] ## Perl 34 Now takes input from `STDIN`. ``` print sort{lc$a cmp lc$b}<>=~/\w/g ``` --- ## Perl 18 *If output including capitals first and symbols included is acceptable:* ``` print sort<>=~/./g ``` [Answer] # Python 3: 45 ``` print(''.join(sorted(input(),key=str.lower))) ``` [Answer] # Haskell, 88 ``` import Data.List import Data.Char import Data.Ord main=interact$sortBy$comparing toLower ``` (38 without imports from standard lib) [Answer] # k (~~10~~ 9) Reads from stdin ``` x@<_x:0:0 ``` Example ``` x@<_x:0:0 Johhny walked the dog to the park. " .aaddeeeghhhhJkklnoooprtttwy" ``` [Answer] # C#: 83 ``` Console.Write(new string(Console.ReadLine().OrderBy(i=>i+"".ToLower()).ToArray())); ``` # Update: 65 Executable in *LinQPad* ``` new string(Console.ReadLine().OrderBy(i=>i+"").ToArray()).Dump(); ``` [Answer] # F# (68 56) I'm learning F# so I'm sure this could be shorter: ``` let f s=s|>Seq.sortBy Char.ToLower|>Seq.iter(printf"%c") ``` Output: ``` > f "Johnny walked the dog to the park." .aaddeeeghhhJkklnnoooprtttwy ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes ``` áδ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///wwnNb/v9X98rPyMurVChPzMlOTVEoyUhVSMlPVyjJBzMLEouy9dS51EMyMosVgCgxT8G1IjG3ICdVITg1ryQ1Lzn1Ucsi9f8A "MathGolf – Try It Online") ## Example output ``` .aaddeeeghhhJkklnnoooprtttwy ``` ## Removing non-alphabetical characters To remove all non-alphabetical characters, this solution works: ``` áδgÆ∞_δ¡ ``` It is the same as the code above, followed by a filtering where each character is first doubled, and then compared its own capitalization. For example, the string `"a"` is converted to `"aa"` and then capitalized to `"Aa"`, which is not equal to `"aa"`. The same way, the string `"B"` is converted to `"BB"` and capitalized to `"Bb"`, which is not equal to `"BB"`. However, `"."` is converted to `".."` and is unchanged when capitalized, so it will become filtered out. ## Explanation I really need more string handling in MathGolf... Right now there isn't even an operator to convert to lowercase/uppercase. The only thing I could use was the capitalization operator, which works like an uppercase operator for strings of length 1. This solution also sorts non-alphabetical characters, but those could be ignored. The alphabetical characters preserves their case and are output in the correct order. ``` á sort by comparator δ capitalize string ``` [Answer] # J, 12 characters ``` (/:32|a.i.]) ``` Ignores any non-alpha characters. [Answer] **Javascript - 74** Unfortunately, due to the way JS sorts characters, we cannot use standard sorting function: ``` prompt().split("").sort(function(a,b){return a.localeCompare(b)}).join("") ``` Actually this can be shortened to: ``` prompt().split("").sort((a,b)=>a.localeCompare(b)).join("") ``` [Answer] # PHP, 50 bytes ``` $a=str_split($argn);natcasesort($a);echo join($a); ``` does not remove non-letters, takes input from STDIN; run with `-R`. [Answer] # Java 10, 72 bytes (as lambda function) ``` s->{for(int i=64;++i<91;)for(var c:s)if((c&~32)==i)System.out.print(c);} ``` [Try it online.](https://tio.run/##LY/LasMwEEX3@YpLFkUiRNAHhcZ1IHRXaDZZli6mshwrdiQjTVxMcH/dlVNvhpkLwzn3RB2tT0U96oZixAdZd10A1rEJJWmD/XQCnbcFtDhwsO6IKLOUDos0IhNbjT0ccoxxvb2WPoj0D5s/P2WrlX19uc/kFHYUoDdRsX@rKOxCoF5IaUsh9N3v44PMcysPfWRzVv7Cqk0oFlpmw5hNpPby3STSDLwJnZPu7PT5BZL/rk5psXz3lXM9fqipTQGuDAp/BPvb2lKo1XIuMYx/) But since it's an old challenge stating full program: # Java 10, 126 bytes (as full program) ``` interface M{static void main(String[]a){for(int i=64;++i<91;)for(var c:a[0].toCharArray())if((c&~32)==i)System.out.print(c);}} ``` [Try it online.](https://tio.run/##HYxNC4JAFAD/yjvFLpL0RVDmIboFnTyKh8e66tPclfVliNhf36zbMAxT44DrOm@8J8PaFag0PKaekUnBYCmHFsmIhB2ZMs1QToV1YmmB4uMhCgK6nLaR/MkBHagzppssZHur0F2dw1FISYUQavXZ72Qck0zGnnUb2heH3TJloWQ0z977u62MGeGNz0bnwJWG3JbA9o8duib8Ag) **Explanation:** ``` interface M{ // Class static void main(String[]a){ // Mandatory main method for(int i=64;++i<91;) // Loop over the uppercase alphabet for(var c:a[0].toCharArray()) // Inner loop over the characters of the input if((c&~32) // If the current character converted to uppercase, ==i) // equals the current letter of the alphabet System.out.print(c);}} // Print the character of the input-loop ``` [Answer] ### R, 48 characters ``` cat(sort(unlist(strsplit(scan(,""),""))),sep="") ``` Example usage: ``` > cat(sort(unlist(strsplit(scan(,""),""))),sep="") 1: Johnny walked the dog to the park. 8: Read 7 items .aaddeeeghhhJkklnnoooprtttwy ``` [Answer] ## q/k4 (3? 5? 8?) if it's sufficient to enter the code and the input directly into the REPL, it's just `asc`: ``` q)asc"Johnny walked the dog to the park." `s#" .Jaaddeeeghhhkklnnoooprtttwy" ``` the ``s#` is bit of q notation that indicates that the string is in sorted order (can be binary searched, etc.). if it has to go, that costs two characters, making five: ``` q)`#asc"Johnny walked the dog to the park." " .Jaaddeeeghhhkklnnoooprtttwy" ``` if you want it provided on stdin, it's time to switch to k4 (and we get rid of the ``s#` for free), and it's an eight-character solution: ``` x@<x:0:0 Johnny walked the dog to the park. " .Jaaddeeeghhhkklnnoooprtttwy" ``` that one, btw, will work as a code file exactly as is (still eight characters, since q is fine with not having the final newline in a code file). normally there would be issues with a welcome banner and with the REPL staying open, but if you pass the input as a herestring, all that goes away: ``` $ cat asc.k x@<x:0:0 $ q asc.k<<<'Johnny walked the dog to the park.' "\n .Jaaddeeeghhhkklnnoooprtttwy" $ ``` not actually sure where that extra newline in the output is coming from.... [Answer] # Jelly, 3 bytes ``` ŒlÞ ``` My first Jelly solution on this site! Thanks to @LeakyNun and @ErikTheOutgolfer for teaching me how to use Jelly and @Dennis for making it! :D ### Explanation ``` ŒlÞ Þ Sort using the function to its left Œl Converts to lowercase (because it's sort alphabetically, not by codepoint) ``` Alternatively, `ŒuÞ` does the exact same thing except converting to uppercase instead. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~3~~ 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Σl ``` Ignores non-letter characters, so some are leading and some are trailing. [Try it online](https://tio.run/##yy9OTMpM/f//3OKc///j6hS88jPy8ioVyhNzslNTFEoyUhVS8tMVSvLBzILEomw9hbo4AA). A version which removes non-letter characters is **3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` áΣl ``` [Try it online](https://tio.run/##yy9OTMpM/f//8MJzi3P@/4@rU/DKz8jLq1QoT8zJTk1RKMlIVUjJT1coyQczCxKLsvUU6uIA). **Explanation:** ``` á # Optional: only leave the letters ([a-zA-Z]) of the (implicit) input-string Σ # Sort the characters in the string by (sorted by their ASCII unicode value): l # Their lowercase equivalent (in case of the letters) # (And output the result implicitly) ``` [Answer] # Powershell, 36 bytes ``` -join($args-split'\W|(.)'-ne''|sort) ``` Test script: ``` $f = { -join($args-split'\W|(.)'-ne''|sort) } @( ,("Johnny walked the dog to the park.", "aaddeeeghhhJkklnnoooprtttwy") ) | % { $s,$expected = $_ $result = &$f $s "$("$result"-eq"$expected"): $result" } ``` Output: ``` True: aaddeeeghhhJkklnnoooprtttwy ``` [Answer] # [Julia 1.0](http://julialang.org/), 34 bytes ``` s->join(sort([s...],by=lowercase)) ``` [Try it online!](https://tio.run/##HcrNCYAgGADQVcSTQgkNUAO0QnSw1PzDT9Qwp7fo9g7P3t7w6elq7nlcLJhAMqRCtswY24ejzR6qTCfPktIekwmFKIJX0CE0VLl3UqCiJRJwoQI/I0@O4a@/ "Julia 1.0 – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 20 bytes ``` $=>[arrange&=>lower] ``` [Try it](http://arturo-lang.io/playground?zqmp6w) [Answer] # [J](https://www.jsoftware.com), 9 bytes ``` /:tolower ``` Modernized J solution that uses a monadic hook. [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxUt-qJD8nvzy1CMK_6azJlZqcka-QpqAeV6fglZ-Rl1epUJ6Yk52aolCSkaqQkp-uUJIPZhYkFmXrKdTFqcN1OBYE5KQWq0OMWrAAQgMA) [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Simply sorts by lowercase ``` ñv ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=8XY&input=IkpvaG5ueSB3YWxrZWQgdGhlIGRvZyB0byB0aGUgcGFyay4i) [Answer] # [Java (JDK)](http://jdk.java.net/), 90 bytes Not the best Java answer, but i tried to use only inline Stream. Since the rules aren't clear regarding special characters, here are multiple solutions: ``` s->s.chars().boxed().sorted((a,b)->a%32-b%32).map(e->""+(char)(e*1)).reduce("",(a,b)->a+b) ``` returns the correct order for letters, but with special characters mixed in between: ``` aaddeeeghhhJkklnn.oooprtttwy ``` [Try it online!](https://tio.run/##bZDNTsMwDMfveworElLC2kjAjWnjPsGJI@LgNl7bNU1Kku5DaEduPAK83F5kZF2LhIQPtmX5b//sNW4wXav61HaZrnLINXoPT1gZeJ9MACoTyK0wJ3jEJlMYqxDtObjKFLDiQ@LFLNYPZ4UPGOKgoV1fwvzk04WXeYnOcyEzuyMVo7cuxIRjkol0gVd3t2kWnZANtpzSBWNTftYITtc3QkhHqsuJM5aMkmkmTrPz2oF/2L6xlQLaoB4BW3TYJCM37VrK42bx9xxHvtMB5gO1XPFe1t8Wm/Y@UCNtF2Qb24M2nI@DJL11qD2/TBAP7Pj1AeyeHb8/gYnpUP790T@wTXz5APvyCugKP8L1ZwBb2tKYPWxR16QglATKFhBsn0bOWjKABIBBb4hKEVFRluWyrrUx0lrbuhDCds9gRDmcfgA "Java (JDK) – Try It Online") --- Another solution (**98 bytes**) ``` s->s.chars().mapToObj(e->""+(char)e).sorted((a,b)->a.compareToIgnoreCase(b)).reduce("",(a,b)->a+b) ``` returns the correct order for letters, with special characters separated from the letters: ``` .aaddeeeghhhJkklnnoooprtttwy ``` --- ]
[Question] [ Most Unicode characters have full names, for example `”` is "RIGHT DOUBLE QUOTATION MARK". You can find a useful reference [here](https://www.fileformat.info/info/unicode/char/search.htm), just type in the character you want to find the full name of and look in the DESCRIPTION column. Your challenge is to write a program or function that outputs itself as a string of these. You can output as an array, or space/newline separated. # Scoring This challenge is scored in *characters* instead of bytes - Least characters wins! You can only use characters with descriptions other than `U+(Whatever)`, so `` and similar are banned. External resources *are* allowed, but those without are generally more interesting. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 37 characters ``` <print "<$_>~~.EVAL".uninames>~~.EVAL ``` [Try it online!](https://tio.run/##K0gtyjH7/9@moCgzr0RByUYl3q6uTs81zNFHSa80LzMvMTe1GCby/z8A "Perl 6 – Try It Online") Variation of the standard Raku quines using `print` to avoid the trailing newline and `.uninames` to convert to a list of character names. [Answer] # JavaScript, 440 bytes ``` f=a=>[..."f="+f].map(n=>({"(":(l="LEFT ")+(p="PARENTHESIS"),")":(r="RIGHT ")+p,"{":l+(c="CURLY"+(b=" BRACKET")),"}":r+c,"[":l+(q="SQUARE"+b),"]":r+q,"=":"EQUALS"+(s=" SIGN"),">":"GREATER-THAN"+s,"+":"PLUS"+s,"\\":"REVERSE SOLIDUS","\"":"QUOTATION MARK","&":"AMPERSAND",".":"FULL STOP",",":"COMMA",":":"COLON"," ":"SPACE","-":"HYPHEN-MINUS","|":"VERTICAL LINE"}[n]||"LATIN "+(n>{}&&"SMALL"||"CAPITAL")+" LETTER "+n.toUpperCase())).join("\n") ``` [Try it online!](https://tio.run/##HZDBbsIwEER/xdoDcpSQD0AykhtcYuE4qe1UqoBDoFC1oklKql6Ab6dDbjNvxru2v5q/ZtifP/vfadu9H@73o2jEfJ2mKR0Fxcdt@t30vBVzfiFOM34SZNRzYBTFvBdUSadsyJXXnqKEIjTOgpxe5mOlT@hCs1PM94Ky2pk3ivlOEHtyMlupQBHO3Gh2jvcJrcfijyD/UmMqxTuE20f4k5CgGSlw4zFhwASvl/axcY5g6ZQMyk1DLi3FQ0IxYGVqP5rNBs6pV@W8Yr40eoEAmIBf6jLIoEvLCulWoBNAWVToSruAT@Gfa2OYD2UFn8BnZVHIUT20KS00g/aVzBT0FDp/q3Jlp4W247IrEC4QdCYNM9oquq3b7fVKBtstw5va@eU2mZAvpDGEIJOVDtLgD4kZFfA8tNr0t6v7/nDOmuHAoyhKv7rPltOmpei@79qhOx3SU/fBjwjv/w "JavaScript (Node.js) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 642 bytes ``` f" "="SPACE";f"\""="QUOTATION MARK";f"."="FULL STOP";f";"="SEMICOLON";f"<"="LESS-THAN SIGN";f"="="EQUALS SIGN";f">"="GREATER-THAN SIGN";f"\\"="REVERSE SOLIDUS";f"-"="HYPHEN-MINUS";f x="LATIN "<>if x>"Z"then"SMALL LETTER "<>x else"CAPITAL LETTER "<>x;u=putStrLn.f.pure;s=id<>show;n=mapM u.s;main=n"f\" \"=\"SPACE\";f\"\\\"\"=\"QUOTATION MARK\";f\".\"=\"FULL STOP\";f\";\"=\"SEMICOLON\";f\"<\"=\"LESS-THAN SIGN\";f\"=\"=\"EQUALS SIGN\";f\">\"=\"GREATER-THAN SIGN\";f\"\\\\\"=\"REVERSE SOLIDUS\";f\"-\"=\"HYPHEN-MINUS\";f x=\"LATIN \"<>if x>\"Z\"then\"SMALL LETTER \"<>x else\"CAPITAL LETTER \"<>x;u=putStrLn.f.pure;s=id<>show;n=mapM u.s;main=n" ``` [Try it online!](https://tio.run/##nZDdboIwGIZvpemRHsANFEga7ZSs/Ehhycx3QiJEMgUikHn37KOdRNzZ0vagz9ufN885776Ky2Wsrm1z68k273M7aOqmOpHVyvHW67GkhLpUxXwjKCspUNwdsijlqR@FJODJ@4RtpG@ZlESlUTwBNl0Sgb@JZBROwEEghVJWuuchUf5OUxeHOGRcqhl5iHaJ4KlIlmcBMEnEh0iUICqS/jZTE7cQ7z/jvQitwA81I3f8DBuGhDpehVuPHml/LmqqAo4tpUjx@Sm8k@LSFXTDYz/li4ANbjv0qr/J2i7tdrgVrHOrk@N15@ab1e41bwMy2B275lXt1rQESrAhGFeALQAr45rY0pgJbZ3M1gxk5omHOQMdDZf2TOLq@WTQYE/jPxbnUqDzF5cmtXT07BOMUPg1Cg@lQI@gpcLSKsxa4dUr/EfsOP4A "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 68 characters Based on [this quine](https://codegolf.stackexchange.com/a/51011/64121). ``` s="from unicodedata import*;print map(name,u's=%r;exec s'%s)";exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWKa0oP1ehNC8zOT8lNSWxJFEhM7cgv6hEy7qgKDOvRCE3sUAjLzE3VadUvdhWtcg6tSI1WaFYXbVYUwnK/v8fAA "Python 2 – Try It Online") [Answer] # JavaScript (browser), 365 characters ``` (f=async _=>{i='';for(e of `(f=${f})()`)i+=await fetch(`https://unicode-search.net/unicode-namesearch.pl?term=${e}&.submit=Search`).then(r=>r.text()).then(s=>(/[a-zA-Z]/.test(e)?`LATIN ${/[a-z]/.test(e)?'SMAL':'CAPITA'}L LETTER `+e.toUpperCase():s.substr(S=s.search(/(?<=class\="name" (colspan\="."|lang\="en")>)/),s.slice(S).search(`<\/`)))+' ');console.log(i)})() ``` This took a really long time to write. Outputs ``` LEFT PARENTHESIS LATIN SMALL LETTER F EQUALS SIGN LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER Y LATIN SMALL LETTER N LATIN SMALL LETTER C SPACE LOW LINE EQUALS SIGN GREATER-THAN SIGN LEFT CURLY BRACKET LATIN SMALL LETTER I EQUALS SIGN APOSTROPHE APOSTROPHE LATIN SMALL LETTER F LATIN SMALL LETTER O LATIN SMALL LETTER R LEFT PARENTHESIS LATIN SMALL LETTER E SPACE LATIN SMALL LETTER O LATIN SMALL LETTER F SPACE GRAVE ACCENT LEFT PARENTHESIS LATIN SMALL LETTER F EQUALS SIGN DOLLAR SIGN LEFT CURLY BRACKET LATIN SMALL LETTER F RIGHT CURLY BRACKET RIGHT PARENTHESIS LEFT PARENTHESIS RIGHT PARENTHESIS GRAVE ACCENT RIGHT PARENTHESIS LATIN SMALL LETTER I SPACE EQUALS SIGN LATIN SMALL LETTER A LATIN SMALL LETTER W LATIN SMALL LETTER A LATIN SMALL LETTER I LATIN SMALL LETTER T SPACE LATIN SMALL LETTER F LATIN SMALL LETTER E LATIN SMALL LETTER T LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS GRAVE ACCENT LATIN SMALL LETTER H LATIN SMALL LETTER T LATIN SMALL LETTER T LATIN SMALL LETTER P LATIN SMALL LETTER S COLON SOLIDUS SOLIDUS LATIN SMALL LETTER U LATIN SMALL LETTER N LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER D LATIN SMALL LETTER E HYPHEN-MINUS LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H FULL STOP LATIN SMALL LETTER N LATIN SMALL LETTER E LATIN SMALL LETTER T SOLIDUS LATIN SMALL LETTER U LATIN SMALL LETTER N LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER D LATIN SMALL LETTER E HYPHEN-MINUS LATIN SMALL LETTER N LATIN SMALL LETTER A LATIN SMALL LETTER M LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H FULL STOP LATIN SMALL LETTER P LATIN SMALL LETTER L QUESTION MARK LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER R LATIN SMALL LETTER M EQUALS SIGN DOLLAR SIGN LEFT CURLY BRACKET LATIN SMALL LETTER E RIGHT CURLY BRACKET FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER U LATIN SMALL LETTER B LATIN SMALL LETTER M LATIN SMALL LETTER I LATIN SMALL LETTER T EQUALS SIGN LATIN CAPITAL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H GRAVE ACCENT RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER N LEFT PARENTHESIS LATIN SMALL LETTER R EQUALS SIGN GREATER-THAN SIGN LATIN SMALL LETTER R FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER X LATIN SMALL LETTER T LEFT PARENTHESIS RIGHT PARENTHESIS RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER H LATIN SMALL LETTER E LATIN SMALL LETTER N LEFT PARENTHESIS LATIN SMALL LETTER S EQUALS SIGN GREATER-THAN SIGN LEFT PARENTHESIS SOLIDUS LEFT SQUARE BRACKET LATIN SMALL LETTER A HYPHEN-MINUS LATIN SMALL LETTER Z LATIN CAPITAL LETTER A HYPHEN-MINUS LATIN CAPITAL LETTER Z RIGHT SQUARE BRACKET SOLIDUS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER T LEFT PARENTHESIS LATIN SMALL LETTER E RIGHT PARENTHESIS QUESTION MARK GRAVE ACCENT LATIN CAPITAL LETTER L LATIN CAPITAL LETTER A LATIN CAPITAL LETTER T LATIN CAPITAL LETTER I LATIN CAPITAL LETTER N SPACE DOLLAR SIGN LEFT CURLY BRACKET SOLIDUS LEFT SQUARE BRACKET LATIN SMALL LETTER A HYPHEN-MINUS LATIN SMALL LETTER Z RIGHT SQUARE BRACKET SOLIDUS FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER E LATIN SMALL LETTER S LATIN SMALL LETTER T LEFT PARENTHESIS LATIN SMALL LETTER E RIGHT PARENTHESIS QUESTION MARK APOSTROPHE LATIN CAPITAL LETTER S LATIN CAPITAL LETTER M LATIN CAPITAL LETTER A LATIN CAPITAL LETTER L APOSTROPHE COLON APOSTROPHE LATIN CAPITAL LETTER C LATIN CAPITAL LETTER A LATIN CAPITAL LETTER P LATIN CAPITAL LETTER I LATIN CAPITAL LETTER T LATIN CAPITAL LETTER A APOSTROPHE RIGHT CURLY BRACKET LATIN CAPITAL LETTER L SPACE LATIN CAPITAL LETTER L LATIN CAPITAL LETTER E LATIN CAPITAL LETTER T LATIN CAPITAL LETTER T LATIN CAPITAL LETTER E LATIN CAPITAL LETTER R GRAVE ACCENT SPACE LATIN SMALL LETTER E FULL STOP LATIN SMALL LETTER T LATIN SMALL LETTER O LATIN CAPITAL LETTER U LATIN SMALL LETTER P LATIN SMALL LETTER P LATIN SMALL LETTER E LATIN SMALL LETTER R LATIN CAPITAL LETTER C LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER E LEFT PARENTHESIS RIGHT PARENTHESIS COLON LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER U LATIN SMALL LETTER B LATIN SMALL LETTER S LATIN SMALL LETTER T LATIN SMALL LETTER R LEFT PARENTHESIS LATIN CAPITAL LETTER S EQUALS SIGN LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS SOLIDUS LEFT PARENTHESIS QUESTION MARK LESS-THAN SIGN EQUALS SIGN LATIN SMALL LETTER C LATIN SMALL LETTER L LATIN SMALL LETTER A LATIN SMALL LETTER S LATIN SMALL LETTER S REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK LATIN SMALL LETTER N LATIN SMALL LETTER A LATIN SMALL LETTER M LATIN SMALL LETTER E QUOTATION MARK SPACE LEFT PARENTHESIS LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER L LATIN SMALL LETTER S LATIN SMALL LETTER P LATIN SMALL LETTER A LATIN SMALL LETTER N REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK FULL STOP QUOTATION MARK VERTICAL LINE LATIN SMALL LETTER L LATIN SMALL LETTER A LATIN SMALL LETTER N LATIN SMALL LETTER G REVERSE SOLIDUS EQUALS SIGN QUOTATION MARK LATIN SMALL LETTER E LATIN SMALL LETTER N QUOTATION MARK RIGHT PARENTHESIS GREATER-THAN SIGN RIGHT PARENTHESIS SOLIDUS RIGHT PARENTHESIS COMMA LATIN SMALL LETTER S FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER L LATIN SMALL LETTER I LATIN SMALL LETTER C LATIN SMALL LETTER E LEFT PARENTHESIS LATIN CAPITAL LETTER S RIGHT PARENTHESIS FULL STOP LATIN SMALL LETTER S LATIN SMALL LETTER E LATIN SMALL LETTER A LATIN SMALL LETTER R LATIN SMALL LETTER C LATIN SMALL LETTER H LEFT PARENTHESIS GRAVE ACCENT LESS-THAN SIGN REVERSE SOLIDUS SOLIDUS GRAVE ACCENT RIGHT PARENTHESIS RIGHT PARENTHESIS RIGHT PARENTHESIS SPACE APOSTROPHE SPACE APOSTROPHE RIGHT PARENTHESIS LATIN SMALL LETTER C LATIN SMALL LETTER O LATIN SMALL LETTER N LATIN SMALL LETTER S LATIN SMALL LETTER O LATIN SMALL LETTER L LATIN SMALL LETTER E FULL STOP LATIN SMALL LETTER L LATIN SMALL LETTER O LATIN SMALL LETTER G LEFT PARENTHESIS LATIN SMALL LETTER I RIGHT PARENTHESIS RIGHT CURLY BRACKET RIGHT PARENTHESIS LEFT PARENTHESIS RIGHT PARENTHESIS ``` using unicode-search.net. -7 chars to fix small bug. No, that's not a typo, I actually *saved* characters fixing a bug which made all small letters "CAPITAL". [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~66~~ 64 bytes ``` “__import__('unicodedata').name(*'''“ ''')“jⱮṾ;ṪƊŒV€Y”jⱮṾ;ṪƊŒV€Y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5z4@Mzcgvyikvh4DfXSvMzk/JTUlMSSRHVNvbzE3FQNLXV1daAqBSClCaSzHm1c93DnPuuHO1cd6zo6KexR05rIRw1zsQn//w8A "Jelly – Try It Online") *-2 bytes by splicing and splatting instead of using `string`* This still feels... easily outdone. Probably using `v`. ``` “...“...“jⱮṾ;ṪƊŒV€Y” Operate on this list of three strings. Ṿ Get its string representation ; and concatenate Ṫ and pop its last element; Ɱ Ɗ for each character of that result j join the remaining two elements on it. ŒV€ Evaluate each as Python, Y and join the values on newlines. ``` In order to place a literal single quote inside the Python code and use it as such, we can't use `'\“'` because most other characters will either result in an unwanted incorrect escape sequence or an actual backslash and a `TypeError`, we can't use `"“"` because now we just have the same problem with double quotes, and we can't use `'''“'''` because `'''''''` parses as `'''''' '` resulting in a `SyntaxError`. `'''“ '''[0]` only breaks even with the previous version, but fortunately `unicodedata.name` can take an optional second argument--a default for if the character given does not have a name--so we can use the splat operator `*` to send the unwanted space there for two less bytes. [Answer] # JavaScript, ~~144~~ 102 bytes Needs to be run in the browser console from [this page](https://util.unicode.org/UnicodeJsps/character.jsp) as permitted [here](https://codegolf.meta.stackexchange.com/q/13938/58974). Returns an array of promises containing the character names as permitted [here](https://codegolf.meta.stackexchange.com/a/12327/58974). +12 bytes to fix a bug with spaces :\ ``` f=_=>[...`f=`+f].map(async c=>(await(await fetch(`?a=`+(c==` `?20:c))).text()).match(/me'>(.+?)</)[1]) ``` [Answer] # [Perl 5](https://www.perl.org/), 63 bytes ``` $_=q(say charnames::viacode(ord)for"\$_=q($_);eval"=~/./g);eval ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rZQozixUiE5I7EoLzE3tdjKqiwzMTk/JVUjvyhFMy2/SCkGrEglXtM6tSwxR8m2Tl9PPx3C@f//X35BSWZ@XvF/XV@4EdpQE4BipnoGhgA "Perl 5 – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 156 bytes ``` v->{var s="v->{var s=%c%s%1$c;return s.format(s,34,s).chars().mapToObj(Character::getName);}";return s.format(s,34,s).chars().mapToObj(Character::getName);} ``` [Try it online!](https://tio.run/##pY8/T4RAEMV7PsXkIgkYbhOjFdzRGO3UAmNjLOb2Fm5xdyE7sySXC58dAU0sLK3mz/vNm7wWB9y2x89J277zDO08i8DaiDo4ybpz4rqI/ojEXqFdJGmQCJ5QO7hEAH04GC2BGHkuQ6ePYGctqdhr17x/APqG0hUFePx5sXubuaxaPXffZFlCDftp2JaXAT3QfvPbxjKm@OZKFl5x8A5I1J23yAllt3cZpUKe0FOSCov9a/dyaJP7eYGSlc/zRvEzWpUW4@af91OxhqgF9r05Jy4Yky5ODyhPSXUmVlZ0gfO8nwOxcenCj9E4fQE "Java (JDK) – Try It Online") Takes a `null` input and returns a `Stream<String>`. ]
[Question] [ The `round` function in Python 3 will round values of the form \$k+\frac{1}{2}\$ (with \$k\$ being an integer) to the nearest **even** integer, which is apparently [better than the rounding method taught in school](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior/10825998#10825998) Your task is to recreate this functionality: write a program of function that given a (real) number as input, outputs that number rounded to the nearest number, using the same tie-breaking rule as [Python's round function](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhab02xzEnOTUhIV8qyK8kvzUjTyNCEyN63T8osUMhUy8xSKEvPSUzV0DY10DI00rbgUFAqKMvNKNNKUqjP1TWoVYkoUdO1AZHWaBlBAs1YJagTMEgA) ## Examples/Test-cases ``` -3.0 -> -3 -2.7 -> -3 -2.5 -> -2 -2.2 -> -2 -1.7 -> -2 -1.5 -> -2 -0.7 -> -1 -0.5 -> 0 0.0 -> 0 0.4 -> 0 0.5 -> 0 0.51 -> 1 1.0 -> 1 1.2 -> 1 1.4999 -> 1 1.5 -> 2 1.7 -> 2 2.0 -> 2 2.3 -> 2 2.5 -> 2 2.6 -> 3 ``` ## Rules * Please add built-in solutions to the community wiki * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution wins [Answer] # JavaScript (ES6), 30 bytes Uses the `Math.round()` built-in, then clears the least significant bit of the result if the squared fractional part of the original input is \$1/4\$. ``` v=>Math.round(v)&~(v*v%1==.25) ``` [Try it online!](https://tio.run/##Xc7BToMwGAfwO0/xZYm2daOBMjTTFE9608uO6gFZ2TCMzlJIjNEnMPHiUd/D59kL@AjYohkwSEh@fP/v3z7EdVwmKttot5AL0aS8qXl0FesVVbIqFrgmh6@4PqoPfM4pC0mjxGOVKYFHaTkiVIl4cZnlYv5UJNgjVMu5VlmxxISWmzzTeHRbmFgq1UWcrHAJPIJnByAXGm6gnoCsNNwBh/I/j9wIEbqON/i6Wt8LRSYmbR8lzDKk5kJn5k8ii1LmguZyie1kDMi8Y2jBeVt7Dujn@337@WG@CE4Bbb/eEDHrL6RxA@qZUjey1W7guIye7DnszKzZwH4/33qY9/pz37qbe47Xnt7jdMhwj/6OvuP3dy3ZkNPZbNZjr4o5f7fekfWrLIMhwyGPOwa/ "JavaScript (Node.js) – Try It Online") ### Explanation `Math.round` does *rounding half up*. We have 4 cases. Given \$k\ge 0\$: * \$2k+1/2\$ is rounded to \$2k+1\$. Clearing the LSB turns it into \$2k\$. Example: \$22.5 \rightarrow 23 \rightarrow 22\$ * \$2k+1+1/2\$ is rounded to \$2k+2\$. Clearing the LSB leaves it unchanged. Example: \$23.5 \rightarrow 24 \rightarrow 24\$ * \$-(2k+1/2)\$ is rounded to \$-2k\$. Clearing the LSB leaves it unchanged. Example: \$-22.5 \rightarrow -22 \rightarrow -22\$ * \$-(2k+1+1/2)\$ is rounded to \$-(2k+1)\$. Clearing the LSB turns it into \$-(2k+2)\$. Example: \$-23.5 \rightarrow -23 \rightarrow -24\$ [Answer] ### Builtins in various languages # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands/2649a799300cbf3770e2db37ce177d4a19035a25), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ò ``` Only works in the legacy version of 05AB1E, which is builtin in Python. The new version of 05AB1E, which is built in Elixir, will round away from zero. [Try it online](https://tio.run/##MzBNTDJM/f//8Kb//3WN9EwB) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/w5v@6/yP1jXWM9DRNdIzBxGmIMJIR9cQxDUEcQ1ALAMgywCozEDPRAfCNjXUMQQKGAIVG@qZWFpa6oBUg7QZAYWN9Ix1QIYZ6ZnFAgA). # C, 5 bytes ``` lrint ``` The [Linux manual page](https://man7.org/linux/man-pages/man3/lrint.3.html) lists this as being part of the C99, POSIX.1-2001, and POSIX.1-2008 standards. It can be used without a prototype for golfing since it returns `long`, unlike the 4-byte [`rint`](https://man7.org/linux/man-pages/man3/rint.3.html) which returns `double` and thus can handle the full range of `double` inputs. Both these and `nearbyint` use the current rounding FP mode, which is nearest-even by default on IEEE-754 systems, unlike [C's `round` function](https://man7.org/linux/man-pages/man3/round.3.html) which uses away-from-zero as a tiebreak (like Python 2's `round`). C++11 includes the C99 math library (which many C/C++ implementations already provided). Since you need prototypes anyway in C++, `std::rint` or just **`rint` 4 bytes** should be available after `#include <cmath>` ([cppreference](https://en.cppreference.com/w/cpp/numeric/math/rint)). # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 17 bytes ``` x=>Math.Round(x); ``` [Try it online!](https://tio.run/##NY69CsIwFEb3PsUdE6qlDk79WQQnu@jgHJO0XmiTkpuUSumzx4C4nAOHb/gkHSXJGAjNAI8PeT1VWTaH14gS5CiIYHZ2cGKCDf6dvPBJi0UFnUDDOGxZdg1G1sqmiT781PZNXJu2E/5d3G0wiq28ir11bBEOsCkrrE8Jec7hYg3ZURdPh17f0GjWM8zL4qw4T4/2PX4B "C# (Visual C# Compiler) – Try It Online") The build in Math.Round in C# already rounds to the nearest even number # [Factor](https://factorcode.org), 13 bytes ``` round-to-even ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU3P0GBPP3crhdzEkgy9tNK85JLM_LxihYKi1JKSyoKizLwSheLUwtLUvOTUYgVrLq5qBSM9UwVDIAbSBoZAlomlpaVCrUL00tKSNF2LtUX5pXkpuiX5uqllqXkQseWxQOMLFPQgvAULIDQA) # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 6 bytes ``` fround ``` [Try it online!](https://tio.run/##Jco7DoAgEATQnlNM6CF@wAISLwOuVkKInH9Ft3ozk6HSnsuc9MEBBKZW@p0ZUQVUpAbKvYIsrIbZocdnlKjUZP2BqmZhEVbBCV7YhNTG4P7ILw "Forth (gforth) – Try It Online") # [Haskell](https://www.haskell.org/), 5 bytes ``` round ``` [Try it online!](https://tio.run/##y0gszk7Nyfmvq6sQ878ovzQv5X9uYmaegq1CSj6XAhAUFGXmlSioKIDlFIz0TLGIGuuZ/v@XnJaTmF78XzfCOSAAAA "Haskell – Try It Online") From the [documentation](https://hackage.haskell.org/package/base-4.18.0.0/docs/Prelude.html#v:round): > > `round x` returns the nearest integer to `x`; the even integer if `x` is equidistant between two integers > > > # [Jelly](https://github.com/DennisMitchell/jellylanguage), 3 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` ær0 ``` [Try it online!](https://tio.run/##HYuxDYAwDARXSYuUWLaTgDIBQyBKGpSKjgnYhEUymOHdnN9n/3n0fpuN92KL45lWsy1l4hiS0uKsTv0pbsQNe2ZkxjtTAXytEoNACmpCpbWGWYG/prgpZaAC8/4B "Jelly – Try It Online") # [MMIX](https://en.wikipedia.org/wiki/MMIX), 4 bytes/1 instruction ``` ␗�␄� ``` The replacement characters are in order the output and input registers; Unicode control pictures have been used to encode unprintable characters. This is `FINT $x,ROUND_NEAR,$y`, which rounds a float to the nearest integer (half-even). # [PowerShell Core](https://github.com/PowerShell/PowerShell), 22 bytes ``` [Math]::Round("$args") ``` [Try it online!](https://tio.run/##XZDRaoMwFIbvfYqDhKEQi8a6YqEgjO1ubLRjN6UMZ08nw83ORDbofHaXxM4mnrvvP3@@hBzrb2x4iVUVFHWDPTmsTv32Phflbrlc1@3n3nNJ3rxx1@87x8k8B@TQzAviWUghiP0xYLPFNEhkwMyA2UGkj1jB5EioG5EZyEY4cqheYeLcxkk5iShcZJE6bCKzcZ6mqZ1IHTNwYSJTNhNjGxMbrynIv/LhF@7q5jYvyuDh9R0LASfdIQK5eM6rFikQ/DnKDe5hBeRlWDfI20rI4IocjLJebh83Ny0X9cdg3GWDUs2mLQrkXInOhgC/LheMPfdJGkErXVW2L1Cz/n/AWaQXndP1fw) # [PHP](https://php.net/), 20 bytes PHP's `round` has a third parameter "mode" that can be used with the constant `PHP_ROUND_HALF_EVEN` (value: 3) ``` <?=round($argn,0,3); ``` [Try it online!](https://tio.run/##JYxBCsJADEX3OUZxYaETkkyrDFXc9RTdFBXrZmaoen1jgpvP@5@X1LWqni7nrXzybb9btkfuqIvtqPfrWpo5N6OGiARB8OgxeAgE9speyYmMyDTCHv48MLANbDJjn1ICt/1MbBaM4M8ED99S38@SXxqmHw "PHP – Try It Online") # [Python](https://www.python.org), 5 bytes ``` round ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZLi_JL81Ig7JtuaflFChUKmXkKRYl56akausYGBjoKYMLIVNNKoaAoM69EI02pukJBX8HQwEDPoFZB106hOk0DLqBZq6QJMW3BAggNAA) # [R](https://www.r-project.org), 5 bytes ``` round ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhZLi_JL81Ig7JuqJTa6xamFGrrGOsY6ekammlzJSZl5KRolOsWJBQU5lUBGmqYmRPGCBRAaAA) # Rust, 25 bytes Using libmath ``` math::round::half_to_even ``` # [Thunno 2](https://github.com/Thunno/Thunno2), 1 byte ``` V ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVYmZm9vdGVyPSZpbnB1dD0tMy4wJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMC0zJTBBLTIuNyUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAtMyUwQS0yLjUlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwLTIlMEEtMi4yJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMC0yJTBBLTEuNyUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAtMiUwQS0xLjUlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwLTIlMEEtMC43JTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMC0xJTBBLTAuNSUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAwJTBBMC4wJTIwJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMDAlMEEwLjQlMjAlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwMCUwQTAuNSUyMCUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAwJTBBMC41MSUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAxJTBBMS4wJTIwJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMDElMEExLjIlMjAlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwMSUwQTEuNDk5OSUyMC0lM0UlMjAlMjAlMjAlMjAxJTBBMS41JTIwJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMDIlMEExLjclMjAlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwMiUwQTIuMCUyMCUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAyJTBBMi4zJTIwJTIwJTIwJTIwLSUzRSUyMCUyMCUyMCUyMDIlMEEyLjUlMjAlMjAlMjAlMjAtJTNFJTIwJTIwJTIwJTIwMiUwQTIuNiUyMCUyMCUyMCUyMC0lM0UlMjAlMjAlMjAlMjAzJmZsYWdzPUM=) # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` ṙ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJBIiwiIiwi4bmZIiwiIiwiMVxuMS41XG4yXG4yLjVcbjNcbjMuNVxuNCJd) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes Jelly's builtin is 3 bytes: `ær0` - round to nearest multiple of \$10^0\$, which employs Python's `round`. ``` Ḟ,ĊḂÞạÞ⁸Ḣ ``` **[Try it online!](https://tio.run/##y0rNyan8///hjnk6R7oe7mg6PO/hroWH5z1q3PFwx6L/OofbNd3//4/WNdYz0FHQNdIzB5OmYNIISBqCRQzBIgZgtgGIbQBSbqBnAiLAXFNDHQVDkKAhSJuhnomlpSWINgURQG1GIDkjPWMQYQoizGIB "Jelly – Try It Online")** ### How? ``` Ḟ,ĊḂÞạÞ⁸Ḣ - Link: float, X Ḟ - floor {X} Ċ - ceil {X} , - pair -> [floor(X), ceil(X)] Þ - sort by: Ḃ - is odd? Þ - sort by: ạ ⁸ - absolute difference {X} Ḣ - head ``` [Answer] # [J](http://jsoftware.com/), 7 bytes ``` 0".@":] ``` [Try it online!](https://tio.run/##Xc6xCgIxDIDh3acIXQ5BQ5JePVo4EAQnJ3dxEA9xufef6sEl0txQyveTlH5rwG6CsUAHByAoyzkiXO63a6WA51Aedb97vz4zPCOMMC0Xkg@CgwaxkLZBfODtCv9XeA1kE2ROrck@Yew9dZiN3Jpt2Siefc55LaIleQ4txV4zRk/djcpT/QE "J – Try It Online") Formats to zero decimal places and then evaluates back to number. # [J](http://jsoftware.com/), 14 bytes ``` <.@+1-:@~:4|+: ``` [Try it online!](https://tio.run/##Xc7BCsIwDIDhu08RvAyZC0naOlocDARPnnwBD@IQL76A@Op1sEaaHUr5fpLSV95iM8GQoIE9EKT5dAin6@Wcjzi23KXxm/ynTXm3edyfb7g5GGCaLyQbBPsSRENYB7GB1yv8X@ElkE6QOtQm/YTSW5ZhVnJt1mWlWPoY41KklGDZ1xR9Teksy64rPOQf "J – Try It Online") Evaluates `floor(x + 0.5)` unless `2*x%4 == 1`, in which case `floor(x)` is returned instead. ``` <.@+1-:@~:4|+: 4|+: 2*x%4 1 ~: != 1 -:@ / 2 + x + <.@ floor() ``` [Answer] # [R](https://www.r-project.org), ~~35~~ ~~25~~ 23 bytes *Edit: -2 bytes thanks to pajonk* ``` \(x)(x+.5-!x%%2-.5)%/%1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGK3Mqi_NK8FNulpSVpuhbbYzQqNDUqtPVMdRUrVFWNdPVMNVX1VQ0hsjdNS2x0i1MLNXSNdYx19IxMNbmg2jVKNLkSc3I0EFxbWxhLE6J5wQIIDQA) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 38 37 34 27 23 bytes ``` {*r-2!r*=/r:|1_:\x+0.5} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdzjkPwiAUAOD9/QrERHoI5SiaYjxW1s4k1aXuDMZE7W9XatJCl5f35Z29eRWeypUvjpU3b9EZ9yw50x+ACqhiHCFETyhEBVSy/cJ6tgyWiUXcPzrt53FdBM91Dny8HrFOqRcUEwWIeDZQpqybpokYrZLw/3qijFcFqpQ65W6mAgdgjejsZTNk9rwluHIO5yRbra3h5nrz9wcSOWT20OamZITgMIodsQDtgFz/S74IAEdm) -1 : Shuffle -3 : Shuffle -7 : Rework [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 61 bytes ``` ([02468])\.5$|\.[0-4].* $1 \b9+\. 0$& T`9d`d`.9*\. \..+ -0 0 ``` [Try it online!](https://tio.run/##JY2xDsIwDET3@46CSqtYdpoU/AX8AFtTKaAysHRAjPx7sMVyenc6@97Pz2u/t0N/ra1fOKb5sp4K5e5baOGQVhrQCcpDx0Lg7ohb1a1ulXSwoBCNQGBwa0EpI0zECJHOLtklIohbcctObMRWY0r4cxaIBWJloaSq8LafRYsjTfBnkWbYxg8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ([02468])\.5$|\.[0-4].* $1 ``` Remove the `.5` after an even digit, and any decimal less than `.5`. ``` \b9+\. 0$& ``` If there is an all `9`s integer part with a decimal part, prefix a zero. ``` T`9d`d`.9*\. ``` If there is a decimal part then increment the integer part. ``` \..+ -0 0 ``` Remove any decimal part and change `-0` to `0`. # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 46 bytes ``` ([02468])\.5$|\.[0-4].* $1 \d+\..+ $.(*__ -0 0 ``` [Try it online!](https://tio.run/##JY2xDsIwEEN3f0eRQqtYd2lSyBfwEU1VkGBgYUCM/Hu4E4tlW@/O78fn@bppP4TLtYdVUl7O27GxDN/GVWLeOGJQtPvUyAkDw7jviALpPVYWxJmCmHhyKS4JUT2qR3En5sQwYcbfF4VaoQYrc60VTvtZsjpxhj9LXGAbPw "Retina – Try It Online") Link includes test cases. Explanation: ``` ([02468])\.5$|\.[0-4].* $1 ``` Remove the `.5` after an even digit, and any decimal less than `.5`. ``` \d+\..+ $.(*__ ``` If there is still a decimal part, remove it and increment the integer part. ``` -0 0 ``` Change `-0` to `0`. [Answer] # [J](http://jsoftware.com/), ~~22~~ 21 bytes ``` <.@+&1r2([-AND)1=2|+: ``` [Try it online!](https://tio.run/##Xc6xCsIwEIDh3ac4HKylNuQuTUuCAUVxEgdXBwexFBfB2XePheYk1yGE7@cu5BWXqugheChgAxr8eGoFh@v5FLdqV63wQ@tbvb8cSwz0rXwsF8/H8Ia7gQD9eCktA6kuBeJg54FkwPkK/ldwCponNNvm1vwJZiOZhpGJuZGXmSTZOOemQqlYyS4n8WtMI5l2TWIbfw "J – Try It Online") Heavily inspired by Arnauld's approach, except checks for exact 0.5 by doubling and checking that the remainder mod 2 is exactly 1 `1=2|+:`. Then subtracts the adjustment bit `AND`ed with the standard round from the standard round. [Answer] # [R](https://www.r-project.org), 57 bytes ``` \(x,a=x%/%1)`if`(x-a<.5,a,`if`(x-a>.5|a%%2,ceiling(x),a)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3LWM0KnQSbStU9VUNNRMy0xI0KnQTbfRMdRJ1YDw7PdOaRFVVI53k1MyczLx0jQpNnURNTagBDiU2usWphRq6xjrGOnpGpppcyUmZeSkaJTrFiQUFOZVARpqmJldiTo4GkoCtbVF-KUgVzJwFCyA0AA) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes ``` {_x+0.5-1=4!2*x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdzr0OgjAQAOD9nqLUxILY2muphhp/1q7MTdAFdwdDYuTZtZhAy3K5L/fb2Xfbl1IYjqcqU5v+A7ADroUkhPAzCVEDV+KwsJmtglVijPtHp/0yrmPwXJcgx+sRq5RmQZyIgPFsoEpZ1XUdMVql4P/1RBWvCtQpTcr9TA0ewFls3XU95O6yZXTnPS1Ynq2clfZ2fz5eBAvI3bEpbCkYo2GUeuYAmoH47pd8AUxCRRc=) A near-port of my own J answer. [Answer] The [nearest-even rounding mode](https://en.wikipedia.org/wiki/Rounding#Rounding_half_to_even), aka Banker's Rounding, is the default for IEEE-754 math, so normal programs (which haven't changed the FP environment) on most ISAs including x86 can just use instructions that round a float to an integer-valued float, or convert to integer with the current rounding mode. (Most programs don't change the rounding mode away from the default.) This is basically just using built-ins, but I didn't want to clutter up the existing answer with a bunch of machine-code stuff and associated interesting stuff I wanted to write about x86. If people want to add sections for other ISAs, feel free, although most other mainstream ISAs have fixed-width instructions so it's always either a 2 or 4-byte instruction. For the convert-to-integer instructions, out-of-range inputs produce the most-negative 2's complement integer of whatever destination width, which Intel calls the "integer indefinite" value. (e.g. `0x80000000` for 32-bit.) For AVX-512 unsigned conversions, the "integer indefinite" value is all-ones, `0xffffffff` (e.g. from [`vcvtss2usi`](https://www.felixcloutier.com/x86/vcvtss2usi).) Rounding instructions that produce a number in the same format as the input don't have this problem. # x86(-64) machine code, x87 scalar math, 3 bytes Uses the rounding mode in [the x87 control word](http://www.ray.masmcode.com/tutorial/fpuchap1.htm), which defaults to round-to-nearest w. even as a tie-break. (at reset and `finit`, and in fresh processes under normal OSes). Input arg in `st0`, top of the x87 stack, result stored to an `int *` pointed-to by RDI (or EDI if the same bytes execute in 32-bit mode). None of the standard calling conventions even for 32-bit mode pass FP args in x87 registers; unlike the SSE part of the answer, you couldn't write a C prototype to describe it to a C compiler. ``` db 1f fistp DWORD PTR [rdi] c3 ret ``` Or to round to an integer-valued `long double` (modifying `st0` in place), [2-byte `frndint`](https://www.felixcloutier.com/x86/frndint) is `D9 FC`. # x86(-64) SSE2 or AVX scalar math, 5 bytes These use the current rounding mode in MXCSR, the SSE math control/status register, which is fully independent of the x87 FP environment. Both use the same 2-bit codes for four different rounding modes, ceil/floor/trunc and nearest-even. (The Python 2 / C `round()` rounding mode is not directly available in hardware on x86, so [should be avoided for performance reasons unless you specifically want it](https://stackoverflow.com/questions/485525/round-for-float-in-c/47347224#47347224). IIRC, ARM does have it in hardware, as well as IEEE standard rounding.) All the relevant SSE / SSE2 / AVX conversion instructions are 4 bytes long, whether encoded as legacy-SSE or AVX, except for conversion into an MMX register. SSE1 [`cvtps2pi mm0, xmm0`](https://www.felixcloutier.com/x86/cvtps2pi) is `0f 2d c0`, allowing for a total 4-byte function if you're willing to return a 32-bit signed integer in the bottom of `mm0`, which is a pretty inconvenient place for it and would need the caller to use longer instructions to store or do math with it. SSE1 `ps` instructions are only 3 bytes, but [`cvtps2dq`](https://www.felixcloutier.com/x86/cvtps2dq) involves packed integers so was new in SSE2 along with `cvtpd2dq` (packed-double vs. packed-single, converting to a double-quad-word of packed integers). SSE1 scalar instructions have an extra prefix, so SSE1 `cvtss2si eax, xmm0` is also 4 bytes, same as SSE2 `cvtsd2si eax, xmm0`. An AVX encoding of all of these is available with 2-byte VEX prefixes (plus opcode + modrm byte), again for 4-byte instructions, except there's no `cvtps2pi` (MMX destination.) ``` sse: # first arg in XMM0, return in EAX f3 0f 2d c0 cvtss2si eax,xmm0 # SSE1 c3 ret Alternatives: # float vs. double, and scalar vs. packed. f2 0f 2d c0 cvtsd2si eax,xmm0 # SSE2 scalar double to i32, note same 0f 2d opcode but different prefix from SSE1 scalar. 0f 2d c0 cvtps2pi mm0,xmm0 # SSE1 2 floats to 2 i32 in an MMX reg 66 0f 5b c0 cvtps2dq xmm0,xmm0 # SSE2 packed conversion 4 floats to 4x i32. cvtpd2dq (2 doubles to 2 i32) is the same size c5 f9 5b c0 vcvtps2dq xmm0,xmm0 # AVX encodings; different bits in the C5 ... prefix represent different combinations of prefixes. c5 fa 2d c0 vcvtss2si eax,xmm0 c5 fb 2d c0 vcvtsd2si eax,xmm0 ... etc. ``` (There are also truncating versions of these, like `cvttsd2si`, to implement C `(int)double` rounding semantics of truncation toward 0 without having to change the rounding mode like in the bad old days of x87 before SSE3 `fisttp`.) Implementing C `rint[f]` / `nearbyint[f]` (rounding to an integer-valued `double` [or `float`]) needs multiple instructions until SSE4.1 `roundsd` / `roundps` etc, which are 6-byte instructions (with register args and no REX). e.g. `66 0f 3a 0a c0 00 roundss xmm0,xmm0,0x0`. (roundss and roundsd have separate opcodes, instead of being distinguished by prefixes like SSE1 `addss` vs. SSE2 `addsd`). The instruction needs an immediate to specify the rounding mode: whether to override or not, and if so, which of the 4 modes to use, and whether to suppress FP inexact (precision) exceptions. See [`roundsd`](https://www.felixcloutier.com/x86/roundpd) documentation. An immediate of `0` selects rounding-control = from the immediate, with the `00` field being the nearest-even mode that's the default. (Like the "alternatives" above, I'm showing machine code + assembly of multiple instructions. You'd only ever use one, depending on the input format (float or double, scalar vs. packed).) ``` 66 0f 3a 08 c0 00 roundps xmm0,xmm0,0x0 # other than SSE1, the ps form isn't shorter. 66 0f 3a 0a c0 00 roundss xmm0,xmm0,0x0 66 0f 3a 0b c0 00 roundsd xmm0,xmm0,0x0 c4 e3 79 0b c0 00 vroundsd xmm0,xmm0,xmm0,0x0 # 3-byte VEX prefix needed for instructions in opcode "maps" used by SSE4 and later, i.e. with 3 prefixes such as 66 0f 3a c4 e3 79 08 c0 00 vroundps xmm0,xmm0,0x0 ... etc. ``` # x86 + AVX-512 not relying on the current rounding mode, 7 bytes **AVX-512 EVEX prefixes can override the rounding mode on a per-instruction basis**, for *any* instruction with scalar or 512-bit vector width, including when `vaddps` or whatever have to round their result to a representable float/double. (Not 128 or 256-bit vector width until [APX and AVX10.2](https://www.intel.com/content/www/us/en/developer/articles/technical/advanced-performance-extensions-apx.html) which finally stops caring about obsolete 32-bit mode so it can use more of the bits of the EVEX prefix, instead of having to slot in to only invalid-in-32-bit-mode encodings of some instruction.) Fun fact: out-of-order exec CPUs that support SMT (e.g. hyperthreading) already have to track the rounding mode on a per-instruction basis internally, because different logical cores could be using different rounding mode settings. So it makes some sense to expose this functionality to programmers. AVX-512 also allows for conversion directly [to unsigned integer, and to *packed* 64-bit integers](https://stackoverflow.com/questions/64592329/convertion-of-four-packed-single-precision-floating-point-to-unsigned-double-wor), not just scalar-only for conversions involving 64-bit signed integers in SSE/AVX (in 64-bit mode only). An [Intel manual from 2016](https://www.intel.com/content/dam/develop/external/us/en/documents/319433-024-697869.pdf) when AVX-512 was newish has some details in section 2.5.4 *Static Rounding and Suppress All Exceptions*, where it compares to instructions like `vroundps` and `vrndscaleps` which allow this via an immediate, vs. setting MXCSR. ``` avx512: 62 f1 ff 18 2d c0 vcvtsd2si rax,xmm0{rn-sae} c3 ret ``` The NASM syntax I used is `vcvtsd2si rax, xmm0, {rn-sae}`. The disassembly is from `objdump -drwC -Mintel`, so is using GAS's `.intel_syntax noprefix` style for the rounding override. Using an `eax` destination wouldn't save any machine code bytes, unlike with legacy SSE (separate REX prefix), or with AVX where `vcvtsd2si rax,xmm0` needs a 3-byte VEX prefix for a total length of 5 bytes instead of 4. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` NθI⊟⌊E⟦⌊θ⌈θ⟧⟦↔⁻θι﹪ι²ι ``` [Try it online!](https://tio.run/##FcqxCsMgFIXhvU/heAVTSqFTphIodLBkDxlMKu0F9Rr19vWtnuk/8O1fk3YyrtZniFxe7Deb4JDjaU4YCkwmF5gpgsaAnj1oE2F5OKKulJgsOgyf1qsSy33L5LjYrjnDoQTKhjS92RGgEtf2cJV9Y63D5Xyrw8/9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @JonathanAllan's Jelly answer. ``` Nθ Input as a number θ Input number ⌊ Floor θ Input number ⌈ Ceiling E⟦ ⟧ Map over both values θ Input number ι Current value ↔⁻ Absolute difference ι Current value ﹪ Modulo ² Literal integer `2` ι Current value ⟦ Make into list ⌊ Take the minimum ⊟ Pop the rounded result I Cast to string Implicitly print ``` 34 bytes for arbitrary precision: ``` ≔⪪θ.η≔⊟ηζI⁻IΣη∧⎇﹪IΣ粬‹ζ5›ζ5∨№θ-±¹ ``` [Try it online!](https://tio.run/##XY5BCoMwEEX3PYW4moBKW3DlSlx0U61gLxA0aCAmdpIU6uXTsXZROjAwvP9gfj9x7A1XIZTWylFDtyjp4JFEcRazJJpYcfgmrVlgIrQSalFqBxW3Dmqpvd3Pzs9kkFLqAe4CNccX1GbwyvwJZ9rGOLgKa2GlZ3m84QsK7gT@kBtCZbzeG6Vbo0aM5MCJfaYIIT1meUif6g0 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪θ.η≔⊟ηζ ``` Separate the integer and decimal parts. ``` I⁻IΣη∧⎇﹪IΣ粬‹ζ5›ζ5∨№θ-±¹ ``` Compare the decimal `>=` or `>` than `.5` depending on whether the integer is odd or even, and increment the absolute value of the integer if so. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 17 bytes ``` v=>v*(k=3e-324)/k ``` [Try it online!](https://tio.run/##Xc7BToMwGAfwO0/xZZe2bq1QNg2a4kmPXnZUD8jKxDGKhZEY4xuYePGo7@Hz7AV8BGzRbGWQNPnx/b9/eUzapE51XjW0VAvZZaJrRdwe4ZUIJQ35lByvOi2fNrmWeJTVI8K0TBZXeSHnz2WKfcIaNW90Xi4xYXVV5A0e3ZYmlil9maQPuAYRw4sHUMgGbqCdgNo0cAcC6v88ojEibJ1U@HqzvpeaTEzaPlqaZchwS87Nl1SVtSokK9QS28kYkHnH0EOIvvYC0M/3@/bzw5wIzgBtv94QMeuvpKMh800pjW01DT3K2emBZ3tzaz5w4OZ7D/O@Ow@s93Pf8/vbHU6HnB0w2DHwAnfXkg85jaLIoVPFvb@/3pG7VZbhkLMhT/YMfwE "JavaScript (Node.js) – Try It Online") ]
[Question] [ This sequence is defined as * Starts with 1, 2, 3 * The next element of the sequence is the first number greater than the previous three that is co-prime with each of the previous *3* elements in the sequence. + In other words, if the previous 3 elements are `a`, `b`, `c`, then the next is the first integer `n>c` such that `gcd(a,n)=gcd(b,n)=gcd(c,n)=1`. This sequence on OEIS: [OEIS](https://oeis.org/A062062) All elements below 100: ``` 1,2,3,5,7,8,9,11,13,14,15,17,19,22,23,25,27,28,29,31, 33,34,35,37,39,41,43,44,45,47,49,52,53,55,57,58,59,61, 63,64,65,67,69,71,73,74,75,77,79,82,83,85,87,88,89, 91,93,94,95,97,99, ``` You can either: * Take a number as input, then output the Nth element in the sequence. Either 0 or 1 based is fine. * Take a number as input, then output the first N elements in this sequence. * Take no input, output the sequence infinitely. [Inspired by a discussion in chat](https://chat.stackexchange.com/transcript/message/64204669#64204669) [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ 77 bytes *-1 byte thanks to @Bubbler!* Prints the 0-indexed `n`-th term of the sequence. Who needs `gcd` anyway? ``` lambda n:sum((v+(t+b''+v+t)*n)[:n])+1 v=b''*3 t=(b''+v[1:]+v[6:])*3 ``` [Try it online!](https://tio.run/##DcyxCsMgFEBRtJn8Cjff00UJdBD8ktRBadMGmpdgrdCvty53OtzzV18HzX0Nt/5Oe74nSf7z3QGagWqymhibuDLNVNSEi6eIxokWsmKMc6VnUQNkdRlkcT6OXn1EPY5HkSQ3kiXR8wHOWoteyLNsVGEFQux/ "Python 3 – Try It Online") If we look at the differences between each term in the sequence, they become periodic after the 7th term, repeating every 125th term. The periodic string is: ``` 22112231221122112222112231221122112222112231221122112222112241142112211221122312211221122221122312211221122221122312211221122 ``` The code simply attempts to construct this periodic string, plus the non-periodic bit at the beginning. It helps that the string naturally contains a lot of repetition, making compression relatively short. By the way, the unprintables in ASCII are `41142`, `1122`, and `3` in order of appearance. [Answer] # [Python](https://www.python.org), ~~81~~ 79 bytes ``` from math import* *a,d=1, while 1:a+=[d][:gcd(prod(a[-3:]),d)<2!=print(d)];d+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3_dOK8nMVchNLMhQycwvyi0q0uLQSdVJsDXW4yjMyc1IVDK0StW2jU2KjrdKTUzQKivJTNBKjdY2tYjV1UjRtjBRtC4oy80o0UjRjrVO0bQ0hxkJNh9kCAA) Prints the sequence indefinitely. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~43~~ 41 bytes ``` {{{y+/1<y(|!\)/x,y}[x*y*z]/z}\[x-3].1+!3} ``` [Try it online!](https://ngn.codeberg.page/k#eJwVjr1uwkAQBvt7igBS+Jtg9vbWe2tFCq2fAaMkDelTRBgCzx6n+bqZ+c7d7XYbt428jqvf2bBuLoz342Uzbq6n5nofjpcXPe1kO9N7Sk0SMorhVAIRRJGCGOJIkDNZyUZ2ciUHKiRVtKCGOhoUoSilUIzilMAyNmkNc6xiQTthrdIWWqN12sAFV7zgU9/xoGaqUo06/anUIIUQShTCCCciDSl1fbejkff+8PxY9W8s580wzNfL1WzRd/vu4/P76+dJ1in1j/Nh0af/+QMJcz05) -2 thanks to ovs. The original version had `(|!\|!\)/` for the GCD (because `(|!\)` alternates between `0,gcd` and `gcd,0` in the end). ovs suggested `y(|!\)/` which iterates exactly `y` times, which is valid because: * at each iteration, `x,y` becomes `y%x,x`, which strictly reduces the minimum of the two until one becomes 0 (except at the first iteration, because `x > y` at that point); the minimum is reduced at least `y-1` times * the above leaves the possibility that the minimum is reduced by 1 `y-1` times in a row, but it is impossible: after one reduction, the pair becomes `y-1,y`, and after one more, `1,y-1`, which is a reduction of more than 1 if `y >= 4`. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 59 52 bytes ``` {{{~1=(*|(*:)(|!\)/)y,x}[x*y*z](1+)/z+1}\[x-3].1+!3} ``` [Try it online!](https://ngn.codeberg.page/k#eJwNjjtOw0AQQPs9BUkkYjuPmNnZ8exYQqT1GXAENKGnQPmfnRzgfQ7j5XK5y1vTXZtubJvrYm779sTx9nHsTt1538im7c8buc0fxxfdb2Wz0FtKfRIyiuFUAhFEkYIY4kiQM1nJRnZyJQcqJFW0oIY6GhShKKVQjOKUwDL20BrmWMWC4YENylAYjMEZAhdc8YI/+o4HNVOVatTHT6UGKYRQohBGOBFpTmmcxi29fE6753szvbNe9vO8bNfNYjWNr+PX9+/P35O0KU33w241pX9XLT4P) -7 : peeking at @ovs’s solution suggested obvious golf [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~16~~ ~~14~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` λ∞+Dλ3.£P¿Ïн ``` -1 byte thanks to *@ovs*. Outputs the infinite sequence. [Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//8674oieK0TOuzMuwqNQwr/Dj9C9//8) **Explanation:** ``` λ # Start a recursive environment, # to output the infinite sequence # (which is output implicitly at the end) # Implicitly starting with a(0)=1 # Where every following a(n) is calculated as: # (implicitly push a(n-1)) ∞ # Push an infinite positive list: [1,2,3,...] + # Add the a(n-1) to each: [a(n-1)+1,a(n-1)+2,a(n-1)+3,...] D # Duplicate this infinite list λ # Push a list of all items thus far: [a(0),a(1),...,a(n-1)] 3.£ # Pop and only leave (up to†) the last three items: [a(n-3),a(n-2),a(n-1)] P # Take the product of this triplet: a(n-3)*a(n-2)*a(n-1) ¿ # Check the gcd (Greatest Common Divisor) of this product with each value `v` # in the infinite (duplicated) list: gcd(v,a(n-3)*a(n-2)*a(n-1)) Ï # †† Pop both lists, and only leave the values at the truthy††† positions н # Pop and push the first remaining item of this infinite list ``` Footnotes: * †: In the first two iterations, `λ` won't contain three items yet, so will be `[1]` or `[1,"2"]` respectively. This won't affect the output though, since it'll calculate \$2\$ based on just \$[a(0)=1]\$ and calculate \$3\$ based on \$[a(0)=1,a(1)=2]\$. * ††: The outputs are strings (except for the first implicit item) because of the `Ï` builtin. Not sure why it does that tbh. (You could add a `ï` to the footer if you prefer actual integer outputs: [Try it online](https://tio.run/##ASAA3/9vc2FiaWX//8674oieK0TOuzMuwqNQwr/Dj9C9/8Ov/w).) * †††: Only `1` is truthy in 05AB1E, so only the items at which `gcd(v,a(n-3)*a(n-2)*a(n-1))==1` will be kept with `Ï`. [Answer] # [J](http://jsoftware.com/), 40 bytes ``` {1&(]],_3&{.>:@]^:(3<1#.+./)^:_{:)&1 2 3 ``` [Try it online!](https://tio.run/##NdA7SwNBGIXhPr/iI8ImSybj3G8YEQQrK/tNCnExNoLa7Y9f3xEspnnOYXbOfqxbvZvl1GQnSow0zlHL48vz07rYYT9N6uKHRd@3h@nc9v7O3uiDvh3P7bK0cbDixK/jZr5@ff@kIictVolT4pVEJVlJUVKVWNRiNnAILInFHVWHO8xhjrrDPX2Pe/qezJN5POABD3jAAx7wyD2xfxOLWOSeiCf6CU/0E1kiS3jGM57x3B@KZ7xwT8ELVvrruafglX7FK/1KVslq32X6MNOXmT7N9G2mjzN/q/1m8/b6/in//@fYZN4e5KpTWX8B "J – Try It Online") 0 indexed, returns the selected element, though it generates all up to that element under the hood. [Answer] -10 from ovs/emanresu A -5 from Arnauld -3 from dingledooper # [JavaScript (V8)](https://v8.dev/), 64 bytes ``` for(A=B=C=D=j=1;;)A*B*C%j|D%j--||(j||print((A=B,B=C,C=D)),j=++D) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SMPR1snW2dbFNsvW0Npa01HLSctZNavGRTVLV7emRiOrpqagKDOvRAOkTgeoUgeoVlNTJ8tWW9tF8/9/AA "JavaScript (V8) – Try It Online") [Answer] # [R](https://www.r-project.org), ~~83~~ 71 bytes ``` a=3:1 repeat if(all(prod(a[1:3])%%2:a|(T=T+1)%%2:a))show((a=c(T,a))[4]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN90TbY2tDLmKUgtSE0sUMtM0EnNyNAqK8lM0EqMNrYxjNVVVjawSazRCbEO0DSEcTc3ijPxyDY1E22SNEB0gN9okVhNiHNRUmOkA) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 18 bytes ``` #eaYf!-iT>3Y1he|Y0 ``` [Try it online!](https://tio.run/##K6gsyfj/Xzk1MTJNUTczxM440jAjtSbS4P9/AA "Pyth – Try It Online") Outputs terms of the sequence indefinitely. ### Explanation ``` # implicitly assign Y = [] # # repeat until error |Y0 # short circuiting Y or 0 e # last element of h # plus 1 f # counting up from this number, find the first element which satisfies lambda T >3Y # last three elements of Y iT # map to gcd with T - 1 # remove 1 from this list ! # True if list is empty aY # append to Y e # print the last element of Y ``` [Answer] # [Julia](https://julialang.org), ~~84~~ 79 bytes ``` ~n=(i=A=1;while length(A)<n;if max(gcd.(last(A,3),i+=1)...)<2;A=[A;i]end;end;A) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NZAxbsJAEEV7n8KlrfxYmp3dnR0ZS_EJcgBEYcECGzkWwkZQcZE0NBwqF0kdR4HiF6PR_zPvf90_Tn3qbrf7adq-hu_369AUqWkbqs_71Me8j8Nu2hdtuRjqtM0_u0uxW2-qou_GqWjBJdJLQ2VVVeXC1G2zbOu0isOm_lNbPmJ_umE8x2Pe5FdPWbwc4nqKm3lcEgwYDoIABRGIQRbkQAJSGAPDMA5GYAKMggkZM9iCHVjACkuwDGthHazAKpyBm2MdnMAFOIWfbZ7hLbyDF3iFEIQhFjLfF4giGARGcAjzPwFBkSlBGWqhDipQxSp768YxHqf8SdXkT6TscEzDVPwvHvTPcn8B) Given \$n\$, returns \$[a\_1, a\_2, \ldots, a\_n]\$. The function `last(A,3)` works gracefully for vectors with less than 3 values. Substituting `A=[A;i]` for `push!(A,i)` saves 3 bytes. Incrementing `i` inside a function call saves 2 bytes. * -4 bytes thanks to MarcMush: replace `i=1;A=[1]` with `i=A=1` * -1 byte thanks to MarcMush: remove unecessary semicolon [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` FN«≔⊕↨υ⁰θW¬⬤…²⊕θ∨﹪θλ﹪Π…⮌υ³λ≦⊕θ⊞υθ»Iυ ``` [Try it online!](https://tio.run/##ZU47DsIwDJ3pKTI6UpD4jEzAxECpeoMQDKnkJm0@RQhx9pBIHZDwYj37/ZSWTllJKd2tY3AyQwx17K/ogHP2rhZ777uHyQ/lsEcT8AYH6RGiYCvOBRv5rlo8dUfIoLYB9kTQSvNA2Aj2qxoL@@LgbG@RLIyCUT7MqHF5qwDHlyI8ajtAixO6kpNJ2yIlXoad5fBfaa7RRK9LsQI@VeM6kx2lD9mE71Jar9Jyoi8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` numbers. Explanation: ``` FN« ``` Repeat `n` times. ``` ≔⊕↨υ⁰θ ``` Start with `1` more than the previous number, or `1` if there were no previous numbers. ``` W¬⬤…²⊕θ∨﹪θλ﹪Π…⮌υ³λ ``` While a common factor between the candidate number and the product of the last three numbers can be found... ``` ≦⊕θ ``` ... increment the candidate number. ``` ⊞υθ ``` Add the next element to the list. ``` »Iυ ``` Output the found elements. [Answer] # [Arturo](https://arturo-lang.io), 69 bytes ``` a:@0..3i:5whileø[drop'a 1print a\0while->1<>gcd@[i∏a]->i:i+1'a++i] ``` [Try it!](http://arturo-lang.io/playground?pDtU4O) (Modified to print the first `n` elements so the playground can actually show the output.) Prints the sequence indefinitely. ``` a:@0..3 ; assign [0 1 2 3] to a i:5 ; assign 5 to i whileø[ ; start infinite loop drop'a 1 ; delete the first element in a print a\0 ; print the (new) first element in a while->1<> ; while 1 is not equal to... gcd@[i∏a]-> ; ...the gcd of i and the product of a i:i+1 ; increment i (without mutation) 'a++i ; append i to a ] ; end loop ``` [Answer] # [J](https://www.jsoftware.com), 34 bytes ``` ($1 2 3,3((]+3<1#.+.)^:_{:)\])^:_~ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY89TsNAFIT7nGKVIGIrny3evl2_fVagQaKiok6gQFiIhsJQIXERGlNwCE6CuA2OQjGaKUbz8_H5NH0v27Aewnkf1oSz0M9o2nB5c3319foyNOV3WZ1IiEHRqtpvdCurdtPWt_3dW1_v9gfx_u_8qRfjIUiIKBmj4IggiiQkI4Y4MRKVmIlGLERHBZ0LEppRQ50kJCUlUiYZycmRPKdmspEL2emETukSXaYzOscEUyxhc7thTokUpWTKvKZQHBdc8YRn3HBfPNw_PochrMajqra7sQ5NH4bT9iKsduPx3jQd-Q8) Returns first n terms. Very inefficient because it computes the next term for every 3-window at every iteration. ``` ($1 2 3,3((]+3<1#.+.)^:_{:)\])^:_~ ( )^:_~ repeat (...) on n until it converges, also giving n as the fixed left arg (after 1 iteration, the value is always a length-n array starting with 1 2 3) $1 2 3,3( )\] compute the next term for every 3-window, prepend 1 2 3 and make it length n (]+3<1#.+.)^:_{: compute the next term for a window: ( )^:_{: iterate from the 3rd number until convergence: +. gcd with the 3 preceding terms ]+3<1#. if the sum is >3, increment ``` # [J](https://www.jsoftware.com), 34 bytes ``` 0{(]}.,](]+3<1#.+.)^:_{:)^:[&1 2 3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PY89TgNRDIT7nOIpkfKjfFnFz8_r5xXQIFFR0aINBSICGopAFXESmlBwCE6CuA2LgijG1lijGc_b--Phc9yk2TaddmlGWqduwKpJ51eXFx8vz9tV_R6v9_P-taGf90s9kUmzbBab7mbfDfN6Kikn_VN-LUa7XyMhoxhOJRBBFCmIIY4EOZOVbGQnV3KggipaUEMdDYpQlFIoRnFKYBkbXA1zrGJBK7RKW2iN1mkDF1zxgg_pjgc1U5Vq1OGbSg1CCCUKYYQTMbq7vX9K2-lZemgmuyPbpVX3fzrWOxyO-wc) Returns the nth term, 0-indexed. Maintains the next 3 terms in a loop. ``` 0{(]}.,](]+3<1#.+.)^:_{:)^:[&1 2 3 0{( )^:[&1 2 3 starting from 1 2 3, iterate n times and extract the first number ](]+3<1#.+.)^:_{: compute the next term }., prepend previous two terms ] ignore n in this function ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 118 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 14.75 bytes ``` W£λ¥nġΠṅ;+)T⁺⌐Ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI1PSIsIiIsIlfCo867wqVuxKHOoOG5hTsrKVTigbrijJDhuJ4iLCIiLCIiXQ==) [Answer] # [Haskell](https://www.haskell.org), 73 bytes ``` h n|n<4=n h n=head[x|x<-[h$n-1..],all(\d->gcd d x==1)[h$n-1,h$n-2,h$n-3]] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NVAxasNAECStirxhCxc2jEz29k53C1b6vCCFokJEciQkC2MrYIJ_ksZNyJuS1-RskWYYGGaYmc_vtjr2zTBcLl_v0zYNP08tjedxY_MxiSxvm6ouTufTJi3axZjyel2iGoblS50-vr3WVNMpz3k1i7iiuaGU5Rz4e3e_7Q7HiXIqEiKGgcDBI0DBDBawBTuwByuMgREYB-NhAoxCGNEnArEQB_EQhWVYgbWwDtbDKpyBi8EOzsMFOEV2M2aCzCJzyDwyhWd4gbfwsYOHVwSDIAgOIXYKCHp1KUMFaqEO6qFaJkkfJ_BDkuyqbox0f-jGiRZUjXXEqeob6iP56PbP3dTSMs9XNC9f0K7aU0vF9b1kvuX_7z8) [Answer] # [Raku](https://raku.org/), 51 bytes ``` 1,2,3,{first 1==(*Xgcd$^x,$^y,$^z).all,($z..*)}...* ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPvfUMdIx1inOi2zqLhEwdDWVkMrIj05RSWuQkclrhKIqzT1EnNydDRUqvT0tDRr9YDkf2uF4kSQ9ug4QwOD2P8A "Perl 6 – Try It Online") This is an expression for the infinite sequence of numbers. * `1, 2, 3, { ... } ... *` is a lazy sequence starting with 1, 2, and 3, and with successive elements generated by the brace-delimited anonymous function. The function mentions placeholder variables `$^x`, `$^y`, and `$^z`, so it takes the previous three elements of the sequence as arguments. * `first 1 == (* Xgcd $^x, $^y, $^z).all, ($z .. *)` finds the first number in `$z .. *`--that is, the numbers starting from the last number in the sequence going up to infinity--such that the `gcd` of that number with each of the last three elements in the sequence is 1. ]
[Question] [ Similar to [this](https://codegolf.stackexchange.com/questions/236301/swap-two-values-in-a-list). Input a list and rotate N numbers in it given their indices. The following example uses 1-indexing, but feel free to use either. In other words, take a list of indices and a list of numbers: ``` [1,2,3,4,5,6,7] [1,3,6] Separate out the elements at those indices: [ 2 4 5 7] 1 3 6 Rotate those left: [ 2 4 5 7] 3 6 1 Insert them back in [3 2 6 4 5 1 7] And there's your result! ``` ## Testcases ``` [4, 1, 3, 2], [1, 2, 3] -> [1, 3, 4, 2] [1, 2, 3, 4, 5, 6, 7], [1, 3, 6] -> [3, 2, 6, 4, 5, 1, 7] [5, 6, 7, 1, 2, 3, 4], [2, 4, 5] -> [5, 1, 7, 2, 6, 3, 4] [3, 2, 6, 4], [1, 3] -> [6, 2, 3, 4] ``` ## Rules * You can assume the N indices are given in order and they're distinct. * Default I/O rules apply, standard loopholes are banned. This is code-golf, so shortest code in each language wins. [Answer] # [R](https://www.r-project.org/), 35 bytes ``` function(a,i){a[i]=a[c(i,i)[-1]];a} ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNRJ1OzOjE6M9Y2MTpZIxPIi9Y1jI21Tqz9n6ZhaGWmZWigk6xhqGOsY6ap@R8A "R – Try It Online") [Answer] # [J](http://jsoftware.com/), 11 bytes ``` (1|.{)`[`]} ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NQxr9Ko1E6ITYmv/a3KlJmfkK2gYKBgpmGoqpCkY6igY6SgY6yiY6CiY6iiY6SiYK/g56SlEG4MlzGASQHXmsf8B "J – Try It Online") * `}` Amend... * `]` The right argument... * `[` At the indexes specified by the left argument... * `(1|.{)` With the current values at those indexes `{` rotated once `1|.` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes -1 byte thanks to @att. ``` RotateLeft~SubsetMap~##& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@z8ovySxJNUnNa2kLrg0qTi1xDexoE5ZWe1/QFFmXkl0WnS1oY6CkY6CsY6CiY6CqY6CmY6Cea2OAkgYKGZWGxv7HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 58 bytes ``` |a:&mut[_],b:&[_]|for w in b.windows(2){a.swap(w[0],w[1])} ``` [Try it online!](https://tio.run/##RY3BCoJAEIbvPcWfB1lhErUsMKwHEQlNhQVdxV3Zg/rsplvSZeYw3/dNP0i1VAJNxgVzMKIuFap4mbLIbgaVvFLKI3tdU9X20OACuau5KFotWeCMmSt11jGdeCnpxE@deQHuB5gOF92gECPxCQHhTLgQQsKVcEt3aP2CmsuNM/xfLvi7lJvuUUChESpm7zzB/iHOdul6LlQtjswao@dM2CZOD7Mt@qZpj5IprN68fAA "Rust – Try It Online") 0-based indexing. Changes the input array in-place. [Answer] # [Python 3](https://docs.python.org/3/), 54 bytes ``` def f(L,I): r=L[I[0]] for i in I[::-1]:r,L[i]=L[i],r ``` [Try it online!](https://tio.run/##JYw7CoAwEAX7nGJLhSf4FwI5QCA3WLbTYJooi42nj4rNwBQz533tRx5KWbdIsQrwtTWkLrDnVsRQPJQSpUyerW06sYrASdwHaHkDxx16DBgxYcYi4Pb1Scy/M6emfFWhLg8 "Python 3 – Try It Online") 0-based, in-place. Works for length 1 but not length 0 index list. [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` yy)w1YS( ``` Indices are 1-based. [Try it online!](https://tio.run/##y00syfn/v7JSs9wwMljj//9oQwMdBSMgNgZiEyA2BWIzIDY3iOWKNgSKA7mxAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L@yUrPcMDJY479LyP9oEx0FQx0FYx0Fo1iuaCDLCMhBsHQUgPKmOgpmOgrmEFGgkBmQBRUDa4YqBIoaQdQDWcZgYTOIMEhbLAA). ### Explanation Consider inputs `[10, 20, 30, 40, 50, 60, 70]`, `[1, 3, 6]` as an example. As usual, the stack is shown with the most recent element below. ``` yy % Take the two inputs implicitly. Duplicate them % STACK: [10, 20, 30, 40, 50, 60, 70] % [1, 3, 6] % [10, 20, 30, 40, 50, 60, 70] % [1, 3, 6] ) % Reference indexing: takes entries in first input indexed by the second % STACK: [10, 20, 30, 40, 50, 60, 70] % [1, 3, 6] % [10, 30, 60] w % Swap % STACK: [10, 20, 30, 40, 50, 60, 70] % [10, 30, 60] % [1, 3, 6] 1YS % Rotate 1 position to the right % STACK: [10, 20, 30, 40, 50, 60, 70] % [10, 30, 60] % [6, 1, 3] ( % Assignment indexing: overwrites the first input with the values from % the second at the positions given by the third % STACK: [30, 20, 60, 40, 50, 10, 70] ``` [Answer] # JavaScript (ES6), 48 bytes Expects `(list)(indices)`, 0-indexed. ``` a=>b=>a.map((v,i)=>b[j]^i?v:a[b[++j]||b[0]],j=0) ``` [Try it online!](https://tio.run/##TZDBbsIwDIbvfQofE2EKLayThtKd9hSWJzkd3VpBg2DqiXfvkjSF@ZT8/vzFSi@j3Jprd/ldD@7rOLVmElNbU0t@lotSI3ba36nnz@59fBOytFr1fL9b2jJjb7Z6OlAGQEB7hAJhh1AyAvlj6W8Mj/LpZhMbntkHbJ5LZMxeECqE1yTwWcXL3C5i1YIVAZsFaShmyRQE5Yw@BGlo0URsFjzVy8P/1g6bQxRUT33GWd6664c0P0qRIFjWYGpo3HBzp2N@ct@qVaKVjf84hN4Aayi0r@kP "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = main list b => // b[] = list of indices (0-indexed) a.map((v, i) => // for each value v at position i in a[]: b[j] ^ i ? // if b[j] is not equal to i or b[j] is undefined: v // leave v unchanged : // else: a[ b[++j] || // increment j and use a[b[j]], b[0] // or a[b[0]] if it's undefined ], // NB: because the indices are given in order, '0' // may only appear at position 0 in b[] and cannot // trigger the b[0] failover j = 0 // start with j = 0 ) // end of map() ``` [Answer] # APL+WIN, 19 bytes Prompts for inices then vector ``` n[i]←(n←⎕)[1⌽i←⎕]⋄n ``` [Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf150ZiyQp5EHJIBSmtGGj3r2ZkI4sY@6W/L@A5Vx/U/jMlQwVjADkkZA2kTBVMFMwZyLiwsA "APL (Dyalog Classic) – Try It Online") [Answer] # [Raku](http://raku.org/), 18 bytes ``` {@^a[@^i].=rotate} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2iEuMdohLjNWz7YovySxJLUWJOWQqGCrYKinZ26tkKbhkKijEG2go2Cko2Aaq2mtUJwIUvAfAA "Perl 6 – Try It Online") 0-based indexing. Changes the input array in-place. This is the same answer as my answer to the "swap two values in a list" question. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 8 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {1⌽@⍺⊢⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=qzZ81LPX4VHvrkddix71bq0FAA&f=M1QwUjBWSFMwUTAE0kZcINIMyDcEi5somAJ55lxGYFYahAeTA6tNA@kCipoAAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) A dfn submission which takes indices on the left, array on the right. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` IEθ⎇№ηκ§θ§η⊕⌕ηκι ``` [Try it online!](https://tio.run/##NUy9CsIwEN59ihsTOMG/ujhJQOggOLiVDEcSaLC92BhFnz5eBb/p@3c9ZZdoqPVMd5PGkdirCeEaMlP@KJOeXFSPcNMIx9KyD@85/1NJWnY5jIFL8OoUZf5rCxCi1ofFJUe5MPQoahJda9etENYIG4Qtwg6hQdhbhNkWr7G2Ll/DFw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation: ``` θ Data array E Map over values № Count of κ Current index η In index array ⎇ If index present then θ Data array § Indexed by η Index array § Indexed by ⌕ Index of κ Current index η In index array ⊕ Incremented ι Otherwise original value I Cast to string Implicitly print ``` [Answer] # [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), ~~242~~ 219 bytes ``` mod R is pr LIST{Nat}. ops r x : Nat Nat ~> Nat . var A B I J : Nat . var R X Y :[Nat]. ceq r(X A Y,I R)= X x(A I Y,R)if size(X)= I . ceq x(A I X B Y,J R)= B X x(A J Y,R)if size(X)+ s I = J . eq x(A I X,nil)= A X . endm ``` The result is obtained by reducing the `r` function with the two lists (given as Maude lists) with zero-indexing. It is assumed the indices are distinct and ordered. This solution only works for \$N > 0\$. It wouldn't be difficult to handle \$N = 0\$, but it would be expensive byte-wise. (It would require an extra equation.) ### Example Session ``` \||||||||||||||||||/ --- Welcome to Maude --- /||||||||||||||||||\ Maude 3.1 built: Oct 12 2020 20:12:31 Copyright 1997-2020 SRI International Sat Nov 6 01:42:43 2021 Maude> mod R is pr LIST{Nat}. ops r x : Nat Nat ~> Nat . var A B I J : Nat . var R X > Y :[Nat]. ceq r(X A Y,I R)= X x(A I Y,R)if size(X)= I . ceq x(A I X B Y,J R)= > B X x(A J Y,R)if size(X)+ s I = J . eq x(A I X,nil)= A X . endm Maude> red r(1 2 3 4 5 6 7, 0 2 5) . result NeList{Nat}: 3 2 6 4 5 1 7 Maude> red r(1 2 3 4 5 6 7, 2) . result NeList{Nat}: 1 2 3 4 5 6 7 ``` ### Ungolfed ``` mod R is pr LIST{Nat} . ops r x : Nat Nat ~> Nat . var A B I J : Nat . var R X Y : [Nat] . ceq r(X A Y, I R) = X x(A I Y, R) if size(X) = I . ceq x(A I X B Y, J R) = B X x(A J Y, R) if size(X) + s I = J . eq x(A I X, nil) = A X . endm ``` --- Saved 23 bytes by prepending `A` and `I` to the first list rather than passing as a separate parameter. This requires a new function `x`, but `x` can be declared in the same `ops` declaration as `r`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` İǓZ(n÷Ȧ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C4%B0%C7%93Z%28n%C3%B7%C8%A6&inputs=%5B0%2C2%2C5%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%5D&header=&footer=) ``` İ # Get the elements at those indices Ǔ # Rotate Z # Zip with the indices (n # Foreach ÷Ȧ # Assign that index to that value ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` èÀ¹ǝ ``` First input-list are the 0-based indices, second the full list. [Try it online](https://tio.run/##yy9OTMpM/f//8IrDDYd2Hp/7/3@0gY6RjmksV7QhkDbWMdEx1THTMY8FAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkVCa4FB1a@f/wisMNh9Ydn/tf5390dLSBjqGOUaxOtAmQNgayYnUUQIJGOqZAQaAUUNBEx1THTMccIgVSZQKUAgvpQBXAdQElgIYApYBCsQA). A minor alternative could be `è¹Áǝ`: [try it online](https://tio.run/##yy9OTMpM/f//8IpDOw83Hp/7/3@0gY6RjmksV7QhkDbWMdEx1THTMY8FAA). **Explanation:** ``` è # Get the values from the second (implicit) input-list at the indices of the first # (implicit) input-list À # Rotate those values once towards the left ¹ǝ # Insert them back into the second (implicit) input-list at the indices of the # first input-list # (after which the list is output implicitly as result) è # Same as above: get the values at the indices ¹ # Push the first input-list of indices again Á # Rotate the indices-list once towards the right ǝ # Insert the values at those indices back into the second (implicit) input-list # (after which the list is output implicitly as result) ``` [Answer] # [Python 3](https://docs.python.org/3/) + numpy, 34, 30 bytes (@Neil) ``` def f(L,I):L[I]=L[I[1:]+I[:1]] ``` [Try it online!](https://tio.run/##hYyxCsMgFEV3v8JR20fRpGlByAcI/oG8QWjSZsiLWDv49daSoUOHLhfu5ZwbS35s1Nd6m2Y@CwdWGuctji28Nni03mjEuqxxS5nTa42FhyenyFiDR4qnkFIowmvooIczDHCBK0rwqg0Dsv2UxbRQFk5@rUD3SWilVGMPe1Pw6dDJf9rQnF@mvgE "Python 3 – Try It Online") [Old version](https://tio.run/##hYxBCoMwFET3OUWWSRlKorWFgAcQcoPwF4Fq68L4Se3C06dWl110NfNg3vC6POdUl3LvBzkoj047HzpqfQinLlhH2MJZIirjxHNeZHpPvMr4komF2IR2iqwSn2POcYUKFhVqXNDgihshmI0b0loc94LzmBbl9e7uXkyPXlljjMbRDb6E6p/TaAT62ZQP "Python 3 – Try It Online") 0-based, in-place. Data L must be a numpy array, index I can be many things: range, array, list, but not tuple must be a list. I can be empty. [The fine print](https://codegolf.meta.stackexchange.com/a/10085/107561) [Answer] # [ErrLess](https://sr.ht/%7Eruan_p/Errless/), 44 bytes ``` 0ml0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}!r.M ``` A [macro](https://man.sr.ht/%7Eruan_p/errless_docs/reference.md#-procedures-amp-macros). ## Explanation ``` 0m {...} M { Macro identified by 0, takes two stacks as input: (list indices) } l0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}! { Reverse indices list } l0$: { Add (0 #-of-indices) to the top of the stack: (list indices (i N)) } Y {...} 1-[{ {...} y} { While } @;2/< { i < N // 2 } @;$@1+ { (list indices (i N) N i i+1) } 3G$-: { (list indices (i N) (i N-i-1) } 1G$ { (list (i N) indices (i N-i-1) } r { Swap the i-th and i-th from last elements of indices: (list (i N) indices) } $ { Swap: (list indices (i N)) } ; { (list indices i N) } $1+$ { (list indices i+1 N) } : { (list indices (i+1 N) } ! { Pop: (list indices) } r. { Rotate & halt (return) } ``` The biggest difficulty was reversing the indices list, as ErrLess rotates to the right, not to the left. If we had to rotate right the macro would be very easy: `0mr.M`. Exactly the same as in [this answer](https://codegolf.stackexchange.com/a/236560/91340), in fact. You can test it with the following program: ``` 0ml0$:Y@;2/<1-[{@;$@1+3G$-:1G$r$;$1+$:y}!r.M { Uses 0-based indexing. Appended "1-" to the end of the list of indices to convert to 0-based indexing } 1,2x3x4x5x6x7x 1,3x6x 1- 0"# a? { -> (3 2 6 4 5 1 7) } 4,1x3x2x 1,2x3x 1- 0"# a? { -> (1 3 4 2) } 1,2x3x4x5x6x7x 1,3x6x 1- 0"# a? { -> (3 2 6 4 5 1 7) } 5,6x7x1x2x3x4x 2,4x5x 1- 0"# a? { -> (5 1 7 2 6 3 4) } 3,2x6x4x 1,3x 1- 0"# a? { -> (6 2 3 4) } . ``` [Try it online!](https://tio.run/##1Vvrdts2Ev6vp0BspyJtSRbtJO0qUZo0t/VpEmcTd8@2slaHIiGJCUWyABRLdtOf@wD7iPsi2RkAJMGLZOfibdfnRBFBYOabKwYXJSsxi6PD7xL2cZs8pcKbUZ9MWDwnMyES3tvfnwaiw1lnJvZ/Zws3GiX7lLGQcj5idML3BaN0f@4G0X4g6Hx/HEyDSIwWUeDFPt1PFPl0SCdZkQfkDnkZv6fzMWXkoHvgNBrBPImZIC6bJi7jNH3mK55@FcGcNhpe6HJOgijpNQj8@XRCRqMgCsRoZHEaTmzVjn/42PFd4ZI@aTYbWf8pFWEQ0XJ3RsWCRcaoPeTe4cIPog6jri8H2YNe2xkWiElCLcKDc9pvOwbFYCIbyT3S7V1O3rJzKIA46zjoIZHh3YI8@Vt82RuWpWBV8tixHdLIYrZdwB@UNRHRKbB46oZghwokFNjJoZ7NgpAS1gk4T1wP9JOT2TRMsFWxI@gK@oKh2s2eBnDCFvTuWgo58ygWhA3AKjkI4kZ@1uaDP4oyMAVubz1tU9uSEmo0bavIyJRbFJqVJSAUQOMoH@JEySjolbRVezaCLj2aCGL93Q0X9AljMWuRo8inS/m9rFVFegB@CJEA7OET3KeBBg2TOLHCFglyXwTeAQ8iLtwIlAPvwoAL@zQlibqyrIDc75OufAjAY9FRQtsmMSMWPqs3Vjuwyb1@@rYaPWEH2QdKLgOmQkbpuz8Q2iAY1sLiYHxE1SLL/yEqhAOWWxqQFJ5J6Aohu2dg0HNqAGVJZRBqyYDgQH2dAA4KfkFCQxEdugTKvpWyoHbBUEwB8OJkZXKv41xW7kAOorbBt6DsUJH249HCSlONFHZkLavUJtBYI/dSc1cRNICxK8VwhQyXBYaTUcbRr3BskZXB1G2RMcZQlVHLbFzpRjO9u9LI4/roBE7nLXKmIOI3RHkeJIp/nixoiJQ20dBinhtiZgPXMwc258bA1bBGzUi7rDY1xb6kIPc4pL3Unc5c5oOaLjIqzXNI1c1fmq285QJbPpgtFrbYZsscW17olg/yc@x676rkV9jxZ3PoB2y5MFtsbLHMlhfYMs/ISyfg74Jk5MXzOYWkm7B42iKJgASrpeJ9nGpSh488gOGgddPXOmM78r03czHMkMoAiCilRqAsmYY9@cgFCyKcwrCzmmv1VAX9cnvBcJyB0lFp002VLpBD7my1bA1ee5qZ4ZxqSF9apeAjEi0McIqelPX/UNe/jf1NV7EAxh5gt29maFsajaF1rUNT60gOOvVlgdEikJD6L@Mo1f9a/Y7AH713mOGwy7BG0VpuihkZHBho9uRDP3PmjoajSZQsozhU7ONci3UsrQacMFLN5yAG3aEqYuQriN6yBJXqaa21NfAWGWElVRsJdmVAjntUeefFEQBf0IqPKOgdN0lwkkFAdtHDLNRc3tMmN0zt5pNrWVhZnxnKgVKrJe1ro8SSUW8dGqxHSjDKKPoY75my4QngX0KvEgjO5jBIM9yfJQ5SPFcPhPafLRBSEdZHwodPj4SWWvb8aQMiFfr/OiLEIgGmn1xj4jBqpYOXqrRZylpTiSNFKVKSY2rWAjW1KYuFK@SgOLm89K6nWB0QJ2nRCmBRH0AcFwTOGgpijuu5bKkUJxgAWUUfoLTMjabUclopOQMM1HOKAHy2ClSCYW7ydMUjm3HV0yi1doeSjl2jpSlzxxYH2oaa0vaRlTXJkEkdP12SIlY1AJcBcoSNQ7T@F8pZeugrMhh7uHhG18FkJLUIJdsi4j3iBx5otH0fO@gCdREV8o5s3N4mb04ePvqRHL968vrhydHxyzeN1E5yACSJHtSL2@RRHHlg/Qj@5esCaQiAroIiax@vaZe5rGh9VxtfLQtLL8fpy2JkFXLGADq5QzNaOe0Vu4zJHnHtslhLKdZD2eVSicL1El3q/1XIYQ3kQvcw7era68mEFZHuSpHe0ISyq5ipCt6tBY/jB645UyEKvVJ2jcyS4rghcbyKk1x/JfaF7g9k98eYtjwTNy4Y1FJbhqkabjdqlSFq6E4l3WcQRdmYONlo4JxN9kKFM7alIV1l9CxjpHaFZffLeZqk9X@15ENJ/jmNpmJW2B8s@QNuiZiaquydnawStXNWGtl2arg@N7iSeFISqsLZtE6BDpN0Xsu5o6iTbB8n180a66YzT97RyJUFbq8NbnV22MhTs9lki5akj9VGY01s54SHNeN3VIieuclnZ9FC@GHIjtPtasjmzwMBwR/yRpE1TIrNrnNweOv2nW@/@4s79mA@UZIs8IiB1wuDO7AwukWcO3W6Pm2qmQEqINcTJpV0XXh3fR1cYBTrul/OTHWs3ii1nbw@evmsUahUeVqp1qyj9boBRq/hO0DGnqqTPFQSHzi4TW0kZz25A71Mxw/ZSszmrgi8RhXpnppWfP8L7asRyt250J2PfRdrF4j55d7KxpnRrdNTW@lpMRZokmuD0N4AYaQjZGrGe5ngIiPYI@2lXQjHGpq7kuaLRSiCJFxdm1i7G8TaV5NU8D7wP78Akqtdd0L94H15jzXL6drhlvv7q8JLncN/oSxGFDyII53L9YjuBjk10/Xi3VQajv1FGH@xePPYv1S8m19ZOuC5XrrT09R60O1rWO8KEpq9PlHU1lVsaQqcZqZH8TxxWcDjqCYz9aUOnvy6cMNAXFsQtZ1da9nvr@z11rinKwvOiZi50bUiubcJyH1dt1FIVez6sdw3sKQW@yEQZwGnZJ88j6dQ/obkWFbv4BS8xoa/q@R6fHKlzPr75Zn1GzVdvXx8bUn1mw1J9TfJ/fj1tTH/bQPzf0rm/7hG7v9cVex9LGaU1RhWqJgIhAgpObkuRFjQLXed7u7uprA4kVh@CKbkam6GVJHm0r7U3RJTzFfXK@bBZilfZVK@urKUB3VC5sk3EiwOydMwPquxcEfy@6sbinJtqc/NCr3PZe@n6fnas1jEhep6fdErT@oG3WFdBVths1JK0Hum6/nU7c5/EqMLyejkLG6fuSsyXcOmeu5yVfoDVfgCkUxp2bi383Ur8AS3GIrb8KbV3wKGfiJ6JOmMRpwKvLw1GlkwP1u4Bdh@a2zgglu8TTcEc6kScVUBhrkAmTmuXYK9L5AgdftXLPaov2CUk2/IC9djcd3EZaktobRvcQ0H7L3LlnE5LtzgHGQ75EYoDtX@pqfWcFfS@lzCMhkXkc3drwXMwiN3IKfA2VdCt6U2M@ApU9y@1HDOco1byEIUoRcwTcw7FaoK/ZGudPHppSAhU@WE5pV7bsUTBK96giAPfHDrblC67zXXV9ZMUvnWEUqsrgThpuS8tEU1MFTG1@3VVTc0eXq2kNPdtC9b2bu5lCXGZbd01y@R956KjLAf7t@DvhLctNBQ5@rmhN5xQmPZYPG5jCISq31cEkdQm6a7WWnYHR3XRNn3Ospgrsq4b5fmsQTfWt6M6StEy/zEpLt0nC786ftDzdNuU526NpulWS@nTk4A2iQOYdLD4z/XmwX0PeUKsTunkOvdsKU1M6bYZ@JyqLeNw1OJqNnsvI2D6MrI8sOtuj09OwNuQD0iwRx8FacY6gPCgKsPmJJagM1zF0BbokGYFGQB8j4u@WHNZNDx0h0vItx3IOuvC8irJIwjSAzjhTBIvKe4VyQVI8COHsXz5vnCmxnUlDo6gG7Xixehv5ujJDwGDXK83BtPgPRkotYpAm@lKjYoSGxQ48KPAQILpjMBMoGS8LJZAk0xk0bB/MXcOaqHK7hHMGVETYG6iN5hH4McnUyQOyoJ/gd9CKl3JAQSwkzuQqwB9glZxQtQJGAWMXgypSGZMEqL4HLBgA4MYHhf9EbVj7dzP8YdyoZxjvweI1E5M5cHYRa3NwW@8herSfZIk6QuBmSK2342vrabJZeU/UyvKjpVAfLfJOQj1HSe2yHgISZbuKIvJBcd6lfclATzddIr2bWbyr/mvAvq@jz@ml1g1VXNgcHqkXlPobKfq8lYTu1C4KhEh9eWL8ve1VQDCWNYzlBponwR8Lp92sdqR4iOF9M/1L3S44wJ5Me@vpBOGbvkuoA@agbJJxEkWT37MnWPX85EAZ7agNJUhxaew8AsyCWfXuHSOraY9@vTe/ggO8tPnkfI18LfK5SOn3ECLBxB4y2aOKLmSXTW5KO@1X0ejTm/oa5oJ3i1EmaVGJQE6RPzyQwzGKRIaMCcK4/YPOZymVdhcjynLMZ7@3hQJVMdTw9G1UWg7IpPdi9oaJyc8vy9fOqTiw9K@Ucvnx7LkhKlhM4SvLK4dpHdUYvs7o5GPUkgH2U1TwWEHVRS@kNXDeUOsopkNGFSser0QxWI2Ylg8z//@nezmHd0lQHlebHOUAW7rDKAmqZulhZZTwWhhEurRErZkz8m6fCQ0sTqdJ3y0M9EL50JfwejEcL0OI45TS94Vb1jW/7WBcVKf/fSecimC5xCXsk36b0a3bHj@v7I1T2srfb7rRbZarc1H3iY0TDpb2XPaiyp@YP5PYij/hYXMIOOBJStW/YmTr7iJEXI@NAI7yRpx5mDyF@PYxPDtqkZNWURhl6BN61Av7L4UD8nknHVTNUE49HFNUX5H9LkqR7BAbRyKvVZu92GxEkeHT9@QiCFwmPTXMZweVrvg9PAYgO6n0bG6@zSO/QrFcaKODgU5Eg66N06KJXeFOjSwa2D3rDmly2hvKNfc4lNUSXgfqeCkHW019AvCPz6yZufnp8UBC6kw9Rt5SdoUbo3azabH7vzsLvT@/nB3YP9e057cPHg7s4DZ@/w2U675zzbYTt3d5y9nd7qww3WefHxgvzEQYfd9tjlUNMF@MsWsGJH31CBpi2nvQXllMyHeFkRKkL8KlMufMdK1cPCO5bzGMUfhMUVenjh22kdLA@Xt5a3l3eW3y6J0zqEL8Rpk@7WNnG/Jxd4b8g6JAfkDrlFbhOHfGvjuFstB8Yd4AgkUBnhkEPof2B/CY/bLezvLNVoctBCEpVxsr8cCxzluEPgdwdHIKdK/zvQN@3ZaYBt9Cr8438B) [Answer] # [Ruby](https://www.ruby-lang.org/), 46 bytes ``` ->a,i{eval"a[#{i*B='],a['}]=a[#{i.rotate*B}]"} ``` [Try it online!](https://tio.run/##XZBRa8MgFIXf/RV36YNQbgNJuwwGdlDYa9d364NrLQvb0uCykmH87akaJbAXPff4nXNB/fv@N17YuNpKrI26ya9M8oWplztGBUpOrWDByPW1k51a7qzI7MgJcL5BKBDWCKVA4E6WborSuRv/INCT8S14jwgVwtPMVV6uA1ElovDElI188GKJD5QT6mXkU0MgpuzcmtYJ5NXcI4jIlTx9mEFqjfW5/0HVt@rUqfNAwM/MH/m3bM3QD/2qsARaXTcdZAvjMhbc1zjCAtsem4zAhacm8Z@EcDOWNsAL0OsnhWeg@7fD6wO1x8Z32PEO "Ruby – Try It Online") Lambda: modifies *a* by *i* indexes, constructs an expression like for example: *a[1],a[2],a[3]=a[2],a[3],a[1]* and evaluates it. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 114 bytes ``` (\d+).*$ $&,$1 \d+(?=.*$) $* \d+(?<=((,)|.)*)(?=.*¶(1*,)*(?<-2>1)*(?(2)$),(1)*)(?<=(?=(?<-4>\d+,)*(\d+)).*) $5 1G` ``` [Try it online!](https://tio.run/##JY0xDsJADAR7v8NCttlE8ZGjyiUln6AACQoaCkSZd/EAPnb4QrerGXtf9/fjea1Vzre99sbEO7BTNFlKdCW2f5uKCHTt1XRD34@4QS1Il2ZvQZKyQnxTwl9Kg@Mc901sE7ERLzP56VLrAEfCASMyjjREzj8 "Retina 0.8.2 – Try It Online") 0-indexed. Explanation: ``` (\d+).*$ $&,$1 ``` Duplicate the first index and append it. ``` \d+(?=.*$) $* ``` Convert all of the indices to unary. ``` \d+ ``` Match an array element... ``` (?<=((,)|.)*) ``` ... calculating its index... ``` (?=.*¶(1*,)*(?<-2>1)*(?(2)$),(1)*) ``` ... where that index exists in the list of indices, capturing the next index... ``` (?<=(?=(?<-4>\d+,)*(\d+)).*) ``` ... capture the array element at that index... ``` $5 ``` ... and replace the original element. ``` 1G` ``` Delete the indices. [Answer] # [Zsh](https://www.zsh.org/), 60 bytes **Input**: values as arguments, indices on stdin separated by whitespace. 1-indexed. ``` b=(`<&0`) for x;{((k=b[(I)$[++i]]))&&x=$@[b[k%$#b+1]];<<<$x} ``` [Try it online!](https://tio.run/##LY1BCoMwFET3OcVAU/ODFGq0dmEC3fYMISApFYsLoXYRKp49jdrV/Hkzw/9OfexI0vT84BSiN9Tq7NxK1o1vhGYmGoy3dJfc5vnLOSmzLBh@s94OR37weeFco7XmYYn7qIACMVGlo4QSECsoBdsVFS6ocd14iTrxzeOfJq7WTuJpnZJqbwomZ9aBmwLrN8Wej36EMMYItsQf "Zsh – Try It Online") ``` b=(`<&0`) # split stdin on whitespace for x;{ # for x (implicit 'in "$@"') ((k=b[(I)$[++i]])) && # If we find $x's index in the array $b x=$@[b[k%$#b+1]] # then update $x to be the elemnt at index $k + 1 (wrapped) <<<$x # output the element $x } ``` [Answer] # TI-Basic, 55 bytes ``` Prompt A,I ʟA(ʟI(1→F For(I,2,dim(ʟI ʟA(ʟI(I→ʟA(ʟI(I-1 End F→ʟA(ʟI(dim(ʟI ``` `ʟA` is manipulated in-place. Indexes are 1-based. [Answer] # [Uiua](https://uiua.org), 6 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ⍜⊏(↻1) ``` [Try it!](https://uiua.org/pad?src=ZiDihpAg4o2c4oqPKOKGuzEpCgpmIFswIDEgMl0gWzQgMSAzIDJdCmYgWzAgMiA1XSBbMSAyIDMgNCA1IDYgN10KZiBbMSAzIDRdIFs1IDYgNyAxIDIgMyA0XQpmIFswIDJdIFszIDIgNiA0XQo=) 0-indexed. ``` ⍜⊏(↻1) ⍜ # apply one function 'under' another ⊏ # at the given indices (↻1) # rotate left by one ``` ]
[Question] [ When making a Minecraft data/resource pack, you need to include a `pack.mcmeta` file, which specifies information about it. `pack.mcmeta` contains a description, but it also contains a `pack_format` number, which tells Minecraft which versions this pack is for. Your task is to take a version string, and output what `pack_format` number matches the string. Your input must be a string, and you can assume it's either `1.x` or `1.x.y`. As of when this challenge was posted, the conversion goes like so: ``` 1.6.1 - 1.8.9 -> 1 1.9 - 1.10.2 -> 2 1.11 - 1.12.2 -> 3 1.13 - 1.14.4 -> 4 1.15 - 1.16.1 -> 5 1.16.2 - 1.16.5 -> 6 1.17 -> 7 ``` These are all the possible inputs, and what they need to be mapped to: ``` 1.6.1 -> 1 1.6.2 -> 1 1.6.4 -> 1 1.7.2 -> 1 1.7.4 -> 1 1.7.5 -> 1 1.7.6 -> 1 1.7.7 -> 1 1.7.8 -> 1 1.7.9 -> 1 1.7.10 -> 1 1.8 -> 1 1.8.1 -> 1 1.8.2 -> 1 1.8.3 -> 1 1.8.4 -> 1 1.8.5 -> 1 1.8.6 -> 1 1.8.7 -> 1 1.8.8 -> 1 1.8.9 -> 1 1.9 -> 2 1.9.1 -> 2 1.9.2 -> 2 1.9.3 -> 2 1.9.4 -> 2 1.10 -> 2 1.10.1 -> 2 1.10.2 -> 2 1.11 -> 3 1.11.1 -> 3 1.11.2 -> 3 1.12 -> 3 1.12.1 -> 3 1.12.2 -> 3 1.13.1 -> 4 1.13.2 -> 4 1.14 -> 4 1.14.1 -> 4 1.14.2 -> 4 1.14.3 -> 4 1.14.4 -> 4 1.15 -> 5 1.15.1 -> 5 1.15.2 -> 5 1.16 -> 5 1.16.1 -> 5 1.16.2 -> 6 1.16.3 -> 6 1.16.4 -> 6 1.16.5 -> 6 1.17 -> 7 ``` This is code golf, so the shortest answer wins. Good luck! [Answer] # JavaScript (ES6), ~~ 43 ~~ 42 bytes ``` s=>([,x,y]=s.split`.`,x*x+x*3+~~y)/51^x>16 ``` [Try it online!](https://tio.run/##TdJNToNAFAfwfU8xaZow09KxfKMNuKoXcFlrIHxUDIHKIKFp2hOYuHGp9/A8vYBHQMoU3mzIL2/@897LhFe/8llQJLtynuVh1MROwxwXr@Va3m8cRtkuTUqPenI9rWf1VJudTntyYyjPtauYje@sN8sientPighLMZMILSI/fEjS6HGfBXhBaJk/lkWSbTHhvfD4KRsTGufFyg9eMEOOiw4jhNaoklERMbRBDmJ9Fs1dNCbL9jzIM5anEU3zLfYmh4ru/HCVhdgkxzYzOcS4IkeEOZDjdL3ukfT3@3n@/mq/ErpD0vnnQzoSr@14JI1CTapcJiijC1Wg3tOCqiVWDaAJtIA28BaoLHoP5zasYMMwm2pAHWgATaAFFPoOczuoF/BZnCpQA@o9@apccK31cE/pqlonKlodLEhIqEJC43WdWx2sg4SELib42ldDvnsioxO/ebU62AQJiesPYHJrgnXBxuDu0a1/ "JavaScript (Node.js) – Try It Online") ### How? Given an input string `1.x.y`, we compute: $$\left\lfloor\frac{x^2+3x+y}{51}\right\rfloor$$ Because we're using `~~y`, we implicitly assume \$y=0\$ if the input string is just `1.x`. This gives the correct result for all versions except the last one, which gives \$6\$ instead of \$7\$. This is fixed by XOR'ing with \$1\$ if \$x>16\$. [Answer] # JavaScript (ES7), 31 bytes ``` s=>s.slice(2)**2/45+.2|s[3]%1.2 ``` [Try it online!](https://tio.run/##TdJdToNAEAfw955i0tSw29pVlk811Kd6gT7WJiV8VAyByiKJqdzAxBcf9R6epxfwCAhsy@wL@WX2PzuTDc9@5YugSPblPMvDqIm9RngLwUSaBBHhdDrlV6Y1Y/xdrI3Nhc54U0Qvr0kRES0WGmVF5IcPSRqt3rKAXFNW5quySLIdoUzs06Qk48dsTFmcF0s/eCICvAUcRgBrqC6hiARswANxzsJ8AWN6154HeSbyNGJpviPbyaFiez9cZiGxad1mJoeYVLQGIgGe1991D9rf7@fx@6v9anAL2vHnQ4MZkD407zK0ptt2QE0bndlM7wbqo44caZ7pYNVRqxbSRjpIF3mD1K/PHs5dXMHFYS4zkCbSQtpIB6ncO8ztwTvIWZIcaSDNM@WqUtjWeujT@6rRi6nmgxUpCa4kDFk3pflgE6UkTDUh1z4Z8/0TWb1k58l8sI1SEqcfwJY2FJuKrcH9ozv/ "JavaScript (Node.js) – Try It Online") TIO setup is based on Arnauld's answer. Ignore the `1.` part and treat the input as a floating point number. For example, `1.16.1` becomes `16.1`. This formula (find out by some brute force search) works quite good (48/52 correctness). $$\left\lfloor\frac{s^2}{45}+0.2\right\rfloor$$ And with some manually fix... It finally works. So if you are interesting in how it works: I don't know why it work either. [Answer] # Excel, ~~46~~ 44 bytes *-2 bytes change first item from 6.1 to 0* ``` =MATCH(MID(A1,3,9)*1,{0,9,11,13,15,16.2,17}) ``` Since they are all 1.x or 1.x.y, this basically matches everything from the 3rd character on. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ṫ3V×⁵>“Ym²Ɱƙʋ‘S‘ ``` [Try it online!](https://tio.run/##TdI9asNAEAXgPqdwG3AU74925caXCAhyADfBPkAKg1y5SOnCNiRVcGUwOFiFSScTF7mF9iJraUfaN4XgY@atZlj2bTqbvXtfXw4qv27cspy44vN1Xv240/G2@/9wxfal@Xz9e67Kv3V9@W76g6fJwBVf19UwX1T7av/86L1ITCLahnhoKUHd06JqeTUFDWjBDByDYtQ79jOskGFYlihQgyloQAuy/8a5AbIFzSJKUIG6J61KwrHG8ZwIVRWUcMtoJpaQLKGorskyWkMsoXmC1u6MfLiiNIhOdpbRBmKJ7gEYsmLWzGl0uHR7Bw "Jelly – Try It Online") ``` ṫ3V×⁵>“Zn³Ɲɱȥ‘S‘ Main Link; take the string as required ṫ3 Remove the first two characters V Eval it ×⁵ Multiply it by 10 >“Zn³Ɲɱȥ‘ Compare (>) to each of [89, 109, 130, 149, 161, 169] S Sum ‘ Increment ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of [hyper-neutrino's solution](https://codegolf.stackexchange.com/a/225918/58974) so be sure to upvote them too. ``` Ò"Ym¡©"¬mc x<¢*A ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0iJZbYKVoakirG1jIHg8oipB&footer=W1RnV/opJz1VIih7Z1ZnVLApZ2BwhnNmYWlsYPI0fSkiXbg&input=WyIxLjYuMSIsIjEuNi4yIiwiMS42LjQiLCIxLjcuMiIsIjEuNy40IiwiMS43LjUiLCIxLjcuNiIsIjEuNy43IiwiMS43LjgiLCIxLjcuOSIsIjEuNy4xMCIsIjEuOCIsIjEuOC4xIiwiMS44LjIiLCIxLjguMyIsIjEuOC40IiwiMS44LjUiLCIxLjguNiIsIjEuOC43IiwiMS44LjgiLCIxLjguOSIsIjEuOSIsIjEuOS4xIiwiMS45LjIiLCIxLjkuMyIsIjEuOS40IiwiMS4xMCIsIjEuMTAuMSIsIjEuMTAuMiIsIjEuMTEiLCIxLjExLjEiLCIxLjExLjIiLCIxLjEyIiwiMS4xMi4xIiwiMS4xMi4yIiwiMS4xMy4xIiwiMS4xMy4yIiwiMS4xNCIsIjEuMTQuMSIsIjEuMTQuMiIsIjEuMTQuMyIsIjEuMTQuNCIsIjEuMTUiLCIxLjE1LjEiLCIxLjE1LjIiLCIxLjE2IiwiMS4xNi4xIiwiMS4xNi4yIiwiMS4xNi4zIiwiMS4xNi40IiwiMS4xNi41IiwiMS4xNyJdClsxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwxLDEsMSwyLDIsMiwyLDIsMiwyLDIsMywzLDMsMywzLDMsNCw0LDQsNCw0LDQsNCw1LDUsNSw1LDUsNiw2LDYsNiw3XQotbVI) (Includes all test cases) ``` Ò"..."¬mc x<¢*A :Implicit input of string U Ò :Negate the bitwise NOT of "..." :String containing the characters at codepoints 89, 109, 130, 149, 161 & 169 ¬ :Split m :Map c : Codepoint x :Reduce by addition < :After checking each is less than ¢ : Slice the first 2 characters off U *A : Multiply by 10 ``` [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), [69 bytes](https://tio.run/##LZDdasMwDIXv@xSilBKzTtTxXwxeHmM3Y4wNEmgZSUloRyl79tQ@ykW@Ix3pyJBLN/36Zb7@UE/V7qboQcvHyye9d9N8Ggceuj/YKbVvKVU3zf6QEQu0Bg3oQM81NKjlf1Ptvg77PlMpPo@nodrSa0tbxfP3nfpxopSvsabCGrSZAXVYawd6MIANGEF9zFKMBmcaRBs2oAUd6MEAyn45gA/JiGREMiKJ0/qIaZYy1qg1rwJLIFYtlpHOSIdbViy7WngmC2YOkAUnCx5gvZE/Kp0RsSJIhXZ5Ag "Perl 6 – Try It Online") ``` [+] Version.new($v) <<>=<<(v1.6,v1.9,v1.11,v1.13,v1.15,v1.16.2,v1.17) ``` Like Perl, Raku has native support for version string comparison. See [Version](https://docs.raku.org/type/Version) for more info. **Explanation** * `Version.new($v)` converts from `Str` to `Version` type (it's a shame `v$v` doesn't work) * `<<>=<<` hyper-operator converts major versions to `Bool`s * `[+]` counts `True` values [Answer] # [Python 3](https://docs.python.org/3/), 94 60 57 bytes ``` lambda s:sum(x<=float(s[2:])for x in(0,9,11,13,15,16.2,17)) ``` [Try it online!](https://tio.run/##bdLNjsIgEAfwsz4Ft0KCRD4K1USfYm9uD90Vo6ZqU@hu9@m7tSjDftx@mfkPQwjNlz/ernI4bF6Hurq87Svk1mbhugvut/ajqrHbiXVJDrcW9eh0xSvKOeWS8pxyzQTlhpDh83iqLXppO7uez3q0GYNN5zGZzyrnbOvRAffMNfXJ4wxlZLcsCdrcU/5nXZTjSNP@qS9LVp8757EmFGWLbUb/OXHs2L6x797ux/7vcwfONONosUV8fqcAqicNVE1azYEaaIAFcAXky6djv4ArFLCsYBKogDlQAw0wOTfunSDuCLsCBVAC1ZPhqkEwNjrO8akqJ7HUIjpRkhBJQoa6ChbRCpQkVJoI134Y8tMT5ZPC5MMiWoOSxOMD6GCZWCXOo6dHN98 "Python 3 – Try It Online") This function takes the string `s` and returns the corresponding `pack_format`. -34 bytes thanks to Command Master (using `lambda` and `sum` instead of a basic loop + a stopping condition) -3 bytes thanks to tsh (flipping the conditional, changing the list structure, replacing `float` with `eval`) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~67~~ \$\cdots\$ ~~60~~ 58 bytes Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved ~~4~~ 6 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!! Saved 2 bytes thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!!! ``` y;f(p){p=(~-sscanf(p,"1.%d.%d",&p,&y)*y+p*p+3*p)/51+p/17;} ``` [Try it online!](https://tio.run/##pZPLboMwEEX3@QoLiYh3Yt6I0k3Vr2iyQMYkqC2xMFJJo/TTSx1gTNLHqtFEPswdrj3YJvaOkL4/pqXG9BPLtA@bc5LX4tFSsKMWIhRryazlUTeOJjOY6RlMXwXYZCscpee@qlv0mle1pi9OCyR@ZJ83Bmopb/nTFmXoJHxCBysWGsAF8EeIIBPNmQAgBIgAYoAEAK9HmpQYporBOHY8AB8gAAgBIgDpM80AA/gm4JuAbwK@sBS8hmJBUzWGDHZmAk2OUnOl5smcJ3Mwny81f9ZgWYKgLoBR1geyPoRRauGsSS@5X4LALVLO6bDllzNAO0ZJS4txz7GF/hPuH@H9CP@3CG4jvIpoWvJ4SsmekmfaiDWj4aRuukd30yUP4j80efXsQbPloUHapeOqLmgnXlunE94hXr3TQ6nBt9BXU8KQmRSZ5lCto/G6XF0Z4TVem6Fgm0r9MhsXaqm1@m2Wiqz88t9fY40oKTVF5ci@R2qBVL6pRVuthbgle6dZxreT7Xlx7j9J@ZLveG@/fQE "C (gcc) – Try It Online") Uses a variation of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s formula from his [JavaScript answer](https://codegolf.stackexchange.com/a/225920/9481). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` ¦¦T*•BÎΣÚÁÿ•Ƶζв›O> ``` [Try it online!](https://tio.run/##ATIAzf9vc2FiaWX//8KmwqZUKuKAokLDjs6jw5rDgcO/4oCixrXOttCy4oC6Tz7//zEuMTYuNQ "05AB1E – Try It Online") ``` ¦¦T*•...•Ƶζв›O> # trimmed program O # sum of all elements of... › # is... # implicit input... ¦ # excluding the first character... ¦ # excluding the first character... * # times... T # 10... › # greater than... # (implicit) each element of... в # list of base-10 values of base... Ƶζ # 170... в # digits of... •...• # 12728408213639... > # plus 1 # implicit output ``` [Answer] # Java, 93 bytes ``` s->{var i=Float.valueOf(s.substring(2));return i<9?1:i<11?2:i<13?3:i<15?4:i<16.2?5:i<17?6:7;} ``` [Try it online!](https://tio.run/##VZPPcpswEMbP4Sk0nKCtNUH8c4xtbpnJodODj44PiiM8cmUgSDDOePwUPfTSp8uLuBLCZs1lf9/q00rA7p52dLJ//33hh7pqFNprjVvFBS7acqt4VeJvmVO3b4Jv0VZQKdFPykt0cpB@eKlYU9AtQ6tKdKw56QSSBr2Vani5wxhLPzv35qGIVFTp0FX8HR10qcG53iDa7KR/ch6eh5PnduXHiz5lx5plsbjIyfLU0QbxxbOoqMIdFS37VXgSy/ZN9naP@H7WMNU2JeLzpzyY8XkQ5MSEMA9NiPPIhASTPDaQ5skszc6XzHkwxRWTSqIFcgOc4ABNlih4LQ0TwNGNU5BP7/Ix4ARwCngK@Alw8HgTo2UKrjMFx05xCDgCHANOAKeAYf3xCj2RnuypAxPAIeDoxvbqA4K9Woybgz4fWsR3gowCIjQRaArtSjQIMooIIDRFdyb7GlcB9vQfL7Zot18FGUUCEJqGdkkGEUIRQRGPov8rqav7sKgaz/Si4CWb2Y7EshZcee5r6fpmTMxMGctRt6qxXddNDdfP@pm7PqtPqdgBV63CtR4SJUrvuH7coO/I2jUUmNa1@Ozzfr9gst5dGrOPlgrpDRN5G7/jOtj4PsqR@/Xvj4tmJv7Vt9QvYmf/7Jwv/wE) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 23 bytes ``` L2$"iE₀*`-AViu}`C44+>∑› ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=L2%24%22iE%E2%82%80*%60-AViu%7D%60C44%2B%3E%E2%88%91%E2%80%BA&inputs=1.6.1&header=&footer=) [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` f=lambda p,n=0:float(p[2:])<[9,11,13,15,16.2,17,18][n]and n+1or f(p,n+1) ``` [Try it online!](https://tio.run/##pZJNboMwEIX3OYV3YMVFGX5siEovQllQYpSoqYOCK7WNcnYKhGdatV0VjTQf84Y3tpj23e5PJur7Jj9WL0@7irXC5JttczxV1m@LcFvy@yITRIIiQYkgGYSClKC0LExZmR0zazqdWeMPH66J91Z3tmM58z0KZECeYBOEgPgGChW1VBKABChACsgAtLnRrKQYlcI4DSJADEgAEqAAzmeegATfDL4ZfDP44ii0QfNAczehQsFC0Fx2Wui0yNUiV8O82GnxouFYA6EvQXb9ieuXyE6Ti@a83P8aCG7K4yv91ura6t34o0mw/0T4R0Q/Iv4tku8hv4Tiq3qv62d9nvbx8TVUcT1eYiSKhms0w@ZaodnBsI9D60@7Kxgux7crNjzjNje@5dNLez4Y6zfexV7Z3QO7dFd2mYcUOs@78urx/hM "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ 29 bytes ``` ILΦI⪪”#|⊞u⦄,<q'Zχ=” ¬›ιI✂θ²χ¹ ``` [Try it online!](https://tio.run/##LYtBCsIwEEWv8slqAmPpVFTEZUE3IoInCCHYgdDaOHj9WKmP/zYfXhxCiVPItd6LjkZ9eBtd0/i0gc6aLZX1eryyGrkWR4hAtpAdZN90kINjODjvGbfJ6FJS@FXKWMOsMdHM6BjSLvo/p1qlkWV188lf "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ”...” Compressed string `0 9 11 13 15 16.2 17` ⪪ Split on spaces I Cast to float Φ Filtered where ι Current value ¬› Is not greater than ✂θ²χ¹ Slice of input string I Cast to float L Take the length I Cast to string Implicitly print ``` Prefixing `0` to the compressed string or post-incrementing both cost 1 byte. I've stuck with prefixing `0` as it used to be shorter with the previous method. Edit: Switched to a less-than-or-equals comparison which costs a byte but saves 4 bytes from the compressed string. [Answer] # BRASCA 0.5.2, 30 bytes The G operator was added on the same day as the challenge was posted, but not specifically for this challenge. The program assumes input as `1.x.y` at all times. Ex. `1.16` must be input as `1.16.0`. The math is from Arnauld's JS answer, go upvote it! ``` C'.iGX$:16S>[7n@]x::*$3*++51S/ ``` [Try it online!](https://tio.run/##zVt5d9rGFv@fTzG10wIxYLDjLDzjNk7S1G0T59jueXnHxyUDGkCppFGkUTDdvnrevaMFLQMaxSvnJAZp5t7fXWe74y7EjDu7T13vi2m73BPEX/gtYlMxaxFTME9wbvm1icdtIkybkbiVxZgbPvaoY8Cf6AX@gn9TVoseCI@O2YiO/6jVxhb1fXLoUX9MX@D3fo3AZ2Nj41RAgxbx2NT0galPgAr5TD2TjizmQwPZ0GATMhyajimGw4bPrEmzX5Mv8LMpaciOCZnkJTbu@LLBgJxfZJ9TeNbNPhplHi15PPcYmTNgQA3TmRL2mXmgQPxKfTKeUZAV@X6fZ@xBk6HNDQZ0f6SWz1K435kuM9qmQwwqaPLYnBCHS2tAd2DWMX0qxKLR7CdNUvShwRC7A/llD0TZaJ73@@3eRabThHtk2CJDAkyZE9jMo4I1cqRyjBTM0F5@YAlkmn1zjixbhad5HFnLdKjrMsdocM9ohISbzaQ5A52VSQ5estTqTxSdKDLOiDGHuGAEwQyyYCJnH2qhqhbDuEXRRmcz0ydz07KILzj4AIVvYsbICAz@BxPE5b4pTO7kPG4@My02tDh3fSD61z8ZioyM0SHQYZGUy5G5lyWALYbRm6KXjkOHSsstn0PkWeYYogRsmwijbiG4mxV3813gzwh0HAFHwSU0aZ4kAl1oMAwbSJ9pYeuUtxQtiu/T1D9TK2CET5YRg5wUXPB9xAO/rmWCbiMbNVcLMuJCQKoCzmvFGobtyqQzHR/yY6MbNikXUAsB9sjyXy35EkBReLCrzM45FtyNE2c@0SRks2HmMRF4TsrzipEYNUkBQzZh7ObQlKqAu2nhbwFmN9bYKYQxAooHjwSTz8QwfhiZJP6ZxRc/JQOISbqhSFc0TpVLBYVY871Hqt6jYu@Uz6Wx1/3IBZUBjMnuuiTKhGAoY1Mtd7equEXSo6ZaKd3IhCc4HvtMKbJ8k3eqFJ@4RTOhJb0FSVnMmYqZ2mHDd3m6kavBy8aSRSo0AwsGXElNjhAERwhigT5IIz9uNBNWo8C0jPBhnp9gtpud2OCTIcw7MnOO7EsYGC32KeCCZayDk4N4OIPkw20bR6jiTAEHn9wcAcxaIH1AusWJRKFVe0B6mVbSR4o4B6up5WTNA4sFQXc73whH3Uy/qKOafOyGsWKaRbBpBheVGIB3eDiJkoyymWHVbOJc9rmATjGi8i5xS@wlu6@Xob5RqukzL2Dlth2QnfWcPlQ2R7pZAYQufexYTj7yphquQU4XkLFsQr0pRIIjYPniyuUTTgNhSdNxF2RC9iegcofa7KD4dkz2MWwOarUzDvGEixsI7VEwbZEA8tbE2B5jqAEXamC@mWyPO9jUt/icGHzuEB4INxBRc3977EtgJq6LkOdwKCUeDm0K8@JhZMIQABgitfSKnCzClswkN768qHfM1@8f9HuPTw/Onzg/XFz2@w8f7D7c2trrnW5/iRZsYSojh5iTwiSJKcymbppqOmPF2Y@8AWSytfwd5r8UimS2uy/TZ@pNOt95i6zlEnOnSZ0ryF7k80LUJrNEW@l7hQebRI69@5AaD7Jz2DXpp6uIrJTW0vPrbjEVFNy7p0@up0FuR5/cjga5XX1yuxrkHumTe6RBbk@f3J4Gucf65B5rkHuiT@6JBrmn@uSeapB7pk/umQY5q4Ib64TFrxXo6XgeqxAXOsZ9VSEwdALNqBAZOuZ9WcGXdWJjVsFddLz5pyr@ouMwv1QiqEPxr40@2XzJxh7D6YIu8fgRTgTbOhn7H2Rz5FyBzZYOGw/ZyOHuRO7vqvjQ5QisnshKMDqNcBli4rJDbiY3Ri1CAaXaQiskNJu14oAtBQhHe5g@zahXKnj9Q32tY2R3d5VzYq3JdV4KuflVMp3Z6l001xHKzKi2cJFV1MgbiotbF5d2PLVlvhL7FvrBc8O4YQdQuewW1fDTNuI7DUZ48CDuAGRbB@RDBPkmsITpWos7APlQB@R2mFgEm4L3GOZn01ctNG8e7Pa2DtpvpUq5EVj8DjB@qwPxd4T46tLlzqpEfcNW1zK7LwPok3cVhEXmeKTYmcDCL/rqA4MGbTZVSfrQFHMTVrgVstK/CPrt8dm1Yv5XR13fyXz49uUd2PM7HXx/I77jkzuA97cOvCHCe38n@H4HfArvO1Uu4gvAKQJ35dY7X25nP187VUgfJQABDfWMlFwO9bmMdLg8l1ziUxo9YbLHCHrSHKr5HFbgoyVPC/lEW/orNmUyHOK9/1LCfSRsBHh6KrfwQRQ@WcPhazMPvUrLAur/ZFEvT@B0gceHcrqo4vb0GjoUpLFRGpt/zqof4yMkomQZnod9lTFibJKEBr43Cb6couVxXLTxWY6vqs618bkl@iOOLPXx1X5h88ARuis4Z7mC67bCrmvWcNo2uh47vSux0z3Sw3pfuKI/fC@TZVjFFdVLdNu9nSe6fpeUfDVgnZnfV2hqAPgmGeOWR62lSVuxlxEdxuqwfIAs/Tl1paHFnGOxm@0T7lw5md94xh9pyHcibcpFPEiJmcfY7co4vnFFjK@iMuV5TkGPp6jHMXdw3HQSZYK7hIT92/cTjDFfoEhb@IdqRdg0L8ZqB4hqCZBNvd75yE1HsnOay0SWbHxhVcPqpDfGNAfJJJX6Ukd6Ue/yHb0qykHwGup4rVSHPCX2YZKkXvhufuh1dnY7j/Y@kHqHmOQ1GRyQHtnZJY/2lB0M4GvrWBl4YvUGFoA0FqGeL1tkgYpLSnA7U48H7miRUV@LWNQeGZT82Sd/omSSZTMulrq8uDPbSBmQOsi2mswKX4t0IBVw2aw05mk6gBk5AMz7BQEipoljfjT4NdqqA5KM5lrRGJ0pi8kob7XQACXsfDAgj55Glc74e39A9p6s7pfZcgYW5xIJVnPI7gC6XO6jtNzL2shQA42tW5O7mxX72VdLDZBr5WJfyvWPCUQ8o3zNtta5C7Tfp2nrrKx0ZnUFLgFy@c1pnypJOrrzUFnIFabzakcpEKGGzkDzW4RzuhJnOtAvm8tEkfGiWpkbZKvdrltMxabQ0faxhqNxudcma3TwRsDz0xdHR1Hla5nXLWtRCuXoK@tRcqIU69iVp1H4kU0a41n2HLDZgrA2BvW6hqWPV4qqEwR3L20SfFWEdrJCRxn0/ho4bdwKYr5dLeZ9Na7CsEuBFfH8gjvC4xb50eLzcoXso0J@Zb4PCyl600dgqL59Wilx9dSUmI6qq9abHaAuXoN55LWG21HHwf1Vx0Ce6X0KwK1vQRGDwb3VRP1/ddDEIRNzxpz7sLeA@sLZ5Rj/u78O9AM60BnzbBOXorXrSYp4C5BdmkJnbrmJACAfGrI8nFrkY2C7JYldah312i3VR7EGpRTRR0T0M6DA2dwcJtZ@lSKXbAFVObefE254TbUau3aW3ZYGu3Nk91@se27LouliLX5R3eGc9xuc9K5dYGVWSu3eRYmFVkmVCJW@P1BaTa2U9iInLQzJNyXrwY2KquNJL9aXdeXuZeqVip1p0gxvckqatezKJby3JKVwPSZ3ffzkCjNek43q4Yq3KNTF8eqLE5tneOXJFDA1nJD5jDmwxOfA2JNRJUywKbCdwOrdKCmQr1Zwl73alKA5RtayiEQeLCj29FYn80IVXgQuV6qy@UaeocUXefMXeLVSILscM1eQX9hixCHxYLGV5wWuyN2HK2bzqOMr@QfSNhoyJ87mKbdZeAF6zhxB5h53pi08CuBzMA4BTjwLN5xKb7w6OTk@6RNV99zhe9ghueLfgXRtUzEEcPlTmJQI4UWQo8hxoysttaoLh2XbTAiAjylWGGsP@q@wH0oHa2chCowY@mqMxcUqLVuzrSCuDtAlbVokqyQX6bNIbo3YlUUuF7e6qCvFxM@XXqe309n5Pw "Python 3.8 (pre-release) – Try It Online") ## Explanation The second number will be called X, the third number will be called Y. ``` C - Set implicit output to number mode i - Turn "0-9" from char into the numbers 0-9 '. G - Split stack by "." X - Remove the first number, it's not needed. $ - Put X on top of the stack :16S>[7n@]x - If it's more than 16, the version is 1.17.0, so print 7 and terminate. - Calculate the final number: ::* - (X**2 $3*+ - + X*3 + - + Y) 51S/ - /51 <implicit> - Output the number ``` [Answer] # [Python 3](https://docs.python.org/3/), 66 bytes ``` lambda i:sum([float(i[2:])>x+8.2 for x in [.7,2,4,6.2,7.9,8.3]])+1 ``` [Try it online!](https://tio.run/##BcHbCoMwDADQX8ljgiFgHd5g@5GuDx2jGNC2aAX9@npOvsuSYlfD@1tXv/3@HnQ@zg1tWJMvqNbMjj5XM4qBkHa4QCNYGdjwi3sxPMjEo3TOUdPWvGssGFBjPgsSUX0A) Explanation: * Our input is `i`. Remove the `1.` at the start with `i[2:]`. * Convert the rest to a number with `float`. * For each `x` in the list, check if this is greater than `x+8.2`. + Why 8.2? Well, all of the finishing versions (1.8.9, 1.10.2, etc.) are greater than 8, thus saving some bytes. + In addition, since two of them end with .2, I can subtract that as well, saving 2 more bytes. * Since `True` and `False` are treated as `1` and `0` by the arithmetic operators, we can use `sum` to count the number of `True`s in the list. * This is now off by one, so we add 1. ]
[Question] [ **Specs** 1. You have a cubic 3D space `x,y,z` of size `S` integer units, such as `0 <= x,y,z <= S`. 2. You get from [default input methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top) an array of points `P` represented as `x,y,z` integer coordinates, in any reasonable format as you like, for example: `[x1,y1,z1],[x2,y2,z2],[x3,y3,z3] ... [xn,yn,zn]`. 3. All the `P` values will be in the above said cubic 3D space, such as `0 <= x,y,z <= S`. 4. The possible total number of `P` will be `1 <= P <= S3`. 5. You also get as input the `x,y,z` integer coordinates of the *base point* `B` and the 3D cube size `S`. **Task** Your goal is to output, in your preferred format, the points `P` sorted by the linear (Euclidean) distance from the *base point* `B`. **Rules** 1. If you find more than one point `P` that are equidistant from `B` you must output all of the equidistant `P`'s in your preferred order. 2. It is possible that a point `P` will coincide with `B`, so that their distance is `0`, you must output that point. 3. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code wins. 4. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. 5. Code explanations are appreciated. **Test cases** ``` Input: S (size), [B (base point x,y,z)], [P1 (x,y,z)], [P2], [P3], [P4], [P5], [...], [Pn] 10, [5,5,5], [0,0,0], [10,10,10], [2,0,8], [10,3,1], [4,4,5], [5,5,5], [5,5,4] Output: [5,5,5], [5,5,4], [4,4,5], [2,0,8], [10,3,1], [0,0,0], [10,10,10] - - - Input: 5, [2, 3, 3], [3, 0, 4], [5, 0, 3], [0, 2, 4], [0, 3, 5], [4, 2, 1], [2, 2, 2], [3, 1, 2], [3, 1, 0], [1, 3, 2], [2, 3, 1], [3, 1, 5], [4, 0, 0], [4, 3, 1], [0, 5, 5], [1, 5, 1], [3, 1, 4], [2, 2, 2], [0, 2, 5], [3, 3, 5], [3, 3, 0], [5, 4, 5], [4, 1, 3], [5, 1, 1], [3, 5, 3], [1, 5, 3], [0, 5, 2], [4, 3, 3], [2, 1, 1], [3, 3, 0], [5, 0, 4], [1, 5, 2], [4, 2, 3], [4, 2, 1], [2, 5, 5], [3, 4, 0], [3, 0, 2], [2, 3, 2], [3, 5, 1], [5, 1, 0], [2, 4, 3], [1, 0, 5], [0, 2, 5], [3, 4, 4], [2, 4, 0], [0, 1, 5], [0, 5, 4], [1, 5, 1], [2, 1, 0], [1, 3, 4], [2, 2, 2], [4, 2, 4], [5, 5, 4], [4, 4, 0], [0, 4, 1], [2, 0, 3], [3, 1, 5], [4, 4, 0], [2, 5, 1], [1, 2, 4], [4, 3, 1], [0, 2, 4], [4, 5, 2], [2, 0, 1], [0, 0, 2], [4, 1, 0], [5, 4, 3], [2, 5, 2], [5, 4, 4], [4, 4, 3], [5, 5, 1], [4, 0, 2], [1, 3, 5], [4, 2, 0], [0, 3, 1], [2, 2, 0], [0, 4, 5], [3, 2, 0], [0, 2, 1], [1, 2, 2], [2, 5, 3], [5, 5, 2], [5, 2, 4], [4, 5, 5], [2, 1, 2], [5, 4, 3], [4, 5, 4], [2, 3, 1], [4, 4, 4], [3, 0, 0], [2, 4, 5], [4, 3, 3], [3, 5, 3], [4, 0, 0], [1, 1, 1], [3, 1, 3], [2, 5, 5], [0, 0, 5], [2, 0, 2], [1, 0, 3], [3, 1, 4], [1, 2, 5], [4, 1, 3], [1, 4, 5], [3, 1, 4], [3, 5, 1], [5, 1, 4], [1, 0, 4], [2, 2, 0], [5, 2, 1], [0, 5, 3], [2, 1, 1], [0, 3, 0], [4, 5, 5], [3, 4, 2], [5, 3, 3], [3, 1, 1], [4, 0, 1], [5, 0, 5], [5, 0, 4], [1, 4, 3], [5, 4, 2], [5, 4, 0], [5, 1, 0], [0, 0, 1], [5, 3, 0] Output: [2, 4, 3], [2, 3, 2], [1, 3, 4], [1, 3, 2], [2, 2, 2], [1, 4, 3], [2, 2, 2], [2, 2, 2], [1, 2, 2], [3, 4, 2], [1, 2, 4], [3, 4, 4], [2, 5, 3], [4, 3, 3], [2, 3, 1], [4, 3, 3], [2, 3, 1], [1, 3, 5], [4, 4, 3], [2, 5, 2], [3, 1, 3], [1, 5, 3], [4, 2, 3], [2, 1, 2], [3, 5, 3], [2, 4, 5], [3, 3, 5], [3, 5, 3], [3, 1, 4], [0, 2, 4], [0, 2, 4], [1, 2, 5], [3, 1, 2], [3, 1, 4], [3, 1, 4], [4, 2, 4], [1, 4, 5], [4, 4, 4], [1, 5, 2], [4, 3, 1], [0, 5, 3], [2, 1, 1], [4, 1, 3], [4, 3, 1], [2, 5, 5], [0, 3, 5], [4, 1, 3], [2, 5, 1], [2, 1, 1], [0, 3, 1], [2, 5, 5], [1, 1, 1], [0, 4, 5], [4, 5, 4], [4, 5, 2], [0, 2, 1], [1, 5, 1], [5, 3, 3], [0, 5, 2], [3, 5, 1], [3, 5, 1], [0, 2, 5], [1, 5, 1], [4, 2, 1], [3, 1, 5], [3, 1, 1], [0, 2, 5], [4, 2, 1], [0, 5, 4], [0, 4, 1], [2, 0, 3], [3, 1, 5], [2, 4, 0], [2, 2, 0], [2, 0, 2], [3, 3, 0], [3, 3, 0], [5, 4, 3], [1, 0, 3], [5, 4, 3], [2, 2, 0], [3, 0, 2], [5, 4, 4], [5, 4, 2], [1, 0, 4], [3, 0, 4], [5, 2, 4], [3, 2, 0], [3, 4, 0], [0, 1, 5], [0, 5, 5], [4, 5, 5], [4, 5, 5], [0, 3, 0], [2, 0, 1], [2, 1, 0], [4, 4, 0], [5, 1, 4], [5, 5, 4], [5, 2, 1], [3, 1, 0], [5, 4, 5], [4, 4, 0], [1, 0, 5], [4, 2, 0], [0, 0, 2], [4, 0, 2], [5, 5, 2], [4, 1, 0], [5, 5, 1], [0, 0, 1], [5, 1, 1], [4, 0, 1], [0, 0, 5], [5, 0, 3], [5, 3, 0], [5, 4, 0], [3, 0, 0], [5, 0, 4], [5, 0, 4], [5, 1, 0], [4, 0, 0], [4, 0, 0], [5, 0, 5], [5, 1, 0] - - - Input: 10, [1, 9, 4], [4, 6, 2], [7, 5, 3], [10, 5, 2], [9, 8, 9], [10, 5, 10], [1, 5, 4], [8, 1, 1], [8, 6, 9], [10, 4, 1], [3, 4, 10], [4, 7, 0], [7, 10, 9], [5, 7, 3], [6, 7, 9], [5, 1, 4], [4, 3, 8], [4, 4, 9], [6, 9, 3], [8, 2, 6], [3, 5, 1], [0, 9, 0], [8, 4, 3], [0, 1, 1], [6, 7, 6], [4, 6, 10], [3, 9, 10], [8, 3, 1], [10, 1, 1], [9, 10, 6], [2, 3, 9], [10, 5, 0], [3, 2, 1], [10, 2, 7], [8, 4, 9], [5, 2, 4], [0, 8, 9], [10, 1, 6], [0, 8, 10], [5, 10, 1], [7, 4, 5], [4, 5, 2], [0, 2, 0], [8, 3, 3], [6, 6, 6], [3, 0, 2], [0, 1, 1], [10, 10, 8], [6, 2, 8], [8, 8, 6], [5, 4, 7], [10, 7, 4], [0, 9, 2], [1, 6, 6], [8, 5, 9], [3, 7, 4], [5, 6, 6], [3, 1, 1], [10, 4, 5], [1, 5, 7], [8, 6, 6], [4, 3, 7], [2, 1, 0], [6, 4, 2], [0, 7, 8], [8, 3, 6], [9, 2, 0], [1, 3, 8], [4, 4, 6], [5, 8, 9], [9, 4, 4], [0, 7, 3], [8, 3, 4], [6, 7, 9], [8, 7, 0], [0, 7, 7], [8, 10, 10], [10, 2, 5], [6, 9, 5], [6, 2, 7], [0, 9, 6], [1, 4, 1], [4, 3, 1], [5, 7, 3], [9, 6, 8], [4, 1, 7], [4, 0, 8], [3, 4, 7], [2, 3, 6], [0, 0, 7], [5, 3, 6], [7, 3, 4], [6, 7, 8], [3, 7, 9], [1, 9, 10], [2, 1, 2], [2, 8, 2], [0, 3, 0], [1, 1, 9], [3, 5, 2], [10, 5, 3], [5, 2, 9], [6, 9, 0], [9, 5, 0], [7, 1, 10], [3, 3, 8], [2, 5, 1], [3, 10, 10], [6, 2, 2], [10, 7, 2], [4, 3, 1], [4, 2, 1], [4, 2, 8], [6, 8, 5], [3, 10, 0], [1, 1, 7], [6, 9, 6], [6, 2, 4], [5, 5, 7], [5, 4, 5], [9, 8, 1], [9, 8, 1], [0, 10, 6], [1, 1, 9], [3, 8, 8], [3, 1, 5], [5, 7, 4], [4, 3, 6], [5, 4, 7], [6, 0, 8], [7, 8, 1], [9, 8, 4], [2, 10, 0], [3, 4, 5], [9, 3, 10], [7, 4, 1], [2, 1, 9], [10, 8, 1], [10, 3, 7], [2, 0, 6], [3, 8, 4], [10, 0, 2], [9, 9, 10], [8, 9, 5], [4, 10, 2], [8, 3, 4], [4, 2, 10], [9, 1, 6], [6, 1, 3], [4, 1, 3], [2, 9, 0], [5, 6, 5], [8, 8, 3], [5, 5, 0], [7, 6, 9], [1, 1, 5], [3, 0, 4], [1, 10, 6], [8, 0, 2], [0, 7, 3], [8, 9, 8], [2, 1, 8], [3, 1, 10], [4, 5, 9], [7, 6, 10], [3, 6, 10], [5, 9, 8], [9, 3, 3], [2, 2, 3], [9, 9, 0], [7, 2, 2], [0, 0, 9], [8, 7, 4], [9, 2, 9], [0, 6, 4], [9, 4, 3], [10, 1, 3], [5, 9, 10], [5, 10, 6], [6, 3, 10], Output: [1, 10, 6], [3, 8, 4], [0, 9, 6], [0, 9, 2], [2, 8, 2], [0, 7, 3], [0, 7, 3], [0, 10, 6], [3, 7, 4], [0, 6, 4], [1, 6, 6], [0, 7, 7], [4, 10, 2], [1, 5, 4], [0, 9, 0], [2, 9, 0], [2, 10, 0], [5, 7, 4], [5, 7, 3], [5, 10, 6], [5, 7, 3], [0, 7, 8], [3, 10, 0], [3, 8, 8], [4, 6, 2], [3, 5, 2], [1, 5, 7], [5, 10, 1], [6, 9, 3], [6, 9, 5], [5, 6, 5], [2, 5, 1], [0, 8, 9], [6, 8, 5], [5, 6, 6], [6, 9, 6], [4, 5, 2], [4, 7, 0], [3, 5, 1], [3, 4, 5], [5, 9, 8], [6, 7, 6], [3, 7, 9], [1, 4, 1], [1, 9, 10], [4, 4, 6], [0, 8, 10], [6, 6, 6], [3, 4, 7], [3, 9, 10], [5, 5, 7], [3, 10, 10], [2, 3, 6], [6, 9, 0], [5, 8, 9], [5, 4, 5], [6, 7, 8], [7, 8, 1], [5, 5, 0], [4, 3, 6], [3, 6, 10], [8, 9, 5], [5, 4, 7], [4, 5, 9], [5, 4, 7], [2, 2, 3], [8, 8, 3], [1, 3, 8], [5, 9, 10], [0, 3, 0], [7, 5, 3], [8, 7, 4], [4, 3, 1], [8, 8, 6], [6, 4, 2], [4, 3, 7], [6, 7, 9], [4, 6, 10], [4, 3, 1], [6, 7, 9], [3, 3, 8], [5, 3, 6], [4, 4, 9], [4, 3, 8], [8, 6, 6], [3, 2, 1], [7, 4, 5], [7, 10, 9], [2, 3, 9], [5, 2, 4], [1, 1, 5], [3, 4, 10], [8, 9, 8], [9, 8, 4], [0, 2, 0], [4, 2, 1], [3, 1, 5], [2, 1, 2], [8, 7, 0], [9, 10, 6], [7, 4, 1], [7, 6, 9], [7, 3, 4], [1, 1, 7], [0, 1, 1], [4, 2, 8], [9, 8, 1], [0, 1, 1], [4, 1, 3], [6, 2, 4], [9, 8, 1], [8, 4, 3], [3, 1, 1], [6, 2, 2], [5, 1, 4], [9, 9, 0], [7, 6, 10], [2, 1, 0], [2, 1, 8], [4, 1, 7], [8, 6, 9], [6, 2, 7], [8, 3, 4], [8, 3, 4], [10, 7, 4], [3, 0, 4], [8, 3, 3], [8, 10, 10], [2, 0, 6], [9, 6, 8], [10, 7, 2], [1, 1, 9], [8, 3, 6], [1, 1, 9], [7, 2, 2], [3, 0, 2], [9, 4, 4], [8, 5, 9], [2, 1, 9], [6, 1, 3], [6, 2, 8], [5, 2, 9], [9, 4, 3], [9, 8, 9], [0, 0, 7], [10, 8, 1], [4, 2, 10], [8, 3, 1], [9, 5, 0], [6, 3, 10], [10, 10, 8], [10, 5, 3], [8, 4, 9], [9, 9, 10], [10, 5, 2], [9, 3, 3], [8, 2, 6], [3, 1, 10], [4, 0, 8], [0, 0, 9], [10, 4, 5], [10, 5, 0], [10, 4, 1], [8, 1, 1], [6, 0, 8], [10, 3, 7], [9, 2, 0], [10, 2, 5], [9, 1, 6], [10, 5, 10], [8, 0, 2], [9, 3, 10], [7, 1, 10], [9, 2, 9], [10, 2, 7], [10, 1, 3], [10, 1, 6], [10, 1, 1], [10, 0, 2] - - - Input: 10000, [8452, 3160, 6109], [7172, 5052, 4795], [9789, 4033, 2952], [8242, 213, 3835], [177, 7083, 908], [3788, 3129, 3018], [9060, 464, 2701], [6537, 8698, 291], [9048, 3860, 6099], [4600, 2696, 4854], [2319, 3278, 9825] Output: [9048, 3860, 6099], [7172, 5052, 4795], [9789, 4033, 2952], [8242, 213, 3835], [4600, 2696, 4854], [9060, 464, 2701], [3788, 3129, 3018], [2319, 3278, 9825], [6537, 8698, 291], [177, 7083, 908] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` ΣαnO ``` [Try it online!](https://tio.run/##XVXLlRtBCLw7iglgDtD/jsIB6Omwfs/XTWojcCKbktyiiy1mbqjFpygKRurHH/37en1/ff/7/P16PR7lPNp5pOd5PPp51PPIb1PFbHue5zHOY4ZnFfthdnmb6//1S2G24F3wnLdpgctYpQQl317mXu3Zyjcz/VVRZcWtNANmgcO7GsJW7bTKo15FaTEHgUOBrxDyrtaQtznMbHHqgRneGiLnhm@hyVwiTZ4lhchldyLxDhM6lCvVitT7eSOpu6SCvZWkArjPa1cJsJ3SRm6Evhr7EvDbLMdAjoHAavW6e3einsinrDIM0URB960XGLG2d7Jl1amlxtl3EK3or1mYd9KJOCNskgu9q8dbcsanvRYmy0xWbqoclPD2dbybxTDtSo1WMtvJWwM435RCqYWNmEaFo1dkKDbJwQXrVKIrR/Ba@drvPQ1OaQLOj/Q33QnmIN2ZxCoH7SrEDmQqPGyroKUazkBYO59T4hLnSO3mMAUdphtzhVtXKOVm@GvIFxrohNdYxEVbyaILdd9FvZkSTsKVmUGeFSkqF6NwPGHNGgfc7@WKT0d4agK27Gx1aisRkArzqVy2S7igXkaFN2Ne7@LkBVJ3CUuDSfjElewq1FFoJqpjH4rKC5Q5CW@rUa7KuYpjDpMYl5MXdntSanqZz8@nyo9Yv34aWjjInmTy3CZrO5Mvx5wIQy7HpPBeTTg0vpbwYVaSMW@fBed2D//5C5tcnv8B "05AB1E – Try It Online") **Explanation** ``` Σ # sort by O # sum of n # square of α # absolute difference between current value and second input ``` [Answer] ## JavaScript (ES6), 71 bytes ``` (b,a,g=a=>a.reduce((d,c,i)=>d+(c-=b[i])*c,0))=>a.sort((b,a)=>g(b)-g(a)) ``` [Answer] # [Haskell](https://www.haskell.org/), ~~54~~ 52 bytes ``` import Data.List f o=sortOn(sum.map(^2).zipWith(-)o) ``` [Try it online!](https://tio.run/##ZVe7blw5DK3XX3GLLWzgrkHqrSJdygAptzC8wAC7QQaJH4gnTX7euZKoOaQWHsCChs/DQ1Lz9fT27b/v39/fz0@vLz8u28fT5XT/6fx2ufmyvXx4O64@P9@@/Xy6fzq93v7j7u5/nV//Pl@@3v5193L3/nQ6P28ftn9ftps/Xn@cny/bn9uX7SHux9/j9vBA@/H3uG8PTHv/tLM7Lotc@p3bKezhUNinphzC46Mx6/bNH59m@PhP@xaGZDv6djz@O7mlLhuH8XbLw3U7unY8vmVzHHF2NSeyXtSGwDRGIhsgcFxFEeB@VGphcTyCjCLgzZEkoQBvLLnFfpx2o9wyjiMGh8i8OFZqysWEj42aEzWLWUSQQSyMAiigHCJjxCsFb2ozXhJjFocAoKYLAuojt7Dg69a6rVAH8CHCQjAuAoxNGtlyB2QxHTPsWhKo2wh0CAKEyNiU28OFw62K1yMLBhEdkldcJ3SAor3KeKKubp3JzSEc5XhGZtOMqIVbEgpAXbVTQG4e7eQM7T1qEWGMUG42TeYXphJ45gxQtsYBGa/9xgYoRryW4AF2wwJ1BKiELFRDEhoyrE02kfQmXlV5Rh/H/7e0IkwwZaGlN8kY6@HYoXsI1mb3GLqHehJjWY0gNXgOyXLIq2smNG0PriCR0u1dpQMqGqbiccgSaW53Ih77dXef@rEuFRkMKmBbFdkqaqUXJy01pS5AIhAwWWfIw1sSu2mG6bseT8VJdFaadYSf0AsaJkJDXjWPc0Ykdek9slCzmB7XfC3zLG423RXNLlJhT0gTsCHIss6LBN/UbRSxUURxsC1P6YyoK5pxeik9oioOM0a2CkP7DmbXZnApofZ52RAJnTDiKcg6SYGc2SaKPTOliXjFBCNQsWAJKVYWUHjIzngHiqraERyNQDYDt4Tu5mX5qI6oHYqCeZYxNQoaLIOJCZMgYxIk4Y3NqaBKVcK5Ul8tAdfBcsuYG3O7ouuc6gEPhqtuJUkpqjGg2m7Wydln1xXahHUmPHQLcuqpE0Dl1OOPyp5KICO8BCfqnZGXd9yYi7wcSY0Ei0wBzoz5ns1wW9ssocB5dTdX0zUPb2LzE61s3kOs5ktR7ae6i9Cg0w2rZ061c7GqNTtFVNNIJWbFGegyngBq2VessySWxwRST5aZVgJdGXVVG/NaiWJGnurtCqqxqQ@rFV7h78rRpAbyNFLNE92hdStiVr8YyAyTgHlVRSDhNqjFrH491GUtTGxH8e3SLyG2kDg1Oabatn/m3JqM2jch18GdXJpD8m111TgK6kILnFt6xY85ndvYo9KWHg3gcml1YtdwIB6QUHMXUqNBprFuo29cTrXNkjoITaFplh4a1Z5/SNRKlmpDocTBds/NtsutcsXFI8Obm/ff "Haskell – Try It Online") I don't need the size of the space. `sum.map(^2).zipWith(-)o` computes the distance from a point to `o` : `(xo-xp)^2+(yo-yp)^2+(zo-zp)^2`. The points are simply sorted on the distance to `o`. **EDIT**: "if you don't need it, don't take it" saved 2 bytes. [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ 64 bytes *-4 bytes thanks to [@Ramillies](https://codegolf.stackexchange.com/users/30415/ramillies)* ``` def f(b,l):l.sort(key=lambda p:sum((a-b)**2for a,b in zip(b,p))) ``` [Try it online!](https://tio.run/##JY7LboNADEX3fIWXM9G0mvfYkfIliAUoQUUlMCJ0kf48tenSx/dcu773r3UJx3F/jDCqwcz6On@@1m1X34/3be6fw72Hen39PJXqPwZ9ufhx3aA3A0wL/E6Vnaq1PircoMWYvIHgsjWQnaWumQW3xRXmyco2FkqdgZYKEk82BAOekheGPnLCO0YBwxlzpRgoFhmRRSGhIMoRz3qw7mRk5WTMke1inaCcApuYCaXf/aeimHi@Z4mExWx58pky@5iiMB@cdPvCaUKfuq4ZVTUw66Zu07KrWR9/ "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~56~~ 40 bytes *-16 bytes thanks to flodel for suggesting a different input format* ``` function(P,B)P[,order(colSums((P-B)^2))] ``` [Try it online!](https://tio.run/##PY/NaoQwFIX38xSSVQIZyH/uhbrxCdw7Fqx1ZMDOiNEyfXp7Y@lkEThfzncgyz4Wb@fiut379fa48ySG727ic7ekga/lmLYPzi6XlkkmmPyPDcWeMzl3aR04m25ppZRyR@RzOl1pdX@t1rISdfNYPoeFp26epx9Cr9enSNsX589zJd4N2e1@5XU5ctZEHY0svPJ0u4i@lUWDEZCSslYWBr3JDIyjhtGELNijpmOURVRACBVkYiMAvWtDulX6YKiCorHgyI5KZxS8JRMCQt7Xfy2XTcjdoBAzc0FRMgED@eBdZsbqvG0itRGMb5mQVdlzcPkDVh@@VijE/gs "R – Try It Online") Takes `P` as a `3xn` matrix of points, i.e., each column is a point; output is in the same format. Use the helper function `g` to transform the list of points `P` from the test cases into the appropriate R format. [Answer] # Mathematica, 24 bytes ``` xN@Norm[#-x]&//SortBy ``` Takes input in the format `f[B][P]`. We have to use 4 bytes on `x` to make the nested function. The precedence of `` (`\[Function]`) and `//` works out nicely so that the expression is equivalent to this: ``` Function[x, SortBy[N@Norm[# - x]&] ] ``` We need `N` because by default, Mathematica sorts by expression structure instead of by value: ``` Sort[{1, Sqrt@2, 2}] {1, 2, Sqrt[2]} SortBy[N][{1, Sqrt@2, 2}] {1, Sqrt[2], 2} ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~68~~ ~~57~~ 53 + ~~23~~ 18 bytes *-11 bytes thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)* ``` B=>P=>P.OrderBy(p=>p.Zip(B,(x,y)=>(x-y)*(x-y)).Sum()) ``` Byte count also includes ``` using System.Linq; ``` [Try it online!](https://tio.run/##jVdbb9s2FH73r@D80EitapASJZJIbawt2mFAixVLsQFz/eA5aivMVjxJbh0E@e0Zrz6HijdMNmyaOpfvfOdCedM/39x09cOhb9ov5Oq2H@rd7PXNdltvhuam7Wc/1W3dNZvLSSTxsT4Os1/rL4ftuntz3Hd13xvpy8mkXe/qfr/e1EH0XdP@PbmbEH1ttuu@Jy/t2u2Yqx/WQ7Mh326aa/J@3bRJeroFQuZ6e2g3L35@0x52dbf@c1u/aNphkT3eHotomf@8vViQz2T@8Gq@@KDfs1@667p7dZvs54v97I9mn7zKkmN2m84XyfH5bfrUfqazq8MuSdMHDFCHj3/2Q2coa9r9YbiM7nz/2mxrkiT2FpmT15q7m22tGV1fa75qbZj8MCftYbslT544C2Zj@qmdppGlmCFzfVt3pN/f6Mh6bbmtv5N3TT@8cGAWSXr5SOOzLoD15itJ3q8H/bWzn01LdH7r48xu1r3DmpEfp5@WS/pcZWT19NNqmqaPzD2GZMlwkGYvr68T62H223p7qM/AuZ@cjekUUrB0VZsiTY5kviDH2ceu2SU62uXq7mJ5kV2sLu51jvbbZkj0rzRI3xpprT77sO76Orl1eqm@Ls967WqTn8@J9/m26fpBi4ffV3/p@mBG@d9ZPYE3nGp7/5sxVz4m5On08qxI5OO62RkP1lV6VtxaJc/mVvQZmWZkega4uUJB/t41Q51Ml3f0fpUZhR4RTe6IpjYjF/p1n57N5H/adZUeq4GKW91P7h@WZaZf2v@SZvplFoxm9m3Wud6UfrPImFnxjDuFk6ZZ8NVEC5NCv82W/qYZ4e6uWRbOBcn9LrWypTNodplzZ5a5t8CipcNm1XIvW3g1JxCMUS/LQUBvlV6A2SVS4yPHDmTpBYpoSX1AHLwxH1tpl8Fu6XcZLB2GHJAV3jFSQy4CfSxSy71azFkJILm34BKAiMoBGQO8PslGLeCl3ljMAweiggsKrLvY@IjffJy3MdUc6qEECzxywcEYheJC6eYQRXDMwG5cBGi3BHYoCFBAxqJ0F@Aih12Et4AoGBRiDsGjWqfQAajsUcSBdbSbR7HlAAc5DsjiMEvIRT4KiAPrqJ04xFZAO@VR2aNGL8EYhXSzqMmKUaVSqLM8IirOMYeIx/3GIqIY4I0LnINdPqK6BFIpRIEakkJD8nGTBSaLCC/KPIM@Lh@3NCoYHqWFjnqTRsYsnIkxoCDFlTcg0NhBw0ZLSi2PthmFRrVGJICX1t5JmkMWeVDUC@HRCbPnxUu7bd1XdqlGWXBVI6HClJdVXk3ahFSjPFIrQL0Ah2kaIDtvFbDBwgRUYS2huBnSVA5@BfWPaaLQhCdNvRaARI36jcZUM2/abbNTakNCRdRRZXT@INiB0gq4oSDLcFzU81tZG9LbkF7RVZgI0gJQK2jA4EVaRMo7FDCmEQzsm0fnq4BaqiD3YnQqVFD9Do@EqCufoDw6QVD1hJAC4wqmFoVSlHDwoKqUUMJONuB1LKJsl1CjJTArgLcKOpqNDhzUEcpSIWGGCZgUEhpMQCVW0P0Cur/ydRPHJCFLysM5lT4a/LklKx@NNjerFXRdjnqggApH3Up9SCUaA6jtQp7y@FHrRG0FR5ivw3zEHHq84VDKlcVfInsoAAHwKnCCni3E6NnNzUU2WlI0EmJmJPDMYKaLaLiN26yCBIuxu3AcneIoImxFYEtEz0AMzReJ2g91F4UGDW4YerRR8VxU6GgNIqhpfCZCxhmwy@DYRwe8giOs8pbdBEKPKSGsCsqVQV7RKXnKhIxGHuptBaXGovwwdGwr8Heq0QoN5GBERY/lObSuAszoXwKNhgmHeaW8QAW7HB3M6B@DGh0LgduQ/MlS8tIAYZW5y6gLhQnTWtTc4UK5ihHSuKGFObBU6dKYcwOXmaBk4aazMMOOSnPUUUeXkCY7LDfRU@aIoMYdr0zyBXWHbFmYCq6UmSDKlTHlRlNaaFRZaLyiJlGVMrHL0tV4wYztXJh8ybxc/QM "C# (.NET Core) – Try It Online") Points are treated as collections of ints. Explanation: ``` B => P => // Take the base point and a collection of points to sort P.OrderBy(p => // Order the points by: p.Zip(B, (x, y) => // Take each point and combine it with the base: (x - y) * (x - y) // Take each dimension and measure their distance squared ).Sum() // Sum of the distances in each dimension together ) ``` [Answer] # JavaScript (ES6), ~~72~~ 71 bytes This one is not shorter than [Neil's answer](https://codegolf.stackexchange.com/a/142503/58563), but I thought I would post it anyway to demonstrate the use of **[`Math.hypot()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/hypot)**, which was introduced in ES6. Takes input in currying syntax `(p)(a)`, where ***p = [ x,y,z ]*** is the base point and ***a*** is the array of other points. ``` p=>a=>a.sort((a,b)=>(g=a=>Math.hypot(...a.map((v,i)=>v-p[i])))(a)-g(b)) ``` ``` let f = p=>a=>a.sort((a,b)=>(g=a=>Math.hypot(...a.map((v,i)=>v-p[i])))(a)-g(b)) console.log(JSON.stringify(f([5, 5, 5])([[0, 0, 0], [10, 10, 10], [2, 0, 8], [10, 3, 1], [4, 4, 5], [5, 5, 5], [5, 5, 4]]))) console.log(JSON.stringify(f([2, 3, 3])([[3, 0, 4], [5, 0, 3], [0, 2, 4], [0, 3, 5], [4, 2, 1], [2, 2, 2], [3, 1, 2], [3, 1, 0], [1, 3, 2], [2, 3, 1], [3, 1, 5], [4, 0, 0], [4, 3, 1], [0, 5, 5], [1, 5, 1], [3, 1, 4], [2, 2, 2], [0, 2, 5], [3, 3, 5], [3, 3, 0], [5, 4, 5], [4, 1, 3], [5, 1, 1], [3, 5, 3], [1, 5, 3], [0, 5, 2], [4, 3, 3], [2, 1, 1], [3, 3, 0], [5, 0, 4], [1, 5, 2], [4, 2, 3], [4, 2, 1], [2, 5, 5], [3, 4, 0], [3, 0, 2], [2, 3, 2], [3, 5, 1], [5, 1, 0], [2, 4, 3], [1, 0, 5], [0, 2, 5], [3, 4, 4], [2, 4, 0], [0, 1, 5], [0, 5, 4], [1, 5, 1], [2, 1, 0], [1, 3, 4], [2, 2, 2], [4, 2, 4], [5, 5, 4], [4, 4, 0], [0, 4, 1], [2, 0, 3], [3, 1, 5], [4, 4, 0], [2, 5, 1], [1, 2, 4], [4, 3, 1], [0, 2, 4], [4, 5, 2], [2, 0, 1], [0, 0, 2], [4, 1, 0], [5, 4, 3], [2, 5, 2], [5, 4, 4], [4, 4, 3], [5, 5, 1], [4, 0, 2], [1, 3, 5], [4, 2, 0], [0, 3, 1], [2, 2, 0], [0, 4, 5], [3, 2, 0], [0, 2, 1], [1, 2, 2], [2, 5, 3], [5, 5, 2], [5, 2, 4], [4, 5, 5], [2, 1, 2], [5, 4, 3], [4, 5, 4], [2, 3, 1], [4, 4, 4], [3, 0, 0], [2, 4, 5], [4, 3, 3], [3, 5, 3], [4, 0, 0], [1, 1, 1], [3, 1, 3], [2, 5, 5], [0, 0, 5], [2, 0, 2], [1, 0, 3], [3, 1, 4], [1, 2, 5], [4, 1, 3], [1, 4, 5], [3, 1, 4], [3, 5, 1], [5, 1, 4], [1, 0, 4], [2, 2, 0], [5, 2, 1], [0, 5, 3], [2, 1, 1], [0, 3, 0], [4, 5, 5], [3, 4, 2], [5, 3, 3], [3, 1, 1], [4, 0, 1], [5, 0, 5], [5, 0, 4], [1, 4, 3], [5, 4, 2], [5, 4, 0], [5, 1, 0], [0, 0, 1], [5, 3, 0]]))) console.log(JSON.stringify(f([1, 9, 4])([[4, 6, 2], [7, 5, 3], [10, 5, 2], [9, 8, 9], [10, 5, 10], [1, 5, 4], [8, 1, 1], [8, 6, 9], [10, 4, 1], [3, 4, 10], [4, 7, 0], [7, 10, 9], [5, 7, 3], [6, 7, 9], [5, 1, 4], [4, 3, 8], [4, 4, 9], [6, 9, 3], [8, 2, 6], [3, 5, 1], [0, 9, 0], [8, 4, 3], [0, 1, 1], [6, 7, 6], [4, 6, 10], [3, 9, 10], [8, 3, 1], [10, 1, 1], [9, 10, 6], [2, 3, 9], [10, 5, 0], [3, 2, 1], [10, 2, 7], [8, 4, 9], [5, 2, 4], [0, 8, 9], [10, 1, 6], [0, 8, 10], [5, 10, 1], [7, 4, 5], [4, 5, 2], [0, 2, 0], [8, 3, 3], [6, 6, 6], [3, 0, 2], [0, 1, 1], [10, 10, 8], [6, 2, 8], [8, 8, 6], [5, 4, 7], [10, 7, 4], [0, 9, 2], [1, 6, 6], [8, 5, 9], [3, 7, 4], [5, 6, 6], [3, 1, 1], [10, 4, 5], [1, 5, 7], [8, 6, 6], [4, 3, 7], [2, 1, 0], [6, 4, 2], [0, 7, 8], [8, 3, 6], [9, 2, 0], [1, 3, 8], [4, 4, 6], [5, 8, 9], [9, 4, 4], [0, 7, 3], [8, 3, 4], [6, 7, 9], [8, 7, 0], [0, 7, 7], [8, 10, 10], [10, 2, 5], [6, 9, 5], [6, 2, 7], [0, 9, 6], [1, 4, 1], [4, 3, 1], [5, 7, 3], [9, 6, 8], [4, 1, 7], [4, 0, 8], [3, 4, 7], [2, 3, 6], [0, 0, 7], [5, 3, 6], [7, 3, 4], [6, 7, 8], [3, 7, 9], [1, 9, 10], [2, 1, 2], [2, 8, 2], [0, 3, 0], [1, 1, 9], [3, 5, 2], [10, 5, 3], [5, 2, 9], [6, 9, 0], [9, 5, 0], [7, 1, 10], [3, 3, 8], [2, 5, 1], [3, 10, 10], [6, 2, 2], [10, 7, 2], [4, 3, 1], [4, 2, 1], [4, 2, 8], [6, 8, 5], [3, 10, 0], [1, 1, 7], [6, 9, 6], [6, 2, 4], [5, 5, 7], [5, 4, 5], [9, 8, 1], [9, 8, 1], [0, 10, 6], [1, 1, 9], [3, 8, 8], [3, 1, 5], [5, 7, 4], [4, 3, 6], [5, 4, 7], [6, 0, 8], [7, 8, 1], [9, 8, 4], [2, 10, 0], [3, 4, 5], [9, 3, 10], [7, 4, 1], [2, 1, 9], [10, 8, 1], [10, 3, 7], [2, 0, 6], [3, 8, 4], [10, 0, 2], [9, 9, 10], [8, 9, 5], [4, 10, 2], [8, 3, 4], [4, 2, 10], [9, 1, 6], [6, 1, 3], [4, 1, 3], [2, 9, 0], [5, 6, 5], [8, 8, 3], [5, 5, 0], [7, 6, 9], [1, 1, 5], [3, 0, 4], [1, 10, 6], [8, 0, 2], [0, 7, 3], [8, 9, 8], [2, 1, 8], [3, 1, 10], [4, 5, 9], [7, 6, 10], [3, 6, 10], [5, 9, 8], [9, 3, 3], [2, 2, 3], [9, 9, 0], [7, 2, 2], [0, 0, 9], [8, 7, 4], [9, 2, 9], [0, 6, 4], [9, 4, 3], [10, 1, 3], [5, 9, 10], [5, 10, 6], [6, 3, 10]]))) console.log(JSON.stringify(f([8452, 3160, 6109])([[7172, 5052, 4795], [9789, 4033, 2952], [8242, 213, 3835], [177, 7083, 908], [3788, 3129, 3018], [9060, 464, 2701], [6537, 8698, 291], [9048, 3860, 6099], [4600, 2696, 4854], [2319, 3278, 9825]]))) ``` [Answer] # [k](https://en.wikipedia.org/wiki/K_(programming_language)), 14 bytes ``` {y@<+/x*x-:+y} ``` [Try it online!](https://tio.run/##PVW7chxBCMz9FRuerHIZZpgHWgf@D5VSJQqcSuXyt5@bhr061WpvBhroBu7jx5@P@/395e/X71/PPz@/f/54ef76d7@9v44Dn/MmBz6nysG/s@Hrjq/90NMOg0kaxtOe3s5v768Nl/28dZgazmF7ytHwHl4DXg2@Dc92AqWeiIHbdjYix0lYRmzjiTAKTuvWCiGQB056PQURjb7Aw7vSfuBd@QycRswOhLxNr8hW6xZZPPIcREYuZ1SUGTZiKvGDFCM@sB/5GDMML2EtEdcq//ao96rCyA85JKvhZbQM9i42jLECQWl/MZPvg7kJT4SYWmx0ejW@J35nLCXDjZmkLnKmsq3ejbXke6u4jWiJEJhX9MG6WkU01tIefWJkL7kaxX/qkipraaGV7WAVgxU1cttLdyXDqa9Whkr8SxGjvVUVg5kLY6XiQsXtoWzk3As/OVH2w3h0RTJmVZ2U7lKWQMvO18NhfrNjwnJl12XD@bEPzy8qbAM7N8NtGPPGWL/FvR0L8CtmzoG/gDPx9Kou2Ntk1XHuuN2ocRYD8IHzZs7CEOE7z8hKo4k9/m0qo2kQJ7AItSpJoew0aMcimpfWcpWicIkvSj6CilXijhrMDBPJT6YnPNcKHJsEROG5gTJJ7YqbxShO3cNxA9DhvjgjCVUgVkthkcdJalYN2KRgAbeZx0SdrQYv6YuYUYyzQYVEb45l0r2pQ5wHfm5AzQkP3gfTX8x1sku0ZjI1wykDKWyMi7OzxMZkonsWu2eCuCvoZp3gN2XKkQJHrKTXoDilbilVpy7ZCYKYI1sntY5K27U0mf/kCJPlVtnmpjNKgYxzoq6hXASe9MsVtWrFRk9rPSU76Epusw7lBK3q2EvgSSbWwznmlNF6oUZwtlJuSvbaTrlTXGEHhKfmqvOrpz03Q5yljiwtWFGWoNw3uWOcczzhEe2X@yzichyZe6/pZ2m7ujd7xMmrVpma28TpTd5nTkWYef3WNHaEM0b@ckm1mLExHSeT75Z7I3/A/DFfUUBwk7tm2wCiTpyr@HlbuiC04NCWg8a1ASQdY@wDbDRDTEUmu2NiFjpaNqZdUMDaKF8b8hRFugJImyBuCVbH6FBqOvrPIZcYTHfEFPfTpoCT6ch6D8jYFRhtgZ3dxtPb0/0/ "K (oK) – Try It Online") ``` { } /function(x,y) +y /transpose y x-: /w[j,i] = x[j] - y[j,i] x* /w[j,i]*w[j,i] +/ /v[i] = sum over all j: w[j,i] < /indices to sort by y@ /rearrange list of points by indices ``` Also, this works for n dimensions, and is not limited to 3. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~10~~ 9 bytes *-1 byte thanks to @Shaggy* ``` ñ_íaV m²x ``` Takes points as an array of three-item arrays and the base point an a single array, in that order. Does not take the size argument. [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=8V/tYVYgbbJ4&input=W1s3MTcyLCA1MDUyLCA0Nzk1XSwgWzk3ODksIDQwMzMsIDI5NTJdLCBbODI0MiwgMjEzLCAzODM1XSwgWzE3NywgNzA4MywgOTA4XSwgWzM3ODgsIDMxMjksIDMwMThdLCBbOTA2MCwgNDY0LCAyNzAxXSwgWzY1MzcsIDg2OTgsIDI5MV0sIFs5MDQ4LCAzODYwLCA2MDk5XSwgWzQ2MDAsIDI2OTYsIDQ4NTRdLCBbMjMxOSwgMzI3OCwgOTgyNV1dCls4NDUyLCAzMTYwLCA2MTA5XQotUg==) or run the [huge test case](https://ethproductions.github.io/japt/?v=1.4.5&code=8V/tYVYgbbJ4&input=W1s0LCA2LCAyXSwgWzcsIDUsIDNdLCBbMTAsIDUsIDJdLCBbOSwgOCwgOV0sIFsxMCwgNSwgMTBdLCBbMSwgNSwgNF0sIFs4LCAxLCAxXSwgWzgsIDYsIDldLCBbMTAsIDQsIDFdLCBbMywgNCwgMTBdLCBbNCwgNywgMF0sIFs3LCAxMCwgOV0sIFs1LCA3LCAzXSwgWzYsIDcsIDldLCBbNSwgMSwgNF0sIFs0LCAzLCA4XSwgWzQsIDQsIDldLCBbNiwgOSwgM10sIFs4LCAyLCA2XSwgWzMsIDUsIDFdLCBbMCwgOSwgMF0sIFs4LCA0LCAzXSwgWzAsIDEsIDFdLCBbNiwgNywgNl0sIFs0LCA2LCAxMF0sIFszLCA5LCAxMF0sIFs4LCAzLCAxXSwgWzEwLCAxLCAxXSwgWzksIDEwLCA2XSwgWzIsIDMsIDldLCBbMTAsIDUsIDBdLCBbMywgMiwgMV0sIFsxMCwgMiwgN10sIFs4LCA0LCA5XSwgWzUsIDIsIDRdLCBbMCwgOCwgOV0sIFsxMCwgMSwgNl0sIFswLCA4LCAxMF0sIFs1LCAxMCwgMV0sIFs3LCA0LCA1XSwgWzQsIDUsIDJdLCBbMCwgMiwgMF0sIFs4LCAzLCAzXSwgWzYsIDYsIDZdLCBbMywgMCwgMl0sIFswLCAxLCAxXSwgWzEwLCAxMCwgOF0sIFs2LCAyLCA4XSwgWzgsIDgsIDZdLCBbNSwgNCwgN10sIFsxMCwgNywgNF0sIFswLCA5LCAyXSwgWzEsIDYsIDZdLCBbOCwgNSwgOV0sIFszLCA3LCA0XSwgWzUsIDYsIDZdLCBbMywgMSwgMV0sIFsxMCwgNCwgNV0sIFsxLCA1LCA3XSwgWzgsIDYsIDZdLCBbNCwgMywgN10sIFsyLCAxLCAwXSwgWzYsIDQsIDJdLCBbMCwgNywgOF0sIFs4LCAzLCA2XSwgWzksIDIsIDBdLCBbMSwgMywgOF0sIFs0LCA0LCA2XSwgWzUsIDgsIDldLCBbOSwgNCwgNF0sIFswLCA3LCAzXSwgWzgsIDMsIDRdLCBbNiwgNywgOV0sIFs4LCA3LCAwXSwgWzAsIDcsIDddLCBbOCwgMTAsIDEwXSwgWzEwLCAyLCA1XSwgWzYsIDksIDVdLCBbNiwgMiwgN10sIFswLCA5LCA2XSwgWzEsIDQsIDFdLCBbNCwgMywgMV0sIFs1LCA3LCAzXSwgWzksIDYsIDhdLCBbNCwgMSwgN10sIFs0LCAwLCA4XSwgWzMsIDQsIDddLCBbMiwgMywgNl0sIFswLCAwLCA3XSwgWzUsIDMsIDZdLCBbNywgMywgNF0sIFs2LCA3LCA4XSwgWzMsIDcsIDldLCBbMSwgOSwgMTBdLCBbMiwgMSwgMl0sIFsyLCA4LCAyXSwgWzAsIDMsIDBdLCBbMSwgMSwgOV0sIFszLCA1LCAyXSwgWzEwLCA1LCAzXSwgWzUsIDIsIDldLCBbNiwgOSwgMF0sIFs5LCA1LCAwXSwgWzcsIDEsIDEwXSwgWzMsIDMsIDhdLCBbMiwgNSwgMV0sIFszLCAxMCwgMTBdLCBbNiwgMiwgMl0sIFsxMCwgNywgMl0sIFs0LCAzLCAxXSwgWzQsIDIsIDFdLCBbNCwgMiwgOF0sIFs2LCA4LCA1XSwgWzMsIDEwLCAwXSwgWzEsIDEsIDddLCBbNiwgOSwgNl0sIFs2LCAyLCA0XSwgWzUsIDUsIDddLCBbNSwgNCwgNV0sIFs5LCA4LCAxXSwgWzksIDgsIDFdLCBbMCwgMTAsIDZdLCBbMSwgMSwgOV0sIFszLCA4LCA4XSwgWzMsIDEsIDVdLCBbNSwgNywgNF0sIFs0LCAzLCA2XSwgWzUsIDQsIDddLCBbNiwgMCwgOF0sIFs3LCA4LCAxXSwgWzksIDgsIDRdLCBbMiwgMTAsIDBdLCBbMywgNCwgNV0sIFs5LCAzLCAxMF0sIFs3LCA0LCAxXSwgWzIsIDEsIDldLCBbMTAsIDgsIDFdLCBbMTAsIDMsIDddLCBbMiwgMCwgNl0sIFszLCA4LCA0XSwgWzEwLCAwLCAyXSwgWzksIDksIDEwXSwgWzgsIDksIDVdLCBbNCwgMTAsIDJdLCBbOCwgMywgNF0sIFs0LCAyLCAxMF0sIFs5LCAxLCA2XSwgWzYsIDEsIDNdLCBbNCwgMSwgM10sIFsyLCA5LCAwXSwgWzUsIDYsIDVdLCBbOCwgOCwgM10sIFs1LCA1LCAwXSwgWzcsIDYsIDldLCBbMSwgMSwgNV0sIFszLCAwLCA0XSwgWzEsIDEwLCA2XSwgWzgsIDAsIDJdLCBbMCwgNywgM10sIFs4LCA5LCA4XSwgWzIsIDEsIDhdLCBbMywgMSwgMTBdLCBbNCwgNSwgOV0sIFs3LCA2LCAxMF0sIFszLCA2LCAxMF0sIFs1LCA5LCA4XSwgWzksIDMsIDNdLCBbMiwgMiwgM10sIFs5LCA5LCAwXSwgWzcsIDIsIDJdLCBbMCwgMCwgOV0sIFs4LCA3LCA0XSwgWzksIDIsIDldLCBbMCwgNiwgNF0sIFs5LCA0LCAzXSwgWzEwLCAxLCAzXSwgWzUsIDksIDEwXSwgWzUsIDEwLCA2XSwgWzYsIDMsIDEwXV0KWzEsIDksIDRdCi1S) with `-R` to output one `x,y,z` per line. ## Explanation ``` ñ_ Sort the input array as if each item were mapped through the function... í V Pair the x,y,z in the current item with those in the base point, V a Take the absolute different from each pair m² Square each of the 3 differences x Sum those squares Sorted array is implicitly returned ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes Saved 1 byte, thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun). ``` ạ²SðÞ ``` [Try it online!](https://tio.run/##y0rNyan8///hroWHNgUf3nB43v///6OjDXSAMFZHIdrQQAeMQGwjoKAFVNBYxxDEMtEx0TEFMUx1TBEMk9jY/0CGAgjFAgA "Jelly – Try It Online") # Explanation ``` ạ²SðÞ Þ - Sort by key function. ạ - Absolute difference with the elements in the second input list. ² - Square. Vectorizes. S - Sum. ð - Starts a separate dyadic chain. - Output implicitly. ``` [Answer] # [Perl 6](https://perl6.org), 35 bytes (33 characters) ``` {@^b;@^p.sort:{[+] ($_ Z- @b)»²}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/2iEuydohrkCvOL@oxKo6WjtWQUMlXiFKV8EhSfPQ7kObamv/W3NxFSeC1GvYmCoAoZ2Oho2BAhDa6dgYGiiAEZBpBBSygAgZKxgCGSYKJiDFME1g2sROU5PrPwA "Perl 6 – Try It Online") **Explanation:** This takes a list with the coordinates of the base point (called `@b`), then a list of lists with coordinates of the other points (called `@p`). In a block, you can use them on the fly using the `^` symbol. Each of the `^`'d variables corresponds to one argument. (They're sorted alphabetically, so `@^b` is the 1st argument and `@^p` the 2nd.) After one use of this symbol, you can use the variable normally. The statement `@^b` is there just to say that the block will take the base point argument, which is used only inside the sorting block. (Otherwise it would refer to the argument of the sorting block.) The method `.sort` may take one argument. If it's a block taking 1 argument (like here), the array is sorted according to the values of that function. The block itself just takes each point in turn and zips it with minus (`Z-`) with the base point coordinates. Then we square all the elements in the list with `»²` and sum them using `[+]`. **As an added bonus,** this will work with float coordinates as well, and in any dimension (as long as you, obviously, supply the same number of coordinates for all the points, it does the right thing). --- # This is no longer valid. I leave it here just for fun. ## [Perl 6](https://perl6.org), 24 bytes — only a joke! ``` {@^b;@^p.sort:{$_!~~@b}} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYPu/2iEuydohrkCvOL@oxKpaJV6xrs4hqbb2vzUXV3EiSJGGjakCENrpaNgYKAChnY6NoYECGAGZRkAhC4iQsYIhkGGiYAJSDNMEpk3sNDW5/gMA "Perl 6 – Try It Online") Since the OP doesn't state which metric shall be used, this submission chooses to use the discrete metric. In this metric, the distance between two points is 0 if they are identical, and 1 if they are not. It's easy to check that this is indeed a metric (if ρ(A,B) is distance from A to B, we require that 1) ρ(A,B) = 0 iff A = B, 2) ρ(A,B) = ρ(B,A), 3) ρ(A,B) + ρ(B,C) ≥ ρ(A,C) ("triangle inequality")). It could be probably golfed a lot more, but I don't mean it seriously. [Answer] # [Kotlin](https://kotlinlang.org) 1.1, 58 bytes ``` {t,i->i.sortedBy{it.zip(t).map{(f,s)->(f-s)*(f-s)}.sum()}} ``` ## Beautified ``` // t is the target, i is the list of inputs { t, i -> // Sort the inputs by the distance i.sortedBy { // For each dimension it.zip(t) // Calculate the square of the distance .map { (f, s) -> (f - s) * (f - s) } // Add up the squares .sum() } } ``` ## Test ``` var f: (List<Int>, List<List<Int>>) -> List<List<Int>> = {t,i->i.sortedBy{it.zip(t).map{(f,s)->(f-s)*(f-s)}.sum()}} data class TestData(val target: List<Int>, val input: List<List<Int>>, val output: List<List<Int>>) fun main(args: Array<String>) { val items = listOf( TestData(listOf(5, 5, 5), listOf(listOf(0, 0, 0), listOf(10, 10, 10), listOf(2, 0, 8), listOf(10, 3, 1), listOf(4, 4, 5), listOf(5, 5, 5), listOf(5, 5, 4)), listOf(listOf(5, 5, 5), listOf(5, 5, 4), listOf(4, 4, 5), listOf(2, 0, 8), listOf(10, 3, 1), listOf(0, 0, 0), listOf(10, 10, 10)) ), TestData(listOf(8452, 3160, 6109), listOf(listOf(7172, 5052, 4795), listOf(9789, 4033, 2952), listOf(8242, 213, 3835), listOf(177, 7083, 908), listOf(3788, 3129, 3018), listOf(9060, 464, 2701), listOf(6537, 8698, 291), listOf(9048, 3860, 6099), listOf(4600, 2696, 4854), listOf(2319, 3278, 9825)), listOf(listOf(9048, 3860, 6099), listOf(7172, 5052, 4795), listOf(9789, 4033, 2952), listOf(8242, 213, 3835), listOf(4600, 2696, 4854), listOf(9060, 464, 2701), listOf(3788, 3129, 3018), listOf(2319, 3278, 9825), listOf(6537, 8698, 291), listOf(177, 7083, 908)) )) items.map { it to f(it.target, it.input) }.filter { it.first.output != it.second }.forEach { System.err.println(it.first.output) System.err.println(it.second) throw AssertionError(it.first) } println("Test Passed") } ``` [Answer] # Java 8, ~~194 + 31~~ ~~214~~ ~~169~~ ~~163~~ ~~123~~ ~~112~~ ~~106 + 19~~ ~~109~~ 103 bytes ``` B->P->P.sort(java.util.Comparator.comparing(p->{int d=0,i=0;while(i<3)d+=(d=p[i]-B[i++])*d;return d;})) ``` [Try it online!](https://tio.run/##ZVVNb6MwEL3nV/gIDUH@PCUgbSvtaVeK1L1FObjANs4mgMC0iiJ@e9aA6dg0qtTpZD7eezPjnuWH3FR1UZ7zfw91ratGo7PxxZ1Wl/hvV2ZaVWX8tF19@9L4VnX3dlEZyi6ybdFvqUp0XyHzabXUxv/T5u9UqQ/H6KUq2@5aNLtfqtWTL01TdErQ43mT7s1P3JoeAfR4qa61bKSumjgbTVW@B/UmvZtklCc4Ugnefp7UpQjUjoX5OgnypD6o4@b5oNbrY/iUb5tCd02J8m0fhg/AbCF@VCpHV4M8eNVD9cMRyea9DS2R4TMCNf49SlBZfM5/3@8sQjhCvI/QXYwmG0zzm1rv4IqQGEw@eslg0tGkg2m@JZ6JB5OMadTGMps2BczFsI3lEGBcwgaQ0XTS@KLxBFLYAOaZ2BLi0I1YbmI057rCegmYEwYKyJht7KQ5LWb5iJdGbZqvmQCQ3FaYBuAIRQEZAbzYBnDAi20xXwcOQs0tMKg@ceMLfelybkupOeyDgArca8Gh2LxG/rg5sJgbE6jrL4HjFaAOhgAMyIg3bgYtKHgdvAxYEFhECuSdXcdwAc7aO4xn1R0v9bhRgOM0npH5NAXMgi4IcVDdOScO3BicE/XWnsEsBBTDMG7iHRlbbCqGPaOeUP6MOTBe3hvxhCKA119wDnX5QmoBomJg4RwkhoPkyyOblWQeXmfyBO5YfD9pZ2G4Nxa8uE3sFRvh9Oalnh/gUyzr@nILvh5fO0fWh7HMsqLWwY@mkbc2lu3wryXYh6GT/nprdXGNq07HtXniv4Lzoqj/VNOzP6UM0f2qf/wH "Java (OpenJDK 8) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` yZP&SY) ``` Inputs are: 3-column matrix with points as rows, and 3-column vector with base point. Try it at [**MATL Online!**](https://matl.io/?code=yZP%26SY%29&inputs=%5B0%2C+0%2C+0%3B+10%2C+10%2C+10%3B+2%2C+0%2C+8%3B+10%2C+3%2C+1%3B+4%2C+4%2C+5%3B+5%2C+5%2C+5%3B+5%2C+5%2C+4%5D%0A%5B5+5+5%5D&version=20.4.1) ### Explanation ``` y % Implicitly take two inputs: 3-column matrix and 3-row vector. Duplicate the first % STACK: input 1 (matrix), input 2 (vector), input 1 (matrix) ZP % Euclidean distance between rows of top two elements in stack % STACK: input 1 (matrix), distances (vector) &S % Sort and push the indices of the sorting (not the sorted values) % STACK: input 1 (matrix), indices (vector) Y) % Use as row indices. Implicitly display % STACK: final result (matrix) ``` [Answer] # Pyth, 6 bytes ``` o.a,vz ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=o.a%2Cvz&input=%5B0%2C0%2C0%5D%2C+%5B10%2C10%2C10%5D%2C+%5B2%2C0%2C8%5D%2C+%5B10%2C3%2C1%5D%2C+%5B4%2C4%2C5%5D%2C+%5B5%2C5%2C5%5D%2C+%5B5%2C5%2C4%5D%0A%5B5%2C5%2C5%5D&debug=0) ### Explanation: ``` o.a,vzNQ implicit variables at the end o Q order the points from the first input line by: .a the euclidean distance between N the point , and vz the point from the second input line ``` [Answer] # [Perl 5](https://www.perl.org/), 90 bytes ``` sub v{$i=$t=0;$t+=($_-$p[$i++])**2for pop=~/\d+/g;$t}@p=<>=~/\d+/g;say sort{v($a)<=>v$b}<> ``` [Try it online!](https://tio.run/##PYvRCoIwGIXvfQov/gt1MzebELRJL9ATmISShRBtuCWE2KO3/oziHDiHj3NMN1wL7@29DccJegVOsS04oiI4pmAq6Amp4yTJz3oIjTbqmR1OJLvgZt4ZJcs/sM0jtHpw0xhBE0tVjtDOsvS@KiiqDipGUZic0cVYc0SbL1pTjkVQsWx/n0@KOnhp43p9sz7dFyvG2Rs "Perl 5 – Try It Online") Input is newline separated list of points, with the first one being the base point and the last having a trailing newline. Brackets (`[]`) around the coordinates are optional. ]
[Question] [ A *Bell number* ([OEIS A000110](https://oeis.org/A000110)) is the number of ways to partition a set of n labeled (distinct) elements. The 0th Bell number is defined as 1. Let's look at some examples (I use brackets to denote the subsets and braces for the partitions): ``` 1: {1} 2: {[1,2]}, {[1],[2]} 3: {[1,2,3]}, {[1,2],[3]}, {[1,3],[2]}, {[2,3],[1]}, {[1],[2],[3]} ``` There are [many ways](http://fredrikj.net/blog/2015/08/computing-bell-numbers/) to compute Bell numbers, and you are free to use any of them. One way will be described here: The easiest way to compute Bell numbers is to use a number triangle resembling Pascal's triangle for the binomial coefficients. The Bell numbers appear on the edges of the triangle. Starting with 1, each new row in the triangle is constructed by taking the last entry in the previous row as the first entry, and then setting each new entry to its left neighbor plus its upper left neighbor: ``` 1 1 2 2 3 5 5 7 10 15 15 20 27 37 52 ``` You may use 0-indexing or 1-indexing. If you use 0-indexing, an input of `3` should output `5`, but should output `2` if you use 1-indexing. Your program must work up to the 15th Bell number, outputting `1382958545`. In theory, your program should be able to handle larger numbers (in other words, don't hardcode the solutions). **EDIT: You are not required to handle an input of 0 (for 0-indexing) or 1(for 1-indexing) because it is not computed by the triangle method.** Test cases (assuming 0-indexing): ``` 0 -> 1 (OPTIONAL) 1 -> 1 2 -> 2 3 -> 5 4 -> 15 5 -> 52 6 -> 203 7 -> 877 8 -> 4140 9 -> 21147 10 -> 115975 11 -> 678570 12 -> 4213597 13 -> 27644437 14 -> 190899322 15 -> 1382958545 ``` Answers using a built-in method (such as BellB[n] in the Wolfram Language) that directly produces Bell numbers will be noncompetitive. Shortest code (in bytes) wins. [Answer] ## JavaScript (ES6), 47 bytes ``` f=(n,a=[b=1])=>n--?f(n,[b,...a.map(e=>b+=e)]):b f=(n,a=[b=1])=>--n?f(n,[b,...a.map(e=>b+=e)]):b ``` First one is 0-indexed, second is 1-indexed. [Answer] ## Haskell, 36 bytes ``` head.(iterate(last>>=scanl(+))[1]!!) ``` Uses the triangle method, correctly handles 0, 0-based. [Answer] # [R](https://www.r-project.org/), 31 bytes ``` sum(gmp::Stirling2.all(scan())) ``` uses the [Stirling Number of the Second Kind formula](https://en.wikipedia.org/wiki/Bell_number#Properties) and calculates those numbers with the [gmp package](https://cran.r-project.org/web/packages/gmp/index.html); reads from stdin and returns the value as a Big Integer; fails for 0; 1-indexed. [Answer] # Mathematica , 24 bytes ``` Sum[k^#/k!,{k,0,∞}]/E& ``` -13 bytes from @Kelly Lowder! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ ~~12~~ 11 bytes ``` ṫ0;⁸+\ 1Ç¡Ḣ ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4bmrMDvigbgrXAoxw4fCoeG4ov///zE1 "Jelly – Try It Online") Didn't exactly hit the strong points of Jelly with ~~dynamic input to `¡`,~~ `Ṫ` always modifying the array and the lack of a prepending atom (one-byte `;@` or reverse-`ṭ`). [Answer] ## CJam (19 bytes) ``` Xa{X\{X+:X}%+}qi*0= ``` [Online demo](http://cjam.aditsu.net/#code=Xa%7BX%5C%7BX%2B%3AX%7D%25%2B%7Dqi*0%3D&input=15) ### Dissection ``` Xa e# Start with an array [1] { e# Repeat... X\ e# Put a copy of X under the current row {X+:X}% e# Map over x in row: push (X+=x) + e# Prepend that copy of last element of the previous row to get the next row } qi* e# ... input() times 0= e# Select the first element ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` :dtEw1Zh1Ze/Yo ``` Input is 0-based. [Try it online!](https://tio.run/##y00syfn/3yqlxLXcMCrDMCpVPzL//39DUwA "MATL – Try It Online") ### Explanation This uses the [formula](http://mathworld.wolfram.com/BellNumber.html) [![enter image description here](https://i.stack.imgur.com/oekpY.gif)](https://i.stack.imgur.com/oekpY.gif) where *p* *F**q* (*a*1, ..., *a**p*; *b*1, ..., *b**q*; *x*) is the [generalized hypergeometric function](https://en.wikipedia.org/wiki/Generalized_hypergeometric_function). ``` : % Implictly input n. Push array [1 2 ... n] d % Consecutive differences: array [1 ... 1] (n-1 entries) tE % Duplicate, multiply by 2: array [2 ... 2] (n-1 entries) w % Swap 1 % Push 1 Zh % Hypergeometric function 1Ze % Push number e / % Divide Yo % Round (to prevent numerical precision issues). Implicitly display ``` [Answer] # [Python](https://docs.python.org/3/), 42 bytes ``` f=lambda n,k=0:n<1or k*f(n-1,k)+f(n-1,k+1) ``` [Try it online!](https://tio.run/##LcpBDkAwEEbhNaeYZUcrMbFrOEyFIuXXNDZOPyzsXvK9/NzbhV41jkc4pzkQXBo7j0GuQqmJBq24xPYPK6zxE9AOKgHrYsSJsK@rXHbcBo6@lVlf "Python 3 – Try It Online") The recursive formula comes from placing `n` elements into partitions. For each element in turn, we decide whether to place it: * Into an existing partition, of which there are `k` choices * To start a new partition, which increases the number of choices `k` for future elements Either way decreases the remaining number `n` of elements to place. So, we have the recursive formula `f(n,k)=k*f(n-1,k)+f(n-1,k+1)` and `f(0,k)=1`, with `f(n,0)` the n-th Bell number. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ṖµṀcæ.߀‘ ``` This uses the formula ![formula](https://i.stack.imgur.com/CWDIK.png) which is closed whenever **n < 2**. [Try it online!](https://tio.run/##ASsA1P9qZWxsef//4bmWwrXhuYBjw6Yuw5/igqzigJj/MHIxNcK1xbzDh@KCrEf/ "Jelly – Try It Online") ### How it works ``` ṖµṀcæ.߀‘ Main link. Argument: n Ṗ Pop; yield A := [1, ..., n-1]. µ Begin a new, monadic chain with argument A. Ṁ Maximum; yield n-1. c Combinatons; compute (n-1)C(k) for each k in A. ߀ Recursively map the main link over A. æ. Take the dot product of the results to both sides. ‘ Increment; add 1 to the result. ``` [Answer] # [Python 2](https://docs.python.org/2/), 91 bytes ``` s=lambda n,k:n*k and k*s(n-1,k)+s(n-1,k-1)or n==k B=lambda n:sum(s(n,k)for k in range(n+1)) ``` [Try it online!](https://tio.run/##RYsxDoMwEAT7vOJKH5jCKSgsueEnRoTkdLAgmxR5vXGkiHSr2Zn9c7w23EvJYYnrOEWCVY9GKWIibbJB56xy@xud4y0RQtDbcBU@v1dTherN9VUSUIp4Pgxax1y@UP7Q9expT4KDxNJghMsJ "Python 2 – Try It Online") B(n) calculated as a sum of Stirling numbers of the second kind. [Answer] # MATLAB, ~~128~~ 103 bytes ``` function q(z) r(1,1)=1;for x=2:z r(x,1)=r(x-1,x-1);for y=2:x r(x,y)=r(x,y-1)+r(x-1,y-1);end end r(z,z) ``` Pretty self explanatory. Omitting a semicolon at the end of a line prints the result. 25 bytes saved thanks to Luis Mendo. [Answer] # [R](https://www.r-project.org/), 46 bytes ``` r=1;for(i in 1:scan())r=cumsum(c(r[i],r));r[1] ``` [Try it online!](https://tio.run/##K/r/v8jW0Dotv0gjUyEzT8HQqjg5MU9DU7PINrk0t7g0VyNZoyg6M1anSFPTuijaMPa/oel/AA "R – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~19~~ 18 bytes ``` 1i:"t@q@:qXn*sh]0) ``` Uses 0-based input. Based on the [recurrence relation](http://mathworld.wolfram.com/BellNumber.html) [![enter image description here](https://i.stack.imgur.com/RmltW.gif)](https://i.stack.imgur.com/RmltW.gif) [Try it online!](https://tio.run/##y00syfn/3zDTSqnEodDBqjAiT6s4I9ZAEyhmCgA) [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), 15 bytes ``` 2°M^┼ⁿ^!/Σ;αê/≈ ``` [Try it online!](https://tio.run/##ASIA3f9vaG3//zLCsE1e4pS84oG/XiEvzqM7zrHDqi/iiYj//zE1 "Ohm – Try It Online") Uses Dobinski's forumla (even works for B(0) *yay*). ### Explanation ``` 2°M^┼ⁿ^!/Σ;αê/≈ 2° ; # Push 100 M # Do 100 times... ^ # Push index of current iteration ┼ⁿ # Take that to the power of the user input ^! # Push index factorial / # Divide Σ # Sum stack together αê # Push e (2.718...) / # Divide ≈ # Round to nearest integer (Srsly why doesn't 05AB1E have this???) ``` [Answer] ## Python (79 bytes) ``` B=lambda n,r=[1]:n and B(n-1,[r[-1]+sum(r[:i])for i in range(len(r)+1)])or r[0] ``` [Online demo](https://tio.run/##XcwxDoMwDEbhq3iMRZDqDh0isXANy0MqaGsJfpBLh54@Ze78Pr39e7w2XFsbh6Wu96kScgwqVkAVE40JvWQN7cW692dNocWNH1uQk4Oi4jmnZUYK7oSNzxB6sfYn5MaF9nAc5Pm8Orcf) in Python 2, but it also works in Python 3. This builds Aitken's triangle using a recursive lambda for a golfy loop. [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` (%0) n%k|n<1=1|m<-n-1=k*m%k+m%(k+1) ``` [Try it online!](https://tio.run/##BcExDoAgDADA3Vd0kAQ0ELrTlxgHBomktCHqyN/x7s4vX63NWcia6BY1PDQh4ZDk1SPxJoZ3MZZ3dFNyVSDoT9UPVpDcocCBIWA85w8 "Haskell – Try It Online") Formula explained in [my Python answer](https://codegolf.stackexchange.com/a/132432/20260). [Answer] # J, 17 bytes ``` 0{]_1&({+/\@,])1: ``` Uses the triangle calculation method. [Try it online!](https://tio.run/##y/r/P03B1krBoDo23lBNo1pbP8ZBJ1bT0IqLKzU5I19BQ0cvTclAUyFTT8HQ7P9/AA "J – Try It Online") ## Explanation ``` 0{]_1&({+/\@,])1: Input: integer n 1: The constant 1 ] Identity function, get n _1&( ) Call this verb with a fixed left argument of -1 n times on itself starting with a right argument [1] ] Get right argument { Select at index -1 (the last item) , Join +/\@ Find the cumulative sums 0{ Select at index 0 (the first item) ``` [Answer] # [Python 3](https://docs.python.org/3/), 78 bytes ``` from math import* f=lambda n:ceil(sum(k**n/e/factorial(k)for k in range(2*n))) ``` I decided to try and go a different route for calculation. This uses Dobinski's formula, 0-indexed, doesn't work for 0. [Try it online!](https://tio.run/##VY/BbsMgEETv@QqOYFWKFxYDlfoxJDUNsgGL0EO/3oFKlbbHeZrZnTl@2qNkdZ6hlsSSbw8W01Fqmy7hY/fp9ulZfr@vcefP78S3acrX9Rr8vZUa/c43EUplG4uZVZ@/Vi6nLIQ4jxpz44GDeGMg2OVPy64l0aprTTQOPwV6GGhiGRdmRYjpxBpDiO0EAWeC3IgBILXBPL6BdoZ@hNF5MVYbmofRHCWo7qZ4DJBmQUT1j/8OcbN1TklaH8YgUFY6bTVqcb4A "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~68~~ 60 bytes Simple recursive construction of the triangle, but it's wildly inefficient for practical purposes. Calculating up to the 15th Bell number causes TIO to time out, but it works on my machine. This uses 1-indexing, and returns `True` instead of 1. ``` f=lambda r,c=0:r<1or c<1and f(r-1,r-1)or f(r-1,c-1)+f(r,c-1) ``` [Try it online!](https://tio.run/##JYtBCoAgEEXXeYpZKhko7aQOY5o1UGMMbTq9DbX48N6Dfz33XmlsrcxHPJccgW2aXeDJV4Y0@UgZiubBW5mR9ksS6QU/aEU6AhJwpG3V3pmguouRbo1WHmiMai8 "Python 3 – Try It Online") --- **Thanks to @FelipeNardiBatista for saving 8 bytes!** [Answer] # [PHP](https://php.net/), 72 bytes recursive function 1-indexed ``` function f($r,$c=0){return$r?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;} ``` [Try it online!](https://tio.run/##NYrBCoUgEEV/JWQWDSpkvFUW/kg7SZqNymCrR99uE7y3uRzOPfWsfQ1VNl05Nip5SCOwgbhN@OWjXZyBA8TwauvksA71rxFc/p7tjIvzd0@FR6Bt8kBar@7j8YhnATJqb8pITiiYle8P "PHP – Try It Online") # [PHP](https://php.net/), 86 bytes 0-indexed ``` for(;$r++<$argn;)for($c=~0;++$c<$r;)$l=$t[$r][$c]=$c?$l+$t[$r-1][$c-1]:($l?:1);echo$l; ``` [Try it online!](https://tio.run/##HcyxCoMwFEbh3cew/5AQCpVu3gSH4tClXbqJhBJSFYIJl8y@eqouZ/iGk@ZUdJfmVHnmyJZ9ipyXdRJbb1/vz/PRS6rw5Wk19b2m8ossCKyUPpHkAXBmu5FScBpMEsEgD@BxgBsNXIegTrg2B@1tBULXNpK8myMClUviZc12X2VJ5Q8 "PHP – Try It Online") # [PHP](https://php.net/), 89 bytes recursive function 0-indexed ``` function f($r,$s=NULL){$c=$s??$r-1;return$r>1?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;} ``` [Try it online!](https://tio.run/##NYvBCsMgEER/pcgeIip0C73EWH8g9NZbbxLJXlQ25hT67dZQehlmHm/KWtrkS8@4p1App0scgDVs7vmaZ3lAcLB5D2zQ8lJ3TsAP9BD86RnUEAxK9TuddfxzNjc5ov20mHkAclcLNOHdyiWsGUiLdxW6y6SU7CMJ274 "PHP – Try It Online") [Answer] # [Alice](https://github.com/m-ender/alice), 22 bytes ``` /oi \1@/t&wq]&w.q,+k2: ``` [Try it online!](https://tio.run/##S8zJTE79/18/P5MrxtBBv0StvDBWrVyvUEc728jq/39DUwA "Alice – Try It Online") This uses the triangle method. For n=0, this calculates B(1) instead, which is conveniently equal to B(0). ### Explanation This is a standard template for programs that take input in ordinal mode, process it in cardinal mode, and output the result in ordinal mode. A `1` has been added to the template to put that value on the stack below the input. The program uses the stack as an expanding circular queue to calculate each row of the triangle. During each iteration past the first, one implicit zero below the stack becomes an explicit zero. ``` 1 Append 1 to the implicit empty string on top of the stack i Get input n t&w Repeat outer loop that many times (push return address n-1 times) q Get tape position (initially zero) ] Move right on tape &w On iteration k, push this return address k-1 times The following inner loop is run once for each entry in the next row . Duplicate top of stack (the last number calculated so far) q, Move the entry k spaces down to the top of the stack: this is the appropriate entry in the previous row, or (usually) an implicit zero if we're in the first column + Add these two numbers k Return to pushed address: this statement serves as the end of two loops simultaneously 2: Divide by two: see below o Output as string @ Terminate ``` The first iteration effectively assumes an initial stack depth of zero, despite the required 1 at the top of the stack. As a result, the 1 ends up getting added to itself, and the entire triangle is multiplied by 2. Dividing the final result by 2 gives the correct answer. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes ``` n->n!*Vec(exp(exp(x+O(x^n++))-1))[n] ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y5PUSssNVkjtaIAjCu0/TUq4vK0tTU1dQ01NaPzYv@n5Rdp5AFVG@goGANxQVFmXglQQElB1w5IpGnkaWpq/gcA "Pari/GP – Try It Online") [Answer] # Mathematica, 5 bytes Definitely, Mathematica has built-in. [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yk1J8fpf5qCvoNCUGJeemq0kUGsgoK@fkBRZl6J9X8A) ``` BellB ``` ]
[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/10759/edit). Closed 6 years ago. [Improve this question](/posts/10759/edit) Write a program which displays the current system time as an analog clock, using ASCII graphics. The clock must show at least the hour and minute pointers, and must have enough resolution of at least 5 minutes. The display can be as small and as ugly as you wish, but the shown time should be easily recognizable. The program has to run continuously and update its status. If your system can clear the screen, use it, otherwise it's enough to repaint the clock when its state changes. You get a -20% bonus on the character count if the clock has at least a 1 minute resolution. [Answer] ## Javascript 370 - 74 = 296 <http://jsfiddle.net/wBKQ6/7/> (This only works in Chrome because I'm abusing the fact that element IDs are added to the global scope). ``` (function loop(){ M=Math;p=M.PI/2;z=M.pow;q=M.sqrt;d=new Date();h=(d.getHours()%12/3*p+p)%(p*4);m=(d.getMinutes()/15*p+p)%(p*4);s=(d.getSeconds()/15*p+p)%(p*4);e=49;o=''; for(r=0;r<99;r++){ for(c=0;c<99;c++){ d=q(z(r-e,2)+z(c-e,2)); a=(M.atan2(e-r,e-c)+p*4)%(p*4); E=(d<e*.8&&M.abs(m-a)*d<.5) || (d<e*.5&&M.abs(h-a)*d<.5) || (d<e*1&&M.abs(s-a)*d<.5); o+=d-e>0||d<1||E||(e-d<5&&a%p==0)?'●':'○'; //■□●○ } o+='\n'; } O.innerText=o setTimeout(loop,1000); })() ``` Golfed (370): ``` !function L(){p=M.PI/2;q=p*4;P=M.pow;d=new Date();s=(d.getSeconds(S=d.getMinutes(e=40))/15*p+p)%q;m=(S/15*p+p)%q;h=(d.getHours(A=M.abs)%12/3*p+S/180*p+p)%q;for(r=o='';r<81;r++,o+='\n')for(c=0;c<81;){d=M.sqrt(P(r-e,2)+P(c-e,2));a=(M.atan2(e-r,e-c++)+q)%q;o+='○●'[d-e>0|d<e*.8&A(m-a)*d<1|d<e/2&A(h-a)*d<1|d<e&A(s-a)*d<1|e-d<5&a%p==0]}O.innerText=o;setTimeout(L,9)}(M=Math) ``` Sample Output (much more condensed in demo): ``` ●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●● ●●●●●●●●●●●●●●○○○○○○●○○○○○○●●●●●●●●●●●●●● ●●●●●●●●●●●●○○○○○○○○●○○○○○○○○●●●●●●●●●●●● ●●●●●●●●●●○○○○○○○○○○●○○○○○○○○○○●●●●●●●●●● ●●●●●●●●○○○○○○○○○○○○●○○○○○○○○○○○○●●●●●●●● ●●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●● ●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●● ●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●● ●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●● ●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●● ●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●● ●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●● ●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●● ●●○○○○○○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○●● ●○○○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○○○○○●●○○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○○○○● ●●●●●○○○○○○○○○○○○○○○●○○○○○○○○○○○○○○○●●●●● ●○○○○○○○○○○○○○○○○○○●○●○○○○○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○○●○○●○○○○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○●○○○○●●○○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○○●○○○○○●●○○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○○●○○○○○○○●●○○○○○○○○○○○○○● ●○○○○○○○○○○○○○○○●●○○○○○○○○●●○○○○○○○○○○○○● ●●○○○○○○○○○○○○○○●○○○○○○○○○○○●○○○○○○○○○○●● ●●○○○○○○○○○○○○○●○○○○○○○○○○○○○●○○○○○○○○○●● ●●●○○○○○○○○○○○○●○○○○○○○○○○○○○○●○○○○○○○●●● ●●●○○○○○○○○○○○●○○○○○○○○○○○○○○○○●○○○○○○●●● ●●●●○○○○○○○○○○●○○○○○○○○○○○○○○○○○●○○○○●●●● ●●●●○○○○○○○○○●○○○○○○○○○○○○○○○○○○○●●○○●●●● ●●●●●○○○○○○○●●○○○○○○○○○○○○○○○○○○○○●●●●●●● ●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●● ●●●●●●●○○○○○○○○○○○○○○○○○○○○○○○○○○○●●●●●●● ●●●●●●●●○○○○○○○○○○○○●○○○○○○○○○○○○●●●●●●●● ●●●●●●●●●●○○○○○○○○○○●○○○○○○○○○○●●●●●●●●●● ●●●●●●●●●●●●○○○○○○○○●○○○○○○○○●●●●●●●●●●●● ●●●●●●●●●●●●●●○○○○○○●○○○○○○●●●●●●●●●●●●●● ●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●● ``` [Answer] ## Python, 328 - 65 = 263 Prints a new clock every second, with the minute hand updating every minute. ``` import math,time def p(t,r):c[int(25-r*math.cos(t))][int(25+r*math.sin(t))]='*' while 1: time.sleep(1);c=[[' ']*50 for i in range(50)];t=time.localtime();h=t.tm_hour*6.283+t.tm_min/9.549 for i in range(999): p(i/158.0,24);p(h,i*.02);p(h/12,i*.01) for q in range(12):p(q/1.91,24-i*.005) for y in range(50):print''.join(c[y]) ``` The clocks it prints look like this (it's not as stretched in my terminal): ``` ************** **** * **** *** * *** *** * *** ** ** * ** ** ** * * ** ** ** ** ** * * * ** ** ** ** ** ** ** * * *** *** * *** *** * ** ** ** ** * * * * ** ** * * * * * * ****** * * ****** * * ****** * * ***** * ***** * ****** * ** * * ** * * * * * ** * * ** * ** ** ** * * * * * * ** ** ** ** * *** *** * *** *** * * ** ** ** ** ** ** * * * * ** ** ** ** ** * * ** ** ** * ** ** *** * *** *** * *** **** * **** ************** * ``` [Answer] # Mathematica 207 - 42 = 165 The ticks and hour labels are placed on the unit circle. `H` and `M` revolve around the clock center showing the whole number of completed hours and minutes, respectively. `S` updates its position several times each second. Two versions are shown: a version that plots text in the Cartesian plane, and another that displays text characters in a grid. This version plots the characters into the Cartesian plane. ``` d = Dynamic; t = Table; x = Text;i_~u~k_ := {Sin[2 \[Pi] i/k], Cos[2 \[Pi] i/k]}; d[{f = Date[], Clock[{1, 1}, 1]}] Graphics[d@{t[x[".", u[i, 60]], {i, 60}],t[x[i, u[i, 12]], {i, 12}], x["H", .7 u[f〚4〛, 12]],x["M", .8 u[f〚5〛, 60]],x["S", .9 u[f〚6〛, 60]]}] ``` The clock below shows the time **3:08:17**. ![clock](https://i.stack.imgur.com/Gj5z1.png) **Terminal or Grid Version**: 430 316 chars (253 with bonus discount) This version works much the same, but places the characters in a 61 x 61 cell grid rather than in the Cartesian plane. It could still be golfed a bit, but I merely wanted to show a (sloppier) terminal-like output in *Mathematica*. ``` d = Dynamic; i_~u~k_ := Round /@ (10 {Sin[2 \[Pi] (i + 3 k/4)/k], Cos[2 \[Pi] (i + 3 k/4)/k]}); d[{f = Date[], Clock[]}] z = Round /@ (# u[f[[#2]], #3] + 11) -> #4 &; t = Table[( u[i, 12] + 11) -> i, {i, 12}]; d@Grid[ReplacePart[ConstantArray["", {21, 21}], Join[z @@@ {{.9, 5, 60, "M"}, {.8, 4, 12, "H"}}, DeleteCases[Table[( u[i, 60] + 11) -> "*", {i, 60}], x_ /; MemberQ[t[[All, 1]], x[[1]]]], t]]] ``` The clock below displays **11:06**. ![terminal clock](https://i.stack.imgur.com/eGtmW.png) --- Just for fun: Here's a non-Ascii version of the analog clock. (60 chars) No external libraries were used. ``` Dynamic@Refresh[ClockGauge@AbsoluteTime[], UpdateInterval -> 1] ``` ![clock3](https://i.stack.imgur.com/cJhxU.png) [Answer] ## 100% pure [bash](/questions/tagged/bash "show questions tagged 'bash'") only! Without fork! A finalized and upgraded version could be found [there](http://f-hauri.ch/vrac/ascii-clock.sh.txt) or on this page: [ascii-clock for geeks](http://fhauri.cartou.ch/ascii-clock/). But don't use it! Read the note at end of this answer, you've been warned! Use this [perl version](https://codegolf.stackexchange.com/a/13009/9424) instead! ### First simple clock without second tick. Scalable and editable: ``` time 2>&1 /tmp/asci-art.sh 10 10 10 . . . 12. . . 11. . 1 . . . . . . 10 2 . H M . . . . . . . 9 3 . . . . . . . . 8 4 . . . . . . 7 . . 5 . . . 6 . . . real 0m0.356s user 0m0.348s sys 0m0.004s ``` Draw a 21x21 (10x2+1) clock at 10H10 in less than one second. This accept 3 arguments: `Usage: ascii-clock.sh [ray of clock] [Hour] [Min]` where default ray is 12, clock drawing is `2 x ray + 1` lines height and double width because of space added to try to obtain a round shape. If the script is called with `0` or `1` argument, it will loop to redraw each minute. Else if at least *Hour* (second param) is specified, It will draw only once and exit. The `H` marker is located at 70% of ray and the `M` marker is located at 90% of ray. **No use of external binaries like `date` or `bc`** for the draw! (Thanks to @manatwork for the *builtin* `read -t` in place if `/bin/sleep`). So all this is done by *builtin* shell commands. It use *ANSI* sequence, but only for loop and to make markers bold. ``` #!/bin/bash # Analog clock in Ascii-Art written in BASH V4.2 += RAY=${1:-12} NowH=$2 NowM=$3 sqrt() { local -a _xx=(600000 200000) local _x1=${_xx[$(($1&1))]} _x0=1 while [ $_x0 -ne $_x1 ] ;do _x0=$_x1 [ $_x0 -eq 0 ] && _x1=0000 || printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 )) printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3} done _x1=0000$_x1 printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4} } clksin() { # $1:moment [0-60], $2:path length, $3:variable name local _csin=(0 104528 207912 309017 406737 500000 587785 669131 743145 809017 866025 913545 951057 978148 994522 1000000) local xsign=1 x=$1 ysign=-1 y=$1 [ $x -gt 30 ] && xsign=-1 x=$((60-x)) [ $x -gt 15 ] && x=$((30-x)) x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]})) [ $y -gt 30 ] && y=$((60-y)) [ $y -gt 15 ] && ysign=1 y=$((30-y)) y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]})) printf ${3+-v} $3 "%.0f %.0f" \ ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6} }; MLEN=000$((900*RAY)) printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3} HLEN=000$((700*RAY)) printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3} declare -A ticks for ((i=1;i<=12;i++));do clksin $((5*(i%12))) $RAY tick ticks[$tick]=$i done while :;do [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1 clksin ${NowM#0} $MLEN NowM [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1 clksin $((5*(${NowH#0}%12))) $HLEN NowH [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console for ((i=0;i<=2*RAY;i++));do x=$((RAY-i)) sqrt $((RAY**2 - ${x#-}**2 )) y0 printf -v y0 "%.0f" $y0 for ((l=0;l<=2*RAY;l++));do y=$((RAY-l)); sqrt $((RAY**2 - ${y#-}**2 )) x0 printf -v x0 "%.0f" $x0 if [ "${ticks["$i $l"]}" ] ;then printf "%-2s" ${ticks["$i $l"]} elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then echo -n .\ elif [ "$i $l" = "$NowM" ] ;then echo -en \\e[1mM\ \\e[0m elif [ "$i $l" = "$NowH" ] ;then echo -en \\e[1mH\ \\e[0m else echo -n \ \ fi done echo -e \\e[K done echo -en \\e[J [ "$2" ] && break # Exit if at least Hour was specified printf -v SleepS "%(%S)T" -1 read -t $((60-${SleepS#0})) foo unset NowH NowM done ``` This could by run as: ``` for time in 10:10 15:00 12:30 06:00 09:15 16:40 ;do echo - $time -{,}{,}{,} ./ascii-clock.sh 5 ${time//:/ } echo -{,,,,,}{,} done | sed 's/\o033\[\(.m\|[JK]\)//g;/-$/!s/$/|/;s/-$/+/' | column -c 80 ``` This will produce something like: ``` +- 10:10 - - - - - - - + - 12:30 - - - - - - - + - 09:15 - - - - - - - + | . . 12. . | . . 12. . | . . 12. . | | 11 1 | 11 H 1 | 11 1 | | 10 2 | 10 2 | 10 2 | |. H M . | . . | . . | |. . | . . | . . | |9 3 | 9 3 | 9 H M 3 | |. . | . . | . . | |. . | . . | . . | | 8 4 | 8 4 | 8 4 | | 7 5 | 7 M 5 | 7 5 | | . . 6 . . | . . 6 . . | . . 6 . . | +- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - + +- 15:00 - - - - - - - + - 06:00 - - - - - - - + - 16:40 - - - - - - - + | . . 12. . | . . 12. . | . . 12. . | | 11 M 1 | 11 M 1 | 11 1 | | 10 2 | 10 2 | 10 2 | |. . | . . | . . | |. . | . . | . . | |9 H 3 | 9 3 | 9 3 | |. . | . . | . . | |. . | . . | . M H . | | 8 4 | 8 4 | 8 4 | | 7 5 | 7 H 5 | 7 5 | | . . 6 . . | . . 6 . . | . . 6 . . | +- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - + ``` Or could be run as: ``` xterm -geom 86x44 -bg black -fg grey -e ./ascii-clock.sh 21 & xterm -geom 103x52 -fn nil2 -bg black -fg grey -e ./ascii-clock.sh 25 & gnome-terminal --geometry 103x52 --zoom .5 -e "./ascii-clock.sh 25" & ``` ### Alternative: With full path drawing: ``` #!/bin/bash # Analog clock in Ascii-Art written in BASH V4.2 += RAY=${1:-12} NowH=$2 NowM=$3 sqrt() { local -a _xx=(600000 200000) local _x1=${_xx[$(($1&1))]} _x0=1 while [ $_x0 -ne $_x1 ] ;do _x0=$_x1 [ $_x0 -eq 0 ] && _x1=0000 || printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 )) printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3} done _x1=0000$_x1 printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4} } clksin() { # $1:moment [0-60], $2:path length, $3:variable name local _csin=(0 104528 207912 309017 406737 500000 587785 669131 743145 809017 866025 913545 951057 978148 994522 1000000) local xsign=1 x=$1 ysign=-1 y=$1 [ $x -gt 30 ] && xsign=-1 x=$((60-x)) [ $x -gt 15 ] && x=$((30-x)) x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]})) [ $y -gt 30 ] && y=$((60-y)) [ $y -gt 15 ] && ysign=1 y=$((30-y)) y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]})) printf ${3+-v} $3 "%.0f %.0f" \ ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6} }; MLEN=000$((900*RAY)) printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3} HLEN=000$((700*RAY)) printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3} declare -A ticks for ((i=1;i<=12;i++));do clksin $((5*(i%12))) $RAY tick ticks[$tick]=$i done while :;do [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1 unset MPath declare -A MPath for ((i=1;i<=MLEN;i++));do clksin ${NowM#0} $i tick MPath[$tick]=M done [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1 unset HPath declare -A HPath for ((i=1;i<=HLEN;i++));do clksin $((5*(${NowH#0}%12))) $i tick HPath[$tick]=H done [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console for ((i=0;i<=2*RAY;i++));do x=$((RAY-i)) sqrt $((RAY**2 - ${x#-}**2 )) y0 printf -v y0 "%.0f" $y0 for ((l=0;l<=2*RAY;l++));do y=$((RAY-l)); sqrt $((RAY**2 - ${y#-}**2 )) x0 printf -v x0 "%.0f" $x0 if [ "${MPath["$i $l"]}" ] ;then echo -en \\e[1m${MPath["$i $l"]}\ \\e[0m elif [ "${HPath["$i $l"]}" ] ;then echo -en \\e[1m${HPath["$i $l"]}\ \\e[0m elif [ "${ticks["$i $l"]}" ] ;then printf "%-2s" ${ticks["$i $l"]} elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then echo -n .\ else echo -n \ \ fi done echo -e \\e[K done echo -en \\e[J [ "$2" ] && break # Exit if at least Hour was specified printf -v SleepS "%(%S)T" -1 read -t $((60-${SleepS#0})) foo unset NowH NowM done ``` could produce: ``` +- 10:10 - - - - - - - + - 12:30 - - - - - - - + - 09:15 - - - - - - - + | . . 12. . | . . 12. . | . . 12. . | | 11 1 | 11 H 1 | 11 1 | | 10 2 | 10 H 2 | 10 2 | |. H M . | . H . | . . | |. H H H M M M . | . H . | . . | |9 3 | 9 3 | 9 H H H H M M M M 3 | |. . | . M . | . . | |. . | . M . | . . | | 8 4 | 8 M 4 | 8 4 | | 7 5 | 7 M 5 | 7 5 | | . . 6 . . | . . 6 . . | . . 6 . . | +- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - + +- 15:00 - - - - - - - + - 06:00 - - - - - - - + - 16:40 - - - - - - - + | . . 12. . | . . 12. . | . . 12. . | | 11 M 1 | 11 M 1 | 11 1 | | 10 M 2 | 10 M 2 | 10 2 | |. M . | . M . | . . | |. M . | . M . | . . | |9 H H H H 3 | 9 3 | 9 3 | |. . | . H . | . M M M H H H . | |. . | . H . | . M H . | | 8 4 | 8 H 4 | 8 4 | | 7 5 | 7 H 5 | 7 5 | | . . 6 . . | . . 6 . . | . . 6 . . | +- - - - - - - - - - - + - - - - - - - - - - - + - - - - - - - - - - - + ``` or ``` . . . . 12. . . . . . . . . . . . . . . 11 1 . . . . . . . . . . . . . 10 2 . M . . M M M . . H M . . H H M M . . H M . . H H H M M M . . H M . . H H M M . . H M . 9 H M 3 . . . . . . . . . . . . . . . . . . 8 4 . . . . . . . . . . . . . 7 5 . . . . . . . . . . . . . . . 6 . . . . ``` ### Last version with *Seconds* ticks rendering and *nanosleep* to sync. This work only on recent Linux, as this use `/proc/timer_list` to compute fraction of second to sleep between each refresh. ``` #!/bin/bash # Analog clock in Ascii-Art written in BASH V4.2 += RAY=${1:-12} NowH=$2 NowM=$3 # Hires Sleep Until # there is a need to store offset in a static var mapfile </proc/timer_list _timer_list for ((_i=0;_i<${#_timer_list[@]};_i++));do [[ ${_timer_list[_i]} =~ ^now ]] && TIMER_LIST_SKIP=$_i [[ ${_timer_list[_i]} =~ offset:.*[1-9] ]] && \ TIMER_LIST_OFFSET=${_timer_list[_i]//[a-z.: ]} && \ break done unset _i _timer_list readonly TIMER_LIST_OFFSET TIMER_LIST_SKIP sleepUntilHires() { local slp tzoff now quiet=false nsnow nsslp local hms=(${1//:/ }) mapfile -n 1 -s $TIMER_LIST_SKIP nsnow </proc/timer_list printf -v now '%(%s)T' -1 printf -v tzoff '%(%z)T\n' $now nsnow=$((${nsnow//[a-z ]}+TIMER_LIST_OFFSET)) nsslp=$((2000000000-10#${nsnow:${#nsnow}-9})) tzoff=$((0${tzoff:0:1}(3600*${tzoff:1:2}+60*${tzoff:3:2}))) slp=$(( ( 86400 + ( now - now%86400 ) + 10#$hms*3600+10#${hms[1]}*60+10#${hms[2]} - tzoff - now - 1 ) % 86400)).${nsslp:1} read -t $slp foo } sqrt() { local -a _xx=(600000 200000) local _x1=${_xx[$(($1&1))]} _x0=1 while [ $_x0 -ne $_x1 ] ;do _x0=$_x1 [ $_x0 -eq 0 ] && _x1=0000 || printf -v _x1 "%u" $(( (${_x0}000 + ${1}00000000000/${_x0} )/2 )) printf -v _x1 "%.0f" ${_x1:0:${#_x1}-3}.${_x1:${#_x1}-3} done _x1=0000$_x1 printf ${2+-v} $2 "%.3f" ${_x1:0:${#_x1}-4}.${_x1:${#_x1}-4} } clksin() { # $1:moment [0-60], $2:path length, $3:variable name local _csin=(0 104528 207912 309017 406737 500000 587785 669131 743145 809017 866025 913545 951057 978148 994522 1000000) local xsign=1 x=$1 ysign=-1 y=$1 [ $x -gt 30 ] && xsign=-1 x=$((60-x)) [ $x -gt 15 ] && x=$((30-x)) x=00000$((RAY*1000000+xsign*${2:-10}*${_csin[$x]})) [ $y -gt 30 ] && y=$((60-y)) [ $y -gt 15 ] && ysign=1 y=$((30-y)) y=00000$((RAY*1000000+ysign*${2:-10}*${_csin[15-$y]})) printf ${3+-v} $3 "%.0f %.0f" \ ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6} }; SLEN=000$((870*RAY)) printf -v SLEN "%.0f" ${SLEN:0:${#SLEN}-3}.${SLEN:${#SLEN}-3} MLEN=000$((780*RAY)) printf -v MLEN "%.0f" ${MLEN:0:${#MLEN}-3}.${MLEN:${#MLEN}-3} HLEN=000$((650*RAY)) printf -v HLEN "%.0f" ${HLEN:0:${#HLEN}-3}.${HLEN:${#HLEN}-3} declare -A ticks for ((i=1;i<=12;i++));do clksin $((5*(i%12))) $RAY tick ticks[$tick]=$i done while :;do [ "$NowM" ] || printf -v NowM "%(%M)T\n" -1 unset MPath declare -A MPath for ((i=1;i<=MLEN;i++));do clksin ${NowM#0} $i tick MPath[$tick]=M done [ "$NowH" ] || printf -v NowH "%(%H)T\n" -1 unset HPath declare -A HPath for ((i=1;i<=HLEN;i++));do clksin $((5*(${NowH#0}%12))) $i tick HPath[$tick]=H done printf -v NowS "%(%S)T\n" -1 clksin ${NowS#0} $SLEN STick [ "$2" ] || echo -en \\e[H; # ANSI sequence for top left of console for ((i=0;i<=2*RAY;i++));do x=$((RAY-i)) sqrt $((RAY**2 - ${x#-}**2 )) y0 printf -v y0 "%.0f" $y0 for ((l=0;l<=2*RAY;l++));do y=$((RAY-l)); sqrt $((RAY**2 - ${y#-}**2 )) x0 printf -v x0 "%.0f" $x0 if [ "$i $l" = "$STick" ] ;then echo -en \\e[1ms\ \\e[0m elif [ "${MPath["$i $l"]}" ] ;then echo -en \\e[1m${MPath["$i $l"]}\ \\e[0m elif [ "${HPath["$i $l"]}" ] ;then echo -en \\e[1m${HPath["$i $l"]}\ \\e[0m elif [ "${ticks["$i $l"]}" ] ;then printf "%-2s" ${ticks["$i $l"]} elif [ ${x#-} -eq $x0 ] || [ ${y#-} -eq $y0 ] ;then echo -n .\ else echo -n \ \ fi done echo -e \\e[K done echo -en \\e[J [ "$2" ] && break # Exit if at least Hour was specified printf -v SleepS "%(%s)T" -1 printf -v SleepS "%(%T)T" $((1+SleepS)) sleepUntilHires $SleepS unset NowH NowM done ``` ### More obfuscated version (2702 bytes): As requested by [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork), there is a *more golfed* version. This version is colorized and present digital time on corners. ``` #!/bin/bash W=/proc;J=${1:-12} B=$2 A=$3 LANG=C R=$W/timer_list;if [ -f $R ];then Q=10 mapfile <$R e;for ((P=0;P<${#e[@]};P++));do ((Q+=${#e[P]}));[[ ${e[P]} =~ ^now ]]&&U=$Q;[[ ${e[P]} =~ offset:.*[1-9] ]]&&a=${e[P]//[a-z.: ]}&&break;done;c(){ local q p;read -N$U q <$R;q=${q%% nse*};q=$[${q##* }+a];p=$[2000000000-10#${q: ${#q}-9}];read -t .${p:1} M;};else c(){ local H;read -d\ H < $W/upti*;H=$[200 -10#${H#*.}];read -t .${H:1} M;};fi;u(){ local E=({6,2}00000) F=${E[$1&1]} G=1 while [ $G -ne $F ];do G=$F;[ $G -eq 0 ]&&F=0000||printf -v F "%u" $(((${G}000 +${1}00000000000/${G})/2));printf -v F "%.0f" ${F:0:${#F}-3}.${F:${#F}-3};done F=0000$F;printf -v $2 "%.3f" ${F:0:${#F}-4}.${F:${#F}-4};};g(){ local t=($[7#0 ] 104528 207912 309017 406737 500000 587785 669131 743145 809017 866025 913545 951057 978148 994522 1000000) j=1 x=$1 h=-1 y=$1;[ $x -gt 30 ]&&j=-1 x=$[60-x] ((x>15))&&x=$[30-x];x=00000$[J*1000000+j*${2:-10}*${t[$x]}];((y>30))&&y=$[60-y ];((y>15))&&h=1 y=$[30-y];y=00000$[J*1000000+h*${2:-10}*${t[15-y]}];printf -v\ $3 "%.0f %.0f" ${y:0:${#y}-6}.${y:${#y}-6} ${x:0:${#x}-6}.${x:${#x}-6};};v=000 v+=$((870 *J));printf -v v "%.0f" ${v:0:${#v}-3}.${v:${#v}-3};C=000$((780*J)); printf -v C "%.0f" ${C:0:${#C}-3}.${C:${#C}-3};D=000$[650*J];printf -v D %.f \ ${D:0:${#D}-3}.${D:${#D}-3};declare -A m;for ((i=1;i<=12;i++));do g $[5*(i%12) ] $J w;m[$w]=$i;done;printf -v T "\e[1m%s\e[0m " . + \* o O;T=(${T});m["${J: \ } $J"]=${T} ;printf "\e[?25l\e[H\e[J";trap "printf '\e[?12l\e[?25h\e[$((2*J +3 ))H\e[J';exit" 0 1 2 3 6 9 15; printf -v S "\\e[1;%dH%%(%%H)T\\e[%dH%%(%%M${Z: })T\\e[%d;%dH%%(%%S)T" $[4*J] $[2*J+1] $[2*J+1] $[4*J];declare -A V;V["$[2 * J ] $[2*$J]"]=" ";while :;do [ "$A" ]||printf -v A "%(%M)T" -1;unset r;declare\ -A r;for ((i=1;i<=C;i++));do g ${A#0} $i w;r[$w]=M;done;[ "$B" ]||printf -v \ B "%(%H)T" -1;unset s;declare -A s;for ((i=1;i<=D;i++));do g $((5*( ${B#0}%12) )) $i w;s[$w]=H;done;printf -v z "%(%S)T" -1;g ${z#0} $v n;[ "$2" ]||echo -en\ \\e[H;for ((i=0;i<=2*J;i++));do x=$[J-i];u $[J*J-${x#-}**2] N;printf -v N${Z: } %.f $N;for ((l=0;l<=2*J;l++));do y=$[J-l];u $[J*J-${y#-}**2] O;printf -v O \ %.f $O;c=" ";if [ "$i $l" = "$n" ];then c=$'\e[36;1ms \e[m';elif [ "${r["${i: } $l"]}" ] ;then c=$'\e[32;1m'${r["$i $l"]}$' \e[0m';elif [ "${s["$i $l"]}" ]; then c=$'\e[34;1m'${s["$i $l"]}$' \e[0m';elif [ "${m["$i $l"]}" ];then printf\ -v c "%-2s" "${m["$i $l"]}";elif [ ${x#-} -eq $O ] || [ ${y#-} -eq $N ] ;then c=.\ ;else c=" ";fi;[ "$c" != "${V["$i $l"]}" ]&& V["$i $l"]="$c" && printf \ "\e[%s;%sH%-2s" $((1+i)) $[1+l*2] "$c";done;done;[ "$2" ] &&break;printf "${Z: }\e[H\e[7mS\e[0m";c;printf "\e[H $S" -1 -1 -1;m["$J $J"]=${T[$[10#$z%${#T[@]}] ]};unset B A;done ``` ### Note: Don't use this anyway! As this is [bash](/questions/tagged/bash "show questions tagged 'bash'") *programm* and as bash is not a programmation language, this is not well to use for a while. There is a little demo of memory consumption in only 5 hours, with a drawing of 7 character length ray: ``` $ ascii-clock.sh 7 After PMem PCpu Mem 0'30" 0.0% 21.6% 12.98M 10'30" 1.0% 20.9% 48.91M 1h 0'30" 5.6% 20.8% 228.63M 2h 0'31" 11.2% 20.8% 444.25M 3h 0'32" 16.8% 20.8% 659.91M 5h 0'00" 27.9% 20.8% 1.064G ``` The main advantage of this that when I need memory, I just have to kill the clock. ( **Nota:** I've merged this, the [perl version](https://codegolf.stackexchange.com/a/13009/9424) and a [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") version of same on [ascii-clock for geeks](http://fhauri.cartou.ch/ascii-clock/) ;-) [Answer] # Python 2 - 207 ``` import time as T while 1:t=T.localtime();m=t.tm_min/5;l=[12]+range(1,12);l[m]='';l[t.tm_hour%12]='H';l[m]+='M';a=' %s\n';print(a+('%s'+a)*5+a)%tuple(str(l[x])for x in[0,11,1,10,2,9,3,8,4,7,5,6]);T.sleep(9) ``` It is very ugly, but readable. Prints every 9 sec (you can change to 1 sec if you prefer), updates every 5 min. I don't have much experience with code golfing in python so I expect it can be improved. Example output: ``` 12 11 1 10 2 9 M 8 4 7 H 6 ``` [Answer] ### Perl 5 x 65 = 325 - 65(20%) = 260 chars!! Clean, circular, with a second tick and updated every seconds. ``` perl -E ' $r=11;$p=atan2(1,1)/7.5;sub c{($A,$R,$C)=@_;$a[$r-$R*cos($A*$p)][ $r+$R*sin($A*$p)]=$C." "x($C!~/../)};while(::){@a=map{[map{" "}( 0..$r*2)]}(0..$r*2);map{c$_*5,$r,$_}(1..12);@t=localtime;for$i(qw |H:6:5:2 M:8:1:1 s:9:1:0 |){($S,$P,$F,$T)=split":",$i;map{c$F*$t[ $T],$_,$S}(do{$T?1:$P}/10*$r..$P/10*$r)};map{say@{$_}}@a;sleep 1} ' ``` On a 24 lines console look good (It's **00:12:56**): ``` 12 11 1 s 10 H 2 H H H M M H M M M M M M 9 3 8 4 7 5 6 ``` And there is a colored, nicer and smarter version: ``` #! /usr/bin/perl use Time::HiRes qw|sleep time| ;$h=11;$h=$ARGV[0]if$ARGV[0];$P=atan2 (1,1)/7.5;$V =4*$h; $v= 2* $h+ 1;@r=(0..2*$v) ;sub p{printf @_ }sub b{ return"\e[1m" .pop."\e[0m" };$ |=p"\e[?25". "l\e[H\e[" ."J" ;$ SIG{ 'INT'}=sub {p"\e[?1" ."2l" ."\e" ."[?25h". "\e[%dH" ."\e" ."[J" ,$v+2;exit; };@z=map {[map{" " }@r] }(0 ..2*$v); @Z=map{[@ {$z[$_]}]}@r ;sub c{($A,$r ,$s )=@_;$z[$h-$r*cos ($A*$P) +.5 ][$h+$ r*sin($A*$P)+.5]=$s;} for$x( 0..$h) {$y= int(sqrt($h**2 -$x**2 )+.5);$ z[$h-$x][$h-$ y]=".";$z[$h+$x ][$h-$y ]="."; $z[$h-$x][$h+$ y]=".";$z[$h+$x ][$h+$ y]="."; $z[$h-$y][$h-$ x]=".";$z[$h+$y ][$h-$x ]="."; $z[$h-$y][$h+$x]=".";$z[$h+ $y][$h +$x]="."};map{ c$_*5,$h,b$_}(1..12); @R=map{[@{$z[ $_]}]}@r;while (::){@t=localtime; p"\e[H\e[1;$ {V}H%0" ."2d\e[${v}H%02d\e" ."[${v };${ V }H%02d",$t[2],$t[ 1],$t[ 0];@z= map{[ @{$R[ $_]}]}( 0..2*$ v);for $i('H:' .'65:5:' .'2:4', "" x1 .'M:78:' ."1:1" .":2", "s:8". "7:1:" .'0:6'){($ l,$p,$F,$u,$ c)=split ":",$i;map {c$F*$t [$u],$_ ,b("\e[" ."3${c}m$ l")}(do{$u ?1:$ p} / 100*$h..$p /100*$h);} $z[$ h][ $h]= b((".","+" ,"*","o","O") [$t [0]%5]);for$x (@r){for$y(@r ){$ Z[$x][$y]ne$z [$x][$y]?p"\e[%d;%dH".$z [ $x] [$y],$x+1,2*$ y+1:''};};@Z=map{[@{$z[$_]}]}@r;$n=1-$1 if time=~/(\..*)$/;p"\e[H\e[7m" ."S\e[0m";sleep$n} ``` This version is **strongly** linked to [this other answer](https://codegolf.stackexchange.com/a/13007/9424), with the main advantage: *You could run this quietly, for a while!* So you could find an [upgraded version there](http://www.f-hauri.ch/vrac/ascii-clock-pl.txt) or on this [ascii-clock for geeks](http://fhauri.cartou.ch/ascii-clock/) web page. As a demonstration that doing *approx* same in [perl](/questions/tagged/perl "show questions tagged 'perl'") require less resources: ``` $ ascii-clock.pl 7 After PMem PCpu Mem 0' 0" 0.0% 0.0% 23.5M 10'30" 0.0% 0.0% 23.5M 1h 0' 0" 0.0% 0.0% 23.5M 2h 0' 0" 0.0% 0.0% 23.5M ``` for approx same features: * wait for begin of each seconds for doing a refresh * draw with color and bold attributes * draw full circle with dots, hour tick, hour and minutes full path and a `s` dot for second handler. * draw *digital* clock prompting *hour* at top right, *minutes* at bottom left and *seconds* at bottom right. * prompt a `S` at top left, when *sleeping* (look for difference with [bash](/questions/tagged/bash "show questions tagged 'bash'") version) Plus * The upgraded version authorize `-a` argument for drawing hour and minute path in fraction (11h59 place hour path approx at 12h). ### One more another perl version!!! Using the following (beautiful) picture: ![A wonderful representation of perl code](https://i.stack.imgur.com/xvbHP.png) You could simply: ``` curl https://i.stack.imgur.com/xvbHP.png | perl -e 'use GD;GD::Image->trueColor(1);$i=GD::Image->newFromPng( STDIN);my($x,$y)=$i->getBounds();for my$k(0..$x-1){for my$l(0 ..$y-1){$_.=pack"UUU",$i->rgb($i->getPixel($k,$l))};};eval' ``` or, with arguments (You have to add `-s` switch to perl command): ``` wget -O - http://fhauri.cartou.ch/ascii-clock/ascii-clock.png | perl -se 'use GD;GD::Image->trueColor(1);$i=GD::Image->newFromPng( STDIN);my($x,$y)=$i->getBounds();for my$k(0..$x-1){for my$l(0 ..$y-1){$_.=pack"UUU",$i->rgb($i->getPixel($k,$l))};};eval' -- -a 18 ``` This require having gd2-perl installed! (You could replace `curl` by `wget -O -` ;-) ( Note: This picture is near 1.5Kb. I've built another *same* picture, but 900 bytes length. You may find this picture, well as a [javascript](/questions/tagged/javascript "show questions tagged 'javascript'") version of same at [ascii-clock for geeks](http://fhauri.cartou.ch/ascii-clock/) :-) [Answer] ### Tcl, 288 ``` while 1 {scan [clock format [clock seconds] -format %k-%M] %d-%d h m regsub -all \ +|. "oaosocowoeouooovoioxozom r n\n" \ {&} p lset p [set h [expr $h%12*2]] h lset p [set m [expr $m/5*2]] [expr $h-$m?"m":"x"] puts [string map /\ $p {rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru}]} ``` Ok, here some explaination: * `while 1 {...}` - Ok, forget the explaination. * `regsub -all \ +|. "oaosocowoeouooovoioxozom r n\n" \ {&} p` replaces `+|.` with `_{\0}` and stores the result in `p`. `p` is actually a messed up dictionary where the first key is missing (or just a list with an odd number of elements). * `lset p [set h [expr $h%12*2]] h` sets the hour in the replacement list * `lset p [set m [expr $m/5*2]] [expr $h-$m?"m":"x"]` sets the minute. if hour and minute is the same, use `x` instead. * `string map /\ $p {rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru}` `/\ $p` is equal to `"/ $p"`, so I add the first key (`/`). After that I replace every occurence of a key in `rr/nrzmrann xrrr snnimrrrcnn vrrr wnnromrenrru` with it's value. The usual map is ``` / o a o s o c o w o e o u o o o v o i o x o z o m { } r { } n { } ``` (Read as "Replace `/` with `o`, replace `a` with `o`... replace `m` with `___` (that should be spaces)) I repace an `o` with `h` and an other with `m`, `m`, `r` and `n` are just to shoren the output string (I replaced several spaces with one of them, also `\n` with `n`). I add the first element later so I can use h\*2 instead h\*2+1 for the index that I replace. (saves 2 chars) Some notes: * A list in Tcl uses whitespace as delimiter, if an element contains whilespace, you have to enclose it with `{}`. Ok, it's a little bit more complex e.g. you could escape the whitespace with a `\`, but such details are documented [somewhere else](http://www.tcl.tk/cgi-bin/tct/tip/407.html). * A dict in Tcl is just a list with an even number of elements: `key1 value1 key2 value2` * You can treat a list as string or a string as list. Will work if the string is a valid list. Free serialization! [Answer] ### Javascript 2169 - 434 = 1735 Ok, it's a lot, but they are fine and work same as my previous variant in previous posts ([bash](https://codegolf.stackexchange.com/a/13007/9424) and [perl](https://codegolf.stackexchange.com/a/13009/9424)). This version is *more obfuscated* than the one you may find on my [ascii-clock for geeks](http://fhauri.cartou.ch/ascii-clock/) ``` var x='<div class="m">&nbsp;M</div>',v='<div class="s">&nbsp;s</div>',w='&nbsp;' ,r=10,q,w='&nbsp;',y='<div class="h">&nbsp;H</div>',f=new Object();function d(){ q=document.getElementById("asciiclock");var t=document.location.toString().match (/[?]([0-9]+)/);if (t!=null) r=t[1]*1.0;a();b();}function m(e){r=e;a();}function a(){f=[];for (var i=1;r>i;i++){var u=Math.round(Math.sqrt(Math.pow(r,2)-Math.pow (r-i,2)));f[(2*r-i)+"x"+(r+u)]=w+".";f[(i)+"x"+(r+u)]=w+".";f[(2*r-i)+"x"+(r-u)] =w+".";f[(i)+"x"+(r-u)]=w+".";f[(r+u)+"x"+(2*r-i)]=w+".";f[(r+u)+"x"+(i)]=w+"."; f[(r-u)+"x"+(2*r-i)]=w+".";f[(r-u)+"x"+(i)]=w+".";}for(var i=1;13>i;i++){f[Math. round(r+r*Math.sin(Math.PI/6*i-Math.PI/2))+"x"+Math.round(r+r*Math.cos(Math.PI/6 *i-Math.PI/2))]='<div class="t">'+(i<10?w+i:i)+'</div>';}}function b(){var z=''; var s=new Date(), o=s.getMinutes()*1.0+1.0*s.getSeconds()/60,p=s.getHours()*1.0+ 1.0*o/60,n=s.getSeconds()*1.0,k=s.getHours();if (k<10) k=w+k;var j=s.getMinutes( );if (j<10) j=w+j;var h=s.getSeconds();if (h<10)h=w+h;var g=new Object();for(var i=1;r*.78>=i;i++) {g[Math.round(r+i*Math.sin (Math.PI/30*o-Math.PI/2))+"x"+Math. round(r+i*Math.cos(Math.PI/30*o-Math.PI/2))]=x;};for (var i=1;r*.62 >=i;i++) {g[ Math.round(r+i*Math.sin(Math.PI/6*p-Math.PI/2))+"x"+Math.round(r+i*Math.cos(Math .PI/6*p-Math.PI/2))]=y;};g[Math.round(r+.87*r*Math.sin(Math.PI/30*n-Math.PI/2))+ "x"+Math.round(r+.87*r*Math.cos(Math.PI/30*n-Math.PI/2))]=v;for (var i=0;2*r>=i; i++){for(var l=0;2*r>=l;l++){if((i==r)&&(l==i)){z+=w+'<div class="t">'+['.','+', '*','o','O'][n%5]+'</div>';}else if(f[i+"x"+l]!=undefined){z+=f[i+"x"+l]}else if (g[i+"x"+l]!=undefined){z+=g[i+"x"+l];}else if(l==2*r){if(i==0){z+=w+'<div clas' +'s="t">'+k+'</div>';}else if(i==l){z+=w+'<div class="t">'+h+'</div>';}else{z+=w +w;};}else if(l==0){if(i==2*r){z+='<div class="t">'+j+'</div>';}else if(i==0){z= '<div class="r">S</div>'+w;}else{z+=w+w}}else{z+=w+w}};z+='<br />';};q.innerHTML =z;window.setTimeout(b,1000-new Date().getMilliseconds());};function c(){window. setTimeout(b,0);q.innerHTML=w+q.innerHTML.substring (22);q.setAttribute('style', 'display:none');q.setAttribute('style',null)};window.onload=d; ``` ``` .asciiclock { margin: 3em 0px 0px 0px;padding: 2px 4px 2px 3px; font-size: .5em; display:inline-block;font-family:mono,monospace,courier;background:rgba(0,0,0,.7 );color: #888;}.asciiclock div{ display:inline-block;font-weight:bold;}.h{color: #46F;}.m{color:#0F0;}.s{color:#0FF;}.r{color:#000;background:#aaa;}.t{color:#aaa ;}pre{display:inline-block;} ``` ``` <head><title>Ascii-clock</title><script type="text/javascript" src="ascii-clock.js" ></script><link rel="stylesheet" href="ascii-clock.css" type="text/css"><style type="text/css">body{margin:0;padding:0;background:#000;}.asciiclock{margin:0} </style></head><body><div id="asciiclock" class="asciiclock"></div></body> ``` [Answer] ## Python, 259 - 52 = 207 ``` from time import* from math import* g=[[' ']*61 for _ in[0]*31] while 1: t=localtime() for x in range(60):a=pi*x/30-pi/2;g[15+int(15*sin(a))][30+int(30*cos(a))]='m'if x==t.tm_min else'h'if x==t.tm_hour%12*5 else'-'if x%5 else'#' for r in g:print''.join(r) ``` Sample output: ``` # - - - - - - - - - h # - - - - - m - # # - - - - - - - - # # - - - - - - - - # # - - - - - - - # # - - - - - - - - - # ``` [Answer] # Ruby: ~~230~~ 228 characters - 46 = 182 ``` M=Math P=M::PI x=->n,m=60,r,c{$><<"^[[%d;%dH%s\n"%[M.sin(n*P*2/m-P/2)*r+12,M.cos(n*P*2/m-P/2)*r*2+24,c]} while t=Time.now $><<"^[[2J" 1.upto(12){|i|x[i,12,11,i]} x[t.hour*5+t.min/12,8,?H] x[t.min,9,?M] x[t.sec,10,?S] sleep 0.1 end ``` (Note: `^[` is a single character.) Sample run (at 21:19:33): ``` 12 11 1 10 2 H 9 3 M 8 4 7 S 5 6 ``` ## “As ugly as you wish” version: ~~191~~ 181 characters - 36 = 145 (Smaller size, lower precision, no seconds, identical radius, horrible flickering.) ``` x=->n,m=60,c{$><<"^[[%d;%dH%s\n"%[Math.sin(n*6.3/m-1.6)*8+9,Math.cos(n*6.3/m-1.6)*8+9,c]} while t=Time.now $><<"^[[2J" 1.upto(12){|i|x[i,12,i]} x[t.hour*5+t.min/12,?H] x[t.min,?M] end ``` Sample run (at 21:19): ``` 12 1 11 2 10 H 3 9 M 8 5 7 6 ``` ## Trigonometry-less version: ~~130~~ 125 characters (no bonus) (Inspired by [Johannes Kuhn](https://codegolf.stackexchange.com/users/7789/johannes-kuhn)'s [Tcl solution](https://codegolf.stackexchange.com/a/12963/4198). Not sure how much, as I still not deciphered his code.) ``` while t=Time.now puts"^[[2J k l a j\tb i\tc h\td g f e".tr((t.min/5+96).chr,?M).tr(((t.hour-1)%12+97).chr,?H).tr("a-l",?*) end ``` Sample run (at 21:19): ``` * * * * * H M * * * * * ``` [Answer] # HTML & JS: `397 - 20% = 317.6 characters` My first iteration. I'm not very pleased with it, but it does work and it does show the time in a very clear way. ``` <canvas id=c width=198 height=198></canvas><script>c=document.getElementById("c") .getContext("2d");c.r=c.rotate;c.c=c.clearRect;c.translate(99,99);for(i=0;i<60;i++) {c.fillRect(89,-1,i%5?3:9,5);c.r(p=Math.PI/30);}setInterval(function(){n=new Date(); h=n.getHours()*5*p;c.beginPath();c.arc(0,0,86,0,7);c.fill();c.r(m=n.getMinutes()*p); c.c(-2,-3,4,-80);c.r(h-m);c.c(-2,-3,4,-50);c.r(-h);},5);</script> ``` [Answer] ## Ti-Basic 84, 587 - 20% = 469.6 ``` :Xmax/2→Xmax:Ymax/2→Ymax:-Xmax→Xmin:-Ymax→Ymin:Degree:15→H:20→M:18→S::Circle(0,0,30):For(X,1,12)::Text(28-int(cos(X*30)*25),46+int(sin(30*X)*25),X):End:{0,0,0}→LANG:While getKey=0::getTime→LTIME::If LTIME(3)≠LANG(3)/6:Line(0,0,sin(LANG(3))*S,cos(LANG(3))*S,0)::If LTIME(2)≠LANG(2)/6:Then:::Line(0,0,sin(LANG(2))*M,cos(LANG(2))*M,0):::Line(0,0,sin(LANG(1))*H,cos(LANG(1))*H,0)::End::"SET ANGS::LTIME(1)*30+LTIME(2)/2→LANG(1)::LTIME(2)*6→LANG(2)::LTIME(3)*6→LANG(3)::Line(0,0,sin(LANG(1))*H,cos(LANG(1))*H::Line(0,0,sin(LANG(2))*M,cos(LANG(2))*M::Line(0,0,sin(LANG(3))*S,cos(LANG(3))*S:End ``` Its output is very pretty and detailed. [Answer] C, 554 Bytes, Updates roughly once per second. ``` #include <time.h> #include <math.h> int r=25,i,q,c,i,q,b[999];void v(float a,int f,int m){b[(r/2+(int)(sin(a)*f))*r+r/2+(int)(cos(a)*f)]=m;}void main(){float a,p=6.28,z=1.57,h,m,s;for(;;){time_t u=time(0);struct tm*l=localtime(&u);s=l->tm_sec;m=l->tm_min+s/60.;h=l->tm_hour+m/60.;system("@cls||clear");q=r*r;c=r/2;memset(b,32,q*4);for(i=0,a=p;a>0;a-=0.52,i++)v(a,c,i%3?46:i%6?124:45);v(0,0,79);v(p*s/60.-z,c-4,83);v(p*m/60.-z,c-5,77);v(p*h/12.-z,c-6,72);for(i=0;i<q;i++){c=b[i];putchar(c);if(i%r==r-1)putchar(10);}for(c=0;c<2000000;c++)hypot(3,.4);}} ``` Result: ``` | . . . S . H - O - M . . . . | ``` ]
[Question] [ We don't have a challenge for conversion between [Cartesian and polar coordinates](https://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates), so ... ### The challenge Write **two programs** (or functions) in the same language: * one that converts from polar to Cartesian coordinates, and * the other from Cartesian to polar coodrinates. The **score** is the sum of the two program lengths in bytes. Shortest wins. For reference, the following figure (from the Wikipedia entry linked above) illustrates the relationship between Cartesian coordinates \$(x, y)\$ and polar coordinates \$(r, \varphi)\$:                          [![enter image description here](https://i.stack.imgur.com/HZW8k.png)](https://i.stack.imgur.com/HZW8k.png) ### Additional rules * Input and output are [flexible](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) as usual, except that they **cannot** be in the form of **complex numbers** (which would trivialize the problem). Of course, the program can use complex numbers internally, just not as input or output. Input and output methods can be different for the two programs. * You can choose to input and output the angle \$\varphi\$ either in **radians** or in **degrees**; and to limit its values to any 2π-radian or 360º-degree **interval**. * Builtins for coordinate conversion are allowed. If you use them, you may want to include another solution without the builtins. * Floating-point number limitations (accuracy, allowed range of values) are acceptable. * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ### Test cases Values are shown rounded to 5 decimals. Angles are in radians in the interval \$[0, 2\pi)\$. ``` Cartesian: x, y <--> Polar: r, ϕ ------------------ ------------------ 2.5, -3.42 4.23632, -0.93957 3000, -4000 5000, -0.92730 0, 0 0, <any> -2.08073, 4.54649 5, 2 0.07071, 0.07071 0.1, 0.78540 ``` [Answer] # [Python](https://www.python.org), 49 + 48 = 97 bytes -2 thanks to @Seb ``` lambda r,a,n=9e9:((x:=r*(a/n-1j)**n).real,x.imag) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY1NCsIwFIT3nqLLpKTxvfw0SaE3cROx1ZY2llChnsVNQfRO3sZiFdzMMMM3zO05XMfTOcz3utw9LmOd2Rd2vt8ffBKZZ6F0lSsImYoypsRvQ4YtTdNAeax8xybe9P5Iv8N2iE0YSU0UFzKX6FAbAIVgWZIBd9ItWSopc1TWIKWb30ADAIeVEkY4LUxulXZK2z_qgyyyVOvjPK_-Bg) ``` lambda x,y,n=1e-9:(abs(c:=x+1j*y),(c**n).imag/n) ``` Doesn't use any libraries, no exp, no sin, no cos, etc. ### How? All based on \$\tan(x)\approx x\quad|x|\ll1\$ and \$e^x\approx(1+x/n)^n\quad n\gg 1\$ [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 14+11=25 bytes ``` AbsArg[#+I#2]& AngleVector ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/N1jGp2LEoPVpZ21PZKFaNK93WMS89JzUsNbkkv@h/QFFmXkm0sq5dmoMDkEx30AIxYtXqgpMT8@qquaqN9Ex1dI31TIxqdbiqjQ0MDHR0TYAkiGegA6Z0jfQMLAzMjXVM9ExNzEwswVJ6BuYG5oY6ULqWq/Y/AA "Wolfram Language (Mathematica) – Try It Online") Input `[x,y]`/`[{r,ϕ}]` and output `{r,ϕ}`/`{x,y}`. ``` #+I#2 convert to complex AbsArg[ ] get abs (r) and arg (ϕ) ``` ``` AngleVector built-in. ``` [Answer] # [J](http://jsoftware.com/) 10 (5 + 5) ## to polar, 5 bytes ``` *.@j. ``` [Try it online!](https://tio.run/##DcNBC0AwAAbQ@37FN5dFfLHNtJUS5SQHdzmI5OL/n2av3hu9DM3uZPBKiYzqRh@gUKJGSCti2pY5FhxexlyI63w@aLa4cRhajWQdCUttnNElqpre@LaLPw "J – Try It Online") ## to cartesian, 5 bytes ``` +.@r. ``` [Try it online!](https://tio.run/##DcNBC0AwAAbQ@37Fx2UJX2xDWylRTnJw1w6y5KL8/xqv3h1t4uq9TZyVUqSUAb2DRIEK7l8S07bMMefwMmZCnMf1wFDpVisE@IpW26bDOhKKDbymUYgf "J – Try It Online") Both of these amount to one built-in for the poler/cc conversion, combined with another builtin for the complex/x-y conversion. [Answer] # [Desmos](https://desmos.com/calculator), 33+19 = 52 score Both functions take in two arguments representing either polar or Cartesian coordinates (depending on which function is being used), and returns a list representing the converted coordinates. ### Cartesian to polar: 33 bytes ``` f(a,b)=[(aa+bb)^{.5},arctan(b,a)] ``` ### Polar to Cartesian: 19 bytes ``` g(a,b)=[cosb,sinb]a ``` --- [Try Both Online On Desmos!](https://www.desmos.com/calculator/rtbbe2d2zp) [Try Both Online On Desmos! - Prettified](https://www.desmos.com/calculator/pwqsh2fcxy) [Answer] # [Mathematica](https://www.wolfram.com/wolframscript/), 18+20 = 38 bytes ``` ToPolarCoordinates ``` ``` FromPolarCoordinates ``` [Try it online!](https://tio.run/##XY69CoMwEIB3nyI4m@OaH6ODUCh0dugmHUKrVqgG0mzSZ7dHhVYz3d333d9ow6MdbRhudlm66uJq97T@5Jy/D5MN7Svpq7N3Y4yX2g9TYEfWNbMAnTEuQYn3NdlwiYgkFIW9IBoRLgALNDJjCrTKVRkNABo0BxpbE7I/nXLO03/ZN7MCIXMp6DRCKUttNstI6/UtcsJIjFzGxJ4gfM@aQivqXT4 "Wolfram Language (Mathematica) – Try It Online") For the `<any>` case, it will output a warning and use `Indeterminate`. In some cases, it will not directly return the number, and instead return something like `ArcTan[4/3]` or `5*Cos[2]`. If that's not allowed: # [Mathematica](https://www.wolfram.com/wolframscript/), 21+23 = 44 bytes ``` N@*ToPolarCoordinates N@*FromPolarCoordinates ``` [Try it online!](https://tio.run/##XY69CsIwEIB3nyJ0lCac@WnaQSgIjtLBrTgEbWvBNhCzFZ89nha0zXR333d/g/H3ZjC@v5oQ2v2p3J5tZR/GHax1t340vnluug8/OjvEJlSuHz0pSVtPnKmUUMEkf102Cy4AAIXEsBZII0I5gxy0SIlkSmayiAYYaNA7HJsTtD@dUEqTf9nVk2RcZILjaWCFKJReLEOt5rfQcS0gcinhawLse1bnSmJveAM "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 10 + 12 = 22 bytes Polar to Cartesian: ``` a*[CObSIb] ``` Takes angle in radians. Outputs a list containing x and y. [Try it online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhKltDT2JTSWJdIiwiIiwiIiwiLXAgNC4yMzYzMiAtMC45Mzk1NyJd) Cartesian to polar: ``` PRT$+SQgbATa ``` Outputs radius and angle (in radians) on separate lines. [Try it online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJQUlQkK1NRZ2JBVGEiLCIiLCIiLCItcCAyLjUgLTMuNDIiXQ==) ### Explanations ``` a*[CObSIb] a is radius, b is angle [ ] List containing COb Cosine of b SIb Sine of b a* Multiply each by a PRT$+SQgbATa a is x-coordinate, b is y-coordinate, g is list containing both SQg Square both coordinates $+ Fold the list of squares on addition RT Square root P Print bATa Two-argument arctangent of b and a Autoprint ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 + 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) = 13 #### Polar to Cartesian: ``` ×ıÆeׯi ``` A dyadic Link accepting \$\theta\$ on the left and \$r\$ on the right that yields a list \$[x, y]\$. **[Try it online!](https://tio.run/##y0rNyan8///w9CMbD7elHp5@uC3z////Rv9NAQ "Jelly – Try It Online")** #### Cartesian to polar: ``` æịA,æA ``` A dyadic Link accepting \$y\$ on the left and \$x\$ on the right that yields a list \$[r, \theta]\$. **[Try it online!](https://tio.run/##y0rNyan8///wsoe7ux11Di9z/P//v4meqYmZieV/XSM9AwsDc2MA "Jelly – Try It Online")** ### How? ``` ×ıÆeׯi - Link: theta; r ı - the imaginary unit, i × - (theta) multiplied by (i) Æe - apply the exponential function -> e^(i.theta) × - multiply that by r -> r.e^(i.theta) Æi - Separate that into real and imaginary parts ``` ``` æịA,æA - Link: y; x æị - y+i.x A - absolute value -> r (same as for x+iy - we've just reflected in Re=Im) æA - atan2(y, x) -> theta (by definition) , - pair ``` --- Alternative \$7\$ byte Polar to Cartesian: `ÆẠ,ÆSƊ×` (pair `,` the cosine `ÆẠ` and sin `ÆS` of `Ɗ` \$\theta\$ and multiply `×` by \$r\$). [Answer] # [Factor](https://factorcode.org/), 16 + 15 = 31 bytes ``` [ rect> >polar ] ``` [Try it online!](https://tio.run/##RdDNisIwFAXgfZ7izL65XPPTWJVuBzezGVzJLEJRFLQtaWYhpc9eM51a7@KEwJdzIWdfxSaMh@/91@cGvuuaqsPdx8sUdP6tq3ht6g5tOMX4aMO1jtgK0Quk6aHIQmoyCgPm@YAhpXOtMkimQhfWzVgzM6T5y2HBNl3/pXKaZ8l4k0UmtvP1o5yNVMRrdjqtsyY3RXqQ2jKoVwexY7dazmHqoFWWwq2tYTGI8YhwqmKJsm1uPuBnnL5A3n0LGp8 "Factor – Try It Online") ``` [ cis * >rect ] ``` [Try it online!](https://tio.run/##bdA9C8IwEAbgPb/idZX2OPNhWgVXcXERJ3EoQbGDbWniIOJvr7G0qODBJeHy8BJyLlyo226/22zXCxTe187jWoRLv9D5VrlQ1pVH055CuDdtWQUshXgIxHpAk1RzJZEy5So3Fs/3HBNIMglSRVoO0jBzz6RVPLBeqngRqY7bQBlf4FMTRDcaA/nfpJI4Y6uS@Daj5zofQ2kW22ZG/4THUGLLdpaMB/EU3QGu9Jhi1Z5cwLHrPya9Fg2oewE "Factor – Try It Online") `cis` does `e^(x*i)` and `cis *` is 1 byte shorter than `polar>`. [Answer] # x86 64-bit machine code, 23 + 13 = 36 bytes ``` D9 06 D9 07 D9 F3 D9 07 D8 C8 D9 06 D8 C8 DE C1 D9 FA D9 1E D9 1F C3 D9 07 D9 FB D8 0E D9 1F D8 0E D9 1E C3 ``` [Try it online!](https://tio.run/##jVNNb5tAED2HXzF15WhxABGM49auc2muVSurUis5PiwsHyvhhbLrFGL5r9edBYPqxFYjIWb2zZuZN8MS2kkYHg7vuQizLYvgk1SM5056b5xAGQ9eYiUXySseF0pjxlPOGcQkznKqYFRZcPRqc97Gki5WpLyPlhilcgNkOSBGPDOu4ozBw4@vywf49n0Jq1Ly9WuQNWBBFRWXgpttBlIR17Rac6nyGR5lrEAjf5VKG1WcSXuJNk3LSBlGMrskSeLacnns@caSb@TKrr05wIUa@E1gQ7kg2qFlEloQprSE0QgPT6ax0xL1/hVdrWEBO8@ZWDB2XdcCfGzPcT@40zEeHHfqTm/38z4haBPsseN7yPS7HN@Z@Hf@x5MU3b1CNoZrXK8ukpdA5gi@W8AE7c0NLhzVHKtTJKOkam1BoN0AXcy6KvDmqZgMhrdeDPo1sIAix9TBmFyjf90eOibY93CWnfyX/Sj@4e@NnvQovtAw5SKCMGfRDGmaoOeTesZuOj30cwOgwTE9tP2YLIdd33Toej@xVb0gZCskT0TEms80MmNzhatZm/M9/E55FgGpdSm3@jw@1U2GHIJaRdJsVFdgg2wYWlLV6sdrsS2FFrg3Doc/YZzRRB7szZ2PL/z3Flgryv4C "C (gcc) – Try It Online") These functions take addresses of two 32-bit floating-point numbers in RDI and RSI, and modify those numbers. The first transforms x,y into ϕ,r and the second does the opposite. In assembly: ``` f: # FPU register stack contents fld DWORD PTR [rsi] # y fld DWORD PTR [rdi] # x y fpatan # ϕ fld DWORD PTR [rdi] # x ϕ fmul st(0), st(0) # x² ϕ fld DWORD PTR [rsi] # y x² ϕ fmul st(0), st(0) # y² x² ϕ faddp # x²+y² ϕ fsqrt # r ϕ fstp DWORD PTR [rsi]# ϕ fstp DWORD PTR [rdi]# ret g: # FPU register stack contents fld DWORD PTR [rdi] # ϕ fsincos # cosϕ sinϕ fmul DWORD PTR [rsi]# x sinϕ fstp DWORD PTR [rdi]# sinϕ fmul DWORD PTR [rsi]# y fstp DWORD PTR [rsi]# ret ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 43+37=80 bytes ### Cartesian to Polar, 43 bytes ``` X+Y+R+T:-R is(X^2+Y^2)^0.5,T is atan2(Y,X). ``` [Try it online!](https://tio.run/##JY4xC4MwEIX/SuiUkEu4xrS2DkI7OThJBiVEcGkrtCoqdPOv27NO73vvDt4bxv7dP9X0bde1lJUspEtUwdqJl7WRVW1EjfoEjhLWzE1neAWl0GuiPs3wbqeZ@zykKe/mF3KEHDIBfz4SOwGZdPIm7/Dox08z88MyAFsGplK209IdwGfg4Ab3IAR4b6iOqUhbE8BHiEjOkpAj3EQZjReMI2BWn@zZXreTxhjjIz3sEAKN/AE "Prolog (SWI) – Try It Online") ### Polar to Cartesian, 37 bytes ``` R+T+X+Y:-X is R*cos(T),Y is R*sin(T). ``` [Try it online!](https://tio.run/##JY49C4MwFEX/SnBKmpcQjdbqIOjk4CQOSsgghbYBvzBCN/@6jXV651y4l7es8zC/mf2a46hpQ1vapaxFxqL69pwtbgh0l1kzOeNHysZ@GYzdsKp0luFp@wgsoIKSwJ99x65WurWcFvCa17HfsLcvgPYFsQxdtE8eqBIayKHQhIBSIQ/kXQaAmOCJTKJYg4qEEFcQxFK4wNl5IkDBadx3zuNHFAqt3Xc/ "Prolog (SWI) – Try It Online") [Answer] # MATLAB/Octave, 9+9=18 bytes, builtins Simple builtins, convert between (x,y) and (angle[radians],radius) ### Cartesian to polar: ``` @cart2pol ``` [Try it online!](https://tio.run/##y08uSSxL/f/fITmxqMSoID/nf5ptYl6xNVeahpGeqY6CrrGeiZEmkGdsYGAA5JoAKRDXQAdM6RrpGVgYmBvrKJjomZqYmViC5fQMzA3MDXUUoAzN/wA "Octave – Try It Online") ### Polar to cartesian: ``` @pol2cart ``` [Try it online!](https://tio.run/##y08uSSxL/f/foSA/xyg5sajkf5ptYl6xNVeahq6BnqWxpam5joKJnpGxmbGRJlTQyNzYQEfB1MDAACRiqAOmjHRMQZSBnrmFqYmBjoGeoeZ/AA "Octave – Try It Online") # 23+29=52 bytes, without builtins Same input/output as before ### Cartesian to polar: ``` @(x,y)[atan2(y,x),abs(x+y*i)] ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNCp1IzOrEkMc9Io1KnQlMnMalYo0K7UitTM/Z/mm1iXrE1V5qGkZ6pjoKusZ6JkSaQZ2xgYADkmgApENdAB0zpGukZWBiYG@somOiZmpiZWILl9AzMDcwNdRSgDM3/AA "Octave – Try It Online") ### Polar to cartesian: ``` @(a,r)r*[cos(a),sin(a)] ``` [Try it online!](https://tio.run/##LchLCoAgEADQfadoqTENk59MIuge0UIkoY1BRte3jFYP3uEvd285z8zByc9m8UdijkPa48uaw@RiGqvAWkIrrTZQKxSyl4L/KYwkqDURlengQ4AuEJpBKwLCjucH "Octave – Try It Online") [Answer] # [Python](https://www.python.org), 48+48 = 96 bytes ``` lambda*t:(hypot(*t),atan2(*t)) from math import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXISc5NSErVKrDQyKgvySzS0SjR1EksS84xALE2utKL8XIXcxJIMhczcgvyiEi2Ivi0FRZl5JRppGkZ6pjoKusZ6JkaamhCpBQsgNAA) -4 bytes thanks to xnor. ``` lambda a,b:(a*cos(b),a*sin(b)) from math import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3DXISc5NSEhUSdZKsNBK1kvOLNZI0dRK1ijPzgAxNrrSi_FyF3MSSDIXM3IL8ohItiL7dBUWZeSUaaRomekbGZsZGOgq6BnqWxpam5pqaEBULFkBoAA) [Answer] # [SageMath](https://www.sagemath.org/), ~~69~~ 68 bytes ``` lambda x,y:((x^2+y^2)^.5,arctan2(y,x)) lambda r,t:(r*cos(t),r*sin(t)) ``` [Try it online!](https://sagecell.sagemath.org/?z=eJyFkEtugzAQQPdI3GF2mNYg_wghanqEXCAfyUCiorYkMq6Ei7h7xxC1KJsiGc3Y8-aNfdsewuBDf5a1hp66DSH9STy7k4hPaUa1qaxuBXG0j-MwqBbFhtoNMU_VtSM2puapa1oMsCgM-g62QATyMH-SMTbF-E9EytYslxRYynKWc0TcBCQyVWIqS9QCUGmmVqrA9A8wE6BSIVdyQrIF8KtFwBfbuTtLC1lkOU6AkchFkQm-ZoyvuMAWO72jIPxQ-TpTzF_27Vy9n41no8OXyFUVUZgiLiM8v1yNfzGKDwFNC9_NjfQdBYfL4LJdvAkDP4XGFnhGXTznNea67Ijes2Ni4hd-TjLQbX3f5MfELjY5oIfN5M00rSWXaOhHOrgRklcY9AjDfdR9fRyju6RESUVwtgdp6aX9g7T0Uvef1KDUztLyUfoD776PpA==&lang=sage&interacts=eJyLjgUAARUAuQ==) *Adjusted score correctly thanks to [Steffan](https://codegolf.stackexchange.com/users/92689/steffan).* *Saved a byte thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)!!!* [Answer] # [R](https://www.r-project.org), 30+24=54 bytes ### Cartesian to polar, 30 bytes ``` \(x,y)c(Mod(z<-x+1i*y),Arg(z)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMG65MSikviS_PiC_JzEItulpSVpuhb7YjQqdCo1kzV881M0qmx0K7QNM7UqNXUci9I1qjQ1IYpuMRqg6NUw0jPVUdA11jMx0lRWwA5M9IyMzYyNgMoM9CyNLU3NuVCNMDYwMABKmgApXGaYQpQA9RuZGxug6QfK4NQIBUAlNol5lXZoOnWN9AwsDMyNdYBuNDUxM7HENAboOyN0-_QMzA3MDYG2QhhY7DbQA0ubW5iaGEACbsECCA0A) No imaginary numbers for +2: ``` \(x,y)c((x^2+y^2)^.5,atan2(y,x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZBBCsIwEEVx6ykKbhJMwzhJmhbUk0hLKLgSKyVCcxY3deHW--hpHIyb1nY2E_jv_5_kdm_7Z-1aX_mmujQn1-4eV39M81dyYJ0IvGasK3EdSuSlNMJ5d0YWRMd55N4LGNgZEpWkSmrkq2R6tESVKSQMZKEKY5fDCAUAJGpacxkmIuRHq2DkJ2XW-BtCtu4c9iNnihJysErQHY3OdPEfQ6_DcZ8EC3ZDrfEw0Q3yK9vcaIgf1_dxfwA) ### Polar to cartesian, 24 bytes ``` \(r,a)r*c(cos(a),sin(a)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZBBCsIwEEVx6ykCbhJJhzGTNO3CmwglFARBrKTxNG7qwq1rz-JpjM1CGhX_5g-Z_2bCnC9-uB27vfNN6JrW-bC-nsK2qO4b7qUTftnytuu5E7LfHaKJ1H7MaEJxDYpKUpIVCDXVxooFy6TAxDaBVvMpaxAxgcoSfoJRlCI6WgbH5-_IW69IvlIy9YcqFGCFliTTYHSp63wxrOJcsJXRvz6AgBbtGBuLdLthSP4E) [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/blob/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b/docs/info.txt), 7 + 22 = 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ### Polar to Cartesian (7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)): ``` .¾¹.½‚* ``` Loose inputs in the order \$\phi,r\$; outputs as a pair \$[x,y]\$. [Try it online](https://tio.run/##MzBNTDJM/f9f79C@Qzv1Du191DBL6/9/XQM9S2NLU3MuEz0jYzNjIwA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfWVQwqGV//UO7Tu0Tu/Q3kcNs7T@6/yPjtY10LM0tjQ11zHRMzI2MzaK1QELGZkbG@iYGhgYAPmGOiDSSMcUSBromVuYmhjoGOgZxsYCAA). ### Cartesian to Polar ([22 bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)): ``` nOtI`’£×.aÇâ2(ÿ,ÿ)’.E‚ ``` Input as a pair in the order \$[x,y]\$; outputs as a pair \$[r,\phi]\$. [Try it online](https://tio.run/##MzBNTDJM/f8/z7/EM@FRw8xDiw9P10s83H54kZHG4f06h/drAgX1XB81zPr/P9pIz1RH11jPxCgWAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfeX/PP@SyoRHDTMPLT48XS/xcPvhRUYah/frHN6vCRTUc33UMOu/zv/oaCM9Ux1dYz0To1idaGMDAwMdXRMgCeQY6IBIXSM9AwsDc2MdEz1TEzMTS5CEnoG5gbmhDpSOjQUA). **Explanation:** ``` .¾ # Calculate the cosine of the first (implicit) input ϕ ¹.½ # Also push the sine of the first input ϕ ‚ # Pair them together * # Multiply them to the second (implicit) input r # (after which the pair is output implicitly as result) ``` Although 05AB1E does have tangent, sine, and cosine builtins, it lacks arctan; arcsin; and arccos builtins (both with 1 or 2 arguments). So we'll use a Python eval for it instead (hence the use of the legacy version of 05AB1E)†: ``` n # Get the square of the values in the (implicit) input-pair [y,x] O # Sum them together t # Take the square root of that I # Push the input-pair [x,y] ` # Pop and push both separated to the stack ’£×.aÇâ2(ÿ,ÿ)’ # Push dictionary string "math.atan2(ÿ,ÿ)", # where the two `ÿ` are replaced with `y,x` respectively .E # Evaluate and execute it as Python code ‚ # Pair it with the earlier calculated sqrt(y²+x²) # (after which it 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 `’£×.aÇâ2(ÿ,ÿ)’` is `"math.atan2(ÿ,ÿ)"`. † The new version of 05AB1E is possible as well, but `.E` is eval as Elixir instead of Python, in which case the `math.atan2(a,b)` would be `:math.atan2(a,b)`, which is 1 byte longer. [Answer] # [Lua](https://www.lua.org/), 41 + 41 = 82 bytes **Cartesian to Polar, 41 bytes** ``` x,y=...print((x^2+y^2)^.5,math.atan(y,x)) ``` [Try it online!](https://tio.run/##yylN/P@/QqfSVk9Pr6AoM69EQ6Mizki7Ms5IM07PVCc3sSRDL7EkMU@jUqdCU/P///9Geqb/dY31TIwA "Lua – Try It Online") **Polar to Cartesian, 41 bytes** ``` r,t=...print(r*math.cos(t),r*math.sin(t)) ``` [Try it online!](https://tio.run/##yylN/P@/SKfEVk9Pr6AoM69Eo0grN7EkQy85v1ijRFMHyivOzAPyNP///2@iZ2RsZmz0X9dAz9LY0tQcAA "Lua – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 + 7 = 17 bytes ## Cartesian to Polar, 10 bytes ``` ²∑√?Ṙƒ/∆T" ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLCsuKIkeKImj/huZjGki/iiIZUXCIiLCIiLCJbMzAwMCwgLTQwMDBdIl0=) ## Polar to Cartesian, 7 bytes ``` ⁰₍∆c∆s* ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLigbDigo3iiIZj4oiGcyoiLCIiLCI0LjIzNjMyXG4tMC45Mzk1NyJd) [Answer] # [C (gcc)](https://gcc.gnu.org/), 88 bytes ``` C(x,b,t)float*x,t;{t=x[1];x[1]=b?*x*sin(t):atan(t/(*x));*x=b?*x*cos(t):sqrt(*x**x+t*t);} ``` # 86 bytes 2 bytes can be saved by inverting the order of the cartesian coordinates, that is, \$(y, x)\$ instead of \$(x, y)\$, ``` C(x,b,t)float*x,t;{t=x[1];x[1]=b?*x*cos(t):atan(*x/t);*x=b?*x*sin(t):sqrt(*x**x+t*t);} ``` [Try it online!](https://tio.run/##lVLRbpswFH3nK66YJmHjOMaY0syN9rDPYDy4LFSWEmDgSdaq/HqZDSFUbTptfrCv7znH9@heV5unqhrHb5Elj8Sg@tgqgy0x8tnsbZGU0m/7x6/Y4kE3kUFflFHu3EbYIiSxnbGqHTw2/OyNAzC2scEGyfP46ceh1s0B6rY/KQPh54RTUYfBku8sdL1uTB1dGAvxexMSsAUr/Z6UKAhOyhlAzwG4NfkEU5SwhznjF6cZgU1KBYdbiwAIytO7lDsWo7t0l@XkKk4ZYy4v3PGBOJsZTsnzlK1Kl7wpWZWOkdBkVWw4ZfcsT4kzlIk7sXtfiwB/VYGynOUJWYIbFeiE5veZuDg7yyCYAtddaFyfBv370NZuTLBd4qmN/i7kq7bagpdy1m63UKneHAatGjAtdO1R9TO17SP/st4zCfqhkRDHGq2z8KNzRU0hsC7lNMPlGrtvdeV1do39L2ToNtb9MkMUhhf0PNtbk4vbyaB3erX9325j/tZv@he/yT/6PQfjS1Uf1dMwbo6nPw "C (gcc) – Try It Online") Pointer `x` is used for both input and output. `b` specifies which conversion must be applied (`0` for cartesian to polar, any non-zero value for polar to cartesian). The solution is not made up by two different functions, but I think should be acceptable. # 62 + 53 = 115 bytes As two separate functions: ``` A(x,t)float*x,t;{t=x[1];x[1]=atan(t/(*x));*x=sqrt(*x**x+t*t);} B(x,t)float*x,t;{t=x[1];x[1]=*x*sin(t);*x=*x*cos(t);} ``` [Try it online!](https://tio.run/##lVLbbqMwEH3nK0ZUlbjFMcaURl4e2t@gPFg0VJYSoOBKVit@fdkBQojadNXOgz2XczxHMy42L0UxDA@OCbRbHmqpPfTEh05NFuZiPFKpZeXoreMZ1xWeSbvXVmPgecbXnnZFbz3@j47ITuEDExeDou7GoB9unvelqvZQ1u1RarBvQ0Z4aVtLvjHQtKrSpXNCLMCnyg7AZDQfzzB3LesosYP7YQHaJAN0lkMKc2Y0RuIANhHhDK5ZAMAJi@4ihihKdtEuToIzOaKUYp7j9Q05nhHIZElEVyYmr1JWJiJCEq6MDSP0niZRgIJifsd3X3sFwC46EJrQJAwW50oHMlWT@5iflPXCsiYHpwsVzqlT7/u6xLXAdvGnMY4xFxdjNRnLxczdbqGQrd53Slaga2jqg2xnaN0648sqpQLUn0qA7yt33cW4OmyqM@6pXEw7XEIff80Z15jVxx/qXq80b7pzbPtU7Wdxa3LROskbdZ5F/1qrzz6rjb5R@/hjtb01/C3Kg3zphs3h@A8 "C (gcc) – Try It Online") 2 bytes can be saved using the same trick as above described. [Answer] # [lin](https://github.com/molarmanful/lin), 28 + 17 = 45 bytes To Polar (`[a b] -> [a b]`): ``` "2^.$_ +.5^"".$_.~ atant", Q ``` To Cartesian (`a b -> [a b]`): ``` "cos *""sin *", Q ``` [Try it here!](https://replit.com/@molarmanful/try-lin) For testing purposes: ``` [2.5 3.42_ ][3000 4000_ ][0 0][2.08073_ 4.54649][0.07071 0.07071] ; ( ;.+.$_.; \form.'.$$ " -> "join outln ).' "2^.$_ +.5^"".$_.~ atant", Q "cos *""sin *", Q ``` ## Explanation Prettified code: ``` ( 2^.$_ + .5^ )(.$_.~ atant ) , Q ( cos * )( sin * ) , ' ``` Both of these expressions utilize a somewhat odd feature of lin. Data structures of strings/functions\* passed to certain commands will "fork" and execute each function, preserving the structure's shape. For example: ``` 1 2 [( 1+ )( 2+ )] es ``` would leave on the stack: ``` 1 2 [[1 3] [1 4]] ``` The `Q` command ("quarantine") executes a function on an isolated copy of the current stack and pushes the resulting top item. So the following: ``` 1 2 [( 1+ )( 2+ )] Q ``` would leave on the stack: ``` 1 2 [3 4] ``` \*: In lin, strings and functions are the same datatype. [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 34 + 24 = 58 bytes ``` f(x,y)=[abs(z=x+I*y),if(z,arg(z))] g(r,a)=r*[cos(a),sin(a)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZDNSsQwFEZxOysfIXSVjGnI5Kdpkbr3GWKQKCQUZAzpCNO-ipsuFJ9Jn8bbZiWDq-_cLyH3kPev5PPwGNPy8ZBQ8_l2CnX7fRvwmU6kt_5pxHN_vrnfT4QOAc_U54hnQtwu4kw96fPePr-O2BM6DkcIV574ubr2Kb1M2KP6DqU8HE-4CrhC3h4cqihaSQAR1AMHvPZ06wihyFrBNEW1ZEpAbSXnHEYFsY7AW9aC8ZYbSZFiWjWq2w4ZN9wc4EoB58ju0iX-6xIvXBQTspECBDjrZKfNukYXJWiEkX-sQFwUkU3CtFpxkCgfsywlfwE) ]
[Question] [ Draw an "apartment" building according to the specifications below. ## Basic Rules Take, as input, the number of floors of the building. Return a building with that many floors meeting the following specifications: The building will be eight characters wide, with eight underscore characters (`_`) on top and eight dashes (`-`) on the bottom. The first floor of the building will always look like this: `| || |`. As long as the building has more than one floor, the top floor will always look like this: `| ---- |` All floors in between must be randomly selected between the following: `| - - |` `| [] |` `|__ __|` ## Example Outputs: 5 floors: ``` ________ | ---- | | [] | | - - | |__ __| | || | -------- ``` 2 floors: ``` ________ | ---- | | || | -------- ``` 1 floor: ``` ________ | || | -------- ``` ## Specific rules Your inputted number of floors will, at minimum, be 1. You may output as a string, a list of strings, a nested list of characters, or any other output format in which the position of each element is clear. All floor types must have a nonzero chance of appearing at any given level (other than the bottom and the top), but they do not have to be uniformly randomly chosen. Code-golf, so shortest code wins. [Answer] # x86-64 machine code, 68 bytes ``` B8 5F 5F 5F 5F BA 7C 20 2D 2D AB 0F C8 3C 5B 75 02 B0 5D AB B0 0A AA 0F C7 F0 9E B8 7C 20 20 5B 72 0C B8 7C 20 2D 20 74 05 B8 7C 5F 5F 20 92 FF CE 7F D7 B8 7C 20 20 7C 74 D0 6A 08 59 B0 2D F3 AA 88 0F C3 ``` [Try it online!](https://tio.run/##jVNdb5swFH22f8UdU4RpSJVkXVWRZC973sueJoUocmwDrsBGmLRkTf76sgskrGqnaUICc8/HPb4YMUmFOJ@5K4DBd4/R2zS3O55DQpOIFPYJFG9CYP7Wv5k201l/BbSHZAcdfTiCD/5y@dAuJriY3V9X87uA2oi42jpJyc4987K1pEQUJfA8BH/tU/JoFLikd@2KG5@6ZJAN5dgguS3uKKlkxY3szRzPLupL3DeZYMi0vmQijwLkvyR/tgGD5OdfJdurZPtOIiPSiCzt@TguSqQSoJxGsxTs/0U@vuqPknLvMnhYkNKWUInm1XQmOJxKlXAZUFtfV1JvQhB5i9Q08CBY0CerJSRMZLy6AReCNjUYrNOP2oh8LxUsXS21vc2@UNqCBdeGBfQFvxpqoFJun9frz7P5ZkFJYitgnQWsYLbAx3KF@cCMx5gZNSRhvSLsuhBSVkhPmDfSUWxGLjax8RALL8Yt50QHVmy@cZFpPCHCShV5Ldy2a7DdNIQDvkoLL1c6jKbzH2h3WDG2N06nRknothokwboZjzfB4gTPmc4VsAN8QJPm66fWdHBgIw27Q61c0AVrEDydz79EkvPUnSfF/R3e8JdZIV/lvwE) Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input number in ESI. In assembly: ``` .global f f: mov eax, ('_'*0x01010101) # For the first line. mov edx, ('|' | ' '<<8 | '-'<<16 | '-'<<24) # For the next line. o: stosd # Add EAX to the output string, advancing the pointer. bswap eax # Reverse the order of the bytes of EAX. cmp al, '[' # Check if the low byte is '[' ... jne sf # ... and if it is ... mov al, ']' # ... change it to ']'. sf: stosd # Add EAX to the output string, advancing the pointer. mov al, '\n'# Set AL to a line feed. stosb # Add that to the output string, advancing the pointer. rdrand eax # Put a random number in EAX. sahf # Set flags from AH (its second byte). mov eax, ('|' | ' '<<8 | ' '<<16 | '['<<24) # One of the possibilities. jc d # Jump if CF=1. mov eax, ('|' | ' '<<8 | '-'<<16 | ' '<<24) # Another possibility. jz d # Jump if ZF=1. mov eax, ('|' | '_'<<8 | '_'<<16 | ' '<<24) # The third possibility. d: xchg eax, edx # Exchange registers. dec esi # Subtract 1 from ESI, counting down from the input number. jg o # Jump back if the number was >1 before the subtraction. mov eax, ('|' | ' '<<8 | ' '<<16 | '|'<<24) # For the lowest floor. jz o # Jump back if the number is 0. push 8; pop rcx # Set RCX to 8. mov al, '-' # Set AL to '-'. rep stosb # Add AL to the output string RCX times, advancing the pointer. mov [rdi], cl # Add the low byte of RCX, which is now counted down to 0. ret # Return. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 41 bytes ``` ‹¨2[` [ - __ `²℅|ð2-]\|p;‛| m4-½J\_4*pøm ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigLnCqDJbYCAgWyAtIF9fIGDCsuKEhXzDsDItXVxcfHA74oCbfCBtNC3CvUpcXF80KnDDuG0iLCIiLCIzIl0=) ``` ‹¨2 ; # Dyadic map (val, index) to... [ ] # If the index is truthy (i.e. not first) ` [ - __ `² # String literal " [ - __ ", made into a square (chunks of 3) ℅ # Choose one of these | ] # Else... (first) ð2- # " --" - Take a space and append two -s \|p # Prepend a | ‛| m # Take "| " and mirror it 4- # Append four -s ½J # Split that in half and append \_4*p # Prepend "____" øm # Vertically mirror (flipping []) and join by newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~46~~ 44 bytes *-2 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).* ``` '_4×I≠i"| --"¹ÍF"| - | [|__ "3äΩ]„| º'-4×»º ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fPd7k8HTPR50LMpVqFHR1lQ7tPNzrBmIq1CgoRNfExysoGR9ecm5l7KOGeTUKh3ap6wLVH9p9aNf//6YA "05AB1E – Try It Online") [Answer] # [Python](https://www.python.org), ~~102~~ ~~139~~ ~~136~~ ,~~134~~ 117 bytes ``` lambda n:[8*"_","| ---- |",*choices(['| - - |','|__ __|','| [] |'],k=n)][:n]+[2*"| |",8*'-'] from random import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCsIwEEX3nmLIJmlMwboqhZ4kDaG2jQZtEtJ0IeQmbgqid_I2ptbhw_-84c883u4eLtYsT1U3rzmovPzMt3Y89S2YipcUScRQhDwNRMRod7G6GybCcYKQFDHDUUoAKX8RgAtIVLBrbTLBKyP2_EjTjbVfUpxjsVPejuBb0yfTo7M-0P9zqqwHDdqs6_NAClYcssp5bQKhiuiMTYOrUWNQtjWWZfMv) Thanks to @Steffan for pointing out I can't read. Now outputs the correct apartment -3 bytes thanks to @Steffan -2 bytes from me -17 bytes thanks to @loopy walt [Answer] ## C++, 281 bytes ``` #include<random> #include<string> using t=std::string;t a[3]={"| - - |\n","| [] |\n","|__ __|\n"};t f(int n){std::random_device g;std::uniform_int_distribution<int>d(0,2);t s("________\n");if(n>1)s+="| ---- |\n";for(int i=2;i<n;++i)s+=a[d(g)];s+="| || |\n--------";return s;} ``` I didn't want to use the standard C `rand` and `srand` functions, so here I go with the standard library of C++. [Answer] # [Perl 5](https://www.perl.org/) `-n`, 110 bytes ``` @a=map{('| - - |','| [] |','|__ __|')[rand 3]}1..$_;@a[0,-1]=("| ---- |","| || |");say for'_'x8,@a,'-'x8 ``` [Try it online!](https://tio.run/##JcvRCsIgGAXge5/iRwI3UNHGYDAGvkBPIPIjVBDUFNdFkb16f0aHc@C7OflUriORi8st5lcnKihorUI2gg/wJyIAYhW9L3E9whDeVusdzi56I5UNS8fbswUql41Qf@P9vMUnnFMRKB6TdFEK1UA0sIlZtv@kfL@kdSN1GLWxhtT6BQ "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ×_⁴⸿E⊖N⎇ι‽⪪| - | [|__⁴| --⟦| |⁴⟧‖M ``` [Try it online!](https://tio.run/##Rc0xC8IwEIbh3V9xZLpAuunU1cVBkdqtSonpiYEkLWcqCPnvMUXR8Z6D9zN3zWbULucj2xCxtZ4eKHqhYC1lvfqoOLP4HXs94ZYMk6cQacBdmOZ4mP2VGKVU0BIHzS@0ChodhtHjaXK2RBJUkAC61H/zCharhPwvdUUgLe9LsYZujkzcW@axxOucN7l6ujc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ×_⁴⸿ ``` Output four `_`s and then move to the start of the next line. ``` E⊖N⎇ι‽⪪| - | [|__⁴| -- ``` Output `| --` for the top floor, but randomly choose between `| -` , `| [` and `|__` for intermediate floors. ``` ⟦| |⁴⟧ ``` Output the left half of the ground floor and the ground. ``` ‖M ``` Reflect to complete the building. [Answer] # Excel, ~~143~~ 142 bytes Anonymous worksheet function that takes input from cell `A1` and output to the calling cell. ``` ="________ "&If(A1>1,"| ---- | ","")&Concat(IfError(Choose(RandArray(A1-2,,1,3,1),"| - - ","| [] ","|__ __")&"| ",""))&"| || | --------" ``` ## Example Output [![enter image description here](https://i.stack.imgur.com/ggYHZ.png)](https://i.stack.imgur.com/ggYHZ.png) [Answer] # JavaScript, ~~168~~ ~~153~~ ~~151~~ ~~149~~ ~~147~~ ~~146~~ ~~140~~ 136 bytes -13 thanks to Steffan, -2 by emaneresu A, -2 by myself, -2 by myself, -1 by myself, -6 by tsh, and -4 by me ``` n=>`________${[...Array(n-1)].map((_,i)=>` |${[` - - `,` [] `,`__ __`,` ---- `][Math.random()*3|!i*3]}|`).join``} | || | --------` ``` [Try it online!](https://tio.run/##ZYpBCoMwEEX3OcUUukjEBKx0VSz0AD2BhExQaSOaSJRCaTx7GsFN6eMPfN6fXr/03HgzLdy6tou6ira6oto5fmohxM17/aaWF0yKUU@Uqtyw9EVC2hE4pGCOALWErSgFoNRmeAJQ1ne9PIXXtnUjZVkZDiYr5RqQid4Zi7iSABC2I3wHY@Ps7IZODO5BNT0zdiG/6vSviqTiFw "JavaScript (Node.js) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 160 bytes ``` f->{var b="________\n|"+(f>1?" ---- |\n|":"");for(var r=3;f-->2;r=3)b+=" - - , [] ,__ __".split(",")[r*=Math.random()]+"|\n|";return b+" || |\n--------";} ``` [Try it online!](https://tio.run/##NU9BbsIwELzzipFPDiZWaW81SW@VeuDEEVDkAKGmiRM5GwQivD3dUDqyNbvr0Yz3ZM82Pu1/Blc1dSCcuNcduVIXnd@Rq72emsmutG2LpXUetwnQdHnpdmjJEtO5dntU/CZXFJw/rrew4dhGDynw5enzabX4E6S4JEMRp7ezDcgTkT2x8b1QskjnHwIxA/04eRciMkUd5KgOyZsp4jh9NVxFuUpYCT4zgGMxyzIgy4Rum9KRFDMRrcM0WVr61sH6fV3JaKvEw9eEA3XBI1cC6HuMafETwtwH8/g9B0M6T3BIMDdMC@YXLpT63xBYXVs6VLruSDe8IZVeOiU2XqiLtk1TXqWLxp4n0Z/vfTLe@/AL "Java (JDK) – Try It Online") [Answer] # Google Sheets, ~~162~~ 159 bytes ``` ="________ "&IF(A1>1,"| ---- | ","")&JOIN("",ARRAYFORMULA(IFERROR(CHOOSE(INT(RANDARRAY(A1-2)*3)+1,"| - - ","| [] ","|__ __")&"| ","")))&"| || | --------" ``` [![enter image description here](https://i.stack.imgur.com/aFh65.png)](https://i.stack.imgur.com/aFh65.png) *-2 bytes thanks to Taylor Alex Raine* [Answer] # [Perl 5](https://www.perl.org/) + `-n -M5.10.0`, 93 bytes This is based on golfing [@Xcali's answer](https://codegolf.stackexchange.com/a/247485/9365). ``` say for"_"x8,(map{(<"|{ ---- , - - , [] ,__ __}|">)[$_-2&&1+rand 3]}2..$_),"| |"x2,"-"x8 ``` [Try it online!](https://tio.run/##FcxBCoMwFEXReVbx@IgoJsFEBAelO@gKRD6BtlBoTYgdWIxbb2rv5MxuuMVnn/PiPrj7SEzrIKuXC1t1orRBHUFCAX8wToBkBpj3ROd6LFjZsjRNdPMV3bRbrQuuJSUg0WolqWOYcycGYYT9@vB@@HnJas7q0mvT6vYH "Perl 5 – Try It Online") --- # [Perl 5](https://www.perl.org/) + `-n -M5.10.0`, 97 bytes ``` say$_.reverse=~y/[/]/r for'_'x4,(map{(<'|{ --, - , [,__ }'>)[$_&&1+rand 3]}0..$_-2),'| |','-'x4 ``` [Try it online!](https://tio.run/##DczRCoIwFADQ933FfRhepd3NaUIP1R/0BUOG0ILA3JgRibNPb3U@4AQXxy7neVi4ldG9XJzd6bMoo3oV4eYjWnzvRfkYwloeMa1AJIBAABhhLWx4rgy3RaF3cZiu0PZbLSW31FQCE0BCgfQfcm7ZgWnWfH143v00Z7p0stZ1pukH "Perl 5 – Try It Online") Not smaller, but a reasonably different approach that might have potential for more golfing... [Answer] # [JavaScript (Node.js)](https://nodejs.org), 136 bytes Tied with [@code's solution](https://codegolf.stackexchange.com/a/247475). Used the `!i*3` trick to shorten my own solution. Go vote up their answer because mine would be worse without theirs. ``` n=>['________',...[...Array(n-1)].map((_,i)=>['| - - |','| [] |','|__ __|','| ---- |'][Math.random()*3|!i*3]),'| || |','--------'] ``` [Try it online!](https://tio.run/##fYtBCsIwFET3niKu8lOaD7W4kgoewBPEEEJtNaVNSloEIXeP0XbTjcN8GOb96fRLT7U348ytuzexraKtzoKqVTRHRJHu4r1@g@UFkzjoEUDlhn0/A@EkOdA8RSIkWaJShCi1tDwptVJc9fxEr@3dDcCyMuxNVkr2G4awDPkqKmPt7OT6Bnv3gBaODDtnLNCbpYyddlt6@EuLLY0f "JavaScript (Node.js) – Try It Online") [Answer] # [C (GCC)](https://gcc.gnu.org), ~~213~~ 179 bytes *-31 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) and @JuanIgnacioDíaz* *-3 bytes thanks to [@c--](https://codegolf.stackexchange.com/users/112488/c)* ``` p(x,i){for(i=9;i--;x/=8)printf(L"\n| _-[]"+x%8+!!i);}c;main(n){srand(&n);scanf("%d",&n);for(p(4793490);--n;)p(c++?L"\x592c8\x4d848\x91290"[rand()%3]:374472);p(294984);p(7190235);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=LY9RqsIwFES3ooE-7qWGV9NbmvuCuAF3oCIlpZIPY6g-CKgr8ad-uAJX425s1a-Z-Tkzc73bzdbarrv_Hxupn48AceLw1OxbcDM2TkoTf2caQ-v8sYGFWPnzaCOXa5HGRKfjsUNzsWZXOQ8eT4e28jX8eDQHW_kGRFKLyRAHYAAqOSfO0EjpDQawaTrvkbFgZfUqUq2pF54qzsTyjcIkX__lJVGp0ARQTKxpcOWUM5UXfftn-vdBd6OPeQE) [Answer] # [C++ (GCC)](https://gcc.gnu.org), ~~182~~ ~~177~~ 168 bytes ``` #import<ios> auto f(int i){std::string s(8,95),t[]{" - - |"," [] |","__ __|"};if(--i)for(s+="\n| ---- |";--i;)s+="\n|"+t[rand()%3];return s+"\n| || |\n--------";} ``` This requires gcc's `#import` directive. `95 == '_'`, so `std::string(8, 95)` constructs a string of 8 `'_'`. [Attempt This Online!](https://ato.pxeger.com/run?1=VVJLasMwEKVL6xSDQoNUy9D0A2ns5AQhu64cY4w_icCWgiSnizgn6SabQrvogdrTVHZUQoYZGN783oz0_p3v6lb3lm7y_HT6aE0VTH8-R7zZSWUiLvUCZa2RUBEuDHB60KaYzbRRXGxAkyl7eabMxMkBQwBWO8wwQJzA4KUpQJp2-BjyigQBp5VURPtzvBYdBFZsVmjxkDoQ-yZWmSgIvX1MQlWaVgnQ_pAPXW9rETjB4fHM9_dmNeIir9uihJ6yUWXWLNAFy7eZyqXYX2HnHRYI2cVQk3ExbJipTc6gL4A76-_jhKID8vpQVUupNAMOc5iEyIIVkD4fInigyPMc3SGmhy0Mb0qyel0uKe3BQoLt5Q0nrJRs0n6OJsMcnjBwDvhgydWl-I9Q5obbLq48l62BKLLvcokc4W3L6xKI73PLaaA2HgO5KsCXAwbBWmAGkzM5x_4-RO6sX_ETA6vTxP2LPw) [Answer] # [Factor](https://factorcode.org/), ~~139~~ 138 bytes ``` [ dup [ "________", 1 > [ "| ---- |", ] when 2 [-] [ { "|__ __|""| - - |""| [] |"} random , ] times "| || |", "--------", ] f make ] ``` [Try it online!](https://tio.run/##NU9BDoIwELz7iknPYhT1oolX48WL8YSkaWANFWixlHgQ345bxJl0s9mZ3UzvKvPWDdfL6XzcoSRnqEKtSuLii7EsrMvJodKenKpaOGVyW6OlZ0cmoxbaYj@bvbFixsw1Ntgy4yU@Q4K8a5BAyAlizrZDmPSIGOh5kuJVkOHdJEpZerMoJSBlL4INCDbukKTg7vMPETa9rjlEEPvw@JqIJoyX77//pBxF3IzAw2qDxmnjYSrWM1s3tiWQyorhCw "Factor – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip), 63 bytes ``` P'_X8Fi,DaPi?RC" - - [] __ __"<>6'-X4WRsWR:'|P"| |"X2'-X8 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhY37QPU4yMs3DJ1XBIDMu2DnJUUdBVASCE6VkEhPh6ElWzszNR1I0zCg4rDg6zUawKUahQUapQijICCFhBjoKYtjjaNhTIB) ### Explanation Roof: ``` P'_X8 P Print '_ Underscore X8 Repeated 8 times ``` All floors except ground floor: ``` Fi,DaPi?RC" - - [] __ __"<>6'-X4WRsWR:'| Fi For i in ,Da Range(argument decremented): i? If i is nonzero (not top floor): RC Random choice from " - - [] __ __" This string <>6 Split into sections of size 6 Else (top floor): '-X4 Four hyphens WRs Wrapped in spaces WR:'| Wrap the whole string in pipes P Print it ``` Ground floor and ground: ``` P"| |"X2'-X8 P Print "| |" That string X2 Repeated 2 times '-X8 Hyphen repeated 8 times Last expression is autoprinted ``` [Answer] # [Python 3](https://docs.python.org/3/), 164 161 bytes ``` from random import* def b(n): yield"_"*8 if n>1:yield"| ---- |" for _ in range(n-2):yield choice(["| - - |","| [] |","|__ __|"]) yield"| |"*2+'\n'+"-"*8 ``` [Try it online!](https://tio.run/##RY5LDoMwDETX4RRWNiR8pEI3FYteBFBUfsWoOChig5S701ioqjcej0fP3o59tnQ/z8nZFdyLhtBw3azbk2gYJ@gU6SoSB46fQRqZPCKBE9CzqC7LQx4KvIzEZB0YQGLMe1SUl/oKQT9b7EdVcxqA01mQULdwSWMAjPGy1b9LnjdJmcYNxanMw92T8fjHF1lx48/YXtjuFPIsNoe0qyWgLiUbkvr8Ag "Python 3 – Try It Online") Python generator for the win. Improvement 1 : Removed unnecessary white-spaces. Thank you @jezza\_99 for the suggestion. [Answer] # [SWI-Prolog](https://www.swi-prolog.org/), 177 bytes ``` N+[A|T]:-length([_|X],N),A='________',-X,append(X,['| || |','--------'],T). -X:-X=['| ---- |'|T],+T;+X. +X:-X=[A|T],random_member(A,['| - - |','| [] |','|__ __|']),+T;1=1. ``` Recursion, recursion, recursion. [Try it online!](https://tio.run/##Jc3LCsIwEIXhvU8xZDUDk9KNm6qP0KwLoQwRqxZyKbHQTd69NnpW3@KHs@Tk00t/tnnfHfbU6bi@WzQsLMQeDbG59s2pqtPm1vIz5eBWVAX0MSiKrRnpkl18pCBhCvcp48BgawHwKw6CHeFPEQCRokbiLc/r5CMO1NT7MzVf) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~111~~ ~~109~~ ~~102~~ ~~96~~ 93 bytes ``` '_'*8 for($x=' ---- ';--$args[0];$x=' - - ',' [] ','__ __'|random){"|$x|"} '| |'*2 '-'*8 ``` [Try it online!](https://tio.run/##JY5BCsIwFET3/xRDiH4tDWg3iqUnKeVTsdFF20iKWGh69hj1MYthBoZ5unfnp0fX91FbVFgiC2dnss7v9FwxTAJcGqNbf5/qQ1P@YyRxzkDd4GtEABEOvh1vbtgvKug5qJU4AIGzgtik3bgSnXIqcjqGDRZCQo2v4dp5OAvbO@enC7SoX7VNn7TQGj8 "PowerShell – Try It Online") [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), ~~194~~ 189 bytes -5 (me) small optimistions ``` &&\52**+052*"________">:#,_$:1`#v_>0"--------"52*"| || |">:#,_@ >:#,_$1-:! #v_02vv"| ---- |"*520<0 ^"|__ __|"< 5>:#,_$2-: #v_^ ^"| [] |"? <* <>#5 #2 #0 #< ^ ^"| - - |"<> ^ ``` [Try it online!](https://tio.run/##LczBCsIwDAbg@57iN5EdqoWuUA@lVN9DXUWY3rzZU9@9Jm4/JJDwJc/l9f28l97H8Ra8MQcnncoWQo58LPs4PbiW7MhuIVUNaFr0R5dhtZONO4h2PtQqRrkYE7xLmIeZWilAKY0SNGY98zbqJIcrAq53/X1GQuYENuAA9mAHGTdkAX2esix6d8PpBw "Befunge-93 – Try It Online") Takes a two digit integer from stdin as input. Note that for some reason, in TIO the integers have to be on two lines. [Answer] # C (gcc `-w`), 162 bytes ``` *a[]={"| - - |","| [] |","|__ __|"};f(n,r){r=rand(srand(&n))%3;puts("________");for(n>1&&puts("| ---- |");n-->2;)puts(a[r++%3]);puts("| || |\n--------");} ``` Test main: ``` int main(void) { int i; for(i=0; i<100; i++) { f(i); puts(""); } } ``` Technically, it's not genuinely random, but every level type has a chance of appearing at every level. [Try it online!](https://tio.run/##NU1dC8IwDHzfrwgFR@MsTH2M849so5TJpKBROj8etv11a7bpkYTjcrk05tw0Ma5dWRe9GsCA1KA2QqGsYaHWAlg7qJFazZuAfSiC45Pu5pky4mpP9@ej08r@oJDaW9B83KbpspFsgQQisTHHHeGsuzJk2WpfI/1tMExdsflBDsbo@QFX51m/bv6E0CcAk@QpETZ98kVOkGX@sM1zWgyy0B5pZvcg9lariitWszYmY/w07cWdu2jeXw) ]
[Question] [ From [this](https://stackoverflow.com/questions/52764321/how-to-loop-2d-array-in-a-anti-clock-wise-fashion) stackoverflow question Given a 2D array of size \$ M \times N \$, output the values in a anti-clockwise fashion. The output must start from the outside to the inside and the initial point always is going to be \$(0,0)\$. **Example** Given: $$ \begin{bmatrix} \color{blue}1&\color{red}2&\color{red}3&\color{red}4 \\ \color{red}5&6&7&\color{red}8 \\ \color{red}9&10&11&\color{red}{12} \\ \color{red}{13}&\color{red}{14}&\color{red}{15}&\color{red}{16}\end{bmatrix} $$ The edge values in counterclockwise is then \$ 1,5,9,13,14,15,16,12,8,4,3,2 \$. Now we repeat the process for the inner values. This will end up with a matrix like the following $$ \begin{bmatrix} \color{blue}6&\color{red}7 \\ \color{red}{10}&\color{red}{11} \end{bmatrix}$$ And the inner values is then \$ 6,10,11,7 \$ The final result will be then \$ 1,5,9,13,14,15,16,12,8,4,3,2,6,10,11,7 \$ --- **Rules** * Assume non-empty input * Assume matrix values as positive integers * Standard [I/O Methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and winning criteria apply --- **Some test cases** ``` Input [ [1, 2, 3, 4, 5, 6, 7], [8, 9, 10,11,12,13,14], [15,16,17,18,19,20,21] ] Output 1,8,15,16,17,18,19,20,21,14,7,6,5,4,3,2,9,10,11,12,13 -------------------------------------------------------- Input [ [1,2,3], [3,2,1], [4,5,6], [6,5,4], [7,8,9], [9,8,7] ] Output 1,3,4,6,7,9,8,7,9,4,6,1,3,2,2,5,5,8 ----------------------------------------------------- Input [ [1] ] Output 1 ----------------------------------- Input [ [1, 2], [2, 1] ] Output 1,2,1,2 ----------------------------------------------------- Input [ [1,2,3,6,7], [2,4,3,2,1], [3,2,4,5,6], [6,5,6,5,4], [10,4,7,8,9], [12,4,9,8,7] ] Output 1,2,3,6,10,12,4,9,8,7,9,4,6,1,7,6,3,2,4,2,5,4,7,8,5,5,2,3,4,6 ``` [Answer] # [R](https://www.r-project.org/), 54 bytes Several bytes saved by @Giuseppe and @J.Doe. ``` f=function(m)if(ncol(m))c(m[,1],f(t(m[nrow(m):1,-1]))) ``` [Try it online!](https://tio.run/##VY4xC8IwEIV3f0XMdAfpcI04qJ1EXIvopA4lNTXQJJJGFP98TZwqHPce34O7F0b/iMa7AV6mjfeKZIkzS2xTMNvEYN5AK1oKtvjN8XDapbicxAp4HXwXGmuN67hgvH5@Pv1tyHaeV@PaLHvf66xb3944ClYKJtMtOX2Fo67006ncCCwaDU75PjlUYM@CrkJDTM4F/0p0RaKgKyKOltYaLOFaNRH4xXGcpZqZlf9MZiYnbPwC "R – Try It Online") Recursively strip off the first column and row-reverse/transpose (making the bottom row the new first column) the rest of the matrix until you end up with only one column. Ungolfed "traditional" version: ``` f <- function(m) { if(ncol(m) == 1) { m } else { c(m[,1], f(t(m[nrow(m):1,-1]))) } } ``` It was pointed out that `ncol(m)` could be golfed to `sum(m)` to save another byte because we are allowed to assume positive integer matrix values. But I'll leave it like this since it works for all matrices (even matrices of strings!) [Answer] # [Python 2](https://docs.python.org/2/), 52 bytes ``` f=lambda a:a and zip(*a)[0]+f(zip(*a[::-1])[1:])or() ``` [Try it online!](https://tio.run/##fZDLboMwFET3fMVd4mQqMcbYgNQvsbwgilAitYCibNqfpyaRm6A8Fl4cXc/4XE8/58M46HnuP7@6792@k66NZ9jL73HKN53yRdj2@RV8234wKM82qPGUq3k6HYez9LnPRDwhGlJCDKSCWIgLWAY1pIGwAAlqsATNdcIKtKADa7CBLqAZsqCy7L750q1RXjIRyghMYFDBJrARTAKHGk2CJoJ7Xv3iQdEpG7d6YwULd7tpsLJb4MFwZRm/xWClyiXy7yvzHw "Python 2 – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes ``` shMM.utC_ ``` [Try it here!](https://pyth.herokuapp.com/?code=shMM.utC_&input=%5B%5B1%2C2%2C3%2C6%2C7%5D%2C%5B2%2C4%2C3%2C2%2C1%5D%2C%5B3%2C2%2C4%2C5%2C6%5D%2C%5B6%2C5%2C6%2C5%2C4%5D%2C%5B10%2C4%2C7%2C8%2C9%5D%2C%5B12%2C4%2C9%2C8%2C7%5D%5D&debug=0) ### How? ``` shMM.utC_ Full program. Takes a 2D array (matrix) from STDIN. .u Until a result that has occurred before is found, loop and collect... _ Reverse the matrix (reverse the order of its rows). C Transpose. t Remove first element. hMM For each element in the resulting 3D array, get the heads of its elements. s Flatten. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ôQÖG·í< ``` [Run and debug it](https://staxlang.xyz/#p=93519947faa13c&i=[[1,+2,+3,+4,+5,+6,+7],+[8,+9,+10,11,12,13,14],+[15,16,17,18,19,20,21]]&a=1) It takes an array of rows on one line, and produces newline-separated output. Unpacked, ungolfed, and commented, it looks like this. ``` W repeat the rest of the program until cancelled explicitly rM rotate matrix *clock-wise* (yes, this is the opposite of the challenge) |c assert matrix is truthy. (has rows) cancel otherwise. B remove the top row of the matrix, and push separately to main stack rm reverse the top row (this fixes the rotation direction), and print each value ``` [Run this one](https://staxlang.xyz/#c=W+++%09repeat+the+rest+of+the+program+until+cancelled+explicitly%0A++rM%09rotate+matrix+*clock-wise*+%28yes,+this+is+the+opposite+of+the+challenge%29%0A++%7Cc%09assert+matrix+is+truthy.+%28has+rows%29+cancel+otherwise.%0A++B+%09remove+the+top+row+of+the+matrix,+and+push+separately+to+main+stack%0A++rm%09reverse+the+top+row+%28this+fixes+the+rotation+direction%29,+and+print+each+value&i=[[1,+2,+3,+4,+5,+6,+7],+[8,+9,+10,11,12,13,14],+[15,16,17,18,19,20,21]]&a=1) [Answer] # Pyth, 20 bytes ``` J.TQWJ=+YhJ=J_.TtJ)Y ``` [Try it here](http://pyth.herokuapp.com/?code=J.TQWJ%3D%2BYhJ%3DJ_.TtJ%29Y&input=%5B%5B1%2C2%2C3%2C4%2C5%2C6%2C7%5D%2C%5B8%2C9%2C10%2C11%2C12%2C13%2C14%5D%2C%5B15%2C16%2C17%2C18%2C19%2C20%2C21%5D%5D&debug=0) ### Explanation ``` J.TQWJ=+YhJ=J_.TtJ)Y J.TQ Call the transposed input J. WJ ) While J is not empty... =+YhJ ... put the top row into Y (initially [])... =J tJ ... remove the top row... _.T ... reverse and transpose (rotate clockwise). Y Output the result. ``` [Answer] # [oK](https://github.com/johnearnest/ok), 12 bytes ``` *+,/(1_+|:)\ ``` [Try it online!](https://tio.run/##PY47EoJAEERzTtGZi7YlPftj8SpWmZEYeAHvjrNokb35venX9f3atnU5X3gLel4@y/jY1lMIgiEiDUBGQcXs1KAJEmReKEIJylAZhyDCiEgkIhOFqL4zE41@RIkyKlLdqEwVqlIz1WgTTeNAymeAu4xxx@j0ayZmlp2KU9qpcmbbqTnVngJ2N7gr@JNuYWHP4dkSD1mHw9d1h9KTJh5a9bW/ety@ "K (oK) – Try It Online") This abuses the fact that oK doesn't seem to care too much about shape for transposition. In k this would be **13 bytes**: `*:',/(1_+|:)\`. ``` +|: /reverse, then transpose (rotate right) 1_ /remove first line ( )\ /fixpoint of the above, keeping intermediate results (scan) ,/ /concatenate all the rows *+ /get the first element of each row ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 69 bytes ``` import StdEnv,StdLib ? =transpose @[h:t]=h++ @(reverse(?t)) @_=[] ``` # ``` @o? ``` [Try it online!](https://tio.run/##Lc47C8IwFAXg2fyKCy6KV/D6VgjtoIPg5hiCxBptoElLmvr480YhTofvcIZTVFq5aOtrV2mwyrhobFP7AKdw3bsH/uJoLiwDHrxybVO3muWi3AbJy9EI8oHXD@1bPcjCcMjyMxcynoLygfXh1rkCOOR1xniCVcGbF3uW2us/fgMhCGGKMEOYS2S9nlggLBFWCOvkDQJNkAhpmgqaIc2RFkhLKeOnuFXq3sbx4Rh3b6esKRLS@y8 "Clean – Try It Online") Moves the next row/column to the head of the list so it can pattern matched in the argument. For the first example in the challenge, this looks like: ``` @o? [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] @ h=:[1, 5, 9, 13] t=:[[2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]] [1, 5, 9, 13] ++ @ h=:[14, 15, 16] t=:[[10, 11, 12], [6, 7, 8], [2, 3, 4]] [1, 6, 9, 13, 14, 15, 16] ++ @ h=:[12, 8, 4] t=:[[11, 7, 3], [10, 6, 2]] [1, 6, 9, 13, 14, 15, 16, 12, 8, 4] ++ @ h=:[3, 2] t=:[[7, 6], [11, 10]] [1, 6, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2] ++ @ h=:[6, 10] t=:[[7, 11]] [1, 6, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2, 6, 10] ++ @ h=:[11, 7] t=:[] [1, 6, 9, 13, 14, 15, 16, 12, 8, 4, 3, 2, 6, 10, 11, 7] ++ @ [] ``` [Answer] # [Julia 0.7](http://julialang.org/), 47 bytes ``` f(m)=[m[:,1];sum(m)<1?[]:f(rotr90(m[:,2:end]))] ``` [Try it online!](https://tio.run/##bY3LCoMwEEX3/YrZNYEsHE2TmrT0Q8IshCq1@MLH96cjUgrWzYGZw733vTR1YWOsRCvvoQ1OIflpafm84SOQq8TYz2OeiNWlruyeJCXFYay7uekE63J6FUMp0KFRWml5lvJ0pFNUVmU7HRBSyHzGRK/hAsYbpvYWrpD7nGlpl6C/Bs9pOugFA5adhq1/5W9j28GEX9sYrva7GD8 "Julia 0.7 – Try It Online") Julia has a convenient built-in to rotate the matrix by 90 degrees eliminating the need for transpose-reverse operations. As you can see from the compiler warnings, it insists that all components of the ternary conditional should be separated by spaces, and in v. 1.0 this has been actually enforced. Oddly enough, in this situation the shortest way I found to break out of recursion was to use a try-catch block: ## [Julia 1.0](http://julialang.org/), 50 bytes ``` f(m)=[m[:,1];try f(rotr90(m[:,2:end]))catch;[]end] ``` [Try it online!](https://tio.run/##bY3BCoMwEETv/Yq9NYEcXE2T6tIvCTmIVbSolTSF9uvTBCkF62Vg5@3M3J7jUOMrhI5N/GImUwm05N0bOubu3pUZS15etfPVct7UvunJ2HSFxQ2zH2cWP9tHXy8twwqVkELyI@eHPZyj0KLYYIOQQ0FFVCQJJ1CkokrScIaSyqjabhL2r4Fi2u70ggIdmYS1P@lvY93BLFrrGCb6XQwf "Julia 1.0 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 89 bytes ``` f=a=>a>[]?[...a.map(x=>x[0]),...f(a[0].map((_,i)=>a.map(y=>y[i]).reverse()).slice(1))]:[] ``` [Try it online!](https://tio.run/##hZDdaoQwEIXvfYpcJnAanBj/umgfJIQSbCwudl10WXaf3kaLLNKyvZtvJmfOmRzd1U3N2J0vL6fhw89zW7mqdrWxb0ZK6eSXO/NbVd9MbAVCp@UulGubv6MT4fEK96q@m84KOfqrHyfPhZBT3zWekxD21dj50Aynaei97IdP3nITMWYITIElYBosBcvAcotlUICVYBSDCKRACUj/TCgFZaAcVIBKqBiKbGSFiP4wWC0UklUaIAlAG2ikyDbIAugNchQoNygD5E8dntsztW0Kp/4fFRnyh0BjF3mBX7F30cOXaezy0yJ5HDF/Aw "JavaScript (Node.js) – Try It Online") Takes the first column, transpose the remaining one then reverse each row (= rotate the matrix 90 degrees CW), and then repeat until the array has no more entries. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~24~~ 22 bytes ``` {×≢⍵:⍵[;1],∇⍉⊖0 1↓⍵⋄⍬} ``` [Try it online!](https://tio.run/##lY0rDsJAFEV9V/FczSXpm34BVVOBAIFsRjQhwTQBSwiOFAoZAiGAR@OAFbCTt5FhFB5xzbk5OdW87kwWVT2bWrv83KS9i3n33Mo@a8h2I6aV3TUglubssOzXYh4rawtpjn8InhwuzigookjMS8yTEy93RJqTuwbj0ZD8smSQAoWgCBSDElCqUWagLogDMIMVOARHDnMMTsApOAN3oQIo1tr/pfIv "APL (Dyalog Unicode) – Try It Online") # How? ``` {×≢⍵:⍵[;1],∇⍉⊖0 1↓⍵⋄⍬} { } - a function ×≢⍵: - if non-empty: ⍵[;1] - the left column ,∇⍉⊖0 1↓⍵ - repeat this function without the left column, rotated counter clockwise ⋄⍬ - otherwise, return an empty vector ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~11~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔRøćRˆ}¯˜þ ``` -2 bytes thanks to *@Emigna*. [Try it online](https://tio.run/##yy9OTMpM/f//3JSgwzuOtAedbqs9tP70nMP7/v@PjjbUMdIx1jGJ1Yk21THTMdexALIsdQwNdAwNdQyNgBxDYx1DEx1DUx1Ds9hYAA) or [verify all test cases](https://tio.run/##TY6tDsJAEIRfpake0b3@XTFoFEnt5QQkCAyQUEgQWHgBJO@AIQSFaHFNeKVj7@jRqtnNzjc76@1svlyYfThZbXbVKAjHB4TTXeUX87mUzfN9LtvTsb611@ZlUD9Q341SiiAQI9FQKTLkkDwVoAhEIMELxaAElIIyrREEfwQOYIdED8DZLWYBUA6SoAIigqAhz5aYlVhdEmvGalEugcLVkJzfMT3LF8sNu/x6CO7kM60Oc30290zgH5D1dF/0Fw). **Explanation:** ``` Δ # Loop until the stack no longer changes: R # Reverse the order of the rows # i.e. [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] # → [[13,14,15,16],[9,10,11,12],[5,6,7,8],[1,2,3,4]] ø # Zip, swapping rows and column # → [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]] ć # Head extracted # → [[14,10,6,2],[15,11,7,3],[16,12,8,4]] and [13,9,5,1] R # Reverse this row # → [1,5,9,13] ˆ # Pop and push it to the global array } # After the loop: ¯ # Push the global array # i.e. [[1,5,9,13],[14,15,16],[12,8,4],[3,2],[6,10],[11],[7],"",""] ˜ # Flatten it # → [1,5,9,13,14,15,16,12,8,4,3,2,6,10,11,7,"",""] þ # Remove all empty string by only leaving all digits # → ["1","5","9","13","14","15","16","12","8","4","3","2","6","10","11","7"] # (and output it implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ZḊUƊƬḢ€€Ẏ ``` [Try it online!](https://tio.run/##y0rNyan8/z/q4Y6u0GNdx9Y83LHoUdMaIHq4q@/////RXApAEG2oY6RjrGOmYx6rAxEw0jEBChjpGMIEQBwTHVMdM5iAGYgDxCYwAUMDoAJzHQsdS7gISIslUMQ8lisWAA "Jelly – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` ≔⮌EA⮌ιθWθ«≔E§θ⁰⮌Eθ§μλθI⊟θ ``` [Try it online!](https://tio.run/##TYxNC4JAGITP7a94j7swga9aKZ6kk4dAuooHqSUF8zsLot@@KWV0nHnmmVOedac6K40J@764VPKoR931Wh6yRkZVcxukAi1lodSUWhWIe16UmmSr6ClWX3VWwiGqzvohW5D1J85oqhZ6BZXq97WKu6Ia5D7rBxnX03AigXgZkySCKGGQDXJALmgD2oJ2KWbggXwQW2AG22AH7H4Ib8Bb8A7sgX3YFmxORZqa9Vi@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⮌EA⮌ιθ ``` Rotate the input by 180°. This is for two reasons: a) the last row is the easiest to remove, and b) it's easier to loop if the row is removed at the end of the loop. (I did try reflecting and outputting clockwise but that took an extra byte.) ``` Wθ« ``` Repeat until the array is empty. ``` ≔E§θ⁰⮌Eθ§μλθ ``` Rotate the array by 90°. ``` I⊟θ ``` Remove the last row of the array and print the element as strings on separate lines. [Answer] # [Ruby](https://www.ruby-lang.org/), 65 bytes ``` ->a{x,*a=a.transpose;(w,*a=a.transpose.reverse;x+=w)while a[0];x} ``` [Try it online!](https://tio.run/##XclLCsIwFAXQrXTo51py0z8lbiRk8IQUBdGSqomIa48dOz0nPE/vPJl8OMonYSdGykeQ2zLfFz9u4p@Uwb98WCftTdzG8@XqC7HKjemb52Ky1hIaFWo0aNE52B4DqECCGqzAekU2YAt2YA8O0Aqazrn8Aw "Ruby – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 266 bytes Yeah.. PowerShell isn't the best for handling matrices. But, the algorithm is basically the same as the above.. Each row is represented as a comma-separated string, and we basically do a rotation and transposition for each layer. I can probably shave more off, but... [I *am* already in my pajamas...](http://e.lvme.me/5fpiarl.jpg) ``` Filter F{$a=$_-replace"],|]|\s",''-split'\['|?{$_-ne''};$b=@();while($a-ne $null){$N=($a[0]-split',').Count-1;$a=0..$N|%{$i=$_;($a|%{($_-split',')[$i]})-join','};if($d){[array]::Reverse($a)}if($N-gt0){$b+=$a[0];$a=$a[1..$N]}else{$b+=$a;$a=$null};$d=$true}$b-join','} ``` [Try it online!](https://tio.run/##lVPRiptAFH02XzHILCq9Bu@YaFyRLhRCn/JQCn1wpZjd6a6LaKqmS1G/PXtHXTeEUsiL3JlzPefcc5lD@Sqr@lnm@Wl7LB6arCzYd1k3NWsXGi9ZxPR4oWmMxQhMAHOBrYCtgXnA/ARGaAMsAIYOIAIKQBdw9Y7hGtAD9AE3gAEIBwQmBCV6SAKpEkAg6B9txAI@eLCGFbggIIAzCX2h/aiyRtpfy7phpsnLbmvZ8jfjqUXM5@Y18i7AHRxpsWLCqV4RtzfVg85U@@QomOqAan90rAxHZNclQx5ZGyD6qhMOFgWRrGFznbkP8iGNKydjYjJK27mkUqOCuD4qNd3MOoaPZ/FdxnYeHa1Ibe0jP1T9FyG@m1NCaqdzyxym2vsoJYb9K0YVrRjD//9I/Wmb5Y2s2LalhfGfdiUPefog9QS6pLuvdTAMuz7kWWPcx0b3uaWWQhpGH/J9dGda4etzlkuTp3TLeHHMc6vlu4guYieZfgTDWn4pj0VjY0giznLJd91NyzPSC6mTapNo5@aYZ0lv2S9lVtCxD7NfJn@02jitqvRvcnv7Tf6hh6hErV5hO/upcUh2/ykaZJUIFah0kl7mtZywAVAeyf1jxJvqKHu@n4VOw2s@vQE "PowerShell – Try It Online") ]
[Question] [ **This question already has answers here**: [Largest and smallest values from concatenated integers](/questions/49854/largest-and-smallest-values-from-concatenated-integers) (17 answers) Closed 6 years ago. Write a function or program that given a **list** of **non negative** integers, arranges them such that they form the largest possible number. **INPUT** ``` [50, 2, 1, 9] ``` **OUTPUT** ``` 95021 ``` --- **INPUT** ``` 0 ``` **OUTPUT** ``` 0 ``` --- **INPUT** (Interesting one) ``` [7, 76] ``` **OUTPUT** ``` 776 ``` **RULES** * [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. * Depending on your language you can use `int(32)` / `int(64)` or any other numeric datatype. *(Please append the chosen type to your answer)* * take a **list** as Input * you choose the behavior on empty input **GL** [Answer] # [Python 2](https://docs.python.org/2/), ~~85~~ ~~80~~ ~~77~~ ~~72~~ 70 bytes ``` lambda l:''.join(sorted(map(str,l),key=lambda i:i+i[-1]*max(l))[::-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHHSl1dLys/M0@jOL@oJDVFIzexQKO4pEgnR1MnO7XSFqos0ypTOzNa1zBWKzexQiNHUzPaygrI0/xfUJSZV6KQphFtaqBjpGOpAxTjgouZ65ibAdUAAA "Python 2 – Try It Online") Sorts the numbers lexicographically, but each number is padded with its last digit. This means that 'shorter' numbers (string-wise) can be larger than 'longer' numbers: Example: Input: `[76, 7]` Each number gets padded with its last digit: `['76666..','7777..']` Sorted (descending): `['7777..',76666..']`, which gives `[7, 76]` Joining the result gives: `776` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` œJà ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6GSvwwv@/48211EwN4sFAA "05AB1E – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Œ!VṀ ``` ## Explanation ``` Input: list [1, 4, 5, 21, 4] Œ! Generate all permutations of input list V Eval those lists as Jelly code: every sublist is joined and interpreted as int Ṁ Pick the highest ``` [Try it online!](https://tio.run/##y0rNyan8///oJMWwhzsb/v//H21qoKNgpKNgqKNgGQsA "Jelly – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` pᶠcᵐ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@DhtgXJD7dOeNTT@f9/tKmBjpGOoY5l7P8oAA "Brachylog – Try It Online") ### Explanation ``` pᶠ Find all permutations of the list cᵐ Concatenate each permutation into an integer ⌉ Take the biggest one ``` [Answer] ## JavaScript (ES6), 40 bytes ``` a=>a.sort((a,b)=>``+b+a-(``+a+b)).join`` ``` Sorts the numbers by their ordering when concatenated, and joins the result. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 4 bytes ``` ψJì↑ ``` **Explanation:** ``` ψ All possible permutations J join sublists ì convert to int ↑ get maximum ``` [Try it online!](https://tio.run/##y8/INfr//3yH1@E1j9om/v8fbWqgo2Cko2Coo2AZ@x8A "Ohm v2 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` ñ!îL w q ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=8SHuTCB3IHE=&input=WzUwLCAyLCAxLCA5LCA3LCA3NiwgNzcsIDc4XQ==) Look ma, no permutation built-in! ### Explanation ``` ñ Sort the input as if each item !îL were repeated to 100 chars. (!îL -> LîX for each item X, L = 100) w Reverse. q Join into a single string. Implicit: output result of last expression ``` Repeating each item to length 100 works because while `'7' < '76'`, `'7777...' > '7676...'`, and no number could possibly be length 100 when converted to a string. [Answer] # [Actually](https://github.com/Mego/Seriously), 11 bytes ``` ;l@╨⌠εj≈⌡MM ``` [Try it online!](https://tio.run/##S0wuKU3Myan8/986x@HR1BWPehac25r1qLPjUc9CX9///6NNDXQUjHQUDHUULGMB "Actually – Try It Online") Explanation: ``` ;l@╨⌠εj≈⌡MM ;l@╨ all permutations of input ⌠εj≈⌡M concatenate each permutation M maximum ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 9 bytes ``` eSmsjkd.p ``` **[Try it here!](https://pyth.herokuapp.com/?code=eSmsjkd.p&input=%5B50%2C+2%2C+1%2C+9%5D&debug=0)** **or:** ``` eSsMjLk.p jkeojkN.p ``` --- * `.p` - Generate all the permutations. * `msjkd` - Map on the above with the following function that takes `d` as a variable: + `jkd` - Concatenate the integers into a single string. + `s` - Convert to integer. * `S` - Sort the input. * `e` - Get the last element. [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 65 bytes ``` @(x)max(cellfun(@(s)str2num(s(s>32)),cellstr(num2str(perms(x))))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzN7FCIzk1JyetNE/DQaNYs7ikyCivNFejWKPYzthIU1MHJAkU1AAKGoHogtSi3GKgRhD4n6YRbWqgYKRgqGAZq8kF5BlAKHMFc7NYzf8A "Octave – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~113~~ ~~220~~ 87 bytes ``` l->l.stream().map(i->""+i).sorted((i,j)->(j+i).compareTo(i+j)).reduce((i,j)->i+j).get() ``` [Try it online!](https://tio.run/##ZZBNS8NAEIbv@RVDT7u2WVTwIK2BXhTBW3sR8TAma524X@xOKkX62@NGo1TyHp95B56ZFvdY@qBd27z3ZIOPDG1mqmMy6mxZTNhr52om74ZhUdQGU4I1fBaQkxiZargdK6sHSry6d6x3OlYL2HAkt6uA1vYuamQdt2/oHn0HN9CbsjIqceZWSGUxCCqr2WxOUqVsoBshaNHKshLtwGpvA0a99YLmrZQq6qar9W9nYGqnWcg@Ww5qoXsxWW003HtqwCI58eP09AwoxyOG/BMHk/2c/oB1jHj4HlVCLv/KRmHTiKvzCbqckIsJuT4hm0NibZXvWIVsxWLyKIUhmIMwctw6Fsf@Cw "Java (OpenJDK 8) – Try It Online") [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 18 bytes **Solution:** ``` ,/x@>(|/#:'x)#'x:$ ``` [Try it online!](https://tio.run/##y9bNz/7/X0e/wsFOo0Zf2Uq9QlNZvcJKxdRAwUjBUMHy/38A "K (oK) – Try It Online") **Examples:** ``` > ,/x@>(|/#:'x)#'x:$50 2 1 9 "95021" > ,/x@>(|/#:'x)#'x:$7 76 "776" ``` **Explanation:** ``` ,/x@>(|/#:'x)#'x:$ / the solution $ / convert to string, 50 2 1 9 -> "50","2","1","9" x: / store in x ( ) / do this together #:'x / count (#:) each (') x, "50","2","1","9" -> 2 1 1 1 |/ / max over, 2 1 1 1 -> 2, #' / take each parallel, 2#'"50","2","1","9" -> "50","22","11","99" > / return sorted indices (descending), "50","22","11","99" -> 3 0 1 2 x@ / apply these indices to x, "50","2","1","9" -> "9","50","2","1" ,/ / flatten, "9","50","2","1" -> "95021" ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~13~~ 7 bytes ``` á m¬ñ Ì ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.5&code=4SBtrPEgzA==&input=WzcsNzZd) -6 thanks to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). [Answer] ## Ruby, ~~48~~ ~~41~~ 36 bytes Similar implementation to others, generates all permutations and takes the max. Shame that "permutation" needs to be spelled out in full . . . ``` f=->l{l.permutation.map(&:join).max} ``` Calling it: ``` f.call([50, 2, 1, 9]) => "95021" f.call([7, 76]) => "776" ``` Or ``` f.([50, 2, 1, 9]) => "95021" ``` [Answer] # C#, 113 Bytes It's not very short, but hey, it's still C# we're talking about. ``` int F(List<int>n)=>n.Max(i=>{var l=new List<int>(n);l.Remove(i);return int.Parse(""+i+(l.Count>0?""+F(l):""));}); ``` Formatted: ``` int F (List<int>n) => n.Max (i => { var l = new List<int> (n); l.Remove (i); return int.Parse ("" + i + (l.Count > 0 ? "" + F (l) : "")); }); ``` It simply recursively tries all possible permutations of the input and returns the largest one. It uses a 32 Bit integer as input and output numerical datatype. If anybody has an idea on how to improve this solution, feel free to comment. [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 bytes ``` f$¦⌉ ``` [Try it online!](https://tio.run/##S0/MTPz/P03l0LJHPZ3/Ux@1TfwfbWqgYKRgqGAZCwA "Gaia – Try It Online") [Answer] # Perl 5, 27 bytes ``` join"",sort{"$b$a"cmp$a.$b} ``` [TIO](https://tio.run/##K0gtyjH9X1CUmVfyPys/M09JSac4v6ikWkklSSVRKTm3QCVRTyWp9r@lpaWOpY6hgY65jrkZkDb4DwA) [Answer] # Groovy, 41 bytes ``` {it.permutations().max{it.join()}.join()} ``` --- If commands were 3 bytes in groovy instead of a full word I halve the size lol: ``` {it.p().max{it.j()}.j()} ``` [Answer] # J, ~~29~~ 25 bytes ~~[:>./-.&' '&.":"1@(A.~i.@!@#)~~ ``` [:>./,&.":/"1@(A.~i.@!@#) ``` * ~~`-.&' '&.":"1` smashes a list of numbers together to produce a single number. `-.` is "set minus" and `":` is format, so `":` turns, eg, the list `7 76` into the single string (aka list of chars) into `'7 76'`, and `-.&' '` removes the spaces from that string. Since `":` was applied using Under `&.` the inverse is automatically applied at the end, turning the single string-now-without-spaces back into a number.~~ * `,&.":/"1` smashes a list of numbers together to produce a single number. * `(A.~i.@!@#)` all permutations of the list * `>./` maximum of [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/6Ot7PT0ddT0lKz0lQwdNBz16jL1HBQdlDX/a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QpmBooGCkYKljC@OYK5mb/AQ "J – Try It Online") [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~65~~ 62 bytes ``` @(n)max(str2num(sprintf([repmat('%d',size(n)) 10],perms(n)'))) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9Wmmerp6f330EjTzM3sUKjuKTIKK80V6O4oCgzryRNI7ootSA3sURDXTVFXac4syoVqE5TwdAgVqcgtSi3GMhT19TUBBmjEW1qoKNgpKNgqKNgGav5HwA "Octave – Try It Online") Anonymous function which takes an array as an input, and spits out an integer representing the largest number that can be made. Permutations are found, then the result is formatted to a 2D array where each line contains only the digits from the values in a given permutation in order. This is done by `sprintf` with enough `%d` markers to absorb the whole permutation. The result is then converted back to an array of integers where each line becomes its own value. The maximum from this array is returned. --- * Save 3 bytes using `size(n)` instead of `1,numel(n)` in the `repmat()` call Note: This was developed completely independently from the other Octave answer. [Answer] # bash, 96 bytes ``` f(){ local l g p=$1;shift&&{ for i;{ (($i$p>$p$i))&&l+=\ $i||g+=\ $i;};echo $(f $l)$p$(f $g);};} ``` [Try It Online](https://tio.run/##JcpNCoMwFATgfU4xi0dI6MYEn5ug9CDdWDE/EFCqu@jZ05TOYvgY5j0fsR7rCQtrYDswM7gHD9UrXZC3Zc7ICNhHMu6IyZ9SFvjtg@QKlKJE@0Q7Ja2lzI/xBUrXFf5wt1uXuIGUB2Xdbj8E3fa7Nj2rEcYKZsGdaNXS94KHZtN9AQ) [Answer] # [Python 2](https://docs.python.org/2/), ~~90~~ ~~86~~ 80 bytes ``` lambda l:max("".join(map(str,x))for x in permutations(l)) from itertools import* ``` [Try it online!](https://tio.run/##PcjBCsIwDADQ@74i7NRIER3ocOCX6A4VV4w0TUkj1K@vN9/xla@9JE89Xu89BX48A6SFQ3PjuH8LZcehuGrqG2IUhQaUoWzKHwtGkqtLiENUYSDb1ERSBeIiartelLJBdLfTwU/@4o8rDv@b/Xxesf8A "Python 2 – Try It Online") *-4 bytes thanks to FlipTack* *-6 bytes thanks to i cri everytim* I believe this can be golfed a ton, but I don't really know how. Stupid type conversions added a ton of bytes. [Answer] # Mathematica, 57 bytes ``` Max[FromDigits[Join@@IntegerDigits/@#]&/@Permutations@#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zexItqtKD/XJTM9s6Q42is/M8/BwTOvJDU9tQgipu@gHKum7xCQWpRbWgLUl59XDBL5H1CUmVei4JAeXW1qoGOkY6hjWRvLhRA01zE3q439DwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Matlab, 135 53 bytes New Solution: ``` a=input('') b=sprintf('%d', a) c=sort(b,'descend') ``` Explanation: It takes a user matrix input, then separates it into digits, and finally orders those digits from greatest to least. Old Solution: ``` a=input(''); b=sprintf('%d',a) - '0'; c=[];b=sort(b,'descend'); for i=1:size(b,2) c(i)=b(i); end for y=1:size(c,2) e(y)=num2str(c(y)) end ``` Explanation: First it takes a user input, then separates all of the numbers into individual digits. The %d in sprintf essentially converts the numbers in the string, which is necessary for sorting into each digit (afaik). I tried simply doing num2str(a) but that leaves a space between each number. From there, it is just a matter of sorting and arranging the numbers with proper formatting. The actual code has a lower byte count because it has no semi-colons and everything on one line. ]
[Question] [ Let's say I've got some ASCII art: ``` ___ ,"---". : ; `-.-' | | | | | | _.-\_/-._ _ / | | \ _ / / `---' \ \ / `-----------' \ /,-""-. ,-""-.\ ( i-..-i i-..-i ) |`| |-------| |'| \ `-..-' ,=. `-..-'/ `--------|=|-------' | | \ \ ) ) hjw / / ( ( ``` ([Source](https://www.asciiart.eu/computers/joysticks)) But I want to focus on the cable of this joystick, because I actually want a picture of a garden path, leading up to a door. ``` ,=. -|=|- | | \ \ ) ) / / ( ( ``` I could copy out line after line, I could use a text editor with block selection mode, or... I could write some code! So, my code needs five arguments: * A piece of ASCII art, a newline separated string. * The X axis of the top-left corner (1-indexed, from left hand column, positive integer) * The Y axis of the top-left corner (1-indexed, from top row, positive integer) * Width of the resultant image (positive integer) * Height of the resultant image (positive integer) ## Test Cases ASCII image: ``` ___ ,"---". : ; `-.-' | | | | | | _.-\_/-._ _ / | | \ _ / / `---' \ \ / `-----------' \ /,-""-. ,-""-.\ ( i-..-i i-..-i ) |`| |-------| |'| \ `-..-' ,=. `-..-'/ `--------|=|-------' | | \ \ ) ) hjw / / ( ( ``` ### Garden path * X: 10 * Y: 15 * Width: 5 * Height: 7 Result: ``` ,=. -|=|- | | \ \ ) ) / / ( ( ``` ### DB icon * X: 3 * Y: 12 * Width: 6 * Height: 4 Output: ``` ,-""-. i-..-i | | `-..-' ``` ### Alien Elder * X: 9 * Y: 1 * Width: 7 * Height: 10 ``` ___ ,"---". : ; `-.-' | | | | | | .-\_/-. | | `---' ``` ### Signature * X: 16 * Y: 19 * Width: 3 * Height: 1 ``` hjw ``` ## Rules * Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * Either a full program or a function are acceptable. * [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] # [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` @ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjIw,i=NyUwQTUlMEExNSUwQTEwJTBBJTYwJTYwJTYwJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwX19fJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTJDJTIyLS0tJTIyLiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUzQSUyMCUyMCUyMCUyMCUyMCUzQiUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU2MC0uLSUyNyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3QyUyMCU3QyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3QyUyMCU3QyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCU3QyUyMCU3QyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMF8uLSU1Q18vLS5fJTBBJTIwJTIwJTIwJTIwXyUyMC8lMjAlN0MlMjAlMjAlMjAlMjAlMjAlN0MlMjAlNUMlMjBfJTBBJTIwJTIwJTIwLyUyMC8lMjAlMjAlMjAlNjAtLS0lMjclMjAlMjAlMjAlNUMlMjAlNUMlMEElMjAlMjAvJTIwJTIwJTYwLS0tLS0tLS0tLS0lMjclMjAlMjAlNUMlMEElMjAvJTJDLSUyMiUyMi0uJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTJDLSUyMiUyMi0uJTVDJTBBJTI4JTIwaS0uLi1pJTIwJTIwJTIwJTIwJTIwJTIwJTIwaS0uLi1pJTIwJTI5JTBBJTdDJTYwJTdDJTIwJTIwJTIwJTIwJTdDLS0tLS0tLSU3QyUyMCUyMCUyMCUyMCU3QyUyNyU3QyUwQSU1QyUyMCU2MC0uLi0lMjclMjAlMjAlMkMlM0QuJTIwJTIwJTYwLS4uLSUyNy8lMEElMjAlNjAtLS0tLS0tLSU3QyUzRCU3Qy0tLS0tLS0lMjclMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlN0MlMjAlN0MlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlNUMlMjAlNUMlMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjklMjAlMjklMjBoanclMEElMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAvJTIwLyUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyOCUyMCUyOCUwQSU2MCU2MCU2MA__,v=8) It takes height, width, Y, X, and ASCII art as inputs, in that order. Though almost everything about the ASCII art objects in Canvas is 0-indexed, `@` is 1-indexed by some reason. ¯\\_(ツ)\_/¯ [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ 62 bytes ``` lambda I,x,y,w,h:[l[x-1:][:w]for l in I.split('\n')[y-1:][:h]] ``` [Try it online!](https://tio.run/##jZHNboMwDMfveQorl4TKDqTrh8rEqac@AyDKtDGYKK26Sm0l3p0l4WuXSbMl4t/fYMf48ryV52bZFVHS1fnp7T2HAz7wiXcsw7iOH6TDNA7vaXG@Qg1VAwf1famrmxRJI7z42efLNO2qU/75ARFwzmGyLMvYGCMnIq4mDt3zdWI4kiIxI7TQ/ocyRUnmk@o7ZeCbZP9KAk7zjdvqRMKciXFmRaeMJsDJPhLnpMYbOzC6hIqUomrQB/BYe3St2qFID6JliZ1F2aIYKRjAZ3PHNhq/@Xvg4aKTecbLr/svyQw2kwRpfj1jdlN7uympA9RrXOPWQ/mCeokbXJlwhxq3qAMT6g3qHZqcFzKYVlxIt0tc7K0Ml2vV3KBmrI@GQ5BYrIJR634A "Python 2 – Try It Online") --- If `X` and `Y` can be `0`-indexed: # [Python 2](https://docs.python.org/2/), 56 bytes ``` lambda I,x,y,w,h:[l[x:x+w]for l in I.split('\n')[y:y+h]] ``` [Try it online!](https://tio.run/##jZHNbsIwDMfveQorl6Rgp4TBYJ164sQzUBSYNtZOpSCG1Fbqu3dJ@sEuk2ZLif@/tHYcX@t7einm7SlO2vx4fns/whYrrLHENNrluyqqpuX@dLlBDlkBW/V9zbO7FEkhgl0d1dN0v2@z8/HzA2LgnMNoxhg2xMiJiKtRR359HTUcSJF4SGig@Y8yihITkuoqGQjtYfdJAp6F1l12ImH3xDpz0JPBBHgcInFOarixF5ZLyEgpynrei4A1B1@q6ZN0QjQscb0olxRjBb0I2aNiEw///N1wf9HRAuvpV/kL2cYeSoK0T8@YG9PGjUm@oF7gElcByjlqjc@4sOEaZ7hCPbOhXqJe4xPqIGIwjvck/ShxsnEYrresuEPOWBf1myAxWcwG1v4A "Python 2 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes ``` δJθηTζε ``` [Try it online!](https://tio.run/##jZDJCgIxDIbvfYrQy3SgSfEgooMv4MmDNytVVJgR18EFpO9eM53Ni2BSWr4/bZZu8025vWyOIczL4nxXuzQTs8fpuriom4acaVEWJ/XWsE@zEJZjDYOhBl4jDaWUUkBnzrmOtERESR1P4p71t9dImHw99uD/IUdonUGqKzkwHKyvWIiaYa@yIyZ8WrCi0qLQGgdYNRqlRGr7jWCFggKJsGjkBlLh17GOb1LUkHhhq0GoSqmnBA0Y0dfz0/bN72nrLjtL2fPD60vioXpSoAR//Crg8/gB "Charcoal – Try It Online") Link is to verbose version of code. Takes 0-indexed coordintaes. Explanation: ``` δ ``` Print the ASCII art. ``` Jθη ``` Jump to the top left corner of the desired rectangle. ``` Tζε ``` Trim the canvas to the desired size. [Answer] # [Pip](https://github.com/dloscutoff/pip) `-n`, 21 bytes ``` _@>--b@<dM(a^n--c+,e) ``` [Try it online!](https://tio.run/##jY87DsIwDIb3nMLq0lb0d@iAkICiXoAbRKS8JMpQdWPJ3U2a9MGChC0l@X47fvRtL2LrI3CtD/dTdjl3wG1VPHIRQSc0m7VWTe8iAZDwzLtw7memBox0QXLk/iHLMFaDYydL2gdjiqGgae9DdSD1tyGjBi0Ik/mAV3WBJAFP8wYwKqMWzGhHeYRcuSb0cWOJCKlTZliEh5JFxTSCVks/V01/fm8bp5wt9/58vb@kuNQiZN6JpFxLuZGNbD8 "Pip – Try It Online") Or, if 0-indexing is allowed... ## Pip `-n`, **17 bytes**: ``` _@>b@<dM(a^nc+,e) ``` [Try it online!](https://tio.run/##jY/JCsIwEIbveYqhl7bYmSAo4lLpC/gGwdQNrIfSm5e8@5i9XgRnIMn3z2SWaZiYdXe8dof7qbqcx9uiedTMjCNDNq21SO@mQMSCMu/8uc8MPRKWM4IB8w9pQqUlUuikQdpgSFHgNWndVUcs7a1ACad5IZkNWFU2WBRIaV4PSlQwIBEOUY5QC9P7PiaWCFAaodwi5Eo2LUEEKeZ@pk1/fm8bpsxWW3@@3l9SWGoWKusAvOXlite8@QA "Pip – Try It Online") ### Explanation Takes all five arguments as command-line args. ``` a-e are the 5 cmdline args; n is newline a^n Split a on newlines ,e Range(e) c+ Add c to each element ( ) Use the resulting range(c,c+e) to slice into the list of lines M To each line, map this function: _ The line @>b Slice, keeping indices b and greater @<d Slice, keeping indices less than d Print, joining on newlines (-n flag) ``` --- The above solutions also assume the input is a perfect rectangle--i.e., the lines are all the same length. Otherwise, 2 extra bytes are needed (use `-l` instead of `-n`): ``` (Z(a^nZDsb+,d)c+,e) 0-indexed, 19 bytes (Z(a^nZDs--b+,d)--c+,e) 1-indexed, 23 bytes ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 19 bytes ``` UV¶¡εXG¦}Y£}sG¦}s£» ``` [Try it online!](https://tio.run/##jZC9CgIxDMf3PEXocndwSXU4BOVmn0BRKFQFwXNxuMGlPowIvoEubn0AX6m2vS8XwQTa/P5pk6anerur9s4tlvZpr@/Ham7vl7W9XeoQ1PZmX86NR1CAEAJ701pDF@eCiAT3PI3rrGfcEFMyIBo0/5BmUloSN500Sp9sjiiMmvQeqhMlfleoIGhR6MwnvCpzEoK4e28EBSlWxExVK7eQgdnEPqYt0UBiQIVBOJTMS8YWJAz9TNnd@T1t88reMu@H4/lL8kMNlGLqvx3GBUw@ "05AB1E – Try It Online") Or if `0-indexing is allowed`: # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` UV¶¡εX.$Y£}sF¦}s£» ``` [Try it online!](https://tio.run/##jZBLCsIwEIb3c4ohCG2hM0FQRKVbb6AoBFIFwbpx0YWb9DBS8Aa6cZcDeKWapi83gjOQ5PsnmUcu@f6QHatqvbFPe3s/tjza2bLIV/Ze5La0r6qawxSEENib1hq6cyyISHDPC78ue8aUmIIB0aD5hzST0pK4qaRRumBzRaHXpPM6O1HgdoUKas0LnbmAU2VMQhB3/XpQEGJGzJS1cgsRmNTXMW2KBgIDqh6E65RxwtiChKGeSbo3v6dtuuwtcn46X78kN9RAIYbu22E8gdkH "05AB1E – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, ~~13~~ 11 bytes ``` ·tWÉY ®tVÉX ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=t3RXyVkgrnRWyVg=&input=IiAgICAgICAgICBfX18KICAgICAgICAsJy0tLScuCiAgICAgICAgOiAgICAgOwogICAgICAgICBgLS4tJwogICAgICAgICAgfCB8CiAgICAgICAgICB8IHwKICAgICAgICAgIHwgfAogICAgICAgXy4tXF8vLS5fCiAgICBfIC8gfCAgICAgfCBcIF8KICAgLyAvICAgYC0tLScgICBcIFwKICAvICBgLS0tLS0tLS0tLS0nICBcCiAvLC0nJy0uICAgICAgICwtJyctLlwKKCBpLS4uLWkgICAgICAgaS0uLi1pICkKfGB8ICAgIHwtLS0tLS0tfCAgICB8J3wKXCBgLS4uLScgICw9LiAgYC0uLi0nLwogYC0tLS0tLS0tfD18LS0tLS0tLScKICAgICAgICAgIHwgfAogICAgICAgICAgXCBcCiAgICAgICAgICAgKSApIGhqdwogICAgICAgICAgLyAvCiAgICAgICAgICggKCIKMTAKMTUKNQo3Ci1S) 2 bytes saved thanks to [Kamil Drakari](https://codegolf.stackexchange.com/users/71434/kamil-drakari) 9 bytes if not for the unnecessary requirement that solutions use 1-based indexing. ``` ·tWY ®tVX ``` --- ## Explanation ``` :Implicit input of string U and integers V=X, W=Y, X=Width & Y=Height · :Split U on newlines t :Slice WÉ : From 0-based index W-1 Y : To length Y ® :Map t : Substring VÉ : From 0-based index V-1 X : To length X :Implicitly join with newlines and output ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~70~~ 69 bytes -1 Thanks @Shaggy for the `splice()` idea. ``` (a,x,y,w,h)=>a.split` `.map(q=>q.substr(x-1,w)).splice(--y,h).join` ` ``` [Try it online!](https://tio.run/##jY9hb4IwEIa/91c0fKFN7o51mxpH8Lv/oQllDifECQqbmvDfWSmCJrpkd03T5727vm2e/CTV6pCVNe6Kj7RdR61I4ARnOMJGRouEqnKb1YYZ@kpKsY8We6q@36v6IE6o4Cila1ilAvFsJygvsp3tbsNlZPgYcRyz4QweIno08pvbw5G5NkjoX5k3vPkPxYRaxwFS7xXzwFb7Hq25EwObzgDR7w7aLtbJvTaEz50eAHoe0vBuB1YXPEMizC76BSRrtHF@zeWWHvyGdTam67L3QkR8oIDd2DbRMPf314f3jiFtbvLjjWR/eCXBhWHhqthVxTalbfEp1mIJ6gnUBCYwk/K@@ALqGabw@qg2BwUzO/6opqag5t20lO0v "JavaScript (Node.js) – Try It Online") The ASCII art given is annoying tbh [Answer] # [J](http://jsoftware.com/), 45 bytes ``` f=:4 :0 'a b c d'=.x-#:10 y{~<(a+i.b);c+i.d ) ``` [Try it online!](https://tio.run/##jY/bTsMwDIbv@xS/mgu3rHZb2EBqqcSDBGVdx7TuZpeACLx6SZMeEBIStpT4@235cBmGU1NtURURtTigw5EaeWNVlUX0/vH1mLSbXg5p3bnvGKVD2whhMWOMmuMsZuZYFq78Wy@MPQsTrQwL@x8ywtrkLGGUQe6SoUTDa7nzsT279i7Q0GoUvTLbmHFynnEcs8wre9AqQc8i3E/yBKmyez/JTj0CEFmlx2PEN80awUy5Wmfaxi6j/7wyrLpY6vx8ef0hudNWSpBQ9NKdryh3eEBZYIcTPuXpuZaSFGVtyNJNsLn4Flvc4f5X7fAN "J – Try It Online") Notes: [J](http://jsoftware.com/) accepts up to 2 arguments, left and right. The right argument is the ASCII art string, the left one - a list of U H X W values I simulate the newline and the function call has a code to convert the string to an array. [Answer] # [V](https://github.com/DJMcMayhem/V), 16 bytes ``` ÀGÀ|<C-v>@cl@djyHVGp ``` [Try it online!](https://tio.run/##pZC/CsIwEMb3PoDzkaUt9BI7qKAUutUncAqkoIMtDk6KkKHv1gc70/xpxSyC90HI98txd7kH0Tg046BX9flWX/rX8dTciWAOpdRiknApGCIyHvG9PQ8RhxY5pnEdAG30N1ccpRLI1SdXIHyuBgkqcGE0zYN2HmlkuXAsRDo9GS4KZAzDR52RkGTQIefYee5NnujWdtS@ijOpTuS0ALuBouLgjTD155660kvrH/bgBo855EbX/vnN3bej/MxoCSq3VK5pQ7s3 "V – Try It Online") Input is expected to be padded with spaces to be a perfect rectangle. Also, the 'Y' input comes before the 'X'. Hexdump: ``` 00000000: c047 c07c 1640 636c 4064 6a79 4856 4770 .G.|.@cl@djyHVGp ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 118 109 bytes The input can contain jagged lines: newlines are printed if they exist in the y-range. Thanks to ceilingcat for the suggestion. ``` f(s,x,y,w,h,a,b,c)char*s;{for(b=1,a=0;*s;a=c?!b++:a,s++)((c=*s==10)|++a>=x&a-x<w)&b>=y&b-y<h-c&&putchar(*s);} ``` [Try it online!](https://tio.run/##jVNtb5swEP7Or7gyLTXBJsle21Jn2rR2mlRtH6Z9KlUKBgIThQjDkijw27Mzb0kmdZoJDvfcc3ePfbZgSyH2L@JUJKUfwLUs/Dizorl2AiWx9zeWx@kSsX1IJN3QLV3TiLrUo8IQkZuPpb0Ls5x4fEZdPrXRdrn4cOaZ5pVLpWkahAg@lpzPpkZlmu6cb0Yu21yvjZE359uRx7bXEROj0aosVEIyloZd79UnjJdB8VQmRUxuv97dwDg0YKcBtD5JQVDwyvD@YvrAd9PaRlecFgoSWZkWFFB894VYEqT8YmpryFKCJf/28@7uwOF9GC4CUHKItQUJDeOM33y/tdvKWCAkA5G3WXsXgOR54CZJJnCrhsRmx7J7UpGnYrUl0jyR12s85rXxXZkeP9LZILXWofe9xzQfuFBO5ToS3At9VmbLatP@S@aBV6vtzIOizFOQtoYmsktRgMiy3JdH7fIDKfoObShsKawpRBiCHVHYkxun5HcW@yc95sMJUOe13ZzTCm6ei3vsfyN6p39xcz9IYeUWkU5hNsX3LQX8va9pR/n8CWKRpeh@jd5XFN5ReDN4PyYxxgeJH@TIuEQGxqpMA@NHvExdXHGgCmDs7LLN1BPac8Vmx6/qRE1hLIbzJ7hSboNg82ZrQOBdORwycdb4DcBrIYnupHrXlxXexyIk@kvppI5aRJegc6tbqqBNM2@bed3MkdEfiTAPAoK3TKv3MIzFYqH131RnjOnWYF81sz3Y8Mgsdn4woYLqf6yFxZzFhFltpQVM0NlSHGiwCT4qO2Pn@O@AoymsAfqBDkQnlOk6s3q9jeFoBGJmWSzu4M4wtOqxqVN1KVrjvNIctRBLpaTcgs6YaId6Fe9jnl9tq3IYBj7Rr/URhIs6WATIHw "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` Ỵṫ€¥ṫḣ€ḣ4ƭ/ ``` [Try it online!](https://tio.run/##jZA7CgIxEIb7nGLYJitkJgqKoHgQMRIbQcXKRoRUNh5ErNTOQrFT8B7rReIk@7IRnDy/P8k8spgulxvvs/slux3f29PjwGt23fOW5/brrP1zN/R@tJJSQmXWWlHuVYKICVXci3O/YpggoawRHLh/yBIaq5HySBY0H@ZXDERNcwveEUNmBowIWhRK4wNWtcIkQSrzjWBECnMkwnkhF9AQbhLjuMJFDtIJEwqh4FINCArQoo7nBuWb39XmWVbW4DZbrL8kLqqmFFL@dgWtJo@OAu7d8Qc "Jelly – Try It Online") Takes the ASCII-art as a Python multi-line r-string (so as to avoid problems with backslashes). [Answer] # [Haskell](https://www.haskell.org/), 61 bytes ``` (x#y)w h=unlines.map(take w.drop(x-1)).take h.drop(y-1).lines ``` [Try it online!](https://tio.run/##jY9Lb4MwEITv/hUjUilGyi51H6nSllOvvfWKRJCCCk3iRIGIROK/08U80kNTdY2A@XY8a2dJsU43m6bRp8nZr5CFR7vJbVrwNtnrMlmnqHh12O31iYzvsyNZR85C2JmbbZJbhFjtFKRyuz@WeCV8puXbzpapLQvlOsI/ysO7xQ30xIe5hXkE5HnqNv1mwj3MHTAHHv4wLQDTxkjkVZOZwyzaPLE6U4Ox4jhWw//MIyKPR/3s3i@jxpKYpheJGvV/VMwUxQFxNylGIM3OEsGxQFabTjSVb4RItcyBoaQhNJiR5xEP53UiUho5MVPe4174ql66OXUf0YlpraL2ItxGzkJGLwJ1mVeHw57rt@1OOZYvK/uqfiC51EVp6G8 "Haskell – Try It Online") Takes arguments in order: `x`, `y`, `w`, `h`, `s`. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, 37 ``` cut -b$1-$[$1+$3-1]|tail +$2|head -$4 ``` Interestingly, GNU tail 8.28 (on Ubuntu 18.04) allows `+NUM` format, whereas GNU tail 8.29 on TIO requires 2 extra bytes for this `-n+NUM`. [Try it online!](https://tio.run/##jZLLTsMwEEX3/oorK1JStePUfaovdrBlw46gNE1TJQU1EjEChPn2MHk0LQskxpLjc8e@47Gyi4q0jCODGxzzz8Jk8bMyHwbrNdzb@ztXoIswDDsaSCKSquNlPa8uu7ek6Pqwhf0PhYqC0CfVVArhc7LZEqDWfB6VO5HL3wCBqLRaOAcnWPUHJCWp831rCISHjJSirJVb6Am7revY1qIB14qgakRVloONQgu@uNSzm/OZv7ttbtlFj0d6fL@SuKkLefAEv7wQB6@HrzJ@M6Cdo8l5dHTfGZN@sibKXkCnvjOyaRLtQc6k/BaH/BUmKQyyE6QeQk8xxVxCjqFHmGHCywU05tBDXuoZ9AKckyvsc66fxGkO@cAOcVQkcCqvpQRnDg1g/esfEfv8lJQ/ "Bash – Try It Online") I thought doing this all in `sed` might be shorter, but at 50 bytes its not: ``` sed -nr "$2,$[$2+$4-1]s/.{$[$1-1]}(.{,$3}).*/\1/p" ``` [Answer] # [K4](http://kx.com/download/), 31 bytes **Solution:** ``` {[a;x;y;w;h]a .-1+(y;x)+!:'h,w} ``` **Examples:** ``` q)ASCII:(" ___";" ,\"---\".";" : ;";" `-.-'";" | |";" | |";" | |";" _.-\\_/-._";" _ / | | \\ _";" / / `---' \\ \\";" / `-----------' \\";" /,-\"\"-. ,-\"\"-.\\";"( i-..-i i-..-i )";"|`| |-------| |'|";"\\ `-..-' ,=. `-..-'/";" `--------|=|-------'";" | |";" \\ \\";" ) ) hjw";" / /";" ( (") q)k){[a;x;y;w;h]a .-1+(y;x)+!:'h,w}[ASCII;10;15;5;7] " ,=. " "-|=|-" " | | " " \\ \\ " " ) )" " / / " "( ( " q)k){[a;x;y;w;h].[a;-1+(y;x)+!:'h,w]}[ASCII;3;12;6;4] ",-\"\"-." "i-..-i" "| |" "`-..-'" q)k){[a;x;y;w;h].[a;-1+(y;x)+!:'h,w]}[ASCII;9;1;7;10] " ___ " ",\"---\"." ": ;" " `-.-' " " | | " " | | " " | | " ".-\\_/-." "| |" " `---' " q)k){[a;x;y;w;h].[a;-1+(y;x)+!:'h,w]}[ASCII;16;19;3;1] "hjw" ``` **Explanation:** Take the 1-indexed input, generate the x/y coordinates and index into ascii art. ``` {[a;x;y;w;h]a .-1+(y;x)+!:'h,w} / the solution {[a;x;y;w;h] } / lambda taking 5 inputs, a(scii), x, y, w(idth), h(eight) h,w / concatenate height and width, e.g. 7 5 !:' / range til each, e.g. (0 1 2 3 4 5 6;0 1 2 3 4) (y;x)+ / add list y x to it, e.g. (15 16 17 18 19 20 21;10 11 12 13 14) -1+ / subtract 1, e.g. (14 15 16 17 18 19 20;9 10 11 12 13) a . / index into a at these coordinates ``` [Answer] # [R](https://www.r-project.org/), 62 bytes Perhaps surprisingly short solution to a text challenge in R, because we don't need to actually read the whole text into a matrix. ``` function(x,y,w,h)write(substr(readLines()[y+1:h-1],x,x+w-1),1) ``` [Try it online!](https://tio.run/##jY9LboMwEIb3PoVFFtjKjInbJlFScYPeoFSEFAiuKrcyIIjE3anNK9lUyoxk6//mbfo87PNaf1bqR7MWrtBAwRujqoyV9bmsDDNZkr4pnZWMv1/X8lig/IAW2nWDkoPk/SpncgNyC1vYc7qil8Skmaa/SVUQG3sG@QQ7eHGh9OyI3IE8gOUOleqik6o2GcnZASTsQW4cT75VpgldLI7jRYGHiJ5Y9HF4X2/ZJxTo3xV3tHtExQKjOEAxToppYINjSkQHFlh33RF9@0c0Io4NYDYbsDQA9DwU876DiAijCoVANeFJcNKdhjnd1GIUfkcid4hwLSEUdBIBuc3rwrnm/2vHLRfj1ouv5g7Zo26KUUb6Pw "R – Try It Online") [Answer] # [\/\/>](https://github.com/torcado194/worm/), 123 bytes ``` j:j8+}j+}j}pppp80x {:}i:0(?v:a=?x@s1+: ~~~~1+0!/000y yp:qqqq~ q{y?=p:+1q:}}g$q:pp: 1}x}p}ap:q~q+1{{y!?:- ys{{ ~!u.*2(0:;!?h ``` Input consists of a single line of space-delimited input variables `x`, `y`, `w`, and `h`, followed by the ascii art on the next line onward. ## Explanation This code uses \/\/>'s ability to self-modify by placing the ascii art in the code itself, which ends up looking like this: ![code](https://i.stack.imgur.com/WivJE.png) It then grabs the characters in the specified rectangle off of the code and outputs it. ]
[Question] [ > > Every palindrome with an even number of digits is divisible by 11, so 11 is the only [palindromic prime] with an even number of digits. - [David Wasserman, OEIS](https://oeis.org/A002385) > > > I learned this today the manual way, before I did my research, when my program skipped numbers with an even number of digits (except 11) when calculating palindromic primes. Your task: create a program or function that when given an integer input N, outputs the Nth term in Stephen's Palindromic Sequence™. # Stephen's Palindromic Sequence™ Stephen's Palindromic Sequence™ starts with 11, and continues with [palindromic](https://en.wikipedia.org/wiki/Palindromic_number) [semiprimes](https://en.wikipedia.org/wiki/Semiprime) divisible by 11. Basically, all of the semiprimes that would be primes if 11 didn't "count." The upside is that this list contains numbers with an even number of digits! Yay. And, a lot of numbers with an odd number of digits are skipped, since they were already prime. The beginning of the sequence: ``` 1 : 11 2 : 22 3 : 33 4 : 55 5 : 77 6 : 121 7 : 737 8 : 979 9 : 1111 10 : 1441 11 : 1661 12 : 1991 13 : 3113 14 : 3223 15 : 3443 16 : 3883 17 : 7117 18 : 7447 19 : 7997 20 : 9119 21 : 9229 22 : 9449 23 : 10901 ``` \*Although 1331 (11^3) and similar fit the spirit of this sequence, they do not fit the rules. Longer test cases: ``` 26 : 91619 31 : 103301 41 : 139931 51 : 173371 61 : 305503 71 : 355553 81 : 395593 91 : 725527 101 : 772277 127 : 997799 128 : 1099901 141 : 3190913 151 : 3739373 161 : 7589857 171 : 9460649 200 : 11744711 528 : 39988993 ``` # Input Integer N, >= 1. You can use a 0-indexed N (be sure to adjust test cases) if you specify so in your answer. Trailing newlines allowed. # Output The Nth term in Stephen's Palindromic Sequence™. Trailing newlines allowed. # Rules * The only input your program/function can take is N. Your program cannot, for example, fetch a sequence from OEIS (aka [standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)). * You must be able to print an output up to six digits (N=127). Time is not a factor - however, if your program/function gets very long very fast, you must prove that the algorithm works. If your language naturally allows longer outputs, it you can let it expand naturally up to its limit, or cap it at ten digits, whichever you prefer. Output/termination beyond your limit does not matter, as long as it does not appear to be a valid output. * Program/function function on invalid input is irrelevant. [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ ~~73~~ ~~72~~ ~~70~~ ~~69~~ 68 bytes ``` n=input();c=k=m=11 while n:m*=k/c;k+=c;n-=`k`==`k`[::~m%k-c] print k ``` *Thanks to @WheatWizard for golfing off 3 bytes!* *Thanks to @ØrjanJohansen for golfing off 1 byte!* *Thanks to @xnor and @ØrjanJohansen for paving the way to 68 bytes!* Input is 0-indexed. [Try it online!](https://tio.run/nexus/python2#@59nm5lXUFqioWmdbJttm2traMhVnpGZk6qQZ5WrZZutn2ydrW2bbJ2na5uQnWALIqKtrOpyVbN1k2O5Cooy80oUsv//NzQwAAA "Python 2 – TIO Nexus") or [verify the first 31 test cases](https://tio.run/nexus/python2#Jc7NDoIwEATgM32KvZCiQORH/CnZJyEkYKnaFBZCMHry1XHVwzfHmdFjZwBBSrkSWpoeS7ApNTocME3F8257A6SGLbqdLl2IuqQYG9fgNyql3oPvYl2Laba0gFu5SIjrOAOBJZhbupkgyzcQQpUVEeRJBHtWsAM7shM7J7US3m@f3/TtcOlaBSS8f6/047wDJcEHioRnXkaD5ufrBw "Python 2 – TIO Nexus"). ### Background Recall that [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) states that for all integers **p > 1**, ![](https://i.stack.imgur.com/41Mzr.png) meaning that **(p - 1)! + 1** is evenly divisible by **p** if and only if **p** is prime. If **p > 1** is *not* prime, it is composite; let **q** be the smallest prime divisor of **p**. Clearly, **q ≤ p/q**. There are two cases: * If **q = p/q**, we have that **p = q²**. If **q = 2**, **(p - 1)! = 3! = 6**, so **(p - 1)!** is congruent to **2** modulo **p**. If **p/q = q > 2**, so **2q < p**. This way, **q** and **2q** are both among **1, …, p - 1**, whose product is the factorial of **p - 1**, so **2p = 2q² = q · 2q** divides **(p - 1)!** evenly. * If **q < p/q**, **q** and **p/q** are both among **1, …, p - 1**, so **p = q · p/q** divides **(p - 1)!** evenly. Summing up, ![](https://i.stack.imgur.com/Z4kzg.png) for all integers **p > 1**. Now, for all integer congruences and all integers **a**, **b**, and **c**, the following holds. ![](https://i.stack.imgur.com/s7hI3.png) When **a = -1**, **b = 11**, and **c = -1**, we follow that ![](https://i.stack.imgur.com/uocHX.png) and, since **21** and **-23** are congruent modulo **44** and **-1** and **11p-1** are congruent modulo **11p**, we arrive at the following conclusion. ![](https://i.stack.imgur.com/S5rcT.png) For all possible values of **p**, the outcome (**11**, **21**, or **11p - 1**) will fall in the range **0, …, 11p - 1**, so these values match those that will be returned by Python's `%` operator. ### How it works We initialize **c**, **k**, and **m** to **11** after the saving the input in **n**. **c** will be constant for the remainder of the program. Since there are three occurrences of **c** on the following line and assigning **c** costs only two bytes, this saves a byte. **k** can be thought of **11p** using the meaning of **p** from the previous paragraph; initially, **k = 11 = 11 · 1!**. **m** takes the place of **11 · (p - 1)!**; initially, **m = 11 = 11 · 0!**. **k** and **m** will satisfy the relationship **m = 11 · (k/11)!** at all times. **n** represents the number of “Stephen's palindromes” we have to find. Since **k = 11** initially, we can output **k** verbatim without further computation. However, when **n** is positive, we enter the while loop. The loop begins by multiplying **m** by **k/c = p**, then adding **11** to **k**, thus incrementing **p**. If **k** is a member of the sequence, we subtract **1** from **n** and start over. Once **n** reaches **0**, we found the sequence member at the desired index and break out of the loop, then print the last value of **k**. The expression ``` `k`==`k`[::~m%k-c] ``` performs the actual test, and it's result (*True* / **1** for sequence members, **0** / *False* otherwise) is subtracted from **n**. As seen before, **~m % k = (-m - 1) % k = (-11 · (p - 1)! - 1) % 11p** equals **10** if **p** is prime, **21** if **p = 4**, and **11p - 1 > 43** if **p > 4** is composite. Thus, after subtracting **c = 11**, we're left with **-1** for prime **p** and a positive integer larger than **9** otherwise. For prime **p**, `​`k`[::-1]` gives us the string representation of **k** with reversed digit order, so comparing it to `​`k`​` checks whether **k** is a palindrome. If it is, all conditions are fulfilled and **k** is a sequence member. However, if **p** is not prime, the large range step and the fact that **k** will always have more than one digit mean that `​`k`[::-1]` cannot have the same number of digits as `​`k`​`, let alone be equal to it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 13 bytes ``` ṬÆẸש11ŒḂµ#ṛ® ``` For some reason, this is much slower than my initial revision, despite doing exactly the same. [Try it online!](https://tio.run/nexus/jelly#ASAA3///4bmsw4bhurjDl8KpMTHFkuG4gsK1I@G5m8Ku//84MQ "Jelly – TIO Nexus") ### N = 127 ``` dennis-home:~$ time jelly eun 'ṬÆẸש11ŒḂµ#ṛ®' <<< 127 997799 real 1m43.745s user 1m43.676s sys 0m0.113s ``` ### How it works ``` ṬÆẸש11ŒḂµ#ṛ® Main link. No arguments. µ Combine all links to the left into a chain. # Read an integer n from STDIN and call the chain monadically, with argument k = 0, 1, 2, ... until n values of k result in a truthy output. Return the array of all matching values of k. Ṭ Untruth; yield [0, 0, 0, ..., 1] (k-1 zeroes followed by a 1) or [] if k = 0. ÆẸ Unexponents; consider the resulting array as exponents of the sequence of primes and yield the corresponding integer. For k = 0, this yields 1. For k > 0, it yields the k-th prime. ש11 Multiply the result by 11 and copy the product to the register. ŒḂ Test if the product is a palindrome. ṛ® Replace the resulting array with the integer in the register. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes ``` :I{11|ṗ×₁₁≜.↔}ᶠ⁽t ``` [Try it online!](https://tio.run/nexus/brachylog2#@2/lWW1oWPNw5/TD0x81NYJQ5xy9R21Tah9uW/CocW/J//9Gxv@jAA "Brachylog – TIO Nexus") This is 1-indexed. ### Explanation ``` :I{ }ᶠ⁽t Find the Input'th result of the following: 11 Output = 11 | Or ≜. Output is an integer… ṗ×₁₁ …which is the result of multiplying a prime by 11… .↔ …and Output reversed is still the Output ``` Two realizations with this answer: * I need to fix the fact that superscript passing to metapredicates (with `⁽`) does not work if there is no input to pass (which is why I have to add `:I`). * I need to add a metapredicate to get the `N`th result of a predicate (which would avoid using `ᶠ⁽t` and instead e.g. `ⁿ⁽`). Implementing both changes would make that answer 14 bytes. [Answer] ## Mathematica, ~~65~~ 60 bytes ``` n=NextPrime;11Nest[n@#//.x_/;!PalindromeQ[11x]:>n@x&,1,#-1]& ``` Iterates directly through primes using `NextPrime` and checks whether 11 times the prime is a palindrome. Works up to **N = 528**. The results 528 and 529 are more than 216 primes apart, at which point `//.` will fail to attempt a sufficient number of substitutions. [Answer] # [Python 2](https://docs.python.org/2/), ~~111~~ ~~107~~ ~~103~~ ~~102~~ ~~101~~ ~~100~~ ~~91~~ ~~90~~ 89 bytes Dennis has me beaten [here](https://codegolf.stackexchange.com/a/117194/56656), so go check out his answer. This answer is zero indexed ``` n=input() r=1 while n:r+=1;c=`r*11`;n-=all(r%x for x in range(2,r))*c==c[::-1] print r*11 ``` [Try it online!](https://tio.run/nexus/python2#FctLCoAgEADQvaeYTaB9oGmpzEkiKMRKkEmGIm9v9PavMkXOz62NEkL1njEFYCsdofO0Sou4Oh5oS0lLU2C/BApEBtn4CHrqxZjWE/nZ2gEXlSXyDX@rdfw "Python 2 – TIO Nexus") *One byte saved thanks to math junkie* ## Explanation First we take input and set it to `n` we also make a new variable `r=1`. We will count up `r` searching for palindromes that are the product of a prime and 11. Each time we find one we will decrement `n` until it reaches 0. So we start a the loop: ``` while n: ``` The first thing we do is increment `r` ``` r+=1 ``` We also predefine a variable `c` as the string representation of `r*11` ``` c=`r*11` ``` Now we want to decrement `n` if we have found such a number. We will simply subtract a boolean representing if `r*11` fits the pattern from `r`. If this is `False` we will subtract zero and if it is `True` it will subtract 1. To calculate the boolean we do: ``` all(r%x for x in range(2,r))*c==c[::-1] ``` The first part `all` will determine if `r` is prime. We multiply the result by `c` if `r` is prime this will just be `c` but if `r` is composite it will be `""`, the empty string. We then compare this to `c[::-1]` which is the reverse of `c`. If `r` is prime and `c` is a palindrome this will be `True`, if either fails the whole thing will evaluate as false. When `n` is zero we simply `print c`. # 83 bytes Here is a recursive solution that is shorter but unfortunately doesn't meet the specs because it hits python's recursion cap too fast. ``` f=lambda n,r=1:n and f(n-all(r%x*(`r*11`==`r*11`[::-1])for x in range(2,r)),r+1)+11 ``` [Try it online!](https://tio.run/nexus/python2#JcwxCoAwDADAr2QRklqHdCz0JSIYqRWhRgkO/r4KTrddK6nKsWQB9ZY4KohmKKiD1IrWPQ5nc8xzSr9jjANPVE6DB3YFE91WDN6IvPVMPXO7bNf7SzhQewE "Python 2 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes 0-indexed. ``` 11Iµ11N*DÂQNp*½ ``` [Try it online!](https://tio.run/nexus/05ab1e#@29o6Hloq6Ghn5bL4aZAvwKtQ3v//zcyBQA "05AB1E – TIO Nexus") **Explanation** ``` 11 # initialize stack with 11 Iµ # loop over N in [1 ... inf] until counter equals input 11N* # multiply N by 11 D # duplicate ÂQ # check if the copy equals its reverse Np # check if N is prime * # multiply the results of the checks together ½ # if 1, increase counter ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` !:11foṗ/11İ↔ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8b@ilaFhWv7DndP1DQ2PbHjUNuX////RRsY6RmY6xoY6JoaxAA "Husk – Try It Online") ``` ! # get element at input-th index of :11 # prepend 11 to İ↔ # palindromic numbers fo # that satisfy /11 # when they're divided by 11 ṗ # the result is a prime ``` [Answer] # [Haskell](https://www.haskell.org/), ~~94~~ 90 bytes ``` h#n|n<2=0|mod n h<1=1+h#div n h|j<-h+1=j#n ([n|n<-[0,11..],(==)=<<reverse$show n,3>2#n]!!) ``` [Try it online!](https://tio.run/nexus/haskell#FcoxCoUwDADQ3VNU6qBYxdTBJfkXEQfBSioYpYp/6d0rjg9eYi1R0FIX92NRohiBoGa9@OdT3LDhGmjTkq1Ujl9uxs4AtO1kSqKKEIN7XLhccfHxV2L6n9Uy5XmV9tkLncHLXawK7JBe "Haskell – TIO Nexus") Example usage: `([n|n<-[0,11..],(==)=<<reverse$show n,3>2#n]!!) 127`. `[0,11..]` constructs the infinite list `[0,11,22,33, ...]` (the zero is needed to make the sequence 1-indexed). For each `n` in this list we check `n==(read.reverse.show)n`, that is whether `n` is a palindrome. `3>2#n` checks if `n` has at most two prime divisors. Because `n` is always divisible by 11, we don't get any real primes but only semiprimes. **Edit:** Thanks to Ørjan Johansen for golfing 4 bytes! [Answer] # PHP, 82 Bytes ``` for(;$d<$argn;$i>1||($p=11*$n)!=strrev($p)?:$d++)for($i=++$n;--$i&&$n%$i;);echo$p; ``` [Try it online!](https://tio.run/nexus/php#HcyxDoIwFEbhnbcw@SWtDUM346UyGAYWXdyJkQp3aZsrcSK8ekXXLzmnbtKUsheJ0otPUWYOo1rb/nq7d5dWU4GHjMEdLRWvKIow1H8h8Nkui0Jy1h4Q9M69ZxH/2UQ3JwzG6F8AdsYgUFWByxJhD6bt6p9TRKKcvw "PHP – TIO Nexus") [Answer] # Axiom, 105 bytes ``` g(n)==(i:=c:=1;repeat(c=n=>break;i:=i+1;if(prime? i)then(x:=(11*i)::String;x=reverse(x)=>(c:=c+1)));i*11) ``` ungolf, test code and results ``` f(n)== i:=c:=1 repeat c=n=>break i:=i+1 if(prime? i)then(x:=(11*i)::String;x=reverse(x)=>(c:=c+1)) i*11 (5) -> [[i,g(i)] for i in 1..23] (5) [[1,11], [2,22], [3,33], [4,55], [5,77], [6,121], [7,737], [8,979], [9,1111], [10,1441], [11,1661], [12,1991], [13,3113], [14,3223], [15,3443], [16,3883], [17,7117], [18,7447], [19,7997], [20,9119], [21,9229], [22,9449], [23,10901]] Type: List List PositiveInteger (6) -> [[i,g(i)] for i in [26,31,41,101,151,200]] (6) [[26,91619], [31,103301], [41,139931], [101,772277], [151,3739373], [200,11744711]] ``` Here g(700)=92511529 so the limit would be >700; ww(1000)=703999307 but using nextPrime() ]
[Question] [ From [Wikipedia](https://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon): > > The centroid of a non-self-intersecting closed polygon > defined by *n* vertices (*x0,y0*), > (*x1,y1*), ..., > (*xn−1,yn−1*) is the point (*Cx, > Cy*), where > > > [![Formula for Centroid](https://i.stack.imgur.com/AMpkl.png)](https://i.stack.imgur.com/AMpkl.png) > > > and where *A* is the polygon's signed area, > > > [![Formula for Area of Polygon](https://i.stack.imgur.com/0iGfC.png)](https://i.stack.imgur.com/0iGfC.png) > > > In these formulas, the vertices are assumed to be numbered in order of > their occurrence along the polygon's perimeter. Furthermore, the > vertex ( *xn, yn* ) is assumed to be the same as > ( *x0, y0* ), meaning *i + 1* on the last case > must loop around to *i = 0*. Note that if the points are numbered in > clockwise order the area *A*, computed as above, will have a negative > sign; but the centroid coordinates will be correct even in this case. > > > --- * Given a list of vertices in order (either clockwise, or counter-clockwise), find the centroid of the non-self-intersecting closed polygon represented by the vertices. + If it helps, you may assume input to be only CW, or only CCW. Say so in your answer if you require this. * The coordinates are not required to be integers, and may contain negative numbers. * Input will always be valid and contain at least three vertices. * Inputs only need to be handled that fit in your language's native floating point data type. * You may assume that input numbers will always contain a decimal point. * You may assume that input integers end in `.` or `.0`. * You may use complex numbers for input. * Output should be accurate to the nearest thousandth. ### Examples ``` [(0.,0.), (1.,0.), (1.,1.), (0.,1.)] -> (0.5, 0.5) [(-15.21,0.8), (10.1,-0.3), (-0.07,23.55)] -> -1.727 8.017 [(-39.00,-55.94), (-56.08,-4.73), (-72.64,12.12), (-31.04,53.58), (-30.36,28.29), (17.96,59.17), (0.00,0.00), (10.00,0.00), (20.00,0.00), (148.63,114.32), (8.06,-41.04), (-41.25,34.43)] -> 5.80104769975, 15.0673812762 ``` Too see each polygon on a coordinate plane, paste the coordinates without the square brackets in the "Edit" menu of [this page](https://www.mathsisfun.com/data/cartesian-coordinates-interactive.html). I confirmed my results using this [Polygon Centroid Point Calculator](https://www.easycalculation.com/area/polygon-centroid-point.php), which is awful. I couldn't find one that you can input all vertices at once, or that didn't try to erase your `-` sign when you type it first. I'll post my Python solution for your use after people have had a chance to answer. [Answer] # Mathematica, 23 bytes ``` RegionCentroid@*Polygon ``` ~~Take **THAT**, Jelly!~~ Edit: One does not simply beat Jelly... # Explanation ``` Polygon ``` Generate a polygon with vertices at the points specified. ``` RegionCentroid ``` Find the centroid of the polygon. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~25~~ ~~24~~ ~~22~~ ~~21~~ 18 bytes ``` S×3÷@×" ṙ-żµÆḊçS€S ``` Applies the formula shown in the problem. Saved 3 bytes with help from @[Jonathan Allan.](https://codegolf.stackexchange.com/users/53748/jonathan-allan) [Try it online!](http://jelly.tryitonline.net/#code=U8OXM8O3QMOXIgrhuZktxbzCtcOG4biKw6dT4oKsUw&input=&args=Wy0xNS4yMSwgMC44XSwgWzEwLjEsIC0wLjNdLCBbLTAuMDcsIDIzLjU1XQ) or [Verify all test cases.](http://jelly.tryitonline.net/#code=U8OXM8O3QMOXIgrhuZktxbzCtcOG4biKw6dT4oKsUwrDh-KCrEc&input=&args=W1swLCAwXSwgWzEsIDBdLCBbMSwgMV0sIFswLCAxXV0sIFtbLTE1LjIxLCAwLjhdLCBbMTAuMSwgLTAuM10sIFstMC4wNywgMjMuNTVdXSwgW1stMzkuMCwgLTU1Ljk0XSwgWy01Ni4wOCwgLTQuNzNdLCBbLTcyLjY0LCAxMi4xMl0sIFstMzEuMDQsIDUzLjU4XSwgWy0zMC4zNiwgMjguMjldLCBbMTcuOTYsIDU5LjE3XSwgWzAuMCwgMC4wXSwgWzEwLjAsIDAuMF0sIFsyMC4wLCAwLjBdLCBbMTQ4LjYzLCAxMTQuMzJdLCBbOC4wNiwgLTQxLjA0XSwgWy00MS4yNSwgMzQuNDNdXQ) ## Explanation ``` S×3÷@×" Helper link. Input: determinants on LHS, sum of pairs on RHS S Sum the determinants ×3 Multiply by 3 ×" Vectorized multiply between determinants and sums ÷@ Divide that by the determinant sum multipled by 3 and return ṙ-żµÆḊçS€S Main link. Input: 2d list of points ṙ- Rotate the list of points by 1 to the right ż Interleave those with the original points This creates all overlapping slices of length 2 µ Start new monadic chain ÆḊ Get the determinant of each slice S€ Get the sum of each slice (sum of pairs of points) ç Call the helper link S Sum and return ``` [Answer] # J, 29 bytes ``` 2+/@(+/\(*%3*1#.])-/ .*\)],{. ``` Applies the formula shown in the problem. ## Usage ``` f =: 2+/@(+/\(*%3*1#.])-/ .*\)],{. f 0 0 , 1 0 , 1 1 ,: 0 1 0.5 0.5 f _15.21 0.8 , 10.1 _0.3 ,: _0.07 23.55 _1.72667 8.01667 f _39 _55.94 , _56.08 _4.73 , _72.64 12.12 , _31.04 53.58 , _30.36 28.29 , 17.96 59.17 , 0 0 , 10 0 , 20 0 , 148.63 114.32 , 8.06 _41.04 ,: _41.25 34.43 5.80105 15.0674 ``` ## Explanation ``` 2+/@(+/\(*%3*1#.])-/ .*\)],{. Input: 2d array of points P [[x1 y1] [x2 y2] ...] {. Head of P ] Get P , Join, makes the end cycle back to the front 2 The constant 2 2 \ For each pair of points -/ .* Take the determinant 2 +/\ Sum each pair of points * Multiply the sum of each pair by its determinant % Divide each by 1#.] The sum of the determinants 3* Multiplied by 3 +/@ Sum and return ``` [Answer] ## Maxima, ~~124 118 116 112~~ 106 byte ``` f(l):=(l:endcons(l[1],l),l:sum([3,l[i-1]+l[i]]*determinant(matrix(l[i-1],l[i])),i,2,length(l)),l[2]/l[1]); ``` I'm not experienced with Maxima, so any hints are welcome. Usage: ``` (%i6) f([[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]); (%o6) [- 1.726666666666668, 8.016666666666668] ``` [Answer] ## Racket 420 bytes ``` (let*((lr list-ref)(getx(lambda(i)(lr(lr l i)0)))(gety(lambda(i)(lr(lr l i)1)))(n(length l))(j(λ(i)(if(= i(sub1 n))0(add1 i)))) (A(/(for/sum((i n))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i))))2)) (cx(/(for/sum((i n))(*(+(getx i)(getx(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A))) (cy(/(for/sum((i n))(*(+(gety i)(gety(j i)))(-(*(getx i)(gety(j i)))(*(getx(j i))(gety i)))))(* 6 A)))) (list cx cy)) ``` Ungolfed: ``` (define(f l) (let* ((lr list-ref) (getx (lambda(i)(lr (lr l i)0))) (gety (lambda(i)(lr (lr l i)1))) (n (length l)) (j (lambda(i) (if (= i (sub1 n)) 0 (add1 i)))) (A (/(for/sum ((i n)) (-(* (getx i) (gety (j i))) (* (getx (j i)) (gety i)))) 2)) (cx (/(for/sum ((i n)) (*(+(getx i)(getx (j i))) (-(*(getx i)(gety (j i))) (*(getx (j i))(gety i))))) (* 6 A))) (cy (/(for/sum ((i n)) (*(+(gety i)(gety (j i))) (-(*(getx i)(gety (j i))) (*(getx (j i))(gety i))))) (* 6 A)))) (list cx cy))) ``` Testing: ``` (f '[(-15.21 0.8) (10.1 -0.3) (-0.07 23.55)] ) (f '[(-39.00 -55.94) (-56.08 -4.73) (-72.64 12.12) (-31.04 53.58) (-30.36 28.29) (17.96 59.17) (0.00 0.00) (10.00 0.00) (20.00 0.00) (148.63 114.32) (8.06 -41.04) (-41.25 34.43)]) ``` Output: ``` '(-1.7266666666666677 8.01666666666667) '(5.8010476997538465 15.067381276150996) ``` [Answer] # R, 129 127 bytes ``` function(l){s=sapply;x=s(l,`[`,1);y=s(l,`[`,2);X=c(x[-1],x[1]);Y=c(y[-1],y[1]);p=x*Y-X*y;c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3} ``` Unnamed function that take an R-list of tuples as input. The named equivalent can be called using e.g.: ``` f(list(c(-15.21,0.8),c(10.1,-0.3),c(-0.07,23.55))) ``` **Ungolfed and explained** ``` f=function(l){s=sapply; # Alias for sapply x=s(l,`[`,1); # Split list of tuples into vector of first elements y=s(l,`[`,2); # =||= but for second element X=c(x[-1],x[1]); # Generate a vector for x(i+1) Y=c(y[-1],y[1]); # Generate a vector for y(i+1) p=x*Y-X*y; # Calculate the outer product used in both A, Cx and Cy c(sum((x+X)*p),sum((y+Y)*p))/sum(p)/3 # See post for explanation } ``` The final step (`c(sum((x+X)*p),sum((y+Y)*p))/sum(p)*2/6`) is a vectorized way of calculating both `Cx` and `Cy`. The sum in the formulas for `Cx` and `Cy` are stored in a vector and consequently divided by the "sum in `A`" `*2/6`. E.g.: ``` (SUMinCx, SUMinCy) / SUMinA / 3 ``` , and then implicitly printed. [Try it on R-fiddle](http://www.r-fiddle.org/#/fiddle?id=lruKHfyR&version=1) [Answer] # Python, ~~156~~ 127 bytes ``` def f(p):n=len(p);p=p+p[:1];i=s=0;exec'd=(p[i].conjugate()*p[i+1]).imag;s+=d;p[i]=(p[i]+p[i+1])*d;i+=1;'*n;print sum(p[:n])/s/3 ``` Ungolfed: ``` def f(points): n = len(points) points = points + [points[0]] determinantSum = 0 for i in range(n): determinant = (points[i].conjugate() * points[i+1]).imag determinantSum += determinant points[i] = (points[i] + points[i+1]) * determinant print sum(points[:n]) / determinantSum / 3 ``` [Ideone it.](http://ideone.com/aP78zs) This takes each pair of points `[x, y]` as a complex number `x + y*j`, and outputs the resulting centroid as a complex number in the same format. For the pair of points `[a, b]` and `[c, d]`, the value `a*d - b*c` which is needed for each pair of points can be computed from the determinant of the matrix ``` | a b | | c d | ``` Using complex arithmetic, the complex values `a + b*j` and `c + d*j` can be used as ``` conjugate(a + b*j) * (c + d*j) (a - b*j) * (c + d*j) (a*c + b*d) + (a*d - b*c)*j ``` Notice that the imaginary part is equivalent to the determinant. Also, using complex values allows the points to be easily summed component-wise in the other operations. [Answer] # R + sp (46 bytes) Assumes `sp` package is installed (<https://cran.r-project.org/web/packages/sp/>) Takes a list of vertices, (for example `list(c(0.,0.), c(1.,0.), c(1.,1.), c(0.,1.))`) Takes advantage of the fact that the "labpt" of a Polygon is the centroid. ``` function(l)sp::Polygon(do.call(rbind,l))@labpt ``` [Answer] # JavaScript (ES6), 102 Straight implementation of the formula ``` l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a] ``` **Test** ``` f= l=>[...l,l[0]].map(([x,y],i)=>(i?(a+=w=t*y-x*u,X+=(t+x)*w,Y+=(u+y)*w):X=Y=a=0,t=x,u=y))&&[X/3/a,Y/3/a] function go() { var c=[],cx,cy; // build coordinates array I.value.match(/-?[\d.]+/g).map((v,i)=>i&1?t[1]=+v:c.push(t=[+v])); console.log(c+''), [cx,cy]=f(c); O.textContent='CX:'+cx+' CY:'+cy; // try to display the polygon var mx=Math.max(...c.map(v=>v[0])), nx=Math.min(...c.map(v=>v[0])), my=Math.max(...c.map(v=>v[1])), ny=Math.min(...c.map(v=>v[1])), dx=mx-nx, dy=my-ny, ctx=C.getContext("2d"), cw=C.width, ch=C.height, fx=(mx-nx)/cw, fy=(my-ny)/ch, fs=Math.max(fx,fy) C.width=cw ctx.setTransform(1,0,0,1,0,0); ctx.beginPath(); c.forEach(([x,y],i)=>ctx.lineTo((x-nx)/fs,(y-ny)/fs)); ctx.closePath(); ctx.stroke(); ctx.fillStyle='#ff0000'; ctx.fillRect((cx-nx)/fs-2,(cy-ny)/fs-2,5,5); } go() ``` ``` #I { width:90% } #C { width:90%; height:200px;} ``` ``` <input id=I value='[[-15.21,0.8], [10.1,-0.3], [-0.07,23.55]]'> <button onclick='go()'>GO</button> <pre id=O></pre> <canvas id=C></canvas> ``` [Answer] # Python 2, 153 bytes Uses no complex numbers. ``` P=input() A=x=y=0;n=len(P) for i in range(n):m=-~i%n;a=P[i][0];b=P[i][1];c=P[m][0];d=P[m][1];t=a*d-b*c;A+=t;x+=t*(a+c);y+=t*(b+d) k=1/(3*A);print x*k,y*k ``` [**Try it online**](http://ideone.com/0vnSik) ### Ungolfed: ``` def centroid(P): A=x=y=0 n=len(P) for i in range(n): m=-~i%n x0=P[i][0];y0=P[i][1] x1=P[m][0];y1=P[m][1] t = x0*y1 - y0*x1 A += t/2. x += t * (x0 + x1) y += t * (y0 + y1) k = 1/(6*A) x *= k y *= k return x,y ``` [Answer] # Actually, ~~45~~ ~~40~~ 39 bytes This uses an algorithm similar to [miles' Jelly answer](https://codegolf.stackexchange.com/a/96696/47581). There is a shorter way to calculate determinants using a dot product, but there's currently a bug with Actually's dot product where it won't work with lists of floats. Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=O1xa4pmCIztg4pSs4pmCzqNgTUBgaeKUgk5ARiopRkBOKi1gTTvOozMqKeKZgCrilKzimYLOo-KZgC8&input=W1stMTUuMjEsIDAuOF0sIFsxMC4xLCAtMC4zXSwgWy0wLjA3LCAyMy41NV1d) ``` ;\Z♂#;`i¥`M@`i│N@F*)F@N*-`M;Σ3*)♀*┬♂Σ♀/ ``` **Ungolfing** ``` Implicit input pts. ;\ Duplicate pts, rotate right. Z Zip rot_pts and pts together. ♂# Convert the iterables inside the zip to lists (currently necessary due to a bug with duplicate) ; Duplicate the zip. `...`M Get the sum each pair of points in the zip. i Flatten the pair to the stack. ¥ Pairwise add the two coordinate vectors. @ Swap with the other zip. `...`M Get the determinants of the zip. i│ Flatten to stack and duplicate entire stack. Stack: [a,b], [c,d], [a,b], [c,d] N@F*) Push b*c and move it to BOS. F@N* Push a*d. - Get a*d-b*c. ;Σ3*) Push 3 * sum(determinants) and move it to BOS. ♀* Vector multiply the determinants and the sums. ┬ Transpose the coordinate pairs in the vector. ♂Σ Sum the x's, then the y's. ♀/ Divide the x and y of this last coordinate pair by 3*sum(determinants). Implicit return. ``` **A shorter, non-competitive version** This is another 24-byte version that uses complex numbers. It's non-competitive because it relies on bug fixes that postdate this challenge. [Try it online!](http://actually.tryitonline.net/#code=O1zilILCpSlaYGnDoSrilatAWGBNO86jMyop4pmAKs6jLw&input=Wy0xNS4yMSswLjhqLCAxMC4xLTAuM2osIC0wLjA3KzIzLjU1al0) ``` ;\│¥)Z`iá*╫@X`M;Σ3*)♀*Σ/ ``` **Ungolfing** ``` Implicit input a list of complex numbers, pts. ;\ Duplicate pts, rotate right. │ Duplicate stack. Stack: rot_pts, pts, rot_pts, pts. ¥) Pairwise sum the two lists of points together and rotate to BOS. Z Zip rot_pts and pts together. `...`M Map the following function over the zipped points to get our determinants. i Flatten the list of [a+b*i, c+d*i]. á Push the complex conjugate of a+bi, i.e. a-b*i. * Multiply a-b*i by c+d*i, getting (a*c+b*d)+(a*d-b*c)*i. Our determinant is the imaginary part of this result. ╫@X Push Re(z), Im(z) to the stack, and immediately discard Re(z). This map returns a list of these determinants. ; Duplicate list_determinants. Σ3*) Push 3 * sum(list_determinants) and rotate that to BOS. ♀*Σ Pairwise multiply the sums of pairs of points and the determinants and sum. / Divide that sum by 3*sum(list_determinants). Implicit return. ``` [Answer] # C++14, 241 bytes ``` struct P{float x;float y;}; #define S(N,T)auto N(P){return 0;}auto N(P a,P b,auto...V){return(T)*(a.x*b.y-b.x*a.y)+N(b,V...);} S(A,1)S(X,a.x+b.x)S(Y,a.y+b.y)auto f(auto q,auto...p){auto a=A(q,p...,q)*3;return P{X(q,p...,q)/a,Y(q,p...,q)/a};} ``` Output is the helper struct `P`, Ungolfed: ``` //helper struct struct P{float x;float y;}; //Area, Cx and Cy are quite similar #define S(N,T)\ //N is the function name, T is the term in the sum auto N(P){return 0;} \ //end of recursion for only 1 element auto N(P a,P b,auto...V){ \ //extract the first two elements return (T)*(a.x*b.y-b.x*a.y) //compute with a and b + N(b,V...); \ //recursion without first element } //instantiate the 3 formulas S(A,1) S(X,a.x+b.x) S(Y,a.y+b.y) auto f(auto q,auto...p){ auto a=A(q,p...,q)*3; //q,p...,q appends the first element to the end return P{X(q,p...,q)/a,Y(q,p...,q)/a}; } ``` Usage: ``` f(P{0.,0.}, P{1.,0.}, P{1.,1.}, P{0.,1.}) f(P{-15.21,0.8}, P{10.1,-0.3}, P{-0.07,23.55}) ``` [Answer] ## Clojure, ~~177~~ ~~156~~ 143 bytes Update: Instead of a callback I'm using `[a b c d 1]` as a function and the argument is just a list of indexes to this vector. `1` is used as a sentinel value when calculating `A`. Update 2: Not precalculating `A` at `let`, using `(rest(cycle %))` to get input vectors offset by one. ``` #(let[F(fn[I](apply +(map(fn[[a b][c d]](*(apply +(map[a b c d 1]I))(-(* a d)(* c b))))%(rest(cycle %)))))](for[i[[0 2][1 3]]](/(F i)(F[4])3))) ``` Original version: ``` #(let[F(fn[L](apply +(map(fn[[a b][c d]](*(L[a b c d])(-(* a d)(* c b))))%(conj(subvec % 1)(% 0)))))A(*(F(fn[& l]1))3)](map F[(fn[v](/(+(v 0)(v 2))A))(fn[v](/(+(v 1)(v 3))A))])) ``` At less golfed stage: ``` (def f (fn[v](let[F (fn[l](apply +(map (fn[[a b][c d]](*(l a b c d)(-(* a d)(* c b)))) v (conj(subvec v 1)(v 0))))) A (* (F(fn[& l] 1)) 3)] [(F (fn[a b c d](/(+ a c)A))) (F (fn[a b c d](/(+ b d)A)))]))) ``` Creates a helper function `F` which implements the summation with any callback `l`. For `A` the callback returns constantly `1` whereas X and Y coordinates have their own functions. `(conj(subvec v 1)(v 0))` drops the first element and appends to the end, this way it is easy to keep track of `x_i` and `x_(i+1)`. Maybe there is still some repetition to be eliminated, especially at the last `(map F[...`. ]
[Question] [ **This question already has answers here**: [Guess the number [closed]](/questions/1112/guess-the-number) (14 answers) Closed 10 years ago. The puzzle is as follows: Create the traditional 'Guess my Number' game in as little keystrokes as possible. The player should input a guess between and including 1 and 100, and the computer should reply with either `+` (meaning the player needs to guess higher), `-` (meaning the player needs to guess lower) or `=` (meaning the player has guessed the number. The game continues until the player has guessed the number. The number that the computer generates MUST be a random number between and including 1 and 100. ### Sample gameplay ``` 50 + 75 - 60 - 55 + 57 = ``` Happy Golfing! [Answer] # Ruby: ~~63~~ ~~58~~ ~~52~~ 49 characters ``` puts"=-+"[r=$_.to_i<=>n||=1+rand(100)];r==0&&exit ``` Sample run: ``` bash-4.2$ ruby -ne 'puts"=-+"[r=$_.to_i<=>n||=1+rand(100)];r==0&&exit' 50 - 25 + 37 + 43 - 40 + 42 = ``` [Answer] **Python 84 83 characters** ``` import os a,c=0,ord(os.urandom(1))%100+1 while c-a:a=input();print'=-+'[c!=a:][c>a] ``` [Answer] # JavaScript, 52 ``` for(u=r=1+new Date%100;u=r-prompt(u<0?'-':'+'););'=' ``` Just paste it in the console. [Answer] **Perl 57 53 50 (thanks to @manatwork) Characters** ``` $_=qw(= + -)[$^T%100+1<=>$_];print"$_ ";exit if/=/ ``` Note You need to invoke with `-n` option Alternate version as suggested by @primo **Perl 40 Characters** ``` $_=chr 44-($^T%100+1<=>$_||exit print'=') ``` [Answer] ## APL (28) ``` {'='≠⎕←'+=-'[2+×⎕-⍵]:∇⍵}?100 ``` [Answer] # Haskell, 128 Won’t be winning any awards, but here it is. ``` main=fix.(.)(=<<(read<$>getLine)).f=<<(`mod`100).fst.next<$>newStdGen where p=putStrLn;f y r x|x<y=p"+">>r|x>y=p"-">>r|True=p"=" ``` Ungolfed logic and imports: ``` import Control.Applicative import Data.Function import System.Random main :: IO () main = do random <- newStdGen let number = fst (next random) `mod` 100 fix $ \loop -> do guess <- read <$> getLine check number guess loop where check number guess loop | guess < number = do putStrLn "+" loop | guess > number = do putStrLn "-" loop | otherwise = putStrLn "=" ``` [Answer] **C#: 147 136 Characters** It won't beat most other languages, but here's a C# solution for fun: ``` var r=new Random().Next(1,100);var g=0;while(g!=r){g=int.Parse(Console.ReadLine());Console.WriteLine(""+g+'\n'+(g<r?'+':g>r?'-':'='));} ``` [Answer] ## Clojure (117 characters) ``` java -jar clojure.jar -e "(loop[n(int(*(rand 100)))]((get{-1#(prn '+)0#(do(prn '=)(System/exit 0))1#(prn '-)}(compare(eval(read))n)))(recur n))" 50 + 75 + 90 - 86 - 82 = ``` ## Clojure (74 characters) Guessing a real number. Nobody will be patient enought to solve to "=", so nobody notice the missing exit. ``` java -jar clojure.jar -e "(loop[n(rand)](prn (get{-1 '+ 0 '= 1 '-}(compare(eval(read))n)))(recur n))" 0.5 + 0.8 - 0.6 + 0.7 + 0.75 - 0.72 + 0.74 + 0.745 + 0.748 - 0.746 - 0.7455 - ... ``` [Answer] # R, ~~89~~ 85 chars ``` s=sample(1:100,1);while(s!=(a=as.real(readline())))cat(ifelse(a>s,"-","+"));cat("=") ``` [Answer] **C89 92 90 89 (Thanks to @ugoren) 84 characters** *running on OS and linked with Linker supporting [ASLR](http://en.wikipedia.org/wiki/Address_space_layout_randomization)* ``` main(c,g){g=g/8%100+1;while(scanf("%d",&c)&&printf("%c\n",g-c?"-+"[c<g]:'=')&&c-g);} ``` [Answer] ## K, 69 ``` b:1b;g:1+*1?100;while[b;-1(*$[g<f:"I"$m:0:0;"-";g>f;"+";("=";b:0b)])] ``` Could definitely be golfed more ``` k)b:1b;g:1+*1?100;while[b;-1(*$[g<f:"I"$m:0:0;"-";g>f;"+";("=";b:0b)])] 50 + 75 - 60 + 65 - 63 + 64 = ``` [Answer] # Go, 152 Golfed : ``` package main import(f"fmt";"os") func main(){ c:=1+os.Getpid()%100 u:=0 for u!=c{ f.Scanf("%d",&u) s:="=" if u<c{s="+"}else if u>c{s="-"} f.Println(s)}} ``` Ungolfed : ``` package main import ( f "fmt" "os" ) func main() { c := 1 + os.Getpid()%100 u := 0 for u != c { f.Scanf("%d", &u) s := "=" if u < c { s = "+" } else if u > c { s = "-" } f.Println(s) } } ``` Session : > > guess > > > 4 > > > + > > > 88 > > > - > > > 66 > > > + > > > 77 > > > - > > > 71 > > > + > > > 73 > > > + > > > 75 > > > = > > > Hard to golf when you start any program with `package main` and a list of imports... [Answer] ## R: 88 characters ``` r=sample(1:100,1);i=scan(n=1);while(i!=r){cat(ifelse(i<r,"+","-"));i=scan(n=1)};cat("=") ``` Ex: ``` > r=sample(1:100,1);i=scan(n=1);while(i!=r){cat(ifelse(i<r,"+","-"));i=scan(n=1)};cat("=") 1: 23 Read 1 item + 1: 46 Read 1 item - 1: 35 Read 1 item - 1: 31 Read 1 item - 1: 28 Read 1 item + 1: 30 Read 1 item - 1: 29 Read 1 item = > ``` [Answer] ## PHP: 95 91 87 73 71 65 chars ``` <?php $n=rand(1,100);while(@$g!=$n){$g=trim(fgets(STDIN));echo$g==$n?'=':($g>$n?'-':'+')."\n";} <? for($n=rand(1,100);@$g!=$n?$g=trim(fgets(STDIN)):0;)echo$g==$n?'=':($g>$n?'-':'+')."\n"; <? for($n=rand(1,100);$n!=$g=trim(fgets(STDIN));print(($g>$n?'-':'+')."\n"));echo"=\n"; <? for($n=rand(1,100);$n!=$g=fgets(STDIN);print(($g>$n?'-':'+')."\n"))?>= <? for($n=rand(1,100);$n!=$g=fgets(STDIN);print($g>$n?'-':'+')."\n")?>= ``` ``` <?for($n=rand(1,100);$n!=$g=fgets(STDIN);print$g>$n?"- ":"+ ")?>= ``` [Answer] # C: 86 characters ``` i;main(r){r+=(7*time(0)+3)%100;while(scanf("%d",&i)&&puts(i<r?"+":i>r?"-":"=")&&i-r);} ``` It is well-behaved, implements a simple LCG and compiles under both Clang (Clang is much more picky than GCC) and GCC. [Answer] ## R 70 ``` n=sample(1e2)[1];while(n-(g=scan(n=1)))cat(if(n>g)"+"else"-");cat("=") ``` [Answer] VB.net 146 `Dim r,g As Integer:Dim s As String:r=New Random().Next(1,100):Do Until g=r:g=InputBox(s):If g<r Then s="+" Else If r=g Then s="-" Else s="=" Loop` [Answer] # Tcl, 96 chars ``` set n [expr int(rand()*100)+1];while {[gets stdin g]&&$g!=$n} {puts [expr $g<$n?"+":"-"]};puts = ``` Ok, and now guessing a real number (91 chars): ``` set n [expr rand()*100+1];while {[gets stdin g]&&$g!=$n} {puts [expr $g<$n?"+":"-"]};puts = ``` And here a small script to test this: (Solver) ``` set fd [open "| /usr/local/bin/tclsh hilo.tcl" RDWR] fconfigure $fd -buffering none lassign 0\ 100 + - while 1 { puts "-> [set new [expr {(${-} - ${+}) / 2. + ${+}}]]" puts $fd $new gets $fd in puts "<- $in" if {$in in {+ -}} {set $in $new} break } ``` Change the `2.` to `2` for integers. [Answer] Javascript (75 **74** chars): ``` for(n=1+Math.random(a=alert)\*100>>0;(g=+prompt())-n;)a('+-'[+(g>n)]);a('=') for(n=1+Math.random(a=alert)*100>>0;(g=+prompt())-n;)a(n>g?'+':'-');a('=') ``` Numbers are actually random [Answer] # J: 64 characters ``` r=.>:?100 while.(t=.{&'<=>'>:*-&r".(1!:1)1)~:'='do.t(1!:2)2 end.t ``` Doing I/O in J is sort of bulky compared to the rest of the language. [Answer] **vbScript 115 110** Randomize:dim n,r,s:r=(Int)((100\*Rnd+1)\*2):do until(r=n\*2):n=inputbox(s):If(n\*2>r)Then:s="-":else:s="+":end if:loop ``` Randomize:dim n,r,s:r=Int(100*Rnd+1)*2:do until r=n*2:n=inputbox(s):If(n*2>r)Then:s="-":else:s="+":end if:loop ``` [Answer] **Mathematica 66** ``` n=RandomInteger@100;For[,(i=Input[])!=n,Print@If[n>i,"+","-"]];"=" ``` [Answer] ## GWBASIC, 104 ``` 1 RANDOMIZE TIMER:Z=INT(RND*100)+1:WHILE Q<>Z:INPUT Q:IF Q<Z THEN ?"+" ELSE IF Q>Z THEN ?"-" 2 WEND:?"=" ``` (just because I can) [Answer] ## vba, 95 (immediate window) ``` randomize:z=int(rnd()*100)+1:while q<>z:q=cint(inputbox(q)):?iif(q<z,"+",iif(q>z,"-","=")):wend ``` ]
[Question] [ Given an input value \$n\$, construct an array of \$n\$ random 128 bit (unsigned) integers. The integers should be uniformly random. Your code can use any in built random number generation function it has or you can implement your own. Clearly this challenge is harder (and more fun) in lower level languages. [Answer] # x86-64 machine code, 10 bytes Fortunately, there is a built-in RNG. Requires the RDRAND instruction. ``` 00000000: c1e1 020f c7f0 abe2 fac3 .......... ``` Disassembled: ``` shl ecx, 2 label: rdrand eax stosd loop label ret ``` Outputs to a pre-allocated buffer in `rdi`. `n` is passed in `ecx` (arrays with 2^30 elements and more are not supported). [Try it online!](https://tio.run/##ZVLBTuMwED3HXzHLCpSSNKQsWqFttjf2uh@AqspxnMaVY0e2AxGIby8zDiAoJ3vezHvzZuya@@54FDzABurCQ1XB3f9/zHHT2P4PA99pkGLK4ZqB5rXUiIFrKA@STxj4YH2DSWuHuYI5GRjba1tzDbPQ7tHxYZCOfQ1Rq7cPs770isGhH94YjFzMtngh3m39VEbosZFQ@dAoE4puc4LZb5BWNWFyCtIZeLCqOTGV7nYjaq2ub3fhEgJ3exlyQATMYs0iYXAYfq6DacGeWSI67sCM/f2vcrtmCXEO8BdKurfpj2kRw1Uea8ot3m9uMffYKS1TlEhQI6HcIcsoO8E5rErI5rJkgitkk9rLO@kAy@UGSqQmwxiofxr5W7T6gaxKjF4Y2em5Mmn0GgdagxfctOnZeXOWwwUNmHwZvx5b9NFzra1IzaVXT9K2nydfEOVkgUjK47KS1rqUGqm4BTwq6qmyLBqOW8TiexXttk5KCqNZel7DfQ/LFqRuf9/Qd2R7IeL714VlxRUv7BjwL1S4lOPxFQ "Bash – Try It Online") (a helper function is needed because of the unusual calling convention) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ƛ₇ƛ₀℅;B ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%E2%82%87%C6%9B%E2%82%80%E2%84%85%3BB&inputs=5&header=&footer=) ``` ƛ # Map... ₇ƛ ; # Map 128 to... ₀℅ # Random choice from digits of 10 B # Convert to base 10 ``` Or if it's allowed not to complete within the lifetime of the universe, 5 bytes: ``` ƛ₇Eʁ℅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%E2%82%87E%CA%81%E2%84%85&inputs=5&header=&footer=) ``` ƛ # Map... ₇E # 2 ** 128 ʁ # Range (0...x) ℅ # Choose a random item ``` It's trying to generate a 2128-item array, do you think it's gonna finish any time soon? [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~72~~ 70 bytes *Saved 2 bytes thanks to [@RedwolfPrograms](https://codegolf.stackexchange.com/users/79857/redwolf-programs)* The helper function `g` builds a 128-bit integer, one bit at a time. This seems a bit long... ``` n=>Array(n).fill(128n).map(g=k=>k--&&BigInt(Math.random()<.5)|2n*g(k)) ``` [Try it online!](https://tio.run/##DchBCoMwEADA38huIQEthR6MoDcPfcSiJo2JuxJDQfDvqbdhVvrRMSW/Z8UyL8WawqbrU6ITGLX1MULdvG9utIMzwXRBqaoavBs5w4fyVyfiWTbAVr/wavjhICCWSfiQuOgoDiw87/kD "JavaScript (Node.js) – Try It Online") [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~57~~ 37 bytes ``` &'wa+0> #;\1-:9j;+1?;#*2\_$.1-:!#@_1j ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XUy9P1DawU1C2jjHUtbLMstY2tLdW1jKKiVfRAwooKjvEG2b9/2@sAAA "Befunge-98 (PyFunge) – Try It Online") Note that the input has to have a trailing space because of a bug in the interpreter. The part generating a random 128-bit number bit by bit is explained below: ``` 'wa+0> #;\1-:9j;+1?;#*2\_\.@ ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XL0/UNrBTULaOMdS1ssyy1ja0t1bWMoqJj9Fz@P8fAA "Befunge-98 (PyFunge) – Try It Online") ``` 'wa+ push loop counter, initially 129 0 push initial number 0 > if the IP is coming from the right, turn it around #; # skips the next instruction \ swap to the loop counter 1-: decrement it and push an additional copy 9j skip over the next 9 instructions _ if the loop counter is 0, go right: \. swap to the number and print it @ terminate the execution _ else, go right: *2\ swap to the number and multiply by 2 ? go into a random direction, if up or down is selected, ? gets executed again ; ; if right is selected, jump to the next semicolon and continue with the next iteration > #; ;+1 if left, increment the number and go to the next iteration ``` Animation with 9 instead of 128 bits: [![enter image description here](https://i.stack.imgur.com/OsC6h.gif)](https://i.stack.imgur.com/OsC6h.gif) [Answer] # [Julia 1.0](http://julialang.org/), 18 bytes ``` !n=rand(UInt128,n) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/XzHPtigxL0Uj1DOvxNDIQidP87@ioYGBQo2dQkpmcUFOYuV/AA "Julia 1.0 – Try It Online") sorry, ~~boring~~ useful built-in [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~68~~ 42 bytes ``` f(n,a)char*a;{for(n*=16;n--;)a[n]=rand();} ``` [Try it online!](https://tio.run/##jVRdT9swFH3Pr7gKQrJDSRMWWlAoEmIIVeJLBbRpgKKQOGAtdZDtABvqb@@undImg0nzgxvde87xucdpss2HLJvPCyJ6Kc0eU@ml8VtRSSK8UTiIxeZmTNMbcTeSqcgJjWfzNS6yss4Z7Cmd88p/3HcAV6dc8ntTX9W40PrXE1Om6vQ9x/PgWnHxAHmV1VMmNMvh@PAQDAhqofiDwEqSIC/c2gEulGZpDlWBzRXFyFT3qiqZyrBg2TkrQKRThuS6YSfaB/hWyZ8KXrh@tOdE/tAP4b7WICptZJpi6G8BMdUWGV7@piKKQiXgNM3g/BK@QxigXOQ7Xt95t/BxhqVgbBIAu67HZ1eDKDk9QI2dKBoMoygYfhkGu9vb4SDcvj45AdRcQ0EuGFyEQdIw8MSPy6ABUDrchd9MVky1yUct8q6zLF9eTcZnx@MfRxPySs01wuuyd3WeNO2m1cU6jtKp5hnejYYniXtSm/FqskrOFKjzZt8PA5NZ3DwXQEwP9lsJUNtqwGatZEq8evOuwMgqQr@VRNzBo5IG0DLlpSEs8Ouf4mWG/Y7xxTm0g9lYgArirvtuK5NVoBQuJuN6EPWWJy8kZnZnpWKfzGa9Imvh8jNj5kx3KY5bR1cyXUthQ505jsl3mnJBniue29CV/cuC5lNGIAAKht1@sVMpb8LgbvQWzLBTkDDoYcmg8AMAxF4ZHwUx3wuDeGODUzNAJzGjwO@sq6daK@K65hntNfYB/edub3Jw9tXecOO@ZZ4E1JrHL8K7fyD0f71HK@vRv5xH1vi7bxNoWb7eCjA/cCvcXjNCbznJzOvP/wA "C (gcc) – Try It Online") * takes an 0 array and the number requested as input * the array I taken as \*char to be manipulated byte by byte so that we set every 8bit to rand() which is RAND\_MAX e.g. At least 32767 and thus guaranteed to affect every bit * numbers printed as decimal thanks to [this good answer on the topic](https://stackoverflow.com/a/11660651/7699953) I copy-pasted-adapted [Answer] # [Python 2](https://docs.python.org/2/) **~~54~~ 53 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjexQKMoMS8FiNNTdaJNtLTMTGK18jS50orycxVAMkAqM7cgv6hE639BUWZeiUKahqnmfwA "Python 2 – Try It Online") ``` lambda n:map(randrange,[4**64]*n) from random import* ``` **69 bytes**: [Try it online!](https://tio.run/##DctBCoAgEADAe6/YWxohFNQh6CXVwVJpIXdFDer11twnvPlk6oub13JpvxsNNC1IWXBSd9Rk2AuUytLBxor6tE8tW5SOIyAgLd24NbRV6APHDJxKiP8GJwZZPg "Python 2 – Try It Online") ``` lambda n:[int(os.urandom(i).encode('hex'),i)for i in[16]*n] import os ``` --- # [Python 3](https://docs.python.org/3/) **54 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKlorN7FAoygxLyUps6RYJ9rQyCJWK08zliutKD9XoTg1uSi1pFghM7cgv6hE639BUWZeiUaahqmm5n8A "Python 3 – Try It Online") ``` lambda n:[*map(randbits,[128]*n)] from secrets import* ``` **~~57~~ 56 bytes**: [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKlorN7FAoygxLwWI01N1ok20tMxMYrXyNGO50orycxVAUkAqM7cgv6hE639BUWZeiUaahqmm5n8A "Python 3 – Try It Online") ``` lambda n:[*map(randrange,[4**64]*n)] from random import* ``` **70 bytes**: [Try it online!](https://tio.run/##DctBCoAgEADAe6/wlkYEEXUIeklJKGUt5K6sdvD11twn5HQTDsUtW3mMt4cROK@AqXNMfrc5nVFS7F42eJCXoNrawlUrRyxAAK79pBvUFfhAnATFEvjv0slRqfIB "Python 3 – Try It Online") ``` lambda n:[int.from_bytes(os.urandom(i),'big')for i in[16]*n] import os ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~57 bytes~~ 41 bytes ``` @(1..$n|%{(Random 1.0)*("2*"*128+1|iex)}) ``` **Explanation:** `1..$n` enumerates integers from 1 to $n, `%` is an alias to `ForEach-Object`, `Random` decimal between 0 and 1.0, multiply by 2^128 through [this](https://codegolf.stackexchange.com/a/15368) clever obfuscation. `@()` encapsulates the result in an array, save 3 bytes if a actual array isn't needed. [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmdr@t9Bw1BPTyWvRrVaIygxLyU/V8FQz0BTS0PJSEtJy9DIQtuwJjO1QrNW8/9/AA "PowerShell – Try It Online") **Original (57 bytes):** ``` @(1..$n|%{(Get-Random -Mi 0.0 -Ma 1)*[Math]::Pow(2,128)}) ``` [Answer] # [Factor](https://factorcode.org/), ~~33~~ 31 bytes ``` [ [ 128 2^ random ] replicate ] ``` [Try it online!](https://tio.run/##NcrBCkBAEAbgu6f4n0BRSjyAXFzkpFXTGpG11hgHT79OvvO3kNVT4tC3XVNhZ/HscJCuCMKqb5DNK4T8fB64@XrYW75RJ0kRR4zI8hL59AcD4eA2S8ow0ZJzSOMH "Factor – Try It Online") * `replicate` Create a sequence given a number of elements and a generating quotation. * `128 2^` 2128 * `random` Return a uniformly random number (via Factor's default Mersenne Twister PRNG) from 0 to whatever number is on top of the data stack minus one. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~25~~ 24 bytes *–1 byte thanks to Bubbler!* ``` RandomInteger[4^64-1,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PygxLyU/1zOvJDU9tSjaJM7MRNdQRzlW7X9AUWZeSXRatGls7H8A "Wolfram Language (Mathematica) – Try It Online") I wrote this and even I can't find anything interesting to say about it [Answer] # Excel, 62 bytes ``` =MID(CONCAT((RANDARRAY(A1*128)>0.5)*1),SEQUENCE(A1,,,128),128) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnFlcN6djVEpskqbo?e=YNT6va) Excel doesn't handle 128 bit integers. What this returns is technically n strings of 128 random 1s and 0s, which could be interpreted as n 128 bit binary integers. If Excel did handle 128 bit integers, then answer would be `=RANDARRAY(A1,,,2^128-1,1)` which is 26 bytes. [Answer] # [R](https://www.r-project.org/), ~~24~~ 22 bytes *Edit: -1 byte thanks to pajonk* ``` runif(scan())*4^64%/%1 ``` [Try it online!](https://tio.run/##K/r/v6g0LzNNozg5MU9DU1PLJM7MRFVf1fC/ocF/AA "R – Try It Online") Output is an integer uniformly selected from the range `0`...`2^128-1`. [R](https://www.r-project.org/) does not natively support 128-bit inteters, so the data type of the output is a floating-point representation ([click here](https://tio.run/##RYzNCsIwEITvPsVSKSRSfwrFi/RVhFi7ZSHdhOwGKeKzx3jyNsw336SCI2aelAIbsm@ZHP8LSzfYg86i8EouxjmVlJnQ/GbG2sNwvw7tue3LZyeV@82g6S@2k5iIFTtcdWzaEza2/jxJoncbOO9rXkgFAgL64JR4OcZQFeC8PuYkUL4) for a TIO link that dispays all the digits, instead of displaying in scientific notation). Note though that although 128-bit numbers can be represented using floating-point variables, [rounding inaccuracies can occur](https://stackoverflow.com/a/1848762/13432336) when more than 53 bits are required. If floating point output (with its associated rounding inaccuracies) isn't Ok, we can output the exact value in the form of a vector of binary digits for **[35 bytes](https://tio.run/##K/r/PyexoCCnUsPQqjg5MU9DU6c4MbcgJ1WnwtbAylCn2NbQyELzv6HBfwA)** (or flattened into a string of bits for [41 bytes](https://tio.run/##K/r/v7wosyRVozgxtyAnVcPAylDH0MhCqzg5MU9DUydEUwfM19FRUtL8b2jwHwA)). If neither floating point nor binary output are Ok, then base-[R](https://www.r-project.org/) will struggle a bit, but we can still manage by constructing string of random `0`-`9` digits (so including leading zeros), and checking that its lexicographically smaller than `"340282366920938463463374607431768211456"`, for a whopping **~~117~~ [113 bytes](https://tio.run/##DchBCoMwEADAr4inXchhk003iWIfUfqBYFMMtCqmxYP07akwp9lqfS4b5CbPje7KGGdALNOyw7FP@ZUA4nBLj@@YYI3lk0iV@F7Ppy4oDuqOiNeWLRlvWCQYCuyt8ImdFXKWtRNvtLYXaZH6@MOqqf4B)**: `for(i in 1:scan())show({while((a=Reduce(paste0,sample(0:9,39,T)))>"340282366920938463463374607431768211456")0;a})` [Answer] # JavaScript (Browser), 99 bytes ``` n=>crypto.getRandomValues(a=new BigUint64Array(n*2)).reduce((r,v,i)=>i&1?[v<<64n|a[i^1],...r]:r,[]) ``` This feature is introduced eailer this month by [this post](https://github.com/w3c/webcrypto/issues/255). And it currently requires a recent version of Firefox / Chromium Nightly build to run. It is a sad story that words `crypto`, `getRandomValues`, `BigUint64Array` are too long for golfing. ``` const f= n=>crypto.getRandomValues(a=new BigUint64Array(n*2)).reduce((r,v,i)=>i&1?[v<<64n|a[i^1],...r]:r,[]) { let len = 5; let arr = f(len); for (let i = 0; i < arr.length; i++) { console.log(arr[i] + '') } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` LεžyoÝΩ ``` No TIO, since it won't finish anyway. **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] ε # Map each to: žy # Push builtin 128 o # Pop and push 2 to the power this 128 Ý # Pop and push a list in the range [0, 2^128] Ω # Pop and push a random item from this list # (after which the result is output implicitly) ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` É♣ów] ``` [Try it online.](https://tio.run/##y00syUjPz0n7//9w56OZiw9vLo/9/98UAA) **Explanation:** ``` É # Loop the (implicit) input amount of times, # using the following three characters as inner code-block: ♣ # Push builtin 128 ó # Pop and push 2**128 w # Pop and push a random integer in the range [0,2**128) ] # After the loop, wrap the entire stack into an array # (after which the entire stack is output implicitly as result) ``` [Answer] # Ruby, 29 Bytes ``` ->n{n.times.map{rand 2**128}} ``` # [Try It Online](https://tio.run/##KypNqvz/v0BB1y6vOk@vJDM3tVgvN7GguigxL0XBSEvL0MiitlYvOTEnRyM9taRYryQ/PlPz/39jAA) [Answer] # [Raku](http://raku.org/), 17 bytes ``` {roll ^4**64: $_} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uig/J0chzkRLy8zESkElvva/XnFipUJafpFCmoahgeZ/AA "Perl 6 – Try It Online") `^4**64` is the range of numbers [0, 2¹²⁸). The `roll` method returns randomly selected numbers from that range, in the quantity of `$_`, the input argument. [Answer] # [Scala](http://www.scala-lang.org/), 49 bytes ``` def f(n:Int)=Seq.fill(n)(BigInt(128,util.Random)) ``` [Try it online!](https://tio.run/##PcmxCsJADIDh3afImIAUWhBEqKCbg0t9gtjLSSRNT3uCID77eZPbz/cvIxuX@XqXMcOZ1UHeWTwscEjpU4JEiOi7k2fqL/JoopqhEx71Vg3bbrt@ZbVmYA/zRFQithuCiROCeq4f@j2kZ23zPxHQ6lt@ "Scala – Try It Online") [Answer] # [Racket](https://racket-lang.org/) `srfi/27`, 45 bytes ``` (for/list([i n])(*(random-real)(expt 2 128))) ``` [Try it online!](https://tio.run/##HcfBCkBAEADQu6@YcplRkr3gW@SwMavJGoxV/n6Vd3vm541TLqPXFexPgcbXI8ZwW5DGdVTgwkGUQWGgjOGwJsqdcBTQibBC87oce23sIyG/ZwIHreuJKOcP "Racket – Try It Online") depends on `srfi/27` package [Answer] # [C (gcc)](https://gcc.gnu.org/), 59 bytes ``` f(n){int*a=malloc(n*16),i=0;for(;i<n*4;)a[i++]=rand();n=a;} ``` [Try it online!](https://tio.run/##bVJha4MwEP3urzgKhUQd066MgfWXdEWCJt1BjSWJY1vpb3cXo3UdvS8h757v3jtTPx3rehgU0/yC2sWibMXp1NVMx/krT7HMCtUZVuBOx9uCiz0myaE0QjeMF7oUxXVw32fZSAW9tnjUsoGqIqV88wZ9OIso@uywma@V6yrrTIVOGjZhoFOoP4SJoetdCgSCQmOd53C4REBlnXBYj71OKSsdlJAVYwsVsIU/Qr4e0TSUdF84Rrre6NB/ZFDDM@RZGnxlPBDpsg/itA3S17AmEiSQfb3QrGsUhTD3gkvYOdItMmnUYe8Wf2SnmO/wFLbzxIfWJlf5xAlRPDZa8ItqBWp2W@D42xy2kmV8@saTMAVvYJPdjYpBEKiYm5j0DIDhuExA2IGjI0lm7SWNJcq/3PRqDpOKr7OhtmKr9aYh7tq@61XqTdg/HGWkZDNwjW6QuM/qlz38Ag "C (gcc) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 56 bytes ``` lambda n:eval('randint(0,4**64),'*n) from random import* ``` [Try it online!](https://tio.run/##FYxBCoAgEEX3nWJ2OeLCKCKCbtLGqGwgRxkk6PSWf/PgPfjpzVfkfkpS/LKW24Vtd8Dz8bhbteJ4J87KmkHrcUDTasbmlBigph8UUpSsyxkFCIir94fqTGdxbuBfkvrgFSGWDw "Python 3.8 (pre-release) – Try It Online") Doesn't work for `n=0`. [Answer] # [Rust](https://rust-lang.org) with [`rand`](https://crates.io/crates/rand), 59 bytes ``` |n|->Vec<u128>{vec![0;n].iter().map(|_|random()).collect()} ``` [Try it on Rust Playground!](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6baa193bba2a72891f76985853c5b701) `vec![0;n]` is a built-in macro that generates a `Vec` of length `n` with all values initialized to `0`. While this macro does accept an expression as the first argument, unfortunately it only evaluates it once, not for each item. Otherwise everything from `.iter()` to the end wouldn't be needed. I was excited when I realised Rust has native support for 128-bit integer primitives through `i128` and `u128`, but then I realised Rust's stdlib no longer includes RNG features, meaning we need the [`rand`](https://crates.io/crates/rand) crate to handle RNG. `random()` is from the `rand` crate. Specifically `random()` is an alias for `thread_rng().gen()` and generates a random value of the given, or inferred type. Thankfully, rust's type inference is good enough that, even though we only specify `u128` in the return type of the closure, it figures it out and calls `random::<u128>()` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Ø⁷2*X’) ``` [Try it online!](https://tio.run/##y0rNyan8///wjEeN2420Ih41zNT8//@/KQA "Jelly – Try It Online") A monadic link taking a single argument and returning a list of random 128-bit unsigned integers of that length. ## Explanation ``` ) | For each value from 1..n Ø⁷ | 128 2* | 2 ** that X | Random Int from 1 to that ’ | Subtract 1 ``` If the output can be from 1 to \$2^{128}\$ rather than 0 to \$2^{128} - 1\$, which for practical purposes is almost the same given how unlikely it is to generate the extremes, I can shave off a byte. [Answer] # [Perl 5](https://www.perl.org/), 51 bytes ``` sub{join('',map chr rand 256,1..16*pop)=~/.{16}/sg} ``` [Try it online!](https://tio.run/##bZDfaoMwFIfvfYozJ6u2rjaFyqhklN3tYm8wEK2JnqGJJClDuu7VXaIdbGyBhPz5fl9O0jPV7sZuCDgd9ak8v0kU4WIRd0UPx0aBKkQF210ak/WapMte9hH9TNZnkl4SXV/G7KQZvBSm2e@fsH4WJvO6AQJBdYPcZPBfu4Wj7DonblEwEKeOKTxCoWo7E8YJDoVSxZBLnoscyfYBKNwFPLRiiLKrZEJAcrdpkfsSDaAwrGZKe1wqcIVM4fCvL4Kz5zSOKZH@fMH9o2Dv4SbKvoFDORimqfsSqaoYdN@iSZJ4ks@Uc9i@tD@1CnJwt8@p@bhXtjDwK6zR6D34MbRM1KYJbSaKwYcPZ7AjSWGK2ffOef@X4FVc1xUy2KxmBJBf4RtK0sy7jCPZfQE "Perl 5 – Try It Online") Creates n random 128 bit integers. Or n strings of 16 random 8 bit chars. How to print the array elements as decimal numbers can be seen by clicking the "Try it online" link. [Answer] # [Japt](https://github.com/ETHproductions/japt), 7 bytes ``` ÇMq2pIÑ Ç // Create the range [0..U) where U is the input, then map each value to Mq // a random non-negative integer smaller than 2 // 2 p // to the power of IÑ // 64 * 2. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=x01xMnBJ0Q==&input=NQ==) [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~20~~ 19 bytes ``` ri{L{2mr+}128*2bN}* ``` [Try it online!](https://tio.run/##S85KzP3/vyiz2qDaMNfGKLdIu9bQyELLr1br/39DAwA "CJam – Try It Online") # [CJam](https://sourceforge.net/p/cjam), ~~27~~ 24 bytes (Old method) ``` ri{8,{G*YG#(mr\m<}%:+N}* ``` [Try it online!](https://tio.run/##S85KzP3/vyiz2kKn2l0r0l1ZI7coJtemVtVK269W6/9/QwMA "CJam – Try It Online") **Edit:** had a better idea using the "repeat N times" operator. Saved 3 characters. **Edit 2:** tried a completely new algorithm. Saved 4 characters. **Edit 3:** went for the string manipulation side of things. Saved 1 character. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes ``` IEN‽X²¦¹²⁸ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQMMzr6C0xK80Nym1SENTRyEoMS8lP1cjIL8cyDfSUTA0stAEAev//03/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input integer E Map over implicit range X²¦¹²⁸ 2¹²⁸ ‽ Random integer (0-indexed) I Cast to string Implicitly print ``` ]
[Question] [ The [generalised harmonic number](https://en.wikipedia.org/wiki/Harmonic_number#Generalized_harmonic_numbers) of order \$m\$ of \$n\$ is $$H\_{n,m} = \sum^n\_{k=1} \frac 1 {k^m}$$ In this challenge, we'll be considering the generalised harmonic numbers of order \$2\$: $$H\_{n,2} = \sum^n\_{k=1} \frac 1 {k^2}$$ This sequence begins \$1, \frac 5 4, \frac {49} {36}, \frac {205} {144}, \dots\$ and converges to \$\frac {\pi^2} 6\$ as \$n \to \infty\$. However, we will only be considering the *numerators* of this sequence, which forms another sequence known as the Wolstenholme numbers ([A007406](https://oeis.org/A007406)): ``` 1, 5, 49, 205, 5269, 5369, 266681, 1077749, 9778141, ... ``` You are to take a positive integer \$x\$ as input. \$x\$ is guaranteed to be a Wolstenholme number. You should output the next term in the sequence of Wolstenholme numbers, i.e. given the numerator of \$H\_{n,2}\$, output the numerator of \$H\_{n+1,2}\$ You may input and output in [any convenient format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Your program should not fail due to floating point errors, meaning that attempts that calculate via the generalised harmonic numbers will be invalid if not using rational numbers. Your program should work *theoretically* for any valid input, but it is acceptable to fail for inputs that may be outside your language's integer maximum. You may assume that no element is repeated in the sequence. If it turns out that there are any duplicate values in the Wolstenholme numbers sequence, any and all behaviour is acceptable when passed such values as input. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins ## Test cases ``` x -> out 1 -> 5 5 -> 49 49 -> 205 205 -> 5269 5269 -> 5369 5369 -> 266681 266681 -> 1077749 1077749 -> 9778141 9778141 -> 1968329 1968329 -> 239437889 239437889 -> 240505109 ``` [Answer] # [J](http://jsoftware.com/), 39 35 30 28 bytes ``` (]{~1+i.~)1*.[:+/\_2^~1+i.,] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NWKr6wy1M/XqNA219KKttPVj4o3iwCI6sf81uVKTM/IV0hQMK2AsUzjLxBLONDIwrfgPAA "J – Try It Online") -5 thanks to Bubbler's observation that the numerator is the LCM of the fraction and 1. -2 thanks to Bubbler for a transformation. Note: The approach below relies on the assumption that every Wolstenholme number is greater than or equal its index, which was kindly [proved by Greg Martin](https://math.stackexchange.com/a/4116530/20688). * `[:+/\_2^~1+i.,]` Generates the sequence up to `n+1`, where n is the input: Scan sum `+/\` of 1 over `1%` the square of `*:` one plus `1...+` the integers from 0 to the input `i.@>:`. * `1*.` Numerators only. * `(]{~1+i.~)` Finds index of the input in previous result, adds 1, and plucks from previous result. [Answer] # JavaScript (ES6), 98 bytes ``` f=(n,i=0)=>(g=(p=!(j=k=++i),q=1)=>j?g(p,q*j*j--):k?g(x=p+q/k/k--,q):q?g(q,p%q):x/p)()-n?f(n,i):g() ``` [Try it online!](https://tio.run/##dc/dasMgAIbh811FdlDQRqfG/4DrtZSuCTEl0XWM3n1mSVKy1XmkLw8f6I/fx@vpswtfeBg/ztPUODCgzlHo3kHrQHCvwLvelWUHUXQsZX9oQUBx7/ceY1j36XlzoYykJz3GKMI6phRR2KXrjQQIIB4OzX0W1i2A02kcruPl/HYZW9CAYjkMwoKQ9VXIlzyTv5iweSbsllU0v5b6hslKZdfufcv4P4xvWKWUMuyZzX1ljGqtM19Y@sqs1oaJ57WlP9asMrzKrM19ZhW3gmtj/rJHX5igkkpG7fQD "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: n, // n = input i = 0 // i = counter, initialized to 0 ) => // ( g = ( // g is a recursive function which computes the // next Wolstenholme number in 3 steps p = !(j = k = ++i), // increment i and start with j = k = i, p = 0 q = 1 // and q = 1 ) => // j ? // [step 1] while j is not equal to 0: g(p, q * j * j--) // multiply q by j² and decrement j : // then: k ? // [step 2] while k is not equal to 0: g(x = p + q / k / k--, q) // add q / k² to p, copy p to x and decrement k : // then: q ? // [step 3] while q is not equal to 0: g(q, p % q) // copy q to p and p % q to q : // then: // p is now equal to the GCD of x and the final // value of q at the end of the 1st step x / p // return x / p )() // initial call to g - n ? // if it's not equal to n: f(n, i) // try again until it is : // else: g() // return the next Wolstenholme number ``` [Answer] # [Haskell](https://www.haskell.org/), ~~78~~… 76 bytes * -2 bytes thanks to [kops](https://codegolf.stackexchange.com/users/101474/kops). ``` f n=snd(span(/=n)$head.words.show<$>scanl1(\i j->i+1/j^2::Rational)[1..])!!1 ``` The relevant function is `f`, which takes `n` as a string of digits, and returns the next Wolstenholme number as a string of digits. [Try it online!](https://tio.run/##Tc3dboMgAIbhc66CJj3QDK2A8tNUr2BHO@26hUw76Rw2xaR69c4fSsfRkzcfUCv7UzXNOJ6hya0pA3tVJtjlJtzWlSrje3srbWzr9n7YFvZLmQYH7xpeokK/4N3lg@z3b6rTrVFNeMRxfAo3Gzz@Km3ysgXw2KNPNJwO0fLO9MR31b1qUwF4vWnTBWfY5/mAejQBDSGA880RuoNhVDwMM@D1L6cSeD0zSR7rST5nhLn1rGemPlOfCWNMYOC1ZpxwzpcvndYsORc4nddObi2ZoGRZr5ozoTKlXAgJvJacJlmS4UT@AQ "Haskell – Try It Online") [Answer] # [Raku](http://raku.org/), 54 bytes ``` {first *>$_,map *.nude[0],[\+] map *⁻²,1.FatRat..*} ``` [Try it online!](https://tio.run/##HYlNCoJAAEav8iHSwmRwZpw/SJcdoK2JDOSAkCVqCxEXXaltu47SRaahzYP33tCOV@n7BTuHwq@uG6cZSRk3aW8HJOT2uLRVVqfVeV/jn77P9@eVUnK088nOhCSbn@yCKG5QlFgd4maL4O4jDhQCuQHLBASTBoIHMCmlpqCZUipMo5SmeXAjNWdhc5NzpbUp/Q8 "Perl 6 – Try It Online") * `[\+] map *⁻², 1.FatRat .. *` is the harmonic sequence. The members are of type `FatRat`, a "fat rational" type that does not degrade to floating point. (I could skip the `.FatRat` for seven bytes and use ordinary rationals, which give the correct answer for all of the provided test cases, but the problem states that the solution should theoretically valid for any input, so...) * `map *.nude[0]` maps that sequence into its numerators. `*.numerator` would be the more straightforward way to do this, but it's shorter to use `.nude` which returns the numerator and denominator as a pair. * `first * > $_` finds the first element of the numerator sequence that exceeds the function argument `$_`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~30~~ 26 bytes ``` 0`@:Utptb/swyZd/ht1_)G-]0) ``` [**Try it online!**](https://tio.run/##y00syfn/3yDBwSq0pKAkSb@4vDIqRT@jxDBe01031kDz/38jY0sTY3MLC0sA "MATL – Try It Online") ### Explanation ``` 0 % Push 0. This initiallizes the array of numerators ` % Do...while @:U % Push [1, 2, 4, ..., n^2] where n is iteration index tp % Duplicate, product. Gives denominator (not reduced) tb % Duplicate, bubble up in stack. Moves copy of [1, 2, 4, ..., n^2] to top /s % Divide element-wise and sum. Gives numerator (not reduced) wyZd % Swap, copy from below, GCD / % Divide. This gives the reduced numerator h % Concatenate to vecor of previos numerators t1_) % Duplicate, get second-to last entry G- % Subtract input ] % End. A new iteration is run if top of the stack is non-zero 0) % Get last entry. Implicit display ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ←t↓≠⁰mois∫m□İ\ ``` [Try it online!](https://tio.run/##ASUA2v9odXNr///ihpB04oaT4omg4oGwbW9pc@KIq23ilqHEsFz///8x "Husk – Try It Online") or [Verify all testcases](https://tio.run/##yygtzv4fkqsREqKuoAmkDy1PLdbQVlJ41DZJQan4UVOjpub/R20TSh61TX7UueBR44bc/MziRx2rcx9NW3hkQ8z///@jDXVMdUwsdYwMTHVMjcwsdUyNgYSRmZmZhaGOoYG5uTlQ0tLc3MLQBMi3NLMwNgJKG1uaGJtbWFjGAgA "Husk – Try It Online") ## Explanation ``` ←t↓≠⁰mois∫m□İ\ İ\ infinite list [1,1/2,1/3,... m□ map to squares ∫ cumulative sum mo map to is first integer in string representation (gets numerator) ↓ drop elements till ≠⁰ input is reached t remove first item ← take the first item ``` [Answer] # [R](https://www.r-project.org/), 112 bytes ``` x=scan();while({d=prod((1:T)^2);n=sum(d/(1:T)^2);i=1;while((i=i+1)<n)while(!n%%i&!d%%i)n=n/i;x!=F}){T=T+1;F=n};n ``` [Try it online!](https://tio.run/##vY/NasMwEITvegqZkqIlDqnc2jRR9@on8LnFWAoR2CsjycTF@Nldlf5ceu/lm9llDjN@22YMXUsC1O1qeyMWjaN3Wgh5buC1AEUYpkHo4@/DovzOCot2L@GF4OvOaLez95lOBEI6WjVnWK@wNNjspaqRVkVb8VAy5gfRgEqsgd1xbw7aXCwZ3gZ@maiL1hGPjvspiQmRd20w4czIzPHt5voQDV1dPxhkP3Exw8L@aQNbGQvtOPbvohMy52XOn045T8uSL6pky8dPFlVVPUvI/9SG7QM "R – Try It Online") **How?** ``` x=scan(); # get previous wolstenholme number x while({...do this...;x!=F}) # first 'do this', then check if x is equal to F (initially zero) { # 'do this': d=prod((1:T)^2) # denominator d = product of squares of 1..T n=sum(d/(1:T)^2) # numerator n = sum of d/1, d/4, d/9, d/16 ... d/T^2 # n/d is T-th harmonic number of order 2 # but we need to simplify the fraction: i=1;while((i=i+1)<n) # try each i from 2..(n-1): while(!n%%i&!d%%i)n=n/i # if i divides both n and d, divide n by i # at this point, n equals the simplified numerator # which is the T-th wolstenholme number } ){ # if x isn't equal to F yet T=T+1 # increase T F=n # and set F to the last wolstenholme number n } # if we got here, x was equal to F # and we've already updated n to be the next # wolstenholme number n # so we output n. ``` --- A vectorized version is shorter - [98 bytes](https://tio.run/##tY9BS8QwFITv@RUpsvIeVtZUW7Qh1/6C3pZVSpNlA@1LSVK2UvrbazzoxbOXb4ZhDjN@3xcV@o4A5e1qBwOrVpN3GkDULb4XKEmFeQR9/A2s0rVIMR3BnjI6HOx9phPPJ3FGuWSq2XBtVfsgZKNok7QXTyVjfoQWZWKD7I5786jNxZLhXeCXmfpoHfHouJ@TmBB53wUTakZmiR83N4Ro6OqG0Sj2U4cFV/Zvq9nGWOimafiEHkTOy5y/vOU8fUm@qJItn79ZVFX1KjD/MxT3Lw) - but quickly runs-out of memory as it tries to allocate a vector the size of the non-reduced denominator for order-2 harmonic numbers beyond the first 7... [Answer] # [Stax](https://github.com/tomtheisen/stax), 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ┬Z°#¡Lk╢╙°m╕%ºb ``` [Run and debug it](https://staxlang.xyz/#p=c25af823ad4c6bb6d3f86db825a762&i=1%0A5%0A49%0A205%0A5269%0A5369%0A266681%0A1077749%0A9778141%0A1968329%0A239437889&m=2) Reduced from 22 with help from recursive. ## Explanation ``` {iiGx=!w^G}Z{Ju+Fr { w while result is falsy: ii push iteration index twice G GoTo unclosed curly brace } label: Z push a zero under the index { F for 1..i Ju+ square, invert, add return to GoTo r get numerator x=! is it equal to the input? ^ if so, increment G and GoTo label ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes ``` ->x{r=z=1r;1until[z,z+=(r+=1)**-2]*?_=~/^#{x}.+_(\d+)/;$1} ``` [Try it online!](https://tio.run/##FYrtCoIwGEZvZVDEdPPj3eY@kNWFmEkRQlAhS8EUu/W1/Xk4POe46fb1vfXZcV6dXSy4Gqb3@Hg2C12IxY5YSNI0Y2166uyvuOzWectJh893khT1HjY/TOMHNUBRRZEwFLEyQMVkwIrHZVJKHTyUSqlYGKU0iPgYqTmLCTeCK61Nm7@uAz70if8D "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes ``` from fractions import* x=input() k=1 g=0 n=[] while x not in n[:-1]:g+=Fraction(1,k*k);k+=1;n+=[g.numerator] print n[-1] ``` [Try it online!](https://tio.run/##LcxBDoIwEADAe1/RI1AxFhMjkL36iaYHYqA0tbtNXSK@vnLwATPpyythV8qSKcolT0/2hG/pY6LMjdjBY9q4qkUALRxcBIKx4rP61yx3icTSo0QztNoOTsHjP1T6FJpQj0GBHlGBcWfc4pwnpmxFyh75UAcqRfe3@7Xrfw "Python 2 – Try It Online") fixed thanks to Jonathan Allan [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes ``` (k=1;While[(t=Numerator[++k~HarmonicNumber~2])<=#];t)& ``` [Try it online!](https://tio.run/##FYq7CoMwAEV/JVAoioLmnWADjp1Ktw7ikErQoFEI6VTqr6fJcjmce5wOi3E62EnHWcViVbB7LXYzQxHU4@OM1@HwQ1Wt5117d@x2SvZt/InG8qYuYxfKa3x6uwfQ9HPTf2ENaA2IrAFqE1DEElKcFzHGRPphyznPheRcQJKNZAKjnGBJMBdC/mL8Aw "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 61 bytes Uses Ruby's *Rational* type. ``` ->x{w=l=n=k=0r (l=n;k+=1;w+=1/k/k;n=w.numerator)while l!=x n} ``` [Try it online!](https://tio.run/##FYrLCoMwFAX3fkW6a6mvJJoHcvsj4sKC0pKYSqgkRf32NNkMwzljt@cvzAhC8fC7Aw0GFNQ2u0br1B1w5yIqVanOgCvNtkx2/H7szb3eekL6Aj4zZ@hxjtocNTJHpI7SEha1pYmEMSbij2vOeSok5wI3aZFMUJISKhvKhZBDuYzrfvhjRXPvhzP8AQ "Ruby – Try It Online") 73 bytes with integers: ``` ->x{d=1 n=l=k=w=0 (l=n;k+=1;w*=k*k;w+=d;d*=k*k;n=w/w.gcd(d))while l!=x n} ``` [Try it online!](https://tio.run/##JYpNDoIwGAX3nKLuABFpC/1J83kRwkKtqGltiIlpDXD2SuPmZfJm3p/LN44I4uEUZg04c2DBgIcmyy04ZfaAlS/BlEb5PWil/@zAH319v@pcF4V/PO0N2R2EzK2xxxXqKtTKCpFmg46wDTualjDGxOZxwzlPheRc4DY9kglKUkJlS7kQcqhf52lewjKhsQ/DGn8 "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` Nθ≔⁰η≔⁰ζW⁻θζ«≔ηζ⊞υX⊕Lυ²≔Πυε≔Σ÷ευδWδ«≔﹪εκδ≔κε»≔÷Σ÷Πυυεη»Iη ``` [Try it online!](https://tio.run/##VZDLCsIwEEXX9iuynECEUnDlSnQjqBT8gtoMJrRNNY8WlH57TF9qlzNz5sxlcpHpvM5K74/q4ezFVTfU8KTbaGeMvCuIGRGL6hWqVsgSCZylcgaefY@Sd7SaIDFCq9QZAY6RtG6D86hyjRUqixxOqO42zChlJKE9O62muuYut2HCCP71r64KAnuQjeQIyMiwyntiysKHBDN/Dpqy7sFi5uZRMZm7r/wnXp75DzPcQzo@o4tSLZWFfWYsiJDf@yTe@HVTfgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input the target numerator. ``` ≔⁰η≔⁰ζ ``` Initialise the next and current numerator to zero. ``` W⁻θζ« ``` Repeat until the current numerator is the target. ``` ≔ηζ ``` Save the next numerator as the current numerator. ``` ⊞υX⊕Lυ² ``` Add the next square to the predefined empty list. ``` ≔Πυε≔Σ÷ευδ ``` Get the potential denominator and numerator of the sum by multiplying all of the fractions by the product of all the squares so far. ``` Wδ«≔﹪εκδ≔κε» ``` Get the GCD. ``` ≔÷Σ÷Πυυεη ``` Divide the potential numerator by the GCD and save it as the next numerator. ``` »Iη ``` Output the next numerator. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), (16?) 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ²€P©:$S:g¥® 1Ç⁼¥1#Ḣ‘Ç ``` **[Try it online!](https://tio.run/##AS4A0f9qZWxsef//wrLigqxQwqk6JFM6Z8Klwq4KMcOHZsKlMSPhuKLigJjDh////zQ5 "Jelly – Try It Online")** --- I can't prove that \$a(n) \ge n\$, but if so this 16 byter works too: ``` ‘²€P©:$S:g¥®)ḟRḢ ``` --- ### How? ``` ²€P©:$S:g¥® - Link 1, get a(n): integer n ²€ - square each (of [1..n]) $ - last two links as a monad - f(squares): P - product (of the squares) © - (copy to the register for later) : - integer divide by (each square) S - sum ¥® - last two links as a dyad - f(sum, register) g - (sum) gcd (register) : - (sum) integer divided by (that) 1Ç⁼¥1#Ḣ‘Ç - Main Link: integer, a(z) 1 - set L=1 1# - collect the first 1 integer(s) counting up from k=L for which: ¥ - last two links as a dyad - f(k,a(z)) Ç - call Link 1 (k) -> a(k) ⁼ - equals (a(z))? Ḣ - head -> z ‘ - increment -> z+1 Ç - call Link 1 (z+1) -> a(z+1) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~33~~ 30 bytes ``` 1:{›Ȯ?≤|:λ¡²nɾ²/M∑:n¡²ġ/;†^_}Ȯ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=1%3A%7B%E2%80%BA%C8%AE%3F%E2%89%A4%7C%3A%CE%BB%C2%A1%C2%B2n%C9%BE%C2%B2%2FM%E2%88%91%3An%C2%A1%C2%B2%C4%A1%2F%3B%E2%80%A0%5E_%7D%C8%AE&inputs=1077749&header=&footer=) Let us try to maintain a stack with 2 elements \$n\$ and \$f(n)\$ after every step, with \$f(n)\$ being the required numerator. ``` 1: # Pushes [1, 1] to the stack. { # While... › # Increment the first value of stack -> [n+1, f(n)] Ȯ?≤ # While condition: Is the second value of stack less than or equal to the input? | # If yes, then... : # Duplicate the top value of stack. Now it contains [n+1, n+1, f(n)] λ # Lambda function ¡² # Factorial of n, squared. nɾ² # Inclusive range [1, n], and square every number. /M∑ # Divide every time with first argument and return the sum. :n¡²ġ/ # Duplicate this value, then divide it with it's gcd with factorial n, squared ; # Return value. † # Call the function. Now the stack contains [f(n+1), n+1, f(n)] ^ # Reverse stack -> [f(n), n+1, f(n+1)] _ # Pop from stack -> [n+1, f(n+1)] } # End while Ȯ # Print second item of stack. ``` *-3 bytes thanks to Lyxal* [Answer] # [Python 3](https://docs.python.org/3/), 126 bytes ``` from math import* def f(n,i=1,k=1): k*=i*i q=sum(k//j**2for j in range(1,i+1)) x=q/gcd(k,q) return x>n and x or f(n,i+1,k) ``` [Try it online!](https://tio.run/##HcxBDsIgEEDRPaeYJVCSipo0muBdGintlDC0I03q6ZG4/Iv/tm9ZMt1qDZwTpLEsgGnLXLTwU4AgyaCzJjqrngKidqhRwO4@R5Kx71etryEzrIAEPNI8SWuws0oJON3ez28vo9lb8VQOJjhfBCN5OKFdf71ruqobIxUZpL0Mw3B/KFV/ "Python 3 – Try It Online") Let's find the numerator if the denominator is \$1^2 + 2^2 + ... i^2\$. The numerator of the \$j^{th}\$ term will be just the denominator divided by \$j^2\$. So we add the numerator of all these terms and then divide it with the gcd of numerator and denominator and compare it with \$n\$. [Answer] # [Clojure](https://clojure.org/), 90 bytes ``` #(loop[x 3 y 5/4](let[z(+(/ 1 x x)y)n numerator](condp = % 1 5(n y)(n z)(recur(inc x)z)))) ``` [Try it online!](https://tio.run/##FYxBCsMgFET3PcVAKXzpIkjrsicJWQTzBVurIgrq5Y2ZxWzevNEufEviQQcbmHEnF0JcK15oUMt7I8d57fSkBRIVVTTh4cuf055D2kgHf0R88JhYkUcTs7qgxLoksl5PpYuZIW4Uk/UZlPcfQyqQzdcNw0BeixM "Clojure – Try It Online") Like many other languages, Clojure has native support for rational fractions, but with an annoying quirk: `numerator` and `denominator` functions throw exceptions on integer arguments. If that's not enough, even rational literals of the form `x/y` are auto-converted to integers wherever possible, and the only way I found to force evaluation as a rational is `clojure.lang.Numbers/toRatio`, which is a golfing nightmare. This causes a problem with the initial term \$1\$ of the harmonic sequence, which necessitates a hack - we start the loop from the second term, and cover the first one with a special condition. ]
[Question] [ Your goal is to write a program that prints the string `abc` in two languages. However, while the full code will print `abc` in one language (we'll call it Language 1), the other one (Language 2) must print `abc` if (and only if) every other character is skipped starting from the second character. If the full code is run in language 2, it must throw an error. If the skipped code is run in language 1, likewise, it must throw an error. # Rules and Clarification * Trailing newlines are allowed. * Output must be lowercase. * "Run" means compiled for compiled languages. * We will define "throwing an error" as outputting nothing to STDOUT and something to STDERR. # Test Cases ``` Language 1: 12345 -> abc Language 1: 135 -> error Language 2: 135 -> abc Language 2: 12345 -> error ``` # Scoring The shortest code in bytes wins (the full code, not the skipped code). **Edit: I have clarified the rules based on feedback in the comments. The existing answers should still be valid.** [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~28~~ 26 bytes ``` a+b[c-/[/---<]>>- ]<-.+.+. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v8/UTspOllXP1pfV1fXJtbOTlch1kZXTxsI//8HAA) Got the bf code from [here](https://esolangs.org/wiki/Brainfuck_constants#97). Fails in Ink due to Expected target for new thread but saw `'.+.+.'`. # [ink](https://github.com/inkle/ink) ``` abc//-<>-]-++ ``` [Try it online!](https://tio.run/##y8zL/v8/MSlZX1/Xxk43Vldb@/9/AA) Ink will just print `abc` and the rest is a comment. Fails in brainfuck due to mismatched bracket. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), ~~21~~ 19 bytes (~~19~~ 17 characters) ``` abc#1 / ‚ïò " a b c ``` [Try it online!](https://tio.run/##y05N//8/MSlZ2VBBX@HR1BkKSgqJCkkKyf//AwA) Simply prints `abc` and the rest is a comment. Fails in MathGolf due to an undefined operator overload of `/`. `/` can not work on an integer (`1`) and a string( pushed via the space instruction.) # [MathGolf](https://github.com/maxbergmark/mathgolf) ``` ac1/‚ïò"abc ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z8x2VD/0dQZSolJyf//AwA) Does a bunch of nonsense, then `‚ïò` deletes the whole stack. `"abc` pushes `abc` and the stack has an implicit output. Fails in Keg due to the failure of implicit-outputting a floating-point number in its character form. [Answer] # Japt and Pyth, 20 bytes Both are shortenings of common scripting languages, nice Japt: `"_a_b_c_"v √´2,1 +[]` ([TIO](https://tio.run/##y0osKPn/Xyk@MT4pPjleqUzh8GojHUMFBe3o2P//AQ), [error in Pyth](https://tio.run/##K6gsyfj/Xyk@MT4pPjleqUzh8GojHUMFBe3o2P//AQ)) Pyth: `"abc" 21 [` ([TIO](https://tio.run/##K6gsyfj/XykxKVlJwchQIfr/fwA), [error in Japt](https://tio.run/##y0osKPn/XykxKVlJwchQIfr/fwA)) [Answer] # [CJam](https://sourceforge.net/p/cjam) and [Gaia](https://github.com/splcurran/Gaia), 15 bytes (CJam only cares about printable ASCII, so Gaia's codepage can be used to encode both programs) **Full:** ``` 'a'b'c'‚Äù '·ªç;e< ``` [Works in CJam](https://tio.run/##S85KzP3/X0E9UT1JPVn9UcNcBfWHu3utU23@/wcA "CJam ‚Äì Try It Online") [Errors in Gaia](https://tio.run/##S0/MTPz/X0E9UT1JPVn9UcNcBfWHu3utU23@/wcA) **Reduced:** ``` abc‚Äù'·ªçe ``` [Works in Gaia](https://tio.run/##S0/MTPz/XyExKflRw1z1h7t7U///BwA "Gaia ‚Äì Try It Online") [Errors in CJam](https://tio.run/##S85KzP3/XyExKflRw1z1h7t7U///BwA) ### Explanation This takes some advantage of the fact that `'` defines a character literal in both languages. **Full program:** We push 5 characters: `a`, `b`, `c`, `‚Äù`, and `·ªç`. `;` deletes the `·ªç` and `e<` leaves the minimum of `c` and `‚Äù`, which is `c`. The remaining characters (`abc`) are joined together and output implicitly. In Gaia, everything up to `‚Äù` is a string literal. We then push the char `·ªç`, and then copy (`;`) the string literal back to the top and attempt to eval it (`e`). This throws an error because the last character in that string is `'`, which is improper syntax (a character literal after it is expected). **Reduced program:** `‚Äù` (or, more specifically, byte 0xFB) is not defined, so the program terminates with an error. In Gaia we get the string literal `¬†abc` (with leading space). We then push the character `·ªç` and eval it, which is the command for trim. This leaves plain `abc` on the stack, which is implicitly output. [Answer] # [naz](https://github.com/sporeball/naz) / [7](http://esolangs.org/wiki/7), 54 bytes ``` 6a6a5a5m1a5a1a5a1o5s1a5a1o5s1a5a1o0m3a4a1a2a2a7a4a0a3a ``` This has to be the most esoteric answer I've submitted so far. **Explanation of the full code** (works in naz) ``` 6a6a5a5m1a5a1a5a # Set the register to a value of 97 ("a") 1o # Output once 5s1a5a1o # Output "b" 5s1a5a1o # Output "c" 0m3a4a1a2a2a7a4a0a3a # Extra arithmetic to allow for a valid 7 program ``` [Fails in 7](https://tio.run/##M///3yzRLNE00TTXEEiCcb5pMSptkGucaAKUMwJCcyDLINE48f9/AA): `6 command run with no bar in the frame at /opt/7/7.pl line 605, <> chunk 1.` **The reduced code** (works in 7) ``` 665515151515151510341227403 ``` [Try it online!](https://tio.run/##M///38zM1NQQGRoYmxgaGZmbGBj//w8A) Fails in naz: `error: attempt to chain number literals` I can't give a very accurate explanation of the reduced code due to my relatively poor understanding of 7. I invite anyone who can make sense of it to improve this post. [Answer] # [PHP](https://php.net/) and [Emoji](https://esolangs.org/wiki/Emoji), 21 chars, 30 bytes ### Full: ``` ‚õΩ_a_b_c_üöò‚û°‚û°;echo abc; ``` ### Skipped: ``` ‚õΩabcüöò‚û°eh b; ``` [PHP, Full - Try it online!](https://tio.run/##K8go@G9jXwAkH83eG58YnxSfHP9h/qwZj@YtBCLr1OSMfIXEpGTr//8B "PHP ‚Äì Try It Online") Prints: `abc` [Emoji, Skipped - Try it online!](https://tio.run/##S83Nz8r8///R7L2JSckf5s@a8WjewtQMhSTr//8B "Emoji ‚Äì Try It Online") Prints: `abc` [PHP, Skipped - Try it online!](https://tio.run/##K8go@G9jXwAkH83em5iU/GH@rBmP5i1MzVBIsv7/HwA "PHP ‚Äì Try It Online") Error: `PHP Parse error: syntax error, unexpected 'b' (T_STRING)` [Emoji, Full - Try it online!](https://tio.run/##S83Nz8r8///R7L3xifFJ8cnxH@bPmvFo3kIgsk5NzshXSExKtv7/HwA "Emoji ‚Äì Try It Online") Error: `IndexError: pop from empty list` [Answer] # [JavaScript (V8)](https://v8.dev/) and [PHP](https://php.net/), 29 bytes ### Full: ``` print`abc`;'e_c_h_o_ _a_b_c'; ``` ### Skipped: ``` pitac;echo abc; ``` [JavaScript, Full - Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v6AoM68kITEpOcFaPTU@OT4jPj9eIT4xPik@Wd36/38A "JavaScript (V8) ‚Äì Try It Online") Prints: `abc` [PHP, Skipped - Try it online!](https://tio.run/##K8go@G9jXwAkCzJLEpOtU5Mz8hUSk5Kt//8HAA "PHP ‚Äì Try It Online") Prints: `abc` [JavaScript, Skipped - Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/vyCzJDHZOjU5I18hMSnZ@v9/AA "JavaScript (V8) ‚Äì Try It Online") Error: `SyntaxError: Unexpected identifier` [PHP, Full - Try it online!](https://tio.run/##K8go@G9jXwAkC4oy80oSEpOSE6zVU@OT4zPi8@MV4hPjk@KT1a3//wcA "PHP ‚Äì Try It Online") Error: `abc: command not found` [Answer] # [C++ (gcc)](https://gcc.gnu.org/) / [C (gcc)](https://gcc.gnu.org/), 87 bytes ## Full (C++) ``` //* #import<cstdio> main(){puts("abc"/*// m_a_i_n_(_)_{_p_u_t_s_(_"_a_b_c_"_/*/ ) ; } ``` ## Skipped (C) ``` /*#motcti>mi({us"b"*/main(){puts("abc"// );} ``` [Full C++, Working](https://tio.run/##DYrBCoAgEAXv@xViFw1iP6DoVx62QXhQl7RT9O3maZhhRHW5RHpnnmmKScvdNqntjGWnFGJ2/tWnVWfDIZZnZkoIiMhw8HiheNBQh9nRD8jg2IjIm9V8vf8) [Skipped C++, Error](https://tio.run/##Sy4o0E1PTv7/X19LOTe/JLkk0y43U6O6tFgpSUlLPzcxM09Ds7qgtKRYQykxKVlJX59L07r2/38A) [Full C, Error](https://tio.run/##DYrBCoAgEAXv@xVhFw1iP6DoVx62QXjQJPUkfbvtaZhhZL1FxmBeaA4xP2/dpdQrPAdFH5J1PbdarPGnGF6YKcIjIMHCoSOjoaKoGe0nRKkbEblpm74xfg) [Skipped C, Working](https://tio.run/##S9ZNT07@/19fSzk3vyS5JNMuN1OjurRYKUlJSz83MTNPQ7O6oLSkWEMpMSlZSV@fS9O69v9/AA) [Answer] ## [Backhand](https://esolangs.org/wiki/Backhand) and [><>](https://esolangs.org/wiki/Fish), 39 bytes ### Full ``` 8.cv*c0*~]!]/]:::[@:1[[[email protected]](/cdn-cgi/l/email-protection).+.o.; ``` [Prints abc in Backhand](https://tio.run/##S0pMzs5IzEv5/99CL7lMK9lAqy5WMVY/1srKKtrByjBaOz8/3yhf2yFfz1hPWy9fz/r/fwA) [Errors in ><>](https://tio.run/##S8sszvj/30IvuUwr2UCrLlYxVj/Wysoq2sHKMFo7Pz/fKF/bIV/PWE9bL1/P@v9/AA) ### Skipped ``` 8c*0~!/::@1+o2+o3+o; ``` [Prints abc in ><>](https://tio.run/##S8sszvj/3yJZy6BOUd/KysFQO99IO99YO9/6/38A) [Errors in Backhand](https://tio.run/##S0pMzs5IzEv5/98iWcugTlHfysrBUDvfSDvfWDvf@v9/AA) ### Explanation Backhand doesn't execute the instructions one by one. In the full version, it goes 3, then the `v` instruction turns it to two steps. In the skipped version, this has the consequence that only the first instruction overlaps with the full version. When you run the skipped version on Backhand, it divides by zero. Errors in backhand don't stop the program, so I added a stop command, which makes ><> a bit harder. (It's still a command in ><>, just not a good one.) ><>, on the other hand, does not skip instructions. In the full version, a `.` means jump. Fish is a 2D language, so it pops two arguments. However, only 1 thing was pushed (because of `8`). Thus, `something smells fishy...`. How I get around some of the commands in ><> is simple. When `0` is executed, it pushes 0, then it immediately removes it. Then it skips the next command, which is a mirror. Finally, it duplicates twice, meaning 3 of the same thing is in the stack, which means `@`, which cycles the top 3 items in the stack, does absolutely nothing. [Answer] # [Turing Machine Code](http://morphett.info/turing/turing.html) and [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 85 bytes **Full** ``` 0 _ a r 1 ; ; ; ; 1 _ b r 2 ; ; ; ; ; ; ; 2 _ c * 3 ; ; ; ; ; ; ; ; ; ; ``` [Works in Turing Machine Code](http://morphett.info/turing/turing.html?474cd92c7d84def46ee832b532f553d9) [Errors in Whitespace](https://tio.run/##K8/ILEktLkhMTv3/X4FTwUAhnjORs0jBUMEaBDmtuTi5gJx4hSSFIgUjTqAATEIBLGUElEpW0FIwRpYC6bLmArG5uLj@/wcA): `Prelude.!!: index too large` **Reduced** ``` ``` [Works in Whitespace](https://tio.run/##K8/ILEktLkhMTv3/X0FBgZNTAURycXIpKMC4nAqoXIgsFxfX//8A) [Errors in Turing Machine Code](http://morphett.info/turing/turing.html?2f964654cb5cdfa37b7fe83969257d94): `Halted. No rule for state '0' and symbol '_'.` Takes advantage of the fact that Turing Machine Code ignores most white space and Whitespace pretty much ignores everything else. [Answer] # [GolfScript](http://www.golfscript.com/golfscript/) / MathGolf, 15 bytes Here is a golfing language one in *pure* ASCII. (I guess the best score possible is 15 bytes...) ``` "abc"#; " a b c ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/XykxKVlJ2VpBSSFRIUkh@f9/AA "GolfScript ‚Äì Try It Online") ## GolfScript explanation ``` "abc" # Start a string # # Create a comment (rest is a comment) ; " a b c ``` ## MathGolf explanation ``` "abc" Start a string #; Perform expoentiation between the string and the input (implicitly a string) This isn't defined yet, so it throws an error Discarding the value won't be executed " a b c So does this ``` # [MathGolf](https://github.com/maxbergmark/mathgolf)/GolfScript, 8 bytes ``` "b";"abc ``` [Try it online!](https://tio.run/##y00syUjPz0n7/18pSclaKTEp@f9/AA "MathGolf ‚Äì Try It Online") # MathGolf Explanation ``` "b"; # Push b and then discard the value "abc # Push abc and then implicitly print ``` # GolfScript explanation ``` "b"; # Push b and then discard the value "abc # Unterminated string, throws an error ``` [Answer] # [Rust](https://www.rust-lang.org/) / [Python 3](https://python.org), 70 bytes ## Full (Rust) ``` const _:i8= 3;//1 ; p r i n t ( " a b c " ) # fn main(){print!("abc")} ``` ## Skipped (Python): ``` cnt_i=3/1;print("abc")#f an)pit(ac) ``` Rust fails on the skipped version with ``` error: unexpected closing delimiter: `)` --> a.py:1:28 | 1 | cnt_i=3/1;print("abc")#f an)pit(ac) | ^ unexpected closing delimiter error: aborting due to previous error ``` And Python fails on the full version with ``` File "a.rs", line 1 const _:i8= 3;//1 ; p r i n t ( " a b c " ) # ^ SyntaxError: invalid syntax ``` The Rust comment is turned into a division when one of the slashes disappears; the rest is fairly straightforward. I also avoided a compiler warning by naming the useless variable ‚Äò`_`‚Äô. [Answer] # [Python 3](https://www.python.org/) and [Befunge-98](https://esolangs.org/wiki/Befunge), 36 bytes ``` z= print("@ , , , ""a b c "[8: :2] ) ``` [Works in Python:](https://tio.run/##K6gsycjPM/7/v8pWoaAoM69EQ8lBQQcMlZQSFZIUkhWUoi2sFKyMYhU0//8HAA) ``` z= print("@ , , , ""a b c "[8: :2] ) "@ , , , " #String literal "a b c " #The second string literal is concatenated to the first [8: :2] #Extract every other character starting from index 8, which gives us "abc" print( ) #Print that and return None z= #Assign the result (None) to the variable z ``` [Errors in Befunge:](https://tio.run/##S0pNK81LT9W1tPj/v8pWoaAoM69EQ8lBQQcMlZQSFZIUkhWUoi2sFKyMYhU0//8HAA) ``` z= print("@ , , , ""a b c "[8: :2] ) z #No-op = #Execute "" (raises an error in both FBBI and PyFunge) ``` ## Every other character ``` z rn(@,,,"abc"8 2 ``` [Errors in Python](https://tio.run/##K6gsycjPM/7/v0qhKE/DQUdHRykxKVnJQsFI4f9/AA) The code is nowhere close to anything resembling valid Python syntax, so it raises a `SyntaxError`. [Works in Befunge:](https://tio.run/##S0pNK81LT9W1tPj/v0qhKE/DQUdHRykxKVnJQsFI4f9/AA) ``` z rn(@,,,"abc"8 2 z #No-op r #Reverse direction z #No-op 8 2 #Push 2 and 8 (which we don't care about) onto the stack "abc" #Push "cba" onto the stack , #Print the top of the stack ("a") , #Print the top of the stack ("b") , #Print the top of the stack ("c") @ #End the program ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) / [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)/[bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` "aabbccc"1F√ô; ``` [Try it online in 05AB1E (outputs `abc`)](https://tio.run/##yy9OTMpM/f9fKTExKSk5OVnJ0O3wTOv//wE). [Try it online in MathGolf (errors)](https://tio.run/##y00syUjPz0n7/18pMTEpKTk5WcnQ7fBM6///AQ). Every second character: ``` "abc"F; ``` [Try it online in 05AB1E (errors)](https://tio.run/##yy9OTMpM/f9fKTEpWcnN@v9/AA). [Try it online in MathGolf (outputs `abc`)](https://tio.run/##y00syUjPz0n7/18pMSlZyc36/38A). **Explanation:** ``` # Full program in 05AB1E: "aabbccc" # Push string "aabbccc" 1F # Loop 1 time: √ô # Uniquify the top of the stack ; # Halve it (no-op on strings) # (after the loop, the top of the stack is output implicitly) # Full program in MathGolf: √ô # Errors during compilation, because `√ô` isn't part of its known character- # set from the MathGolf codepage # Reduced program in 05AB1E: "abc" # Push string "abc" F # Loop that many times, which results in an error because it isn't an integer # Reduced program in MathGolf: "abc" # Push string "abc" F # Push builtin integer 17 ; # Discard the top of the stack # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Ruby](https://www.ruby-lang.org/) & [Perl 5](https://www.perl.org/) + `-M5.10.0`, 29 bytes ``` s=a=y=$> .write a=?a ,?b ,?c ``` [`abc` in Ruby](https://tio.run/##KypNqvz/v9g20bbSVsVOQa@8KLMkVUEh0dY@UUHHPgmIk///BwA), [error in Perl](https://tio.run/##K0gtyjH9/7/YNtG20lbFTkGvvCizJFVBIdHWPlFBxz4JiJP///@XX1CSmZ9X/F/X11TP0EDPAAA) This sets the variables `s`, `a` and `y` to the result of `write`ing `a=?a ,?b, ?c` (equivalent to `'abc'` as `?` defines a character literal and `write` accepts multiple arguments) to `$>` (`$>` points to `STDOUT` by default). ``` say$ wie =a,b,c ``` [`abc` in Perl](https://tio.run/##K0gtyjH9/784sVJFoTwzVcE2USdJJ/n//3/5BSWZ@XnF/3V9TfUMDfQMAA), [error in Ruby](https://tio.run/##KypNqvz/vzixUkWhPDNVwTZRJ0kn@f9/AA) This calls `say` with `$ wie =a,b,c`, which sets `$ wie` to the bareword `a` and passes the barewords `b` and `c`. ]
[Question] [ Given an integer greater than 1, output the number of ways it can be expressed as the sum of one or more consecutive primes. Order of summands doesn't matter. A sum can consist of a single number (so the output for any prime will be at least 1.) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Standard rules apply. See [this OEIS wiki](http://oeis.org/wiki/Representations_as_the_sum_of_one_or_more_consecutive_primes) for related information and sequences, including the sequence itself [OEIS A054845](http://oeis.org/A054845). ### Test cases ``` 2 => 1 3 => 1 4 => 0 5 => 2 6 => 0 7 => 1 8 => 1 10 => 1 36 => 2 41 => 3 42 => 1 43 => 1 44 => 0 311 => 5 1151 => 4 34421 => 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to dylnan ``` ÆRẆ§ċ ``` A monadic link **[Try it online!](https://tio.run/##y0rNyan8//9wW9DDXW2Hlh/p/v//v7GhIQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8//9wW9DDXW2Hlh/p/n90z@H2R01r3P//N9Ix1jHRMdUx0zHXsdAxNNAxNtMxMdQxMdIxAUqY6BgbGuoYGpoaAgA "Jelly – Try It Online") (note the final test case would time out at 60s at TIO). ### How? ``` ÆRẆ§ċ - Link: integer, n ÆR - primes from 2 to n inclusive Ẇ - all contiguous substrings § - sum each ċ - count occurrences of n ``` [Answer] # [R](https://www.r-project.org/), 95 bytes ``` function(x,P=2){for(i in 2:x)P=c(P,i[all(i%%P)]) for(i in 1:x){F=F+sum(cumsum(P)==x) P[i]=0} F} ``` [Try it online!](https://tio.run/##Tc1PC4MgGAbwu59CkMCXNcg/tTHw2tl7dIhAEJqNWiyIPrvTsUgv8vN9n8fJj6@3Hd1MP93k1JUBMsqbxfXxla65Vhw2M07UYuswf6ygVU91bptuGKjNMg1tyBwLLCxstaov8/Kk/fKMlwalVkC6sa0qdlTv3lAOOB6CGTJUpJAHioDyAA@o0sktzdxTsAKS6grOAsn@EBE8WZMihYTzH8F@IYLLWM3KKIJlnEjJgwiu/Bc "R – Try It Online") * -24 bytes thanks to @Giuseppe who has basically revolutionized my solution supporting 34421 as well ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ### Code ``` ÅPŒOQO ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##yy9OTMpM/f//cGvA0Un@gf7//5sYAgA "05AB1E – Try It Online") [Answer] # JavaScript (ES6), 92 bytes ``` n=>(a=[],k=1,g=s=>k>n?0:!s+g(s>0?s-(p=d=>k%--d?p(d):d<2&&a.push(k)&&k)(++k):s+a.shift()))(n) ``` [Try it online!](https://tio.run/##dc/NDoIwDAfwu0@hB0kbPmQw1BAHD2I8LA5QRwax6usjaoJxcT32l7b/XuRD0vF67m@h6VQ11GIwogAp9odACxY0gkShC1PG@YL8BqiISwqhF2psL8NQlT0ozNUu8TwZ9Xc6gUbP0wi@rzEnX0Z0Otc3QEQwOBw7Q11bRW3XQA0J4vxVq9WczX4pdRP/UmxR9qXEorV7auO@tXUTiz/2L/x6IjsGZxOlNiXOhTx1E5/I/itln2MjZXZ4lr1tJD48AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` n => ( // n = input a = [], // a[] = array holding the list of consecutive primes k = 1, // k = current number to test g = s => // g = recursive function taking s = n - sum(a) k > n ? // if k is greater than n: 0 // stop recursion : // else: !s + // increment the final result if s = 0 g( // add the result of a recursive call to g(): s > 0 ? // if s is positive: s - ( // subtract from s the result of p(): p = d => k % --d ? // p() = recursive helper function looking p(d) // for the highest divisor d of k, : // starting with d = k - 1 d < 2 && // if d is less than 2 (i.e. k is prime): a.push(k) && // append k to a[] k // and return k (else: return false) )(++k) // increment k and call p(k) : // else: s + a.shift() // remove the first entry from a[] // and add it to s ) // end of recursive call )(n) // initial call to g() with s = n ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ 9 bytes ``` {⟦ṗˢs+?}ᶜ ``` [Try it online!](https://tio.run/##ASIA3f9icmFjaHlsb2cy//974p@m4bmXy6JzKz994bac//8zNv9a "Brachylog – Try It Online") [Multiple test cases](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6Ompoe7Omsfbp0A5M5f9nDn9NOLirWt7W1rH26b8/9/tJGOgrGOgomOgqmOgpmOgrmOgoWOgqEBUBTIMzEEYqAKE5ASoBpjQ6CAoaGpYSwA "Brachylog – Try It Online") *(-5 whole bytes, thanks to @Kroppeb!)* ### Explanation: ``` {⟦ṗˢs+?}ᶜ { }ᶜ Count the number of ways this predicate can succeed: ⟦ Range from 0 to input ṗˢ Select only the prime numbers s The list of prime numbers has a substring (contiguous subset) + Whose sum ? Is the input ``` [Answer] # MATL, ~~15~~ 12 bytes ``` EZqPYTRYsG=z ``` [Try it on MATL Online](https://matl.io/?code=EZqPYTRYsG%3Dz&inputs=1151&version=20.9.2) The initial `E` (multiply by 2) makes sure that, for prime input, the result of the later `Ys` (`cumsum`) does not have the input prime repeating itself in the zeroed part of the matrix (thus messing with the count). ### Explanation: ``` % Implicit input, say 5 E % Double the input Zq % Get list of primes upto (and including) that % Stack: [2 3 5 7] P % Reverse that list YT % Toeplitz matrix of that % Stack: [7 5 3 2 5 7 5 3 3 5 7 5 2 3 5 7] R % `triu` - upper triangular portion of matrix % Stack: [7 5 3 2 0 7 5 3 0 0 7 5 0 0 0 7] Ys % Cumulative sum along each column % Stack: [7 5 3 2 7 12 8 5 7 12 15 10 7 12 15 17] G= % Compare against input - 1s where equal, 0s where not z % Count the number of non-zeros ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` .+ $*_$&$* _ $`__¶ A`^(__+)\1+$ m)&`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1) ``` [Try it online!](https://tio.run/##Dcq7DQIxEEXR/NUxrGZsgRjbLASIFRFF8BkTEBCwwYqQulyAGzMOr85dXt/3/Gwr5ktuGw9yRgM5GCib1YJzfrCZl5t6wkeGnmzyq0V8Ldd@3B1Px3U4qXjiiYOotBYQkbDDiD0O0C3iiKRIAalDQlT9Aw "Retina 0.8.2 – Try It Online") Link includes faster test cases. Explanation: ``` m) ``` Run the whole script in multiline mode where `^` and `$` match on every line. ``` .+ $*_$&$* ``` Convert to unary twice, first using `_`s, then using `1`s. ``` _ $`__¶ ``` Generate all the prefixes of the `_`s and add two to each, thus counting from \$2\$ to \$n + 1\$. ``` A`^(__+)\1+$ ``` Delete all the composite numbers in the range. ``` &`^((_)|¶)+¶[_¶]*(?<-2>1)+$(?(2)1) ``` Match any number of `_`s and newlines (starting and ending at the end of a line) then compare the number of `_`s with the number of `1`s. Count the number of sums of consecutive prime numbers which add up to \$n\$. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~9~~ 8 bytes -1 byte thanks to [Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (use named argument `¹` instead of `S`)! ``` #¹ṁ∫ṫ↑İp ``` [Try it online!](https://tio.run/##yygtzv6fG5yvnaCtpGBrp6CkUfyoqbFI89C2/8qHdj7c2fioY/XDnasftU08sqHg////RlzGXCZcplxmXOZcFlyGBlzGZlwmhlwmRlwmQAkTLmNDQy5DQ1NDAA "Husk – Try It Online") ### Explanation ``` #¹ṁ∫ṫ↑İp -- example input: 3 #¹ -- count the occurrences of 3 in İp -- | primes: [2,3,5,7..] ↑ -- | take 3: [2,3,5] ṫ -- | tails: [[2,3,5],[3,5],[5]] ṁ -- | map and flatten ∫ -- | | cumulative sums -- | : [2,5,10,3,8,5] -- : 1 ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 16 bytes ``` :"GZq@:g2&Y+G=vs ``` [Try it at MATL Online!](https://matl.io/?code=%3A%22GZq%40%3Ag2%26Y%2BG%3Dvs&inputs=311&version=20.9.2) ### Explanation ``` :" % Input (implicit): n. For each k in [1 2 ... n] G % Push n Zq % Primes up to that @:g % Push vector of k ones 2&Y+ % Convolution, removing the edges G= % True for entries that equal n v % Concatenate vertically with previous results s % Sum % End (implicit). Display (implicit) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~106~~ 104 bytes ``` P=k=o=1 p=[] i=input() exec'o+=P%k*sum(p)==i;P*=k*k;k+=1;p+=P%k*[k];exec"p=p[i<sum(p):];"*k;'*i print~-o ``` [Try it online!](https://tio.run/##JY4xa8MwFIT3@xVCUJI4FPpsJS1R35iu9dDNeGhcQYRa66HKtFn6110LT3dwH3cnt3yNYz0P8cOx1npuOXBkgnDXw7MfZcrbHdyvGzZxz@1dqL6nr63smL1tKw5VsGHPZGUNu9DbAmth6fzzyp56qxduU3lI8mP@u4/zMgb8XP2nU29pcicoldOtiFKlQJVLKH5wktX59eWcUkwrcEnuPcw1GhgccMQjnkAPaI4wBFPDLIFBQwSiA/0D "Python 2 – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~100~~ 98 bytes ``` import StdEnv,StdLib $n=sum[1\\z<-inits[i\\i<-[2..n]|all(\j=i/j*j<i)[2..i-1]],s<-tails z|sum s==n] ``` [Try it online!](https://tio.run/##RY6xDoIwFEV3vqKJDGooBmRsNx1M2BgpQy1gHmkfhrYmEr7dimFwujn3JDdX6U5iMGPrdUeMBAxgnuPkSOXaK76SNUq4RzFy602dCTEzCgjO1iAEMFrnaYrNIrXei4HDaTgODA6/FmjWNIll1EnQlszLOkAs59iEysnJRTvSe1QORiScxCuiN/duWuFcFHkW8b/fTPioXsuHDfRWhssbpQG1wfbyCw "Clean – Try It Online") Defines the function `$ :: Int -> Int` which works as explained below: ``` $ n // the function $ of n is = sum [ // the sum of 1 // 1, for every \\ z <- inits [ // prefix z of i // i, for every \\ i <- [2..n] // integer i between 2 and n | and [ // where every i/j*j < i // j does not divide i \\ j <- [2..i-1] // for every j between 2 and i-1 ] ] , s <- tails z // ... and suffix s of the prefix z | sum s == n // where the sum of the suffix is equal to n ] ``` (Explanation is for an older but logically identical version) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes ``` {+grep $_,map {|[\+] $_},[\R,] grep *.is-prime,2..$_} ``` [Try it online!](https://tio.run/##HcmxDoIwFAXQX7kDMQK18bWP6qB8hCsQwtAaEhqbMhH022vDeHKCjYtJfsPJ4Zn2@h1tQDEKPwXs366vh6yf6PqXGHBkJef1EuLsrVBS5kzrtMGdi7GE@0Q8FDQYDQxuuIOu0AZMYAXOwdBEIGqoTX8 "Perl 6 – Try It Online") Uses the triangle reduction operator twice. The last test case is too slow for TIO. ### Explanation ``` { } # Anonymous block grep *.is-prime,2..$_ # List of primes up to n [\R,] # All sublists (2) (3 2) (5 3 2) (7 5 3 2) ... map {|[\+] $_}, # Partial sums for each, flattened +grep $_, # Count number of occurrences ``` [Answer] # Japt, 17 bytes There's gotta be a shorter way than this! Craps out on the last test case. ``` õ fj x@ZãYÄ x@¶Xx ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=9SBmaiB4QFrjWcQgeEC2WHg=&input=MTE1MQ==) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=9SBmaiB4QFrjWcQgeEC2WHg=&input=WwoyCjMKNAo1CjYKNwo4CjEwCjM2CjQxCjQyCjQzCjQ0CjMxMQoxMTUxCl0tbVI=) --- ## Explanation ``` :Implicit input of integer U õ :Range [1,U] fj :Filter primes @ :Map each integer at 0-based index Y in array Z YÄ : Y+1 Zã : Subsections of Z of that length @ : Map each array X Xx : Reduce by addition ¶ : Check for equality with U x : Reduce by addition x :Reduce by addition ``` [Answer] # Java 10, ~~195~~ ~~194~~ ~~184~~ 182 bytes ``` n->{var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}for(x=L.size(),i=0;i<x;)for(k=i++,s=0;k<x;r+=s==n?1:0)s+=(int)L.get(k++);return r;} ``` -1 byte thanks to *@ceilingcat*. -10 bytes thanks to *@SaraJ*. [Try it online.](https://tio.run/##ZVJNbwIhFLz7KyhJEwh0s@hqGyn11pPtxWPbA2XR4G7RAGttjb/dwmpT114IM7w3zPtYyo28WZbVQdXSe/Akjd31ADA2aDeXSoPnBFsCKJROi3lk9r14@CCDUeAZWCDAwd487DbSgamw@hMso3DWBFNnsyBVhTBPyUYwWtEt9dSJnM9XDnFDyL3leJdAJRg314RUDzmPCfNICIOnmSxLZDDfp5itmGbefGuEqYka5n7L8TE3KlEfqSpSjggvhJ2wcY49Ecl51FnogCpCMHc6NM4Cx/cHnipZN@91rORU0GZlSvARW4FmwRm7eHkDEh/7ELQPqE9Z24QTHHRhQfNzOKT9czjqvt52c@@6kOUXP426YgWjgw6@cFZcWrvwNmCMDjsfsiGjRSekKPqMjv4Nve1RG9HOlbYbordrrYIu8d/SSBUaWcf9sJlKM2wfZl8@6I9s1YRsHRscaosMgePXAMkxnkAAECToiIT4FZ7AWaOU1qUur@AYPkpTpxsmEMOTxf3hBw) **Explanation:** ``` n->{ // Method with integer as both parameter and return-type var L=new java.util.Stack(); // List of primes, starting empty int i=1,k,x,s, // Temp integers r=0; // Result-counter, starting at 0 for(;i++<n;){ // Loop `i` in the range [2, `n`] for(k=1; // Set `k` to 1 i%++k>0;); // Inner loop which increases `k` by 1 before every iteration, // and continues as long as `i` is not divisible by `k` if(k==i) // If `k` is now still the same as `i`; a.k.a. if `i` is a prime: L.add(i);} // Add the prime to the List for(x=L.size(), // Get the amount of primes in the List i=0;i<x;) // Loop `i` in the range [0, amount_of_primes) for(s=0, // (Re)set the sum to 0 k=i++;k<x; // Inner loop `k` in the range [`i`, amount_of_primes) r+=s==n? // After every iteration, if the sum is equal to the input: 1 // Increase the result-counter by 1 : // Else: 0) // Leave the result-counter the same by adding 0 s+=(int)L.get(k++); // Add the next prime (at index `k`) to the sum return r;} // And finally return the result-counter ``` --- It's basically similar as the [Jelly](https://codegolf.stackexchange.com/a/170939/52210) or [05AB1E](https://codegolf.stackexchange.com/a/170943/52210) answers, just 190 bytes more.. XD Here a comparison for each of the parts, added just for fun (and to see why Java is so verbose, and these golfing languages are so powerful): 1. Take the input: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 5 bytes) `n->{}` 2. Create a list of primes in the range `[2, n]`: (Jelly: 2 bytes) `ÆR`; (05AB1E: 2 bytes) `ÅP`; (Java 10: 95 bytes) `var L=new java.util.Stack();int i=1,k,x,s,r=0;for(;i++<n;){for(k=1;i%++k>0;);if(k==i)L.add(i);}` 3. Get all continuous sub-lists: (Jelly: 1 byte) `Ẇ`; (05AB1E: 1 byte) `Œ`; (Java 10: 55 bytes) `for(x=L.size(),i=0;i<x;)for(k=i++;k<x;)` and `(int)L.get(k++);` 4. Sum each sub-list: (Jelly: 1 byte) `§`; (05AB1E: 1 byte) `O`; (Java 10: 9 bytes) `,s` and `,s=0` and `s+=` 5. Count those equal to the input: (Jelly: 1 byte) `ċ`; (05AB1E: 2 bytes) `QO`; (Java 10: 15 bytes) `,r=0` and `r+=s==n?1:0` 6. Output the result: (Jelly: 0 bytes) *implicitly*; (05AB1E: 0 bytes) *implicitly*; (Java 10: 9 bytes) `return r;` [Answer] # [Physica](https://github.com/Mr-Xcoder/Physica), 41 bytes ``` ->x:Count[Sum@Sublists[PrimeQ$$[…x]];x] ``` [Try it online!](https://tio.run/##K8ioLM5MTvzvZhvzX9euwso5vzSvJDq4NNchuDQpJ7O4pDg6oCgzNzVQRSX6UcOyithY64rY/0AhoCq3aBPD2Nj/AA "Physica – Try It Online") ### How it works ``` ->x:Count[Sum@Sublists[PrimeQ$$[…x]];x] // Full program. ->x: // Define an anonymous function with parameter x. […x] // Range [0 ... x] (inclusive). $$ // Filter-keep those that... PrimeQ // Are prime. Sublists[...] // Get all their sublists. Sum@ // Then sum each sublist. Count[...;x] // Count the number of times x occurs in the result. ``` [Answer] # [Haskell](https://www.haskell.org/), 89 bytes ``` g n=sum[1|a<-[0..n],_<-filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]]] ``` [Try it online!](https://tio.run/##HcoxDgIhEEDRq0xhAdEli4kd2HgMQsxEEIkwEMBu746rxW9@3gv726c0ZwDS/ZON3FAtZhWC7OmulmdMwzdGWnPRH0hJsiM/uFYqoKlb3e35bzElxq4rF7k4qPx36yKttTNjJNBQW6QBAsJe8@hAKwXBj1uh4Wn0efkC "Haskell – Try It Online") ### Alternative, 89 bytes ``` f n=length$do a<-[0..n];filter(n==).scanl1(+)$drop a[p|p<-[2..n],all((>0).mod p)[2..p-1]] ``` [Try it online!](https://tio.run/##FcqxDoMgEIDhV7nBAdJKtEmngksfwzBcCijpeRBg7LtTHf7lz7dj/Xqi3gOwIc9b2weXAPW4TkqxfYVIzRfBxkhVP8g0i5scXEkZcM2/fMLHBe9IJMQySXUkB1leN4@ztf3AyGAgl8gNFISz4tGB0Ro2396Jm@dW@/MP "Haskell – Try It Online") ]
[Question] [ ### The Language: Oppification A funny language to speak is created by applying the following process to each word: 1. Place `op` after each consonant. So `Code` becomes `Copodope`. Yes, that's it. For the purpose of this challenge, `y` is always a consonant. ### The Challenge: De-oppification Given an oppified word, return the original word. Input will only contain letters. The first letter may be capitalized. The original word will never be empty and will always contain a vowel. ### Test Cases: ``` Oppified -> Original a a I I itop it opop op Opop Op popopop pop Copopop Cop opopopop opop Kopicopkop Kick Asopia Asia soptopopop stop hopoopopsop hoops hopoopopedop hooped ooooohop oooooh aaaopopaaa aaaopaaa Popopopsopicoplope Popsicle gopaloplopopopinopgop galloping aopopbopopopcopopop aopbopcop ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 9 bytes ``` (?!\G)op ``` [Try it online!](https://tio.run/##TYzBCoQwDETv@QsPC/oVsngQ8bD7AR7MqmhRTLD9/@7EKtjAzOuk02MKbuf4yus@5mXW1YUoxcjUkAtAUcjHROUcqi6XO2hF3SC6At8ezAQN13KBGvgHT6PV7SAhZrYQRt9U8unDDS9pxmY72cbtorN17PJL2ZDsDw "Retina – Try It Online") Instead of checking that the preceding character is a consonant, we just make sure that the current `op` is not adjacent to either the beginning of the string or the previous match. The only case where we could match an incorrect `op` is if the original string contained an `op` (resulting in `opop`). But in that case we'll just remove the first `op` instead of the second and the result will be the same. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~12~~, 5 bytes ``` Í.“op ``` [Try it online!](https://tio.run/##TYxLCoAwDET3OYx3EFfiQq8QP2hRTKDiLVx5Iz1YnbQKNjDzOul0D@E@susUDYGpJLeJkiikNlGJQ8Xr8gWVqOtEZ2DuwUzQ7V1OUAP/46G3uh0kxMwWwqhJJZ8@XPCSRmyWyDZuFR2tY5c2ZV2yBw "V – Try It Online") ``` 00000000: cd2e 936f 70 ...op ``` Saved 7 bytes thanks to [@Xnor's realization](https://codegolf.stackexchange.com/a/124770/31716) that since the input must always be opped, we don't have to check for vowels. [Answer] # [Python](https://docs.python.org/2/), 42 bytes ``` lambda s:re.sub('(.)op',r'\1',s) import re ``` [Try it online!](https://tio.run/##VZHBbsMgDIbP5SlYLkmkqNJ2rNTD1F2qHtoHqDSRlCRWKbaAHfb0mSG0yUCK8effP1ag3zCi/Zj6/XUy6tHelPQ7p7f@p63KalsjlY0rr@9l42sBD0IXpNNT0D74fVEUSi5LieMqOwoISwYBSSAtAInBeQXOEdBKQpi2OKzYITNcCfEpPEF3f8ITEnRId8afHl5TfnrmSviwtDMJ2WBEJJ/xyCRCn7m@/ef6FseIa8xjpDNDpRQSf9IvieeUiQt7QWd0xJf5Qj8PadhNDMpwBDtweeAOk3jcYJGG6IvUInVp8uTazvVuDvwYQvTopAGrJViZ3mjryUCoyqst653YGN2HRjoYxiD3SZkFtZAbp7vvKOBKXyVNpNDLV@GNeziy0YYc2DA7NTLbZpmYa8UXWl1Mfw "Python 2 – Try It Online") If I'm not mistaken, you can just substitute all `?op` with `?` without caring about vowels. If the original string contains `op`, then it's oppified to `opop`, and the replacement returns it to `op` and no further. This is because the pattern matches for `?op` cannot overlap, so only one `op` is removed. A non-regex solution is 5 bytes longer. **[Python](https://docs.python.org/2/), 47 bytes** ``` f=lambda s:s and s[0]+f(s[1+2*(s[1:3]=='op'):]) ``` [Try it online](https://tio.run/##dZJNb8IwDIbP@FdkvQADTRvckHpA2wVxYHeGptCmrUWWWHUu@/WdkyKEWJtIsfQ@r50v029ovFt1XZVb/XMuteINK@1KxcfX06Ka8fFtsXqOYbM@5fnU03S@Oc27YDhwnmWZViNDw24M7QCDp0GEATyNME9wGGMHAvI0nCoivI9BAeDHUqMIe09YeLr843ssLrBlwUOPsGXUIDAM1maRoREQGT/iRmS@YVM@8IhNCT6OZujYCYDWOqZLePyaCGSBz/5s3N/QStWrQwBjYQ3UYrQJxYnOU91vWGtro1BD2uTcG4r7y@okiyRtAlD5Vll0RqFTqXtemCyG2fTLSUvBpMW6CUtlTRVUnpxXwxzUpDXF95VUs@SMKlbqBp7ylCqFJtSiC@qu3vJmg55lH96ZrPsD "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 10 + 1 = 11 bytes ``` s/.\Kop//g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXy/GO79AXz/9//@M/IJ8ICoozi/4l19QkpmfV/xft8DXVM/A0AAA "Perl 5 – Try It Online") Run with `-p` (1 byte penalty); golfing languages might do implicit I/O automatically, but Perl needs an option for it. When I saw [@xnor's answer](https://codegolf.stackexchange.com/a/124770/62131), I realised it could be improved using a Perl-specific regex feature; `s/a\Kb/c/g` is equivalent to `s/ab/ac/g` (in other words, the `s///` only replaces the things after the first `\K`). So here's how it looks in Perl. [Answer] # [Retina](https://github.com/m-ender/retina), ~~15~~ 8 bytes ``` (.)op $1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fQ08zv4BLxfD/fwA "Retina – Try It Online") *-7 bytes thanks to Kevin Cruijssen* [Answer] # [Go](https://golang.org/), ~~103~~ 92 bytes Must... compile... Go built-in functions have weird names. :P ``` import."regexp" func f(s string)string{return MustCompile("(.)op").ReplaceAllString(s,"$1")} ``` [Try it online!](https://tio.run/##PU7BagQhDL3PVwTpQWER9rrQw9BTKYWlPZZSZFArqyaoA4Vlvj11nNIEkpf3XkI8MpnlZryFZEKeppAISwPhUhP/A1bBB9aiWG9/SExuzQs4WaG2ErJXR7sX29aS4XWt7QkThWilkFohCaXfLEWz2DnG92GW9SQezkJtPI7tD0h1n6CHwwJfJwhweYRicn8Pq56Lrx/nyyccnuFLTV/7rRazdDIoNZRt2pgNP3NoSEw4kl@QwoJ063CuHRvutf2J373uoFOMe3SCr4dYj8WIZNkjmTjwniEjdeYX "Go – Try It Online") [Answer] # Haskell (~~93~~ ~~62~~ 61 Bytes) ``` a(x:'o':'p':r)|notElem x"aeiouAEIOU"=x:a r a(x:r)=x:a r a x=x ``` thanks to @nimi suggestions in comments! [Answer] # [PHP](https://php.net/), 36 bytes ``` <?=preg_replace("#.\Kop#","",$argn); ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6sUkF8AgsX5BZnJ@QU5@QWpStZc9nZARbYFRanp8UWpBTmJyakaSsp6Md75BcpKOkpKOmC9mtb//wMA "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` r"%Vop"_g ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=ciIlVm9wIl9n&input=InBvcG9wb3Ai) [Answer] # JavaScript (ES6), 35 bytes Add `f=` at beginning and invoke like `f(arg)`. ``` s=>s.replace(/([^aeiou])op/gi,"$1") ``` I am surprised no one posted a JavaScript solution yet.... ## Test Snippet ``` let f= s=>s.replace(/([^aeiou])op/gi,"$1") console.log("a" + " -> " + f("a")); console.log("I" + " -> " + f("I")); console.log("itop" + " -> " + f("itop")); console.log("opop" + " -> " + f("opop")); console.log("Opop" + " -> " + f("Opop")); console.log("popopop" + " -> " + f("popopop")); console.log("Copopop" + " -> " + f("Copopop")); console.log("opopopop" + " -> " + f("opopopop")); console.log("Kopicopkop" + " -> " + f("Kopicopkop")); console.log("Asopia" + " -> " + f("Asopia")); console.log("soptopopop" + " -> " + f("soptopopop")); console.log("hopoopopsop" + " -> " + f("hopoopopsop")); console.log("hopoopopedop" + " -> " + f("hopoopopedop")); console.log("ooooohop" + " -> " + f("ooooohop")); console.log("aaaopopaaa" + " -> " + f("aaaopopaaa")); console.log("Popopopsopicoplope" + " -> " + f("Popopopsopicoplope")); console.log("gopaloplopopopinopgop" + " -> " + f("gopaloplopopopinopgop")); console.log("aopopbopopopcopopop" + " -> " + f("aopopbopopopcopopop")); ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 83 bytes ``` main(c,v)char**v;{for(;*v[1];strchr("aAeEiIoOuU",putchar(*v[1]++))?:printf("op"));} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@bmJmnkaxTppmckVikpVVmXZ2WX6RhrVUWbRhrXVxSlJxRpKGU6JjqmumZ718aqqRTUFoCUqoBVqGtralpb1VQlJlXkqahlF@gpKlpXfv////E/IKk/ILk/IKvefm6yYnJGakA "C (gcc) – TIO Nexus") [Answer] # [///](https://esolangs.org/wiki////), 18 bytes ``` /op/.//../o\p//.// ``` [Try it online!](https://tio.run/##K85JLM5ILf7/Xz@/QF9PX19PTz8/pkAfxPwfkF8AgsX5BZnJ@QU5@QWp/wE "/// – Try It Online") Note that this snippet wants to replace `op` with a `.`, but later on there is a replacement defined where `op` is being put back into the string. That second instruction would have the `op` replaced by a `.` (and thus insert a `.` into the end result), so I've used a `\` between the `o` and `p` to break the pattern. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 13 bytes ``` '(.)op'⎕R'\1' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///PyU1v@BR2wR1DT3N/AL1R31Tg9RjDNUh4odWqCeqKyioe4KIzBKgPJDOL4DQ/lC6IL8AJuSMYOYjCXvnF2Qm5xdkQ3iOxUAu2FggowShKgPIALGLUbmpKVADQSADwk5MTARJASkQLwBiRjHElhygFpBoOlA@B8wFwcy8/IJ0qGYQPwkinAyzHgA "APL (Dyalog Unicode) – Try It Online") Simply PCRE **R**eplace any character followed by "op" with the character itself. [Answer] # Crystal, 39 Bytes ``` def o(s)s.gsub(/([^aeiou])op/,"\\1")end ``` ## How it works It simply searches for each consonant, followed by the sequence `op`. If so, replace that sequence only with the consonant found before: `([^aeiou])`. [Try it online](https://tio.run/##ZU69DsIgEN59CsMEibHxEYyTcdDdakIptsSmd/HawafHow1ClRv4/u7HvN406M772j7WIEnRtqGxkoW83rV1MN4UYLERZbkTyva1R04JLdRqAscI3AAYMWDC5wwjYG4dlhR@7BOgM4DPpOyJpe9qJsOyo2USOP1Lts4WhdcmrrUOEf6icpnn0nxBx@3RaTjXTVIo1wM22aCgVbNl4mn@Aw) [Answer] # Java 8, ~~36~~ 26 bytes ``` s->s.replaceAll("(.)op","$1") ``` -10 bytes by replacing `[^aeiou]` with `.`, thanks to [*@xnor*'s explanation in his Python answer](https://codegolf.stackexchange.com/a/124770/52210). [Try it here.](https://tio.run/##lZA9a8MwEIZ3/4pDZLCgMXQOLYROoTQpdCwdLrLqKFGkw1ICpfi3u6fYS4ciVQJ9Pu97H0e84tKTdsf2NCqLIcALGvddARgXdf@JSsM2XQHeYm9cB6qeD0Gu@H2oeAkRo1GwBQcPMIblY2h6TZbFa2trUTfSk7gTi3shx1US0GVvWTDrrt60cOa4s/X7B6Ccg36FqM@Nv8SG@CtaV7tG1QKFvIX/m9hkCRM5qxzkqQDalUDkqcjsqZDzpYbPnozydCpA14HZfG@ZioXBD0wlMPyD1W1J@WkcCkBETKa8ZdHXqagwNcxyJllJx872xqZpnKeuJKcE7yeN@tXJoRrGHw) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~34~~ ~~27~~ 22 + 1 = 23 bytes *-4 bytes thanks to RJHunter.* +1 byte for the `-p` flag. ``` $_.gsub!(/(.)op/,'\1') ``` [Try it online!](https://tio.run/##TU1BCsJADLznF4LQFrTFJ4gn8aAPECRbZV0sTWjag583Jt0KbmBmdpJJhim8Vde3OsoUVmVT1hVxsymuu6JSRThCGomB2ODswDQXHBamn3EiTi3xy@ReTCMYjkvzaehC/vTj7nF/5gAiumkElxySvLCzSYjW6WbtlXri6Bn/hOy1mT52M1EvuuUv "Ruby – Try It Online") [Answer] # sed, 22 bytes ``` sed -E 's/(.)op/\1/g' ``` Reads from STDIN until EOF and outputs de-oppified string Uses same length reduction technique from [@xnor's Python answer](https://codegolf.stackexchange.com/a/124770/14280) [Answer] # [R](https://www.r-project.org/), 29 bytes ``` gsub("(.)op","\\1",scan(,'')) ``` [Try it online!](https://tio.run/##VUzNCsIwDL7vMXJZC0XwEYYn8aAPsEtWxyyOJZj5/DVpR8GG8uX7yffJeZHv5MCdPDEEGMczBIm4udD33mdA6OCqP@3qd0Bc4F5hEOJkCSY@nEvbyN6rXR3qTS8i8bsQRDRZQYl27S2md2Sr/LH5WeijxqRWrapbl0lTdWLrWbR9LRmbtBGrAvkH "R – Try It Online") Much like most other solutions here, captures character followed by op, replaces it with character itself. ]
[Question] [ # The "problem" Define a function `log` (or other 3 letter name) which when called will log/print/write (whatever is the default for the language in question) both the instruction (as source) and the first argument. In other words: ``` i=777 j=333 log(i) //outputs: "log(i) 777" log(i+j+1) //outputs: "log(i+j+1) 1111" ``` For all practical purposes the output `i: 777` would be enough, but in some languages there are very specific reflection libraries for that, and that would be no challenge, so the entire instruction should be outputted. # Inspiration The inspiration for this was me and another programmer discussing how irritating it is that often (with bad debuggers), you write things like `console.log("i:", i)`, next we made a (pretty crazy) javascript (node only) solution (it outputs `i: 777` rather than the entire line of source) which was suprisingly long and reminded me of codegolfing and made me wonder how much better other (especially code golfing) languages would fare. # Bonuses **-10%**: No file reading (beyond the compiler) PS. This is my first 'question' here, so feel free to point out any mistakes I made. [Answer] # C ~~(40 -10% = 36)~~ (38 -10% = 34.2) Note that, in C, a `log` function can only be defined for a specific type. Therefore, this `log` "function" takes only `int` arguments. ``` #define log(x)printf("log("#x") %d",x) ``` A more general solution specifies how to print the argument, in addition to the argument itself: ``` #define lg2(f,x)printf("lg2("#x") "f,x) ``` which would be used as e.g. `lg2("%s", "I'm a string");` or `lg2("%f", 3.1415)`. [Answer] # Python (65 -10% = 58.5) This assumes your code is in a file (it produces odd output if invoked in the interactive interpreter): ``` import traceback as t def log(x):print t.extract_stack()[-2][3],x ``` It has been tested on Python 2.7.6. Example: ``` def foo(): x = 1 log(x) for i in xrange(10): log(x+i+1) return x log(foo()) ``` outputs ``` log(x) 1 log(x+i+1) 2 log(x+i+1) 3 log(x+i+1) 4 log(x+i+1) 5 log(x+i+1) 6 log(x+i+1) 7 log(x+i+1) 8 log(x+i+1) 9 log(x+i+1) 10 log(x+i+1) 11 log(foo()) 1 ``` [Answer] # C++ ~~121~~ ~~71~~ 67 -10% = 60.3 ``` #include<iostream> #define log(x)std::cout<<"log("#x") "<<(x)<<"\n" ``` Used like this: ``` int main() { int i = 777; int j = 333; log(i); log(i+j+1); } ``` Outputs: ``` log(i) 777 log(i+j+1) 1111 ``` [Answer] # Rebol3 - 31.5 (35 - 10 %) Here is a simple implementation shortened from @draegtun that works well for numbers: ``` log: func[p][print[{log[}p{]}do p]] ``` Running it outputs: ``` >> log: func[p][print[{log[}p{]}do p]] >> i: 777 >> j: 333 >> log [i] log[ 777 ] 777 >> log[i + j + 1] log[ i + j + 1 ] 1111 ``` It can be much more flexible (for displaying the form of non-number types) at **42.3 chars (47 - 10%)** ``` log: func[p][print[{log}mold p mold/only do p]] ``` The output: ``` >> log: func[p] [print[{log}mold p mold/only do p]] >> log [join "4" 4] log [join "4" 4] "44" ;; shows a string >> log [1 + 2] log [1 + 2] 3 ``` [Answer] # Javascript (325) I think this is the `log` function you are looking for: ``` function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()} ``` # Usage ``` <script> function log(m){L=(new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0];N=L.split(':')[1];C=parseInt(L.split(':')[2]);R=new XMLHttpRequest();R.open('GET',location.href,0);R.onload=function(){console.log(R.response.split('\n')[N-1].substr(C-1).split(';')[0]+' = '+m)};R.send()} function doSomething() { var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b); } doSomething(); var message = "...or just do it out here"; log(message + "!"); </script> ``` ## Output ``` log(a) = 123 log(b) = Hello, I am TrungDQ! log(message + "!") = ...or just do it out here! ``` ## Long code ``` <script> function log(msg) { // Get the line number and offset of the line where is function is called var lineInfo = (new Error()).stack.match(/(at log \([\s\S]+?at .+?:)\d+:\d+/m)[0].split('\n')[1].match(/:\d+:\d+/)[0]; var lineNum = lineInfo.split(':')[1]; var charOffset = parseInt(lineInfo.split(':')[2]); // Get the file source request = new XMLHttpRequest(); request.open('GET', window.location.href, true); request.onload = function() { // Get file source code var response = request.responseText; // Get the `log` line var line = response.split('\n')[lineNum - 1]; // Get the `log` statement var logStatement = line.substr(charOffset - 1).split(';')[0]; // Print it console.log(logStatement + ' = ' + msg); }; request.send(); } function doSomething() { var a = 123; log(a); var b = "Hello, I am TrungDQ!"; log(b); } doSomething(); </script> ``` Only works when the script is put inside `<script>` tag which is put in `.html` document because it sends a request to `location.href` to get the source code. JSfiddle, F12 Dev Tool Console, embbed `.js` files won't work, I am trying to make it available everywhere... Anyway, this question is interesting. [Answer] # Scala - (221 - 10%) = 198.9 Yay macros! This is actually exactly the type of stuff they're for. ``` import language.experimental.macros def log(p:Any)=macro l def l(c:reflect.macros.Context)(p:c.Expr[Any])={import c.universe._;reify{println("log("+(c.Expr[String](Literal(Constant(show(p.tree)))).splice)+") "+p.splice)}} ``` Readable version: ``` import language.experimental.macros def log(p: Any) = macro l def l(c: reflect.macros.Context)(p: c.Expr[Any]) = { import c.universe._ val inputString = show(p.tree) val inputStringExpr = c.Expr[String](Literal(Constant(inputString))) reify { println("log(" + (inputStringExpr.splice) + ") " + p.splice) } } ``` Example: ``` log(1) val x = 3 log(x) val y = 4 log(x+y) ``` Outputs: ``` log(1) 1 log(x) 3 log(x.+(y)) 7 ``` Since addition is a method call in Scala, it adds that verbose syntax back in, but it's pretty close! It's also a bit more verbose in a couple of other cases. [Answer] # bash (21 - 10% = 18.9) This: ``` alias log=echo;set -v ``` Then use `log` like you would use `echo`: ``` log $((1+1)) ``` or ``` A=2 B=3 log $((A+B)) ``` This method will do all what is required; as a bonus, some extra information will also be printed, but no explicit rule forbid it. [Answer] # BASH Arguments are not passed using "(...)" in BASH, so I let the output of 'log()' fit that style: ``` $ log(){ echo "$FUNCNAME $@: $(($@))"; } $ i=333 $ j=777 $ log i log i: 333 $ log i+j+1 log i+j+1: 1111 ``` [Answer] # Clojure ``` (defmacro log[x] `(let [x# ~x] (println "log("'~x")" x#))) ``` Homoiconicity has its benefits! To use: ``` (def i 777) (def j 333) (log i) ;Prints log( i ) 777 (log (+ i j 1)) ;Prints log( (+ i j 1) ) 1111 ``` Let's see what's happening with `macroexpand`: ``` (macroexpand '(log (+ i j 1))) ;; Prints the following: (let* [x__1__auto__ (+ i j 1)] (clojure.core/println "log(" (quote (+ i j 1)) ")" x__1__auto__)) ``` [Answer] # Julia, 51\*0.9=45.9 ``` julia> x=4 4 julia> macro log(x) println("log($x) $(log(eval(x)))") end julia> @log(x) log(x) 1.3862943611198906 ``` Alternatively, but not meeting the rules ``` julia> @show log(x) log(x) => 1.3862943611198906 ``` [Answer] ## Tcl, 42.3 (47 - 10%) ``` proc log c {puts [dict g [info fr -1] cmd]\ $c} ``` Usage: ``` set i 777 set j 333 log $i ;#outputs: "log $i 777" log [expr {$i+$j+1}] ;#outputs: "log [expr {$i+$j+1}] 1111" ``` **Edit**: small improvement [Answer] # Common Lisp - 119.7 (133 -10%) ``` (defmacro @(&whole f &rest r)(let((g(gensym)))`(let((,g(multiple-value-list,@r)))(progn(format t"~s~{ ~a~} "',f,g)(values-list,g))))) ``` * Named `@` because `log` is the standard logarithm function and locked by default (at least on SBCL). Also, `@` is only one character long. * Acts as a `progn`, taking a variable number of arguments, but prints to standard output. In real applications, I would probably `signal` a condition with an S-expression instead of printing space-separated output. * Contrary to the existing Clojure solution, we ultimately returns the value of the logged expression, so that `(@ x)` can be used whenever `x` is used. * Printing uses `prin1`, which outputs a `read`-able string. This is useful when trying to reproduce logged expressions. * Handles all possible types (see C answer) * Takes into account mutliple values * Does not produce different outputs (see Scala answer) * Works from a file and from REPL (See Pyhton answer) * Does not require browser/interpreter trick (Python traceback, Javascript request) # Sample outputs: ``` CL-USER>(@ (+ 3 2)) ; user input (@ (+ 3 2)) 5 ; printed output 5 ; result of expression CL-USER> (@ (values 3 4)) ; input (@ (VALUES 3 4)) 3 4 ; logging 3 ; first value 4 ; second value CL-USER>(@ (round 3.4)) (@ (ROUND 3.4)) 3 0.4000001 3 ; rounded value 0.4000001 ; delta ``` And finally, if I log the above `defmacro`, I have the ungolfed version: ``` CL-USER> (@ (defmacro @(&whole f &rest r)(let((g(gensym)))`(let((,g(multiple-value-list,@r)))(progn(format t"~s~{ ~a~} "',f,g)(values-list,g)))))) STYLE-WARNING: redefining COMMON-LISP-USER::@ in DEFMACRO (@ (DEFMACRO @ (&WHOLE F &REST R) (LET ((G (GENSYM))) `(LET ((,G (MULTIPLE-VALUE-LIST ,@R))) (PROGN (FORMAT T ,"~s~{ ~a~} " ',F ,G) (VALUES-LIST ,G)))))) @ @ ; actual result ``` [Answer] # PHP 138 You can't redeclare `log` in PHP without using another module (`APD`) so I used `logg` instead, i can resubmit with `log` example if needed. That's minor, but more sinful i guess is that this assume the log function is on a line by itself. I can update my answer as dictated by comments. ``` <?php function logg($v){$b=debug_backtrace()[0];$h=fopen($b['file'],"r");for($i=0;$i<$b['line']&&$l=fgets($h);$i++);echo trim($l)." $v";} ``` example output: ``` for ($i=1; $i<10; $i++) { $j=$i+1; $k=$j+1; logg($i+$j+$k); echo "\n"; } /* logg($i+$j+$k); 6 logg($i+$j+$k); 9 logg($i+$j+$k); 12 logg($i+$j+$k); 15 logg($i+$j+$k); 18 logg($i+$j+$k); 21 logg($i+$j+$k); 24 logg($i+$j+$k); 27 logg($i+$j+$k); 30 */ ``` ]
[Question] [ For this code golf, you will receive an input of a **fib**onacci sequence, that is, a normal Fibonacci sequence but with one number incorrect. See, the sequence is *fibbing*! Get it? `:D` Your job is to find out which number is incorrect, and print the index (0-based) of that number. For example: ``` Input : 1 1 2 9 5 8 13 Output: 3 Input : 8 13 21 34 55 80 Output: 5 Input : 2 3 5 5 13 21 Output: 3 ``` Specifications: * The sequence may start at any number. * The first two numbers of the input will *always* be correct. * Shortest code (character count) wins. [Answer] ## GolfScript (18 chars) ``` ~]:^,,{^>3<~-+}?2+ ``` The key to keeping this short is [?](http://www.golfscript.com/golfscript/builtin.html#%3f) (find). [Answer] ## J, 30 23 ``` (2+0 i.~2&}.=[:}:}:+}.) ``` [Answer] ## Golfscript, ~~31~~ ~~28~~ ~~26~~ ~~25~~ 23 ``` ~]-1%~1{)\3$3$-=}do])\; ``` [Answer] ## APL (19) ``` 1+1⍳⍨(1↓1⌽k)≠2+/k←⎕ ``` Explanation: * `k←⎕`: store user input in `k` * `2+/k`: sum each pair of elements in `k` (i.e. `1 1 2 3` -> `1+1 1+2 2+3` -> `2 3 5`) * `1↓1⌽k`: rotate `k` to the right by 1 and then drop the first element (i.e. `1 1 2 3` -> `2 3 1`) * `≠`: find the place where these lists are not equal * `1⍳⍨`: find the location of the first `1` in this list (location of the incorrect number) * `1+`: add 1 to compensate for the dropped element [Answer] # K, 32 ``` {2+*&~(n@n@x)=x+(n:{1_x,x 0})@x} ``` [Answer] # dc, 36 32 ``` ?zszsasb[lalbdsa+dsb=x]dsxxlzz-p ``` `dc` is a reverse-Polish calculator, so obviously you need to input the numbers in reverse order ;) ``` $ dc fib.dc <<< "999 13 8 5 3 2 1 1" 7 $ dc fib.dc <<< "999 1 1" 2 ``` [Answer] ## JavaScript, 70 ``` for(n=prompt().split(' '),i=n.length;i---2;)if(n[i-2]- -n[i-1]!=n[i])i ``` [Answer] # Javascript (69 68 61 60 55) ``` for(s=prompt(i=2).split(' ');s[i]-s[i-1]==s[i-2];i++);i ``` --- (60) ``` s=prompt(i=2).split(' ');for(;s[i]==+s[i-1]+ +s[i++-2];);--i ``` --- (61) ``` s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);i ``` --- (68) ``` s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);alert(i) ``` --- (69) ``` s=prompt(i=1).split(' ');k=+s[1];for(;k+=+s[i-1],k==s[++i];);alert(i) ``` [Answer] # Awk: 55 ``` {for(i=3;i<=NF;i++)if($i+$(i-1)!=$(i+1)){print i;exit}} ``` [Answer] # Ruby, 66 My first attempt at an (somewhat) complicated Ruby program: ``` p gets.split.map(&:to_i).each_cons(3).find_index{|a,b,c|a+b!=c}+2 ``` [Answer] # Python, 74 ``` a=map(int,raw_input().split()) i=2 while a[i-2]+a[i-1]==a[i]:i+=1 print i ``` I had this solution first, but Doorknob answered the question about the format of input *right* before I had time to post it: # Python, 66 ``` a,b=input(),input() i=2 while input()==a+b:a,b=b,a+b;i+=1 print i ``` Assumes newline separated input. [Answer] **VB.net (77)** Assuming the numbers are already in a IEnumerable(Of Integer). ``` Dim p = xs.Skip(2).TakeWhile(Function(c, i) c = xs.Skip(i).Take(2).Sum).Count + 2 ``` [Answer] # JS, 52B ``` for(s=prompt(i=2).split` `;s[i]-s[i-1]==s[i++-2];);i ``` [Answer] # Matlab / Octave, 39 bytes *Thanks to [Stewie Griffin](https://codegolf.stackexchange.com/users/31516/stewie-griffin) for saving a byte! (`-` instread of `~=`)* ``` @(x)find(diff(x(2:end))-x(1:end-2),1)+1 ``` This is an anonymous function that inputs an array and outputs a number. [**Try it online!**](https://tio.run/##JcrBCoMwEIThe59ijruowd0YqEKh7yE5lCYLXvRSSt4@Rrz9fDPH9/f552ov51x9U2Hb9kRpM6NCuuQ9MQ@F5KpBuRfupBqtAoFiRsAT4iM/ml0FFfgJofl4q8K3V7i3yPUE) [Answer] # [Kotlin](https://kotlinlang.org), 77 bytes ``` {val r=it.split(' ').map{it.toInt()} var i=2 while(r[i]==r[i-1]+r[i-2])i++ i} ``` ## Beautified ``` { val r = it.split(' ').map { it.toInt() } var i=2 while(r[i] == r[i-1] + r[i-2]) i++ i } ``` ## Test ``` var f:(String)->Int = {val r=it.split(' ').map{it.toInt()} var i=2 while(r[i]==r[i-1]+r[i-2])i++ i} data class Test(val input: String, val output: Int) val TESTS = listOf( Test("1 1 2 9 5 8 13", 3), Test("8 13 21 34 55 80", 5), Test("2 3 5 5 13 21", 3) ) fun main(args: Array<String>) { val fails = TESTS .asSequence() .map { it to f(it.input) } .filter { (test, res) -> test.output != res } .toList() if (fails.isEmpty()) { println("Test Passed") } else { fails.forEach{ println(it)} } } ``` [Answer] # [Raku](http://raku.org/), 45 bytes ``` {first :k,?*,(@($/=.words)Z-($0,$1,*+*...*))} ``` [Try it online!](https://tio.run/##JYpbCsIwFAW3cijBPIyxNzHig6jr8KcIGhCVSiJIKV17bPFrYGbet/Rcl1eHWUQofbyn/MHuoY9Ki5Ngy2C@bbpmeV4IVmtGWs2VMUZJOZR86VCxBuGAPoI1Q4XYJnACwWILjw3IcQ0@EZbgVvCjrSdn4cbD/wvflx8 "Perl 6 – Try It Online") `$/ = .words` stores the words (numbers) of the input string into the pattern-match variable `$/`. Conveniently, the elements of that variable can be accessed with `$0`, `$1`, etc, so `$0, $1, * + * ... *` forms the Fibonacci sequence starting with the first two input numbers. The input numbers and the Fibonacci sequence are then zipped together using the subtraction operator (`Z-`), forming a new sequence which is nonzero only at the place where the two series are different. Then `first :k, ?*, ...` returns the index (thanks to the `:k` parameter) of that location; `?*` is an anonymous predicate function that coerces its argument to a boolean value. [Answer] ## Python (90) ``` a=map(int,raw_input().split()) print min(i for i in range(2,len(a))if a[i-2]+a[i-1]!=a[i]) ``` [Answer] # Mathematica 59 Because space-delimited input is required, `StringSplit` needs to be employed. The following assumes that the input is in the form of a string `i`. ``` s = StringSplit@i; p = 3; While[s[[p - 1]] + s[[p - 2]] == s[[p]], p++]; p - 1 ``` [Answer] # Haskell, 48 ``` f l=length$fst$span id$zipWith(==)l$1:scanl(+)1l ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ÆḞ€i$€In1i1 ``` [Try it online!](https://tio.run/##y0rNyan8//9w28Md8x41rclUARKeeYaZhv///4@20FEwNNZRMDLUUTA20VEwNdVRsDCIBQA "Jelly – Try It Online") [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 31 bytes ``` _!_!{_!~a+b=c|a=b┘b=c┘s=s+1\_Xs ``` ## Explanation ``` _!_! Ask the user for two umbers, assign them to 'a' and 'b' { DO _! Ask for a third number (this will be assigned to 'c' on every iteration) ~a+b=c IF the previous two terms add up to the third |a=b THEN shift b into a, ┘b=c and c into b ┘s=s+1 increment s (starts as 3 in QBIC) \_Xs ELSE quit, printing the step counter ``` I'm not quite sure if this is allowed; the sequence is entered one term at a time, and the program aborts on error, not after entering the entire sequence. [Answer] # [Pxem](https://esolangs.org/wiki/Pxem), 0 bytes (content) + 52 bytes (filename). * Filename (escaped): `\002._._X.w.c.t.v.m.v.+._.c.t.v.m.v.-\001.r.x.n.d.a\001.+.vX.a` ## Usage * From stdin * Must be an actual FIBonacci sequence * Each integer are separated with blank characters ## With comments ``` XX.z # Initial stack: F(i-1), F(i-2), i # i is initially 2 .a\002._._XX.z # while :; do .aX.wXX.z # to: (F(i-1)+F(i-2)), i, F(i-1) .a.c.t.v.m.v.+XX.z # input is F(i) # to: F(i), (F(i-1)+F(i-2)), i, F(i-1), F(i) .a._.c.t.v.m.vXX.z # to 0, abs(F(i)-F(i-1)-F(i-2)), i, F(i-1), F(i) # if (pop!=pop); then .a.-\001.r.xXX.z # print pop; exit; fi .a.n.d.aXX.z # to F(i), F(i-1), (i+1) .a\001.+.vXX.z # done .aX.a ``` [Try it online!](https://tio.run/##jVh7V9rKFv@/n2JII5mQ5wAqEqNS8FrOUYrWuqyArhCCgiFwkqBo4Hz13j2TIBB6u267NDO//Zz9mIfPwdOvz59ty7L3bKe7388f5Ill9Z2CZZcKdr9I8jqxd0v6vrOX7@c/BU6IFGdqTEdW8Ix0PZ83nNlk7IfovPpQOT83qwYO3yYOenRCe@z1s1k2s8ejkeX1xCOt57xo3tR1Uf4oS7LZRLhZuf5qcjxO@JAyWSpgJJGP6EcqL@KBsuCWZn806rcP369rZl7XC0uw@e17/fb850P129XVafXaJEYLcXz0pfL968PN6dX3@rdGWXpbcMhEb6iTzbJVjdFkHAxm8Uz6Eovc/Q8JZzR1rdBBwRPjH09CGL6O/V4wcQdhNmu5AytAyiMS@IhIHH/CLQRToF8hm238OD@vXtTMMrOBqb2eETwN@qHBxojyJYBjP40R/1mklgm1nAFD@bHbO8pC6F8sF3EZ1LfcwOHm83UaU82kZ/PA6SEh0Gbam2YE8OtdE5jCd9ShQowLeJaiNhbxGJJQ8ZDyEk7JPPSRUg1Qu6UrBx0ktNperiPMH31ngtRYuXZf3OO1qFwx@K7RMLS2x@ZNMHevqm1P04xuxVjE09Y91UNIntcmmhGugyV9GyOE8No4Be4fbGOEgLSXZixtY0Tf5bVBmrGwjR0A30MaA8t2Ctvb38YIAeEgvb7CNkYIuPiSZtzbxogOEeun3da3MaJDxJy0jwfbGCFFXvPTpvPbGCEg/Zpm3N/GYL/godBSjKVtjOTBx7c048E2RvLgz3s6CfpvMHDHSi96dxsjBGIbpi0XtzGigzujdLz3tzGigzu9tOnSNlaE9EtpDFxUUlgB@DJpDLzm0xg4s0OxhTDHtpVsFz0xaUrWr1p0RptyZvSg/86odBurbbGN2x79rebaIq@1C@18m2jAFWhqDrp1ttnfZdfgM5HWep29vVu9jpaJGkbXBYUL4w2aXUOaobXuEyotcV5DPW1Dh@IhITHfuj@RO2AXPMCteAgu5E8QdeEp4YlxpOaAxDyLrcN6JsxNXpMp2gUXIMURzDJRAKOKNjG6l4DGbPIJKPhg7H0w9rTaknGDbUlJ4lD2DT6KzZ0gqhq2OMaNKkskrLDQ8pkGUNpeCynvnVyPagv9NQSWxOLTiRerMZIFbBOW03hxViy1AG/Llx8qVeZbeJnac5N4fIXI1CoQl1mSXBbZVdzi@JwlmthP7ErsSZL13wkKaHl0rCVEG/Sxa3Ud1zS5NuHEiK0EtyZjb/BgBy99xw9HUobfUTqUu02waGiPMQ@tx3ZE5PaCkpq4TRKate5SMO1ijiaEk6n0MYy5MnfCycysuEgMbvL/ibnGa13fsZ7ZBPJWwZw7Hk@QNw7RyArtp4H3yAGrsFyuhEWti4lI@RU2VuJJhk10NuZh/E8y3mFj4IE@ZD0o9Md@EiZwxjDESDA@GlRYCKL46z@NysWpKbThFqU@qA@36qtqq6H6oo7gRwJoNVOAiai@OlM9tadabCapL7eqJXyqfmtcnzauTUH4Ffi2KXw5Pas3IkiSFDhOTwx8uFBhNlz0p54dDsYeauKaGH1vPct/Y7Fj1gwYdiRpRT/FYuQ74dT3UEYCnhXlrxUF8COyovy9olB1K8L1BoGaVMga@RZfidGVCVzMDUUxEuarFc8UV8Vo4g@8EFVX6Bm@ku8@dMOF0R14zpF@zOtlZc2xr7EBnhisUO5ZFUpQLxwnbkAohrbN/6Dmp565ZruCL5YeXcw5yCxcnOildBCiNdMTWPrr08B1cAZCKo7XIwmTCMD5fIpvgbYieLgu38g12RVpFplgdGMCj@GaruM9hk/4RjRofdXhZls/NF1DnGJcM2EtQejjG7kuSTIRxX85ti7uuCYVS@XirrhYGRmA9SY@2zD8gC/kqnwn/xSjC5NTH8qoAQ1ioZ5jD0Zw04TFOo@OD9/JNOSMqgnixh34QH2hJQ7uFvcPq9ls9XC3JLKWMwCr/svdF1uF3Q4Pu8WdWSwq1UQ47kpgwaVYjBQhIFXTLOTFKGaBR0A48KbOgkacslYPiyXgOdrdFykUG1@ZjTWLP038U0RVpVgyaPaMJr7L/Vxbq72MfhNfbwQhWBJu15P1AjkZyjdiVDd1ZnFosjqG8A9p2cpDRemYNzRRdFbvMBDy0GHzYWct9P7KNEQUs/4Uc7QG1gy@rppm25sZvpSZrQy0I41wBmaXrERuzMtDypvI3qyE3v4odPR7ofcPN6gUc0PZcCVcLuYJetfcII2A9AzFguCN1MSUvkbsYgsCGpf4X7TCm9g6BnHJopEo3yYRMVY7Rs4kSj6HrUNdzNGcwXctqP@k9Q2TjrlNFouHOVeEigEznLoDR4QK1ciV0Z3jw41p8DIIQA1HC4UmxToeHrnHwx237O4My2yssTHkaBHvsOCZqXegHOBZh9lO0IcnF9vUubktcsLKuT5EYoMr2bO5@fYz6w@vLDM@nuI7AVy54Liir13F957J3J7CqCcgASn9/PIcgytME2dF@txbc8dhxRyfjxEULivoZ0kyJGl4iOkmTIsWQh6Hf5hMYSAav18GXW7PcR14EUOeoRWS7QkaRJLqhyAukbgl2ElTZxolAn0Sb/pSPO8sBIOeVPRPAXBpshH7c8GUdsh4RB@/APpb4CqGvSJSGsUNhvkcT@AhXoHX/aAnO@Fg5MgTezKVX4J3owdPeHE9B8U/P3VRaA1cuMgW1wJML9NRiV5o2LVJmFuvz6ALWaaSJ8X9YqmwVywhIbIkk9cXp41acmpYcAfgPv3f@U@0JtGhHw4SAAc@x0gCr8NtDP5xKIjTg7mdMSfzuijMZ5b/CDGoz1CSuRn69CuPCmgX/pMCypP/Ag "ksh – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` δV≠İf ``` [Try it online!](https://tio.run/##yygtzv7//9yWsEedC45sSPv//3@0oY6hjpGOpY6pjoWOoXEsAA "Husk – Try It Online") You know it's a good day when you get to use `decorV` in an answer. ]
[Question] [ Carry sort is an \$O(n)\$ "sorting" algorithm. Here's how it works. The algorithm moves left to right along a list. As it traverses a list it "carries" a single item, the largest item it has encountered so far. Once it encounters a larger item it picks up that item and drops the item it is already carrying in place. When it gets to the end it drops the item that it is carrying (the largest item in the list) at the end of the list. ### Worked example Here we are going to apply carry sort to the list `[1,2,0,3,2,1,2,4,3]` ``` [1,2,0,3,2,1,2,4,3] ^ [ 2,0,3,2,1,2,4,3] ^ 1 [ 1,0,3,2,1,2,4,3] ^ 2 [ 1,0,3,2,1,2,4,3] ^ 2 [ 1,0,2,2,1,2,4,3] ^ 3 [ 1,0,2,2,1,2,4,3] ^ 3 [ 1,0,2,2,1,2,4,3] ^ 3 [ 1,0,2,2,1,2,4,3] ^ 3 [ 1,0,2,2,1,2,3,3] ^ 4 [ 1,0,2,2,1,2,3,3] ^ 4 [ 1,0,2,2,1,2,3,3,4] ^ ``` Here we can see that carry sort has definitely made the list *more* sorted than it was, but it's not perfectly sorted. ## Task If you repeatedly apply carry sort to a list it will eventually sort the list. Your task is to take a list of integers and determine the minimum number of passes required for carry sort to sort the input list in ascending order. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` [] -> 0 [-2,3,9] -> 0 [4,1,2,3] -> 1 [1,3,2,4] -> 1 [4,3,2,1] -> 3 [0,-1,-2,-3,-4] -> 4 [1,2,0,3,2,1,2,4,3] -> 3 ``` [Answer] # [R](https://www.r-project.org), ~~41~~ ~~40~~ 35 bytes *Edit: -1 byte thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and -5 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* ``` \(x)max(order(y<-c(x,Inf))-seq(!y)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9NCsJADIX3nqLSTQIJzB-ioO69gxupnZ2KVWF6Fjej4KHEyzh_Feoq5HsvL8n90fmnXb1uV8vzd70Fh4edg1O3bzvol9yAo83RIvKlPcO0RyzWj4UGEOuK15WYxIalGPeKNC1GyJCkQAuTicngUmRGzCQmC9OJCWJJIZM18eA2JUGRyBMx6ZevixppvEUHzfzdYxJXaXbYN8svep_rFw) The idea is that we look how much to the right are the elements displaced in the input versus the sorted array, and take the maximum. This is because moving elements to the right is easy and to the left is hard (moving one space to the left requires exactly one pass). Example: ``` x = 1 2 0 3 2 1 2 4 3 sort(x) = 0 1 1 2 2 2 3 3 4 order(x) = 3 1 6 2 5 7 4 9 8 # positions of the input in the sorted array (sort(x) === x[order(x)]) order(x)-seq(x) = 2 -1 3 -2 0 1 -3 1 -1 # how far to the right is input vs sorted take max -> answer ``` [Answer] # JavaScript (ES6), 50 bytes This is inspired by [@pajonk's excellent answer](https://codegolf.stackexchange.com/a/259178/58563). But instead of explicitly sorting the input array, we subtract from the position of each element the number of elements that are less than or equal to it. ``` a=>a.map(m=(v,i)=>a.map(V=>i-=V<=v)|m>++i?0:m=i)|m ``` [Try it online!](https://tio.run/##hc6xDoIwFAXQ3a9gbMMrtLST8eFfsBiGBsHUUErEMPnvtVpdysDbbnJy373rVS/dw8xPNrlr7wf0GmtdWD0Ti2QFQ/@xwdowbE640pet89yc@dGiCcF3blrc2Beju5GBXNosPUqzssz4IYFMQAWy3YcKUhmhSKEAGaDah@oLxQbKFHIIK1kFTAKLvRGq7esKeGz9TAhrf43@DQ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(m = // initialize m to a non-numeric value (v, i) => // for each value v at position i in a[]: a.map(V => // for each value V in a[]: i -= // decrement i if V <= v // V is less than or equal to v ) | // end of inner map() m > ++i ? // increment i; if m is greater than i: 0 // do nothing : // else: m = i // update m to i ) | m // end of outer map(); return m ``` --- # JavaScript (ES6), 66 bytes [-1](https://tio.run/##jc6xDoIwEAbg3aeABdpwLRS6aCyG52g6NAhGQykR09evVZzAgVsuuXz5739op@f2eZ9eZLTXzvteNKJG0gClVCshw2oAFGihqdETcqJ2Z3NxJ5PF0ginMI5Fk6VpkrCsRxr71o6zHTo62BsKF6mi9WAc5XlUHNaSlFDBUe2QHBgErNaSbSQLkSXwHZJ/JdvIaiMLIAxCWVIBWZIXyf98L6FYcj8tQuNfpn8D) if we return *false* for 0. ``` f=A=>([m,...a]=[...A,,],a=a.map(v=>v<m?v:m+![m=v]))==A+''?0:1+f(a) ``` [Try it online!](https://tio.run/##hc6xDoMgFIXhvU9hJyFeEJSlpmh8DsNArDZtRExteH1KayccZGH58t/z1E6v/euxvMlsb4P3o2xljToDlFKtZBe@FkCBlpoavSAna3c1jatMdu6MdApjKdssTRtW8WxEGvvezqudBjrZOxpRp5L4YZzkecJOESQFlHBRx1AAh2BVDHkMeQgWII6h@EG@g2UMGRAOYSgpgWzdDYr96QLYVv1OCGv/Rf8B "JavaScript (Node.js) – Try It Online") ### Commented ``` f = A => // recursive function taking the input array A[] ( // split into: [ m, // m = first element ...a ] = // a[] = all remaining elements // the array defined as: [ ...A,, ], // A[] padded with a trailing undefined value a = a.map(v => // for each element v in a[]: v < m ? // if v is less than m: v // leave v unchanged : // else: m + ![m = v] // put m here and update m to v ) // end of map(); save the result in a[] ) == A + '' ? // if a[] is equal to A[]: 0 // stop : // else: 1 + // increment the final result and do f(a) // a recursive call with the updated array ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~53~~ ~~33~~ 31 bytes ``` ≔⟦⟧ηW⁻θυ«⊞υ⌊ιF⌕Aθ⌊ι⊞η⁻κLη»I∨⌈η⁰ ``` [Try it online!](https://tio.run/##TYyxCsIwEEDn9ituvMAJ1bo5FcHJYvfSIdTaHKYpJo0K4rfHpJPLcbx773olbT9LHULlHI8G245AiUP@UqwHwJqNd/gg8ELAJ88a7xR6gsh58hOyiG52my3gic210jrJf1cBa6JWGF/dCc6DGZeIRGq/eWPZLHiUbsGLxVq@11QJgiIZIbTtlnZUUBln2vZUdl3YPPUP "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Having written my [comment](https://codegolf.stackexchange.com/q/259167#comment571526_259167), I finally got around to implementing a version using grade up. ``` ≔⟦⟧η ``` Start with an empty list. ``` W⁻θυ« ``` Repeat until the list has been graded. ``` ⊞υ⌊ι ``` Track the elements already graded. ``` F⌕Aθ⌊ι⊞η⁻κLη ``` Save the offsets of each matching element in the list. ``` »I∨⌈η⁰ ``` Output the maximum, or `0` if the list was empty. [Answer] # Excel (ms365), 137 bytes Within the windows version one can create their own named function using the named manager. Here we will create a function named 'Z': ``` =LAMBDA(a,b,IF(AND(a=SORT(a)),b,Z(DROP(REDUCE({0;0},a,LAMBDA(c,d,LET(y,TAKE(c,-1),IF(d>y,VSTACK(c,d),VSTACK(DROP(c,-1),d,y))))),2),b+1))) ``` Now you can call 'Z' using: ``` =Z(<YourVerticalRange>,0) ``` For example: [![enter image description here](https://i.stack.imgur.com/kZOUI.png)](https://i.stack.imgur.com/kZOUI.png) --- If one would like to try this online, I tried to mimic this using Google Sheets: ``` =LAMBDA(a,b,IF(INDEX(AND(a=SORT(a))),b,Z(QUERY(REDUCE({0;0},a,LAMBDA(c,d,LET(y,INDEX(c,COUNT(c)),IF(d>y,VSTACK(c,d),VSTACK(QUERY(c,"limit "&COUNT(c)-1),d,y))))),"offset 2"),b+1)))(a,b) ``` [![enter image description here](https://i.stack.imgur.com/ZDCWk.png)](https://i.stack.imgur.com/ZDCWk.png) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 25 bytes ``` {:ÞṠ¬|÷^!(~<ß$‟)„$‟^W&›}¥ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiezrDnuG5oMKsfMO3XiEofjzDnyTigJ8p4oCeJOKAn15XJuKAun3CpSIsIiIsIltdXG5bLTIsMyw5XVxuWzQsMSwyLDNdXG5bMSwzLDIsNF1cbls0LDMsMiwxXVxuWzAsLTEsLTIsLTMsLTRdXG5bMSwyLDAsMywyLDEsMiw0LDNdIl0=) Count how many times the sweep is applied until it's sorted. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ΔZªćUεDX›iXsU]N ``` -4 bytes porting [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/259169/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f//3JSoQ6uOtIee2@oS8ahhV2ZEcWis3///0YY6RjoGOsZAEsQy0TGO/a@rm5evm5NYVQkA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKSvdL/c1OiDq060h56bqtLxKOGXZkRxaGxfv@V9MJ0uEAqucozMnNSFYpSE1MUMvO4UvK5FBT08wtK9CEGQikUO3R18/J1cxKrKoG22SiogHXlpf6PjuWK1jXSMdaxBDJMdAx1gGwgyxAoYqRjAhYDsQyBLAMdXUMdoFpdYx1dE7AaIx0DiCxILUgfAA). **Original 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` Δā<ü2vDyè©`›i®yRǝ]N ``` [Try it online](https://tio.run/##yy9OTMpM/f//3JQjjTaH9xiVuVQeXnFoZcKjhl2Zh9ZVBh2fG@v3/3@0oY6RjoGOMZAEsUx0jGMB) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKSvdL/c1OONNoc3mNU5lJ5eMWhlTEJjxp2ZR5aVxl0fG6s338lvTAdLpAOrvKMzJxUhaLUxBSFzDyulHwuBQX9/IISfYjBUArNLhsFFbDavNT/0bFc0bpGOsY6lkCGiY6hDpANZBkCRYx0TMBiIJYhkGWgo2uoA1Sra6yjawJWY6RjAJEFqQXpAwA). **Explanation:** ``` Δ # Loop until the result no longer changes (aka, until it's sorted), # using the (implicit) input-list Z # Push the maximum of the list (without popping) ª # Append this maximum to the list ć # Extract head; pop and push remainder-list and first item # separately to the stack U # Pop and store this first item in variable `X` ε # Map over the remainder-list: D # Duplicate the current integer X›i # Pop the copy, and if it's larger than `X`: X # Push `X` sU # Swap, pop, and store the current integer as new `X` # (implicit else: keep the current integer, hence the need for the # `D`uplicate before the if-statement) ] # Close the if-statement; map; and changes-loop N # Push the final (0-based) index of the changes-loop # (which is output implicitly as result) ``` ``` Δ ]N # Same as above: ā # Push a list in the range [1,length] (without popping) < # Decrease it to 0-based range [0,length) ü2 # Get all overlapping pairs of this index-list v # Pop and loop over each index-pair `y`: Dyè # Get the values at indices `y` in a copy of the current list © # Store this pair of values in variable `®` (without popping) `›i # Pop the pair, and if the first is larger than the second: ®yRǝ # Swap the values at the index-pair `y` within the list: ® # Push values-pair `®` yR # Push the reversed of index-pair `y` ǝ # Insert the values at those reversed indices to the list ``` [Answer] # [R](https://www.r-project.org), ~~90~~ 82 bytes *Edit: -8 bytes thanks to Giuseppe* ``` f=\(l)`if`(is.unsorted(l),{l[c(F,d,T)]=l[c(T,d<-diff(cummax(l))>0)];f(l[-1])+1},0) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN4PSbGM0cjQTMtMSNDKL9UrzivOLSlJTgEI61TnRyRpuOik6IZqxtiB2iE6KjW5KZlqaRnJpbm5iBVCRpp2BZqx1mkZOtK5hrKa2Ya2OgSbU5FlAZRqamgrKCrp2CgZcIJ6ukY6xjiWqmImOoQ5QGCZoCBY0BKoz0jFBFTQBCxrCBI3BggY6uoY6QHN1jXV04epNoIYY6RhA9IAMQ9hhDHEhLAwA) Recursively performs carry-sort and counts how many times it's needed until the argument is sorted. Take a look at [pajonk's much more elegant and shorter approach](https://codegolf.stackexchange.com/a/259178/95126) that simply calculates the right answer directly, though... [Answer] # [Python](https://www.python.org) + numpy, ~~67~~ 65 bytes *Edit: -2 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs).* ``` lambda x:len(x)and max(argsort(x)-r_[:len(x)]) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3HXMSc5NSEhUqrHJS8zQqNBPzUhRyEys0EovSi_OLSoAiukXx0VDJWE2utKL8XIW80tyCSoXM3AKgCi2oQXsLijLzSjTSNKJjNTWVFXTtFAy44EK6RjrGOpZYJEx0DHWAcjAZQ4SMIVCHkY4JFhkTsIwhTMYYIWOgo2uoA7RL11hHF67TBNlMIx0DiG6Q2Qh7jSGeWLAAQgMA) Port of [my R answer](https://codegolf.stackexchange.com/a/259178/55372). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~47 ...~~ 41 bytes ``` ->l{l.map{*l,c=l;l.count{|a|a>c}}.max||0} ``` [Try it online!](https://tio.run/##Xc3BCsIwDAbgu09R8CbJaNpeRNYXGTvUwk5RhzhwtH32WleqsGO@5P/zXK5rnvqMlgN3NzeHE4Pv@cKdfyz3V4guOutTKrt3jDLlWUzDMI7iKNAKedhGVKDhvEMDBMWbUlUqlwrMTs2m1FRXlYAEpRs14C9hWo8CWVPfvv8fnT8 "Ruby – Try It Online") [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 7 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) Another port of [pajonks R answer](https://codegolf.stackexchange.com/a/259178/64121). ``` 0⌈´⍋-⊒˜ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkDDijIjCtOKNiy3iipLLnAoKdGVzdHMg4oaQIOKfqOKfqOKfqSzin6gtMiwzLDnin6ks4p+oNCwxLDIsM+KfqSzin6gxLDMsMiw04p+pLOKfqDQsMywyLDHin6ks4p+oMCwtMSwtMiwtMywtNOKfqSzin6gxLDIsMCwzLDIsMSwyLDQsM+KfqeKfqQoKPuKLiOKfnEbCqHRlc3Rz) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, ~~9 7~~ 6 bytes ``` ⇧$ẏ-0J ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwi4oenJOG6jy0wSiIsIiIsIls0LDMsMiwxXSJd) or [verify all test cases](https://vyxal.pythonanywhere.com/#WyJBRyIsIiIsIuKHpyThuo8tMEoiLCIiLCJbXSAjLT4gMFxuWy0yLDMsOV0gIy0+IDBcbls0LDEsMiwzXSAjLT4gMVxuWzEsMywyLDRdICMtPiAxXG5bNCwzLDIsMV0gIy0+IDNcblswLC0xLC0yLC0zLC00XSAjLT4gNFxuWzEsMiwwLDMsMiwxLDIsNCwzXSAjLT4gMyJd) Port of [@pajonk's R answer](https://codegolf.stackexchange.com/a/259178/114446) *-2 thanks to @Neil* #### Explanation ``` ⇧$ẏ-0J # Implicit input ⇧ # Grade up: push the indices which will sort the list $ẏ # Swap and push a list in the range [0, len(input)) - # Subtract the range from the grade up list 0J # Append a 0 to this list # G flag gets the maximum # Implicit output ``` Old: ``` [⇧›$ż-G|0 # Implicit input [ # If it isn't empty: ⇧ # Grade up: push the indices which will sort the list › # Increment it to make it one-indexed $ż # Swap and push a list in the range [1, len(input)] - # Subtract the range from the grade up list G # Pop and push the maximum item |0 # Otherwise, push 0 # Implicit output ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ụ_JṀ ``` A monadic Link that accepts the list and yields the number of required passes. **[Try it online!](https://tio.run/##y0rNyan8///h7iXxXg93Nvw/3P6oac3//9HRsTpcCtG6RjrGOpZgpomOoQ6QB2YbAkWNdEyg4iC2IZhtoKNrqAPUo2uso2sCVWmkYwBRAdIB1h8LAA "Jelly – Try It Online")** ### How? Just as [pajonk's](https://codegolf.stackexchange.com/users/55372/pajonk) [R answer](https://codegolf.stackexchange.com/a/259178/53748), but with automatic `0` as the maximum of an empty list. ``` Ụ_JṀ - Link: List, A Ụ - grade-up (A) -> list of 1-indexed indices of the sorted values J - range of length (A) -> 1-based indices = [1..length(A)] _ - (graded indices) subtract (indices) Ṁ - maximum (the maximum of an empty list is 0) ``` [Answer] # [J](http://jsoftware.com/), 14 bytes ``` [:>./0,/:-i.@# ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PQNdPStdDP1HJT/a3KlJmfkK6QpKKirw5nxRgrGCpZwromCoQJQBM43BMoaKZggyYP4hnC@gUK8IciMeGOFeBMkXUZAGbBKkG6geVx@TnoKrhUFqcklqSkgNxoApUCGAyX/AwA "J – Try It Online") ## Explanation Same approach as a few answers. ``` [:>./0,/:-i.@# /: grade up input - and subtract from each position i.@# the corresponding element in the range [0, size) 0, prepend zero (edge case of empty lists) [: and then >./ take the maximum of that array (which is otherwise -∞ for empty lists) ``` [Answer] # [Factor](https://factorcode.org/), 46 bytes ``` [ arg-sort [ - ] map-index 0 suffix supremum ] ``` [Try it online!](https://tio.run/##TY69DoJAEIR7nmJ8gCMcR6MmtsbGxlgRigscSsGPe0eCITz7uRBQq518s18ypc5dS/5@u1zPB1jz6k2TGxuawZG2P4Bau2fYUmFoiejIOPfuqGocjkEwBiMm7CBOiDiKGAr7f5JAYoYrkgtSjOSGFKMIQs6yUBDJViRczHK0/seL@bUmn0LTQ9iWHFIIZLywE1VTmIEd25dlNfDhxXVfI/PcIvQf "Factor – Try It Online") Port of @TheThonnu's [Vyxal answer](https://codegolf.stackexchange.com/a/259179/97916). * `arg-sort` Get the indices that would sort the sequence. (aka grade up/inverse permutation) * `[ - ] map-index` Subtract each index from its element. * `0 suffix` Append a 0. * `supremum` Get the maximum element. [Answer] # [Desmos](https://www.desmos.com), ~~52~~ 48 bytes ``` s=[0...x.length] f(x)=max(sort(s,join(0/0,x))-s) ``` [Try it on Desmos!](https://www.desmos.com/calculator/sk6iqn4ddv) One of the only times where 0/0 is useful. Based on [pajonk's answer](https://codegolf.stackexchange.com/a/259178/58563). -4 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow). [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 9 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ⌈/0,⍋-⍳∘≢ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TToW@g86i3W/dR7@ZHHTMedS4CAA&f=S@NKU3jUuwZIHlpvpGCsYAlkmSgYKgDZQJYhUMRIwQQsBmIZAlkGQJWGYNWH1hsDsQlYnRFQHKwCpF7BGAA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f) ### Explanation ``` ⌈/0,⍋-⍳∘≢ ≢ ⍝ length of the input ⍳∘ ⍝ create a range from 1 to the length - ⍝ subtract that list from... ⍋ ⍝ the input graded up 0, ⍝ prepend a zero ⌈/ ⍝ get the maximum of the resulting list ``` Just for reference, this is what the train tree looks like: ``` ┌─┴─┐ / ┌─┼───┐ ┌─┘ 0 , ┌─┼─┐ ⌈ ⍋ - ∘ ┌┴┐ ⍳ ≢ ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 66 bytes --- Golfed version, [try it online!](https://tio.run/##fc/PasJAEAbwu08xECgadt2sWYRWlHi3rYi3EGQxmz8HV4kjBEo99yl8uL5I3JjEQKO97vz2m292EhO1k5huZRH5@WaRHjGAtykU@Xl@OCgdnn9/Lox9ZqHKUh0z9i5z36IrqWPl2QulY0w8iw3XSaZk6H/s0bPojAfBy6To9W2ITnqL6V4DqiOaALAHvcj/@g4YW5pABGPoDJz6nXKnHf2djQi4BF6fAkGAEyhVh/Ca8FuEIeIpEQ3hHeLWxCFATVJZiBpLu2Gi3WeQc4@sdj9q6LY/KlVd6964@O9m0cBRs6PbfFzy4go) ``` x~Append~∞//Ordering//Max[#-Range@*Length@#/.Thread[Not@#->1]]&; ``` Ungolfed version ``` f[x_List] := Module[{y, yOrder, seqY}, y = Append[x, Infinity]; yOrder = Ordering[y]; seqY = Range[Length[yOrder]] /. Thread[Not[yOrder] -> 1]; Max[yOrder - seqY] ] (* function testing *) f[{}]//Print (* -> 0 *) f[{-10}]//Print (* -> 0 *) f[{-2, 3, 9}]//Print (* -> 0 *) f[{4, 1, 2, 3}]//Print (* -> 1 *) f[{1, 3, 2, 4}]//Print (* -> 1 *) f[{4, 3, 2, 1}]//Print (* -> 3 *) f[{0, -1, -2, -3, -4}]//Print (* -> 4 *) f[{1, 2, 0, 3, 2, 1, 2, 4, 3}]//Print (* -> 3 *) f[{1, 1, 2, 2, 3, 3, 4, 4}]//Print (* -> 0 *) f[{4, 4, 3, 3, 2, 2, 1, 1}]//Print (* -> 6 *) ``` ]
[Question] [ Your task is to write a program or function which takes a pure brainflak program as input (assume it contains only balanced `()[]{}<>`), and output a visually mirrored copy of it. If you reversed a brainflak program as a string, say `({}())` (add one to an input), you would get `))(}{(`, which is not valid. Instead, you should mirror it, by reversing the direction of the parentheses/brackets/braces/angle-brackets, like what you would see if the program was placed in front of a mirror: `((){})`. Test cases (`???` means anything is okay): ``` () -> () ({}[{}]) -> ([{}]{}) ()[] -> []() <(){}[]> -> <[]{}()> ([{<()[]{}<>>}]) ->([{<<>{}[]()>}]) (a) -> ??? {> -> ??? ))(}{( -> ??? ()↵[] -> ??? ``` This is a code golf challenge, shortest answer per language wins. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 3 bytes ``` S‖T ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMzr6C0JLgEyE7X0NS05gpKTctJTS4JKUrMK07LL8rV0LT@/18jutpGQzM6trrWxs6uNlbzv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: `S` reads the input and implicitly echos it, while `‖` is the mirroring operator, which normally just reverses the input, but the `T` modifies it to mirror the characters at the same time. [Answer] # [Python 3](https://docs.python.org/3/), 47 bytes ``` lambda x:x[::-1].translate('>]<[)('*20+'}_{'*2) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqiLaykrXMFavpCgxrzgnsSRVQ90u1iZaU0Ndy8hAW702vhrI0PxfUJSZV6KRpqGkEW1TXWsXq6mkqfkfAA "Python 3 – Try It Online") Python has a convenient string method `translate` that accepts a translation string `s`, and maps each character `c` to `s[ord(c)]`. So, we just need to make a translation string with the right characters at the positions of ASCII values `[40, 41, 60, 62, 91, 93, 123, 125]` of `()<>[]{}`. The ideal would be to make the table like `'????????'*16`, putting the correct character for each ASCII value modulo 8. Unfortunately, the values `[40, 41, 60, 62, 91, 93, 123, 125]` are not distinct modulo 8, and the first modulus making them distinct is 18, which would mean something like `'??????????????????'*6`. However, conveniently, the lowest 6 ASCII values `[40, 41, 60, 62, 91, 93]` are distinct modulo 6. That lets us handle them with `'>]<[)('*20`, translating ASCII values 0 through 119. For the remaining two, 123 and 125, we use `'}_{'*2` to hit the next 6 ASCII values 120 to 125. Python 3 lets us stop there, unlike Python 2, which requires the translation string to be length 256 exactly. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~51 47~~ 44 bytes *Saved 3 bytes thanks to @xnor* ``` s=>Buffer(s).map(c=>c^68%c/3%8).reverse()+'' ``` [Try it online!](https://tio.run/##Zc7RCsIgFMbx@55iDMbOYbRdBLEL50WvIQbDNIo1h9ZuxGc3jSCaXn78zw/v4zpaYW7Lcz/riwxqCHagp5dS0oDF9jEuIAYqzse@Et2h6rE1cpXGSsCmroPQs9WTbCd9BQUlYFn8PcSi6wrA3TZ0njnPf/k3TKPzeY6Ml7nLeC4TwGhzupEJiy4gzWTmSNKdJ5SmD33ytBKanHgS1/AG "JavaScript (Node.js) – Try It Online") ### How? For each pair of characters, we can switch from the 1st to the 2nd character (and vice versa) by XOR'ing the ASCII code with \$1\$, \$2\$ or \$6\$. ``` char 1 | code | XOR | code | char 2 --------+------+-----+------+-------- '(' | 40 | 1 | 41 | ')' '<' | 60 | 2 | 62 | '>' '[' | 91 | 6 | 93 | ']' '{' | 123 | 6 | 125 | '}' ``` Given an ASCII code \$c\$, we can turn it into the correct XOR value by using the following function: $$f(c)=\left\lfloor((68 \bmod c)/3)\bmod 8\right\rfloor$$ ``` c | 68 mod c | / 3 | mod 8 | floor ------+----------+--------+-------+------- 40 | 28 | 9.333 | 1.333 | 1 41 | 27 | 9 | 1 | 1 ------+----------+--------+-------+------- 60 | 8 | 2.667 | 2.667 | 2 62 | 6 | 2 | 2 | 2 ------+----------+--------+-------+------- 91 | 68 | 22.667 | 6.667 | 6 93 | 68 | 22.667 | 6.667 | 6 123 | 68 | 22.667 | 6.667 | 6 125 | 68 | 22.667 | 6.667 | 6 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes *Saved 1 byte thanks to @JonathanAllan* ``` O&80%15‘^OỌṚ ``` [Try it online!](https://tio.run/##y0rNyan8/99fzcJA1dD0UcOMOP@Hu3se7pz1//9/jehqGw3N6NjqWhs7u9pYTQA "Jelly – Try It Online") ### How? The idea here is to XOR the ASCII codes to turn each character into its mirrored counterpart, like I did in my [JS answer](https://codegolf.stackexchange.com/a/195606/58563). But we use a formula that is bit golfier in Jelly: $$f(c)=((c\text{ & }80)\bmod 15)+1$$ where \$\text{&}\$ is a bitwise AND. ``` char | code | and 80 | mod 15 | + 1 | XOR code | new char ------+------+--------+--------+------+----------+---------- '(' | 40 | 0 | 0 | 1 | 41 | ')' ')' | 41 | 0 | 0 | 1 | 40 | '(' ------+------+--------+--------+------+----------+---------- '<' | 60 | 16 | 1 | 2 | 62 | '>' '>' | 62 | 16 | 1 | 2 | 60 | '<' ------+------+--------+--------+------+----------+---------- '[' | 91 | 80 | 5 | 6 | 93 | ']' ']' | 93 | 80 | 5 | 6 | 91 | '[' '{' | 123 | 80 | 5 | 6 | 125 | '}' '}' | 125 | 80 | 5 | 6 | 123 | '{' ``` ### Commented ``` O&80%15‘^OỌṚ - a monadic link taking a string, e.g. "(<>[])" O - convert the input to ASCII codes --> [40, 60, 62, 91, 93, 41] &80 - bitwise AND with 80 --> [ 0, 16, 16, 80, 80, 0] %15 - modulo 15 --> [ 0, 1, 1, 5, 5, 0] ‘ - increment --> [ 1, 2, 2, 6, 6, 1] O - input to ASCII codes again --> [40, 60, 62, 91, 93, 41] ^ - bitwise XOR --> [41, 62, 60, 93, 91, 40] Ọ - convert back to characters --> ")><][(" Ṛ - reverse --> "([]<>)" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` º2äθ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//0C6jw0vO7fj/X6O6Nrq6NlYTAA "05AB1E – Try It Online") or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@f/QLqPDS87t@K@k8KhtkoJSpb29zv9oJQ1NJR0FJY3q2ujq2lgIWzM6FkTbaGgCRWPtwGLR1TYg8epaGzs7kLpYAA "05AB1E – Try It Online") **Explanation** ``` º | Mirror (i.e. "({}[{}])" -> "({}[{}])([{}]{})" 2ä | Split into two pieces θ | Take the last piece ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ↔ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMTk0,i=JTI3JTI4JTVCJTdCJTNDJTI4JTI5JTVCJTVEJTdCJTdEJTNDJTNFJTNFJTdEJTVEJTI5JTI3,v=8) Surprised that this is the first 1-byte answer. [Answer] # [J](http://jsoftware.com/), 24 bytes ``` |.rplc(;"0|.)@'([{<>}])' ``` [Try it online!](https://tio.run/##XY1NC8IwDIbv@xVhlyTgys41loHgyZPX0tNwiAiK166/vaaObmKghDzvR@@5NTjBwQLCDnqw@joDx8v5lGfzfj1G2rf9bHhA8lFcCoyZm@Y63p4wAVJMPha4EKybGKGzX8eqUXHGtCl/WR9@Uz5ULl5TxK5qQqzJoPc62w8irohqL821TXlpjEncwvMH "J – Try It Online") Test cases by Jonah. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 20 bytes ``` O^$`. T`([{<>}])`Ro ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3z9OJUGPiyskQSO62sauNlYzISj//38NTS6N6troaiCfS0MzOpbLRkMTyI@14wIpA4lU19rYgZQDAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` O`. ``` Sort individual characters... ``` $ ``` ... by substitution value (constant empty string, therefore keeps original order)... ``` ^ ``` ... with reversed sort order (i.e. reversing the string). ``` T`([{<>}]) ``` Substitute each character of `([{<>}])`... ``` `Ro ``` ... with the matching character from the reverse of that string, thus mirroring those characters. [Answer] # [J](http://jsoftware.com/), ~~32~~ 25 bytes ``` '([{<)]}>'|.@([{~8|4+i.)] ``` [Try it online!](https://tio.run/##XU29CsJADN77FMElCdrDwUFKegiCk5PrkUks6uIDXM9XP3OWa8VASPL95ZlXDgfoO0DYwBY669bB8XI@ZaQQhTV5HN3B9vd@3K0fjjVz09yu9xcMgBRTiEkZJwTrJEZou69i5qgoY1qYP2/QX1fQikswF7GvnBCbU@2ea/kg4gtp8pJc0wwviTGJn/D8AQ "J – Try It Online") Quick explanation: * Find the index of each input char within the string `'([{<)]}>'`. * Add 4 to it to get its mirror * Take that mod 8 to handle wrapping around to the beginning * Use the result to index back into `'([{<)]}>'` * And reverse that result [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Blatant port of [Arnauld's JS solution](https://codegolf.stackexchange.com/a/195606/58974) so go upvote him. ``` ÔcÈ^68%X/3%8 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1GPIXjY4JVgvMyU4&input=IihbezwoKVtde308Pj59XSki) [Answer] # [Python 3](https://docs.python.org/3/), 61 bytes ``` lambda x,s="([<{}>])":"".join(s[7-s.find(c)]for c in x[::-1]) ``` [Try it online!](https://tio.run/##BcFRCoQgEADQq4hfM1BB7Ecg1UXMj7aQJmqUNHARz@6@53/xcPypdlrqtd7ffRWpCZMEPeYyG5RKyu50xBD00IbOEu@wobHuEZsgFkkr1fYGq3@II1gg9m8ERKyQi87F4B8 "Python 3 – Try It Online") [Answer] # [Icon](https://github.com/gtownsend/icon), 67 bytes ``` procedure f(s) r:="reverse" return map(r(s),d:="([{<>}])",r(d)) end ``` [Try it online!](https://tio.run/##TYwxCoAwEAT7vCKkugNfIOpHxELMCSmMsolahLw9RrBw2pldt@y@lAP7IvaE6JUCK7S9gVyCIEZB4gmvt/kgVNnYKmlM3ZAnNg3IMivx9vexzc4TK1254aLQSoZSHtO7@OoH "Icon – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) This approach has many 13-byte solutions, although I can golf [Arnauld's 13 byter](https://codegolf.stackexchange.com/a/195628/53748) to 12 bytes. ``` QṢiⱮịQṢṭ2/FƲṚ ``` **[Try it online!](https://tio.run/##y0rNyan8/z/w4c5FmY82rnu4uxvEfLhzrZG@27FND3fO@v//v7pGdLWNhmZ0bHWtjZ1dbaymOgA "Jelly – Try It Online")** ### How? ``` QṢiⱮịQṢṭ2/FƲṚ - Link: list of characters, P Q - de-duplicate (P) Ṣ - sort (call this X) Ɱ - map across (p in) P with: i - first index of (p) in (X) Ʋ - last four links as a monad - i.e. f(P): Q - de-duplicate (P) Ṣ - sort 2/ - 2-wise reduce with: ṭ - tack F - flatten (i.e. pair-wise reversal of sorted unique values) ị - (left) index into (right) Ṛ - reverse ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 302 bytes ``` {(({}(<()>))<({}[(((()()()()()){}){}){}])>{[()](<()>)}{}<({}[()])>{()(<()>)}{}<({}[(((()()())){}{}){}()])>{[()()](<()>)}{}<({}[()()])>{()()(<()>)}{}<({}[(((()()()){}()){}){}()])>{[()()](<()>)}{}<({}[()()])>{()()(<()>)}{}<({}[(((()()()()()){})){}{}])>{[()()](<()>)}{}<({}[()()])>{()()(<()>)}{}<>)<>{}}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1pDo7pWw0ZD005T0wbIjNYAAk0Y1KyuhaBYTbvqaA3NWIjK2upaiFpNkDhQIaoozASQdrBuiLpokBiGCXAzcJoC0q9JuTkw/4AdRZo5dpo2dtW1QHo0vEgML91kAA "Brain-Flak – Try It Online") This is (currently) very poorly golfed, but I thought there ought to be at least one Brain-Flak answer to this question. [Answer] # [Red](http://www.red-lang.org), 56 bytes ``` func[s][foreach c reverse s[prin select"[][()({}{<><"c]] ``` [Try it online!](https://tio.run/##TYo7CsMwDIb3nEJ4sq9QjA@R9UdDUWRaKEmR0y7CZ3fxlI7fw3Qbq27gpd5o1M8uaIx6mN7lQUKmX7Wm1PC2505NXypnACOm6N1zyUGYx4wnVQoxgcNyoXd45/Sv4Hle3nMpM40f "Red – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` “[({})]”©iⱮUịUɼ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xojepazdhHDXMPrcx8tHFd6MPd3aEn9/z//x8oHl1dG6sJAA "Jelly – Try It Online") A monadic link that reverses the input and input brackets of all their types. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 32 bytes ``` $_=reverse y/(){}[]<>/)(}{][></r ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3rYotSy1qDhVoVJfQ7O6NjrWxk5fU6O2Ojbazka/6P9/jehqGw3N6NjqWhs7u9pYzX/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~85~~ ~~84~~ ~~64~~ 60 bytes 60 bytes thanks to Neil ``` p;f(char*s){for(p=strlen(s);p--;)putchar(s[p]^68%s[p]/3%8);} ``` [Try it online!](https://tio.run/##FclBCoAgEADAe6@QINgNpEMQwtJLwiAkSyhb1E7i241OcxgjD2NqZbJgzi30EbN9AvAcU7h2DxGJpSTkN/0PcWG9Tqr7HcZOIZXqfBL35jxgboSw0EIuSy4aW6Sm1A8 "C (gcc) – Try It Online") ]
[Question] [ ## Description Write a program or function that takes in a positive integer \$n\$ as input and outputs all Sophie Germain primes that are safe primes less than or equal to \$n\$. A prime number \$p\$ is a Sophie Germain prime if \$2p+1\$ is also a prime. A prime number \$p\$ is a safe prime if \$p=2q+1\$, where \$q\$ is also a prime. The output should be a list of the Sophie Germain primes that are also safe primes, in ascending order only. ## Test Cases ``` [20] => 5, 11 [10000] => 5, 11, 23, 83, 179, 359, 719, 1019, 1439, 2039, 2063, 2459, 2819, 2903, 2963, 3023, 3623, 3779, 3803, 3863, 4919, 5399, 5639, 6899, 6983, 7079, 7643, 7823 [1000] => 5, 11, 23, 83, 179, 359, 719 ``` ## Task and Criterion Output primes \$p\$ such that both \$\frac{p-1}{2}\$ and \$2p+1\$ are prime less then, equal to a specific \$n\$ given in input. Shortest bytes answer will win, in case if bytes are equated, a tie will occur. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` [UUÑÄUz]ej ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=W1VV0cRVel1lag&input=MTAwMA) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Select[Range@#,And@@PrimeQ@{#,(#-1)/2,2#+1}&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277Pzg1JzW5JDooMS891UFZxzEvxcEhoCgzNzXQoVpZR0NZ11BT30jHSFnbsFYtVu0/UCqvREHfIV3fQaHayEDH0MAAQhjU/v8PAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [R](https://www.r-project.org), 71 bytes ``` f=\(n)if(n>4)c(f(n-1),n[all(Map(\(y)sum(!y%%2:y)<2,(n+1)*2^(-1:1)-1))]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGCpaUlaboWN93TbGM08jQz0zTy7Ew0kzWAtK6hpk5edGJOjoZvYoFGjEalZnFproZipaqqkVWlpo2RjkaetqGmllGchq6hlaEmULlmrCbEuE1pGoaGmlxpGkYGINLUwAAqAbMPAA) Heavily inspired by [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/258874/55372) to [Imtiaz Germain Primes](https://codegolf.stackexchange.com/q/258817/55372). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Lʒx>y2÷)pP ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f59SkCrtKo8PbNQsC/v83NAACAA) **Explanation:** ``` L # Push a list in the range [1, (implicit) input-integer] ʒ # Filter it by: x # Double the current value (without popping) > # And increase it by 1 y # Push the current value again 2÷ # Integer-divide it by 2 ) # Wrap all three values into a list: [n,2n+1,(n-1)/2] p # Check for each whether it's a prime number P # Check if all three are truthy # (after which the filtered list is output implicitly as result) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes ``` ':d›n‹½WæA ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInOmTigLpu4oC5wr1Xw6ZBIiwiIiwiMTAwMCJd) Ports japt. Quite literally get all numbers where n, 2n incremented, and n decremented halved are all prime. Here's a more fun 11 byter ## [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` ~æ~≬‹½æ'd›æ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ+w6Z+4oms4oC5wr3Dpidk4oC6w6YiLCIiLCIxMDAiXQ==) ## Explained ``` ~æ~≬‹½æ'd›æ ~æ # keep only from range [1, input] where prime ~≬--- # from that, keep where: ‹½ # (n - 1) / 2 æ # is prime ' # from that, keep where: d› # 2n + 1 æ # is prime ``` [Answer] # Java 8, ~~117~~ ~~115~~ 110 bytes ``` i->{for(;i-->5;)if(p(i)+p(i-~i)+p(i/2)<4)System.out.println(i);};int p(int i){for(int k=i;k%--i>0;);return i;} ``` Outputs each Sophie Safe prime on a separated newline in reversed order. Based on [my answer for the Imtiaz Germain Primes challenge](https://codegolf.stackexchange.com/a/258841/52210). [Try it online.](https://tio.run/##LY/PDoIwDMbvPEUvJlvMEI2eqryBXjgaD3MMU8BBxtAYg6@OBe2hf740v34t9UOrMq9GU@uug6Mm944AyAXrC20snKYR4NFQDkawDiSRpSHidAIHh5FU@i4aL5CUSncoqRCtILnkpD6/utrI/VZmry7Ye9z0IW49o2rHazjgRG3/7Jk0tdWBsFooRWmCEr0NvXdAOIw4XW77a00GuqADl9ndnb2LLDD4dr5o@fPt7HN@SsjYxUasE46//2H8Ag) **Explanation:** ``` i->{ // Method with integer parameter and no return-type for(;i-->5;) // Loop `i` in the range (input,5]: if(p(i) // If `i` is a prime number +p(i-~i) // and `2i+1` is a prime number +p(i/2) // and `i` integer-divided by 2 is a prime number <4) // (by checking if all three are 0 or 1) System.out.println(i);} // Print `i` with trailing newline // Separated method with integer as both parameter and return-type, // to check whether the given number (≥2) is a prime number (0 or 1) int p(int i){ for(int k=i; // Set `k` to the given integer `i` k%--i>0;); // Decrease `i` before every iteration with `--i` // Keep looping as long as `k` is NOT divisible by `i` return i;} // After the loop, return `i` // (if it's 1 or 0, it means it's a prime number) ``` [Answer] # JavaScript (ES6), 71 bytes ``` f=p=>p>4?f(p-1)+[[,p+' '][(P=x=>p%--x?P(x):x)(p)*P(p-=~p)*P(p>>=2)]]:'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbA1q7AzsQ@TaNA11BTOzpap0BbXUE9NlojwLYCKKWqq1thH6BRoWlVoalRoKkVAFRnWwdh2NnZGmnGxlqpq/9Pzs8rzs9J1cvJT9dI0zA0MDDQ1PwPAA "JavaScript (Node.js) – Try It Online") ### Commented ``` f = p => // recursive function taking a prime candidate p p > 4 ? // if p is greater than 4: f(p - 1) + // do a recursive call with p - 1 [[, p + ' '][ // append p followed by a space iff the following // result is 1: ( P = x => // helper recursive function taking x p % --x ? // decrement x; if x is not a divisor of p: P(x) // do recursive calls until it is : // else: x // return x (smallest proper divisor of p) )(p) * // first call with p P(p -= ~p) * // second call with 2p + 1 P(p >>= 2) // third call with floor((2p + 1) / 4) which is // (p - 1) / 2 if p is odd // the product is 1 iff all calls return 1, ]] // i.e. all tested numbers are prime : // else: '' // stop ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno) `+`, \$ 16 \log\_{256}(96) \approx\$ 13.17 bytes ``` gzt2*1+s2,ZPsTNP ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSStlLsgqWlJWm6FhvSq0qMtAy1i410ogKKQ_wCIMJQ2QWLjAwgLAA) #### Explanation ``` gzt2*1+s2,ZPsTNP # Implicit input g # Filter [1..input] by the following: n zt # Triplicate the number n, n, n 2*1+ # Multiply by two and add one n, n, 2n+1 s2, # Swap and integer divide by two n, 2n+1, n//2 ZP # Pair the top two items n, [2n+1, n//2] sT # Swap and append to the list [2n+1, n//2, n] NP # Are they all prime? ``` [Answer] # [Raku](https://raku.org/), 41 bytes ``` {grep {is-prime $_&2*$_+1&$_/2-.5},1..$_} ``` [Try it online!](https://tio.run/##Fcq9CoAgFAbQV/mQi0M/pkJt9iqXBo0gSWwK8dmtprOc5PO5tPhABrhW9uwTynGPKR/Rg1jajrg3kniyo5rrYJQiru3eHghiuBUlfK8KhCvD6gFGs9a/P@0F "Perl 6 – Try It Online") This filters (`grep`s) the numbers from 1 to the input argument to those where the conjunction (`&`) of the number (`$_`), twice that number plus one (`2 * $_ + 1`) and half the number minus one half (`$_ / 2 - .5`) is prime. The conjunction is prime if all of its elements are. [Answer] # [J](https://www.jsoftware.com), 28 bytes ``` [:I.1*/@p:i.>:@+:^:_1 0 1@,] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxJ9rKU89QS9-hwCpTz87KQdsqzireEKjK0EEnFqJkryZXanJGvoKDQppCamJyhoIRUNbAAEIYQNQsWAChAQ) `i.,]` Integers from 0 to n. `>:@+:` Function f that computes `i` -> `1+2*i`. `f^:_1 0 1` Apply f -1 times (inverse), 0 times, and 1 time and collect results in a 3-row matrix. `1 p:` For each integer, is it prime? `*/` Take the product of each column. `I.` Indices of 1s in the resulting vector. [Answer] # Excel, 118 bytes ``` =LET( a,SEQUENCE(2*A1+1), b,IF(MMULT(N(MOD(a,TOROW(a))=0),a^0)=2,a), FILTER(b,1-ISNA(XMATCH(2*b+1,b)*XMATCH((b-1)/2,b))) ) ``` Fails where `A1>3663`. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 75 bytes ``` .+ $* ¶11$`$` 4A` A`^(11+)\1+$ 1(1?) $1 A`^(11+)\1+$ A`^1((11+)\2+)\1$ %`1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYuL69A2Q0OVBJUELhPHBC7HhDgNQ0NtzRhDbRUuQw1De00uFUNUUSDHUAPCNQIJqXCpJhj@/29oYGAAAA "Retina 0.8.2 – Try It Online") Link is to verbose version of code. Explanation: Based on my Retina answer to [Imtiaz Germain Primes](https://codegolf.stackexchange.com/q/258817). ``` .+ $* ``` Convert to unary. ``` ¶11$`$` ``` Generate all numbers of the form `2n+1` up to the input. Due to golfing, the last entry is not odd, so I have to add `2` to each value so that the final odd entry is `2n+1`. (Although, the non-golfy way only goes up to `2n-1` so wouldn't work anyway.) ``` 4A` ``` Deleting composite numbers won't work when the number to be tested is `0` or `1` so delete the small numbers manually. ``` A`^(11+)\1+$ ``` Delete the remaining non-prime numbers. ``` 1(1?) $1 ``` Integer divide by `2`. ``` A`^(11+)\1+$ ``` Delete all composite numbers. ``` A`^1((11+)\2+)\1$ ``` Delete all numbers that are `1` more than `2` times a composite number. ``` %`1 ``` Convert the results to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes ``` I⊕⊗Φ…²⊘⊕N⬤⊖×⊕ιE³X²λ⬤…²λ﹪λν ``` [Try it online!](https://tio.run/##VY1BCsIwEEWvkuUUIkRduhKL2IVSxAuk6aCB6aSkST1@HEGs/s3A57357mGjC5ZKaaPnBAc7JWjYRRyQE/ZQh9yR3KOnhBGulu8IG61Olmapf9GGx5wueeiEqyRa7YmgxoW4@QGnP8cLdbYjbLVqw1NEeU2L/J2jNxf6TAFIK64@2ZWyNsaU1Uwv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` … Range from ² Literal integer `2 to N Input integer ⊕ Incremented ⊘ Halved Φ Filtered where ³ Literal integer `3` E Map over implicit range ² Literal integer `2` X Raised to power λ Inner value × Vectorised multiply by ι Outer value ⊕ Incremented ⊖ Vectorised decrement ⬤ All values satisfy … Range from ² Literal integer `2` λ To inner value ⬤ All values satisfy λ Inner value ﹪ Modulo i.e. is not a multiple of ν Innermost value ⊗ Vectorised double ⊕ Vectorised increment I Cast to string Implicitly print ``` [Answer] # Excel (ms365), 146 bytes [![enter image description here](https://i.stack.imgur.com/gtOj6.png)](https://i.stack.imgur.com/gtOj6.png) ``` =LET(x,SEQUENCE(A1*2+1),y,MAP(x,LAMBDA(z,SUM(--((z/x)=INT(z/x)))))=2,q,FILTER(x,y),FILTER(q,MAP(q,LAMBDA(p,SUM(--(q=(p-1)/2))*SUM(--(q=2*p+1)))))) ``` --- **EDIT:** Since the above is rather slow (thought should work for all given samples), I was looking for ways to gain more speed. Just for fun, I created my own `LAMBDA()` based function called 'a' within Excel's name-manager based on one of the more simplistic ways to [generate prime numbers](https://en.wikipedia.org/wiki/Generation_of_primes); the [***Sieve of Eratosthenes***](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes): ``` =LAMBDA(x,y,z,IF(x=MAX(y),SORT(y),a(SMALL(y,z),FILTER(y,MOD(y,x)+(y=x)),z+1))) ``` Now, since we can output all primenumbers, we can call this on the worksheet and do some filtering on the output: ``` =LET(q,a(2,SEQUENCE(A1*2,,2),1),FILTER(q,MAP(q,LAMBDA(p,SUM(--(q=(p-1)/2))*SUM(--(q=2*p+1)))))) ``` The combined byte-count == 173, but it is working faster then the original answer of 146 bytes. This makes me wonder if I, or someone, else can come up with ways to implement other known ways of generating primes and gain more speed. [Answer] # [Factor](https://factorcode.org/) + `math.primes`, 63 bytes ``` [ primes-upto [ dup 2/ swap 2 * 1 + [ prime? ] both? ] filter ] ``` [Try it online!](https://tio.run/##LYq7DsIwEAT7fMXWRASHEgpKREODqKIUxlyUCMc257Mivt6YR7Ojnd1BG/Gcr5fT@bhDpGciZyjiQezIYtYyfqMJPM3FByaRVylOsK@qVimVO/zGdQri0eGeArYbxEUXYoUWNf6fA3rcvIwfDpMVYvTZaGvR5Dc "Factor – Try It Online") * `primes-upto` get a list of primes up to the input * `[ ... ] filter` select \$p\$ where... * `dup 2/` \$\lfloor{p/2}\rfloor\$ * `swap 2 * 1 +` and \$2p+1\$ * `[ prime? ] both?` are both prime [Answer] # [Arturo](https://arturo-lang.io), 45 bytes ``` $=>[select..1&'n[every?@[1+n*2n/2n]=>prime?]] ``` [Try it](http://arturo-lang.io/playground?Hnas1X) ``` $=>[ ; a function select..1&'n[ ; select numbers from 1 to <input>, assign current elt to n every? ; is every element in the block... @[1+n*2n/2n] ; ... [n/2, n, n*2+1] (where / is integer division) =>prime? ; prime? ] ; end select ] ; end function ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` ÆRḤ‘$ÆP$Ƈ’H$ÆP$Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8//9wW9DDHUseNcxQOdwWoHKs/VHDTA8o8////4YGQPD/PwA "Jelly – Try It Online") ``` ÆR - list of prime numbers up to the input Ḥ‘ - 2x+1 $ÆP$Ƈ - evaluates as primes ’H - (x-1)/2 $ÆP$Ƈ - evaluates as primes (again) ``` [Answer] # [SageMath](https://www.sagemath.org/), 76 bytes [Run it on SageMathCell!](https://sagecell.sagemath.org/?z=eJwtzEEKgzAQBdC9kDsMrmbaqIlLwZNIKClVSUmixAjx9k2ws_iL_x-zjla790eDH6YEyxYggfGTbFvfSGUW0NaiOV57MG7Gi4q4ikgcUyOp63reP9JTKlKsYlXZ_emygKkXHKQQ_xRqYBXkC_Nx2ggjrJgl3WX-7yPWvG6_m_Ho9I5HDPy2RPQDfSQwog==&lang=sage&interacts=eJyLjgUAARUAuQ==) ``` g=lambda n:[x for x in[1..n-1]if all(is_prime(y)for y in[x,(x-1)//2,2*x+1])] ``` [Answer] # Uiua, 63 Bytes ``` ▽⍥×3∩∩∵(¬∊0↘2◿⇡.)⌊÷2:+1×2⍥.4↘3+1⇡ ``` [Try It](https://uiua.org/pad?src=0_8_0__4pa94o2lw5cz4oip4oip4oi1KMKs4oiKMOKGmDLil7_ih6EuKeKMisO3MjorMcOXMuKNpS404oaYMysx4oehIDEwMDAK) ``` ▽⍥×3∩∩∵(¬∊0↘2◿⇡.)⌊÷2:+1×2⍥.4↘3+1⇡ +1⇡ # generate all numbers from [1, n] ↘3 # drop first three since the prime number function will flag 3 (it returns true for 1) ⍥.4 # make four copies, 3 for checking 2p+1, p, and floor(p/2), # one extra so that we can use a double both (∩) later +1×2 # calculate 2p+1 ⌊÷2: # calculate floor(p/2) ∩∩∵(¬∊0↘2◿⇡.) # apply prime number function to the top four stack elements . # copy so we can divide by the number later ⇡ # generate numbers [0, x] where x is the number we are checking ◿ # calculate mod, to see if it evenly divides ↘2 # drop first two so we discard mod by 0 and 1 ∊0 # check if there is remainder of 0 ¬ # if there exists no divisors which yield a remainder of zero, it is prime ⍥×3 # use multiplication to and conditions together: prime(floor(p/2)) & prime(2p+1) & prime(p) & prime(p) ▽ # only keep numbers that matched condition ``` ]
[Question] [ [Cops' Thread](https://codegolf.stackexchange.com/questions/231321) Your challenge is to find an uncracked, unsafe cop on the cops thread, and find an input value for which their code does not do as specified by the challenge. You must use values within the bounds specified by the cop and the challenge - if a float breaks their program but they specified integers only, it's not a valid crack. Use any submission on the specified challenge to find the correct value for any input - you probably want to check this against another submission. # Scoring Your score is the number of cops you have cracked, with higher score being better. [Answer] # [Python by Sisyphus](https://codegolf.stackexchange.com/a/231394/64121) for [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) \$ 110728750366081 = 37 \times 41 \times 71 \times 661 \times 673 \times 2311 \$ is wrongly recognized as a prime. [Try it online!](https://tio.run/##NY9db4IwGIXv@yu6C7B1NaHt@Ijwcl/jfzCOYHi7iowUULP41xnO7O7kPMnJc7qbby6tnmcD2HqGbTd4xjnZgykUcX/lStbVeK4jNdmjr2N3t83w1X7Urqk93qrKR1Vf@SQbmt7j8fR5vZ6q8/htx/tK6ISTqUFXU7clFMHkFnbgQqlllMr8AJLQF7cLf8WHDdTWliUsfA3yZ8MwTLFlWsSLGaVWIKCw/9CGGgBDXSqe2wCQ0P07dJeJ7cRjY8pSCsPfgGGh@PoQGELdczolXf88ty8kn2e52KgsjSOdJFEmfwE "Python 3 – Try It Online") Sisyphus implemented the [Solovay-Strassen primality test](https://en.wikipedia.org/wiki/Solovay%E2%80%93Strassen_primality_test), which is based on a theorem by Euler which states for any prime number \$p\$ and any integer \$a\$: $$ a^{p-1\over2} \equiv \left({a \over p}\right) \mod p, $$ where \$\left({a \over p}\right)\$ is the Jacobi symbol. The primality test usually draws a few random numbers for \$a\$ and assumes \$p\$ is a prime if the equality was satisfied for all \$a\$. Because randomness doesn't work very well with [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"), the long constant hardcodes a fixed set of values for \$a\$: ``` 2, 3, 5, 7, 11, 13, 17, 19, 11617, 15493, 16433, 25919, 31091, 31469, 49307, 55001, 55399, 65071 ``` For a given \$a\$ there exist composite numbers that satisfy the equivalence, these are called *Euler-Jacobi Pseudoprime* to base \$a\$. To solve the challenge, one needs to a find a single positive integer that is a *Euler-Jacobi Pseudoprime* to all the bases. Bruteforcing this turned out to be infeasible, but [this article](https://mathworld.wolfram.com/Euler-JacobiPseudoprime.html) mentions that some Carmichael numbers are *Euler-Jacobi Pseudoprime* to some base. By filtering a list of Carmichael numbers from [this site](http://www.s369624816.websitehome.co.uk/rgep/cartable.html)¹, I was able to find a few solutions: ``` 110728750366081 37*41*71*661*673*2311 237382308072001 29*101*127*337*631*3001 549022047900481 29*31*199*857*1381*2593 815369599393441 179*5741*6673*118903 1777021736490001 71*79*199*461*3453451 2409992788323121 29*67*499*20693*120121 5514474572006401 1051*2521*11551*180181 6036890513068801 43*71*101*40129*487873 9704292238761121 79*113*521*631*937*3529 14988701359951201 191*241*271*401*1051*2851 23456937465858961 37*43*71*103*181*821*13567 23880657211210801 23*61*109*157*271*937*3917 26055899070788161 31*173*433*1777*2437*2591 28365866503643761 43*53*137*281*443*457*1597 30908877197436001 421*601*1429*1709*50021 33834184755920641 29*37*71*73*97*547*114661 45561504118095001 211*421*751*3571*191251 51176905599093121 29*31*43*67*137*6427*22441 64612622789870401 97*181*277*647*691*29717 83629862695874881 181*881*953*4789*114913 132132263067090001 41*131*647*47501*800473 162098861806081201 71*421*2393*11047*205141 219842309289002401 23*29*71*151*337*3851*23689 283029750046243201 47*101*113*691*21841*34961 308601054690500881 29*37*41*331*691*4621*6637 314618527970346601 991*1093*3511*3571*23167 317711413912838401 43*53*73*79*113*3361*63649 397597753071953281 73*211*241*271*8317*47521 406954063186624801 29*37*41*191*3037*3221*4951 507180584040530401 89*163*281*397*463*743*911 511311312146194561 37*79*131*353*577*1361*4817 594232587298120681 29*71*127*1163*1171*1668629 650151107946325441 547*6553*35491*5110561 682696543350931201 315011*882029*2457079 685726732138361761 67*331*397*487*1567*102061 738294418360350721 89*353*5897*14081*283009 794134562259598561 23*79*89*157*241*2341*55441 806936176399473121 53*137*157*2731*4409*58787 830121613337016001 73*109*34651*53353*56431 963141865421809921 23*43*61*113*193*353*617*3361 ``` ¹The files are not actually gzipped, they are just plain text files [Answer] # [Jelly by caird coinheringaahing](https://codegolf.stackexchange.com/a/231329/68942) for [Is it double speak?](https://codegolf.stackexchange.com/q/189358/66833) ``` ṾḊṖŒœE ``` [Try it online!](https://tio.run/##y0rNyan8///hzn0Pd3Q93Dnt6KSjk13/H25/1LTm/3@lRw1zgEhJRwHImgtESgA "Jelly – Try It Online") Uneval doesn't always surround the string in quotes. Since Jelly cannot escape string delimiters (and even if it could, the escape characters would cause it to fail), `““` unevaluates to `”“,”“` (literal character `“` followed by literal character `“`), which is not even an even-length string. [Answer] # [Jelly by caird coinheringaahing](https://codegolf.stackexchange.com/a/231324/65836) for [Is it double speak?](https://codegolf.stackexchange.com/q/189358/66833) Original code: ``` ṾḊṖ⁼2/Ạ ``` Crack: ``` ' ``` The explanation described removing quotes, so I just tried quotes. Edit: Based on several other cracks by [fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241) and [Jonathan Allen](https://codegolf.stackexchange.com/users/53748/jonathan-allan) that I only sniped by a matter of seconds, any odd-length string will also result in a crack. [Try it online!](https://tio.run/##ARwA4/9qZWxsef//4bm@4biK4bmW4oG8Mi/huqD///8n "Jelly – Try It Online") [Answer] # [Jelly by caird coinheringaahing](https://codegolf.stackexchange.com/a/231335/65836) for [Make a ;# interpreter](https://codegolf.stackexchange.com/q/121921/65836) For `n > 127`, `;` repeated `n` times, then `#`. Original: [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYqP9w57Uj3o6Y1QLa1qqGR@cPdPf///7ceGkAZAA "Jelly – Try It Online") Broken: [Try it online!](https://tio.run/##y0rNyan8///hzsWPGuYqP9w57Uj3o6Y1QLa16uEZjxq3P9zd8///f@uhAZQB "Jelly – Try It Online") [Answer] # [Taxi by Stephen](https://codegolf.stackexchange.com/a/231336/85334) for [Draw an asterisk triangle](https://codegolf.stackexchange.com/q/95780/65836) ``` 9 ``` [Be sad online](https://tio.run/##nVOxTsMwEP2VU5dIDBG0MJCxgBgqoGpBDMDgJhfnhLEj223o1wenidM0QqR0OFk@@969e3627JvK8l6BVTBXxsJTmlKMUQEXIFzoag3nFH@uc2CQM2NQctTAFUleVT1nCFO2QpGSyVBvwxqsn46MRxxEe5EJaq7VWiZh8C4DMlAwstUNZuFVk0UdGLjFXNmm22EyknDleo0HmC/UylUs0HiUfcIh1LO3Eb6xj7/AZkrOmA1MGJydQNiL00Z4VK8ay28jkDBxbMcDGt9sY6EkNtXNbjfxsGYdj5ysrel4q9b2HA4lW1qm44xEAo/rL9RKKO599dtRB3GI/wPjFMMd8cwT67t@p1/r/L2ZO65s3SFO0nlyhM79f/C/mTqZRpshTyxog3pDWMBUU8I96X7aoTnmcNkq03nWYnc07j3tsiAbZ9XVXDAJIzYKy/L6Bw "Taxi – Try It Online") [Answer] # [Javascript by Redwolf Programs](https://codegolf.stackexchange.com/a/231378/78410) for [Is this even or odd?](https://codegolf.stackexchange.com/questions/113448/is-this-even-or-odd) ``` x=>{var b=[...x.toString(2)].reverse()+"";try{eval.call(window,(t=y=>y?t(y/256n)+String.fromCharCode(Number(y%256n)):"")(x))}catch{};return +[...b][0]} ``` Crack input: ``` 968040030946052874125008971077898749420224656625100629300118076307717369397814550869471412902654978373500023349257848576032587637596801109818665n ``` Outputs 0, which is wrong because the given number is odd. This is the result of `f(s)` where `f` and `s` are ``` f=s=>[...s].map(c=>BigInt(c.charCodeAt())).reduce((x,y)=>x*256n+y) s='Object.defineProperty(Array.prototype,0,{get:_=>0,set:_=>_})' ``` The payload basically fixes the index 0 of every single `Array` as 0 by defining the `0` property of `Array.prototype`. The getter returns 0 and the setter does nothing. Does not work in Chrome console for security reasons, but you can try out the following full code by copy-pasting into an MDN demo window such as one [on this page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty). The whole page will malfunction after the code runs, so be sure to close the tab after seeing the result :P ``` z=x=>{var b=[...x.toString(2)].reverse()+"";try{eval.call(window,(t=y=>y?t(y/256n)+String.fromCharCode(Number(y%256n)):"")(x))}catch{};return +[...b][0]} f=s=>[...s].map(c=>BigInt(c.charCodeAt())).reduce((x,y)=>x*256n+y) s='Object.defineProperty(Array.prototype,0,{get:_=>0,set:_=>_})' console.log(n=f(s)) console.log(z(n)) console.log([10][0]) // bonus; shows what the code does ``` Output: ``` 968040030946052874125008971077898749420224656625100629300118076307717369397814550869471412902654978373500023349257848576032587637596801109818665n 0 0 ``` [Answer] # [Vyxal by A username](https://codegolf.stackexchange.com/a/231323/68942) for [Stack Exchange Vote Simulator](https://codegolf.stackexchange.com/questions/63369/stack-exchange-vote-simulator) ``` C⁽꘍R:£80>[¥₁-±N|0 ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=C%E2%81%BD%EA%98%8DR%3A%C2%A380%3E%5B%C2%A5%E2%82%81-%C2%B1N%7C0&inputs=%27%5Ev%27&header=&footer=) Input of `^v`. I don't think this even works for most of the test cases. [Answer] # [Vyxal by Aaron Miller](https://codegolf.stackexchange.com/a/231333/100664) for [Simple cat program](https://codegolf.stackexchange.com/questions/62230/simple-cat-program) Any string - implicit output is with a trailing newline, so this is invalid no matter what. [Answer] # [JavaScript by Redwolf Programs](https://codegolf.stackexchange.com/a/231337/65836) for ["Hello, World!"](https://codegolf.stackexchange.com/q/55422/65836) Input: `90071992547409929007199254740992` [Try it online!](https://tio.run/##XU67bsIwFN35iuDJVp3ISfPAiszCws7AgDq4iZ0mMvdGxkUg4NsDQZ0qHZ2XznAGfdanxvdjiAFbM01WgVrfekvDdTRoI1CK4PdgmkDud4g/s6WamXkTfj1EZGucQx7t0bt2Seqz9lH7XtR/i0MueCl5Vb4heZpxwYtitqts7soVT7@Sox7pRa13wffQJdbjcfOj/eb1iULcflwYSwbsgRLCHvVi0SCc0JnEYUctlUJUqZRZkVe5eOn/zNg0PQE "JavaScript (Node.js) – Try It Online") Since all numbers in JavaScript are floating point, once numbers get big enough, adding and subtracting from them gets kinda weird. [Answer] # [Vyxal by Wasif](https://codegolf.stackexchange.com/a/231347/100664) for [Least Common Multiple](https://codegolf.stackexchange.com/questions/94999/least-common-multiple) ``` [2,1,2] ``` Or similar [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%A0%3F%C4%A1%2F&inputs=%5B2%2C1%2C2%5D&header=&footer=) [Answer] # [Rattle](https://github.com/DRH001/Rattle) by [Daniel H.](https://codegolf.stackexchange.com/a/231362/68942), 3 bytes ``` |!p ``` [Try it Online!](https://rattleinterpreter.pythonanywhere.com/?flags=&code=%7C!p&inputs=.1) Fails for input `.1`. It seems that `|` just outputs the input but `p` will evaluate it? I am not sure exactly how this language works. [Answer] # [Python 3 by *Gavin S. Yancey*](https://codegolf.stackexchange.com/a/231382/88546), [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) The input `77833763775941059` is a prime, but evaluates as `False` in the answer given. ``` x=int(input()) print(x>1 and next(d for d in range(2,x+1)if x/d==x//d)==x) ``` [Try it online!](https://tio.run/##FcdLDoQgDADQvafokkYTZFCrC@YuJvXDphKCST09zqxeXnrKeYmvVUOUYqKkuxjEJuV/9etgFQbZtBiG/crAEAXyKsdmPp22DuMOajkEtZbxB9ZKNHtPkycal8H14/IC "Python 3 – Try It Online") `x/d==x//d` is the obvious culprit here. It's supposed to act like `x%d==0`, but due to precision issues it starts to falter for primes at around 17 digits. [Answer] # [Python 3 by pajonk](https://codegolf.stackexchange.com/a/231350/101249) for [Convert YYYYMM to MMMYY](https://codegolf.stackexchange.com/questions/83591/convert-yyyymm-to-mmmyy) Month 09 just outputs `'SER'` instead of `'SEP'`. [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSknBy83X0dfLyzHY38/F0dUxwDE0NNTV2d/VzykoKNLPxz0oJMxZKTozr0SjONrEKlbTysrQKFa7ONrIyiT2f0ERSCJNQ93IwMjQwFJdU/M/AA "Python 3 – Try It Online") [Answer] # [Vyxal by A username](https://codegolf.stackexchange.com/a/231352/100752) for [Find the first word starting with each letter](https://codegolf.stackexchange.com/questions/77263/find-the-first-word-starting-with-each-letter) Original Code (40 bytes): ``` kBð\_9ɾṅṠ↔⌈:£ƛh⇩⅛¥ƛh⇩;¼ḟ¥$i=[|¤;;';ðvp∑Ṫ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=kB%C3%B0%5C_9%C9%BE%E1%B9%85%E1%B9%A0%E2%86%94%E2%8C%88%3A%C2%A3%C6%9Bh%E2%87%A9%E2%85%9B%C2%A5%C6%9Bh%E2%87%A9%3B%C2%BC%E1%B8%9F%C2%A5%24i%3D%5B%7C%C2%A4%3B%3B%27%3B%C3%B0vp%E2%88%91%E1%B9%AA&inputs=Ferulas%20flourish%20in%20gorgeous%20gardens.&header=&footer=) Crack: Any word repeating without change. example: `test test`, or `.test test` results in `test test`, while it should return `test` [Answer] # [Jelly by Jonathan Allan](https://codegolf.stackexchange.com/a/231359/55372) for [Generate Recamán's sequence](https://codegolf.stackexchange.com/q/37635/53748) Input of `1024`. [Try it online!](https://tio.run/##y0rNyan8///hroU@D3euerhj/on12j4qQKa1A9fh9kMLH@6c9v@/oYGRCQA "Jelly – Try It Online") As the challenge asks for a sequence involving some sort of recursion, I tried a large input (if something breaks early it probably will be carried on) and compared with correct answers in the challenge. As pointed by [@Stephen](https://codegolf.stackexchange.com/questions/231321/it-almost-works-cops-thread/231359?noredirect=1#comment530188_231359), the code actually breaks around input of `58`. [Answer] # [Python 3 by Gavin S. Yancey](https://codegolf.stackexchange.com/a/231373/46076) for [Is this number a prime?](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime) Input is `1`. The program given loops forever on that input, and, since [all programs are required to terminate](https://codegolf.meta.stackexchange.com/a/4785/46076), it is not a valid answer. The challenge given even explicitly states that answers have to handle `1` as composite. [Answer] # [Python by dingledooper](https://codegolf.stackexchange.com/a/231452/48931) for [DDoouubbllee ssppeeaakk!!](https://codegolf.stackexchange.com/q/188988/88546) ``` '()'*200000 ``` [Try it online!](https://tio.run/##FY3NCsMgEITvPsXeVkMbJPQUkicJKYjdEEurstqS9OfZrZ3THL75Ju55Db4rxd1j4AxM4kILLDKpXkDmvU8jU5vIsF0lTub4mt@n72c61ybVjIekBj3Q09zqZBxxNRsGhiSANksx91pUaX6wR2yvwXlpm26phAXnIakS2flcD1EqbDr9jyo/ "Python 2 – Try It Online") (that is, 200000 pairs of left right brackets in a row) This is an application of [Python Bug 5765](https://bugs.python.org/issue5765) where a stack overflow can be caused by a large number of chained function calls. This doesn't work in modern versions of Python 3. [Answer] # [Python by StardustGogeta](https://codegolf.stackexchange.com/a/231375/100664) for [Simple cat program](https://codegolf.stackexchange.com/questions/62230/simple-cat-program) ``` 䅫 ``` [Try it online!](https://tio.run/##DclBCsIwEADAu6/IRZrgJZvd7e4WfIl4s9KApKFExAf4Gr/lP2JvA1PfbVkL9v5a8mN2MB1cPudSn82HnXcHrEhMIJHVAE1IRyTEZCYmInvzyISCURQIlVljUlVQJhrRFBPjcd1u3ufTMA/hEq9hqlsuzefQ@@/z/QM "Python 3 – Try It Online") ]
[Question] [ ### Challenge Given a positive integer `N`, output the sum of the first `N` reciprocals as an exact fraction, which is represented as a pair of integers in a consistent order representing numerator and denominator. ### Rules * Output must be exact. * Output should be as a pair of integers in a consistent order representing numerator and denominator. * Using non-integer numeric types (built-in or library) is forbidden. + Clarification/exception: non-integer numeric types are okay if and only if all values used, computed, and returned are integers (i.e. your language uses rational numbers by default, but you only use integer arithmetic in your answer) * Output should be as reduced as possible. (`3/2` is okay, `6/4` is not) * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Submissions should work for inputs at least up to 20, or [this meta](https://codegolf.meta.stackexchange.com/a/8643/44694), whichever is higher. ### Test Cases ``` 1: 1/1 2: 3/2 (1/1 + 1/2) 3: 11/6 (1/1 + 1/2 + 1/3) 4: 25/12 etc. 5: 137/60 6: 49/20 20: 55835135/15519504 56: 252476961434436524654789/54749786241679275146400 226: 31741146384418617995319820836410246588253008380307063166243468230254437801429301078323028997161/5290225078451893176693594241665890914638817631063334447389979640757204083936351078274058192000 ``` ### [Test-Case Generation (Python 3)](https://tio.run/##PY3BCsIwEETPzVcshUKCodpWPRR69SfEQzCJ7iGbskmhfn1tRTqnecODGT/5HalbFgxj5AyezTNjpCSs8@DlrHoBa9jliQnSFOSu1Ld/k41GBT4yICABG3q5dZsPjVJLdiknGODe6FZ3@qwv@qrb00Ps/s/oRWEGL1GJYmSkLMvK9lDZY2VLqECiBlPTFBybHHkD6ygGpA3Xmy8) ``` import fractions def f(x): return sum(fractions.Fraction(1,i) for i in range(1,x+1)) ``` Similar to [this challenge](https://codegolf.stackexchange.com/questions/123173/partial-sum-of-harmonic-sequence) and [this challenge](https://codegolf.stackexchange.com/questions/82815/denominator-of-harmonic-series). Numerators are [OEIS A001008](http://oeis.org/A001008), and denominators are [OEIS A002805](http://oeis.org/A002805). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` !:RS,!:g/$ ``` [Try it online!](https://tio.run/##y0rNyan8/1/RKihYR9EqXV/l/@H2R01r3P//N9RRMNJRMNZRMNFRMNVRMANyDYAsEG1kBgA "Jelly – Try It Online") ### How it works ``` !:RS,!:g/$ Main link. Argument: n ! Compute n!. R Range; yield [1, ..., n]. : Divide n! by each k in [1, ..., n]. S Take the sum. Let's call it s. ! Compute n! again. , Pair; yield [s, n!]. :g/$ Divide [s, n!] by their GCD. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~80~~ 79 bytes ``` D=1;N=n=0;exec"n+=1;y=N=N*n+D;x=D=D*n;"*input() while y:x,y=y,x%y print N/x,D/x ``` [Try it online!](https://tio.run/##LY1BCoMwFETX/acIQrFVQY3VheHvYpfpGVr7QWmJIaQ0OX0aoZuBYR5vTHDLpnmctydhnudRYisUamwEeZozXaYeUKEqdCmFR4my0CIrVm0@7nSG77K@iYXRVwFD5Y8BjF21Y6r2lax9TM4/047AnA0jHHYz2x@BkZ/JODbdrpO1m03jw9L9BbEFDh1coIcBeAN9Sj78AA "Python 2 – Try It Online") Prints the numerator and denominator. Yay! MathJax support!!!! One observes: $$\sum\_{i=1}^{n} \frac{1}{i} = \sum\_{i=1}^{n} \frac{n!}{n!i} = \frac{\sum\_{i=1}^{n} \frac{n!}{i}}{n!}$$ Then, thinking about recursion, for \$n\$ positive, in the `N`umerator: $$\sum\_{i=1}^{n+1} \frac{(n+1)!}{i} = (n+1) \sum\_{i=1}^{n} \frac{n!}{i} + \frac{(n+1)!}{n+1} = (n+1) \sum\_{i=1}^{n} \frac{n!}{i} + n!$$ and one can't help think of the `D`enominator \$n!\$ recursively as well; thus the `exec`. We must pay the Reduced Fraction Piper with a GCD calculation in the `while` loop; and then we're done. [Answer] # [J](http://jsoftware.com/), 16 bytes ``` !(,%+.)1#.!%1+i. ``` [Try it online!](https://tio.run/##y/qfpmBrpZCXX5qnkJKalpmX@l9RQ0dVW0/TUFlPUdVQO1PvvyZEDbo4V5qCWQWQMDIAkaZmFQA "J – Try It Online") ### Run examples ``` f =: !(,%+.)1#.!%1+i. f 6x 20 49 f 20x 15519504 55835135 f 56x 54749786241679275146400 252476961434436524654789 ``` ### How it works ``` !(,%+.)1#.!%1+i. NB. Tacit verb 1+i. NB. 1 to n inclusive !% NB. Divide factorial by 1 to n 1#. NB. Sum i.e. numerator (not reduced) ! NB. Factorial i.e. denominator (not reduced) (,%+.) NB. Divide both by GCD ``` --- ## [J](http://jsoftware.com/), 9 bytes, using fraction type ``` 1#.1%1+i. ``` [Try it online!](https://tio.run/##y/qfpmBrpZCXX5qnkJKalpmX@t9QWc9Q1VA7U@@/JkQSLsCVpmBWASSMDECkqVkFAA "J – Try It Online") J gives fractions for int-int division if not divisible. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` !DIL÷O)D¿÷ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f0cXT5/B2f02XQ/sPb///38gAAA "05AB1E – Try It Online") Uses the same method as all other entries. Output is in the form `[denominator, numerator]`. ``` !DIL÷O)D¿÷ Full program. Let's call the input I. !D Push the factorial twice to the stack. STACK: [I!, I!] IL Range from 1 to I. STACK: [I!, I!, [1 ... I]] ÷ Vectorized integer division. STACK: [I!, [I! / 1, I! / 2, ..., I! / I]] O Sum. STACK: [I!, I! / 1 + I! / 2 + ... + I! / I] ) Wrap stack. STACK: [[I!, I! / 1 + I! / 2 + ... + I! / I]] D Duplicate. STACK: [[I!, I! / 1 + ... + I! / I], [I!, I! / 1 +... + I! / I]] ¿ GCD. STACK: [[I!, I! / 1 + ... + I! / I], gcd(I!, I! / 1 +... + I! / I)] ÷ Vectorized integer division. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes ``` #/GCD@@#&@{Tr[#!/Range@#],#!}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Z393ZxcFBWc2hOqQoWllRPygxLz3VQTlWR1mxVu2/S350QFFmXkl0noKunUJadF5srI5CdZ6OgoGOgrFBbex/AA "Wolfram Language (Mathematica) – Try It Online") --- ## 14 bytes if built-in fractional types are allowed ``` HarmonicNumber ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98jsSg3Py8z2a80Nym16L9LfnRAUWZeSXSegq6dQlp0XmysjkJ1no6CgY6CsUFt7H8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # JavaScript (ES6), 60 bytes Returns `[numerator, denominator]`. ``` f=(n,a=0,b=1)=>n?f(n-1,p=a*n+b,q=b*n):b?f(0,b,a%b):[p/a,q/a] ``` [Try it online!](https://tio.run/##DY07DoMwEAV7TrFNhBfbfFICSw4SpVgTiEBobSBKE@Xsjpun0Wikt/KHz/FYwtuKf04xzqTEMNXGUYM0yG1WYhsTiAvRzuzkCsHWJZ0SwxeH7T1UbPaKH3H2hxIgaDoQ6AmudQKtEb4ZwOjl9NtUbv6VIg05WDuk1ZAusFz9IiqHCnLELvvFPw "JavaScript (Node.js) – Try It Online") ### How? The method is similar to [@ChasBrown's Python answer](https://codegolf.stackexchange.com/a/168705/58563). We first compute the unreduced numerator \$a\$ and unreduced denominator \$b\$ by starting with \$a=0\$ and \$b=1\$ and recursively doing: $$a\gets an+b\\ b\gets bn\\ n\gets n-1$$ until \$n=0\$. We save \$(a,b)\$ into \$(p,q)\$ and then compute \$a\gets \gcd(a,b)\$ with: $$a\gets b\\ b\gets a \bmod b$$ until \$b=0\$. We finally return the reduced numerator \$p/a\$ and reduced denominator \$q/a\$. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~57~~ 53 bytes ``` {+($!=[*] 1..$_)/($!=($/=sum $! X/1..$_)gcd$!),$//$!} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pbQ0XRNlorVsFQT08lXlMfxNVQ0bctLs1VUFFUiNCHiKcnp6goauqo6OurKNb@T8svAqk3NFCo5lJQ0FNL0ytOrOSq/Q8A "Perl 6 – Try It Online") An anonymous code block that takes an integer and returns a tuple of `denominator, numerator`. If we were allowed to use fractional types, it would be the much simpler 32 byter: ``` {sum(map 1/*.FatRat,1..$_).nude} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFcjN7FAwVBfS88tsSQosUTHUE9PJV5TL680JbX2f1p@kQJQwNBAoZpLQUFPLU2vOLGSq/Y/AA "Perl 6 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 29 bytes ``` @(n)sym(sprintf('+1/%i',1:n)) ``` [**Try it online!**](https://tio.run/##Nce9CoAgFAbQvaf4lvBeCkv7GYKg94iGqASHLFKCnt5aWg6cYwnzvUXTSynjQI79s5M/L@uCIZGpIrUiV51jjua4ENBjVNCoUKNBC12i@dTtlACr9ScZCsx/BAQnm1vjCw "Octave – Try It Online") [Answer] # [C++17 (gcc)](https://gcc.gnu.org/), 108 bytes Only use integer arithmetic: ``` #import<random> int f(int x,long&n,long&d){n=0;d=1;int a;while(n=n*x+d,d*=x,a=std::gcd(n,d),n/=a,d/=a,--x);} ``` [Try it online!](https://tio.run/##RY7BasMwEETP8VcYCrEVySTppRCt8iW9CK3sCKyVsWVqCP71uJJT6GV2mdnljRmGpjNm2z6cH8IYYdSEwd8LR7Fs66yL6AN1R3oPZE9SF4nqKlNYaPnzcL2tSdFp4SjwpBah1RTxdusM1iSQCTorLTBL0yxMrglGpp/RggtTHK3@43ntqGbP4tCGcUe7TAH1eZGcuxwccoeSZm8FWgpeJiu1FP8Oy9aON2GOADkBqMoKYM/T/k1VOlqLdXuZttfdtDXpQRnOr1@/ "C++ (gcc) – Try It Online") --- # [C++17 (gcc)](https://gcc.gnu.org/), 108 bytes ``` #import<random> int f(long&n){double a=0;long d=1;while(d*=n,a+=1./n,--n);n=a*d+.5;n/=a=std::gcd(n,d);d/=a;} ``` [Try it online!](https://tio.run/##TY7BasMwEETP8VcYCrUU2UlcKIVI2y/pRdXKrkBeGVmmh@BfryuFEnp9M8MbM8/daMy@P7lpDjGpqAnD9F45SvXAfKDxmfgNw/rpba3hIguqEHr5/eW8ZXgEarWA/nSmtuuISwJ9RHF6lXQGDUvC63U0yKhFLjEjuWUZGb@iVS4sKVr955u0I8Zv1WEIkRXgssYpeLlIIVwJDsVe0zrZqFOI4GRmpYmWwuToDgf2KPCS3y@YsCalHoFSTd0o9W@WyQc1ub9V2/5jBq/HZe/yFowQ/dsv "C++ (gcc) – Try It Online") Same as below, but use C++17's [`std::gcd`](https://en.cppreference.com/w/cpp/numeric/gcd). --- # [C++ (gcc)](https://gcc.gnu.org/), 109 bytes ``` #import<regex> int f(long&n){double a=0;long d=1;while(d*=n,a+=1./n,--n);n=a*d+.5;n/=a=std::__gcd(n,d);d/=a;} ``` [Try it online!](https://tio.run/##TY7disIwEEav7VMUBJvY1p@FvTHJPsmCxExaB5pJiSkuSJ@9Ji6It@d8wxkzjm1vzLKs0Y0@RBlsb/9@CqRYdmzw1G@IP8BPl8GWWh1ERgWoo7hfcbAMtooaXavjbk9N2xIXpPQW6t23oL3S6hbhdDqfewOMGuACEhRzqpEZJrAS/S0Gq91/0Wkkxh/FqvOBZYAphFJ9HURdYxar3C9pcjbo6INCkVhegiXvkF6wY@8Bz/71hPFTlPItpKzKSsqPs0R@qUr7uZiXJw "C++ (gcc) – Try It Online") Because C++ doesn't have native bigint support, this will definitely overflow for `n>20`. Require: * gcc's deprecated `import` statement. * gcc's `std::__gcd`. * `-O0` (I think so) otherwise the compiler will optimize out `d/=a`. * At least 64-bit `long`. Explanation: * Let \$d=n!, a=H\_n\$. * Round `a*d` to nearest integer by casting `a*d+.5` to `long`, and assign to `n`. Now `n/d` is the output. * Simplify the fraction with `std::__gcd`. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes ``` n->l=[sum(i=1,n,n!/i),n!];l/gcd(l) ``` [Try it online!](https://tio.run/##DcgxCoAwDEDRq0SnBFqqOEq9iDiI0hKosVQ9f8zw3/Dr3tjnqgmiil9KXJ/vQo6jEyddYDK3uYR8nFhI091QIMLgYLJqY3lt9OAXI6EQkf4 "Pari/GP – Try It Online") --- ## 17 bytes if built-in fractional types are allowed ``` n->sum(i=1,n,1/i) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P0/Xrrg0VyPT1lAnT8dQP1Pzf1p@kUaegq2CgY6CMRAXFGXmlQAFlBR07YBEmkaepqbmfwA "Pari/GP – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ó╢Δ'åç4}ú┌7 ``` [Run and debug it](https://staxlang.xyz/#p=a2b6ff278687347da3da37&i=1%0A2%0A3%0A4%0A5%0A6%0A20%0A56%0A226&a=1&m=2) Explanation: We want to calculate: $$\sum\_{i=1}^n{\frac 1 i}$$ We now need a denominator \$b\$ and a list of numerators \$a\_i\$: $$\sum\_{i=1}^n{\frac{a\_i}b}=\frac{\sum\_{i=1}^n{a\_i}}{b}$$ We can make \$b=n!\$, then we have: \begin{align} \frac{a\_i}{n!}&=\frac 1 i&|\times n! \\ a\_i&=\frac{n!}i \end{align} So we have: $$\sum\_{i=1}^n{\frac 1 n}=\frac{\sum\_{i=1}^n{\frac{n!}i}}{n!}$$ ``` |Fx{[/m|+L:_m Full program |F Factorial x Push input again { m Map over range [1, n] [ Copy the factorial / Divide factorial by current value |+ Sum L Listify stack, top gets first element :_ Divide both values by gcd m Print each followed by newline ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 12 bytes ``` ⌽!(,÷∨)1⊥!÷⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HPXkUNncPbH3Ws0DR81LVUEcjs3fw/7VHbhEe9fY/6pnr6P@pqPrTe@FHbRCAvOMgZSIZ4eAb/Tzu0AqjSyAAA "APL (Dyalog Unicode) – Try It Online") Tacit function, taking a single argument `⍵`. Saves a byte by removing the `⌽` if we're allowed to print the denominator first. Thanks @dzaima for 3 bytes. ### How: ``` ⌽!(,÷∨)1⊥!÷⍳ ⍝ Tacit function, argument will be called ⍵. ⍳ ⍝ Range 1..⍵ ÷ ⍝ Dividing ! ⍝ the factorial of ⍵ 1⊥ ⍝ Base-1 decode, aka sum; !( ) ⍝ Using that sum and the factorial of ⍵ as arguments, fork: ∨ ⍝ (GCD ÷ ⍝ dividing , ⍝ the vector with both arguments) ⌽ ⍝ reversed. ``` [Answer] # MATL, 13 bytes ``` :tptb/sht&Zd/ ``` [Try it on MATL Online](https://matl.io/?code=%3Atptb%2Fsht%26Zd%2F&inputs=6&version=20.9.1) Same method as used in [@Dennis' Jelly answer](https://codegolf.stackexchange.com/a/168708/8774). ``` :t % Range from 1 to n, duplicate. pt % Take the product of that (= factorial), duplicate that too. b/ % Bring the range to top of stack, divide factorial by each element sh % Sum those. Concatenate factorial and this into a single array. t&Zd/ % Compute GCD of those and divide the concatenated array elements by the GCD. ``` (Implicit output, prints denominator first and then the numerator.) ~~Floating point inaccuracies mean this doesn't work for n = 20, because the intermediate values are too large.~~ Looks like the test case output was a typo, this returns the same answer as the other answers for n=20. Here's an integer type-preserving version (25 bytes) I tried in the meantime, before finding this out: ### 25 bytes, input upto 43 ``` O1i:3Y%"t@*b@*b+wht&Zd/Z} ``` [Try it online!](https://tio.run/##y00syfn/398w08o4UlWpxEErCYi0jVRKolL0y0199f/HZqirpuirpqhHuvw3MQYA "MATL – Try It Online") Casts the numbers to `uint64` before operating on them, does the arithmetic explicitly in a loop (without using `prod` or `sum`). More importantly, divides the partial numerators and denominators by their GCD every step along the way, at the end of each iteration. This increases the input range to allow `n` upto 43. Part of the code is based on @Chas Brown's Python answer. Alternate (original) method using LCM instead of factorial: ### ~~16~~ 15 bytes ``` :t&Zmtb/sht&Zd/ ``` [Try it on MATL Online](https://matl.io/?code=%3At%26Zmtb%2Fsht%26Zd%2F&inputs=6&version=20.9.1) [Answer] # Excel VBA, 141 bytes Takes input from `[A1]` and outputs to the console. ``` s="=If(Row()>A$1,":[B:B]=s+"1,Row())":l=[LCM(B:B)]:[C:C]=s &"0,"&l &"/B1)":g=[GCD(LCM(B:B),SUM(C:C))]:?Format([Sum(C:C)]/g,0)"/"Format(l/g,0) ``` ### Ungolfed and Commented ``` Sub HarmonicSum(n) [A1] = n '' Pipe input s = "=IF(ROW()>A$1," '' Hold the start of formulas [B1:B40] = s + "1,ROW())" '' Get series of numbers 1 to N, trailing 1s l = [LCM(B1:B40)] '' Get LCM [C1:C40] = s & "0," & l & "/B1)" '' Get LCM/M for M in 1 to N g = [GCD(LCM(B1:B40),SUM(C1:C40))] '' Get GCD '' Format and print output Debug.Print Format([Sum(C1:C40)] / g, 0); "\"; Format(l / g, 0) End Sub ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 87 bytes ``` ?sn1dsNsD[lndlDdlNln*+sN*sD1-dsn1<M]sMln1<MlDsAlNsB[lAlB%sTlBsAlTsBlB0<G]dsGxlDlA/lNlA/ ``` [Try it online!](https://tio.run/##FYwxCoAwEARfY6OIibUgOQ5SJVW6YOVhtaTZxt/HWA3DwNjd@8nmjZla0QxqyGjzwjxT/WojHuliwk8oAzKlIkAmFsjwQoG4I17G@EIRtnEIW3/67j4 "dc – Try It Online") This leaves the numerator and denominator on top of the stack in that order, as allowed by [this](https://codegolf.meta.stackexchange.com/a/8507/52405) output default. Since `dc` does not have a `gcd` built-in, this utilizes the [Euclidean algorithm](https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid's_algorithm) to calculate the `gcd`. [Answer] # APL(NARS), 56 chars, 112 bytes ``` {⍵=1:⊂1 1⋄{(r s)←⍺⋄(i j)←⍵⋄m÷∨/m←((r×j)+s×i),s×j}/1,¨⍳⍵} ``` test: ``` f←{⍵=1:⊂1 1⋄{(r s)←⍺⋄(i j)←⍵⋄m÷∨/m←((r×j)+s×i),s×j}/1,¨⍳⍵} f 1 1 1 f 2 3 2 f 3 11 6 f 20 55835135 15519504 ``` In few words reduce "sum function on 2 fraction numbers" (one fraction number is a list 2 integers) on the set: ``` 1 2, 1 3,..., 1 n ``` this below seems wrong: ``` f 56 74359641471727289 16124934538402170 ``` but if i change the type of input than: ``` f 56x 252476961434436524654789 54749786241679275146400 f 226x 31741146384418617995319820836410246588253008380307063166243468230254437801429301078323028997161 529022507845189 3176693594241665890914638817631063334447389979640757204083936351078274058192000 ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 14 bytes ``` Đ!⇹ř/Đ↑⇹ƩáĐÁǤ/ ``` [Try it online!](https://tio.run/##K6gs@f//yATFR@07j87UPzLhUdtEIPPYysMLj0w43Hh8if7//4YGBgYA "Pyt – Try It Online") Outputs `[denominator, numerator]`. ``` Đ implicit input; Đuplicate ! factorial ⇹ swap top two on stack ř řangify / divide Đ↑ Đuplicate; get max ⇹ swap top two on stack Ʃ Ʃum á push stack to árray Đ Đuplicate Á push contents of Árray to stack Ǥ get ǤCD / divide; implicit print ``` ]
[Question] [ Probably a simple code-golf challenge. Given 2 positive integers `m` and `n`, make a list of `n` values that are positive integers whose sum is equal to the number `m`. Either all values in the output are the same value or the difference is exactly 1. **Examples** For example * `m=6` and `n=3` would become `2, 2, 2` * `m=7` and `n=3` would become `2, 2, 3` or `2, 3, 2` or `3, 2, 2` * `m=7` and `n=2` would become `3, 4` or `4, 3` * `m=7` and `n=1` would become `7` * `m=7` and `n=8` would generate an error because the sum of 8 positive integers cannot be 7. * `m=10` and `n=4` would become `3, 3, 2, 2` or any other permutation **Rules** * Both input and output is only about positive integers. * Either all values in the output are the same value or the difference is exactly 1. * The order of the values in the list is not important. * The sum of the values in the list is equal to `m`. * When it's not solvable, generate an error or a false value (in case of m=7 and n=8 for example). * As a result of the other rules `m=8` and `n=3` would generate any of the permutations of `3, 3, 2` (not `2, 2, 4`) **The winner** This is code-golf, so the shortest valid answer – measured in bytes – wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~48~~ 43 bytes Returns `0` on error. ``` lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFXJ88qVz9PITEvJRpIx2pp5OnmquZpagMJLZCItmHs/5KiSisuzvKMzJxUhZCi0lQgh7OgKDOvRCFNQyszr6C0RENTkyu1Ijm1oETB1d/NtagovwioqCCxuPi/mY4xlzkYGwGxIRBbcBkaGOhYAAA "Python 2 – Try It Online") --- ### 41 bytes (with @xnor's trick) Throws `NameError` on error. ``` lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1] ``` [Try it online!](https://tio.run/##TYpPC4IwGIfP26fYJZx/IjUoETrasS7dSmLWRMG9jtdJ@enXsoIOzw9@D4@eTNNDauvdxXZCVXfBVAT5Wa2A9ciuZcBhqRbgh26Ctw6T0hqcckoeTdtJdsJRukM@jhCNLRhW86AFPRru@07K501qww5CyQKxx7/Qm4VHv0lx3P8KLYbBbqI13c6kjsSR0SSOo@wF "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` :gie!Xs ``` When there is no solution the output is an array containing at least one zero, which is [falsy](https://codegolf.stackexchange.com/a/95057/36398) in MATL. [**Try it online!**](https://tio.run/##y00syfn/3yo9M1Uxovj/f0MDLhMA "MATL – Try It Online") ### Explanation Consider inputs `m = 10` and `n = 4`. ``` : % Implicitly input m. Push [1 2 ... m] % STACK: [1 2 3 4 5 6 7 8 9 10] g % Logical: convert nonzeros to 1 % STACK: [1 1 1 1 1 1 1 1 1 1] i % Input n % STACK: [1 1 1 1 1 1 1 1 1 1], 4 e % Reshape into matrix with n rows, padding with zeros % STACK: [1 1 1; 1 1 1; 1 1 0; 1 1 0] ! % Transpose % STACK: [1 1 1 1; 1 1 1 1; 1 1 0 0] Xs % Sum of each column. Implicitly display % STACK: [3 3 2 2] ``` [Answer] # Mathematica, 33 bytes ``` #>#2&&Last@IntegerPartitions@##1& ``` **input** > > [63, 11] > > > **output** > > {6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5} > > > outputs ***False*** when it's not solvable [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` m%n|m>=n=map(`div`n)[m..m+n-1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1c1rybXzjbPNjexQCMhJbMsIU8zOldPL1c7T9cw9n9uYmaegq0CUNJXoaAoM69EQQXEUdAozUsuLSqqVNBQ1dRUiNYw0zHW1NEwh5JGYNIQSBoa6JiAORaasf8B "Haskell – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes after applying NDD1 ``` ¿÷NNIEIη÷⁺IθιIη ``` [Try it online!](https://tio.run/##S85ILErOT8z5///Q/sPb3@9ZB0Yr3@9ZCiTPbT@8/VHjLhBrx7mdYIH//w0NFIwB "Charcoal – Try It Online") Outputs nothing if there is no solution. Link to the [verbose version](https://tio.run/##S85ILErOT8z5/z8zTcMzr8QlsywzJRXIKigt8SvNTUot0tDUQeFpaioEFGXmlWg4JxaXaPgmFkAYGZo6Cgj9jikpEOFCTZ1MoAxUCQhY//9vaKBg/l@37L9ucQ4A). 1NDD = Neil-Driven Development. My previous answer: # [Charcoal](https://github.com/somebody1234/Charcoal), 32 27 24 20 bytes ``` NμNν¿÷μνIEν⁺÷μν‹ι﹪μν ``` [Try it online!](https://tio.run/##S85ILErOT8z5///9nnXn9oCIvYf2H95@bs@5ve/3rHy/Z@m5vY8ad0EEHjXsPLfz/c5VIPb//@YKpgA "Charcoal – Try It Online") Outputs nothing if there is no solution. Link to the [verbose version](https://tio.run/##XYs7CsMwEAX7nGLLFciQkNKVSRpDbHIFxZLxgrQy@vj6G6ULnm6G95bNpCUaLzLyXstcw8clDKq//Ds3pxVw5PKkg6zDoIGVgnciLvgwueBkdmQNg7XnmYaXyxlJwxRt9bHV9v3Ri9yucJfukC77Lw). Of course, I couldn't have golfed it down without Neil's help. [Answer] # [R](https://www.r-project.org/), 33 bytes ``` function(m,n)diff(trunc(0:n*m/n)) ``` A port of Luis Mendo's [Octave answer](https://codegolf.stackexchange.com/a/132126/67312). Pretty sad that this is almost 50% shorter than my previous answer. [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jVydPMyUzLU2jpAgopGFglaeVq5@nqfk/TcNcx0LzPwA "R – Try It Online") ### previous answer, 63 bytes: ``` function(m,n,o=rep(m%/%n,n),d=m-sum(o))o+c(rep(0,n-d),rep(1,d)) ``` An anonymous function that takes two (mandatory) arguments `m` and `n`, and two optional ones which are for golfing purposes. Returns a vector in increasing order. For failure, the first value will be `0`, which is falsey in R, since `if` only uses the first value of the vector (with a warning). It is essentially equivalent to the following function: ``` function(m,n){o=rep(m%/%n,n) d=m-sum(o) o+c(rep(0,n-d),rep(1,d))} ``` [Try it online!](https://tio.run/##JckxCoQwEAXQ3lOkEebjFxUEt0m7J/AGSQYEMxFdzx@R7R68s6qvelv4bcUk01j8mQ7J7dAaDYw@99edpQClC/LeSOsj@HJiBKrKNHJGo7Lwg2ZT@QtudWm/kvvWBw "R – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 4 [bytes](https://github.com/splcurran/Gaia/blob/master/codepage.md) ``` …÷l¦ ``` There's almost just a built-in for this... ### Explanation ``` … Get the range [0 .. m-1]. ÷ Split into n roughly even length chunks. Throws an error if the number of chunks if more than the list's length. l¦ Get the length of each chunk. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes ``` :ȧœsL€ ``` [Try it online!](https://tio.run/##y0rNyan8/9/qxPKjk4t9HjWt@f//v/l/YwA "Jelly – Try It Online") Outputs nothing for falsy. ### How it works ``` :ȧœsL€ Main link. Arguments: m (integer), n (integer) : Integer division. Yields 0 if m < n; a positive integer otherwise. ȧ Logical AND. Yields 0 if m < n; m otherwise. œs Split into n roughly equal groups. Since the left argument is an integer, this implicitly converts it to [1..m] (or [] for 0) before splitting. L€ Length of €ach. If the inputs were 7 and 3, the previous result would be [[1,2,3],[4,5],[6,7]], so this would give [3,2,2]. ``` [Answer] ## TI-Basic, 23 bytes ``` :Prompt M,N :N(M≥N :int(Ans⁻¹randIntNoRep(M,M+N-1 ``` Returns ERR:DIVIDE BY 0 on error [Answer] # [Octave](https://www.gnu.org/software/octave/), 24 bytes ``` @(m,n)diff(fix(0:m/n:m)) ``` The code defines an anonymous function. The output is a numeric array (row vector). When there is no this array contains at least one zero, which is [falsy](https://tio.run/##y08uSSxL/f@/QsFWIdpQwUjBWMEg1porM02hgktBISWzuEBDvaSotCSjUl2TKzWnOBUumpaYUwwWzEv5/x8A) in Octave. [**Try it online!**](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjVydPMyUzLU0jLbNCw8AqVz/PKldT83@ahpmOsSZXmoY5jDKCUIYQygJEGRromGj@BwA "Octave – Try It Online") ### Explanation `0:m/n:m` produces an array of `n+1` values from `0` to `m` with step `m/n`. `fix` rounds each entry towards `0`, and `diff` computes consecutive differences. As an example, here are all intermediate results for `m = 7`, `n = 3`: ``` >> 0:m/n:m ans = 0 2.3333 4.6667 7.0000 >> fix(0:m/n:m) ans = 0 2 4 7 >> diff(fix(0:m/n:m)) ans = 2 2 3 ``` [Answer] # [Haskell](https://www.haskell.org/), ~~93~~ ~~89~~ ~~88~~ ~~87~~ ~~86~~ 71 bytes ``` m!n|n<=m=e$m:(0<$[2..n]) e(a:b:x)|b<a=e$a-1:e(b+1:x) e(a:x)=a:e x e x=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1cxrybPxjbXNlUl10rDwEYl2khPLy9WkytVI9EqyapCsybJJhEomahraJWqkaRtCBQCy1Vo2iZapSpUcAGxbcX/3MTMPNuCosy8EhULRYv/AA "Haskell – Try It Online") ## Explanation The main function here is `e`. `e` will take a list and essentially run a rolling pin along it from left to right. While there is an element in the list that is greater than its neighbor to the right we will move one from it to the right. Now all we have to do is feed this function a sufficiently lopsided list and allow it to do the magic. The list we will choose is just `m` followed by `n-1` zeros. Since that is easy to make. The last thing we need to do is make sure that the error case is handled. For this we just throw a `Non-exhaustive patterns in function` error as long as `m>n`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 86 82 71 bytes ``` using System.Linq;a=>b=>new int[b].Select((x,i)=>(i<a%b?1:0/(a/b))+a/b) ``` throws an error for invalid inputs. [Try it online!](https://tio.run/##nY9LSwMxEIDv@RVDQUhw3bYovrYbD0VFqSD04KH0kMRxGdhNMMn6QPrb16xULd7cOYRkMt/MNyYcGOexawPZCpbvIWJTsN1XviD7/Cc1d3WNJpKzIb9Gi55MwZipVQhw713lVQMfDFKEqCIZeHH0CHeKLA/Rp0arNShfBbGt6uOqtWZGNmY7t5tL2zbola6xT0gp4Sl9QgnfGOtUKXUpLb5Cqljpdb7E3o3zt4xEKTnN1J6@mJ5PxlyNtRD7/dlB8v0ZPU97uBrzB08R07q4tcxvXTIeZaPsayw/FvxQCFH8GzwZCk4ngh8NIs8EPx3q@gtu2Kb7BA) -4 bytes thanks to *TheLethalCoder* -11 bytes thanks to *OlivierGrégoire* [Answer] ## Haskell, 48 bytes ``` m#n|m>=n=iterate(\(a:b)->b++[a+1])(0<$[1..n])!!m ``` Start with a list of `n` zeros. Repeat `m` times: take the first element, add one and put it at the end of the list. Fails with a pattern match error if `n < m`. [Try it online!](https://tio.run/##y0gszk7Nyfn/P1c5rybXzjbPNrMktSixJFUjRiPRKklT1y5JWzs6UdswVlPDwEYl2lBPLy9WU1Ex939uYmaegq1CSj6XgkJBUWZeiYKKgrmyGQrPBIVnjMIz/A8A "Haskell – Try It Online") [Answer] # [Braingolf](https://github.com/gunnerwolf/braingolf), 30 bytes ``` .M>.M/v.mR>[.]$_v%!?[R1+>v]|R= ``` [Try it online!](https://tio.run/##SypKzMxLz89J@/9fz9dOz1e/TC83yC5aL1YlvkxV0T46yFDbriy2Jsj2////xv8NDQE "Braingolf – Try It Online") Takes inputs in reverse order (`n` is first input, `m` is second) Divides `m` by `n`, duplicates the result `n` times, then loops through and increments one by one `m % n` times [Answer] ## Batch, 71 bytes ``` @if %1 geq %2 for /l %%i in (1,1,%2)do @cmd/cset/an=(%1+%%i-1)/%2&echo( ``` `cmd/cset/a` doesn't output any separator, so I have to use `echo(` (`(` avoids printing `ECHO is on.`). [Answer] # PHP>=7.1, 62 bytes ``` for([,$s,$n]=$argv;$n;)$s-=$r[]=$s/$n--^0;$r[0]?print_r($r):0; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/c54597ef374eef5e40c48cb7411aebb0802ab077) [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda m,n:(m%n*[m/n+1]+[m/n or _]*n)[:n] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFXJ89KI1c1Tys6Vz9P2zBWG0Qr5BcpxMdq5WlGW@XF/i/PyMxJVQgpKk214uIsKaoEkpwFRZl5JQppGlqZeQWlJRqamlycqRXJqQUlCq7@bq5FRflFIFVJRamJ2TAZhDYlsAKl/2Y6xlzmYGwExIZAbMFlaGCgYwEA "Python 2 – Try It Online") `NameError` when impossible. --- **[Python 2](https://docs.python.org/2/), 43 bytes** ``` lambda m,n:[c/n for c in range(m,m+n,m>=n)] ``` [Try it online!](https://tio.run/##RcsxD4IwFATgmf6KFybQJgImQkhww9XFTR0KFmikj@alRPn1tZIYh@@WuzOLHSbMXFfd3Ch08xCgOZbXdofQTQQtKAQS2MtIc71Fro8Vxnf3GtQo4UKzLFlgafEZGFJooYs2Cs1sozhmgXy30lioz6eaaKLvqiEpnr/mfwvXQegOfM/yVealXuHlLE0SXnwA "Python 2 – Try It Online") `ValueError` when impossible. [Answer] # Javascript (ES6), ~~57 56 53~~ 41 bytes ``` m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0) ``` Answer now includes smarter way of creating the values. Thanks @Neil **Usage** ``` f=m=>n=>m>=n&&[...Array(n)].map(_=>m++/n|0) f(6)(3) // [2, 2, 2] f(7)(3) // [3, 2, 2] f(7)(2) // [4, 3] f(7)(1) // [7] f(7)(8) // false f(8)(3) // [3, 3, 2] ``` **History** First mine ``` (m,n)=>m>=n&&Array(n).fill(~~(m/n)).map((v,i)=>v+(i<m%n)) (m,n)=>m>=n&&Array(n).fill().map((v,i)=>~~(m/n)+(i<m%n)) ``` Then added the spread operator and currying syntax tipped by @Arnauld ``` m=>n=>m>=n&&[...Array(n)].map((v,i)=>~~(m/n)+(i<m%n)) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~80~~ ~~73~~ ~~63~~ ~~61~~ 59 bytes ``` n->m->{for(int i=n;i-->0/(m/n);)System.out.println(m++/n);} ``` [Try it online!](https://tio.run/##bZBfT8IwFMXf9ylueGplK6BGjZO9GEx8MCbwSPZQy8Di@ifrHZGQffbZsTGI4aW9/d1zz2m75TseGZvp7eqnlsqaAmHrGStR5mxdaoHSaHYTB7b8yqUAkXPn4INLDYcAoKMOOfptZ@QKlO@RBRZSb5Yp8GLj6FEK8K7xrXN88fWr0a5UWZHAelrrKFFRclibgkiNIKc6llGUjEdEjTSN6WLvMFPMlMist8ZcEzUcNq2qjo/uHi5Tn4iZQwfTLhPgAPAQwh1U4Rk8XgG3/8HTJZiMQ7g/gapN7C7bZT63ybQPxmLf117MuLX5njSi5SSljAuRWWzP45TGvfLKU/tuBYKj@AYy@22m/U9CRi9SrswOZvP553xwtghOaxW0df0H "Java (OpenJDK 8) – Try It Online") Note, for currying purpose, `m` and `n` are reversed. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 11 bytes ``` efqlTeQ./hQ ``` [Try it online!](http://pyth.herokuapp.com/?code=efqlTeQ.%2FhQ&input=%5B10%2C+4%5D&test_suite=1&test_suite_input=%5B6%2C+3%5D%0A%5B7%2C+3%5D%0A%5B7%2C+2%5D%0A%5B7%2C+1%5D%0A%5B7%2C+8%5D%0A%5B10%2C+4%5D%0A%5B8%2C+3%5D&debug=0) [Answer] # [Husk](https://github.com/barbuz/Husk), 15 bytes ``` S`?ø▼Ẋ-mo÷³*⁰Θḣ ``` [Try it online!](https://tio.run/##ASgA1/9odXNr//9TYD/DuOKWvOG6ii1tb8O3wrMq4oGwzpjhuKP///82/zEw "Husk – Try It Online") A port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/132126). Takes `n` followed by `m` as arguments. Outputs an empty list when no solution is possible. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 13 bytes ``` KE?>KQ0lMcK*d ``` [Try it online!](https://pyth.herokuapp.com/?code=KE%3F%3EKQ0lMcK%2Ad&input=10%0A4&debug=0&input_size=4) Output `0` on error. **Cheating, 6 bytes** ``` lMcE*d ``` [Try it online!](https://pyth.herokuapp.com/?code=lMcE%2Ad&input=10%0A4&debug=0&input_size=4) The array contains a `0` on error. Sadly this isn't falsy in [Pyth](https://github.com/isaacg1/pyth). **Explanation** ``` KE?>KQ0lMcK*dQ # Implicit input Q for m KE # Store n in K *d # Generate a string of length Q containing only spaces cK # Chop this string in K pieces of equal sizes, initial piece longer if necessary lM # For each string, compute the length. Here we already have our result. However if the array contain a zero, we must output a falsy value ?>KQ # If K > Q... 0 # Then display zero, otherwise display the array ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~13~~ 12 bytes ``` {_2$>/,/z:,} ``` [Try it online!](https://tio.run/##S85KzP2fU6eQqqwQlJqYopCZV1BaopBWlJ@rEBzi4un3vzreSMVOX0e/ykqn9j9YnWtFanJpSapCSUaqQlJOfnI2VwJI2C2/KDexBCxalFpcmlPy31jB0AAA "CJam – Try It Online") This is an anonymous block that takes the input as `n m` on the stack. It would have been a good answer, but the error handling requirement completely killed it. Errors with a divide-by-zero when it's not possible to solve. ## Explanation ``` { e# Stack: | 3 10 _ e# Duplicate: | 3 10 10 2$ e# Copy from back: | 3 10 10 3 > e# Greater than: | 3 10 1 (true) / e# Divide: | 3 10 e# This will cause an error on invalid input. , e# Range: | 3 [0 1 2 3 4 5 6 7 8 9] / e# Split on nth element: | [[0 1 2] [3 4 5] [6 7 8] [9]] z e# Transpose array: | [[0 3 4 9] [1 4 7] [2 5 8]] :, e# Length of each: | [4 3 3] } ``` If the error-handling requirement is lifted, this can be shortened to 7 bytes, which is a decrease of over 40%: ``` {,/z:,} ``` ]
[Question] [ # Input A non-empty string or list of capital letters `k` with length between 3 to 5000. # Output A value indicating whether `k` can be expressed as `a+b+b`, where `a` and `b` are non-empty. # Truthy test cases ``` SSS SNYYY SNYY SNNYY SNYNY ``` # Falsy test cases ``` FALSYTESTCASES FALSYFALSYTESTCASES FALSYTESTCASESXFALSYTESTCASES FALSYTESTCASESFALSYTESTCASES SMARTIEATIE ``` # Neglegible cases: ``` XX lowercase 123 ABC (repeated 2000 times) ``` [Answer] # JavaScript (ES6), 21 bytes Takes a string and returns a Boolean value. ``` s=>/.(.+)\1$/.test(s) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k5fT0NPWzPGUEVfryS1uESjWPN/cn5ecX5Oql5OfrpGmoZScHCwkqYmF7qoX2RkJA5xrMK4xCP9MMQxVLk5@gRHhrgGhzg7Brticw2qgggS1RNUHuzrGBTi6eoIxEDZ/wA "JavaScript (Node.js) ‚Äì Try It Online") --- # JavaScript (ES6), 59 bytes A non-regex solution. ``` s=>(g=i=>s[2*i]&&s.slice(-2*i)==(q=s.slice(-i))+q|g(-~i))`` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k4j3TbT1q442kgrM1ZNrVivOCczOVVDF8jVtLXVKLSFi2RqamoX1qRr6NYBWQkJ/5Pz84rzc1L1cvLTNdI0lIKDg5U0NbnQRf0iIyNxiGMVxiUe6YchjqHKzdEnODLENTjE2THYFZtrUBVEkKieoPJgX8egEE9XRyAGyv4HAA "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 13 bytes ``` cP$h_*>h_>~ É ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNxczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRMDS0pI0XYv1abbJASoZ8Vp2GfF2daeaIaI3_XMTM_MUbBVS8hW4FBQKihRUFNIUlBKTkpVQuIlJyPzkVEyRpESgWKISxNgFCyA0AA) ## Explanation This uses the parser library. `h_` parses any non-empty string, so we ask if there is a `h_` followed by `h_` and then we feed the output of the second `h_` into `É`. Since `É` parses any fixed string given as input, this means it parses whatever `h_` gave again. `cP` takes the parser we built and turns it into a function which returns true when there is at least one parse which completely consumes the string. ## Reflection This is such a simple challenge it's hard for this to get any better, but I have some thoughts: * `(>~ É)` is a pretty common function. It attempts to parse the result of the last parse again. However unless I assigned it a 2 byte name it wouldn't make any savings in this particular case. * `(h_*>)` might also be useful to have a shortcut for. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes ``` Jtƒë= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fku9So5MtF1SnJRcDBVZcLNJKTg4WIlLKdgvMjISSoMpGB3pB6LdHH2CI0Ncg0OcHYNdgzEEIgjIY0gH-zoGhXi6OgKxEsQpAA) ``` Jtƒë= J Split the input into a list of parts t Remove the first part ƒë Check that there are exactly two remaining parts = Check that the two remaining parts are equal ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ≈íH√ê∆§·∏äE∆á ``` A monadic Link that accepts a list of characters and yields a non-empty list (truthy) if the input can be expressed as `a+b+b` or an empty list (falsey) otherwise. **[Try it online!](https://tio.run/##y0rNyan8///oJI/DE44tebijy/VY@3@dRw1zQopKSzIqHzXMBbLdEnOKU0Hsw@32WUC@gq2dApCnGfn/f7RScHCwkg6XglKwX2RkJJwFZSBYkX4QlpujT3BkiGtwiLNjsGswFqEIgiqwKAj2dQwK8XR1BGIgPxYA "Jelly ‚Äì Try It Online")** ### How? ``` ≈íH√ê∆§·∏äE∆á - Link: list of characters, S √ê∆§ - for suffixes of S: ≈íH - split into half (if odd length first half is longer) ·∏ä - dequeue (we don't want to test for a+a, only a+b+b) ∆á - keep those for which: E - all equal? ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 8 bytes ``` .(.+)\1$ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F9PQ09bM8ZQ5f//4OBgrmC/yMhIMAkkIGSkXySXm6NPcGSIa3CIs2OwazAaNwKvLJpksK9jUIinqyMQAwA "Retina ‚Äì Try It Online") [Answer] # [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), ~~20~~ 19 bytes ``` f(_:_++b++b)|b>""=1 ``` [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI94qXls7CYg0a5LslJRsDf/nJmbmKdgqpCkoBftF@kUq/QcA "Curry (PAKCS) ‚Äì Try It Online") with truthy, or [Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z9NI94qXls7CYg0a5LslJRsDf/nJmbmKdgqpCkouTn6BEeGuAaHODsGuwaj8pT@AwA "Curry (PAKCS) ‚Äì Try It Online") with falsy test case. Thanks for a byte saved by Wheat Wizard. [Answer] # [C (gcc)](https://gcc.gnu.org/), 67 bytes ``` n;f(char*s){n=strlen(++s);return~-n&&!bcmp(s-~n/2,s+n%2,n/2)|f(s);} ``` [Try it online!](https://tio.run/##fYtNC4JAEIbv/goLlN1UAm8hHSQMgvLQeGipDrX5BTrIjtHB8q/bWrcODczDDO/7SC@XchgwyJgsLmpGvMMltapKkTkO8UCl7V1h76FtT66ybhh5Pc59lxy0fFdf/Jkx3XsNo2/ScaHnHNSXEhnvHkVZpSxPW9Id3qgS24xNLTKt2wmnLrmjO8oAYEAshPhQ40sRC2MdbkEkESSrECL4eQ9/058QduE@2USh3jc "C (gcc) ‚Äì Try It Online") -1 byte from ceilingcat [Answer] # [Uiua](https://www.uiua.org), 45 bytes ``` S‚Üê‚â°(‚ñ°‚Üô)+1‚äÉ‚á°‚ÜØ‚ߪ. ‚àä:‚äô‚ñ°‚ô≠‚äû(‚ñ°‚äê/‚äÇ‚áå‚äÇ‚äÇ.).‚äê/‚äÇ‚àµ(‚ñ°S‚äê‚áå)S‚áå. ``` [Test pad](https://uiua.org/pad?src=0_8_0__UyDihpAg4omhKOKWoeKGmSkrMeKKg-KHoeKGr-Knuy4KRiDihpAg4oiKOuKKmeKWoeKZreKKnijilqHiipAv4oqC4oeM4oqC4oqCLiku4oqQL-KKguKItSjilqFT4oqQ4oeMKVPih4wuCgpGICJTU1MiCkYgIlNOWVlZIgpGICJTTllZIgpGICJTTk5ZWSIKRiAiU05ZTlkiCgpGICJGQUxTWVRFU1RDQVNFUyIK) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes ``` ‚äôŒ¶Ôº•Œ∏‚Ķ‚ÆåŒ∏Œ∫Œπ‚źŒπ√ó¬≤‚àïŒπ¬≤ ``` [Try it online!](https://tio.run/##FYg7CsMwEAWvonIFSqPWVXCSzmBMLiDkBS/Z6GsLfPq1/JiZ4vnNFR8di8yFwg7PcMKHeMcCk0uQjRpPzzhuMcGCDUtFyNqon@6h7jsfjiuQUV/6YwVr1IsarXhfVt8bREIMFTvyaHwB "Charcoal ‚Äì Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for `a+b+b`, nothing if not. Explanation: ``` Œ∏ Input string Ôº• Map over characters Œ∏ Input string ‚Æå Reversed ‚Ķ Truncated to length Œ∫ Current index Œ¶ Filtered where Œπ Reversed suffix (is not empty) ‚äô Any reversed suffix satisfies Œπ Current reversed suffix ‚àï ¬≤ First half √ó¬≤ Repeated twice ‚ź Equals Œπ Current reversed suffix Implicitly print ``` [Answer] # [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 6 bytes ``` ·∏¢·∂úœ©¬Ω‚âàa ``` [Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCLhuKLhtpzPqcK94omIYSIsIiIsIlNOWVlZIiwiMy40LjEiXQ==) Essentially, a case is truthy if some suffix of the input minus the first character (ensuring a is non empty) can be split into two equal halves. ## Explained ``` ·∏¢·∂úœ©¬Ω‚âàa¬≠‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Ű‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Ű‚Å™‚Äè‚ņ‚Å™‚Å™‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå‚Å¢‚Ű‚Äã‚Äé‚Äé‚Å™‚Ű‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Äè‚Äã‚Ű‚ņ‚Ű‚Äå¬≠ ·∏¢ # ‚Äé‚ŰRemove the first character of the string because it could be `a` ·∂úœ© # ‚Äé‚Å¢Over all suffixes: ¬Ω # ‚Äé‚Å£ Split into halves ‚âà # ‚Äé‚ŧ And test whether both halves are the same a # ‚Äé‚Å¢‚ŰOutput whether any are true. üíé ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~15~~ 13 bytes *-2 bytes thanks to @NahuelFouilleul* ``` $_=/.(.+)\1$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfT0NPWzPGUEX//383R5/gyBDX4BBnx2DXYC5UbgReWTTJYF/HoBBPV0cg5goOBvL9IiMjwSSQgJCRfpH/8gtKMvPziv/rFuQAAA "Perl 5 ‚Äì Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~7~~ 5 bytes *-2 bytes thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)* ``` ba‚ÇÅ·∏ç= ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/PynxUVPjwx29tv//Kzk5OkUCkRIA "Brachylog ‚Äì Try It Online") ### Explanation ``` b Remove the first character from the input a‚ÇÅ Get a nonempty suffix of the remaining string ·∏ç Split it into two halves = Assert that both are identical ``` The first `b` is necessary to prevent the prefix from being empty. [Answer] # [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 42 bytes ``` {‚஬¥(‚â°Àù2‚Äø‚Üë‚ä∏‚•ä)¬®2‚Ü쬪‚Üìùï©} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwdK0R20TqpeWlqTpWtzUqn7UseLQFo1HnQtPzzV61LD_UdvER107Hi3t0jy0wuhR2-RDu4HEh7lTV9ZCdGyq5XrUsCg4I79cwU1BKdgvMlIJIrFgAYQGAA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Three different alternatives: * `.≈ì3√πŒµ¬¶√ã}√†` - [Try it online](https://tio.run/##AR4A4f9vc2FiaWX//y7FkzPDuc61wqbDi33DoP//U05ZWVk) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf72jk40P7zy39dCyw921hxf81/kfHBzMFewXGRkJJoEEhIz0i@Ryc/QJjgxxDQ5xdgx2DYZw0cVCnCMinUEUEHEF@zoGhXi6OgIxAA). * `.s¬®Œµ2√§√ã}√†` - [Try it online](https://tio.run/##yy9OTMpM/f9fr/jQinNbjQ4vOdxde3jB///BfpGRkQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf73iQyvObTU6vORwd@3hBf91/gcHB3MF@0VGRoJJIAEhI/0iudwcfYIjQ1yDQ5wdg12DIVxsYnBuBF5ZNMlgX8egEE9XRyAGAA). * `¬¶D.s2√ó√Ö¬ø√†` - [Try it online](https://tio.run/##yy9OTMpM/f//0DIXvWKjw9MPtx7af3jB///BfpGRkQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0PLXPSKjQ5PP9x6aP/hBf91/gcHB3MF@0VGRoJJIAEhI/0iudwcfYIjQ1yDQ5wdg12DIVxsYnBuBF5ZNMlgX8egEE9XRyAGAA). **Explanation:** ``` .≈ì # Get all partitions of the (implicit) input-string 3√π # Only keep the partitions containing three parts Œµ # Map over each over each remaining partition: ¬¶ # Remove the first part √ã # Check if the remaining two parts are equal }√† # After the map: check if any is truthy # (which is output implicitly as result) ``` ``` .s # Get all suffixes of the (implicit) input-string ¬® # Remove the last suffix (the input itself) Œµ # Map over each suffix: 2√§ # Split it into two equal-sized parts (first part is larger for odd lengths) √ã # Check that both parts are equal }√† # After the map: check if any is truthy # (which is output implicitly as result) ``` ``` ¬¶ # Remove the first character of the (implicit) input-string D # Duplicate it .s # Pop the copy, and push its prefixes 2√ó # Double each string √Ö¬ø # Check if the input minus first character ends with a string √† # Check if any is truthy # (which is output implicitly as result) ``` [Answer] # [Python 3](https://docs.python.org/3/) with regex, ~~43~~ 42 bytes ``` import re f=re.compile(r'.+(.+)\1$').match ``` Python3 port of the Javascript answer. Takes a string for input, returns a `re.Match` object as truthy, `None` as falsy. [Try it online!](https://tio.run/##hY4xC8IwEIX3/IoQhCZUAuImOBRpQdAOJoMBlxJSGmibkMShvz5qq120OBz3eHf3vbNDaEy/jVF31rgAnQL13ikqTWd1q7BLaIppSm6bVUJoVwXZROt0HzDi7i4HGJQPHhFQGwdl5RXUPcSIMYbWELFSCPERU5@FKAUiOwAnWo1fx4QA8KYXVeuX6EV2YoLnjB8ylo9Bo7Ngz87138L3nJ2zCz/m2bN@PBsf "Python 3 ‚Äì Try It Online") # [Python 3](https://docs.python.org/3/), ~~65~~ ~~59~~ 57 bytes ``` lambda s:any(s.endswith(2*s[i:],1)for i in range(len(s))) ``` Takes a string for input, returns `True` and `False` accordingly. [Try it online!](https://tio.run/##hU6xDoIwEN35iqZTa4iJupE4FAOJiTJYBht1qFCkCRbC1Ri@HgWURY3D5d69e@/dVY3NS7Nos@WxLeT1nEoEnjQNgakyKdy1zcl8AgftndwZzcoaaaQNqqW5KFIoQ4BS2la1NpbguL4lDbIKLGDqdOJEgur0BHPOsYswj4QQbzD0EYhIYOo5aEjLSGem1HFe6aEs4Fd6yDZcxAGPV4wH/aGe@UGPzP6f4HPPt2wXrwP2rG5kvs/8L1@3Dw "Python 3 ‚Äì Try It Online") [Answer] # APL+WIN, 39 bytes Prompts for string. ``` √ó+/n=+/¬®(n‚Ü묮‚äÇv)=n‚Ü묮(n‚Üê‚ç≥‚åä.5√ó‚ç¥v)‚Ü쬮‚äÇv‚Üê‚åΩ1‚Üì‚éï ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/@Hp2vp5ttr6h1Zo5D1qm3hoxaOupjJNWwgbJDThUe/mRz1deqaHpz/q3VKm@ahtMkQRSKpnryGQDzTyP9Awrv9pXOrBwcHqXCDaLzIyEs6CMhCsSD8Iy83RJzgyxDU4xNkx2DUYi1AEQRVYFAT7OgaFeLo6ArG6AgA "APL (Dyalog Classic) ‚Äì Try It Online") [Answer] # [Python 3.8](https://docs.python.org/3.8/), 90 bytes The function takes as input a string `s`. It returns `0` for True cases, `None` for False ones. ``` def f(s): l=len(s) for i in range(1,l): x=(i+l)//2 if s[i:x]==s[x:]:return 0 return ``` [Try it online!](https://tio.run/##jZHBa4MwGMXv@Su@m7oJtfYyBA9ZsTDYelg8KOLBbdEGQpQkMvvXu6izTaGMHQLvve9HePnSnfWpFbunTo7jF62hdpUXIeAxp8JIBHUrgQETICvRUHfr82kOQ@yyR@5tNqExrAZVsGgo41gVQ1RGkupeCggQLGrUstenM8RQGBzAIYQ4/q885nlum6u@MflxMiVCdcWVddUBv5I8TUi6xyS53Dqnf4wuafYf6D5D3vB7@pJgc5ZmgjbXXlm2crz9pvKzUnQNtuFulfh57zyEQRAsTzPLVtOyl31FM9NJJrSbyp768/d4FjfvwsYOJrjDmWY25RjPWcM@uOm0wOMP "Python 3.8 (pre-release) ‚Äì Try It Online") --- *Explanation* The function takes as input a string `s`. The `i` loop takes substrings of `s` representing `b+b`, starting from the second character in order to leave a non-empty substring `a`. `x` represents the middle of the substring. The two halves of the substring are compared: if they are equal, return `0`. If no equal halves are found, return `None`. [Answer] # [Zsh](https://www.zsh.org/), 57 bytes ``` repeat $#1-2 {1=${1:1};eval '>${1//${1:0:'{2..$#1}'-1}}'} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwc1paflFCoYKGsHBwVzBfpGRkWASSEDISL9ILjdHn-DIENfgEGfHYNdgCBebGJwbgVcWTTLY1zEoxNPVEYg1uao1uIpTSxR0U5eWlqTpWty0LEotSE0sUVBRNtQ1Uqg2tFWpNrQyrLVOLUvMUVC3A_L09UFCBlbq1UZ6ekBlteq6hrW16rUQAzZoWqcmZ-QrqNhbKxTlKmhBhRcsgNAA) Outputs via exit code. [Answer] # [Scala 3](https://www.scala-lang.org/), 32 bytes ``` s=>".+(.+)\\1$".r.findFirstIn(s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nVHRasIwFGWvfsUl7CHBWRh7GUILZVQQ1IHpYEV9iDXVbF1akrghwy_Ziy_zZV_kvmZp6yrixmAP4d6cnHPPueRtq2OWsquPEWrJ7IUpiSY7nU0feGygz4SE1wbAjCfwZC-Yqblug68UW42oUULOJ6QNd1IYcC3TUgGeWQrxgsePQ55zZviMLqe65LZxpXG929yITNYjrPh9aZLW9Q606yGniZ0mGY8vz5GjnETIWUcobboSa1LxPs82pVdu9SaVGIVqGa_AcG00InUMU6BhAVqHntAGI0opugBEB1EUfTdVrZtoEO1nHPROkinO4gUuLMD1auefNy1phJDGccoOS_VpyqRAj1N2_B6NwoCGNz4NysAl8gtcI_d_EU7fad8fht3At2cf6RDnv0sDrBvr6qM2m6p-AQ) ]
[Question] [ I made this because, although we have a bunch of other questions involving smiley faces, there is nothing for just printing an ASCII smiley face with as little code as possible. Anyway, print this exactly (Trailing spaces allowed): ``` ********** ****************** ********************** ******* ****** ******* ************************ ************************** ************************** ***** ********** ***** ***** ******** ***** ****** ****** ********************** ****************** ********** ``` This is code-golf, so fewest bytes wins. Yes, you have to use asterisks. [Answer] # [Python 3](https://docs.python.org/3/), ~~97~~ 93 bytes Thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/mukundan314) for -4 bytes! The string has a leading and trailing unprintable with value `19`. ``` for c in"%.»677íìư.%":c=ord(c);s=c//8%8*'*'+c//64*' '+c%8*'*';print(f'{s+s[::-1]:^26}') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFZITNPSVhV79BuM3Pzw2sPrzm2QU9VWMkq2Ta/KEUjWdO62DZZX99C1UJLXUtdG8g0M9FSVwCyICLWBUWZeSUaaerVxdrF0VZWuoaxVnFGZrXqmv//AwA "Python 3 – Try It Online") [Answer] # APL+WIN, 57 bytes ``` m,⌽m←13 13⍴(¯17+⎕av⍳'hedibkagbca⊢ceaecdafhkdihe')/26⍴' *' ``` String used to index into atomic vector has been adjusted to allow for differences between APL+WIN and Dyalog [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tf67Oo569uSC@sYKh8aPeLRqH1huaawNVJZY96t2snpGakpmUnZielJz4qGtRcmpianJKYlpGdkpmRqq6pr6RGVCLuoKW@n@gaf/TAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 153 bytes ``` v->{var s=0;for(var c:"HJ!DR!BV!AGBFBG!AX!@Z!@Z!@ECJCE!AECICE!AFLF!BV!DR!HJ".getBytes())System.out.print("\n* ".split("")[c/64+(s^=c/64)].repeat(c%32));} ``` [Try it online!](https://tio.run/##HY5dS8MwFIbv9ytOC0IyWRQVL6wdtrX7KHrjYIhzQszSkdmmJTktjNHfXtPCgffjPBfvibd8djr89aqsK4Nwcpk1qAqWN1qgqjSbBhNRcGvhnSsNlwlA3fwWSoBFjk7aSh2gdD@yQaP0cbcHbo6WjihAUmnblNI8bx03hxzCvp3NLy03YMPbIK8MGbx48leZ9/rhxVsvWsaLeOlFn97L13hpkiWpF6XJepDF22KgHLvKfHaUGJ9RWkLp5mxRlqxqkNVuCRL/W0/BZ7YulAs@3Ymbx4drYn/CwdA9M7KWHIm4ur@jNOj6YJycMy6ErJHopijo0HWTrv8H "Java (JDK) – Try It Online") ## Explanation The idea is to have toggle, `s`, which will tell us when to print spaces or stars. The number of those spaces or spaces is defined by each character used in the long string. Any letter is their corresponding number (`A=1, B=2, ...`), `@` actually is zero, and `!` also means 1, but it's in a lower range than `A` to know when to go to the next line. We can see the smiley as a sequence of [0,26] spaces followed by stars [1,26], possibly repeated. This makes sure that if we provide 2 chars, the first char represent the spaces and the second char represent the stars. This toggling is done using `s^=1`. But it happens that I have to insert new lines in that sequence. A new character would then mess up with that `s^=1`, so I changed that to `s^=c/64`, meaning that only letters and `@` actually trigger the toggle, while `!` result in `s^=0` which is a no-op. | `s` | `c` | `s^(c/64)` | `c/64+(s^(c/64))` | Result | | --- | --- | --- | --- | --- | | `0` | `!` | `0` | `0` | `\n` | | `0` | `[@-Z]` | `1` | `2` | (space) | | `1` | `!` | `1` | `1` | Never occurs | | `1` | `[@-Z]` | `0` | `1` | `*` | After the character is selected (but kept as a string, not as a character), it is repeated `c%32` times. It is to note that `'!' % 32 = 33 % 32 = 1` and `'@' % 32 = 64 % 32 = 0`. Java's `.repeat(0)` will indeed result in the empty string (`""`). [Answer] # TI-BASIC, 172 bytes (on-calc) / 205 bytes (as text) Conveniently, the image is exactly as wide as the screen on the TI-84 Plus CE. This should work with an 83/84(+) too, but it won't display properly due to the smaller screens. ``` {7,10,12,18,6,22,3,7,2,6,2,7,2,24,1,57,3,10,3,5,1,5,3,8,3,5,2,6,12,6,3,22,6,18,12,10,8→D " For(I,1,37 For(J,1,⌊D(I Ans+sub("* ",remainder(I,2)+1,1 End End For(I,1,338,26 Disp sub(Ans,I,26 End ``` ## Explanation * `{7,10,12,18,6,22,3,7,2,6,2,7,2,24,1,57,3,10,3,5,1,5,3,8,3,5,2,6,12,6,3,22,6,18,12,10,8→D`: Stores a list of the number of spaces and asterisks, alternating, like the lines of the image are unwrapped in 1-D space one after the other. The first value is an exception; it should theoretically be 8, but since TI-BASIC doesn't like empty strings, the output string is created with a single space already in it. * `"` : Create a string in the `Ans` "variable" with a single space in it. * `For(I,1,37`: For (the index of) each value in `⌊D`... + `For(J,1,⌊D(I` - `Ans+sub("* ",remainder(I,2)+1,1`: ...concatenate that number of either asterisks or spaces to the string, depending on whether `I`, the index of the list, is odd or even. + `End` * `End` * `For(I,1,338,26`: For I from 1 to 338 (length of the resulting string) with a step of 26 (length of each row of the image)... + `Disp sub(Ans,I,26`: ...display a substring starting at I (the start of the I-th row of the image) which is 26 characters long. * `End` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~72~~ ~~68~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •A9lΘRfÓβèε¢|Ïí"·тjêøè§Äα9₃ê˜ì•… * ÅвJº.c ``` -26 bytes by adding a mirror (inspired by [*@Neil*'s Charcoal answer](https://codegolf.stackexchange.com/a/218455/52210)). [Try it online.](https://tio.run/##AVMArP9vc2FiaWX//@KAokE5bM6YUmbDk86yw6jOtcKifMOPw60iwrfRgmrDqsO4w6jDgsKnw4TOsTnigoPDqsucw6zigKLigKYgKgrDhdCySsK6LmP//w) **Explanation:** ``` •A9lΘRfÓβèε¢|Ïí"·тjêøè§Äα9₃ê˜ì• "# Push compressed integer 61833926632893543016875916488121666051545681457434856388592933517828315 … *\n # Push string " *\n" Åв # Convert the integer to base-" *\n" (which means to convert it to base-3, # and index them into the 3-char string) J # Join all characters together to a string º # Mirror each line .c # And centralize all lines # (after which the result is output implicitly) ``` [This is the result without the mirror and centralize.](https://tio.run/##AU8AsP9vc2FiaWX//@KAokE5bM6YUmbDk86yw6jOtcKifMOPw60iwrfRgmrDqsO4w6jDgsKnw4TOsTnigoPDqsucw6zigKLigKYgKgrDhdCySv//) The code for this is generated with [this 05AB1E ASCII-art tip](https://codegolf.stackexchange.com/a/120966/52210). [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•A9lΘRfÓβèε¢|Ïí"·тjêøè§Äα9₃ê˜ì•` is `61833926632893543016875916488121666051545681457434856388592933517828315`. [Answer] # [PHP](https://php.net/), (all versions) ~~119~~ ~~106~~ ~~104~~ 71 bytes `<?=gzinflate("SP€ -8àåBå#‹cŠBe ,˜ ¸J„]¸dˆ’Cq#Œ³I]JK À‰Ûg8Ã=Ü");` **WARNING**: this code contains many non-printable chars and a function that is disabled in most online code testers. It is either impossible to enter the correct code on the page or run the function. Here is the php file I uploaded to gitHub so that you can test: [Try it OFFline!](https://github.com/Kaddath-R/Shared-Files/blob/main/SE-Golf/218443-ascii-smiley.php) For info, it was generated by PHP's `file_put_contents` with the direct result of `gzdeflate`, no other manipulation required, the file is not manually edited with an Hex program, the only modification is deleting the last null byte of the generated zip string in notepad. Thanks to @hanshenrik for the help trying to share this shortest version! **Longer version that can be tested online:** ## [PHP](https://php.net/), (version < 8.0) 104 bytes ``` <?=gzinflate(base64_decode(U1CAAC044OVC5SOLY4pCZaAsmAq4SoQUFl24ZIiSQ3EjjAOzDkkSXUpLAQnAHYnbZzjDAj3cAA)); ``` [Online PHP function(s)](http://sandbox.onlinephpfunctions.com/code/b0908711f8e68d75932034f58dbd50b55f296b68 "PHP – Online PHP function(s)") Simply encoded with gz, which is not available in TIO so I provided another site's link. (inspired by [this answer](https://codegolf.stackexchange.com/a/126233/90841) after following @Neil's link "In Honor of Adam West") EDIT: zip shortened by removing trailing spaces + finally it's only alphanumeric chars so I could remove the quotes (the warning would not show in the output in TIO like it does with Online PHP functions) [Answer] # JavaScript (ES6), 108 bytes ``` _=>`8a 4i 2m 172627 1o 0q 0q 053a35 153835 16c6 2m 4i 8a`.replace(/./g,c=>"* "[_^=1].repeat(parseInt(c,36))) ``` [Try it online!](https://tio.run/##HYrBDoIwEAXv@xWGUzFYbCull3L3G4zCpi4Eg7RS4u8jNZnkJfPmhV@MbhnDepr9k7bebq1tOoNwGUG@QdRSyxqEh/PnT6VQVSAqZdJop1O1twY7vlCY0BEreTkUzjbZ8ZDd2ocV93QRrizgEuk6r8wVSud5vjk/Rz8Rn/zAeraLHw "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~112~~ 109 bytes Returns an array of strings. ``` _=>[p=1020,960,768,515,512,0,0,28,526,519.9,768,960,p].map(n=>(g=(k,c="* "[n*8>>k&1])=>~k?c+g(k-1)+c:'')(12)) ``` [Try it online!](https://tio.run/##HYrRDoIgGEZfpXkRP4oM2CRt@@lBzDVH6hQDlq3LXt2ofTsXZ@db@ne/2eccX6UP92Efcb@haSNKoQRrtGAnXbNKVgnFRJpKqnTShjf/@DvFjj/6CB4NTAiOWczyQ9b6vDbGHWVH0XzcxRYTuFLSwp4JoSAVpbsNfgvrwNcwwQiUL2H2QK6epPYF "JavaScript (Node.js) – Try It Online") ### How? Each value in the array represents the inverted 13-bit value of the left side of the smiley, divided by 8. Dividing by 8 saves 7 bytes overall, although there's a non-integer value in there (`519.875`, which can be rounded to `519.9`). ``` ........***** -> 1111111100000 -> 8160 / 8 = 1020 ....********* -> 1111000000000 -> 7680 / 8 = 960 ..*********** -> 1100000000000 -> 6144 / 8 = 768 .*******..*** -> 1000000011000 -> 4120 / 8 = 515 .************ -> 1000000000000 -> 4096 / 8 = 512 ************* -> 0000000000000 -> 0 / 8 = 0 ************* -> 0000000000000 -> 0 / 8 = 0 *****...***** -> 0000011100000 -> 224 / 8 = 28 .*****...**** -> 1000001110000 -> 4208 / 8 = 526 .******...... -> 1000000111111 -> 4159 / 8 = 519.875 ..*********** -> 1100000000000 -> 6144 / 8 = 768 ....********* -> 1111000000000 -> 7680 / 8 = 960 ........***** -> 1111111100000 -> 8160 / 8 = 1020 ``` So, we extract the **k**th 'pixel' stored in the bitmask **n** with: ``` n * 8 >> k & 1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` ⭆”←&∨n?Þ\`W!π↖δ℅If#≕W⧴@b⪪¹λ”∨×Σι*ι‖M← ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaCiZxuRZApFRTJ6xgoI5kGUMxCYQbKqgoACUN4FQCmBgBlEM1GOqpKPgX6QRkpmbWqwRXJqrkampo6CkpQQkMzU1rbmCUtNyUpNLfDOLivKLNKx8UtNKNK3///@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ⭆”...” ``` Map over partially RLE-encoded string. ``` ∨×Σι*ι ``` Replace non-zero digits with their count of `*`s. ``` ‖M← ``` Reflect the result. Out of interest, I tried porting my answer to [In Honor of Adam West](https://codegolf.stackexchange.com/questions/126223/) but that weighed in at a massive 39 bytes (although it was still my second best approach). [Answer] # [Perl 5](https://www.perl.org/), 93 bytes ``` say'IK ES CW BHCGCH BY A[ A[ AFDKDF BFDIDF BGMG CW ES IK'=~s/./('*',$")[--$|]x(-65+ord$&)/ger ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLd05vLNZjLOZzLycPZ3dmDyymSyzEajNxcvF3cuJzcXDxBlLuvO0gVUK2nt7ptXbG@nr6Gupa6joqSZrSurkpNbIWGrpmpdn5Rioqapn56atH////yC0oy8/OK/@v6muoZGBoAAA "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 50 bytes ``` » «0QÞ*⌊B⊍E⟨}¹ǍaȦM.¥⁺⊍Ṅ₂ṖA«[¥ȯ⇩»3τ` * `viṅøṀ` `€øĊ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%0A%C2%AB0Q%C3%9E*%E2%8C%8AB%E2%8A%8DE%E2%9F%A8%7D%C2%B9%C7%8Da%C8%A6M.%C2%A5%E2%81%BA%E2%8A%8D%E1%B9%84%E2%82%82%E1%B9%96A%C2%AB%5B%C2%A5%C8%AF%E2%87%A9%C2%BB3%CF%84%60%20*%0A%60vi%E1%B9%85%C3%B8%E1%B9%80%60%0A%60%E2%82%AC%C3%B8%C4%8A&inputs=&header=&footer=) All hail new vertical mirror!! [Answer] # [///](https://esolangs.org/wiki////), 121 bytes ``` /4/33//3/22//2/11//1/**//8/99//9/00//0/ /813 914 0124 *120120*12 34 134 134 *2 013 0*2 *2 03 0*2 129812 0124 914 813 ``` [Try it online!](https://tio.run/##LYw7DsMwDEN3n0KzlqePB@s4GQJ06Ob7w1WKDAQfCJL7e@3Pvc9hkglJBATu4KjCogoKMzBEWJ6jfA7zmEPUo8HahuQc/kpDzFNMO374RY9a3fxPn4/@OucH "/// – Try It Online") Will add explanation soon! [In the meantime, if this isn't obscure enough, see if you can figure this one out!](https://tio.run/##DYwxDgMhDAT7vCJ1mnkDNviwOfhDikgp0vF/EVczWo12/977@9nnsCgFJqpwY8sNHKnQMR1FJIeLsAHGAxojtRIBSksXauYFcRg8IXgxW@ltVRsezZtfS@78ltCiciVEkj6nW1Y963P@ "/// – Try It Online") [Answer] # [Vim](https://www.vim.org), 82 bytes ``` 13i*<esc>Ypr Yppr p3r p7r :g/^/t0 3j2r 3jYp6|3r jh3r jh6r :%s/\v(\*+)( *)(.*)/&\3\2\1 ``` [Try it online!](https://tio.run/##K/v/39A4U8smtTjZLrKgSCGyAEgUGAOxeZGCVbp@nH6JAZdxllGRgnFWZIFZDVAmKwNMmAHlVYv1Y8o0YrS0NTUUtDQ19LQ09dVijGOMYgy5/v//r1sGAA "V (vim) – Try It Online") ### Explanation Approach: 1) Make a quarter-circle with asterisks. 2) Mirror it vertically. 3) Replace some of the asterisks with spaces. 4) Mirror it horizontally. ``` 13i*<esc> ``` Insert 13 asterisks. ``` Ypr<spc> ``` Make a copy of the line and replace the first character of the copy with a space. ``` Yppr<spc> ``` Make two copies of that line. Replace the first non-space character of the second copy with a space. ``` p3r<spc>p7r<spc> ``` Paste another copy and replace the first three characters with spaces; paste one more copy and replace the first seven characters with spaces. ``` :g/^/t0<nl> ``` A modified version of [this trick for reversing the lines in the buffer](https://vim.fandom.com/wiki/Reverse_order_of_lines): instead of moving each line to the beginning with `m0`, copy it to the beginning with `t0`, effectively mirroring the whole buffer upward. ``` 3j2r<spc> ``` The cursor is on the first asterisk of the top line; if we go down three times, we happen to land on the leftmost character that should become the eye. Replace two characters with spaces. ``` 3jYp ``` Go down three more times and make a copy of the line. (This is the center line; we need three copies of it, but the mirroring code left us with only two.) ``` 6|3r<spc> ``` Go to the sixth character; replace three characters with spaces. ``` jh3r<spc> ``` Go down one line, go left one column, and replace three characters with spaces. ``` jh6r<spc> ``` Go down and left again and replace six characters with spaces. ``` :%s/\v ``` On all lines, substitute (using the "very magic" setting so we don't have to backslash all the parentheses)... ``` (\*+)( *)(.*) ``` ... one or more asterisks, zero or more spaces, and the rest of the line if any... ``` /&\3\2\1<cr> ``` ... with the full match followed by the three capture groups in reverse order. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ 32 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)! Very similar to my [Python answer](https://codegolf.stackexchange.com/a/218475/64121), this encodes the half of every line as a 3-digit base 8 integer. ``` •γÂÂàª[O‘ôγ̹‚5•₄;вε8в„* Þ×J}º.c ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOic5sPNwHhgkOrov0fNcw4vAUo0HNo56OGWaZA2UdNLdYXNp3banFh06OGeVoKh@cdnu5Ve2iXXvL//wA "05AB1E – Try It Online") **Commented:** ``` •γÂÂàª[O‘ôγ̹‚5•₄;в # compressed integer list # [5,135,263,467,327,391,391,349,348,432,263,135,5] (base 10) # [5,207,407,723,507,607,607,535,534,660,407,207,5] (base 8) ε } # map over the integers; example: 467 8в # convert to base 8 [7, 2, 3] „* # push the string "* " Þ # create a infinite list by cycling the characters × # for each each base-8 digit, repeat the character at the same index this many times # ['*******', ' ', '***'] J # join into a single string '******* ***' º # mirror every line .c # centralize and join by newlines ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 82 bytes ``` i10¶e18¶c22¶b7c6c7¶b24¶26¶26¶5d10d5¶b5d8d5¶b6jd6¶c22¶e18¶i10 \d+ $** T`l`d \d $* ``` [Try it online!](https://tio.run/##K0otycxL/P@fK9PQ4NC2VEOLQ9uSjYwObUsyTzZLNgfSRiaHthmZQbBpiqFBiilQ0DTFAkybZaWYQTWAtQIN4YpJ0eZS0dLiCknISUgB8oAchf//AQ "Retina 0.8.2 – Try It Online") Explanation: Uses run-length encoding, where numbers encode `*`s and letters `b-j` encode spaces (so for the 12 spaces of the mouth I need two letters). ``` i10¶e18¶c22¶b7c6c7¶b24¶26¶26¶5d10d5¶b5d8d5¶b6jd6¶c22¶e18¶i10 ``` Insert the run-length encoded text. ``` \d+ $** ``` Decode integers to runs of `*`s. ``` T`l`d ``` Replace letters `b-j` with digits `1-9`. ``` \d $* ``` Decode digits to runs of spaces. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 49 bytes Obligatory bubblegum entry. Generated with `zopfli --i1000 --deflate -c smiley.txt | xxd`. ``` 00000000: 5380 022d 38e0 42e6 a208 8369 4c09 9838 S..-8.B....iL..8 00000010: 4401 8246 c860 ea01 6272 a560 ae83 71a0 D..F.`..br.`..q. 00000020: 56c1 b898 3230 3e02 60f5 11e1 10c0 0c2b V...20>.`......+ 00000030: 00 . ``` [Try it online!](https://tio.run/##jY4xCgIxEEV7T/F7cZjMZOOshYWIlZ1gbRKjCFoo7PljgnsAXzHwmzcvTSk9y3161cozGwxqDBa5Qq0wvJSAKGwwDSN85hGjqQEnopXRjhqPI5EtfgbXHN6zg4kPyBYYJbYZZC2IQ5uxmGLtIgN7ogNdiNKn3zfNDukdITskGw0qytDCgsC3Ac4VB8e5VWZJwLkFCG@7oLOcHdoc3F78BdX6BQ "Bubblegum – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ 33 bytes ``` “ ṄUçɓĠḷƑżØS`’b12o43µ⁾ *ṁxs13m€0Y ``` [Try it online!](https://tio.run/##AT8AwP9qZWxsef//4oCcIOG5hFXDp8mTxKDhuLfGkcW8w5hTYOKAmWIxMm80M8K14oG@ICrhuYF4czEzbeKCrDBZ//8 "Jelly – Try It Online") ## Explanation ``` “ ṄUçɓĠḷƑżØS`’b12o43µ⁾ *ṁxs13m€0Y Main monadic link “ ṄUçɓĠḷƑżØS`’ 8060783762011200773438708597 b12 Convert to base 12 => [8,5,4,9,2,11,1,7,2,3,1,0,3,5,1,5,3,4,1,6,8,11,4,9,8,5] o43 Logical OR with 43 => [8,5,4,9,2,11,1,7,2,3,1,43,3,5,1,5,3,4,1,6,8,11,4,9,8,5] µ Use as argument to new monadic chain ⁾ *ṁ Repeat " *" to have the same length x Repeat each character as many times as the corresponding number s13 Split into chunks of 13 m€0 Mirror each Y Join with newlines ``` [Answer] # [Julia](http://julialang.org/), 102 bytes ``` println.(split(join(collect(" *"^18).^(b"HJKRFVCGBFBGBXAyCJCEAECHCEBFLFCVFRLJ".-64)),r"(?<=\G.{25})")) ``` [Try it online!](https://tio.run/##nVBNC4JAEL3vr5A57S4lGBURReiyq5h08CAdQijpsLKomEER/XbzoKKSBL3b@xhm5sV3Jc/GoyyzXCaFSnR8y5QscJzKBEepUteowKBRCI0V0UN8Acfd@yJgtiUs2zqaT@YybnLmMG4JT7BA@J4L@nQ5J2SSA95ttidbf80WbwKENGsw@Fxwnx8YXwNBrQqg1aAtUJ92ZPoVqNGbQBtEIxOVQ@nfVu@6htSrOt7AoVoHPz8aa2DYVVUgKT8 "Julia 1.0 – Try It Online") the string stores the amount of consecutive `' '` and `'*'`. We than split the string in 26-character chunks and print with line breaks [Answer] # [Perl 5](https://www.perl.org/) `-M5.10.0`, 73 bytes ``` $_=unpack"B*","......w......|{.......";y/01/ */,say$_.reverse for/.{13}/g ``` [Try it online!](https://tio.run/##ZY/NbsIwEITveYpRxAmBY68TL7RqD733GVBivCUqhSiBAqJ99tThR63UOYy0P/p2tiq7Vd8fj0tMW6h60@x3aldv8Yzuo16Hk2rWSdKEdo3pa6GMVvrvIPjVNkkOHlP/2@57fdMDKC8EdskFXGANZ5yFq4iQE5UgIh9Na2C0eNpvmtK/py/jdJKq5EowkSEzFniRAAnMkKi7GQF7riBaC6AGHS6uvs7qzqCBEeLqZWum43Vb8RwkVsMaEpAewkgMc2Wkj6dMmwzjbHJj2Mhg6wx4TjkKoQAmV4DdYMTxq4Lif87FHF15Gi1UGz5D28XQ2xsjHxg0nAsxsjXWgpexdIz/ajN1NvY7e/sB "Bash – Try It Online") ## Explanation This solution consists of mostly unprintable characters which are a packed binary string containing a representation of the left-half of the image as `0`s and `1`s which is `unpack`ed into `$_`, then `y///` (`tr///`) changes all the `0`s to s and the `1`s to `*`s, before the `/.{13}/g` (`m//`) matches each stretch of 13 chars passing them to `say` (`$_`), along with the `reverse` of `$_`, to print the result on individual lines. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~66~~ ~~55~~ 52 [bytes](https://en.wikipedia.org/wiki/UTF-8) -11 bytes thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco) ``` "ǿ߿࿧࿿῿῿἟ྏ࿀߿ǿ"¬®c s" *" ê1Ãû ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=Ih9cdTAxZmZcdTA3ZmZcdTBmZTdcdTBmZmZcdTFmZmZcdTFmZmZcdTFmMWZcdTBmOGZcdTBmYzBcdTA3ZmZcdTAxZmYfIqyuYyBzIiAqIiDqMcP7) ## Explanation ``` "..." // String with characters at codepoints: // 31 (' *****' as binary string where ' ' -> 0, '*' -> 1) // 511 (' *********' as binary string where ' ' -> 0, '*' -> 1) // 2047 (' ***********' as binary string where ' ' -> 0, '*' -> 1) // 4071 (' ******* ***' as binary string where ' ' -> 0, '*' -> 1) // 4095 (' ************' as binary string where ' ' -> 0, '*' -> 1) // 8191 ('*************' as binary string where ' ' -> 0, '*' -> 1) // 8191 ('*************' as binary string where ' ' -> 0, '*' -> 1) // 7967 ('***** *****' as binary string where ' ' -> 0, '*' -> 1) // 3983 (' ***** ****' as binary string where ' ' -> 0, '*' -> 1) // 4032 (' ****** ' as binary string where ' ' -> 0, '*' -> 1) // 2047 (' ***********' as binary string where ' ' -> 0, '*' -> 1) // 511 (' *********' as binary string where ' ' -> 0, '*' -> 1) // 31 (' *****' as binary string where ' ' -> 0, '*' -> 1) ¬ // Convert the string to an array ® // map array with func: c // convert char to codepoint s" *" // convert codepoint to a binary string with chars "* " ê1 // concatenate reverse of the binary string to itself û // centre-pad result of map The -R flag then concatenates the resulting array with newlines ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~175~~ 168 bytes -7 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) ``` *s;i;p(x,y){for(i=x-printf("%*s",x-97,"");i++<y;printf("*"));s++;}f(){for(s=L"ikjesjcwjbhcgchjbyja{ja{jafdkdfjbfdidfjbgmgjcwjesjikA";*s-'j'?p(*s,s[1]):puts(""),*s++;);} ``` [Try it online!](https://tio.run/##RY7BboMwDEDvfEWUqWoSwrSdqtbtpt33B9sOJSHgsKYIgwpCfDsLq6ZZlmzZz3o2WWnM8oDBfPe2YEfqLF4fq5dFESA0YtCjnNy1FXgasqbF0DnBN4q4HrL9TnMuAdP0OMLfTnEpgdIUZiful3R651j7gry5@bwypal8Pvrz9JvO1tb53FlcS3kpVyqyWL9xUJRt/fa1EYo0fTx/yUPTdySiVavVIWFeopZdzhiEZFOSsBhRDMkd/Azxwf/h2rRF17eBPUEyLz8 "C (gcc) – Try It Online") Explanation before some golfing: ``` char*s="ikjesjcwjbhcgchjbyja{ja{jafdkdfjbfdidfjbgmgjcwjesjik"; ``` This string encodes the number of consecutive spaces and asterisks along with the newlines position. ``` p(x,y){for(i=97;i++<x;printf(" "));for(i=97;i++<y;printf("*"));s++;} ``` This function takes as arguments the ASCII value of two characters and use the first one to print whitespace and the second to print asterisks. ``` f(){*s-'j'?p(*s,s[1]):puts("");*s++&&f();}; ``` Here we check whether the current character is a `'j'`, which has been chosen to encode a newline. [Answer] # [Python](https://python.org), ~~142~~ 140 bytes ``` for x in"销夀㬀✣Ⰰᴀᴀᔵ┴♠㬀夀销":a,b,c,d=[int(x,16)for x in hex(ord(x))[2:]];s=' '*(a-1)+'*'*b+' '*c+'*'*d;print(s+s[::-1]) ``` [Try it online](https://tio.run/##K6gsycjPM/7/Py2/SKFCITNP6eWUhqdLGh6vaXg0Z/GjDQ0Pt4DRlK2Ppmx5NHMBUBwoC1SjZBWdqJOkk6yTEmsbnZlXolGhY2imCTNFISO1QiO/KEWjQlMz2sgqNta62FZdQV1LI1HXUFNbXUtdK0kbxE8Gs1OsC4pARhRrF0dbWekaxmr@/w8A) This is very... stupid. It's in the vein of another Python answer but uses a more naive encoding: ``` (number of alternating spaces and asterisks in half of the image.) _ * _ * ======== 9 5 0 0 \u9500 销 5 9 0 0 \u5900 夀 3 11 0 0 \u3b00 㬀 2 7 2 3 \u2723 ✣ 2 12 0 0 \u2c00 Ⰰ 1 13 0 0 \u1d00 ᴀ 1 13 0 0 \u1d00 ᴀ 1 5 3 5 \u1535 ᔵ 2 5 3 4 \u2534 ┴ 2 6 6 0 \u2660 ♠ 3 11 0 0 \u3b00 㬀 5 9 0 0 \u5900 夀 9 5 0 0 \u9500 销 ``` [Answer] # Excel, 111 bytes ## Formula, 60 bytes ``` =CONCAT(IF(A1:A32=""," ",REPT(" ",A1:A32)&REPT("*",B1:B32))) ``` ## Data in cells, 51 bytes | | A | B | | --- | --- | --- | | 1 | 8 | 10 | | 2 | | | | 3 | 4 | 10 | | 4 | | | | 5 | 2 | 22 | | 6 | | | | 7 | 1 | 7 | | 8 | 2 | 6 | | 9 | 2 | 7 | | 10 | | | | 11 | 1 | 24 | | 12 | | | | 13 | 0 | 26 | | 14 | | | | 15 | 0 | 26 | | 16 | | | | 17 | 0 | 5 | | 18 | 3 | 10 | | 19 | 3 | 5 | | 20 | | | | 21 | 1 | 5 | | 22 | 3 | 8 | | 23 | 3 | 5 | | 24 | | | | 25 | 1 | 6 | | 26 | 12 | 6 | | 27 | | | | 28 | 2 | 22 | | 29 | | | | 30 | 4 | 18 | | 31 | | | | 32 | 8 | 10 | [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnFvFtajNojOPmYnT?e=yHevV4) Column A indicates the number of " "; Column B the number of "\*". If column A is "" then add a line feed. [Answer] # [C (gcc)](https://gcc.gnu.org/), 145 bytes116 Bytes Thanks to [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only), who managed to shave 29 bytes off. ``` c;f(i){for(i=0;c="+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y'u+-"[i++];c&64&&puts(""))while(--c%64>34)putchar(i&1?32:42);} ``` [Try it online!](https://tio.run/##DYxLCoMwFAD3nkKiiXkN6UeDi6bag5Qu5Kn1FT@lKkXEs9swMJuBQf1C3APqsZ3Lyr@NU0nDscl3tLUkWOvhKyk7W8yY6qKZL@GBA3@Ha7A5pNCiCaVQznAivkSz0uxBSj0titQI8ZmnUTIG8GuoraTWyFOTJwZcwKZwc3G5J/HVxGC3nfrJ7wrqJXirV0uw3rb/AQ "C (gcc) – Try It Online") I had to start the encoding at 35, since 34 is `"` which requires an additional `\` as escape character and thus would increase the total character count. Each character in the string `+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y` minus 35 represents the number of spaces and asteriks, in an alternating pattern. This achieves a compression rate of almost 8 (318/40). Ungolfed: ``` char*s="+m'u%y$*%)%j${#}#}#(&-&h$(&+&h$)/i%y'u+-"; void f() { for( int i=0; i < 40; ++i) { for(int j=35; j < (s[i]&63); ++j ) { if( i&1 ) { printf("*"); } else { printf(" "); } } if( s[i] & 64 ) { printf("\n"); } } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 57 bytes ``` jm.[26+_K++*\*%/J|Cd390 8 8*\ /J64*\*%J8K\ ",5Ÿ6>>íå5, ``` [Try it online!](https://tio.run/##K6gsyfj/PytXL9rITDveW1tbK0ZLVd@rxjnF2NJAwULBQitGQd/LzAQk7GXhHaOgJKVjemi@mZ3d4bWHlzKY6kj9/w8A "Pyth – Try It Online") [Answer] ## x86-16 machine code, ~~101~~ 96 bytes Saved 5 bytes thanks to @peterferrie. ``` 0BEC:0100 BE 44 01 31 DB AD 91 E3-22 51 E8 20 00 59 C1 E9 .D.1...."Q. .Y.. 0BEC:0110 03 80 36 2E 01 08 E8 14-00 80 36 2E 01 08 83 FB ..6.......6..... 0BEC:0120 0C 74 05 B8 0A 00 CD 29-43 EB DA CD 20 D1 E1 19 .t.....)C... ... 0BEC:0130 C0 24 0A 0C 20 83 FB 09-75 03 83 F0 0A CD 29 85 .$.. ...u.....). 0BEC:0140 C9 75 EA C3 F8 00 F8 0F-F8 3F 38 7F F8 7F F8 FF .u.......?8..... 0BEC:0150 F8 FF F8 F8 78 7C F8 81-F8 3F F8 0F F8 00 00 00 ....x|...?...... ``` Standalone executable. Instruction listing (nasm syntax): ``` org 100h mov si, face xor bx, bx lop: lodsw xchg cx, ax jcxz ed push cx call loop pop cx shr cx, 3 xor byte [loop+1], 8 call loop xor byte [loop+1], 8 cmp bx, 12 je sk mov ax, 0Ah int 29h sk: inc bx jmp lop ed: int 20h loop: shl cx, 1 sbb ax, ax and al, 0ah or al, ' ' cmp bx, 9 jne yy xor ax, 10 yy: int 29h test cx, cx jnz loop ret face: dw 00f8h, 0ff8h, 3ff8h, 7f38h, 7ff8h, 65528, 65528, 63736, \ 7c78h, 33272, 3ff8h, 0ff8h, 00f8h, 0000h ``` ## Example run ``` C:\test>smile.com ********** ****************** ********************** ******* ****** ******* ************************ ************************** ************************** ***** ********** ***** ***** ******** ***** ****** ****** ********************** ****************** ********** ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 123 bytes ``` print(''.join(['\n',['*'*x,' '*-x][x<0]][x!=0]for x in(y-90for y in b'RdZVlZXpZYaX`XaZYrZtZtZ_WdW_ZY_WbW_ZY`N`ZXpZVlZRd'))) ``` [Try it online!](https://tio.run/##FYpNCsMgGAWvYldflKQI3bTQXqGLLOpfRROkJKWoiAtzeqs8mMfAxCNvwV@uMdUa0@7zAHD@ht0PCt4eRgUESBkBAZmKVuVOdePpQfUnJFRQC4/pRrscTdAKs5Ovn@RRioVbvkiRZG4zzDEjhWFrP/u0PWnh7ABjXOsf "Python 3.8 (pre-release) – Try It Online") ## Explanation The list-switch part outputs newlines when x is 0, x number of `'*'` characters when x > 0, and -x number of `' '` characters when x < 0. I think of it as abs(x) characters, where the sign determines which character I'm writing. The byte list comprehension subtracts 90 from each byte in the buffer to feed the outer comprehension the expected values centered at 0, since a buffer can't hold negatives in a literal (afaik). Used a script to encode the smiley face as character run lengths to create the bytes literal... I think I lost the original but may add it later. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 249 bytes ``` s=`\t***** ********* *********** ******* *** ************ ************* ************* ***** ***** ***** **** ****** *********** ********* \t*****`;s=s.split`\n`;s=s.map(l=>l+[...l].reverse().join``);console.log(s.join`\n`) ``` [Try it online!](https://tio.run/##hU7LCsMgELz7FTmqpfsDwf5IU1BSKYaNiiv5fZuHQtJL5zQzy8zOZBZDY3Ix331421JI6SHLDaxbIRvYiW@qkt1l55Nk8p9qvTVXZWvpdvz@u2ypC3VPioAiuqwHf6jZRI7qgbcnAOALkl1sIssFTMF5rUU/Bk8BLWD4cDrcNSxK@QI "JavaScript (Node.js) – Try It Online") ]
[Question] [ ### Introduction *Pareidolia*: From Ancient Greek; *παρα* ‎(*para*, “concurrent, alongside”) + *εἴδωλον* ‎(*eídōlon*, “image”). The tendency to interpret a vague stimulus as something known to the observer, such as interpreting marks on Mars as canals, seeing shapes in clouds, or hearing hidden messages in music. Source: [Wiktionary](https://en.wiktionary.org/wiki/pareidolia). For example: [![enter image description here](https://i.stack.imgur.com/CIN97.jpg)](https://i.stack.imgur.com/CIN97.jpg) *Paralogia*: From Ancient Greek; *παρα* ‎(*para*, “concurrent, alongside”) + *λόγος* ‎(*lógos*, “speech, oration, word, ...”). The tendency to perceive words in arbitrary sequences of characters, such as in code golf programs. Source: yeah, I made that up (actually the word means [something else](http://www.merriam-webster.com/medical/paralogia), as pointed out by @Martin). For example: ``` df4$/H)hEy_^p2\ jtK2$)look|x1$ ``` ### Challenge Write a program that takes a positive integer as input, produces an integer as output, and includes an English word as part of the code. The input-output relationship must correspond to an integer sequence that can be found in [OEIS](https://oeis.org/). ### Rules * Only words from this [**list**](http://www.mieliestronk.com/corncob_lowercase.txt) are allowed. This is admittedly arbitrary, but it's essential that we all agree on which words are accepted; and in that regard this list is probably as good as any other. * Words need to be formed by **concatenating** at least two function names or statements. If your language for example has a function called `correlation` it can't be used as is. The concatenation has to be strict: no other symbols should appear between the parts of the word. For example, `bro~ken` would not count as a word. * **Case** is unimportant: both `valid` and `vaLiD`are acceptable. * Words within strings do not count. The letters that make up the word need to be functions or statements in the language of choice, that is, something that is actually **executed**. For example, the following code would not be allowed: `'deoxyribonucleic'~1`, where `'...'` is a string, `~` discards the previous content, and `1` just prints number `1`. * Every letter of the word should be **necessary**. This means that removing a single letter from the word should change the input-output relation. That includes outputting a different sequence, or outputting any other thing(s), or producing no output, or causing an error. * Any **positive integer** should be acceptable as an input, and should produce an output, except for data-type or memory restrictions. * The outputs corresponding to inputs `1`, `2`, `3`, ... should correspond to a sequence appearing in [**OEIS**](https://oeis.org/). No other output should be produced; only an integer number, possibly with trailing or leading whitespace. * Input and output can be function arguments or stdin/stdout. ### Score The score is computed as total code length minus twice the length of the longest word, in characters. Or equivalently, number of not-in-longest-word characters minus length of longest word. Lowest score wins. ### Examples Consider an imaginary postfix language that has these functions: `c`: input a number; `At`: compute square; `$`: add 1. `cAt` would be a valid program (its output corresponds to the sequence `1`, `4`, `9`, ..., which is [A000290](https://oeis.org/A000290)), and it would have score −3. `cAt$` would also be valid (sequence `2`, `5`, `10`, ..., which is [A002522](https://oeis.org/A002522)), with score −2. `c$At` would not be valid, because the only word here is "At" and is produced by a single function or statement. [Answer] # CJam, -20 ``` COUNTErREVOLUTIONARIES], ``` Outputs the nth element in the sequence [A010861](https://oeis.org/A010861). ``` COUNTE e# push values of six preinitialized variables r e# read a token of input REVOLUTIONARIES e# push values of 15 other preinitialized variables ] e# wrap whole stack in array , e# get length ``` Removing a character from the word results in a completely different sequence [A010860](https://oeis.org/A010860). There is a quite interesting relationship between the two sequences: at every index n, `A010860(n)` is coprime to `A010861(n)`! There must be some deep mathematical reason behind this. Try it [here](http://cjam.tryitonline.net/#code=Q09VTlRFclJFVk9MVVRJT05BUklFU10s&input=&args=MjM0NTE). [Answer] ## CJam, -5 ``` limpet; ``` [A010051](https://oeis.org/A010051): prints `0` for composite numbers and `1` for primes. It took me forever to find something that scored a few points and would break at the removal of any letter. Removing anything except `m` throws an error, and removing `m` turns the program into the identity function. ``` li e# Read input and convert to integer. mp e# Check for primality. et e# Get current datetime as a list. ; e# Discard the datetime again. ``` [Try it online.](http://cjam.aditsu.net/#code=limpet%3B&input=9) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~-4~~ -11 Code, prints [A010869](https://oeis.org/A010869) (constant 30): ``` ASYNcHRonouSlyI)g ``` --- Previous code: ``` DoGS ``` Explanation: ``` D # Duplicate top of the stack o # Pop a, push 2**a G # For N in range(1, 2**a): S # Push all chars seperate from the top of the stack ``` Prints the [A010879](https://oeis.org/A010879) sequence. [Answer] # [MATL](https://esolangs.org/wiki/MATL), −6 ``` INhale ``` [**Try it online!**](http://matl.tryitonline.net/#code=SU5oYWxl&input=NQ) Produces sequence `1`, `2`, `3`, ... ([A000027](https://oeis.org/A000027)) Removing any letter changes the output, or leaves the program expecting a second input which doesn't exist, or produces an error. ### Explanation The program simply *inhales* a number and, after some fiddling around, exhales it unchanged. ``` I % produces number 3 N % number of elements in stack: produces number 1 h % concatenates horizontally into array [3, 1] a % true if any element is nonzero. So it gives true (or equivalently 1) l % produces number 1 e % triggers implicit input and reshapes into a 1x1 array. So it leaves input unchanged ``` [Answer] # Pyth, 1 ``` *QhSatan0000 Satan ``` Explanation? ``` n00 - 0 != 0 (0) a 0 - abs(^-0) (0, Required so it doesn't print out a random 0) t - ^-1 (-1, required or will output 0 all the time) a 0 - abs(^-0) (1, Required so counts in right direction, would also print out a random 0) S - 1-indexed range ([1], required so next command works properly) h - Get the head (if `S` missed, will out 2) *Q - Multiply by Q ``` 1, 2, 3, 4, 5... [Sequence A000027](https://oeis.org/A000027) Subliminal messages? Never. [Try it here.](http://pyth.herokuapp.com/?code=*QhSatan0000&input=3&debug=0) [Answer] # Japt, -6 ``` NuLLIFIED)r^ ``` Outputs [A004453](http://oeis.org/A004453): nimsum of N and 12 (N XOR 12). [Test it online!](http://ethproductions.github.io/japt?v=master&code=TnVMTElGSUVEKXJe&input=MQ==) Note: the OEIS sequence is 0-indexed, so an input of 0 will result in the first item. ### How it works ``` // Implicit: N = array of inputs Nu // Push the following things to N: LLIF // 100, 100, 64, 15, IED // 64 again, 14, and 13. )r^ // Reduce by XORing (using ^ between each pair) // The reduction goes as follows: U, U^100, U, U^64, U^79, U^15, U^1, U^12. ``` [Answer] # [Headsecks](https://esolangs.org/wiki/Headsecks), score −4 ``` exit ``` This maps to the Brainfuck program `,+-.`, which reads a single character and prints it, calculating [A000030](https://oeis.org/A000030). Removing any character will obviously break it. There's also `marshal` (`,-<>+-.`), which is effectively `,-.`, but that doesn't correspond to any OEIS sequence. [Answer] # x86 machine code, score -4 Hexdump of the code: ``` 53 51 55 41 53 68 69 65 73 74 51 58 83 c4 14 c3 ``` Or, in [code page 437](https://en.wikipedia.org/wiki/Code_page_437): ``` SQUAShiestQXâ─¶├ ``` Assembly code: ``` push ebx push ecx push ebp inc ecx push ebx push 0x74736569 push ecx pop eax add esp, 0x14 ret ``` A function that [adds 1 to its argument](https://oeis.org/A020725). Removing `A` turns it into an identity function. Removing any other byte messes up the stack, causing either a crash or bad behavior of the calling function. I am pretty sure it's possible to improve the score, but it may depend on the interpretation of the requirements. For example, using the word `SQUEAMIShness` gives a program, that increases and then decreases the `ebp` register. Does removing any of these cause a crash? A simplest test program doesn't use the `ebp` register, so maybe it doesn't... To avoid this doubt, I used a shorter word. [Answer] # Ruby, score 3 ``` puts gets.partition'' ``` This computes the [identity sequence A000027](https://oeis.org/A000027). Output is surrounded by some whitespace; I hope that's okay. [Answer] # Math++, score -2 ``` ?*sine ``` Implements [A000004](https://oeis.org/A000004). ]
[Question] [ You have played \$N\$ matches in some game where each match can only result in one of the two outcomes: win or loss. Currently, you have \$W\$ wins. You want to have a win percentage of \$P\$ or more, **playing as few matches as possible**. Output the minimum win streak that you need. Assume the current win streak is at \$0\$. For example: If \$N=10, W=2, P=50\$, then you can win \$6\$ matches in a row, bringing your win percentage to \$\frac{2+6}{10+6} = \frac{8}{16} = 50\%\$. You cannot have a win percentage of \$50\$ or more earlier than this. So the answer for this case is \$6\$. # Examples ``` W, N, P -> 2, 10, 50% -> 6 3, 15, 50% -> 9 35, 48, 0.75 -> 4 19, 21, 0.91 -> 2 9, 10, 50% -> 0 0, 1, 1/100 -> 1 43, 281, 24/100 -> 33 0, 6, 52% -> 7 ``` # Rules * \$N\$ and \$W\$ will be integers with \$0 \le W < N\$. * The percentage \$P\$ will be an integer between \$1\$ and \$100\$ inclusive. You can also choose to take a decimal value between \$0\$ and \$1\$ inclusive instead, which will contain no more than \$2\$ decimal places, or take it as a fraction. * You can take the inputs in any convenient format. * Standard loopholes are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), 35 bytes ``` lambda w,n,p:-min(0,(w-p*n)//(1-p)) ``` [Try it online!](https://tio.run/##bc7BCsIwDMbxu0/RYyLp1mSdroJv4mUiw4GrRQZjT1@7glDR648/XxLW@f70TRzOl/jop@utVwt5Cic9jR4MwaLD3mNdA@uAGMNr9DMMIKTYkDJVi7j7YJOw/cEkttv0WDI7UsIbOy7Y/dtNkEtTljZdky672O/4kAckvfsG "Python 3 – Try It Online") -4 bytes thanks to pajonk Some simple math: if \$X\$ is the number of wins we need, then we have: \$\frac{W+X}{N+X}\geq P\$ \$W+X\geq PN+PX\$ \$X-PX\geq PN-W\$ \$X(1-P)\geq PN-W\$ Since \$P<1\$, then \$1-P>0\$, so we can divide from both sides without division by zero or flipping the sign. \$X\geq\frac{PN-W}{1-P}\$ [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ ~~15~~ 11 bytes ``` ∞<.Δ¹+.«/²@ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8G71zUw7t1NY7tFr/0CaH//@jjXQUDA1iuQz0TAE "05AB1E – Try It Online") Why aren't I using Vyxal? Because I'm leaving the chance for others so they can claim the bounty. *+2 due to bug fix :(* *but -4 thanks to @ovs* ## Explained (old) ``` ∞0š.ΔD²+s¹+s/³@ ∞0š.Δ # get the first integer n where: D²+s¹+s/ # (wins + n) / (matches + n) ³@ # >= percentage ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Ḣ_Ḣ×$÷’Ċ»0 ``` [Try it online!](https://tio.run/##y0rNyan8///hjkXxQHx4usrh7Y8aZh7pOrTb4P/h9kdNa/7/jzbSUTA00FEw0DON1VGINgbyTBE8INPEAsQ1B/MNLXUUjAxBfEtDEN8SRS@QBZYzAMuZAI0ysgALGJlApc3Aao1iAQ "Jelly – Try It Online") ## Explanation This uses the same formula as my [Python answer](https://codegolf.stackexchange.com/a/224352): \$X\geq\frac{W-PN}{P-1}\$ Takes the input as a list of three numbers, \$W,N,P\$. ``` Ḣ_Ḣ×$÷’Ċ»0 Main Link Ḣ W (pops from the list) _ minus Ḣ×$ N (pops from the list) times the list (now only has P) ÷’ divided by (P - 1) Ċ ceiling »0 maximum of that and 0 ``` ## In-depth explanation This is an even more in-depth explanation of this answer. If you are familiar with Jelly, you should probably skip this. I won't do these often. Since this link is called with one argument each time, it is a monadic chain. Hence, as we walk down the chain, the following patterns are matched in this order: `dyad-monad`, `dyad-nilad`, `nilad-dyad`, `dyad`, and `monad` (nilads take 0 arguments; you can think of them as constants) (monads take 1 argument) (dyads take 2 arguments). Since the link doesn't start with a nilad, the evaluation value starts equal to the argument, `[W, N, P]`. First, we see `Ḣ`, a monad meaning "pop and return the first element". This matches the last rule, so it applies as a monad to the current value, which is `[W, N, P]`. Thus, the current value is now `W`, and this also modifies the left argument object itself to `[N, P]`. Here, it is important to note the function of `$` - it takes the last two links and groups them into a monadic link. Here, the two links are `Ḣ` and `×`. We'll get back to this. Next, we see `_`, a dyad (subtraction). It is followed by a monad, namely the one formed by the `$` grouping two links, thus matching the first pattern. The dyad-monad pattern, if we have some dyad `+` and some monad `F`, computes `v + F(a)` where `v` is the current value and `a` is the right argument. Thus, this computes `W - F([N, P])`. Here, `F(a)` computes `Ḣ×` as a monadic chain whose argument is `a = [N, P]`. The value starts at `v = [N, P]` as well. The first link is a monad and thus the value becomes `N`. Also, since "pop" mutates, the argument (to both the sub-link and the main link) is now `[P]`. Then, the second link is a dyad and nothing else follows, so the value becomes `N × [P]` which is `[NP]`. This is a singleton list, not a value, but that's fine because everything else vectorizes. Now, the value is `W - [NP]` which vectorizes to `[W - NP]`, and the argumnt is `[P]` since it was mutated within the sub-link. `÷’` is a dyad-monad chain, which computes `[W - NP] ÷ P÷’`. `’` decrements, so this computes `[W - NP] ÷ (P - 1)`, which vectorizes to `[(W - NP) / (P - 1)]`. Penultimately, `Ċ` is a monad meaning "ceiling", which just rounds all of these values up. Finally, `»0` is a dyad-nilad chain which takes the maximum of this value and 0, thus preventing negative outputs. Here's a shitty hand-drawn visualization of how chaining works out here: [![enter image description here](https://i.stack.imgur.com/dMRLD.png)](https://i.stack.imgur.com/dMRLD.png) [Answer] # [R](https://www.r-project.org/), ~~45~~ ~~43~~ ~~42~~ 38 bytes *Edit: simultaneous discovery of -1 byte by Kirill L., and then -4 bytes thanks to pajonk* ``` function(W,N,P)-min((W-P*N)%/%(1-P),0) ``` [Try it online!](https://tio.run/##dc/RCoIwFAbge5/iQAhbnNk2N3UX9QjinZcSuWJEC8zo8W12I5I719//859h@jjvnb91r3Gw53vnre1tf5yub38Z3dOTFmtsKHs4T0jLmn1N00NKBGsocrqdJhJBcIRMw@8o7ICdoEi2dR60/tMmpgNVFQLPSr1oFdHCIEgxayMWLSPabO7mER1kaM64WGkR0Sq8Kas5INWi8zxeXsxL5Kq8TJLpCw "R – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 44 bytes Every answer of [Wasif](https://codegolf.stackexchange.com/a/224354/80745) inspires me to make the right one. Thanks. ``` param($w,$n,$p)for(;$w++/$n++-lt$p){$k++}+$k ``` [Try it online!](https://tio.run/##ZZDNTsMwEITvfoo9GJTILo3z0zZCSJV4ABA9ogqFsKXQ/BE7ClLJs4d1khYQe7K/2ZmRtipbrPUes6znO7iBY18ldZI7vJW8kLxyd2XtXPNWiDkvhJhlhtiRH4ToBD/0HWNrhzHp@BKUJ8G7imAcCQuXeEA8@svjgRMMV1ZYRhMPLVexBF9ZHquJ@5bH//M9y4nRtqPmyvPckSvLQyr2V1byw0GTEASTYUE08k8OCUuXMRe@4AKOzEbw9q3QEniemHSP9lVhnWJhklekD35WmBp8oWvxp9FQo24yQ@CSjjjYz@7f5mH58X5z22hT5nfP75SzXY@ldjZNmqLWNnhKnOHHT@F57@FUN60NQse6/hs "PowerShell – Try It Online") [Answer] # [Clojure](https://clojure.org/), 39 bytes ``` #(max(Math/ceil(/(-(* %2%)%3)(- 1%)))0) ``` [Try it online!](https://tio.run/##Tc5BDoIwEAXQfU8xiWkyNSBtAYVDeIKmCwIlaipgQYOnry0mxt1/@TOTae14ezrjsTM99H6H92bFc7NcstZcLWaY4h6opIzmDFMQlDHGmWcEu3E2D1CwKqJkAoInwA@lJioPKH8IqaiiTpGiTkCKyFoE1v97IWwNj00Rrshqsyy@5XEblJpoTXBy12GxA2AzTfYNPaAzL@NmA2v4kPkP "Clojure – Try It Online") Takes arguments in reverse order compared to the provided test cases (\$P, N, W\$). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 0+÷/:⁴ʋ1# ``` [Try it online!](https://tio.run/##y0rNyan8/99A@/B2fatHjVtOdRsq////30hHwdDgv4GeKQA "Jelly – Try It Online") Full program that takes `[w, n]` on the left and `P` on the right. ## How it works ``` 0+÷/:⁴ʋ1# - Main link. Takes [w, n] on the left and P on the right ʋ - Previous 4 links as a dyad f(x, [w, n]): + - Yield [w+x, n+x] ÷/ - Yield (w+x)÷(n+x) ⁴ - Yield P : - Floor divide (w+x)÷(n+x) by P, returning 0 if P < (w+x)÷(n+x), and 1 otherwise 0 1# - Count up x = 0, 1, 2, ..., and find the first x such that f(x, [w, n]) is 1 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 51 bytes ``` param($w,$n,$p)while(($w+$k)/($n+$k)-lt$p){$k+=1}$k ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQ6VcRyVPR6VAszwjMydVA8jXVsnW1NdQyQPRujklQKlqlWxtW8Nalez///8b/Tc0@G@gZwoA "PowerShell – Try It Online") What? It beat my python answer? oO [Answer] # [Ruby](https://www.ruby-lang.org/), 34 bytes ``` ->w,n,p{[0,-(w-p*n).div(1-p)].max} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf165cJ0@noDraQEdXo1y3QCtPUy8ls0zDULdAM1YvN7Gi9n@BQlq0kY6CoYGOgoGeaSwXiG8M5Jsi84EcEwuQgDlUxNBSR8HIECRiaQgRsUQzA8gGyxtA5U2AhhpZgIWMTOBKzMA6jGL/AwA "Ruby – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` \d+ $* \G1 100$* 1(?=1*,(1*)%) $1 +`^(1*,)(1+\1(1+)) 100$*1$1$3$2_ _ ``` [Try it online!](https://tio.run/##NYo7DsIwFAT7dw4/yXa28PoDcYEocwmLBAkKGgqU@xujiGY1s5rPc3@9713tsvX2mMR4aQuFIQyivV7oYemdOjGUabsNgbOcGsc4d5Q0NMnEVdbeIxhQgkoCywEFeca5qLAiEpUq9V8FEMNzQpyJmH/PCSXqFw "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `P` as a percentage (including `%` sign). Explanation: ``` \d+ $* ``` Convert `W`, `N` and `P` to unary. ``` \G1 100$* ``` Multiply `W` by `100`. ``` 1(?=1*,(1*)%) $1 ``` Multiply `N` by `P`. ``` +`^(1*,)(1+\1(1+)) ``` While `100W<NP`... ``` 100$*1$1$3$2_ ``` increment `W` and `N`, i.e. add `100` to `100W` and `P` to `NP`. ``` _ ``` Count the number of increments made. [Answer] # JavaScript, ~~44~~ ~~40~~ 34 bytes ``` f=(w,n,p)=>w/n>=p?0:f(w+1,n+1,p)+1 ``` Takes all three parameters as integers except `p` which is a decimal. *-4 bytes, thanks to @DominicvanEssen* *-6 bytes, thanks to @Arnauld* [Try it online](https://tio.run/##DcNRCoAgDADQ60xcpkE/gXUWMY1CtpGRx7cevCu8ocb7lGcg3lPv2UNDQlF@bSOtXja7ZGjaIf1FadcjU@WSTOEDMkzoLJpZqf4B) [Answer] # [Haskell](https://www.haskell.org/), 37 bytes ``` (n,w)#p|100*w<p*n=1+(n+1,w+1)#p|1>0=0 ``` [Try it online!](https://tio.run/##RdBLCsIwEAbgvacY6iYxIyZtfVSMJ1ARXLioIl0UFGsMtZKNd68ToxYSkv9jZgg5F49rWVVtyww63rcvJeXALezAaCWYEQqdUB9fSi3bW3ExoOFW2PUJ7LPZNfXKQB7t5xAJ8TjfHTghIsBNB4YAYduB9RV6@c@1z6NfZLXWJSc6mOjFHBq0WPLFMO8BsBhBSYQx7QlHLwnJOEj2FYrpDGHqz0AqQ4gVVdCOA2XdJBmEbiqskFMaHc98R4qQJP@iCXXRO6b8iFXZQK2/X3ds3w "Haskell – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes ``` f(W,N,P)=-min(-(P*N-W)\(1-P),0) ``` [Try it online!](https://tio.run/##TcwxDsMgDEDRPSexK4OwgSQMXCFiy9KlSyqGRijq/SlR1ZL16euXx5HVs9S6wUoLJYzqlXdQkG6LWvEOrBKSwVqOvL9hAyE2pD3GOOLwQ0vsvxgu6MnNpKeTXWcOJEw6cGPpHP5f09FQK81ZckdnSebm4ppbe63HdpCmEw71Aw "Pari/GP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` f=lambda w,n,p,c=0:(w+c)/(n+c)>=p and c or f(w,n,p,c+1) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoVwnT6dAJ9nWwEqjXDtZU18jD0ja2RYoJOalKCQr5BcppGlA1Wgbav4vKMrMK9FI0zDSMTTQ0TPV1PwPAA "Python 3 – Try It Online") Simple recursion, I am beaten by few minutes.... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` NθNηNζ≔⁰εW‹⁺θε×ζ⁺ηε≦⊕εIε ``` [Try it online!](https://tio.run/##XYxBCsIwFET3OUWWX4hS0KLQlXRVUOnCC8T4MYEktvmJQi8fU3Uhzu49ZkZpGdRd2pw7P6R4Su6CAcZFw35Z//FUeE9kbh4qwbHQUxuLHA5IBL1NBOPsBT8bhwST4G@pZ1nCj3L47juvAjr0Ea@fpz4YH6GVFKF0m5zXNdvsWLXa1nn5sC8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` NθNηNζ ``` Input `W`, `N` and `P`. ``` ≔⁰ε ``` Start with `X=0`. ``` W‹⁺θε×ζ⁺ηε ``` Until we reach the desired win percentage... ``` ≦⊕ε ``` ... increment `X`. ``` Iε ``` Output `X`. A port of @hyper-neutrino's solutions is of course much shorter at 13 bytes: ``` I⌈⟦⁰±÷⁻×NNN⊖θ ``` [Try it online!](https://tio.run/##bcixCsJADADQvV/RMYEqhVoUHO3i0NLBTRzOa9BAc@pdrvj30VVwfM/fXfQPN5uNkYPCwSWF3r1ZssC5rsqBbk4JjkE7Xngi6DnkBCcWSt99Zh2yXCkCVuUP/7gjH0koKE3wQrwg4t6sXm/bYrMrmtZWy/wB "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `P`, `N`, `W`. Explanation: ``` N `P` as a number × Multiplied by N `N` as a number ⁻ Subtract N `W` as a number ÷ Floor divided by ⊖θ `P` decremented ± Negated ⌈⟦⁰ Maximum of that and 0 I Cast to string Implicitly print ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` @°*L¨V°*W}a ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLAqTKhWsCpXfWE&input=MgoxMAo1MA) [Answer] # [CSASM v2.4.0.1](https://github.com/absoluteAquarian/CSASM/releases/tag/v2.4.0.1), 123 bytes A function which pops three values from the stack (`[N, W, P]`) and pushes the result as an `f64`. The function expects the types of all three values to be `f64`. ``` .include <stdmath> func a: pop $3 pop $2 pop $1 push $3 dup push $2 swap push $1 mul sub neg swap push 1.0 sub div neg push 0.0 call max ret end ``` **Explanation + Full Program:** ``` .include <stdmath> func main: ; Get the three inputs in "N: " conv f64 in "W: " conv f64 in "P: " conv f64 call a ; Truncate the result and print it conv i32 push "Wins needed: " swap add print.n ret end func a: pop $3 ; P pop $2 ; W pop $1 ; N push $3 ; [ P ] dup ; [ P, P ] push $2 ; [ P, P, W ] swap ; [ P, W, P ] push $1 ; [ P, W, P, N ] mul ; [ P, W, P*N ] sub ; [ P, W-P*N ] neg ; [ P, P*N-W ] swap ; [ P*N-W, P ] push 1.0 ; [ P*N-W, P, 1 ] sub ; [ P*N-W, P-1 ] div ; [ (P*N-W)/(P-1) ] neg ; [ -(P*N-W)/(P-1) ] push 0.0 call max ret end ``` ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` 0//.x_/;x+#-##2<x#3:>x+1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b730BfX68iXt@6QltZV1nZyKZC2djKrkLbUO1/QFFmXkm0sq5dmoODcqxaXXByYl5dNVe1gpGOgqGBjoKeaa0OkGcM5JnCeMZAlokFkGcO5hpa6igYGQK5loZgtZYoOoEsBZCkAVjSxFjHyALENTKBy5qB1BrVctX@BwA "Wolfram Language (Mathematica) – Try It Online") We can also directly compute the number of needed wins: ### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` ⌈Min[#-##2,0]/--+#3⌉& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7/1FPh29mXrSyrrKykY5BrL6urray8aOeTrX/AUWZeSVACbs0BwflWLW64OTEvLpqrmoFIx0FQwMdBT3TWh0gzxjIM4XxjIEsEwsgzxzMNbTUUTAyBHItDcFqLVF0AlkKIEkDsKSJsY6RBYhrZAKXNQOpNarlqv0PAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Takes `P` as a decimal. ``` @°/V°<W}f ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLAvVrA8V31m&input=NDMgMjgxIC4yNA) [Answer] # JavaScript, 28 bytes Takes `P` as a decimal and outputs `false` for `0`. ``` w=>n=>g=p=>w++/n++<p&&g(p)+1 ``` [Try it online!](https://tio.run/##bc3BCsIwDIDhuw8yEoq6xk5bMH2XIWzMQwlzbI9f04NQx475@JO8@7X/vOZJlvPq88B545g4jiwcN2OuyZinNM0IgsZmmae0wACEYFuES4d4@tlNrdubgvOKj1ptQCCrGmyl4eCmzqVr687pI/KFyf2n97JNiPkL) [Answer] # [Vyxal 2.4.1](https://github.com/Lyxal/Vyxal), 8 bytes ``` λ¹+ɖ⁰≥;ṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=5&code=%CE%BB%C2%B9%2B%C9%96%E2%81%B0%E2%89%A5%3B%E1%B9%85&inputs=%5B2%2C%2010%5D%0A0.5&header=&footer=) Here's what I managed to come up with. It doesn't seem like anyone else is going to give this a go using Vyxal, so here's my solution. ## Explained ``` λ¹+ɖ⁰≥;ṅ λ # start a lambda that, given a single argument "n": ¹+ # adds n to the list [wins, matches] ɖ # reduces that list by division ⁰≥; # and returns whether that number is greater than the percentage ṅ # take that lambda, and find the first integer (starting at 0) where it evaluates as truthy ``` ]
[Question] [ The title is valid Jelly Code which has the same output as `L€€` except printed twice. ### Background You can skip this section without losing ability to complete the challenge Some operations in Jelly try to convert its argument to a list first before applying the operation. One example is `€`, the mapping quick. This sometimes leads to unintended output. For the program `L€` and input 5, the Jelly interpreter tries to find the length of every element of the list 5. Since 5 is not a list, Jelly converts it to the list [1,2,3,4,5]. Then the length of every element is output: `[1,1,1,1,1]`. Note that every integer has length `1`. If e.g. `10` was present, it would become `1`, not `2` (the length in digits). For the program `L€€` and input 5, the Jelly interpreter tries to find the length of every element of every element of the list 5. Since 5 is not a list, Jelly converts it to the list `[1,2,3,4,5]`. Now the interpreter tries to find the length of every element of every element of the list `[1,2,3,4,5]`. Every element is not a list, so Jelly converts them to lists in the same manner: `[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]`. The length of every sub-element is output as `[[1],[1,1],[1,1,1],[1,1,1,1],[1,1,1,1,1]]` ### Task Your task is to find the output of the Jelly program `L` followed by `€` repeated `a` times, with input `b`, where `a` and `b` are positive integers equal to your program/function's inputs. A way to do this is: Starting with the input `b`, do the following `a` times: * For every integer that the program sees, replace it with the range of the integer (where `range(x) := [1,2,3,...,x-1,x]`) Finally, replace every integer with 1. ### Test Cases ``` a b output - - - - - 1 1 [1] - - - - - 1 2 [1, 1] - - - - - 1 3 [1, 1, 1] - - - - - 1 4 [1, 1, 1, 1] - - - - - 1 5 [1, 1, 1, 1, 1] - - - - - 1 6 [1, 1, 1, 1, 1, 1] - - - - - 2 1 [[1]] - - - - - 2 2 [[1], [1, 1]] - - - - - 2 3 [[1], [1, 1], [1, 1, 1]] - - - - - 2 4 [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]] - - - - - 2 5 [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]] - - - - - 2 6 [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]] - - - - - 3 1 [[[1]]] - - - - - 3 2 [[[1]], [[1], [1, 1]]] - - - - - 3 3 [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]] - - - - - 3 4 [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]] - - - - - 3 5 [[[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]]] - - - - - 3 6 [[[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]]] - - - - - 4 1 [[[[1]]]] - - - - - 4 2 [[[[1]]], [[[1]], [[1], [1, 1]]]] - - - - - 4 3 [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]] - - - - - 4 4 [[[[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]]]] - - - - - 4 5 [[[[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]]]] - - - - - 4 6 [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 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]]]] - - - - - 5 1 [[[[[1]]]]] - - - - - 5 2 [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]] - - - - - 5 3 [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]] - - - - - 5 4 [[[[[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]]]]] - - - - - 5 5 [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [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]]]]] - - - - - 5 6 [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]], [[[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]]]]] - - - - - 6 1 [[[[[[1]]]]]] - - - - - 6 2 [[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]]] - - - - - 6 3 [[[[[[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]]]]]] - - - - - 6 4 [[[[[[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]]]]]] - - - - - 6 5 [[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]]] - - - - - 6 6 [[[[[[1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]]], [[[[[1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]], [[[[1]]], [[[1]], [[1], [1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]]], [[[1]], [[1], [1, 1]], [[1], [1, 1], [1, 1, 1]], [[1], [1, 1], [1, 1, 1], [1, 1, 1, 1]], [[1], [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]]]]]] ``` ### Rules * `a` and `b` are restricted to positive integers * Your program or function may take `a` and `b` in any order and in any standard input format * The output should be a depth-a list or string representation of such a list * The output should be returned through any standard output format. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code **in each language** wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` R¡Ṡ ``` [Try it online!](https://tio.run/##ARoA5f9qZWxsef//UsKh4bmg/8OHxZLhuZj//zP/Mg "Jelly – Try It Online") Takes input in reverse order. -2 bytes thanks to fireflame. -1 byte thanks to Dennis # Explanation ``` R¡Ṡ Main link ¡ Repeat <first argument> times R Range (generates range, and vectorizes on lists) Ṡ Sign (converts all numbers to 1 because they are all positive) ``` [Answer] # [Python 2](https://docs.python.org/2/), 49 bytes -1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) ``` f=lambda a,b:1>>a or[0]*b and f(a,b-1)+[f(a-1,b)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVEnycrQzi5RIb8o2iBWK0khMS9FIU0DKKxrqKkdDWTpGuokacb@T8svUkhUyMxTKErMS0/VMNQx17Ti4gSJJmGIchYUZeaVKCTCWUlwFthoTThXXVcBCtX/AwA "Python 2 – Try It Online") This problem seemed like it could be written in the form of a doubly recursive function, subtracting one from each parameter. The key idea is that the sequence can be related as follows: ``` f(0,b) = 1 f(a,0) = [] f(a,b) = f(a,b-1) + [f(a-1,b)] ``` However writing a recursive function like this is pretty tricky, since `1` is a truthy value and `[]` is a falsy value, so we need two short-circuiting keywords (`and` and `or`). A less golfed version might look like: ``` lambda a,b:int(a<1)or[1,[]][b<1]and f(a,b-1)+[f(a-1,b)] ``` However we can use the trick that `1>>a` gives `1` if a is zero, and `0` otherwise, and that we can return a truthy value if `b>0` and an empty list otherwise by doing `[0]*b`. [Answer] # Mathematica, 17 bytes ``` 1^Range~Nest~##& ``` Takes `b` then `a`. [Try it on Wolfram Sandbox](https://sandbox.open.wolframcloud.com/) ### How? ``` 1^Range~Nest~##& Range (* Range function; generates {1..<input>} *) ~Nest~## (* Apply it on <input 1> <input 2> times *) (* Mathematica automatically maps Range onto integers *) 1^ (* Raise those to the exponent of 1; make everything 1 *) ``` ### Usage ``` 1^Range~Nest~##&[4, 2] ``` > > `{{1}, {1, 1}, {1, 1, 1}, {1, 1, 1, 1}}` > > > [Answer] # [Gaia](https://github.com/splcurran/Gaia), 7 bytes ``` ẏ¦”@)⊃e ``` [Try it online!](https://tio.run/##S0/MTPz//@Gu/kPLHjXMddB81NWc@v@/MZcJAA "Gaia – Try It Online") `ẏ¦` does just about the same thing here as `L€` in Jelly. `ẏ` is "is positive?" and `¦` is map, which also implicitly casts an integer to the range 1 .. n before mapping. And since we're dealing with only integers >= 1, `ẏ` will result in `1` for each. ``` ẏ¦” Push the string "ẏ¦" @) Push the first input+1 ⊃ Repeat the last character of the string until it's input+1 characters long. e Eval it. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~57~~ 55 bytes -1 byte thanks to Jakob -1 byte thanks to notjagan ``` f=lambda a,b:[1]*b*(a<2)or[f(a-1,i+1)for i in range(b)] ``` [Try it online!](https://tio.run/##BcExDoAgDADAr3SkiAO4GX0JYShRtIkWQlh8fb1r37irBNWyP/Tmg4BcXqNPNltDW8DaYzE0e8eTx1I7MLBAJ7lOkzFp6ywDillcQP0B "Python 2 – Try It Online") [Answer] # PHP, 134 bytes ``` for($r=[$argv[2]];$argv[1]--;)($w=array_walk_recursive)($r,function(&$n){$n=range(1,$n);});$w($r,function(&$n){$n=1;});print_r($r[0]); ``` There may be a shorter approach than the literal one ... but it´s working at least. Run with `-nr` and provide `a` and `b` as arguments or [try it online](http://sandbox.onlinephpfunctions.com/code/0a829eba8eb5496e2171da45150dd2b59f749a0c). --- For output as in the examples, use `echo strtr(preg_replace('#"\d":#','',json_encode($r[0],JSON_NUMERIC_CHECK)),"{}","[]");` (as I do in the TiO) instead of `print_r($r[0]);`. [Answer] ## JavaScript (ES6), 95 bytes ``` f=(a,b,r=/\d+/g)=>a--?f(a,b.replace(r,s=>`[${[...Array(+s)].map((_,i)=>++i)}]`)):b.replace(r,1) ``` ``` <div oninput=o.textContent=f(a.value,b.value)><input type=number min=0 value=0 id=a><input type=number min=0 value=0 id=b><pre wrap id=o>1 ``` I/O is with strings. The best I could do nonrecursively was 100 bytes: ``` (a,b)=>[...Array(-~a)].reduce(r=>r.replace(/\d+/g,a--?s=>`[${[...Array(+s)].map((_,i)=>++i)}]`:1),b) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` ,1{t+₁I&⟦₁ᵐ⁾;I}ⁱ⁽ṡᵐ⁾c ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X8ewukT7UVOjp9qj@cuA9MOtEx417rP2rH3UuPFR496HOxdCRJL//4820VEwjv0fBQA "Brachylog – Try It Online") Conceptually simple, but keeping track of the right level to map the 'range' `⟦` predicate at, takes up almost half the bytes. :( ``` % Implicit input, list [a, b] ,1 % Append iteration index 1 to the list { }ⁱ⁽ % Do this iteratively a times, with [b, i] as the initial input t+₁I % Increment iteration index, let this be I &⟦₁ᵐ⁾ % Map the "range from 1 to input" predicate on the first part of input % (b in the first iteration), at depth given by (old) iteration index ;I % Append the incremented index to this, this is the input to next iteration ṡᵐ⁾ % Take the sign of each element, mapped at depth given by final I c % "Concatenate" to remove extra surrounding array ``` And a recursive solution, just for the heck of it: ### 24 bytes ``` {t0&hṡᵐ|t-₁L&h⟦₁ᵐ;Lz↰ᵐ}c ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7rEQC3j4c6FD7dOqCnRfdTU6KOW8Wj@MiADKGLtU/WobQOQUZv8/3@0iY6Ccez/KAA "Brachylog – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ⁴Ṿ;”L;”€ẋ³¤V ``` [Try it online!](https://tio.run/##y0rNyan8//9R45aHO/dZP2qY6wMiHjWtebir@9DmQ0vC/v//b/TfGAA "Jelly – Try It Online") Just to get things started. I'm pretty sure it would be shorter if I actually did it the way I'm supposed to, so I'm working on that (inb4 ninja'd by someone) # Explanation ``` ⁴Ṿ;”L;”€ẋ³¤V Main link Ṿ Generate Jelly code that will evaluate to ⁴ The second input ; Concatenate with ”L "L" ; Concatenate with ”€ẋ³¤ Niladic Expression ”€ "€" ẋ Repeated times ³ <first input> V Jelly-eval it ``` ]
[Question] [ [Kirchhoff's law](https://en.wikipedia.org/wiki/Kirchhoff%27s_circuit_laws#) says that when you sum up all the currents (positive for the currents going to a junction, and negative for current leaving a junction), you will always get as result 0. Look at the following diagram: [![enter image description here](https://i.stack.imgur.com/dDsXa.png)](https://i.stack.imgur.com/dDsXa.png) Using Kirchhoff's law, you can see that i1 + i4 - i2 - i3 = 0, so i1 + i4 = i2 + i3. Given two lists, one with all the currents entering the junction and one with all the currents leaving the junction except one, output the last one. Testcases: ``` [1, 2, 3], [1, 2] = 3 [4, 5, 6], [7, 8] = 0 [5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1] = 6 ``` The second list always has one item less than the first list. The output cannot be negative. Smallest program wins. [Answer] # Jelly, 2 bytes ``` _S ``` [Try it here!](http://jelly.tryitonline.net/#code=X1M&input=&args=NSw3LDMsNCw1LDI+OCw0LDUsMiwx) Takes the entering currents in the first argument, and the leaving currents in the second argument. `_` subtracts them pairwise, leaving the single element from the longer list as-is, and `S` sums the result. [Answer] ## Haskell, 14 bytes ``` (.sum).(-).sum ``` Usage example: `( (.sum).(-).sum ) [5,7,3,4,5,2] [8,4,5,2,1]` -> `6`. Sum each list and take the difference. [Answer] ## CJam, ~~8~~ 6 bytes ``` q~.-:+ ``` Input uses two CJam-style arrays. [Run all test cases.](http://cjam.aditsu.net/#code=qN%2F%7B%22%20%3D%20%22%2F0%3D%3AQ%3B%0A%0AQ~.-%3A%2B%0A%0A%5DoNo%7D%2F&input=%5B1%202%203%5D%20%5B1%202%5D%20%3D%203%0A%5B4%205%206%5D%20%5B7%208%5D%20%3D%200%0A%5B5%207%203%204%205%202%5D%20%5B8%204%205%202%201%5D%20%3D%206) (This reads multiple test cases at once and includes a framework to process each line individually, discarding the expected result from the input.) ### Explanation ``` q~ e# Read and evaluate input. .- e# Elementwise difference. :+ e# Get sum. ``` `.-` works reliably because we're guaranteed that the first list is always longer than the second. (Otherwise, the extraneous elements of the second list would be appended to the result which would add them to the sum instead of subtracting them.) [Answer] # [MATL](https://esolangs.org/wiki/MATL), 3 ~~4.0~~ bytes ``` _hs ``` Inputs are: leaving currents first, then entering currents. [**Try it online!**](http://matl.tryitonline.net/#code=X2hz&input=WzgsIDQsIDUsIDIsIDFdIApbNSwgNywgMywgNCwgNSwgMl0K) ``` _ % implicitly input array with leaving currents (except one). Negate h % implicitly input array with entering currents. Concatenate s % sum of all elements in concatenated array ``` [Answer] # Javascript, 36 bytes ``` (a,b)=>eval(a.join`+`+'-'+b.join`-`) ``` ``` f= (a,b)=> eval( a.join`+` +'-'+ b.join`-` ) document.body.innerHTML = '<pre>' + 'f([1,2,3],[1,2]) = ' + f([1,2,3],[1,2]) + '\n' + 'f([4,5,6],[7,8]) = ' + f([4,5,6],[7,8]) + '\n' + 'f([5,7,3,4,5,2],[8,4,5,2,1]) = ' + f([5,7,3,4,5,2],[8,4,5,2,1]) + '\n' + '</pre>' ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes Code: ``` OEO- ``` Explanation: ``` O # Take the sum of the input list E # Evaluate input O # Take the sum of the input list - # Substract from each other ``` --- Thanks to **Luis Mendo** for reminding me that I need to implement a concatenate function. If I've had implemented it sooner, it would have been 3 bytes: **Non-competing version (3 bytes):** The first list is the leaving current list, the second is the entering current list. Code: ``` («O ``` Explanation: ``` ( # Negate the list, e.g. [3, 4, 5] would become [-3, -4, -5] « # Concatenate the second list to the first O # Take the sum and implicitly output it ``` Uses CP-1252 encoding. [Answer] # Mathematica, ~~17~~ 11 bytes ``` Tr@#-Tr@#2& ``` Quite simple. [Answer] ## Common Lisp, 40 ``` (lambda(x y)(-(reduce'+ x)(reduce'+ y))) ``` [Answer] # [Perl 6](http://perl6.org), 11 bytes ``` *.sum-*.sum ``` ### Usage: ``` # give it a lexical name my &code = *.sum-*.sum; say code [1, 2, 3], [1, 2]; # 3 say code [4, 5, 6], [7, 8]; # 0 say code [5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1]; # 6 ``` [Answer] # Python 3, 24 bytes ``` lambda a,b:sum(a)-sum(b) ``` or # Python 2, 19 bytes ``` print sum(a)-sum(b) ``` depending if I am required to print the result or just create a function that returns it. [Answer] ## ES6, 39 bytes ``` (i,o)=>i.reduceRight((r,a,j)=>r+a-o[j]) ``` Because I wanted to use `reduceRight`. [Answer] # Python 2, 30 bytes ``` a,b=map(sum,input());print a-b ``` [Answer] ## Pyth, 6 bytes ``` -.*sRQ ``` Explanation ``` - autoassign Q = eval(input()) sRQ - map(sum, Q) -.* - imp_print(minus(*^)) ``` [Try it here](http://pyth.herokuapp.com/?code=-.*sRQ&input=%5B%5B4%2C+5%2C+6%5D%2C+%5B7%2C+8%5D%5D&debug=0) [Answer] # K5, 5 bytes ``` -/+/' ``` Difference over (`-/`) sum over (`+/`) each (`'`). In action: ``` (-/+/')'((1 2 3;1 2);(4 5 6;7 8);(5 7 3 4 5 2;8 4 5 2 1)) 3 0 6 ``` [Answer] # Pyth, 5 bytes ``` -FsMQ ``` [Try it online.](https://pyth.herokuapp.com/?code=-FsMQ&input=%5B4%2C+5%2C+6%5D%2C+%5B7%2C+8%5D&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=-FsMQ&test_suite=1&test_suite_input=%5B1%2C+2%2C+3%5D%2C+%5B1%2C+2%5D%0A%5B4%2C+5%2C+6%5D%2C+%5B7%2C+8%5D%0A%5B5%2C+7%2C+3%2C+4%2C+5%2C+2%5D%2C+%5B8%2C+4%2C+5%2C+2%2C+1%5D&debug=0) `M`ap `s`um on both input lists, then `F`old subtraction (`-`). This could also be written as `-sQsE`, which takes the lists on two lines. [Answer] # 𝔼𝕊𝕄𝕚𝕟, 5 chars / 7 bytes ``` ⨭î-⨭í ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=%5B%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%5D%5D&code=%E2%A8%AD%C3%AE-%E2%A8%AD%C3%AD)` Wut. # Explanation `sum(input1) - sum(input2)` [Answer] # Common Lisp REPL, SBCL ~~28~~ 24 bytes write this into REPL: ``` #.`(-(+ #1=,@(read))#1#) ``` then write input lists like this: ``` (2 3 4) (2 3) ``` I hope it's okay to use such list format (instead of e.g. `'(2 3 4)`) I used [coredump's answer](https://codegolf.stackexchange.com/questions/71345/apply-kirchhoffs-law/71420#71420) as formula for my solution and then achieved his calculation effect in a different way. ### Explanation Let `e_1,...,e_n` be elements of the first list and `f_1,...,f_{n-1}` be elements of second list. We want to evaluate expression `(-(+ e_1 e_2 ... e_n)f_1 f_2 ...f_{n-1})` It would mean subtracting elements of second list from sum of elements of first list. The needed expression is constructed like so: backqoute stops evaluation `#1=` saves a bit of writting, remembering `,@(read)` `,@` stops effects of backquote (so that (read) will be evaluated) and takes elements out of a list. `(read)` asks for input `#1#` "loads" Lisp object saved by `#1=` `#.` does evaluation of printed representation of an Lisp object ]
[Question] [ # Introduction The [Baker's map](http://en.wikipedia.org/wiki/Baker%27s_map) is an important dynamical system that exhibits chaotic behavior. It is a function from the unit square to itself defined intuitively as follows. * Cut the square vertically in half, resulting in two rectangles of size `0.5×1`. * Stack the right half on top of the left, resulting in one rectangle of size `0.5×2` * Compress the rectangle back into a `1×1` square. In this challenge, you'll implement a discrete version of this transformation. # Input and Output Your input is a 2D array of printable ASCII characters and whitespace of size `2m×2n` for some `m, n > 0`. Your output is a similar array obtained as follows, using the `6×4` array ``` ABCDEF GHIJKL MNOPQR STUVWX ``` as an example. First, stack the right half of the array on top of the left half: ``` DEF JKL PQR VWX ABC GHI MNO STU ``` Then, split the columns into pairs of characters, and independently turn each pair 90 degrees clockwise, "compressing" the tall rectangle back to the original shape: ``` JDKELF VPWQXR GAHBIC SMTNUO ``` This is the correct output for the above array. # Rules The input and output formats are flexible. You can use newline-delimited strings, lists of strings, or 2D arrays of characters. However, the input and output **must** have the exact same format: you must be able to iterate your submission an arbitrary number of times on any valid input. You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. # Test Cases ``` Input: 12 34 Output: 42 31 Input: Hell ! o d - lroW Output: lol o W- !H e ldr Input: ABCDEF GHIJKL MNOPQR STUVWX Output: JDKELF VPWQXR GAHBIC SMTNUO Input: *___ ___ o o|__) |__) * *| | o o __ __ * *| | _ o o|__ |__| * Output: |_____) *o |_ _ *o ||_ __| *o o*|_____) o* |_ _ o*||_ _ ``` [Answer] # Pyth, ~~25~~ ~~19~~ 18 bytes ``` msC_dcs_Cmck/lk2Q2 ``` [Online demonstration](https://pyth.herokuapp.com/?code=msC_dcsCm_ck%2Flk2Q2&input=%5B(%27A%27%2C+%27B%27%2C+%27C%27%2C+%27D%27%2C+%27E%27%2C+%27F%27)%2C+(%27G%27%2C+%27H%27%2C+%27I%27%2C+%27J%27%2C+%27K%27%2C+%27L%27)%2C+(%27M%27%2C+%27N%27%2C+%27O%27%2C+%27P%27%2C+%27Q%27%2C+%27R%27)%2C+(%27S%27%2C+%27T%27%2C+%27U%27%2C+%27V%27%2C+%27W%27%2C+%27X%27)%5D&debug=0). It uses an 2D-array of chars. Array of strings is one char longer (19 bytes). [Online demonstration](https://pyth.herokuapp.com/?code=mssC_dcs_Cmck%2Flk2Q2&input=%5B%27ABCDEF%27%2C%20%27GHIJKL%27%2C%20%27MNOPQR%27%2C%20%27STUVWX%27%5D&debug=0) ### Explanation: ``` m Q map each string k in input: /lk2 calculate half the line-length: len(k)/2 ck/lk2 chop k into pieces of length len(k)/2 results in two pieces C zip the resulting list results in a tuple ([first half of strings], [second half of strings]) _ invert the order ([second half of strings], [first half of strings]) s sum (combine the two lists to a big one c 2 chop them into tuples m for each tuple of strings: sC_d invert, zip, and sum ``` The last part is a bit confusing at first. Let's assume we have the tuple `['DEF', 'JKL']` (I use the example from the OP). ``` d (('D', 'E', 'F'), ('J', 'K', 'L')) just the pair of strings _d (('J', 'K', 'L'), ('D', 'E', 'F')) invert the order C_d [('J', 'D'), ('K', 'E'), ('L', 'F')] zipped sC_d ('J', 'D', 'K', 'E', 'L', 'F') sum (combine tuples) ``` [Answer] # Julia, 136 bytes A very straightforward implementation. Not a particularly competitive entry, but it was fun! ``` A->(s=size(A);w=s[2];u=w÷2;C=vcat(A[:,u+1:w],A[:,1:u]);D=cell(s);j=1;for i=1:2:size(C,1) D[j,:]=vec(flipdim(C[i:i+1,:],1));j+=1end;D) ``` This creates a lambda function that accepts a 2-dimensional array as input and returns a transformed 2-dimensional array. Ungolfed + explanation: ``` function f(A) # Determine bounds s = size(A) # Store the array dimensions w = s[2] # Get the number of columns u = w ÷ 2 # Integer division, equivalent to div(w, 2) # Stack the right half of A atop the left C = vcat(A[:, u+1:w], A[:, 1:u]) # Initialize the output array with the appropriate dimensions D = cell(s) # Initialize a row counter for D j = 1 # Loop through all pairs of rows in C for i = 1:2:size(C, 1) # Flip the rows so that each column is a flipped pair # Collapse columns into a vector and store in D D[j, :] = vec(flipdim(C[i:i+1, :], 1)) j += 1 end return D end ``` To call it, give the function a name, e.g. `f=A->(...)`. Example output: ``` julia> A = ["A" "B" "C" "D" "E" "F"; "G" "H" "I" "J" "K" "L"; "M" "N" "O" "P" "Q" "R"; "S" "T" "U" "V" "W" "X"] julia> f(A) 4x6 Array{Any,2}: "J" "D" "K" "E" "L" "F" "V" "P" "W" "Q" "X" "R" "G" "A" "H" "B" "I" "C" "S" "M" "T" "N" "U" "O" julia> B = ["H" "e" "l" "l"; "!" " " " " "o"; "d" " " " " "-"; "l" "r" "o" "W"] julia> f(B) 4x4 Array{Any,2}: " " "l" "o" "l" "o" " " "W" "-" "!" "H" " " "e" "l" "d" "r" " " ``` And proof that it can be arbitrarily chained: ``` julia> f(f(B)) 4x4 Array{Any,2}: "W" "o" "-" "l" "r" " " " " "e" "o" " " " " "l" "l" "!" "d" "H" ``` Suggestions are welcome as always, and I'll happy provide any further explanation. [Answer] # CJam, ~~25~~ 24 bytes ``` qN/_0=,2/f/z~\+2/Wf%:zN* ``` Straight forward spec implementation. Explanation: ``` qN/ "Split input by rows"; _0=,2/ "Get half of length of each row"; f/ "Divide each row into two parts"; z "Convert array of row parts to array of half columns parts"; ~\+ "Put the second half of columns before the first half and join"; 2/ "Group adjacent rows"; Wf% "Flip the row pairs to help in CW rotation"; :z "Rotate pairwise column elements CW"; N* "Join by new line"; ``` [Try it online here](http://cjam.aditsu.net/#code=qN%2F_0%3D%2C2%2Ff%2Fz%7E%5C%2B2%2FWf%25%3AzN*&input=ABCDEF%0AGHIJKL%0AMNOPQR%0ASTUVWX) [Answer] # JavaScript (ES6), 104 ~~141~~ **Edit** Reviewing the spec, I found that the number of rows must be even (I missed this before). So it's not too complicated find the correct source position for each char in output in a single step. ``` F=a=>a.map((r,i)=> [...r].map((c,k)=> a[l=i+i]?a[(j=l+1)-k%2][(k+r.length)>>1]:a[l-j-k%2][k>>1] ).join('') ) ``` **Test** In Firefox/FireBug console ``` ;[["ABCDEF","GHIJKL","MNOPQR","STUVWX"] ,["12","34"], ["Hell","! o","d -","lroW"] ,["*___ ___ o","o|__) |__) *","*| | o","o __ __ *","*| | _ o","o|__ |__| *"] ].forEach(v=>console.log(v.join('\n')+'\n\n'+F(v).join('\n'))) ``` *Output* ``` ABCDEF GHIJKL MNOPQR STUVWX JDKELF VPWQXR GAHBIC SMTNUO 12 34 42 31 Hell ! o d - lroW lol o W- !H e ldr *___ ___ o o|__) |__) * *| | o o __ __ * *| | _ o o|__ |__| * |_____) *o |_ _ *o ||_ __| *o o*|_____) o* |_ _ o*||_ _ ``` [Answer] # J, ~~45~~ 39 bytes ``` $$[:,@;@|.@|:([:,:~2,2%~1{$)<@|:@|.;.3] ``` J has a tessellation function (cut `;.`) which helps a lot. ``` ]input=.4 6$97}.a. abcdef ghijkl mnopqr stuvwx ($$[:,@;@|.@|:([:,:~2,2%~1{$)<@|:@|.;.3]) input jdkelf vpwqxr gahbic smtnuo ``` [Answer] # Haskell, ~~128~~ 127 bytes ``` import Control.Monad f=g.ap((++).map snd)(map fst).map(splitAt=<<(`div`2).length) g(a:b:c)=(h=<<zip b a):g c g x=x h(a,b)=[a,b] ``` Usage: `f ["12", "34"]` -> `["42","31"]` How it works: ``` input list: ["abcdef", "ghijkl", "mnopqr", "stuvwx"] ========================================================================== map(splitAt=<<(`div`2).length) split every line into pairs of halves: -> [("abc","def"),("ghi","jkl"),("mno","pqr"),("stu","vwx")] ap((++).map snd)(map fst) take all 2nd elements of the pairs and put it in front of the 1st elements: -> ["def","jkl","pqr","vwx","abc","ghi","mno","stu"] ( zip b a) : g c via g: take 2 elements from the list and zip it into pairs (reverse order), recur until the end of the list: -> [[('j','d'),('k','e'),('l','f')],[('v','p'),('w','q'),('x','r')],[('g','a'),('h','b'),('i','c')],[('s','m'),('t','n'),('u','o')]] h=<< convert all pairs into a two element list and concatenate: -> ["jdkelf","vpwqxr","gahbic","smtnuo"] ``` Edit: @Zgarb found a byte to save. [Answer] # GNU sed -r, 179 bytes Score includes +1 for the `-r` arg to sed. It took me a while to figure out how to do this in `sed`, but I think I have it now: ``` # Insert : markers at start and end of each row s/ /: :/g s/(^|$)/:/g # Loop to find middle of each row :a # Move row start and end markers in, one char at a time s/:([^ :])([^ :]*)([^ :]):/\1:\2:\3/g ta # Loop to move left half of each row to end of pattern buffer :b s/([^ :]+)::(.*)/\2 \1/ tb # remove end marker s/$/:/ # double loop to merge odd and even rows :c # move 1st char of rows 2 and 1 to end of pattern buffer s/^([^ :])([^ ]*) ([^ ])(.*)/\2 \4\3\1/ tc # end of row; remove leading tab and add trailing tab s/^ +(.*)/\1 / tc # remove markers and trailing tab s/(:| $)//g ``` Note all the whitespace above should be single `tab` characters. Comments are not included in the golf score. Note also that this makes extensive use of `:` marker characters. If the input stream contains `:`, then undefined behaviour will ensue. This can be mitigated by replacing all `:` with some non-printing character (e.g. BEL) at no cost to the golf score. Input and output is a tab-separated list of strings: ``` $ echo 'Hell ! o d - lroW' | paste -s - | sed -rf baker.sed | tr '\t' '\n' lol o W- !H e ldr $ ``` [Answer] ## J, ~~33~~ 32 characters A monadic verb. ``` 0 2,.@|:_2|.\"1-:@#@{.(}.,.{.)|: ``` ### Explanation Let's begin by defining `Y` to be our sample input. ``` ] Y =. a. {~ 65 + i. 4 6 NB. sample input ABCDEF GHIJKL MNOPQR STUVWX ``` The first part (`-:@#@{. (}. ,. {.) |:`) splits `Y` in half and appends then ends: ``` # {. Y NB. number of columns in Y 6 -: # {. Y NB. half of that 3 |: Y NB. Y transposed AGMS BHNT CIOU DJPV EKQW FLRX 3 {. |: Y NB. take three rows AGMS BHNT CIOU 3 }. |: Y NB. drop three rows DJPV EKQW FLRX 3 (}. ,. {.) |: Y NB. stitch take to drop DJPVAGMS EKQWBHNT FLRXCIOU ``` In the second part (`_2 |.\"1`) we split this into pairs of two and reverse them: ``` R =. (-:@#@{. (}. ,. {.) |:) Y NB. previous result _2 <\"1 R NB. pairs put into boxes ┌──┬──┬──┬──┐ │DJ│PV│AG│MS│ ├──┼──┼──┼──┤ │EK│QW│BH│NT│ ├──┼──┼──┼──┤ │FL│RX│CI│OU│ └──┴──┴──┴──┘ _2 <@|.\"1 R NB. reversed pairs ┌──┬──┬──┬──┐ │JD│VP│GA│SM│ ├──┼──┼──┼──┤ │KE│WQ│HB│TN│ ├──┼──┼──┼──┤ │LF│XR│IC│UO│ └──┴──┴──┴──┘ ``` Finally (`0 2 ,.@|:`), we transpose the matrix as needed and discard the trailing axis: ``` ] RR =. _2 |.\"1 R NB. previous result JD VP GA SM KE WQ HB TN LF XR IC UO 0 2 |: RR NB. transpose axes JD KE LF VP WQ XR GA HB IC SM TN UO ($ RR) ; ($ 0 2 |: RR) NB. comparison of shapes ┌─────┬─────┐ │3 4 2│4 3 2│ └─────┴─────┘ ,. 0 2 |: RR NB. discard trailing axis JDKELF VPWQXR GAHBIC SMTNUO ``` The whole expression with whitespace inserted: ``` 0 2 ,.@|: _2 |.\"1 -:@#@{. (}. ,. {.) |: ``` And as an explicit verb: ``` 3 : ',. 0 2 |: _2 |.\"1 (-: # {. y) (}. ,. {.) |: y' ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 18 bytes ``` mΣmm↔TmC2T§+m→m←m½ ``` [Try it online!](https://tio.run/##yygtzv7/P/fc4tzcR21TQnKdjUIOLdcGsicB8YTcQ3v///8freTo5Ozi6qako@Tu4enl7QNk@Pr5BwQGARnBIaFh4RFKsQA "Husk – Try It Online") Gaming ]
[Question] [ # Definition Narcissistic 1 integers of an array think they are better than their neighbours, because they are strictly higher than their arithmetic mean. Neighbours are defined as follows: * If the integer is at index **0** (the first), then its neighbours are the last and the second elements of the list. * If the integer is not the first nor the last, then its neighbours are the two immediately adjacent elements. * If the integer is at index **-1** (the last), then its neighbours are the second-last and the first elements of the list. --- # Task Given an array of integers, your task is to discard the narcissistic ones. * The integers can be positive, negative or zero. * You may assume that the array contains at least three elements. * All standard rules apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. # Examples Consider the array `[6, 9, 4, 10, 16, 18, 13]`. Then we can built the following table: ``` Element | Neighbours | Neighbours' Mean | Is Narcissistic? --------+------------+------------------+----------------- 6 | 13, 9 | 11 | False. 9 | 6, 4 | 5 | True. 4 | 9, 10 | 9.5 | False. 10 | 4, 16 | 10 | False. 16 | 10, 18 | 14 | True. 18 | 16, 13 | 14.5 | True. 13 | 18, 6 | 12 | True. ``` By filtering the Narcissistic ones out, we are left with `[6, 4, 10]`. And that's it! # Test Cases ``` Input -> Output [5, -8, -9] -> [-8, -9] [8, 8, 8, 8] -> [8, 8, 8, 8] [11, 6, 9, 10] -> [6, 10] [1, 2, 0, 1, 2] -> [1, 0, 1] [6, 9, 4, 10, 16, 18, 13] -> [6, 4, 10] [6, -5, 3, -4, 38, 29, 82, -44, 12] -> [-5, -4, 29, -44] ``` 1 - *Narcissist* does not mean [mathematically Narcissistic](https://en.wikipedia.org/wiki/Narcissistic_number). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ṙ2+ṙ-<ḤCx@ ``` [Try it online!](https://tio.run/##y0rNyan8///hzplG2kBC1@bhjiXOFQ7/D7c/alrz/390tKmOgq4FEFvG6nBFAxlQBOIZGuoomOkoWOooGBqA@ToKRjoKBkAukAESgEiagOSBGMgzBGo1NIZK6QKNNgZSQHljoLgRUKmFEYgP0mAUGwsA "Jelly – Try It Online") Explanation: ``` ṙ2+ṙ-<ḤCx@ ṙ2 Rotate the original list two elements to the left + Add each element to the respective element of the original list ṙ- Rotate the result one element to the right <Ḥ Check if each element is less than the double of its respective element on the original list C Subtract each 1/0 boolean from 1 (logical NOT in this case) x@ Repeat each element of the original list as many times as the respective element of the logical NOT (i.e. keep elements of the original list where the respective element from the result is 1) ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` lambda x:[b for a,b,c in zip(x[-1:]+x,x,x[1:]+x)if b*2<=a+c] ``` [Try it online!](https://tio.run/##LYzRDoIwDEXf/Yq@AdIlbKgBIv7I3MOGIS5RIGQP6M/POzVt057e2y6vcJ8nFcf@Gh/26W6Wtk47GueVLDseyE/09ku@aSE7U26M0N@p8CO5vTr3thxMTAchmbU@MokG1RrW6P8ESMl0YmqZZJWQSTFVIAzgn3RIKgokcSfrnyLwtUaDXGOt4GxU4uRXxnQ7WlY/BQqciUvGYx6K@AE "Python 2 – Try It Online") [Answer] ## JavaScript (ES6), ~~57~~ 56 bytes ``` a=>a.filter((e,i)=>e+e<=a[(i||l)-1]+a[++i%l],l=a.length) ``` Edit: Saved 1 byte thanks to @g00glen00b. [Answer] # Mathematica, 44 bytes ``` Pick[#,#<=0&/@(2#-(r=RotateLeft)@#-#~r~-1)]& ``` ### How it works Given input such as `{11,6,9,10}`, computes ``` 2*{11,6,9,10} - {6,9,10,11} - {10,11,6,9} ``` and picks out the elements of the original input in places where this result is at most 0. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~17~~ ~~15~~ 14 bytes ``` vy¹®1‚N+èO;>‹— ``` [Try it online!](https://tio.run/##MzBNTDJM/f@/rPLQzkPrDB81zPLTPrzC39ruUcPORw1T/v@PNtNR0DXVUTAGUiZAykJHwchSR8HCCMQHChgaxQIA "05AB1E – Try It Online") ``` vy # For each... ¹ # Push array. ®1‚ # Push [1,-1] N+ # Add current index. è # Push surrounding values of current index. O; # Summed in half. >‹ # A <= B? — # If true, print current. ``` [Answer] # [Haskell](https://www.haskell.org/), 51 bytes ``` f s=[b|(a,b,c)<-zip3(last s:s)s$tail$s++s,b*2<=a+c] ``` [Try it online!](https://tio.run/##DcdBCoMwEAXQq/xFFmqm0FQpKuYkksVEFEOjiJNV6d3TLN7i7SyfNcacN4id/a9i8rTU0@MbrraKLAkySi0qcYhKtBbyzWuyrBeXDw4nLK47nAkKG@Y3YSB0BPMsykxftC7/AQ "Haskell – Try It Online") Usage example: `f [1,2,3]` yields `[1,2]`. For `s = [1,2,3]`, `last s:s` is the list `[3,1,2,3]` and `tail$s++s` the list `[2,3,1,2,3]`. `zip3` generates a list of triples `(a,b,c)` from three given list, truncating the longer ones to the length of he shortest list. We get `[(3,1,2),(1,2,3),(2,3,1)]`, with `b` being the original list element and `a` and `c` its neighbours. The list comprehension then selects all `b` where `b*2<=a+c`, that is `b` is not narcissistic. [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 48 bytes ``` @(x)x(conv([x(end),x,x(1)],[1,-2,1],'valid')>=0) ``` [**Try it online!**](https://tio.run/##NY7RCoMwDEXf9xV5WwpRTN2GMhz@R@mDaAVBdGAnhbFv79LJICE5uTcha@@73cWxyfM8thhUwH5ddjQB3TIoChSQlSXDlGliS@e9m6fhrB5NoaJ3m9@ggTeYK0FWSdYWjNR/CDET3AhqAi4SEmiCQkga4UO6JFVSiGWRy0PJ5GwpReRSxlqclU6c/Np@7qfezfP4WrBFr2CYtieO0imC328qfgE "Octave – Try It Online") ### Explanation The input array is first extended with the last (`x(end)`) and first (`x(1)`) entries at the appropriate sides. The test for narcissism is done by `conv`olving the extended array with `[1, -2, 1]` and keeping only the `'valid'` part. Comparing each entry in the convolution result with `0` gives a logical index (mask) which is used to select the numbers from the input. [Answer] # [J](http://jsoftware.com/), 16 bytes ``` #~+:<:1&|.+_1&|. ``` [Try it online!](https://tio.run/##LYxNCsIwGET3OcVDoUUqoV/SlvxYr5KFGMSNi27Vq8ekyDDD8BjmWfLGGhipLsfvEC5BurceUstyUgdNn9fQc@YTyJtS99vjRe70lZnkSJ6I@ysiwoJHxtYx9bhl3OHUsCyIQ@zO0owlTViH8ThTex2Z8gM "J – Try It Online") ## Explanation ``` #~+:<:1&|.+_1&|. Input: array A _1&|. Rotate A right by 1 1&|. Rotate A left by 1 + Add +: Double each in A <: Less than or equal to #~ Copy the true values from A ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~17~~ ~~16~~ 15 bytes ``` kÈ>½*[Y°ÉY]x!gU ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=a8g+vSpbWbDJWV14IWdV&input=WzYsLTUsMywtNCwzOCwyOSw4MiwtNDQsMTJd) --- ## Explanation Implicit input of array `U`. ``` kÈ> ``` Remove (`k`) the elements that return true when passed through a function, with `Y` being the current index, that check if the current element is greater then ... ``` [Y°ÉY] ``` The array `[Y-1, Y+1]` ... ``` x!gU ``` Reduced by addition (`x`) after indexing each element into `U` ... ``` ½* ``` Multiplied by `.5`. --- ## Alternative, 15 bytes ``` fÈ+X§UgYÉ +UgYÄ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=ZsgrWKdVZ1nJICtVZ1nE&input=WzYsLTUsMywtNCwzOCwyOSw4MiwtNDQsMTJd) [Answer] # [R](https://www.r-project.org/), ~~51~~ 56 bytes *Thanks to user2390246 for correcting my algorithm* ``` function(l)l[c(l[-1],l[1])+c(l[s<-sum(l|1)],l[-s])>=2*l] ``` [Try it online!](https://tio.run/##PY3BCsIwEETvfsUeszqBbFpDA9UfKTkVCkKsYNub/x43EIVdZubBzr7LQqMty7HO@@O1msx5mk2erCTkSRJfatpGux1Pkz/CFdst8f3mzzmVxczmCrKDbmQ@1ay@TQMioACKIHE/BPIgp0RNYwERPcRBAmSAdH9OVn90Kr2KFnutGnzNCkTvyxc "R – Try It Online") indexes `l` where `c(l[-1],l[1])+c(l[s],l[-s])`, the neighbor-sums of `l`, are not less than twice `l`. [Answer] # Mathematica, 40 bytes ``` Pick[#,+##>=3#2&@@@Partition[#,3,1,-2]]& ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` Ḣ+ṪH<ḢṆ .ịj⁸Ç3ƤTị ``` [Try it online!](https://tio.run/##y0rNyan8///hjkXaD3eu8rABMh7ubOPSe7i7O@tR447D7cbHloQAOf///48201Gw1FEw0VEwNABiIM/QAoiNYwE "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~64~~ 60 bytes * Saved four bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor); golfing `l[-~j%len(l)]` (and a space) to `(l+l)[-~j]`. ``` lambda l:[k for j,k in enumerate(l)if(l+l)[-~j]+l[~-j]>=k+k] ``` [Try it online!](https://tio.run/##fZDPCoMwDMbvPkWOihVs/cMcuBfpcnBMmVqrqDvs4qu7dAqTMS0NbZPvl6@ke42PVou5SK@zyprbPQN1ljUUbQ8Vq6HUkOtnk/fZmNvKKQtbucqR3lShq@TkVXhJa7fGORuGvB@hsGXEwDtRJAg7y4E0BbmKrC9JiXXjIbnRbWjOGcQMEgbcxwM6/gi2IAPBwKc0XXAf5Itoiy5@oelIYTrTr3iAfzzDX1vKeTSrgA6qBQQK6nUS5m3EAtc5RYvCVKmCVteXeoQje2d@Aw "Python 2 – Try It Online") [Answer] # Java 8, ~~141~~ ~~137~~ 127 bytes ``` import java.util.*;a->{List r=new Stack();for(int i=0,l=a.length;i<l;)if(2*a[i]<=a[(i-1+l)%l]+a[++i%l])r.add(a[i-1]);return r;} ``` -10 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##lVBNb8IwDL33V/gyKaUf0LJNoND9gg1N4lj1ENoUAiGtUpcJof72zi1wBylW7Be/5@ccxFkEVS3NoTj26lRXFuFAWNii0uGEA8B0Cr@C4KoE3EvYXlAGedUadJxci6aBH6HM1QFQBqUtRS5hPZQA36pByBnhaQbC5QR2FHQaFKhyWIOBBHoRfF3HXpsY@QcbFPmRubys7MAFlcx8nYhQS7PDPVcrzV1VsngiUpWtEpEyFUSedt905onU8xQlrg1FUTDqCKLM5VZiaw1Y3vX85qBut5oc3I2cK1XAifZgG7TK7Ea/tyU2lwblKaxaDGt6Qm2YCXM2GB0Xu374ECwolp07rvgEhdrv53lOFPnw6cPSh2j2AsuH2IcZkSh5nnYb9D7MoqAqIrPR/CWBgD5mThepzIkdk@AiHupB9uGlc7r@Hw) ``` import java.util.*; // Required import for List and Stack a->{ // Method with integer-array parameter and List return-type List r=new Stack(); // Return-list for(int i=0, // Index integer, starting at 0 l=a.length; // Length of the input array i<l;) // Loop over the input array if(2*a[i]<= // If two times the current item is smaller or equal to: a[(i-1+l)%l] // The previous integer in the list +a[++i%l]) // + the next integer in the list r.add(a[i-1]); // Add the current integer to the result-list // End of loop (implicit / single-line body) return r; // Return result-List } // End of method ``` [Answer] # [Julia 0.6](http://julialang.org/), 38 bytes ``` !x=x[x[[e=end;1:e-1]]+x[[2:e;1]].>=2x] ``` [Try it online!](https://tio.run/##LY9vC4IwEMZf56c4BSHpFm5L8Q9K32PtRdQEI1aoxb79uqWw457f89yN7fF5jtfS@9h1TjmlTGfsveWNYVzrAxmiMS3JY98Jp/3wmuBrbgu10cJeFQisoqo1giKxnUCcI5QINQLP/4wgEHJCEsFYw1PIqYg4rXK5RYyultQol@QLGq1E4LAgdBbtzu9ptMuwT1ImixlYD@l8sQluD0SIV5FF9CX/Aw "Julia 0.6 – Try It Online") [Answer] # JavaScript ES5 , 59 bytes ``` F=a=>a.filter((x,i)=>2*x<=a[-~i%(l=a.length)]+a[(i-1+l)%l]) console.log(""+F([5, -8, -9])==""+[-8, -9]) console.log(""+F([8, 8, 8, 8])==""+[8, 8, 8, 8]) console.log(""+F([11, 6, 9, 10])==""+[6, 10]) console.log(""+F([1, 2, 0, 1, 2])==""+[1, 0, 1]) console.log(""+F([6, 9, 4, 10, 16, 18, 13])==""+[6, 4, 10]) console.log(""+F([6, -5, 3, -4, 38, 29, 82, -44, 12])==""+[-5, -4, 29, -44]) ``` [Answer] # [Perl 5](https://www.perl.org/), 51 + 1 (`-a`) = 52 bytes ``` $p=$F[-1];say map{$p+$F[++$i%@F]<2*($p=$_)?'':$_}@F ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lwFbFLVrXMNa6OLFSITexoFqlQBsooq2tkqnq4BZrY6SlAVITr2mvrm6lEl/r4Pb/v6mOgq4FEFv@yy8oyczPK/6v62uqZ2Bo8F83EQA "Perl 5 – Try It Online") [Answer] **[PowerShell](https://github.com/PowerShell/PowerShell), 75 bytes** ``` for($i=0;$i-lt$a.Length;$i++){if($a[$i]-le(($a[$i-1]+$a[$i+1])/2)){$a[$i]}} ``` [Answer] # APL, 20 bytes ``` {⍵/⍨⍵≤2÷⍨(1⌽⍵)+¯1⌽⍵} ``` [Try it online!](http://tryapl.org/?a=%7B%u2375/%u2368%u2375%u22642%F7%u2368%281%u233D%u2375%29+%AF1%u233D%u2375%7D6%209%204%2010%2016%2018%2013&run) ]
[Question] [ Did you notice, that this is a palindrome? **Input** Non-negative integer number or string representing it **Output** 4 possible outputs, representing two properties of number: * is it palindrome * tricky #2 **Tricky #2 property** If number is not palindrome, this property answers the question "Do the first and the *last* digits have the same parity?" If number is palindrome, this property answers the question "Do the first and *middle* digit have the same parity?". For even lengths, the middle digit is one of the center two digits. **Examples** > > 12345678 -> False False > > It is not palindrome, first and last digits have different parity > > > 12345679 -> False True > > It is not palindrome, first and last digits have same parity > > > 12344321 -> True False > > It is palindrome, the first digit 1 and middle digit 4 have different parity > > > 123454321 -> True True > > It is palindrome, the first digit 1 and middle digit 5 have same parity > > > **P.S.** You are up to decide output type and format. It could be any 4 distinct values. Just mention it in your answer. [Answer] # PHP, ~~55~~ 52 bytes ``` echo$p=strrev($n=$argn)==$n,$n-$n[$p*log($n,100)]&1; ``` takes input from STDIN; run with `-R`. output: * `10` for palindrome and same parity * `11` for palindrome and different parity * `0` for non-palindrome and same parity * `1` for non-palindrome and different parity notes: * `strlen($n)/2` == `log($n,10)/2` == `log($n,100)` * if palindrome, compare middle digit `$n[1*log($n,100)]` * if not, first digit `$n[0*log($n,100)]` * ... to whole number (<- lowest bit <- last digit) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 bytes ``` DµŒḂṄHC×LĊị+ḢḂ ``` [Try it online!](https://tio.run/nexus/jelly#@@9yaOvRSQ93ND3c2eLhfHi6z5Guh7u7tR/uWAQU@///v6GRsYmpibGR4de8fN3kxOSMVAA "Jelly – TIO Nexus") Outputs two lines: * `1` for palindrome, `0` for not * `0` for *tricky #2*, `1` for not ### Explanation ``` DµŒḂṄHC×LĊị+ḢḂ Main link. Argument: n (number) D Get the digits of n µ Start a new monadic chain ŒḂ Check if the digit array is a palindrome (1 if yes, 0 if no) Ṅ Print the result with a newline H Halve (0.5 if palindrome, 0 if not) C Subtract from 1 (0.5 if palindrome, 1 if not) × Multiply by... L ...length of array (length/2 if palindrome, length if not) Ċ Round up ị Take item at that index from the digits + Add... Ḣ ...first item of digits Ḃ Result modulo 2 ``` [Answer] # 05AB1E, ~~15~~, ~~14~~ 13 bytes (Thanks to Riley and carusocomputing) ``` ÐRQi2ä¨}ȹRÈQ ``` [Try online](https://tio.run/nexus/05ab1e#@394QlBgptHhJYdW1B7uOLQz6HBH4P//hkbGRoYA) Returns with brackets if it is a palindrome Returns with 0 if the parity is different, 1 if it is the same `Ð` Add input, such that I have enough input to work with `R` Reverse the last element of the stack `Q` Look if it is the same (takes the two top elements and performs ==) `i` If statement, so only goes through when it is a palindrome `2` Push the number 2 `ä` Split the input in 2 equal slices `¨` Push the first element of the split (1264621 results in 1264) `}` End if `È` Check if last element is even `¹` Push the first input again `R` Reverse that input `È` Check if it is even now `Q` Check if those even results are the same and implicitly print [Answer] # [Python 2](https://docs.python.org/2/), ~~70~~ ~~68~~ 66 bytes ``` lambda n:(n==n[::-1],(ord(n[-1])+ord(n[(n==n[::-1])*len(n)/2]))&1) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ6WRZ2ubF21lpWsYq6ORX5SikRcNZGpqQ5hIsppaOal5Gnma@kaxmppqhpr/0/KLFDIVMvMUopUMjYxNTM3MLZR0YExLKNPE2MgQJgpmx1pxKRQUZeaVKKRpZGr@BwA "Python 2 – TIO Nexus") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~114~~ 99 bytes ``` param($n)((0,(($z=$n[0]%2)-eq$n[-1]%2)),(1,($z-eq$n[$n.length/2]%2)))[($n-eq-join$n[$n.length..0])] ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSp6mhYaCjoaFSZaukAuRGG8RqKqkaaeqmFkL4uoYQAU0dDUMdoDK4hEqeXk5qXnpJhr4RVIVmNFAcKK@blZ@Zh6xCTw9oauz////VDY2MTUxNjI0M1QE "PowerShell – TIO Nexus") *Saved 15 bytes thanks to @Sinusoid.* Inputs as a string. Outputs an array of type `(0|1) (True|False)`, with the `0` indicating "not a palindrome" and the `1` indicating "palindrome", and the `True` indicating parity matches and `False` otherwise. This is done by using a pseudo-ternary and indexing into the appropriate place `(a,b)[index]`. The index `($n-eq-join$n[$n.length..0])` checks whether the input is a palindrome. If it is not, we take the `a` portion, which is a `0` coupled with whether the parity of the first digit `$n[0]` is `-eq`ual to the parity of the last digit `$n[-1]`. Otherwise, we're in the `b` portion, which is a `1` coupled with whether `$z` (the parity of the first digit) is `-eq`ual to the parity of the middle digit `$n[$n.length/2]`. Previously, I had `"$($n[0])"` to get the first digit to cast correctly as an integer, since `$n[0]` results in a `char` and the modulo operator `%` coalesces `char`s based on the ASCII value, not the literal value, whereas a `string` does the literal value. However, @Sinusoid helped me to see that `0,1,2,...,9` as literal values all have the same parity as `48,49,50,...,57`, so if it uses the ASCII value we still get the same result. That array is left on the pipeline, and output is implicit. [Answer] # VBA, ~~117~~ 99 bytes Saved 18 bytes thanks to Titus ``` Sub p(s) b=s If s=StrReverse(s)Then r=2:b=Left(s,Len(s)/2+.1) Debug.?r+(Left(s,1)-b And 1); End Sub ``` It doesn't expand much once formatted: ``` Sub p(s) b = s If s = StrReverse(s) Then r = 2: b = Left(s, Len(s) / 2 + 0.1) Debug.Print r + (Left(s, 1) - b And 1); End Sub ``` Here are the given test case results: ``` s = 12345678 p(s) = 1 = False False s = 12345679 p(s) = 0 = False True s = 12344321 p(s) = 3 = True False s = 123454321 p(s) = 2 = True True ``` [Answer] # [Perl 6](https://perl6.org), 48 bytes ``` {($/=.flip==$_),[==] .ords[0,($/??*/2!!*-1)]X%2} ``` [Try it](https://tio.run/nexus/perl6#VZBNT8JAEIbv@yuGpNhd@oEtiEpd8OTJIwcSSkxth6RJv@y2RoL97WV3LYqX2ewzz0ze3VYgfC7cOCD5EW7iMkHg/YkaU@4esrTi3Hhj9o7zPbhlnYjdrS176/Vk6o9GE8dj@@3Y73o5@9ygaIBDlhYoKHPzqFrCiQDkS6EOAOOpaPN3rFfSomFiMU1NZ2UObfyqMG4w0cKmbvH7JcoEMgvGYIKyukAW63eRDfR6aosfYKo5k5GOtPJlG5kpIFUWFWDpgAE5lPWQ1VkBhTAtqraxIbysAaZTp8JJEKvsCOpPqLaY@5oK6V7U4ap7pOs9fza/W9w/qMU6@E8lA3/84yqjxvOZ7ymswLX9j6tyBg "Perl 6 – TIO Nexus") results in `(True True)` `(True False)` `(False True)` or `(False False)` ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( $/ = # store in 「$/」 .flip == $_ # is 「$_」 equal backwards and forwards ), [==] # reduce the following using &infix:<==> (are they equal) .ords\ # list of ordinals (short way to make 「$_」 indexable) [ 0, # the first digit's ordinal ( $/ # if the first test is True (palindrome) ?? * / 2 # get the value in the middle !! * - 1 # else get the last value ) ] X[%] 2 # cross those two values with 2 using the modulus operator } ``` [Answer] # Java 8, ~~205~~ ~~197~~ ~~182~~ ~~168~~ 134 bytes ``` n->{int l=n.length(),a=n.charAt(0)%2;return n.equals(new StringBuffer(n).reverse()+"")?a==n.charAt(l/2)%2?4:3:a==n.charAt(l-1)%2?2:1;} ``` Outputs: `1` for false-false; `2` for false-true; `3` for true-false; `4` for true-true. **Explanation:** [Try it here.](https://tio.run/##jY/NT4NAEMXv/BUTEpPdKCgffkGw0bu99Gg8jHRoqdsBdxeMafjbcWmbqCebzBzmzcsv722wx6BpiTfL97FUaAw8Y807D6BmS7rCkmA@nXsBSrGwuuYVsMydOLh1YyzauoQ5MBQwcvCwm7yq4FARr@xayAt0R7lG/WjFlTyLc0220wwc0keHygimTzign7qqIi1Yhpp60oaEPPd9OcPiB6EuYweZpVmS/ZGDaJLjLMqHMfdcsrZ7Uy7ZMWDf1EvYun7HFi@vgPJQbvFlLG3DprNh615WsXBY4Udxkl7f3N75cl/4X@P9ScY0iaPTiL@cgzeM3w) ``` n->{ // Method with String parameter and integer return-type int l=n.length(), // The length of the input String a=n.charAt(0)%2, // Mod-2 of the first digit return n.equals(new StringBuffer(n).reverse()+"")? // If the String is a palindrome a==n.charAt(l/2)%2? // And if the first and middle digits are both even/odd 4 // return 4 : // Else 3 // Return 3 :a==n.charAt(l-1)%2 ? // Else-if the first and last digits are both even/odd 2 // Return 2 : // Else 1; // Return 1 } // End of method ``` [Answer] # [Haskell](https://www.haskell.org/), 89 bytes ``` (x:r)#y=mod(sum$fromEnum<$>[x,y])2 f x|reverse x/=x=2+x#last x|y<-length x`div`2=x#(x!!y) ``` [Try it online!](https://tio.run/nexus/haskell#LchLCoMwFEDReVfxRAcJtS1G@8V01mFXIIKCsQomkUTtC3Tv1n4GFw53Jngx1Hdc6orYUQa10fKmRpkG1wxDl1O2qgFfRkzCWAG448jZGv2utMPyXbrphHoMDWBRtVPBOPoEPc/RWZatAg6y7O9AetOqAbZQL9lGPylkEYuT/eF4Cv84f5HELPqdj/L5DQ "Haskell – TIO Nexus") Usage: `f "12345"`. Returns `0` for True True, `1`for True False, `2` for False True and `3` for False False. The function `#` converts both digit characters into their ascii character codes and sums them. If both are even or both are odd the sum will be even, otherwise if one is even and the other odd the sum will be odd. Calculating modulo two, `#` returns `0` for equal parity and `1` otherwise. `f` checks if the input string `x` is a palindrome. If not then `#` is called with `x` and the last character of `x` and two is added to the result, otherwise if `x` is palindromic call `#` with the middle character of `x` instead and leave the result as is. [Answer] # [Kotlin](https://kotlinlang.org), 142 bytes ``` fun Char.e()=toInt()%2==0; val y=x.reversed()==x;val z=x.first();println("${y},${if(y)z.e()==x.get(x.length/2).e();else z.e()==x.last().e()}") ``` [Try it online!](https://tio.run/nexus/kotlin#bY/LDoIwEEX3fEVDNGkTRQXfWBPjyrVf0OC0EGsxpRqQ8NmusfW1YnZz5uTmDr8pdM6NyCXH5fpodKYEqVtu8T5lOgBMqMkPymDSDykdx96dSVTRMtBwB13AyQq0jB19WMozXVg3vtogIxX2e3XVDHp1xnFFHu84awkwuAwkKGHSUUgcjkEWgP6GZC7GbY1P2sZzhS4sU5hpUazRTmtWbT51t6T2kJ3fG/4kjKaz@WLpk06@6uLTKJx0@t9D0z5VPkxYksIL "Kotlin – TIO Nexus") ``` fun Char.e() = toInt() % 2 == 0; //character extension function, returns if character(as int) is even val y = x.reversed() == x val z = x.first() println( "${y} //returns whether or not input is a palindrome , //comma separator between the values ${if(y) z.e() == x.get(x.length/2).e() // if it's a palindrome compare first and middle parity else z.e() == x.last().e()}" //else compare first and last parity ) ``` [Answer] ## REXX, ~~104~~ 100 bytes ``` arg a parse var a b 2''-1 c e=a=reverse(a) b=b//2 if e then f=b&centre(a,1)//2 else f=b&c//2 say e f ``` Returns logical value pair `0 0`, `0 1`, `1 0` or `1 1`. [Answer] # R, ~~115~~ ~~109~~ 105 bytes ``` w=strtoi(el(strsplit(scan(,""),""))) c(p<-all(w==rev(w)),w[1]%%2==switch(p+1,tail(w,1),w[sum(1|w)/2])%%2) ``` Takes input from stdin. Returns `FALSE FALSE` for False False, `FALSE TRUE` for False True, `TRUE FALSE` for True False, and `TRUE TRUE` for True True. [Answer] # AWK, ~~97~~ 96 bytes ``` {n=split($0,a,"") for(;j<n/2;)s+=a[j+1]!=a[n-j++] x=(a[1]%2==a[s?n:int(n/2)+1]%2)+(s?0:2) $0=x}1 ``` Simplest usage is to place the code into file: `OddEven` then do: ``` awk -f OddEven <<< "some number here" ``` Output is essentially the bit-sum of the comparisons in the Question, e.g. ``` 0, Not palindrome and first and last digits have different parity 1, Not palindrome and first and last digits have same parity 2, Palindrome and the first digit and middle digit have different parity 3, Palindrome and the first digit and middle digit have same parity ``` I tried removing the `()` from `(s?0:2)` but this messes up operator precedence somehow. [Answer] ## CJam, 32 bytes ``` q:N_W%=N0=~2%NW=~2%N_,2/=~2%3$?= ``` Input is a number on top of the stack. Explanation: ``` q e# Read input: | "12345679" :N e# Store in N: | "12345679" _ e# Duplicate: | "12345679" "12345679" W% e# Reverse: | "12345679" "97654321" = e# Check equality: | 0 N e# Push N: | 0 "12345679" 0=~ e# First digit: | 0 1 2% e# Modulo 2: | 0 1 N e# Push N: | 0 1 "12345679" W=~ e# Get last digit: | 0 1 9 2% e# Modulo 2: | 0 1 1 N e# Push N: | 0 1 1 "12345679" _ e# Duplicate: | 0 1 1 "12345679" "12345679" , e# Length: | 0 1 1 "12345679" 8 2/ e# Divide by 2: | 0 1 1 "12345679" 4 = e# Get digit (as char): | 0 1 1 '5 ~ e# Eval character | 0 1 1 5 2% e# Modulo 2: | 0 1 1 1 3$ e# Copy stack element: | 0 1 1 1 0 ? e# Ternary operator: | 0 1 1 = e# Check equality: | 0 1 ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 60 + 1 = 61 bytes Uses the `-n` flag. ``` r=->i{$_[i].to_i%2} p e=$_.reverse==$_,r[0]==r[e ?~/$//2:-1] ``` [Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNDN@19kq2uXWa0SH50Zq1eSH5@palTLVaCQaqsSr1eUWpZaVJxqC2TrFEUbxNraFkWnKtjX6avo6xtZ6RrG/v9vaGRsYmJsZAgA "Ruby – TIO Nexus") [Answer] # Groovy, 326 303 bytes Shrunk Code: ``` String str="12345678";char pal,par;pal=str==str.reverse()?'P':'N';if(pal=='P'){par=(int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N'}else{par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N'};print((String)pal+(String)par) ``` Original Code (with Explanation): ``` Declare str as String String str = "12345678" Declare pal and par as char char pal, par Check if Palindrome or not pal = str==str.reverse()?'P':'N' If Palindrome... if (pal=='P') { and has same parity (S) and if not (N) par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N' else if not palindrome... } else { and has same parity (S) and if not (N) par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N' closing tag for if } Print desired output print((String)pal+(String)par) ``` Original Code (without Explanation): ``` String str = "12345678" char pal, par pal = str==str.reverse()?'P':'N' if (pal=='P') { par = (int)str.charAt(0).toString()%2==str.charAt((int)str.length()-1-(int)((str.length()-1)/2))%2?'S':'N' } else { par = (int)str.charAt(0).toString()%2==str.charAt((int)(str.length()-1)%2)?'S':'N' } print((String)pal+(String)par) ``` Input: ``` Just change "12345678" to another set of non-negative digits. ``` Output: ``` "PS" - Palindrome with Same Parity "PN" - Palindrome with Diff Parity "NS" - Non-palindrome with Same Parity "NN" - Non-palindrome with Diff Parity ``` ]