text
stringlengths
180
608k
[Question] [ *EDIT: I'm getting a lot of comments about this not terminating - I will give the "correct answer" tag to either the first person who gives me `FF(3)` (as in provides it in their answer) or proves that `FF(3)` does indeed blow up indefinitely.* ## Task: Your task is make the smallest program possible that generates the list of reciprocals of the Fraction Frenzy function (`FF(n)`) given a positive integer `n`. ## Introduction: Before I can introduce the FF function, I have to first explain Egyptian fractions. ### Egyptian Fractions: Egyptian fractions are a way of expressing fractions as the sum of distinct unit fractions - so one way to express the fraction `5/8` is `1/2 + 1/8`. It is not other fraction sums like ``` 1/4 + 1/4 + 1/8 1/2 + 1/16 + 1/16 ``` because not all of their fractions are distinct (`1/4` is repeated in the first example, and `1/16` in the second). In our definition of Egyptian fractions, we are including the use of negative denominators in the unit fractions as well. ### FF function: The FF (Fraction Frenzy) function is described like so: `FF(1)` is the Egyptian fraction `1/2 + 1/3 + 1/5 + 1/-30`. `FF(2)` is equal to `FF(1)` "multiplied" by itself (`FF(1)` "squared"): ``` (1/2 + 1/3 + 1/5 + 1/-30)(1/2 + 1/3 + 1/5 + 1/-30) = 1/4 + 1/6 + 1/10 + 1/-60 + 1/6 + 1/9 + 1/15 + 1/-90 + 1/10 + 1/15 + 1/25 + 1/-150 + 1/-60 + 1/-90 + 1/-150 + 1/900 ``` This is not a fully reduced Egyptian fraction yet, because there are "repeats" in fractions. To reduce them, the following procedure is done: 1. Sum all "like" unit fractions together. 2. Reduce the sums to their simplest forms - so for example, if a sum from step `1` is `2/6`, that can be reduced to `1/3`. 3. Repeat 1 and 2 until all denominators are distinct: for example, `1/2 + 2/3 + 1/5`, as opposed to `1/2 + 1/3 + 1/3`, which has a repeating denominator `3`. 4. If there is a pair of one positive and one negative fraction that have an equal absolute value, remove both of them (e.g. `1/-5` and `1/5` must both be removed). 5. If fractions are not unit and cannot be reduced further, split it up into unit fractions with a equal denominator, and keep one fraction as it is. With the other ones, multiply them by `FF(1)`: `(1/2 + 1/3 + 1/5 + 1/-30)`. 6. Repeat steps 1-5 until the final fraction sum is a valid Egyptian fraction - i.e. all fractions are distinct from one another, and they are all unit fractions. This is the reduction of `FF(2)`: ``` 1/4 + 1/6 + 1/10 + 1/-60 + 1/6 + 1/9 + 1/15 + 1/-90 + 1/10 + 1/15 + 1/25 + 1/-150 + 1/-60 + 1/-90 + 1/-150 + 1/900 = 1/4 + 2/6 + 1/9 + 2/10 + 2/15 + 1/25 + 2/-60 + 2/-90 + 2/-150 + 1/900 (step 1) = 1/4 + 1/3 + 1/9 + 1/5 + 2/15 + 1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900 (step 2) = 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/15(1/2 + 1/3 + 1/5 + 1/-30) + (step 5) 1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900 = 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/30 + 1/45 + 1/75 + 1/-450 + 1/25 + 1/-30 + 1/-45 + 1/-75 + 1/900 = 1/3 + 1/4 + 1/5 + 1/9 + 1/15 + 1/25 + 1/-450 + 1/900 (step 4) ``` For all `n` (except for `1`), `FF(n)` is defined by "squaring" `FF(n-1)`. ## Input and Output: Given an integer `n`, you must output a list all of the reciprocals of `FF(n)`, sorted in ascending order of their absolute values: ``` 1 -> [2, 3, 5, -30] # 1/2 + 1/3 + 1/5 + 1/-30 = FF(1), reciprocals = [2, 3, 5, -30] 2 -> [3, 4, 5, 9, 15, 25, -450, 900] ``` You are allowed to use a string with any delimiter, or your language's interpretation of a list, so these outputs are all acceptable with the input `1`: ``` 2 3 5 -30 (Space-delimited) 2,3,5,-30 (Comma-delimited) [2 3 5 -30] (Lisp-like lists) etc. etc. ``` ## Specs: * You must output the results of the `FF(n)` function exactly as specified above. * You are guaranteed that the input will be a positive integer - it will never be below zero, and it will never be a decimal (or fraction). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Haskell](https://www.haskell.org/), 365 bytes ``` import Data.Function;import Data.List;import Data.Ratio;n=numerator;d=denominator r=until=<<((==)=<<)$filter(/=0).map(sum).groupBy((==)`on`d).sortBy(compare`on`d) p s=let(o,q)=span((<2).abs.n)s in case q of []->o;(a:b)->let j=a-1%d a*signum a in p.r$o++[a-j]++map(*j)e++b s s=(*)<$>s<*>s;e=(1%)<$>[2,3,5,-30];f=iterate(p.r.s)e;o i=[abs(d q)*signum(n q)|q<-f!!(i-1)] ``` [Try it online!](https://tio.run/nexus/haskell#VU87T8MwEN77K1yple7yME1LFxJnQIgJFtYootfGqVw1tmM7AxL/vTjAANPdffped1ODNS6wJwrEnyd9Csro8i/4onz4B7xR5JRa6GmQjoJxZSc6qc2g9HwtnJh0UFdRVQBCYJy46tU1SAd3YoN8IAt@GpCfnZns48c362D0oUPuY0pETmaw5OQPuLDMi6sMYLIRhbekAaotcjp6rtEzpdmJvGQjMz1r2rw2JdDDEfM6ithFUF6sO0aJV@dYmdEssNytTJo2lF/aNJ0bJReUaXpc@BgGCVar2ldJ7UspoFjPZ7PNdtk@y3ebtuyFCvPvEqIR9yhLw5RoYiPo2Ii/UaDj/jlWeb9cgsoLbG8DKS1i3Os7WKd04AabIpud77N9e/sC "Haskell – TIO Nexus") ]
[Question] [ This challenge is based on another similar challenge. Because finding the most efficient packing of rectangles is NP-hard (that is, its solution is easy to check but hard to find), this challenge is a lot easier than this one [here](https://codegolf.stackexchange.com/questions/96901/arranging-arbitrary-rectangles-to-fill-a-space) ## This Challenge Given a bunch of rectangles, figure out whether or not they fill a rectangular space with no gaps or overlaps. ## Input Input can be in two forms, one of which carries a scoring penalty. The first: it contains a list of sublists, each with length 4. This list contains 4 integers which are the coordinates of opposite vertexes. Since all rectangles will be horizontal/vertical, there is no ambiguity as to where the rectangle is. Each sublist will contain four integers, which, in order, are the x-coordinate of the first vertex, the y-coordinate of the first vertex, the x-coordinate of the second vertex, and the y-coordinate of the second vertex. The second: it contains four lists of integers with the same length. The four lists represent the different coordinates. If you imagine input option 1 as a matrix, the input here is just the [transpose](http://www.mathwords.com/t/transpose_of_a_matrix.htm) of the matrix. This input carries a `+20%` byte penalty. ## Output Simple truthy/falsy output. ## Specifications If there is a rectangle with area 0 (that is, `x1 == x2 || y1 == y2`), disregard this rectangle (so `[0 0 1 1], [2 2 3 2]` is valid). This specification is in place to make it harder for people to simply get the min/max x/y values. `x1 <= x2` and `y1 <= y2` are not always true. If `x1 > x2 || y1 > y2`, the rectangle is not a zero-area rectangle; rather, it occupies the rectangular space between `(x1, y1)` and `(x2, y2)`. Coordinates can be negative, in which case they still occupy the space between the coordinates. The top-left-most rectangle is not always at `(0, 0)`; thus, the rectangular space that is filled doesn't necessarily have its top-left corner at `(0, 0)`. (Thanks to @xnor for pointing out these ambiguities) Please specify how you want your input and how your output will be represented. ## Scoring Score is the size of the code in bytes, plus a byte penalty if applicable. Lowest score as of December 15th wins. ## Test Cases ``` 0 0 1 2 1 0 3 1 ==> true 1 1 3 2 0 0 2 2 0 0 1 1 ==> false 0 0 0 0 0 0 1 1 2 2 2 2 ==> true 0 1 2 1 ``` Good luck, happy golfing! [Answer] ## JavaScript (ES6), 249 bytes ``` with(Math)a=>!(a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b]).filter(g=([l,t,r,b])=>(r-l)*(b-t))).reduce((s,b)=>s-g(b),g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i])))))>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b)) ``` Note: To use this, either evaluate it as a string and assign the result to a variable, or insert the assignment after the `with(Math)`. Explanation: `with(Math)a=>!(` Bring `min` and `max` into scope. `a=a.map(([l,t,r,b])=>[l<r?l:r,t<b?t:b,l>r?l:r,t>b?t:b])` Normalise the coordinates `.filter(g=([l,t,r,b])=>(r-l)*(b-t)))` Remove empty rectangles, also defining a function to calculate area `.reduce((s,b)=>s-g(b),` Subtract the areas of all the rectangles `g([min,min,max,max].map((f,i)=>f(...a.map(a=>a[i])))))` from the area of the bounding box `>a.some(([l,t,r,b],i)=>a.some(([m,u,s,c],j)=>i!=j&l<s&m<r&t<c&u<b))` and check that no rectangles overlap. [Answer] # Mathematica, 194 bytes ``` (r=Select[#,(#-#3)(#2-#4)&@@#>0&];m={#~Min~#3,#2~Min~#4,#~Max~#3,#2~Max~#4}&@@Transpose@r;b=Boole[(x-#)(x-#3)<0&&(y-#2)(y-#4)<0]&;Integrate[(Plus@@(b@@@r)-b@@m)^2,{x,#,#3}&@@m,{y,#2,#4}&@@m]<1)& ``` An ungolfed version: ``` 1 (r = Select[#1, (#1 - #3) (#2 - #4) & @@ #1 > 0 &]; 2 m = {Min[#1, #3], Min[#2, #4], Max[#1, #3], Max[#2, #4]} & @@ Transpose[r]; 3 b = Boole[(x - #1) (x - #3) < 0 && (y - #2) (y - #4) < 0] &; 4 Integrate[ 5 (Plus @@ (b @@@ r) - b @@ m)^2 , 6 {x, #1, #3} & @@ m , 7 {y, #2, #4} & @@ m 8 ] < 1 9 ) & ``` Line 1 defines `r` to be the set of nontrivial rectangles from the given input. (There's a lot of `& @@` going on in this code; that's just so we can use `#1,#2,#3,#4` for the four elements of a list instead of `#[[1]],#[[2]],#[[3]],#[[4]]`.) Then line 2 defines `m` to be the coordinates of the smallest rectangle bounding all of the ones listed in `r`; so if the input rectangles tile a large rectangle, that large rectangle must be `m`. Line 3 defines function `b` which, when applied to a quadruple representing a rectangle, produces a function of two variables `x` and `y` that equals 1 if the point `(x,y)` is inside the rectangle and 0 if it's not. Line 5 produces many of these functions, one for each rectangle in `r` (all added together) and one last one for the large rectangle `m` (subtracted); that complicated two-variable function is then squared. The key, at this point, is that that two-variable function is identically 0 if the small rectangles tile the large rectangle, but it will have some positive values if two small rectangles overlap, or some negative values (before squaring) if some part of the large rectangle isn't covered. We detect this by literally integrating(!) the two-variable function over the large rectangle (the limits of integration are given in lines 6-7): if we obtain 0, then the tiling was perfect, and if we obtain a positive value, then there was a problem somewhere. Since everything in sight is an integer, we save one final byte by using `< 1` instead of `== 0` in line 8. (I think it's pretty fun that we can exploit Mathematica's ability to do calculus to solve this combinatorial problem.) ]
[Question] [ *In honor of [recent news of Google developing a keyboard for iPhone](http://bgr.com/2016/03/23/google-keyboard-app-ios-iphone-gif-search/)...* Your input (for simplicity, all input is case sensitive): 1. Location of standard dictionary file. File format is 1 valid word per line; in alphabetical order. Example file: ``` apple banana citrus domino durian orange tuna zabc ``` 2. Location of personal dictionary file (initially, may be empty or non-existant). Format is 1 word per line, comma separated by count of times that word was used. Example file: ``` Stackoverflow,15 StackExchange,11 Meta,13 TFGITW,2 VTC,10 ``` 3. A stream of words on standard input (for simplicity, newline separated), in the following format on each line: "Typed\_word,intended\_word". You need to emulate a predictive keyboard, as follows. For every line in the stream of words: 1. Process the typed word character by character 2. After 3rd character, generate the 5 most-used words that start with the currently-seen substring "5" is a hard-coded constant, but my example below uses "2" for simplicity. "most-used" are picked as first words when words are sorted in the order of counting; alphabetic order within same counts. The rules for most-used words are: the word from the standard dictionary is assumed to have the used count of 20 (that's a hard-coded constant, but my example below uses "2" for simplicity). The word from personal dictionary has a used count of whatever number the dictionary file has. 3. If one of 5 words matches intended word, print the success: "MATCH:$substring,$intended\_word" and stop 4. If typed word is finished and matches intended\_word, print it: "FULLWORD:$typed\_word,$intended\_word" and stop 5. If typed word is finished, but none of teh matches or the word match intended\_word, print ERROR message including both typed and intended word: "MISMATCH:$typed\_word,$intended\_word" 6. Add the intended word to the personal dictionary if missing from it; or increment its usage count in personal dictionary if already present Answers should be genuine working code - no [gotchas/loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), no edge cases like super-small input. # SAMPLE RUN (I'm going to change the constants to 2 guesses (instead of 5) and main dictionary words weigh as 2 user-usages instead of 20) ## Standard Dictionary: ``` abacus abacii abandon abandoned abandonment ``` ## User dictionary EMPTY ## INPUT ``` abanana,abanana abanana,abanana abanana,abanana abandonmint,abandonment cat,cad ``` ## OUTPUT ``` FULLWORD:abanana,abanana #after this, add "abanana,1" to custom dictionary MATCH:abana,abanana # NOTE: your code should have matched "abandon,abandoned" till seeing "abana" # change custom dict count for abanana to 2 MATCH:aban,abanana #By now, aban matches "abanana,abandon" MATCH:abandonm,abandonment MISMATCH:cat,cad # Add cad to custom dictionary ``` --- **NOTE**: someone asked to be able to live with no files. I'm fine with that, the simplest spec seems to be to pass all 3 inputs on STDIN, separated by empty line between the inputs. [Answer] # Python 3.9, 350 bytes ``` import sys [s,p,x]=sys.stdin.read().split("\n\n") p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]] s={k:20 for k in s.split("\n")} p={k:int(v)for k,v in p} for t,i in x:b=s|p;b={k:b[k]for k in b if k[:4]==t[:4]};b=sorted(b,key=b.get);p[i]=p.get(i,0)+1;print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i) ``` [Try it online!](https://tio.run/##jZDBb4IwFMbv/SsaLoK@EHEzWTA9LG5uJpol080DcihQtAFLQzunMf7trkXdPC4cvve@9@v3WuRerytx9yDr04lvZFVrrPYKRQok7GJial/pjAu/ZjRzPV/JkmvXWYqlcDxkGBJF5cVtQcvLqxqXmAuc/aGOF1s7M3ZkU2OkyKEIe11s7cLS6pY@ImnnXGh32wQWsLWQPCLbaeC224UJObTbCtpteRwk9kQSFfFvZIJ5josovI8J0VYspMwDWeYmULA9SfwV095ARjwm0tYuh67XCQaytrvd3Jk@zoev4eF8HBwT2KxOorAfs1IxnDujj8lk8fb@ZKgzoQnh@DKcjmfXCDP0Otw7naiUJUM0oemXaoRzKyKrxFVZdq02TGiEZpqmRbVldV5W3xD0z8bzLl1TsWIQBGjKNIXgDs1HL@P5Anrocz6EoIuaHPPBRf/V273mB8DtHVKqIaXZDw "Python 3.8 (pre-release) – Try It Online") (Uses `{**a,**b}` instead of `a|b` to merge dictionaries) The I/O formats are restrictive, but this still makes for a simple and fun challenge. ``` import sys #s is the standard dictionary, p is the personal dictionary, and x is the input #They are separated by a blank line [s,p,x]=sys.stdin.read().split("\n\n") #Turn both p and x into lists (separated by \n) of 2-element lists (separated by commas) p,x=[[l.split(',')for l in d.split("\n")]for d in[p,x]] #Split s on \n to get list of words, then map to 20, the default no. of occurrences s={k:20 for k in s.split("\n")} #Turn p into a dictionary, and make the values ints p={k:int(v)for k,v in p} #Iterate over each typed word t and intended word i in the input for t,i in x: #Merge the personal and standard dictionaries and store in b b=s|p #Filter the words who start with the first 4 characters of t (typed word) b={k:b[k]for k in b if k[:4]==t[:4]} #b now contains words from the dictionary, sorted by number of occurrences b=sorted(b,key=b.get) #Increment number of occurrences of i in personal dictionary, or set to 1 if it doesn't exist yet p[i]=p.get(i,0)+1 #Print the corresponding message print((f"MATCH:{t[:4]},"if i in b[:5]else f"FULLWORD:{t},"if t==i else f"MISMATCH:{t},")+i) ``` ]
[Question] [ # Introduction File names can be wildly varying things, ranging from a simple `blah.txt` to `303549020150514101638190-MSP0.txt`. The former is usually human generated, while the latter is often machine generated. Wouldn't it be nice to have a simple function to make educated guesses on whether or not a file might be considered "human-friendly"? Inspired by a post by Eduard Florinescu that has since been deleted. His idea was good, but just needed a little fleshing out. # Challenge Write a program or function in the language of your choice that can take an string, and determine if it is considered "human-friendly", as defined by this challenge. Some further details and rules are as follows: * Input will be a string consisting of the 95 printable ascii characters. * "human-friendly" shall be defined thusly: + Exclude the extension in the consideration. An extension is defined as the final period followed by a series of alpha-numeric characters (as few as 1, as many as 6). + No more than half of the string by length (excluding extension) may consist of the following defined groupings of characters (combined): - Decimal characters longer than 8 in a row. - Hexadecimal characters (upper xor lower case) of at least 16 in a row (must consist of letters and numbers, and of which at least a third of the characters are numbers). - Base64 characters (using `%+=` as the special characters) of at least 12 in a row (must consist of letters and numbers, be mixed case, and of which at least a third of the characters are uppercase letters). + If any of the above groupings overlap in definition (such as one that qualifies as base64, but has 8 digits in a row), choose the longest of them to be excluded. * Output should be a truthy or falsy value, depending on if the string is considered "human-friendly" or not. * Assume that only valid input will be used. Don't worry about error handling. The winner will be determined by the shortest program/function. They will be selected in at least 7 days, or if/when there have been enough submissions. In the event of a tie, the answer that came earlier wins. # Examples Here's a few examples of input and output that your code should be able to handle: ``` "results_for__michael_greer.txt.zip" => true "Georg Feuerstein - Connecting the Dots.pdf" => true "M People - Search for the Hero-ntuqTuc6HxM.mp4" => true "index.html?v=QTR4WGVTUzFsV3d8NHxvcmlnaW5hbHx8MTExMTAxBHxodHRwOi8vLCwsLHRyLDcsMA%3D%3D.html" => false "ol2DCE0SIyQC(173).pdf" => false "d41d8cd98f00b204e9800998ecf8427e.md5" => false "12792331_807918856008495_7076645197310150318_o.jpg" => false ``` [Answer] # Javascript, 466 bytes ``` s=>(s=s.split(/\.[a-z\d]{1,6}$/i)[j=d=0],h=s[l='length']/2|0,m=[],g=r=>(++j,m=m.concat((s[n='match'](r)||[]).map(x=>[x,j]))),p='replace',g(/\d{9,}/g),g(/[\da-f]{16,}/ig),g(/[\da-z%+=]{12,}/ig),m.sort((x,y)=>y[0][l]-x[0][l]).every(x=>x[1]-1?x[1]-2?s=s[p](x[0],y=>y[n](/[a-z]/)&&y[n](/\d/)&&(y+'A')[n](/[A-Z]/g)[l]>y[l]/3|0?(d+=y[l],''):y):s=s[p](x[0],y=>!!y[n](/[A-F]/)^!!y[n](/[a-f]/)&&(y+'0')[n](/\d/g)[l]>y[l]/3|0?(d+=y[l],''):y):(s=s[p](z=x[0],''),d+=z[l])),d<=h) ``` Explaining: ``` f=s=>( // f: take string s (filename) as input s=s.split(/\.[a-z\d]{1,6}$/i)[j=d=0], // s: input without extension // d: combined rules' sum // j: combined rule-number step h=s[l='length']/2|0, // h: half string // l: length m=[], // m: matches g=r=>(++j, // j: next combined rule number m=m.concat( // m: join (s[n='match'](r)||[]).map( // new (r)egex-matches x=>[x,j]) // mapped with its rule number )),p='replace', // p: replace g(/\d{9,}/g), // combined rules §1 g(/[\da-f]{16,}/ig), // combined rules §2 g(/[\da-z%+=]{12,}/ig), // combined rules $3 m.sort((x,y)=>y[0][l]-x[0][l]) // matches ordered by length .every(x=>x[1]-1? // for combined rule §1 x[1]-2? // for combined rule §2 s=s[p](x[0],y=> // for combined rule §3 y[n](/[a-z]/)&&y[n](/\d/)&& // if lower and digit and (y+'A')[n](/[A-Z]/g)[l]>y[l]/3|0? // upper at least `total/3` (d+=y[l],''):y) // replace by empty and sum up `d` :s=s[p](x[0],y=> // replace if !!y[n](/[A-F]/)^!!y[n](/[a-f]/)&& // (upper xor lower case) and (y+'0')[n](/\d/g)[l]>y[l]/3|0? // digits: at least `total/3` (d+=y[l],''):y) // by empty and sum up `d` :(s=s[p](z=x[0],''),d+=z[l])) // no treatment ,d<=h // output if "no more than half of string" ); ["results_for__michael_greer.txt.zip", "Georg Feuerstein - Connecting the Dots.pdf", "M People - Search for the Hero-ntuqTuc6HxM.mp4", "index.html?v=QTR4WGVTUzFsV3d8NHxvcmlnaW5hbHx8MTExMTAxBHxodHRwOi8vLCwsLHRyLDcsMA%3D%3D.html", "ol2DCE0SIyQC(173).pdf", "d41d8cd98f00b204e9800998ecf8427e.md5", "12792331_807918856008495_7076645197310150318_o.jpg"] .forEach(x=>document.body.innerHTML+='<pre>"'+x+'" => '+f(x)+'</pre>') ``` ]
[Question] [ This is the third in a series of puzzles that I will be posting every Monday at Midnight PST, and the final variant of "Take It or Leave It". The first puzzle is located [Here](https://codegolf.stackexchange.com/questions/54147/take-it-or-leave-it-a-game-show-for-computers) The second puzzle is located [Here](https://codegolf.stackexchange.com/questions/54206/take-it-or-leave-it-ii-a-game-show-for-computers) **Context:** > > A reclusive billionaire has created a game show to attract the world's best and brightest programmers. On Mondays at the stroke of midnight, he chooses one person from a pool of applicants to be the contestant of the week, and provides them with a game. You are this week's lucky contestant! > > > **This week's game:** > > The host provides you with API access to a stack of 15,000 digital envelopes. These envelopes are randomly sorted, and contain within them a dollar value, between $1 and $15,000 (no two envelopes contain the same dollar value). > > > You have 5 commands at your disposal: > > > 1. Read(): Read the dollar figure in the envelope at the top of the stack. > 2. Take(): Add the dollar figure in the envelope to your game show wallet, and pop the envelope off the stack. > 3. Pass(): Pop off the envelope on the top of the stack. > 4. Oracle(M): Returns the mean value of the next M envelopes in the stack, not including the one you can currently Read(). > 5. End(): Stop the game, and walk away the money currently in your wallet (your final score). > > > **The Rules:** > > 1. If you use Pass() on an envelope, the money within is lost forever. > 2. If you use Take() on an envelope containing $X, from that point forward, you may never use Take() on an envelope containing < $X. Take() on one of these envelopes will add $0 to your wallet. > 3. If you use Oracle(M) on turn T, envelopes T+1 through T+M's mean will be returned. Oracle() is disabled until turn T+M. > 4. If you use Take() or Pass() on turn T, $T is removed from your wallet. > > > Write an algorithm that finishes the game with the maximal amount of money. Note 1: "Maximal" in this case means the median value in your wallet after N >= 1000 runs. I expect, though I would love to be proven wrong, that the median value for a given algorithm will converge as N increases to infinity. Feel free to try to maximize the mean instead, but I have a feeling that the mean is more likely to be thrown off by a small N than the median is. Note 2: This puzzle has a significant difference from the first two iterations (namely, needing to pay for each envelope you take). Feel free to use any strategies from the first puzzles as a base, but be warned: They will probably (read: definitely) get a negative score without some kind of modification. Edit: The prize condition has been removed, in light of [this post](http://meta.codegolf.stackexchange.com/questions/5677/the-community-is-against-cash-prizes-but-should-that-be-advice-or-a-rule) on meta. [Answer] ## Java, $3889.5 Median ``` int highest=0; int topp=0,tott=0; for(int i=0;i<1000;i++){ if(Read()>topp&&tott+Read()-i>tott){ topp=Read(); tott += Read(); tott -= i; Take(); }else{ if(tott-i>i/2){ tott -= i; Pass(); }else{ End(); break; } } if(highest/1.1>tott){ End(); break; } if(tott>highest) highest=tott; } ``` [Try it Online](https://tio.run/##dVNNb5tAED0vv2LkQ7SIGEOlnjBIVdVDpVaqkt6qHjZhTdaGBS1rp2nFb3dn2MUhsX1hvG/mvfn0VhzEclvujkfVdK2xsEUg3ltVx5@MES/fVG@z4Mx3J3TZNlkQdPuHWj3CYy36Hr4Lpf8FzGO9FRbNSWb9VVtZSVOAMAZy0PJ55ix4mL2nKm3BthZjkyu@7rpvb7RzvvceWlVCg6Xye2uUrn79xoKqPgQsnbnGwKDxJTpkrI6xTWuAk7xCb5qhWUP6MaFfUeQUGMP2YlGWnERiLf9YbJwT2Ku/kocQQRregnKKA31I8UlVT7K3eZJNCLbX5cktTmBCMb3Ljm@1TpMEDeZ1adWG30lR8rAg4s0N8SKHLFVBLx/IRmHnySbEWohyOAeXOSj//il2cnIOsu6ll8PEFIpJ1OrDlOOMzX7giZy053z2Rb8mZQ9Git0UFbx@MYsf0SqN0zf9zPkz@olHsYUnhyM4DZs80xqG4NIduYmMmzVyPCraZCUtTyjlcPm83KhGltqA3wsUtFJ/JasV3L/0VjZxu7dxh4doa80Xn4UGi@SF64eu/@1arvAoUPWg22dYRPiY6PQHmbGpdiOb9iBd@eOMiIuLouYIIhtF13tzexy7OJO7LnVJadwb6VzoyPcwBENwPP4H) ]
[Question] [ Write the smallest program you can to create affine fractals. You may use any method you feel like that generates the same results as the rules below. You don't have to use any ideas from the suggested methods! Your program will take two inputs, the first to define the pattern in the format `074` made of three digits from 0 to 7. The second input will define the size, `3` will be 8x8, `4` will be 16x16 and so on (2^n). Your program must output the correct result for all sizes from 0 (1x1) to at least 5 (32x32). If it produces any output for higher numbers it must be correct, i.e. it must produce the correct output up to a certain size but produce no output above that size if it would be wrong. You may assume a maximum size of 15 (32768x32768) as that is already an insane size for ASCII art (1GB)! An 8x8 pattern will look something like below (rule `160`). The left-most digit will be for block `A`, the middle digit (no rude thoughts please!) for block `B` and the right-most digit for block `C`. To construct the fractal, shrink it by a half in both dimensions, and apply the rotation/mirroring rule for the block. To shrink the pattern divide it evenly into 2x2 areas. There will either be 3 visible characters or none in each area. If there are visible characters place a character in the appropriate place in the smaller block, otherwise place a space. Rules `0`-`3` are not mirrored, rules `4`-`7` are mirrored. Rules `0` and `4` are not rotated, `1` and `5` are rotated 90 degrees clockwise, `2` and `6` are rotated 180 degrees, `3` and `7` are rotated 270 degrees clockwise. Stitch the three blocks together in the order shown, `A` in the top-left corner, `B` bottom-left and `C` bottom-right. ``` AAA AA A AA A BBB CC B BBC BBCCC B CCC ``` Shrunk, rotated and mirrored by rule number: ``` 0 1 2 3 4 5 6 7 ---- ---- ---- ---- ---- ---- ---- ---- AA BAA CCB C C BCC AAB AA A BB A CBB CC CC BBC A BB A BBC CC A A BB BB A A CC CBB BCC C AA AAB BAA AA C CCB ``` Rules: 1. Not mirrored, Rotated 90 degrees clockwise 2. Not mirrored, Rotated 180 degrees clockwise 3. Not mirrored, Rotated 270 degrees clockwise 4. Mirrored but not rotated 5. Mirrored then Rotated 90 degrees clockwise 6. Mirrored then Rotated 180 degrees clockwise 7. Mirrored then Rotated 270 degrees clockwise 8. Rule 0: Not mirrored, Not rotated The mirroring is always done first and is done diagonally through the blank corner e.g. rule 0 vs rule 4: ``` 0 4 ---- ---- AA / C / A / CC/ BBC BB A /BCC /BAA ``` Only rules `1`, `6` and `0` are used in the above pattern, in that order. After the transformations have been applied and the blocks stitched together it will look like the below except I have spaced each block from each other by one space. Your code will not have this extra space in it. If you compare it to the "parent" image you will see that it has visible characters in the same positions. ``` BAA BB A CC C AAB AA A BB A CC BBC C BCC ``` Another way to generate the image without shrinking is as follows: Start with one character: ``` X ``` Apply the transformations for each of the three blocks (none since it's only one character) and stitch the blocks together: ``` X XX ``` Apply the transformations for each of the three blocks again: ``` 1 -- XX X 6 0 -- -- XX X X XX ``` Stitch them together: ``` XX X XXX XXX ``` Apply the transformations for each of the three blocks again: ``` 1 ---- XXX XX X XX X 6 0 ---- ---- XXX XX X XX X XX XXX X XXX ``` Stitch them together: ``` XXX XX X XX X XXX XX X XXX XXXXX X XXX ``` You may use any printable character or characters (0x21 - 0x7E) for the visible part of the pattern but only the space character (0x20) for the blanks. Trailing spaces are allowed but there must be no blanks outside the entire square (i.e. for an 8x8 square there can be no characters past column 8). There are 512 different rules, but some of them produce the same pattern. As a side note, any pattern containing only `0` and `4` will produce the Sierpinski triangle (8 different rules). You may optionally post your favourite pattern and the rule that generates it. If you do, make sure the size is at least 3 (8x8) to distinguish it from similar rules. [Answer] # CJam, ~~63 57 54~~ 52 bytes ``` 0aarari*{\f{\~7"W%z"a*3"Wf%"t<s~}({__Ser+}%\~.++}/N* ``` **How it works**: The basic idea is that you run a loop, the second input number of times. In each loop, starting from a single array of array containing `0` (`[[0]]`), we build the fractal for the next step using the three rules, fill the empty quadrant and prepare the quadrants for the next loop. ``` 0aa e# Starting condition, equivalent to a single A ra e# Read the rule string and wrap it in an array ri* e# Repeat the rule array, second input number of times { ... }/ e# Loop for each rule in the rule array e# In each loop, we will have the current fractal and e# then the rule on stack \f{\~7"W%z"a*3"Wf%"t<s~} \f{ } e# Move the rule on top of stack and for each of the rule e# character, run this loop on the current fractal \~ e# Move the rule char on top and convert to int by face value 7"W%z"a*3"Wf%"t e# This is the array which has the logic to perform the rules e# ["W%z" "W%z" "W%z" "Wf%" "W%z" "W%z" "W%z"] <s e# Based on the rule number value, take that many first items e# from the above array and do a toString on the array e# For rule 0 through 7, you will get the following strings: e# 0: "", 1: "W%z", 2: "W%zW%z", 3: "W%zW%zW%z", e# 4: "W%zW%zW%zWf%", 5: "W%zW%zW%zWf%W%z", e# 6: "W%zW%zW%zWf%W%zW%z", 7: "W%zW%zW%zWf%W%zW%zW%z" e# This works because each W%z will rotate the block of e# fractal 90 degrees in clockwise direction. e# For rule 4, where we need to mirror diagonally, we first e# rotate it 279 degrees clock wise and then reverse each row e# of the block. The rest of the rules after 4 take that e# mirroring as base and rotate 90 degrees additionally ~ e# Simply evaluate the string to apply the rule. \f{ ... } e# After this for each loop, we get 3 copies of the fractal e# block before the for loop. Each copy gets each one of the e# three rule gets applied. ({ }% e# We take out the first part corresponding to the 1st e# quadrant and run each row through this loop to fill the e# second quadrant with spaces __Ser e# Take a copy of the row and replace everything in the e# copy with spaces + e# Append it to the original row \~ e# Bring the last two quadrant array on top and unwrap it .+ e# Append corresponding rows from the 4th quadrant to 3rd + e# Append the rows from lower half to the upper half e# Now we have a full block ready to be run through e# the next iteration which will double its size N* e# Finally, we join the rows of final fractal block with e# newlines and automatically print the result ``` [Try it online here](http://cjam.aditsu.net/#code=0aarari*%7B%5Cf%7B%5C~7%22W%25z%22a*3%22Wf%25%22t%3Cs~%7D(%7B__Ser%2B%7D%25%5C~.%2B%2B%7D%2FN*&input=160%203) [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 47 bytes ``` ⊃(⊂⍪⍕#){,/⍪⌿↑1 ¯2↑¨⊂⍺{⍉∘⊖⍣⍺⌽⍉⍣(⍺>3)⌽⍵}¨⍵}⍣⎕⍨⍎¨⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6mrWeNTV9Kh31aPeqcqa1Tr6IGbP/kdtEw0VDq03AtKHVoAV7Kp@1Nv5qGPGo65pj3oXA/mPevaCRHoXawA5dsaaYP7WWqByIAlS0jf1US@Q0wcSmfcfaN3/NC5DMwMuYwA "APL (Dyalog Classic) – Try It Online") ]
[Question] [ This challenge is to compute the most efficient [multiplication order](http://en.wikipedia.org/wiki/Chain_matrix_multiplication) for a product of several matrices. The size of the matrices is specified on a single line of standard input. You should print to standard output a list of integers indicating the order in which to do the multiplications to minimize the total multiplication cost. ## example 1 ### input ``` 5x6 6x12 12x100 100x7 ``` ## output ``` 3 2 1 ``` The input line will be a space-separated list of matrix sizes, each of which is the number of rows, followed by an `x`, followed by the number of columns. For the example, there are 4 matrices to multiply together (so 3 total multiplications), and since matrix multiplication is associative they can be done in any order. The output should be the order in which to perform the multiplications to minimize total cost. This should be a space-separated list of integers representing the index of the multiplication to perform next. For N matrices, this list should contain the numbers 1 through N-1, inclusive. For example 1, the output `3 2 1` means you should do the `12x100 * 100x7` multiplication first, then the `6x12 * 12x7` multiplication (the second matrix times the result of the previous step), then finally the resulting `5x6 * 6x7` multiplication. The matrix multiplications will always be compatible, i.e. the number of columns of a matrix will match the number of rows of the subsequent matrix. Assume the cost of multiplying two matrices `AxB * BxC` is `A*B*C`. Your code must handle lists of up to 100 matrices, each of dimension up to 999, and do so in a reasonable time. ## example 2 ### input ``` 5x10 10x5 5x15 15x5 ``` ### output ``` 1 3 2 ``` or ``` 3 1 2 ``` ## example 3 ### input ``` 22x11 11x78 78x123 123x666 666x35 35x97 97x111 111x20 20x50 ``` ### output ``` 2 3 4 5 6 7 8 1 ``` Note: for verification, the best total cost for the three examples is 9114, 750, and 1466344. Shortest code wins! [Answer] ### Ruby, 176 172 205 characters Here is another version (several chars longer) which will also run for large input in reasonable time. ``` q=(gets.split<<$_[/\d+$/]).map &:to_i r=Hash.new{|h,i|h[i]=Hash.new{|h,j|h[j]=1e12;h[j]=i==j ?[0,[]]:(i...j).map{|k|a,c=r[i][k];b,d=r[k+1][j];[a+b+q[i-1]*q[k]*q[j],c+d+[k]]}.min}} $><<r[1][q.size-1][1]*' ' ``` First version: straight recursive implementation in Ruby. It does a complete search and thus might be slow on large inputs. ``` k=->m{m[2]?(1..m.size-2).map{|l|s=k[m[0,l]+m[l+1..-1]];[m[l-1]*m[l]*m[l+1]+s[0],[l]+s[1].map{|u|u<l ?u:u+1}]}.min: [0,[]]} $><<k[(gets.split<<$_[/\d+$/]).map &:to_i][1]*' ' ``` ]
[Question] [ What general tips do you have for golfing in Chef? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Chef (e.g. "remove unnecessary whitespace" is not an answer). Please post one tip per answer. ]
[Question] [ Find the moves that bring a chess squad to a given destination. You control a chess squad consisting of a king and several other pieces, on a larger chess board. Your army is placed so that no piece is further than K=8 squares away (horizontally and vertically) from your king. You will receive a destination square for the king and you must generate a list of moves for all your pieces so that your king reaches that square and your pieces' final positions will be at the same distances from your final king as the distances between your pieces' initial positions and the initial king. The constraint that no piece can wander further than K=8 squares from the king (in any direction) must be respected at all times. # Inputs and Outputs The board is a matrix of size 41x51, with each cell containing a digit with the following meaning: * 0: empty square * 1: obstacle square * 2: your pawn * 3: your knight * 4: your bishop * 5: your rook * 6: your queen * 7: your king * 8: your final king position * 9: unused Your task is to write a function that, being given a matrix, generates a list of moves, in order, so that the king reaches the final king position and the other pieces reach their final positions, relative to the king. The format of the list should be an array of moves, where the move is an array of the form `[x1, y1, x2, y2]`. See the example solver for details. # Extended Rules * Pawns move one square orthogonally, in any direction * All special moves from chess are invalid in this setting: two-square pawn advance, en passant, pawn promotion, castling * "no-further-than-8" rule: no move that makes a piece become further than 8 squares away from the king (horizontally or vertically) is allowed # Scoring The controller (challenge.html) comes with a battery of 16 test sets. If your solver doesn't output a move list consisting only of valid moves and having the final position of the pieces at their destination fields, you score 10000 for that test. Otherwise, you score the number of moves in your solution. The lowest total score wins. # Controller <https://github.com/altvali/chess_march_challenge> Or, if you want to use the controller directly, without downloading: <https://raw.githack.com/altvali/chess_march_challenge/main/challenge.html> You can open the controller (challenge.html) in your browser and interact with it using your browser's console. No local server required. Use the dropdown to visualize any of the test set positions. You can look at a sample solver implementation in the Javascript of the page. It outputs a hardcoded best solution to the test set 0, but keep in mind that only a general solver is accepted for the contest. Your own solver will have to take as input the data\_map matrix and output the list of valid moves in the same format (explained above). To evaluate your solver, you can type in the browser console the following: ``` evaluate(window.t.test_sets, solver) ``` It will reply with a breakdown of your score, per category, and the total score. To visualize one of your solutions your can use the Move Player. Example using the first test set and the default solver: ``` var move_list = solver(window.t.test_sets[0]) window.mp.load(window.t.test_sets[0], move_list) ``` This will load the map and the moves up to the last valid move. You'll be able to use the Move Player's buttons to interact with your solution. # Submissions Submit your solver function and total score achieved. Remember, the solver must generalize well and your score should be as low as possible. Good luck! ]
[Question] [ [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are: * Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state * Any dead cell with exactly 3 living neighbours becomes a living cell * Any other cell becomes a dead cell Game of Life is known for having simple rules yet structures can quickly become chaotic with minimal change. Consider the following initial state: [![enter image description here](https://i.stack.imgur.com/bSMmf.png)](https://i.stack.imgur.com/bSMmf.png) That is, `TNB` made up of live cells. Each letter has a \$5\times7\$ bounding box, with an empty column in between, for a \$16\times7\$ overall bounding box After 96 generations, it reaches the following state: [![enter image description here](https://i.stack.imgur.com/xfWsz.png)](https://i.stack.imgur.com/xfWsz.png) From this point, no meaningful change will happen: there is 1 still life and 1 oscillator which does not interact with the still life. Now, let's place 2 \$9\times9\$ "areas" on either side: [![enter image description here](https://i.stack.imgur.com/YPEfb.png)](https://i.stack.imgur.com/YPEfb.png) You are to place up to \$81\$ living cells in the red area in a configuration \$C\$, so that, when run, there is at least one generation (the **target generation**) for which the following is true: * The red box is empty (i.e. consists of \$81\$ dead cells) * The configuration in the blue box is equal to \$C\$ * All other cells on the board are dead. For example, let's assume your starting configuration \$C\$ is [![enter image description here](https://i.stack.imgur.com/LGNbJ.png)](https://i.stack.imgur.com/LGNbJ.png) Then, for this to be a valid answer, the following state would have to be reached by at least 1 generation: [![enter image description here](https://i.stack.imgur.com/uPclR.png)](https://i.stack.imgur.com/uPclR.png) (and there's no other living cells on the board) What the board looks like before and after the target generation is irrelevant, so long as at least one generation meets these conditions. Your score is equal to the number of living cells in \$C\$, aiming for fewer cells, with ties being broken by fewest generations until the target generation. [Here](https://copy.sh/life/?gist=33a2995056bd5be6613f28c17db94ba4) is a pre-loaded grid with the red and blue areas outlined --- If this is impossible, I will also accept a proof of impossibility as a valid answer ]
[Question] [ I need to construct a functor that iterates over the linear representation of a sub-lattice of size \$d\_x,d\_y,d\_z,d\_q\$ embedded in a lattice of size \$n\_x,n\_y,n\_z,n\_q\$. The sub-lattice corner is shifted by \$(l\_x,l\_y,l\_z,l\_q)\$. Since the functor can be called million of times, the goal is to produce the most efficient code with the least integer pressure on the CPU. That is, given ten 16-bit unsigned integers \$d\_x,d\_y,d\_z, n\_x,n\_y,n\_z, l\_x,l\_y,l\_z,l\_q\$ with \$d\_x\leq n\_x\$, \$d\_y\leq n\_y\$, and \$d\_z\leq n\_z\$, construct the most efficient function that takes a 64-bit unsigned integer \$0\leq i\lt d\_x\*d\_y\*d\_z\$ and returns a 64-bit unsigned integer \$j\$ such that if $$i=i\_q (d\_z d\_y d\_x) + i\_z (d\_y d\_x) + i\_y d\_x + i\_x$$ then $$j=(i\_q+l\_q)(n\_z n\_y n\_x) + (i\_z+l\_z)(n\_y n\_x) + (i\_y+l\_y)n\_x + (i\_x+l\_x)$$ Winner solution is the one that achieves the stated goal using the least amount of cycles. Solution preferred in x86\_64 assembly (pseudo-code is ok). It is ok to use any instruction that belongs to the instruction set available on Intel/AMD cpus of latest generation (SSE4,SSE3,...). ]
[Question] [ While idly twisting my [Rubik's cube](https://en.wikipedia.org/wiki/Rubik%27s_Cube) around, my son noticed that it kept going back to the solved state. I'm pretty sure he thought this was some sort of voodoo magic at first, but I explained that if you keep repeating the same sequence of moves, it will always return to its original state. *Eventually.* Of course, being a kid, he had to try it out for himself and picked a "random" sequence he thought would be tricky. He lost track after ten repeats or so, and asked me how many times he would have to repeat it. Not knowing the sequence he was using, I told him I didn't know, but that we could write a program to find out. This is where you come in. Of course, I *could* just whip something up, but he'd like to type it in himself. He isn't a very fast typist yet, though, so I need the *shortest program possible*. ### Objective Given a sequence of turns, output the fewest number of times it must be performed to return the cube to its original state. This is code golf, so least bytes wins. You can write a program or function, and all the other usual defaults apply. ### Input Input is a sequence of moves, taken as a string, list, or other format suitable for your language. Feel free to use a separator (or not) between moves if in string form. There are six "basic" moves that must be taken into account, along with their inverses: ``` R - Turn the right face clockwise L - Turn the left face clockwise U - Turn the up (top) face clockwise D - Turn the down (bottom) face clockwise F - Turn the front face clockwise B - Turn the back face clockwise ``` The inverses are represented by adding a prime mark `'` after the letter. This indicates you turn that face counterclockwise, so `F'` turns the front face counterclockwise, and `F F'` would return it to the original state right away. For the interested, this challenge is using a limited set of [Singmaster Notation](http://rubiks.wikia.com/wiki/Notation). Ruwix has [some nice animations](http://ruwix.com/the-rubiks-cube/notation/) if you'd like to see it in action. ### Output Output is simply the minimum number of times the input sequence must be performed. ### Examples ``` Input Output FF' -> 1 R -> 4 RUR'U' -> 6 LLUUFFUURRUU -> 12 LUFFRDRBF -> 56 LF -> 105 UFFR'DBBRL' -> 120 FRBL -> 315 ``` Here's a (quite naive) solver to compare your answers to, written in Java. It also accepts `2` for double moves (so the fourth case is equivalent to `L2U2F2U2R2U2`). ``` import java.util.ArrayList; import java.util.List; public class CycleCounter{ public static void main(String[] args){ int[] cube = new int[54]; for(int i=0;i<54;i++) cube[i] = i; String test = args.length > 0 ? args[0] : "RUR'U'"; List<Rotation> steps = parse(test); System.out.println(steps.toString()); int count = 0; do{ for(Rotation step : steps) cube = step.getRotated(cube); count++; }while(!isSorted(cube)); System.out.println("Cycle length for " + test + " is " + count); } static List<Rotation> parse(String in){ List<Rotation> steps = new ArrayList<Rotation>(); for(char c : in.toUpperCase().toCharArray()) switch(c){ case 'R':steps.add(Rotation.R);break; case 'L':steps.add(Rotation.L);break; case 'U':steps.add(Rotation.U);break; case 'D':steps.add(Rotation.D);break; case 'F':steps.add(Rotation.F);break; case 'B':steps.add(Rotation.B);break; case '\'': steps.add(steps.get(steps.size()-1)); case '2': steps.add(steps.get(steps.size()-1)); break; } return steps; } static boolean isSorted(int[] in){for(int i=0;i<in.length-1;i++)if(in[i]>in[i+1])return false;return true;} enum Rotation{ R(new int[]{-1,-1,42,-1,-1,39,-1,-1,36, -1,-1,2,-1,-1,5,-1,-1,8, 20,23,26,19,-1,25,18,21,24, -1,-1,11,-1,-1,14,-1,-1,17, 35,-1,-1,32,-1,-1,29,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1}), L(new int[]{9,-1,-1,12,-1,-1,15,-1,-1, 27,-1,-1,30,-1,-1,33,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 44,-1,-1,41,-1,-1,38,-1,-1, -1,-1,6,-1,-1,3,-1,-1,0, 47,50,53,46,-1,52,45,48,51}), U(new int[]{2,5,8,1,-1,7,0,3,6, 45,46,47,-1,-1,-1,-1,-1,-1, 9,10,11,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, 18,19,20,-1,-1,-1,-1,-1,-1, 36,37,38,-1,-1,-1,-1,-1,-1}), D(new int[]{-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,24,25,26, -1,-1,-1,-1,-1,-1,42,43,44, 29,32,35,28,-1,34,27,30,33, -1,-1,-1,-1,-1,-1,51,52,53, -1,-1,-1,-1,-1,-1,15,16,17}), F(new int[]{-1,-1,-1,-1,-1,-1,18,21,24, 11,14,17,10,-1,16,9,12,15, 29,-1,-1,28,-1,-1,27,-1,-1, 47,50,53,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,8,-1,-1,7,-1,-1,6}), B(new int[]{51,48,45,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,0,-1,-1,1,-1,-1,2, -1,-1,-1,-1,-1,-1,26,23,20, 38,41,44,37,-1,43,36,39,42, 33,-1,-1,34,-1,-1,35,-1,-1}); private final int[] moves; Rotation(int[] moves){ this.moves = moves; } public int[] getRotated(int[] cube){ int[] newCube = new int[54]; for(int i=0;i<54;i++) if(moves[i]<0) newCube[i] = cube[i]; else newCube[moves[i]] = cube[i]; return newCube; } } } ``` [Answer] # Pyth, ~~66~~ 63 bytes ``` l.uum.rW}Hdd@_sm_B.iFP.>c3Zk3xZHG_r_Xz\'\39Nf!s}RTcZ2y=Z"UDLRFB ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=l.uum.rW%7DHdd%40_sm_B.iFP.%3Ec3Zk3xZHG_r_Xz%5C%27%5C39Nf!s%7DRTcZ2y%3DZ%22UDLRFB&input=RUR%27U%27&test_suite_input=FF%27%0AR%0ARUR%27U%27%0ALLUUFFUURRUU%0ALUFFRDRBF%0ALF%0AUFFR%27DBBRL%27%0AFRBL&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=l.uum.rW%7DHdd%40_sm_B.iFP.%3Ec3Zk3xZHG_r_Xz%5C%27%5C39Nf!s%7DRTcZ2y%3DZ%22UDLRFB&input=RUR%27U%27&test_suite=1&test_suite_input=FF%27%0AR%0ARUR%27U%27%0ALLUUFFUURRUU%0ALUFFRDRBF%0ALF%0AUFFR%27DBBRL%27%0AFRBL&debug=0). Notice that the program is kinda slow and the online compiler is not able to compute the answer for `RU2D'BD'`. But be assured, that it can compute it on my laptop in about 12 seconds. The program (accidentally) also accepts `2` for double moves. ### Full Explanation: **Parse scramble:** First I'll deal with the prime marks `'` in the input strings. I simply replace these with `3` and run-length decode this string. Since Pyth's decoding format requires the number in front of the char, I reverse the string beforehand. `_r_Xz\'\39`. So afterwards I reverse it back. **Describe the solved cube state:** `=Z"UDLRFB` assigns the string with all 6 moves to `Z`. We can describe a cube state by describing the location for each cube piece. For instance we can say that the edge, that should be at UL (Up-Left) is currently at FR (Front-Right). For this I need to generate all pieces of the solved cube: `f!s}RTcZ2yZ`. `yZ` generates all possible subsets of `"UDLRFB"`. This obviously also generates the subset `"UDLRFB"` and the subset `"UD"`. The first one doesn't make any sense, since there is no piece that is visible from all 6 sides, and the second one doesn't make any sense, since there is no edge piece, that is visible from the top and the bottom. Therefore I remove all the subsets, that contain the subsequence `"UD"`, `"LR"` or `"FB"`. This gives me the following 27 pieces: ``` '', 'U', 'D', 'L', 'R', 'F', 'B', 'UL', 'UR', 'UF', 'UB', 'DL', 'DR', 'DF', 'DB', 'LF', 'LB', 'RF', 'RB', 'ULF', 'ULB', 'URF', 'URB', 'DLF', 'DLB', 'DRF', 'DRB' ``` This also includes the empty string and all the six 1-letter strings. We could interpret them as the piece in the middle of the cube and the 6 center pieces. Obviously they are not required (since they don't move), but I'll keep them. **Doing some moves:** I'll do some string translations to perform a move. To visualize the idea look at the corner piece in `URF`. What happens to it, when I do an `R` move? The sticker on the `U` face moves to the `B` face, the sticker `F` moves to the `U` face and the sticker on the `R` face stays at the `R` face. We can say, that the piece at `URF` moves to the position `BRU`. This pattern is true for all the pieces on the right side. Every sticker that is on the `F` face moves to the `U` face when an `R` move is performed, every sticker that is on the `U` face moves to the `B` face, every sticker on the `B` moves to `D` and every sticker on `D` moves to `F`. We can decode the changes of an `R` move as `FUBD`. The following code generates all the 6 necessary codes: ``` _sm_B.iFP.>c3Zk3 ['BRFL', 'LFRB', 'DBUF', 'FUBD', 'RDLU', 'ULDR'] ^ ^ ^ ^ ^ ^ U move D move L move R move F move B move ``` And we perform a move `H` to the cube state `G` as followed: ``` m.rW}[[email protected]](/cdn-cgi/l/email-protection) m G map each piece d in G to: .rW d perform a rotated translation to d, but only if: }Hd H appears in d (d is currently on the face H) xZH get the index of H in Z @... and choose the code in the list of 6 (see above) ``` **Count the number of repeats:** The rest is pretty much trivial. I simply perform the input scramble to the solved cube over and over until I reach a position that I previously visited. ``` l.uu<apply move H to G><parsed scramble>N<solved state> u...N performs all moves of the scramble to the state N .u... do this until cycle detected, this returns all intermediate states l print the length ``` [Answer] # GAP, ~~792 783 782~~ ~~749~~ 650 Bytes This seems to be working. If it messes up with something let me know. Thanks to @Lynn for suggesting that I decompose some of the primitive moves. Thanks to @Neil for suggesting that instead of `Inverse(X)` I use `X^3`. Usage example: `f("R");` ``` R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17);L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31);U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38);A:=R*L^3*F*F*B*B*R*L^3;D:=A*U*A;;F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45);B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12);d:=NewDictionary((),true);AddDictionary(d,'R',R);AddDictionary(d,'L',L);AddDictionary(d,'U',U);AddDictionary(d,'D',D);AddDictionary(d,'F',F);AddDictionary(d,'B',B);f:=function(s) local i,p,b,t;p:=(); for c in s do if c='\'' then t:=t^2;else t:=LookupDictionary(d,c);fi;p:=p*t;od;return Order(p);end; ``` Here is the ungolfed code with a bit of explanation ``` # Here we define the primitive moves R:=(3,39,21,48)(6,42,24,51)(9,45,27,54)(10,12,18,16)(13,11,15,17); L:=(1,46,19,37)(4,49,22,40)(7,52,25,43)(30,36,34,28)(29,33,35,31); U:=(1,10,27,28)(2,11,26,29)(3,12,25,30)(37,43,45,39)(40,44,42,38); #D:=(7,34,21,16)(8,35,20,17)(9,36,19,18)(48,46,52,54)(47,49,53,51); F:=(1,3,9,7)(2,6,8,4)(10,48,36,43)(13,47,33,44)(16,46,30,45); B:=(27,25,19,21)(26,22,20,24)(39,28,52,18)(38,31,53,15)(37,34,54,12); # Here we define D in terms of other primitive moves, saving on bytes # Thanks @Lynn # This is actually doable with a maximum of 3 of the primitive moves # if a short enough sequence can be found. D:=U^(R*L^3*F*F*B*B*R*L^3); # create dictionary and add moves to it with appropriate char labels d:=NewDictionary((),true); AddDictionary(d,'R',R); AddDictionary(d,'L',L); AddDictionary(d,'U',U); AddDictionary(d,'D',D); AddDictionary(d,'F',F); AddDictionary(d,'B',B); f:=function(s) local c,p,t; # p will become the actual permutation passed to the function p:=(); for c in s do if c='\'' then # The last generator we mutiplied (that we still have in t) # should have been its inverse. Compensate by preparing to # multiply it two more times to get t^3=t^-1. Thanks @Neil. t:=t^2; else t:=LookupDictionary(d,c); fi; p:=p*t; od; return Order(p); end; ``` [Answer] # Mathematica, ~~413~~ 401 bytes ``` Evaluate[f/@Characters@"RFLBUD"]=LetterNumber@"ABFEJNRMDAEHIMQPCDHGLPTOBCGFKOSNADCBILKJEFGHQRST"~ArrayReshape~{6,2,4}; r[c_,l_]:=(b=Permute[c,Cycles@f@l];MapThread[(b[[#,2]]=Mod[b[[#,2]]+{"F","B","L","R"}~Count~l{-1,1,-1,1},#2])&,{f@l,{3,2}}];b); p@s_:=Length[c={#,0}&~Array~20;NestWhileList[Fold[r,#,Join@@StringCases[s,x_~~t:""|"'":>Table[x,3-2Boole[t==""]]]]&,c,(Length@{##}<2||c!=Last@{##})&,All]]-1 ``` --- **Explanations** A Rubik's Cube is made up with 20 movable **cubies** (8 corners, 12 edges). Each cubie can be given a number: *corners*: ``` N starting position 1 UFR 2 UBR 3 UBL 4 UFL 5 DFR 6 DBR 7 DBL 8 DFL ``` *edges*: ``` N starting position 9 UF 10 UR 11 UB 12 UL 13 FR 14 BR 15 BL 16 FL 17 DF 18 DR 19 DB 20 DL ``` Note that when the cube is twisted, the cubies are generally not on their starting positions any longer. For example, when `R` is done, the cubie `1` moves from `UFR` to a new position `UBR`. In such notation, a 90 degree turn can be described by 8 movements of cubies. For example, `R` is described by ``` from to UFR UBR UBR DBR DBR DFR DFR UFR UR BR BR DR DR FR FR UR ``` Since each cubie has a unique starting position, each position has a unique starting cubie. That is to say, rule `UFR->UBR` is just `1->2` (means that `R` takes the cubie on the starting position of cubie `1` to the starting position of cubie `2`). Thus, `R` can be simplified further to a cycle ``` Cycles[{{1,2,6,5}, {10,14,18,13}}] ``` --- To fully solve a Rubik's Cube, we also need to align the cubies to their corresponding starting orientations. The faces of a cube is painted in different colors, the scheme that I often use when solving cubes is ``` face color U yellow D white F red B orange R green L blue ``` When we analyzing the orientations of corners, colors other than yellow or white are ignored, and yellow and white are considered as the same color. Suppose cubie `1` is on its starting position `UFR`, the yellow facet may be aligned to three different faces. We use an integer to represent these cases, ``` 0 yellow on U (correct) 1 yellow on R (120 degree clockwise) 2 yellow on F (120 degree counterclockwise) ``` Suppose cubie `1` is on `DFL`, its three possible orientations are ``` 0 yellow on D (correct) 1 yellow on L (120 degree clockwise) 2 yellow on F (120 degree counterclockwise) ``` When we analyzing the orientations of edges, red and orange are ignored, and yellow and white are ignored only if the edge has a green or blue facet. Suppose cubie `10` is on its starting position `UR`, the green facet may be aligned to two different faces. Its two possible orientations are ``` 0 green on R (correct) 1 green on U (180 degree) ``` Suppose cubie `10` is on `DF`, its two possible orientations are ``` 0 green on D (correct) 1 green on F (180 degree) ``` --- An array is used to store the state of a cube. The starting state of a cube is ``` {{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0},{9,0},{10,0},{11,0},{12,0},{13,0},{14,0},{15,0},{16,0},{17,0},{18,0},{19,0},{20,0}} ``` which means that every cubies are on their starting position with correct orientation. After `R`, the state of the cube becomes ``` {{5,2},{1,1},{3,0},{4,0},{6,1},{2,2},{7,0},{8,0},{9,0},{13,1},{11,0},{12,0},{18,1},{10,1},{15,0},{16,0},{17,0},{14,1},{19,0},{20,0}} ``` which means that cubie `5` is now on position `1` (`UFR`) with orientation `2`, cubie `1` is now on position `2` (`UBR`) with orientation `1`, cubie `3` is now still on position `3` (`UBL`) with orientation `0`, and so on. --- **Test cases** ``` p["FF'"] (* 1 *) p["R"] (* 4 *) p["RUR'U'"] (* 6 *) p["LLUUFFUURRUU"] (* 12 *) p["LUFFRDRBF"] (* 56 *) p["LF"] (* 105 *) p["UFFR'DBBRL'"] (* 120 *) p["FRBL"] (* 315 *) ``` [Answer] # Haskell, 252 bytes ``` r=[-2..2] s=mapM id[r,r,r] t m p@[x,y,z]=case m of"R"|x>0->[x,z,-y];"L"|x<0->[x,-z,y];"U"|y>0->[-z,y,x];"D"|y<0->[z,y,-x];"F"|z>0->[y,-x,z];"B"|z<0->[-y,x,z];c:"'"->t[c]$t[c]$t[c]p;_->p f m=length$s:fst(span(/=s)$tail$iterate(flip(foldl$flip$map.t)m)s) ``` Sample runs: ``` *Main> f ["F","F'"] 1 *Main> f ["R"] 4 *Main> f ["R","U","R'","U'"] 6 *Main> f ["L","L","U","U","F","F","U","U","R","R","U","U"] 12 *Main> f ["L","U","F","F","R","D","R","B","F"] 56 *Main> f ["L","F"] 105 *Main> f ["U","F","F","R'","D","B","B","R","L'"] 120 *Main> f ["F","R","B","L"] 315 *Main> f ["R","U","U","D'","B","D'"] -- maximum possible order 1260 ``` The key observation here is that it’s simpler to model the Rubik’s cube as a 5×5×5 grid of points rather than a 3×3×3 grid of oriented cubies. Corner cubies become cubes of 2×2×2 points, edge cubies become squares of 2×2×1 points, and moves rotate slices of 5×5×2 points. [Answer] # Ruby, 225 bytes ``` ->s{n=0 a=[] b=[] 64.times{|i|a<<j=[(i&48)-16,(i&12)-4,i%4-1];b<<j*1} d=1 (n+=1 s.reverse.chars{|c|m="UFRDBL".index(c) m ?(e=m/3*2-1 b.each{|j|j[m%=3]*e>0&&(j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)} d=1):d=-1})until n>0&&a==b n} ``` Similar to Anders Kaseorg's answer and inspired by Jan Dvorak's [answer](https://codegolf.stackexchange.com/a/44775/15599) to a previous question. However unlike those answers, I don't need 125 cubies. I use a rubik's cube of 27 cubies, but rectangular dimensions. In the solved state the corners are at `+/-1,+/-4,+/-16`. I generate an array of 64 cubies, each with a centre chosen from `x=[-1,0,1,2], y=[-4,0,4,8], z=[-16-0,16,32]`. The cubies with coordinates of 2, 8 and 32 are unnecessary, but they do no harm, so they are left in for golfing reasons. The fact that the length, width and depth of the cubies are different: (1,4,16) means it is easy to detect if they are in the right place but with wrong orientation. Each cubie is tracked as it is moved by the faceturns. If the coordinate of a cubie in the axis corresponding to the face (multiplied by `e=-1` for U,F,R or `e=1` for D,B,L) is positive, then it will be rotated by swapping the coordinates in the other 2 axis and applying an appropriate sign change to one of the coordinates. This is controlled by multiplying by `e*d`. The input sequence is scanned in reverse order. This makes no difference, so long as the "normal" rotations are performed anticlockwise instead of clockwise. The reason for this is so that if a `'` symbol is found, the value of `d` can be changed from 1 to -1 in order to cause rotation of the following face in the opposite direction. **Ungolfed in test program** ``` f=->s{n=0 #number of repeats=0 a=[] #empty array for solved position b=[] #empty array for current position 64.times{|i| a<<j=[(i&48)-16,(i&12)-4,i%4-1] #generate 64 cubies and append them to the solved array b<<j*1 #duplicate them and append to active array } d=1 #default rotation direction anticlockwise (we scan the moves in reverse) ( #start of UNTIL loop n+=1 #increment repeat counter s.reverse.chars{|c| #reverse list of moves and iterate through it m="UFRDBL".index(c) #assign move letter to m (for ' or any other symbol m is false) m ? #if a letter (e=m/3*2-1 #e=-1 for UFR, 1 for DBL b.each{|j| #for each cubie j[m%=3]*e>0&& #m%=3 picks an axis. If the cubie is on the moving face of the cube (j[m-2],j[m-1]=j[m-1]*e*d,-j[m-2]*e*d)#rotate it: exchange the coordinates in the other 2 axes and invert the sign of one of them according to direction } #as per the values of e and d. d=1 #set d=1 (in case it was -1 at the start of the b.each loop) ): d=-1 #ELSE the input must be a ', so set d=-1 to reverse rotation of next letter } )until n>0&&a==b #end of UNTIL loop. continue until back at start position a==b n} #return n p f["FF'"] # 1 p f["R"] # 4 p f["RUR'U'"] # 6 p f["LLUUFFUURRUU"] # 12 p f["LUFFRDRBF"] # 56 p f["LF"] # 105 p f["UFFR'DBBRL'"] # 120 p f["FRBL"] # 315 ``` [Answer] # Python 2, 343 bytes ``` def M(o,v,e): k=1 for m in e: for c in'ouf|/[bPcU`Dkqbx-Y:(+=P4cyrh=I;-(:R6'[m::6]:i=~ord(c)%8*k;j=(ord(c)/8-4)*k;o[i],o[j]=o[j]-m/2,o[i]+m/2;v[i],v[j]=v[j],v[i];k=-k V=range(20) o,v,e=[0]*20,V[:],[] for c in raw_input():i='FBRLUD'.find(c);e+=i<0and e[-1:]*2or[i] M(o,v,e);n=1 while any(o[i]%(2+i/12)for i in V)or v>V:M(o,v,e);n+=1 print n ``` Input is taken from stdin. The given sequence of twists is performed repeatedly on a virtual cube until it returns to the solved state. The cube state is stored as an orientation vector and permutation vector, both of length 20. Orientations are somewhat arbitrarily defined: an edge cubie is oriented correctly if it can be moved into place without invoking an R or L quarter turn. The orientation of the corner cubies is considered relative to the F and B faces. --- **Sample Usage** ``` $ echo FRBL|python rubiks-cycle.py 315 $ echo RULURFLF|python rubiks-cycle.py 1260 ``` [Online Demonstration](http://rextester.com/YEVV53248) and [Test Suite](http://rextester.com/YUDCN56828). [Answer] # [Cubically](//git.io/Cubically), ~~9~~ 6 bytes ``` ¶-7)8% ``` [Try it online!](https://tio.run/##Sy5NykxOzMmp/P//0DZdc00L1f//gwA) (Nonworking until Dennis updates the TIO Cubically interpreter) Explanation: ``` ¶-7)8% ¶ read a string, insert into code -7 add 1 to notepad (subtracts the 7th face "sum" from notepad, defaulted to -1) )8 jump back to start of code if cube unsolved % print notepad ``` This language will dominate all [rubiks-cube](/questions/tagged/rubiks-cube "show questions tagged 'rubiks-cube'") challenges >:D [Answer] ## Clojure, 359 bytes This might be my 2nd longest codegolf. Realizing I could drop trailing zeros from vectors `A` to `F` made me very happy :D ``` #(let[I(clojure.string/replace % #"(.)'""$1$1$1")D(range -2 3)S(for[x D y D z D][x y z])A[0 1]B[0 0 1]C[1]D[-1]E[0 -1]F[0 0 -1]](loop[P S[[n R]& Q](cycle(map{\F[A[B A D]]\B[E[F A C]]\L[D[C B E]]\R[C[C F A]]\U[B[E C B]]\D[F[A D B]]}I))c 0](if(=(> c 0)(= P S))(/ c(count I))(recur(for[p P](if(>(apply +(map * n p))0)(for[r R](apply +(map * r p)))p))Q(inc c))))) ``` Less golfed: ``` (def f #(let [I (clojure.string/replace % #"(.)'""$1$1$1") D [-2 -1 0 1 2] S (for[x D y D z D][x y z]) L {\F [[ 0 1 0][[0 0 1][ 0 1 0][-1 0 0]]] \B [[ 0 -1 0][[0 0 -1][ 0 1 0][ 1 0 0]]] \L [[-1 0 0][[1 0 0][ 0 0 1][ 0 -1 0]]] \R [[ 1 0 0][[1 0 0][ 0 0 -1][ 0 1 0]]] \U [[ 0 0 1][[0 -1 0][ 1 0 0][ 0 0 1]]] \D [[ 0 0 -1][[0 1 0][-1 0 0][ 0 0 1]]]}] (loop [P S c 0 [[n R] & Q] (cycle(map L I))] (if (and (> c 0) (= P S)) (/ c (count I)) (recur (for[p P](if(pos?(apply +(map * n p))) (for[r R](apply +(map * r p))) p)) (inc c) Q))))) ``` This simply implements 3D rotations of selected subsets of `5 x 5 x 5` cube. Originally I was going to use `3 x 3 x 3` and it took me a while to realize why I wasn't getting correct results. Good test cases! Some extra bytes for fist encoding `"RUR'U'"` as `"RURRRUUU"`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 255 bytes Derived separately from the almost-identical Haskell answer as an answer to [this question](https://codegolf.stackexchange.com/questions/178276/order-of-elements-of-the-rubiks-cube) which was closed as a duplicate when it was almost finished, so I posted the answer here. ``` import StdEnv,StdLib a=[-2..2];b=diag3 a a a ?m=iter(size m*2-1)\p=:(x,y,z)=case m.[0]of'F'|z>0=(y,~x,z);'U'|y>0=(~z,y,x);'R'|x>0=(x,z,~y);'B'|z<0=(~y,x,z);'D'|y<0=(z,y,~x);'L'|x<0=(x,~z,y);_=p $l=length(takeWhile((<>)b)(tl(iterate(map(sseq(map?l)))b)))+1 ``` [Try it online!](https://tio.run/##LZBda4MwFIbv@yukFJJsUaxjN7NpobjBoFctZRddGammNSxRV7OhIv70ZSd2hHw973lCklQJXlhdZt9KeJrLwkpdlVfj7Uz2XPxQmDbyNOHs4EdBEB3jE8skvzx43LXJSjNpxBXXsgP9LvLn5L1iT7ihLe0IS3kNODiEx/KMXlDfLUOGWzo0EMZoj/rWgaGD6gbAFvWNAxDToQWwBmXhKiAflQQUB5wxOGUDymJU3Ckk/mDVZKaYEsXF5NjwT/GWSyUwXizJiWCjsLsvNwJrXuG6Fl9usVKEQEzI/dzuDIfnM2/mHabbKZ3u/3uCYFjfFkf7m54Vv9TWf93YpC24lilscvsYhnqEt4/7Aw "Clean – Try It Online") ]
[Question] [ [Fairy Chess](https://en.wikipedia.org/wiki/Fairy_chess_piece) is a sort of generalized chess that allows unconventional pieces. [The eight queens puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle) is a classic problem where you have to put 8 queens on a chess board such that no two queens threaten each other. This challenge is sort of a generalized combination of the two. # Challenge Given a list of fairy chess pieces and their quantities, output a board such that all pieces are used and no piece threatens any other piece. The board is not directional and all pieces have symmetric movement. **Your goal is to generate a solution on the smallest, squarest board you can in under 30 seconds.** ## Pieces Each piece has a list of valid move types. For the sake of simplicity, moves will be one of the following types: * Leaper movement. A generalized form of knights. A leaper has two numbers, `m` and `n` that describe its movement. A leaper moves `m` spaces in one orthogonal direction and then `n` in a direction perpendicular to the other, "leaping" over intervening spaces. * Rider movement. Moves in a straight line. Can be unlimited or restricted to a specific range. Can either be orthogonal or diagonal. It is possible for a piece to be in a rider's movement range without being threatened by it if there is a piece blocking its path that is too close to be captured. For instance, a 3-5 orthogonal rider could be blocked from taking a piece 4 spaces away if a non-threatening piece was one space away along the path * Hopper movement. Hoppers are similar to riders in that they travel in a straight line, but they are different in that they have to "hop" over a piece to take the piece on the other side of the hopped-over piece. As such, they can only capture the second piece along a line of movement. Hoppers may also have minimum and maximum range. How these are to be represented in the input is up to the implementation. ### Piece Examples A 3-1 leaper moves like this: (`x` represents spaces that can be moved to) ``` . . x . x . . . . . . . . . x . . . . . x . . . L . . . x . . . . . x . . . . . . . . . x . x . . ``` *Note: in the following diagrams, rather than make a full diagram for each possible interaction, each row in the diagram represents one direction along the movement path.* A 3-5 hopper moves like this in each direction (`O` represents another piece that cannot be taken) ``` H . . . . . . H O . x x x . H . O x x x . H . . O x x . H . . . O x . H . . . . O . H . . . . . O ``` Limited range on riders can have interesting effects when they have a minimum range. A 3-5 rider behaves in an interesting way when a piece is blocking its path to the minimum range. (`X` represents another piece that *can* be taken.) ``` R . . x x x . R O . . . . . R . O . . . . R . . X . . . R . . x X . . R . . x x X . R . . x x x X ``` Hoppers can only take the *second* piece along their travel path. Once again, with the 3-5 range hopper: ``` H . . . . . . H O O . . . . H O O . . O . H . O x X . . H . . O X . . H . . . O x . H . . . . O O H . O . . . O ``` ### Input Your program input will be passed via stdin in lines of plain text, where each line describes the piece type and the number of instances of that piece. It follows this general format: `<Letter><copies, decimal>: <movements, comma separated>` Movements follow this format: * Leaper: `Lmn`, where `m` and `n` are decimal digits representing the distances in each direction of movement. * Rider: `Rdmn`, where `d` is `+` or `x` for orthogonal or diagonal, respectively; and where `m` and `n` are decimal digits representing the minimum and maximum distance, respectively. `n` may also be `-`, indicating there is no maximum range. * Hopper: `Hdmn`, where `d`, `m`, and `n` have the same meanings as for riders. ### Output Your program should output to stdout with each row of the board on each line. The letters in the piece definitions input should be used to represent each piece type and dots (`.`) should be used to represent empty spaces on the board. Whitespace between board spaces are optional and will be ignored by the test driver. All solutions shown in the examples section are in a valid format. # Coding Your solution should be a program that reads definitions from stdin (as a redirected file) and outputs boards to stdout. Logging, should you choose to use it, should go through stderr, as that is not captured by the test driver. An example baseline solver can be found [here](https://github.com/Beefster09/pcg-general/blob/master/fairy-solver). It's not very smart, but it does a decent job at making compact boards. There is room for improvement. # Scoring Your solution will be scored across 10 test cases (below) and each run will be scored with the following formula: `score = height **2 + width ** 2` This will be totaled across all solutions. **Lowest score wins**. All boards returned must be valid solutions and be calculated in under 15 seconds or else your solution will be disqualified. Ties will be broken by first solution posted. A test driver that scores solutions automatically can be found [here](https://github.com/Beefster09/pcg-general/blob/master/fairy-chess). You will need Python 3.5+ to run it. There are no third-party dependencies. # Examples With the input: ``` A2: L21 B1: Rx1- C2: H+1- ``` You have these pieces: * (`A`) 2 Knights (2-1 Leapers) * (`B`) 1 Unlimited-range diagonal rider * (`C`) 2 Unlimited-range orthogonal hoppers A valid solution is: ``` A . A B . . . . . . C . . . C ``` This solution would score 34 points (3\*3 + 5\*5 = 9 + 25 = 34) --- With the input: ``` A5: L32 B1: R+1-,Rx1-,L21 C2: H+3- D4: Rx14,L30 ``` You have these pieces: * (`A`) 5 3-2 Leapers * (`B`) 1 Unlimited-range 8-way rider with 2-1 Leaps (a queen and knight combined) * (`C`) 2 Range 3+ orthogonal hoppers * (`D`) 4 Range 4- diagonal riders with 3-0 leaps A valid solution is: ``` . . . . . . . . . B A . . . . D . . . . . . . . . . . . . . . . . . . . . . D . . . . C D . . . . . . . . . . . . . A . . . . . D . . . . . A . . . . . . . . . . . . C A . . . . . . . . . . A . . . . ``` This solution would score 200 points (10\*10 + 10\*10 = 100 + 100 = 200) # Test Cases The following test cases will be used for scoring: ### 8 Queens ``` Q8: R+1-,Rx1- ``` ### Standard Chess Set (without pawns) ``` K2: L10,L11 Q2: R+1-,Rx1- R4: R+1- B4: Rx1- N4: L21 ``` ### 10 Amazons ``` A10: R+1-,Rx1-,L21 ``` ### Compound Pieces ``` K2: L10,L11 A2: R+1-,Rx1-,L21 R4: R+1-,L11 B4: Rx1-,L10 C4: R+1-,L21 P4: Rx1-,L21 ``` ### Archbishops and Super Rooks ``` B14: Rx1-,L10 R8: R+1-,L11 ``` ### Wazirs and Ferzes ``` W21: L10 F24: L11 ``` ### 10 Lords-A-Leaping (x3) ``` W3: L10 F3: L11 D3: L20 N3: L21 A3: L22 H3: L30 L3: L31 J3: L32 G3: L33 X3: L40 ``` ### 20 Frog Queens ``` A20: H+1-,Hx1- ``` ### Things are Really Hoppin' ``` A12: Hx36 B8: H+36 C6: H+2- D10: Hx2- ``` ### Blindspots ``` A6: R+36,L22 B16: Hx59 C10: L21,L33 D6: Rx22,R+44 E6: H+47,L31 F8: H+22,Hx22 ``` # Rules and Notes * No abusing standard loopholes * Your program will be limited to running on a single CPU * Final scoring will be done on my 2.8 GHz i5, using Windows Subsystem for Linux * You may assume input files are valid. * You may assume that leapers will never be `L00` so that you never have to check for self-threatening. * There is no hard limit on the size of board in a calculated solution. All that matters is that it is a valid solution. tl;dr: Programs should try to make boards as small and as square as possible in less than 30 seconds. **Lowest Score Wins**. *Ties will be broken by first solution posted*. Once again, the test driver can be found [here](https://github.com/Beefster09/pcg-general/blob/master/fairy-chess) ]
[Question] [ The barbells at my gym look like this: ``` =========[]-----------------------[]========= ``` They can hold plates of five different sizes, 2.5 pounds, five pounds, ten pounds, 25 pounds, and 45 pounds: ``` . . ! | . ! | | | | | | | | ' ! | | | ' ! | ' ``` For safety, we also add a clip `]` or `[` on the outside of all of our plates if there are any. The bar itself weighs 45 pounds. We always put the heaviest plates closest to the center, with no gaps between any plates, and put identical plates on both sides. We also always use the minimum number of plates possible, e.g. we never use two five-pound plates on one side instead of a single ten-pound plate. So if I want to lift 215 pounds, my bar looks like this: ``` . . .!| |!. !||| |||! ====]||||[]-----------------------[]||||[==== !||| |||! '!| |!' ' ' ``` Your code, a function or complete program, must take an integer from 45 to 575, always a multiple of 5, and output the bar that adds up to that weight. For example: Input: `45` Output (note there are no clips on an empty bar): ``` =========[]-----------------------[]========= ``` Input: `100` Output: ``` ! ! .| |. ======]||[]-----------------------[]||[====== '| |' ! ! ``` Input: `575` Output: ``` ..... ..... .!||||| |||||!. !||||||| |||||||! ]||||||||[]-----------------------[]||||||||[ !||||||| |||||||! '!||||| |||||!' ''''' ''''' ``` You can have trailing spaces on each line or not, but your output cannot have leading or trailing empty lines (the output for 45 should be one line, for 50 should be three lines, for 65 should be five lines, and so on.) This is code golf, shortest code wins! [Answer] # Python 2, 295 bytes ``` i=input()-45 w=90,50,20,10,5;p=".|||||'"," !|||! "," .|||' "," !|! "," .|' " a=[' '*46] b=zip(*a*3+['='*9+'[]'+'-'*24+'[]'+'='*9]+a*3) v=8 j=0 while i: if i>=w[j]:i-=w[j];b[v]=b[-v-1]=p[j];v-=1 else:j+=1 if v<8:b[v]=b[10];b[-v-1]=b[9] for l in zip(*b): L=''.join(l).rstrip() if L:print L ``` Builds the bar vertically, then rotates and prints non-empty lines. [Answer] # Pyth, 126 bytes ``` K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTSSM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"jC"¾ª±À£¤¯aàI7"6 ``` The source code contains unprintable characters, so here it is as an XXD dump: ``` 0000000: 4b5b 5a35 5479 5435 3020 3930 296a 6672 K[Z5TyT50 90)jfr 0000010: 5436 2e65 3a3a 2b2b 4a2b 3f71 6b33 5c3d T6.e::++J+?qk3\= 0000020: 6473 6d40 6278 4b64 6866 7151 2b34 3573 dsm@bxKdhfqQ+45s 0000030: 5453 534d 5e4b 383f 716b 3372 225b 5d32 TSSM^K8?qk3r"[]2 0000040: 332d 5b5d 2239 2a32 3764 5f4a 223d 5c7c 3-[]"9*27d_J"=\| 0000050: 2222 5d7c 2222 5c7c 3d22 227c 5b22 6337 ""]|""\|=""|["c7 0000060: 7340 4c22 2e20 217c 3d27 226a 4322 04be s@L". !|='"jC".. 0000070: aa1f b1c0 a3a4 81af 61e0 4937 2236 ........a.I7"6 ``` This code is **extremely slow**, to the point of no actual use. You can speed it up by about 1000 times by adding a `.{` (`set`) call in between, while keeping the code functionally equivalent. Here's a copy-paste friendly version of the resulting code: ``` K[Z5TyT50 90)jfrT6.e::++J+?qk3\=dsm@bxKdhfqQ+45sTS.{SM^K8?qk3r"[]23-[]"9*27d_J"=\|""]|""\|=""|["c7s@L". !|='"j96235640060099376576144045263159 6 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes ``` ¹²[]P×=⁹≔⁻N⁴⁵θWΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ«P|§⪪”{⊞⧴&β1←Z↶RΣ”,Lι→P[≧⁻⊟ιθ»‖B← ``` [Try it online!](https://tio.run/##TU9NT4NAED2XX7Hd02yymraRmNJ4qAdNk9I01XghPSAdYOJ2QViqRvztOMBBk53NfLx5816Sx1VSxKbr9hVZB/OFWnljKqOj5CJsjKNy6DzTGWuQd1KLpeLRuq4psxCSbWrY2LJxu@b8ihUoLW58/t4Z9JGTQQEPZBxPIl@L@UyLBYfPsZwdtdgVDh4rjHvAW7@llPj2Jv8uBy9YOUpio8XabewJP@GpNMQi27a91v2b6iFrp6xOasnXt2gzlwOpXuskLC4IwYGy3A3lH7mM5NCJy9HQgBldabEvSmYYrfx4B0wNJu6@caw1NV8QbDFlvq7zb/3u6mJ@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ¹²[]P×=⁹ ``` Print 12 `-`s, the `[]` and 9 `=`s. This comprises half of the bar. The cursor is left at the beginning of the `=`s. ``` ≔⁻N⁴⁵θ ``` Subtract 45 from the input to allow for the weight of the bar. ``` WΦ⟦⁵χ²⁰¦⁵⁰¦⁹⁰⟧¬›κθ« ``` Filter a list of the possible weights of pairs of weights for those that are not greater than the input, and repeat while the list is not empty. ``` P|§⪪”{⊞⧴&β1←Z↶RΣ”,Lι ``` Split the string `|||.,|.,|!,||.,||!` on commas and select the piece corresponding to the heaviest possible weight, and print it both upwards and downwards. (Alternatively, it's possible to just print it upwards and reflect in the `¬` direction at the end; a number of variations have the same length.) ``` →P[ ``` Print the clip (will get overwritten by the next weight if any). ``` ≧⁻⊟ιθ» ``` Subtract the weight from the input. ``` ‖B← ``` Reflect to complete the barbell. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/6284/edit). Closed 6 years ago. [Improve this question](/posts/6284/edit) Back when I was a freshman in highschool taking chemistry, I'd look at the periodic table of elements and spell dirty words out with the number of the elements (HeCK would be 2619, 2-6-19). I was thinking about this the other day when I saw an amazing shirt that spelled out BeEr (4-68) So my codegolf challenge is shortest program to output a list of words you can spell with the periodic table of elements AND the number code that would represent that word. /usr/share/dict/words or whatever dictionary you want to use for the word list. If you're using a "non-standard" word list, let us know what it is! [Answer] ## GolfScript (339 303 302 301 294 chars) ``` n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAl PSClArKCa TiVCrMnFe ZnGaGeAsSeBrKrRbSrYZr MoTcRuRhPdAgCd TeIXe BaLaCePrNdPmSmEuGdTbDy ErTm Lu TaWRe IrPtAuHgTl AtRnFrRaAcThPaU AmCm EsFmMd LrRfDbSg MtDsRg UutFl Lv'{[1/{.0=96>{+}*}/]}:S~:^/}%.{L}%2$?.){=S{^?}%`+p 0}{;{L.,2$<=},.}if}do}%; ``` With credit to [PhiNotPi](https://codegolf.stackexchange.com/users/2867/phinotpi) whose observation on unnecessary elements allowed me to save 33 chars. This is IMO much more idiomatic GolfScript than the previous recursive approach. Note that I allow words in the dictionary to be mixed case (`L` is a function to lower-case text on the assumption that it doesn't matter if non-alpha characters get broken) but reject any with apostrophes or accents. Since this is code golf, I've optimised for code length rather than speed. This is horrendously slow. It expects the word list to be supplied at stdin and outputs to stdout in the format: ``` "ac[89]" "accra[89 6 88]" "achebe[89 2 4]" ... ``` (lower-casing any mixed-case input words for which it finds a match). If you're more interested in the elements than the numbers per se, for the low low price of 261 253 chars you can use ``` n/{{{32|}%}:L~['']{{`{\+}+'HHeLiBeBCNOFNeNaMgAlPSClArKCaTiVCrMnFeZnGaGeAsSeBrKrRbSrYZrMoTcRuRhPdAgCdTeIXeBaLaCePrNdPmSmEuGdTbDyErTmLuTaWReIrPtAuHgTlAtRnFrRaAcThPaUAmCmEsFmMdLrRfDbSgMtDsRgUutFlLv'[1/{.0=96>{+}*}/]/}%.{L}%2$?.){=p 0}{;{L.,2$<=},.}if}do}%; ``` which gives output like ``` "Ac" "AcCRa" "AcHeBe" ... ``` [Answer] # Ruby - 547 393 New version, thanks for the suggestions: ``` e='HHeLiBeBCNOFNeNaMgAlSiPSClArKaCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'.scan(/[A-Z][a-z]*/).map &:upcase r="(#{e.join ?|})" $<.each{|w|(i=0;i+=1 until w=~/^#{r*i}$/i $><<w;p$~.to_a[1..-1].map{|m|e.index(m.upcase)+1})if w=~/^#{r}+$/i} ``` --- ``` e=%w{h he li be b c n o f ne na mg al si p s cl ar ka ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo} x = "(#{e.join(?|)})" regex = /^#{x}+$/i File.foreach('/usr/share/dict/words'){|w| if w=~/^#{x}+$/i puts w i=1 i+=1 until w=~/^#{x*i}$/i puts $~[1..-1].map{|m|e.index(m.downcase)+1}.join ?- end } ``` uses regexes. slow, and much room for improvement but i must go now :-) [Answer] ## Python 710 (357 + 261 + 92) ``` e=". h he li be b c n o f ne na mg al si p s cl ar k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np pu am cm bk cf es fm md no lr rf db sg bh hs mt ds rg cn uut fl uup lv uus uuo".split() i=e.index def m(w,p=("",[])): if not w:return p x,y,z=w[0],w[:2],w[:3] if x!=y and y in e: a=m(w[2:],(p[0]+y,p[1]+[i(y)])) if a:return a if x in e: b=m(w[1:],(p[0]+x,p[1]+[i(x)])) if b:return b if z in e: c=m(w[3:],(p[0]+z,p[1]+[i(z)])) if c:return c f=open('/usr/share/dict/words','r') for l in f: x=m(l[:-1]) if x:print x[0],x[1] f.close() ``` There's sure to be room for improvement in there somewhere. It's also worth noting that the second level of indentation uses the tab character. It takes just over 5 seconds (on my computer) to go through the whole dictionary, producing output like this: ``` acaciin [89, 89, 53, 49] acacin [89, 89, 49] acalycal [89, 13, 39, 6, 13] ... ``` By adding another **18** characters, you can get output with the right capitalization: ``` e=". H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Uup Lv Uus Uuo".split() i=e.index def m(w,p=("",[])): if not w:return p w=w.capitalize() x,y,z=w[0],w[:2],w[:3] if x!=y and y in e: a=m(w[2:],(p[0]+y,p[1]+[i(y)])) if a:return a if x in e: b=m(w[1:],(p[0]+x,p[1]+[i(x)])) if b:return b if z in e: c=m(w[3:],(p[0]+z,p[1]+[i(z)])) if c:return c OUTPUT: AcAcIIn [89, 89, 53, 49] AcAcIn [89, 89, 49] AcAlYCAl [89, 13, 39, 6, 13] ... ``` You can also check individual words: ``` >>> m("beer") ('beer', [4, 68]) ``` [Answer] ## Python - 1328 (975 + 285 chars of code + 68 dictionary code) ``` t1={'c':6,'b':5,'f':9,'i':53,'h':1,'k':19,'o':8,'n':7,'p':15, 's':16,'u':92,'w':74,'v':23,'y':39} t2={'ru':44,'re':75,'rf':104,'rg':111,'ra':88,'rb':37, 'rn':86,'rh':45,'be':4,'ba':56,'bh':107,'bi':83, 'bk':97,'br':35,'os':76,'ge':32,'gd':64,'ga':31, 'pr':59,'pt':78,'pu':94,'pb':82,'pa':91,'pd':46, 'cd':48,'po':84,'pm':61,'hs':108,'ho':67,'hf':72, 'hg':80,'he':2,'md':101,'mg':12,'mo':42,'mn':25, 'mt':109,'zn':30,'eu':63,'es':99,'er':68,'ni':28, 'no':102,'na':11,'nb':41,'nd':60,'ne':10,'np':93, 'fr':87,'fe':26,'fl':114,'fm':100,'sr':38,'kr':36, 'si':14,'sn':50,'sm':62,'sc':21,'sb':51,'sg':106, 'se':34,'co':27,'cn':112,'cm':96,'cl':17,'ca':20, 'cf':98,'ce':58,'xe':54,'lu':71,'cs':55,'cr':24, 'cu':29,'la':57,'li':3,'lv':116,'tl':81,'tm':69, 'lr':103,'th':90,'ti':22,'te':52,'tb':65,'tc':43, 'ta':73,'yb':70,'db':105,'dy':66,'ds':110,'at':85, 'ac':89,'ag':47,'ir':77,'am':95,'al':13,'as':33, 'ar':18,'au':79,'zr':40,'in':49} t3={'uut':113,'uuo':118,'uup':115,'uus':117} def p(s): o=0;b=0;a=[];S=str;l=S.lower;h=dict.has_key;L=len while o<L(s): D=0 for i in 1,2,3:exec('if h(t%d,l(s[o:o+%d])) and b<%d:a+=[S(t%d[s[o:o+%d]])];o+=%d;b=0;D=1'%(i,i,i,i,i,i)) if D==0: if b==3 or L(a)==0:return else:b=L(S(a[-1]));o-=b;a.pop() return '-'.join(a) ``` For the dictionary part: ``` f=open(input(),'r') for i in f.readlines():print p(i[:-1]) f.close() ``` [Answer] ## C, 775 771 chars ``` char*e[]={"h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","uut","fl","uup","lv","uus","uu",0}; b[99],n; c(w,o,l)char*w,*o,**l;{ return!*w||!strncmp(*l,w,n=strlen(*l))&&c(w+n,o+sprintf(o,",%d",l-e+1),e)||*++l&&c(w,o,l); } main(){ while(gets(b))c(b,b+9,e)&&printf("%s%s\n",b,b+9); } ``` **Input**: Word per line, must be lowercase. `usr/share/dict/words` is fine. **Output**: Word and numbers, e.g.: `acceptances,89,58,15,73,7,6,99` **Logic**: `c(w,o,l)` checks the word `w`, starting with element `l`. Two-way recursion is used - if the first element matches the head of the element list, check the remainer of `w` against the full element list. If this match fails, check the word against the tail of the list. The buffer `o` accumulates the element numbers along the successful path. After a match, it will contain the list of numbers, and is printed. **Issues**: The list isn't encoded efficiently - too much `"` and `,`". But this way it's easy to use. I'm sure it can be much improved, without too much cost in code. ]
[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 6 years ago. [Improve this question](/posts/45014/edit) Can you find initial conditions for either **[Rule 110](http://en.wikipedia.org/wiki/Rule_110)** or **[Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life)** to emulate the other? That is, produce output (in any form, not necessarily the familiar pixel grid) which corresponds directly to the other. Rule 110 takes an infinite one-dimensional binary array as input, and outputs an infinite one-dimensional binary array using the values in the input array for the same position and the positions to the left and right, according to the following rules: ``` Input: 111 110 101 100 011 010 001 000 Output: 0 1 1 0 1 1 1 0 ``` Example: ![An example run of a rule 110 cellular automaton](https://i.stack.imgur.com/ws8tz.png) Conway's Game of Life takes an infinite two-dimensional binary matrix as input, and outputs an infinite two-dimensional binary matrix according to the following rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. Example: ![A screenshot of a puffer-type breeder (red) that leaves glider guns (green) in its wake, which in turn create gliders (blue)](https://i.stack.imgur.com/q5pvl.png) Challenges: * How do you find initial conditions to match a specific output, when slightly different inputs produce vastly different outputs? * How do you map infinite structures of different dimensions to each other? * Do you have to throw away a lot of output to get the relevant bits from the other automaton? ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 9 years ago. [Improve this question](/posts/35791/edit) The recent question about Wang tiles has led me to think that creating Penrose tilings might be an interesting popularity contest. ## Background Wang tiles are tiles that can tile the plane, but only aperiodically (see [Fill the Screen with Wang Tiles](https://codegolf.stackexchange.com/questions/35704/fill-the-screen-with-wang-tiles) for a full description). Penrose tiles give the affirmative answer to a famous problem in mathematics: is it possible to have this property with only two tiles? ## The tiles Here are two different pairs of tiles, both known as Penrose tiles: ![Kites and darts](https://i.stack.imgur.com/xvfzS.png) ![enter image description here](https://i.stack.imgur.com/VFui1.png) In the second pair of tiles, the thin rhombus has angles 36 and 144 degrees; the fat rhombus has angles of 72 and 108 degrees. In either pair, the edges of the tiles must be matched up so that the colored circles continue across an edge between two tiles. The colored circles and nodules are there to enforce the edge-matching rules (do not draw the nodules). These matching rules ensure that the tiling created cannot be periodic. ## The goal The problem is to create a Penrose tiling and output it in some graphical form. [The Wikipedia article about Penrose tiles](http://en.wikipedia.org/wiki/Penrose_tiling) gives some ideas for how to construct them. Rules: 1. One of the two pairs of tiles above must be used, or else the third set of 3 Penrose tiles described in the Wikipedia page ([The original Penrose tiling P1](http://en.wikipedia.org/wiki/Penrose_tiling#The_original_pentagonal_Penrose_tiling_.28P1.29)) 2. You do not need to draw the nodules on the righthand set (they are usually omitted). I know this isn't much of a rule, but the pictures will be prettier if you don't draw the bumps. 3. You must fill a rectangular region with at least 20 tiles 4. As long as the output is recognizably a Penrose tiling, you can take any artistic license you want (e.g. only drawing the colored arcs) I used the deflation method described on Wikipedia (in my opinion, the easiest method) to produce the following example: ![Tiling](https://i.stack.imgur.com/BGVD7.png) Please include a picture with your submission. Rule 4 allows for a lot of license to be taken, so hopefully there are some interesting takes on the challenge! ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/15954/edit). Closed 10 years ago. [Improve this question](/posts/15954/edit) ## Overview [This](http://xkcd.com/832_large/) is the XKCD tic-tac-toe cheetsheet: ![enter image description here](https://i.stack.imgur.com/icnb4.png) It's rather big, I know. But it's also your most valuable resource in your challenge. ## The challenge Create a program (in your language of choice) that uses the Optimal Move Cheatsheet (henceforth OMC) to output the optimal move when given a sequence of moves. ## The input Your program will be fed a series of moves in the following fashion: ``` A3 A2 B2 C2 ... ``` Where the first combination is always X, the second O, and so on. The letter is the Y coordinate (`A-C`, A at the top) and the number is the X coordinate (`1-3`, 1 at the left). You may assume that the given combination is following the OMC's suggestion for each move at least for the player asking for a recommendation. You can also assume that the input will never be null (at least one move has been made). You must: 1. Figure out whether the next move is for X or O (you don't need to output this) 2. Use the OMC to decide the next move 3. Print the next move in the standard format `A3` ## Optional: You may also include the player's chance of winning (as a percentage) for 50 character discount on your score. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/12397/edit). Closed 1 year ago. [Improve this question](/posts/12397/edit) *Inspired by [this](https://github.com/bolknote/SedChess)* Implement simple chess bot (with console or GUI) that has following features: 1. [Pseudo-]graphically showing the board; 2. Accepting user moves and making their own moves; 3. Playing by basic chess rules (not doing illegal moves); 4. Making at least minimally reasonable moves (no random moves, a player making random valid moves against the bot should lose most times). In general, implement something like "SedChess" (linked above) in minimum number of bytes. Optional: 1. Advances rules like castling, stalemate detection, en passant, etc; 2. Checking validity of user inputs; 3. Analysing more than 1 move in depth; Limitations: 1. No networking; 2. No dependance on chess-specific libraries (unless they are included in the language and language's standard library) or programs; 3. No lame tricks like showing two boards and requesting user play two games (with himself). ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/43218/edit). Closed 9 years ago. [Improve this question](/posts/43218/edit) # The Puzzle You have to write a program or function p(n) that returns the square of what is entered into it and you may assume that the input is a non-negative integer. Put in simpler terms, return n2. # Rules 1. You are not allowed to use `*` or `/` (or any other power or square root operator, such as `POW` or `SQRT`, if your language contains such functions) 2. You may not use a loop, or use a constructions that is similar to a loop. Example of loop like constructions are `GOTO` and recursion. # Example ``` Function p(n) Dim r() ReDim r(n) p = Len(Join(r, Space(n))) End Function ``` Be creative and (ab)use the functions and features given to you by your language of choice. \*edit Loop like structures are loops that allow you to repeat 1 or more instructions -if you could add an `stdout "1"` to your code and you would end up with repeating that output n times, it will count as a loop [Answer] # CJam, puts on his glasses ``` q~33c (*_*) (*_")>⌐■-■ (⌐■_■) "]sG>4%,) ``` Input via STDIN [Try the code here](http://cjam.aditsu.net/) *Note that `*` in the code is not used as multiplying, but as a join operator* *Also note that the cool part of the code is not just string, half of it is actually the code involved in finding the square. So.. DEAL WITH IT* This will help you in dealing with it: ``` q~33c "Read the number and put ASCII character 33 on stack with it" ( "Decrease it to get ASCII code 32 character, which is a space"; *_ "Repeat the space input number times and make another copy"; * "Put that many spaces in between each space. Now we have"; ) "n*n spaces string. We take out the last space out of it"; ( "Decrement the space to get ASCII 31 character"; * "Fill the n*n - 1 spaces with that to get 2*n*n - 3"; _ "string. Then copy it again."; ")>⌐■-■ "Put the sun glasses in"; (⌐■_■) "Wear the sun glasses. Be cool."; "]s "Add everything to a single string of 4*n*n - 6 + 16" G> "length. Remove first 16 characters"; 4% "Take every 4th character from that string to get n*n - 1" ,) "length string. Take length and increment to get n*n"; ``` [Answer] # Ruby ``` def square(n) case n when 0..1 n when 2..36 '100'.to_i(n) else raise RangeError, 'Integer overflow!' end end ``` [Answer] # APL? ∊⍵⍵ ``` {+/ ∊⍵⍵ ⍴1} ``` This answer is dedicated to all those people who go "∊⍵⍵" whenever they see the APL symbols :-) **Examples** ``` {+/∊⍵⍵⍴1} 3 9 {+/∊⍵⍵⍴1}¨⍳20 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 289 324 361 400 ``` **Explanation** ``` { } This function takes a number ⍵, { ⍵⍵⍴1} builds a matrix of ⍵ by ⍵ all filled with ones, {+/∊ } and sums all its elements together. ``` [Answer] # Abusing some functions in Mathematica Twice the area of an isosceles right triangle ``` a =RegionMeasure@SASTriangle[n,ArcSin[1], n] a+a ``` --- The area of a square. Of course! ``` RegionMeasure[Rectangle[{0, 0}, {n, n}]] ``` The same idea, in a different form: ``` Integrate[n, {x, 0, n}] (* thx to DigitalTrauma *) ``` --- The number of elements in a square matrix: ``` Length[Flatten[Normal[AdjacencyMatrix[RandomGraph[{n, RandomInteger[n]}]]]]] ``` or ``` Plus@@Flatten[ConstantArray[1, {n, n}]] ``` or ``` Length@Flatten[Outer[f,Range[n],Range[n]]] ``` or ``` Length[Distribute[p[Range[n],Range[n]],List]] ``` etc... [Answer] # C ``` p(n){int a[n];return(&a)[n]-a;} ``` Note: * Variable-length arrays are a conditionally-supported feature since C99. * Implicit `int` is used to reduce character count and for style points. [Answer] # Mathematica Another answer using some funny Mathematica features ``` n = Input[]; g = EdgeCount@CompleteGraph@n; g + g + n ``` A complete graph with `n` vertices has `binom(n,2) = n(n-1)/2` edges (which is also the n'th triangular number). So the result is simply twice that, plus the input. [Answer] # Python 2 Purely mathematical, avoiding any of the banned operations: ``` import cmath n=input() if n: l=complex(0, -cmath.log(n) - cmath.log(n)) print int(round(abs(complex(cmath.cos(l),cmath.sin(l))))) else: print 0 ``` This is the usual `exp(ln(x)*y)` trick tailored to this problem: * Because y is 2, then we can simply do `ln(x)+ln(x)` to get rid of the multiplication. * I felt that `math.exp()` was a bit too close to the banned "POW" for fair play, so instead the whole thing is converted to complex and Euler's identity is used to replace the `exp()` with `cos()` and `sin()` * To avoid the situations where explicit multiplication/division by *`i`* is needed, the `complex()` function is used instead. [Answer] # Pure Bash No explicit loops or arithmetic: ``` (($1))||{ echo 0;exit;} eval a=({1..$1}{1..$1}) echo ${#a[@]} ``` Uses bash expansions to create two lists 1-n and brace-expand them and display the size of the resulting array. --- Similar method, but making use of coreutils instead: ``` join <(seq -f "1 %g" $1) <(seq -f "1 %g" $1) | wc -l ``` [Answer] # R, delicious inefficiency with Monte Carlo The expectation `E[x]` for the shape/scale parametrization of the [Gamma Distribution](http://en.wikipedia.org/wiki/Gamma_distribution) is `shape*scale`. I don't see `mean` being banned, so here is the sample solution with `mean()` ``` f = function(n, k = 1e9){round((mean(rgamma(k, shape = n, scale = n))))} f(99) ``` Without using `mean()`, it is possible to use `mode[x]`, which is equal to `(shape-1)*scale`, but this involves writing a `add.one` function to bypass `+1` then writing another `Mode` function to tabulate the mode. ``` add.one = function(x) length(c(seq(x),NA)) Mode = function(x) (u<-unique(x))[which.max(tabulate(match(x,u)))] f.mode = function(n, k = 1e9){Mode(round(rgamma(k, shape = add.one(n), scale = n))) ``` Accuracy not guaranteed, but law of large number should kick in for 1,000,000,000 samples, which has given me the right results for all my test cases. [Answer] # **Java** First entry, is this how it works? ``` int g(int n){ int[] a = new int[n]; Arrays.fill(a,n); return IntStream.of(a).sum(); } ``` [Answer] # C# Creates a string with n characters and then replaces each character with the n-character string. This produces a string with a length of n\*n. ``` using System; public class Test { public static void Main() { int n = Int32.Parse(Console.ReadLine()); String s = "".PadLeft(n, 'X'); Console.WriteLine(s.Replace("X", s).Length); } } ``` Test it here: <http://ideone.com/lubIFg>. [Answer] # Matlab *a warning: this is primarly math based, so do not expect fancy source code* Note that `a = n^2` iff `log(a) = log(n)*2` iff `log(log(a)) = log(log(n))+log(2)`. So this function is just finding the zero of the function `f(a) = log(log(n))+log(2) - log(log(a))` which obviously is at `a = n^2`. ``` function s = g(n) f = @(a) log(log(n))+log(2)-log(log(a)); s = fnzeros(f); end ``` ### Here some other not very creative functions: Here the program wil sum sum the number `1+2+3+...+n = 1/2 * (n^2+n)` twice and substract `n`, so the result is always `n^2` ``` g=@(n)sum(1:n)+sum(1:n)-n ``` This function creates a `n x n` matrix of random numbers (between 0 and 1) and then returns the number of elements. ``` g=@(n)numel(rand(n)); ``` The following functin creates a [vandermonde matrix](http://de.wikipedia.org/wiki/Vandermonde-Matrix) of the vector `(0,0,n)` and outputs the entry that consists of `n^2` ``` function s = g(n) a = vander([0,0,n]); s = a(3,1) end ``` This function creates the inverse of a [hilbert matrix](http://en.wikipedia.org/wiki/Hilbert_matrix) of size `n` where the top left element is always `n^2` ``` function s = g(n) a = invhilb(n); s = a(1); end ``` [Answer] # C ``` sizeof(char[n][n]) ``` It works up to INT\_MAX in constant time and without memory allocation. Example: ``` #include <stdio.h> #include <limits.h> int main(){ for( int n=0 ; n<10 ; n++ ){ printf("%d: %ld\n", n, sizeof(char[n][n])); } int n = INT_MAX; printf("%d: %ld\n", n, sizeof(char[n][n])); } ``` displays ``` 0: 0 1: 1 2: 4 3: 9 4: 16 5: 25 6: 36 7: 49 8: 64 9: 81 2147483647: 4611686014132420609 ``` [Answer] # Java This is the first answer that truly does not use loops or recursion. ``` int square(int n){ if (n > 0){ n = -n; } return m(n,0) + m(n,1) + m(n,2) + m(n,3) + m(n,4) + m(n,5) + m(n,6) + m(n,7) + m(n,8) + m(n,9) + m(n,10) + m(n,11) + m(n,12) + m(n,13) + m(n,14) + m(n,15) + m(n,16) + m(n,17) + m(n,18) + m(n,19) + m(n,20) + m(n,21) + m(n,22) + m(n,23) + m(n,24) + m(n,25) + m(n,26) + m(n,27) + m(n,28) + m(n,29) + m(n,30) + m(n,31); } int m(int number, int index){ if (number >> index << 31 >>> 31 == 0){ return 0; } else { return number << index; } } ``` [Answer] ## GolfScript Histocrat has shown one way of using base conversion: here's another. ``` {.,1base.++}:p; ``` ### Dissection ``` { # Function boilerplate . # Duplicate the input. Stack: x x , # Turn the second one into an array [0 1 ... x-1] 1base # Sum the elements of the array. Stack: x x(x-1)/2 .+ # Double. Stack: x x(x-1) + # Add. Stack: x*x }:p; # Question asks for the function to be called p # The fact that this destroys the built-in p is unfortunate, but required ``` [Answer] ## Emacs Lisp ``` (defmacro square-it (n) (cons '+ (make-list n n))) (square-it 11) ;; => 121 ``` A simple macro that expands `(square-it 5)` into `(+ 5 5 5 5 5)`. Of course, the input must be a compile time constant. [Answer] # Javascript ``` function square(i) { return new Array(++i).join(new Array(i).join(' ')).length; } ``` [Answer] # Haskell There a lot of possibilities if ranges `[x..y]` are allowed, some of them are: ``` f n|x<-sum[1..n]=x+x-n f n=sum$take n[n,n..] f n=length$[1..n]>>[1..n] f n=sum$[1..n]>>[1..n]>>[1] ``` The two latter ones use the Monad instance of lists. for lists `xs`, `ys` holds that `xs>>ys` is `ys` appended to itself `length xs` times. another trick is just ``` import Data.Monoid f x=x<>x ``` this function, when given an 'appropriate' argument (which are of course from the typeclass `Num`) return it's square. `Product 3 :: Num a => Product a` is an example of such an argument. basically, this function when applied on `Product a`, (which in the `Num` class iff `a` is in i) `mappend`s it with itself and returns `Product (a*a)`. if we are more strict about what is a number / what numbers should our function work on, we can define `f` as ``` import Data.Monoid f n|x<-Product n=getProduct$x<>x ``` [Answer] ## Java This is too long to put in the answer, but basically one of the lines of code occurs an amount of times roughly equal to the sqrt of `Integer.MAX_VALUE` (which is 46340). :D With no comments or line breaks, the code typed out would be 1,112,155 characters. ``` int s(int n){ if(n==0|n==1)return n; int c=2,r=n+n; if(n==c++)return r;r+=n; if(n==c++)return r;r+=n; if(n==c++)return r;r+=n; if(n==c++)return r;r+=n; if(n==c++)return r;r+=n; if(n==c++)return r;r+=n; //... (same line of code a total of 46336 times) if(n==c++)return r;r+=n; if(n==c++)return r; return n==c?r+n:r+n+n; //r = 46340^2 } ``` [Answer] # R This function is based on counting all possible combinations of two sequences ranging from 1 to `n`. The value 0 is treated separately. ``` f <- function(n) if (n) nrow(expand.grid(s <- seq(n), s)) else 0 ``` [Answer] # Clojure ``` (def squares (lazy-cat [0] (map (fn [sq x] (+ sq x x 1)) squares (range)))) ``` Infinite sequence of all squares starting from 0. The function: ``` (defn square [n] (nth squares n)) ``` [Answer] # J Some ascii art... ``` p =. ( $ @,@ ( ($*) ([-])"*/ ($*) )) ``` [Answer] perl : ``` $n=8; $x = "$n +" x $n; $x =~ s/\+$//; print eval $x; ``` [Answer] ## SQL(PostGIS) Making use of the area and make envelope functions in the PostGIS extension to PostGreSQL to create a square geometry and return it's area. Could be changed to return the square of floats as well. ``` CREATE FUNCTION square(n int)RETURNS int AS $$ BEGIN RETURN ST_Area(ST_MakeEnvelope(0,0,n,n)); END; $$LANGUAGE plpgsql; ``` In use; ``` SELECT square(150); Square Integer -------------- 22500 ``` [Answer] # Python Uses simple math. Based on the sum of an arithmetic progression. ``` s=lambda n:(sum(range(n))<<1)+n ``` Explanation: ``` a = sum(range(n)) # sum of arithmetic progression from 1 to n-1: n*(n-1)/2 b = a<<1 # bitshift left by 1 (multiply by 2): n*n - n c = b+n # add n: n*n ``` Although sum and range probably contains implicit loops, but as per question spec, there's no way to insert a print statement here to make it repeat, so ... :) [Answer] # Bash ``` yes|xargs -L$1|xargs -L$1|head -n1|iconv -futf16|wc -m ``` Only works if n < 256. [Answer] # PHP ``` function square($v) { return array_sum(array_fill(0, $v, $v)); } ``` works with integer in the range [0;46340] Edit: I've just seen @thebestone code and it is basically the same [Answer] # Perl ``` $_=<>;chop;s/./$_/g;print ``` the program expects the input number to be squared in unary form (i.e. base 1). Output is also unary. It simply replaces every digit with the whole number. Example usage: ``` perl -e '$_=<>;chop;s/./$_/g;print' 000 # <- user input 000000000 # <- output ``` [Answer] # Scala: ``` scala> val q = (n:Int) =>(List.fill (n)(n)).sum q: Int => Int = <function1> scala> q(9) res21: Int = 81 ``` [Answer] # Scala: ``` scala> val s=(n:Int)=>(("x"*(n))*n).size s: Int => Int = <function1> scala> s(7) res22: Int = 49 ``` ]
[Question] [ Your program has to have an year like `1957` to be the input and then output the century of that year. For example: ``` In: 1946 Out: 20 In: 1705 Out: 18 In: 1900 Out: 19 In: 100 Out: 1 In: 2001 Out 21 ``` because 1946 is in the 20th century. Keep in mind that 2000 should be 20th century or 1900 should be in 19th century. **Therefore, the first century spans from the year 1 up to and including the year 100, the second - from the year 101 up to and including the year 200, etc.** Any programming language is allowed and **keep your code short and sweet. :)** **Additional Challenge: Try to also include float values** [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 308 298 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE x YOU SET US UP 0 GET YOUR ASS TO MARS x DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY GET TO THE CHOPPER x HERE IS MY INVITATION x GET UP 99 HE HAD TO SPLIT 100 ENOUGH TALK TALK TO THE HAND x YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/##RY8xT8QwDIX3/Iq3sfYkBjr6ruZiXZOU2Lmq4wlGBBIT/744hxBLFD1/ef5y@/r4fH973XexB4XGspokDpE3nGIVtUQKq8z4DltpUDY0RVswhLPfPasgdaYgUVXHpgIx5LIGwUrZ@oj00lEQji2fIsozXhqrSckKyhP@0UhXhkVOnuvKlX2YEk9CxvN2X@qUAy5YloWrr4yOQRRpg@SrGPVizzvsquPohBdP/aUus@sdhiFwLu0cYTRfQj/@emMX@v3uXebInGFck2R3mPb9MD49/gA "ArnoldC – Try It Online") This seemed a challenge easy enough to try to write my first answer in ArnoldC... [Answer] # JavaScript, 14 bytes ``` y=>1+--y/100|0 ``` [Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/S1s5QW1e3Ut/QwKDG4H9yfl5xfk6qXk5@ukaahqGlhYWmTpqGkYGBgabmfwA) [Answer] # Vim, 13 bytes ``` 3I0*<Esc>*$3hd0*<C-x>*xx*<C-a>* ``` [Answer] # Taxi, 1327/2433 1057/1835 bytes Two versions here; the shortest one works but shows the result in decimal format (e.g. `20.000000` instead of `20`). I am posting both because, while the longer version is more correct, I still hope to win this code golf with the short one (it could require a little bit of tweaking, though). **Short version** [You can test it here.](https://tio.run/##rZPBboMwDIbvPIUfYEK0O7W3bpN665C2F/CIIVFp0jlhbE/PUi0gCowxqRcUnOT//Du2w0/VNHsDzkBqrIPnPFcZbaEm6@5g5SMl5WHFqpC9YBylKjtWZ0A4o7WkC2IojNLFRe1VEjzgG5W5spL4K45@KMP4DGoesBNCOWU07MqSOvkXh5xJVQo4VCdiU5rCIwjHiOFqrUWwtdmAslCjl/codJOicbRKkkXn/mNi7uwBmU0NKTrpP3xsLV9rjM1ejIWnu2fRf8UFVX5SH0oQoNd4NPq9Im6xw3S2oA07OdkqN8CNd/pOA6@z@kdvcqWPxLbryfA/oTio2C37fsRaWKPenLbiV6M71exBNqTihx72yFjQL1kMLzbNOkmS5hs) ``` Go to Post Office: west, 1st left, 1st right, 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: west, 1st left, 1st right. Pickup a passenger going to Addition Alley. Go to Starchild Numerology: east, 1st left, 1st left, 1st left, 2nd left. 99 is waiting at Starchild Numerology. 100 is waiting at Starchild Numerology. Pickup a passenger going to Addition Alley. Pickup a passenger going to Narrow Path Park. Go to Addition Alley: east, 1st left, 2nd right, 3rd right, 1st right. Pickup a passenger going to Divide and Conquer. Go to Narrow Path Park: north, 1st right, 1st left, 1st right. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer: east, 1st right, 2nd right. Pickup a passenger going to Trunkers. Go to Trunkers: east, 1st right, 3rd right, 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: east, 1st right, 1st right. Pickup a passenger going to Post Office. Go to Post Office: east, 1st left, 1st right. Go to Taxi Garage: east, 1st right, 1st left, 1st right. ``` **Long version** [You can test it here.](https://tio.run/##rVU7b9swEN79Kw5ashSC3QAFnM21gQwJUgMu0KHwwEgn6WCFpx6puvn1KlU9LEuKYhdZDJEmv8fxO9KqP1QU9wyWYcvGwrcoogDv4IjGfoKFm0kxqr@E4qQz6c@2FBzyDBRkyhjUMQrETDou0b4nCF/VM6YRmQTl1Z9VLP35CappglUYkiXWsEpTbOF3VkmQUBrCU/6CwinHjgLVkKL/9VmHta3lEsjAUTl4R6XsKKg/W8znF627xsTU2iclwkfYKpu4Hzk0ls8xhmZLY/XR3UrYPcULqryh3xQiKIexZv0rR2lo@3LuQLPYZDQqH0A3/KfrtOZrrb6TTcn1AcW0mazHI4i9in1k7gdcF9ZonXAGu/yU@XaiwfzijuQq0Q@sH5S9cQX5mQkHaMyGYrJmPy3kNUhZYyujGp7loDr8sojvi1gLvSA8qucG8IeQRbkxsMGMbXVR@DPP93ptd77uSpJ2YipO3dthdyQbJOXWLFUaPM12tXatrp2syHkHV4OOwOGGTEhbz5W63bnvV/B0JQ4a6cKIn060gm7Gjcuetf9A7KRuvPFrzKH9TsC8f4lz9diP6pxW1HmwGlFnb5jhvJQ12sJ1U7rnD@6VqBjf6Mf@7VUUi@V8XvwF): ``` Go to Post Office: west, 1st left, 1st right, 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: west, 1st left, 1st right. Pickup a passenger going to Addition Alley. Go to Starchild Numerology: east, 1st left, 1st left, 1st left, 2nd left. 99 is waiting at Starchild Numerology. 100 is waiting at Starchild Numerology. Pickup a passenger going to Addition Alley. Pickup a passenger going to Narrow Path Park. Go to Addition Alley: east, 1st left, 2nd right, 3rd right, 1st right. Pickup a passenger going to Divide and Conquer. Go to Narrow Path Park: north, 1st right, 1st left, 1st right. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer: east, 1st right, 2nd right. Pickup a passenger going to Trunkers. Go to Trunkers: east, 1st right, 3rd right, 1st left. Pickup a passenger going to The Babelfishery. Go to The Babelfishery: east, 1st right, 1st right. Pickup a passenger going to Chop Suey. Go to Chop Suey: east, 6th right, 1st left. Pickup a passenger going to KonKat's. [processDigits] Pickup a passenger going to Cyclone. Go to Cyclone: north, 1st left, 3rd left. Pickup a passenger going to Crime Lab. Go to Writer's Depot: west. "." is waiting at Writer's Depot. Pickup a passenger going to Crime Lab. Go to Crime Lab: east, 1st right, 2nd right, 2nd left. Switch to plan "notAColon" if no one is waiting. Switch to plan "print". [notAColon] Go to Cyclone: west, 1st right, 1st left, 2nd right. Pickup a passenger going to KonKat's. Go to KonKat's: east, 2nd right, 2nd right. Pickup a passenger going to KonKat's. Go to Chop Suey: north, 1st right, 1st right. Switch to plan "processDigits". [print] Go to KonKat's: east. Pickup a passenger going to Post Office. Go to Post Office: south, 3rd right, 1st left. Go to Taxi Garage: east, 1st right, 1st left, 1st right. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E),  4  3 bytes -1 byte thanks to Jonathon Allan ``` т/î ``` [Try it online!](https://tio.run/##MzBNTDJM/f//YpP@4XX//xsZGBgAAA "05AB1E – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` /₁₀₀⌉₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/9RU@OjpgYQ6ukEsv//NzIwMPgfBQA "Brachylog – Try It Online") Just wanted to try my hand at Brachylog. Uses the "divide by 100 and ceil the result" method that many other answers use. [Answer] # [R](https://www.r-project.org/), ~~19~~ ~~18~~ 16 bytes ``` 1+scan()%/%99.99 ``` [Try it online!](https://tio.run/##K/r/31C7ODkxT0NTVV/V0lLP0vK/kYGB4X8A "R – Try It Online") Saved 1 byte thanks to digEmAll! -2 bytes thanks to JDL! [Answer] # [LOLCODE](http://lolcode.org/), 76 bytes ``` HAI 1.2 I HAS A x GIMMEH x VISIBLE QUOSHUNT OF SUM OF x AN 99 AN 100 KTHXBYE ``` [Try it online!](https://tio.run/##y8nPSc5PSf3/38PRU8FQz4jLU8HDMVjBUaGCy93T19fVA8gI8wz2dPJxVQgM9Q/2CPULUfB3UwgO9QVRFQqOfgqWliDS0MCAyzvEI8Ip0vX/f0NLCxMA "LOLCODE – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~11~~ 10 bytes ``` @)OuI('d,U ``` [Try it online!](https://tio.run/##Sy5Nyqz4/99B07/UU0M9RSf0/39DSwNDAA "Cubix – Try It Online") This wraps onto the cube as follows ``` @ ) O u I ( ' d , U . . . . . . . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgIEAgKQogICAgTyB1CkkgKCAnIGQgLCBVIC4gLgouIC4gLiAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MTk0Ngo=&speed=20) Not sure what I was thinking when I did the first one. Excluding the path changes the general process is `I('d,)O@` - Input integer, decrement, push 100, integer divide, increment, output integer and exit. ***Float version 16 bytes*** And since it was an interesting exercise, here's a version that will handle a float input. Try 1900, 1900.0 and 1900.1. Of course it isn't really doing floats as Cubix prefers integers and the format of the float doesn't really matter. 1900 1, 1900-1 and 1900.1 are all treated the same. ``` WBiWIUd'.(B?@,)O ``` [Try it online!](https://tio.run/##Sy5Nyqz4/z/cKTPcMzRFXU/Dyd5BR9P//39DSwMDPUMA "Cubix – Try It Online") And wrapped ``` W B i W I U d ' . ( B ? @ , ) O . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgIFcgQgogICAgaSBXCkkgVSBkICcgLiAoIEIgPwpAICwgKSBPIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=MTkwMQ==&speed=20) This one does (excluding path changes) * `IiI` Input integer, input char (-1 for EOI or char value for seperator), Input integer * `?` Test TOS + If 0 `B(`, reverse stack and decrement TOS + If positive `B` reverse stack + \*\* negative shouldn't happen \*\* * `'d,)O@` push 100, integer divide, increment TOS, output and exit [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 11 bytes ``` ?({!@/)d':/ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/99eo1rRQV8zRd1K//9/IwNDAA "Hexagony – Try It Online") Linear code (9 bytes): ``` ?({d':)!@ ``` Ungolfed code: ``` ? ( { ! @ / ) d ' : / . . . . . . . . ``` It may be possible to save 1 or 2 bytes by using `:` to terminate (division by zero error), but I can't find out a way. [Answer] # [MarioLANG](https://github.com/tomsmeding/MarioLANG), 821 807 625 595 570 386 bytes ``` ; - ) ) + + ( >- >- >- >- >- >- >- >- >- >-) ( "= "= "= "= "= "= "= "= "= "=+ > > >[!![!![!![!![!![!![!![!![!![!!( "======="======"=##=##=##=##=##=##=##=##=##=## !(![-)+<!(![(< ![ < < < < < < < < < << #=#===="#=#==" #=="=="=="=="=="=="=="=="=="=="= >( ! (< >))-[!(+ "====#==" =====#=: ! < #=====" ``` [Try it online!](https://tio.run/##fVDLCgMhDLznKxK9JIiHQg99xP0RT3sqhT6g/w826u5hW9bJ4ASJo@Nz/tzfj/l1K@UKEcQqWDH@YIoDyv@8SwMGmFbbRTLRgAwudbhVvB8QiClHCVqVFSmj4j4V7FCzberQt4v2CfbimpjQzK0XiZk4QI1taB6IqfcX2HwMtVW3m76nKuVwPh2/ "MarioLANG – Try It Online") I'm sure this can be golfier Now this is starting to be quite golfy, though it took me a while to figure out a way to do the division in MarioLANG. Improvements: * Lots of bytes saved by taking advantage of the fact that Mario starts falling from the upper left corner of the code. * Code before a fall has been placed during the fall. * Great improvement after redesigning the division-by-10 part. Explanation: * First we set `a` to `INPUT` as integer and substract `1`. * Then we set `b` to `0` and `c` equals to 2. * Then we substract `1` from `a` 10 times, checking every step if `a` has reached `0`. * If we successfully substract `10` from `a`, increment `b`. * Repeat this until `a` is `0`. Now we have the result of the division in `b`. * Substract 1 from `c` and move `b` to `a` if `b` is not `0`. After moving the value `b` is set to `0`. * Repeat the division-by-10 operation one more time, substracting 1 from `c` again and now that `c` is `0` the program outputs the result in `b` and exits. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 3 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` M/U ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=TS9V,inputs=MjAwMQ__,v=0.12) [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~20~~ 19 bytes ``` echo $[($1+99)/100] ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I19BJVpDxVDb0lJT39DAIPb///9ACgA "Bash – Try It Online") *-1 thanks to W W* [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 4 bytes *-5 from @Shaggy* ``` /L c ``` [Try it online!](https://tio.run/##y0osKPn/X99HIfn/fyMDA0MA "Japt – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~18~~ 15 bytes ``` $_=1+--$_/100|0 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tZQW1dXJV7f0MCgxuD/f0MuIIPL0AJCAHmWIJYlkGVkAGQBCcN/@QUlmfl5xf91C3IA "Perl 5 – Try It Online") *(-3 whole bytes, thanks to @Dom Hastings.)* Or with `-p -MPOSIX`: ### ~~15~~ 13 bytes ``` $_=ceil$_/100 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jY5NTNHJV7f0MDg/38jAwODf/kFJZn5ecX/dQv@6/oG@Ad7RgAA "Perl 5 – Try It Online") *(-2 bytes, again thanks to @Dom Hastings.)* [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 26 bytes ``` r`(.*)(.?.) $2*X$1* X+ _ . ``` [Try it online!](https://tio.run/##K0otycxLNPz/vyhBQ09LU0PPXk@TS8VIK0LFUIsrQpsrnkvv/38jAwMDAA "Retina – Try It Online") My first attempt at Retina. Can probably be golfed more (though, I like the `(.?.)` babyface in this one). [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 6 Assuming input and output on the top-of-stack is OK: ``` 99+A0/ ``` [Try it online!](https://tio.run/##S0n@b2RgYPjf0lLb0UD/f9p/AA "dc – Try It Online") [Answer] # Java 8, 12 bytes ``` y->~-y/100+1 ``` [Try it online.](https://tio.run/##hY/NCoMwEITvPsUeE4o2Kf1BpH2DevFYetj6U2I1iolCKPbV02i9Fi8DO/Oxw5Q4oF9mL5tWqBRcUci3ByCkzrsC0xzi6ZwNKMikhkbOGT0nSqMWKcQg4QzW@JePb7acsQ230ZS3/aNy@YINjcigdgUk0Z2Qz9sdkP6@J0bpvA6aXgeti3QliQwKwsP9kc51/5ETO6whIWNryCqxY4zTZflovw) **Explanation:** ``` y-> // Method with integer as both parameter and return-type ~-y // Decrease the input by 1 /100 // Then integer-divide it by 100 +1 // And then add 1 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~23~~ 22 bytes ``` f(i){return--i/100+1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1Ozuii1pLQoT1c3U9/QwEDb0Lr2f2ZeiUJuYmYeSJarODkxL01DSTVFSUctU9Oaq6AIKA0VAOkHCtX@NzIwMAQA "C (gcc) – Try It Online") -1 byte saved thanks to @luser droog # 20 bytes ``` R;f(i){R=--i/100+1;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z/IOk0jU7M6yFZXN1Pf0MBA29C69n9mXolCbmJmHkiGqzg5MS9NQ0k1RUlHLVPTmqugCCgNFQDpBQrV/jcyMDAAAA "C (gcc) – Try It Online") -2 bytes saved thanks to @Digital Trauma # 18 bytes ``` f(i){i=--i/100+1;} ``` [Try it online!](https://tio.run/##VYtBDoIwFET3nOIHY9IiaOtGI8LGUxjjohYKP8FiKpIQwtlrf1y5mpc3MzprtPYrtLr7VDWc30OF/bYtoz/V4SM4bxjyGYssw50UYiPzxaMd4KnQMgLlGp3qVjlIksAjhzkCoGaqlSv2Qh5zEobRspT859XQI5nxJu@cBi8XPobF19CeYF3BpbbDx03EcUqf1DAKHuaL9/IgxBc "C (gcc) – Try It Online") Another -2 bytes saved thanks to @ErikF [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 bytes ~~([packed](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax))~~ ``` vAJ/^ ``` [Run and debug it](https://staxlang.xyz/#c=vAJ%2F%5E&i=1946%0A1705%0A1900%0A100%0A2001&a=1&m=2) Explanation: ``` vAJ/^ Full program, implicit input v Decrement AJ Push 100 (102) / Integer division ^ Increment ``` [Answer] # [Perl 6](https://perl6.org), 13 bytes ``` (*+99)/100+|0 ``` [Test it](https://tio.run/##TY7BTsMwEETv/opRG6GkKYkd0YBrpeLaS7lw5FISF1lKbKtxKhDwZdz4sRDXFXDbebMzu1Ye23IceolTmdWCkO4NV7VpJKoxXqScJzmjNP2go/DWvZO9Q4Vosd1lteme4/ypSfPk@yvbDZ3AHIfW7J3SL7BGaUeIr36cQoLYdq@RhoZGnVBM1w7meOm83iBS2g5uiUi@Wlk72eCdAKqH/ycObvLPXmIWIKrNH50J8jlu9RqM35TkYXBrFJScwS1dBcDuAuCUXgAP4FefZUEp8xoFI9NMfZHPTOs/ "Perl 6 – Try It Online") ## Expanded: ``` # WhateverCode lambda ( * # this is the parameter + 99 # add 99 to adjust the century ) / 100 # divide by 100 +| 0 # Integer bitwise-or with 0 (coerce to Int) ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 5 7 bytes ``` ~(100/) ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v07D0MBAX/P/fyMDA0MA "GolfScript – Try It Online") ``` ~(100/) AAA AA \\\ \\ \\\ \Increments the stack \\\ Divides the stack \\\ \\Adds 100 to the stack \Decrements the stack Turn the input string into an int ``` [Answer] # [Python 2](https://docs.python.org/2/), 18 bytes ``` lambda x:~-x/100+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCqk63Qt/QwEDb8H9afpFCZWpikUJmnkK0oaWlpY6RgYEBiDCMteJSKCjKzCsBK9BR17VT10nTALE1/wMA "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 16 bytes ``` (`div`100).(+99) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P81WIyElsyzB0MBAU09D29JS839uYmaebUFRZl6JSpqCoYHhfwA "Haskell – Try It Online") # 16 bytes ``` f x=div(x+99)100 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwjYls0yjQtvSUtPQwOB/bmJmnm1BUWZeiUqagqGB4X8A "Haskell – Try It Online") [Answer] # PHP, 22 bytes ``` <?=1+--$argv[1]/100|0; ``` [Try it online](https://tio.run/##K8go@P/fxt7WUFtXVyWxKL0s2jBW39DAoMbA@v///4aWFhYA) ``` <?=ceil($argv[1]/100); ``` [Try it online](https://tio.run/##K8go@P/fxt42OTUzR0MlsSi9LNowVt/QwEDT@v///4aWFhYA) [Answer] # PHP, 19 bytes ``` <?=ceil($argn/100); ``` or ``` <?=--$argn/100+1|0; ``` Save to file, run as pipe with `-nF`. [Answer] Excel Vba, 89 bytes ``` Function GetCentury(Year As Long) GetCentury = Mid((Year - 1) / 100, 1, 2) + 1 End Function ``` And a version with 65 bytes ``` Function C(Y As Long) C = Mid((Y - 1) / 100, 1, 2) + 1 End Function ``` Honestly I dont even know if this is a valid entry :/ [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 195 bytes ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:Listen toheart!You is the sum ofa cat the quotient betweenthe sum ofyou a pig the square ofthe sum ofa big big big cat a big cat!Open heart ``` [Try it online!](https://tio.run/##TY1NC8IwDIb/SnYfpXjczYMHQVDwJMNDVuNW0XZrU9RfX9PJxEPgSfJ@xPGec63WN3zV6oA9CRuGbaOOhhwVaDeOKUCRALoLFNW5bM3ORiYH7AfCwNXJJ7AReCCI6QH@imCQ531Kni05ho74SQI/zVtMCKPtv74pYSA5/4d08lymBOJC1X6U@rk855XW@gM "Shakespeare Programming Language – Try It Online") ### Explanation: ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax: #Header Listen toheart! # Set Page to the input # Set Page to (n-1)/(10)**2+1 You is the sum ofa cat the quotient betweenthe sum ofyou a pig the square ofthe sum ofa big big big cat a big cat! Open heart # Print Page's value as a number ``` [Answer] # [Elixir](https://elixir-lang.org/), 89 78 bytes Not perfect but I'm just learning Elixir so code-golf it is! ``` IO.gets("")|>String.to_integer|>(&(Integer.floor_div(100,&1-1)+1)).()|>IO.puts ``` [Try it online!](https://tio.run/##S83JrMgs@v/f018vPbWkWENJSZOrxi64pCgzL12vJD8@M68kNT21CCjmnVqUl5qjp6thCFLhCRHXS8vJzy@KT8ks0zA0MNBEKNOGKvPXKygtKf7/39DAEAA "Elixir – Try It Online") In a better format: ``` IO.gets("") # Get input from terminal |>String.to_integer # Make it an int |>(&( # Declare an anonymous function Integer.floor_div(100, # Do a floored division with 100 on the bottom &1-1) # ... and the integer input minus 1 on top +1)) # Add 1 to the result .() # Gotta invoke that anonymous for pipes |>IO.puts # Output ``` [Answer] # Pyth - ~~6~~ 7 bytes ``` .EcQ100 ``` Explanation: ``` .EcQ100 Implicit print Q Input / Divided by 100 100 .E Rounded up ``` Fixed edge case ]
[Question] [ Unlolify a lolified message! I had to ask a coworker if they wanted to have lunch with me, but we're both hackers so it could not be in a lame way. The message asking that was roughly this: > > please respond with `011110010110010101110011` if you'd like to join lunch today > > > The colleague being a hacker, just responded with `0x796573`, to which I responded back: > > 0x636f6f6c2c206e696365 > > > To save my colleague the trouble of unlolifying it, I wrote a Ruby function to unlolify and sent it along with the message. But the function itself was way more lengthier than the lolified message itself. I'd like to have a better alternative in the future and be able to send a much shorter `unlolify` function. Can someone help me? :-) # The challenge A lolified message (valid examples above) is just an integer number. Unlolify it by first getting the binary string representation of the number, then left-padding it with the character `0` (zero) as many times as necessary so that the string length is a multiple of 8. Then take each sequence of 8 digits (from left to right) and convert each one of them to its corresponding ASCII character (the digits form a binary representation of an integer). Finally, put together all the resulting characters so that they represent a text string. The challenge is to write the code of the function `unlolify`, which takes a positive integer number as input and outputs the unlolified string. For example, the lolified hexadecimal number `636f6f6c2c206e696365` will output the string `cool, nice`. **Rules:** 1. Output strings will always contain only ASCII characters. Thus, each character is exactly one byte long 2. The number of bits of the input can be arbitrarily high 3. The input must be a positive integer number (`input > 0`) Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` ₈τC ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=%E2%82%88%CF%84C&inputs=0x636f6f6c2c206e696365&header=&footer=) ``` τ # Convert to base... ₈ # 256 C # Get charcodes ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 2 bytes ``` ?P ``` [Try it online!](https://tio.run/##S0n@/98@4P9/EzNLUzNLC0tLI2NzA2MDQ2MTQ0NjQyNTAA "dc – Try It Online") A full program that `?` reads input as an integer and `P` prints the string resulting from the operation specified in the challenge. From its manual page: ``` P Pops off the value on top of the stack. If it it a string, it is simply printed without a trailing newline. Otherwise it is a number, and the integer portion of its absolute value is printed out as a "base (UCHAR_MAX+1)" byte stream. Assuming that (UCHAR_MAX+1) is 256 (as it is on most machines with 8-bit bytes), the sequence KSK 0k1/ [_1*]sx d0>x [256~aPd0<x]dsxx sxLKk could also accomplish this function, except for the side-effect of clobbering the x register. ``` If the input can be assumed to be left on the stack, then just `P` would work for 1 byte. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` bṘ8ẇṘRvBC ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=b%E1%B9%988%E1%BA%87%E1%B9%98RvBC&inputs=469569899237030134113125&header=&footer=) *-6 thanks to @emanresuA* Well frick. I got played. [Answer] # [C (clang)](http://clang.llvm.org/), ~~31~~ \$\cdots\$ ~~28~~ 21 bytes ``` f(a,n){write(1,a,n);} ``` [Try it online!](https://tio.run/##bVHbboJAEH33KzabGEGXFDDWGNqmSdOvEB/oOquk28UAjbSGXy/dC5dF3YSBnXPmzJmBepQn4tA0zEmIcC/nPC3BCYi6RHWTihJ9JalwXHSZIHnoMclRCUUZbHfoGV386nFJkIzMilTF0ERfZ0DHjY6Gv6qjQSzsxNaGslJxvawj3VOZUCxuWEX6CxlztAn3ob3NzZUgCw3HaOi2eqrtXCsWRlHXEuNkxIHqBLSEfSBZmGYZJ0ikFHB0hYcK/4EC3ys2PXopMlSNetEj0E/IDRvH1XsYV5s3@awwQfZ9ids6luXIUctJxR4qWeZH7edTt4au1bCJPhOhxUKzu19rrUZqmfVowi7qcdWNtyi/QU31xzdjkkITzjPq8IWcOHAH0imXIszBfoWt7DBLO4ecgWuLtj27flrJvZTbdGepqKPay6wyKV8DVk9GDK4Ys9fZrTHkvaAYj8w5qoQg7l7PClKk/8/X6@gEYxyLjmTEp4XKeXdPLORcYHfPAbSBNldP6uaPMp4cisY7/wM "C (clang) – Try It Online") *Saved ~~2~~ 9 bytes with an idea from [Johan du Toit](https://codegolf.stackexchange.com/users/41374/johan-du-toit)!!!* *Added 4 bytes to fix a bug* Inputs a pointer to the number and the number's length in bytes (since pointers in C carry no length info). Outputs the message to `stdout`. [Answer] # [jq](https://stedolan.github.io/jq/), 40 bytes ``` [while(.>0;./256%.)%256]|reverse|implode ``` [Try it online!](https://tio.run/##yyr8/z@6PCMzJ1VDz87AWk/fyNRMVU9TFUjF1hSllqUWFafWZOYW5OSnpP7/b25pamphZA4A "jq – Try It Online") -6 bytes from ovs. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~26~~ 22 bytes -4 bytes thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)! If we can take input as a hex string, the `"%x"%` can be removed. ``` ->s{["%x"%s].pack'H*'} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664OlpJtUJJtThWryAxOVvdQ0u99n9BaUmxQlq0QYW5pZmpuXEsF1zAzNgsDQiTjZKNDMxSzSyBfNPY/wA "Ruby – Try It Online") The arbitrary base conversion builtin *Integer#digits* returns the digits in reverse order, which isn't helpful here: ``` ->s{s.digits(256).reverse.pack'C*'} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvJTM9s6RYw8jUTFOvKLUstag4Va8gMTlb3VlLvfZ/QWlJsUJatEGFuaWZqblxLBdcwMzYLA0Ik42SjQzMUs0sgXzT2P8A "Ruby – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 31 bytes Not very interesting, but there conveniently a direct builtin. ``` lambda n:('%x'%n).decode('hex') ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSkNdtUJdNU9TLyU1OT8lVUM9I7VCXfN/QVFmXolCmoZBhZmxWRoQJhslGxmYpZpZAvmmmlwIeXNLM1NzY83/AA "Python 2 – Try It Online") # [Python 3](https://docs.python.org/3/), 28 bytes `str.decode('hex')` no longer exists in Python 3, but is replaced with a similar `b''.fromhex`. ``` lambda n:b''.fromhex('%x'%n) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKkldXS@tKD83I7VCQ121Ql01T/N/QVFmXolGmoZBhZmxWRoQJhslGxmYpZpZAvmmmppcCAXmlmam5saamv8B "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 39 bytes ``` f=lambda n:n and f(n>>8)+chr(n%256)or'' ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc8qTyExL0UhTSPPzs5CUzs5o0gjT9XI1Ewzv0hd/X9BUWZeiUaahkGFmbFZGhAmGyUbGZilmlkC@aaamv8B "Python 3 – Try It Online") *-2 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 37 bytes Expects a BigInt. ``` f=n=>n?f(n>>8n)+Buffer([[n&255n]]):'' ``` [Try it online!](https://tio.run/##DcfdCkAwGAbgu2FLpGkLZcptaAdr9on0Tv5y96Pn6FntY093LPuVI0w@RurQafTEoHUNng03kT/YOCIRUsIY3qZpdAFn2HyxhZkRK19VKfo54USpvGr@S3AePw "JavaScript (Node.js) – Try It Online") Or **33 bytes** without BigInt support (i.e. limited to 32-bit integers): ``` f=n=>n?f(n>>8)+Buffer([n&255]):'' ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zTbP1i7PPk0jz87OQlPbqTQtLbVIIzpPzcjUNFbTSl39f3J@XnF@TqpeTn66RpqGQYVZqpmlmbGZqabmfwA "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₁вç ``` Basically the same approach as [@*emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/235201/52210), with integer as input. [Try it online](https://tio.run/##yy9OTMpM/f//UVPjhU2Hl///b2JmaWpmaWFpaWRsbmBsYGhsYmhobGhkCgA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9TVulif3i9i5KCxuH9mgqP2iYpKNn/f9TUeGHT4eX/vXT@G1SYW5qZmhtzGVSYGZulAWGyUbKRgVmqmSWQbwoA). **Explanation:** ``` ₁в # Convert the (implicit) input-integer to base-256 as list ç # Convert each integer in this list to a character with this codepoint # (after which the resulting list of characters is output implicitly) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` b⁹Ọ ``` [Try it online!](https://tio.run/##y0rNyan8/z/pUePOh7t7/v//b1BhZmyWBoTJRslGBmapZpZAvikA "Jelly – Try It Online") Same as [@emanresu’s Vyxal](https://codegolf.stackexchange.com/a/235201/42248) answer but in Jelly, so be sure to upvote that one too! [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ìG²od ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=7Eeyb2Q&input=MTY2ODI0NzQwNA) ``` ìG²od :Implicit input of integer ì :Convert to digit array in base G : 16 ² : Squared o : Range [0,G²) d : Characters at those codepoints :Implicitly join and output ``` [Answer] # Postscript, 23 bytes for hex input, 105 for decimal The normal way to get a Postscript program to parse arbitrary formats is to concatenate the parser program and the input and send them to the interpreter. That's what I've done for the "no cheating" solutions. I've set up TIO in Bash to put the program in the code section and the message in the input section. The header and footer arrange to concatenate the two and pass them to the interpreter. In the case of binary encoding, TIO's character count is wrong (it expects UTF-8 but we've got hex) so the header puts a line in the debug window with the correct count. ## Hex input, no binary encoding, no cheating, 64 bytes ``` {currentfile 9 string readhexstring exch print not{exit} if}loop ``` [Try it online!](https://tio.run/##LYzBCsIwEAV/5R31UJCKgWKvevUb4nbTBEpSkxUCtd@e7kHmMnOZty2@ncgKxvHxeuIO9TN@mAu6D7q20TdnjuLCwhhQJIc4I7OdPNd/cSWPVVUQk2xcg@wIbl9SWptem7kap1BP/cWwGbRvBw "Bash/Ghostscript – Try It Online") There's nothing clever here. `readhexstring` does the heavy lifting. The `9` is arbitrary, any size will work. TIO counts the code as 64 bytes, but it will be mandatory to have whitespace between the program and the concatenated input string. I'm not sure if that should be counted. If we're prepared to put a limit on the maximum size of the input message then we can make this smaller: ``` {currentfile 999999 string readhexstring pop print}exec ``` As shown, the limit could be sufficiently high that it's not a problem in practice. However, the question explicitly says no limit, so I won't persue this any further. ## Hex input, binary encoding, no cheating, 23 bytes ``` 7b 92 1f 39 92 a5 92 7c 92 3e 92 76 92 70 7b 92 40 7d 92 54 7d 92 65 ``` [Try it online!](https://tio.run/##LY7RCoJAEEXf@4pLRCkklOaKVEJEhRD10g@s06g9lLa7kUH/bqvEwOHcYZiZTOqydZrmCq/W8BRWq915jy8MMxKHqawwTItHpRiX9DzRoFIqSYYVqHo9zBSmZNSqKpS846Yxco6b02G9xZvgkYvsY1gPMU/GvrsESePa7YW99YTXRhliH/McQdyJDDtG1DHg3kXPGfrJwcLKteuEi7@IsLUPtyIQuS3yyZ8JFrHN4Q8 "Bash/Ghostscript – Try It Online") This is a straight binary encoding of the preceding solution. Unlike the non-binary-encoded version, no whitespace is needed between the program and the input. ## Hex input, no binary encoding, cheating, 7 bytes If we're prepared to allow non-standard ways of passing the input, then we can use Postscript's hex string literals to do all the work. This involves sending character "<", then the hex coding of the input, and finally ">print". This is 7 bytes more than the original message. ``` <the message in hex goes here>print ``` [Try it online!](https://tio.run/##S0oszvifnFiiYGPj6u@mUKOQXqygW6ig@9/GzNgsDQiTjZKNDMxSzSyBfFO7gqLMvJL/QJX/AQ "Bash/Ghostscript – Try It Online") Because the message and the program are interleaved, TIO can't count the program characters. ## Hex input, binary encoding, cheating, 4 bytes And, of course there's the binary encoded version of the cheating method where we replace print with its binary encoding `\x92\x76`. This means adding just four bytes to the message being decoded. ``` <the message in hex goes here>\x92v ``` [Try it online!](https://tio.run/##S0oszvifmZyfV6agm6ZQWpKma6GgW6KQWZyva2FhaqlrqGBjo@Dq76ZQo5BerKBbqKD738bM2CwNCJONko0MzFLNLIF8U7tDk8r@A9X9BwA "Bash/Ghostscript – Try It Online") Note that TIO's bash input insists on UTF-8 encoding its input which mangles the `\x92` into two characters so I've used `iconv` in the header to undo that. ## Decimal input, no binary encoding, no cheating, 202 bytes There's a discussion in the comments about whether hex should be allowed. For Postscript, this makes a big difference. Postscript doesn't have any big integer handling. Integer limits are implementation dependent but you can't reliably expect anything longer than 32 bits to work. For hex, the input can be processed in arbitrary chunks. For decimal, we need to convert manually. This makes it a much more interesting problem. The best I have so far is: ``` [[]{{currentfile read{48 sub exch{10 mul add dup 256 mod exch -8 bitshift}forall dup 0 eq {pop} if][exch}{exit}ifelse}loop dup length 1 sub -1 0{2 copy get 1 string dup 0 4 3 roll put print pop}for}exec ``` [Try it online!](https://tio.run/##LY@7boQwEEX7fMUtkwIJYyCgbJu0@wFoCx4DWPJirx8SK8ffTrwozWg092iO7tDb9Xgfe4fL5fv6gy@k/QO/WCyyB7Kj624hjN4Y2twsJMFQP4WygfUDaB/XwHLcvUQ/TW@T1yiqGnc1nRmyBoNwdhWzi7MyvZQnk4MeCFrpCDHfuhcaA@3CRTGTtBSlUvokJW2LW8FOXcaQhwKj0k8s5F5XZ8S2/P8swWGUlNDeQacgzaRI3kg7jUfqd5R1W9Vt07YF/8x5znjJGGdF9Qc "Bash/Ghostscript – Try It Online") Note that this leaves two objects on the stack. As with the earlier non-binary-encoded answer there needs to be whitespace between the program and the input. This requires a lot more explanation: ``` % Our state when we're parsing the input integer is to have two elements % on the stack, a mark (which we'll use later) and an array containing the % integer so far in base 256, least-significant digit first. % % When we read a digit, we multiply the values in the array by ten modulo % 256 overflowing into the next digit. % % The code won't deal with characters that aren't decimal digits, so you % have to be very careful setting up the input to avoid whitespace creeping % in (including a newline at the end). Adding code to deal with this adds 38 % characters to the minimised version. [ [] % Initialise the stack with mark and zero { % Start of exec (so we don't start parsing till the whole % program has been loaded) { % Start of the per-input-digit loop currentfile read % Read one character from the input { % True path: we read a character 48 sub % Convert ASCII digit to decimal ('5' -> 5) exch % Now have: mark new-digit array-of-current-total { % Start of per-existing-digit loop % Stack: mark already-processed-digits adder next-digit 10 mul % Multiply the existing base-256 digit by ten add % Add new input digit (first pass) or overflow dup % Need the result twice: new digit and overflow 256 mod exch % New digit -8 bitshift % Overflow % Stack: mark already-processed-digits adder=overflow } forall % End of per-existing-digit loop dup 0 eq {pop} if % If the last overflow was zero, discard it % We don't want lots of zeros at the top ] % Use the mark on the stack to reform the array [ exch % Replace the mark below the array } {exit} ifelse % False path: end of file encountered } loop % End of input processing % We now have an array with the input converted to base 256 % We can't use forall on this as that would start with the % least-significant digit and we need to start at the top. So, we'll % use a count-down for loop to access the array elements. dup length 1 sub -1 0 { % Start of per-character output loop % To convert to a character we put the digit into a 1 character string % For the next bit, "1 index exch" is neater than "2 copy ... pop" % but the latter is two characters shorter in non-binary encoding. % In binary, they're the same length. % Stack: mark base-256-array index 2 copy % Stack: mark array index array index get % Stack: mark array index digit 1 string dup 0 % Stack: mark array index digit string string 0 4 3 roll % Stack: mark array index string string 0 digit put % Stack: mark array index string print % Print the converted character pop % Lose the duplicated index } for % End of per-character output loop } exec ``` It feels like it should be possible to golf this down to something shorter. ## Decimal input, binary encoding, no cheating, 105 bytes ``` 5b 5b 5d 7b 7b 92 1f 92 7b 7b 34 38 92 a9 92 3e 7b 31 30 92 6c 92 01 92 38 32 35 36 92 6a 92 3e 2d 38 92 0f 7d 92 49 92 38 30 92 3d 7b 92 75 7d 92 54 5d 5b 92 3e 7d 7b 92 40 7d 92 55 7d 92 65 92 38 92 62 20 31 92 a9 2d 31 20 30 7b 32 92 19 92 4b 31 92 a5 92 38 30 88 04 33 92 87 92 78 92 76 92 75 7d 92 48 7d 92 3f ``` [Try it online!](https://tio.run/##RVFdS8NAEHzPrxiKaAMG7jO5w1oQUSmIffEPXC7XxgebmkSs4H@P2UuqsCyzu3Ozs1zpunpYnk4VsmOHrMVq9bB9xA/6ELBeBl83WGz2h6YNeN1srzr42rXO96GFbz4P/TX6OuDYNvvWveOtw8Xy@e7l6fYeXx6ZT1F@96FbgK8vRXoD7/p0VN@Puz6QDboERYWipLACfEd5KqWCNFQ6S1mGhJocklGZe8qMx5GBHLOGzOPIzXxRzQpsh6IioOyZH0VkNe8t9EhIRqAV@dHlpECvJoJis4LWM8h1MkkRFhCMvE1uaS@PHRYPEfE0S3xVnmn634kxYOOxkjqmiH5INinyP2/Rg5mB3A3jNw0qtzq3xlohCyYZl4pzyYX@BQ "Bash/Ghostscript – Try It Online") This is a straight binary encoding of the preceding solution. No whitespace is needed between the program and the input. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes ``` ⭆↨N²⁵⁶℅ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaDglFqdqeOYVlJb4leYmpRZpaOooGJmaAUlnoJ7E5BKgUKampqb1///RBhVmxmZpQJhslGxkYJZqZgnkm8b@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Prefers to input a decimal integer, but you can make Charcoal accept hexadecimal by prefixing `[0x` and suffixing `]` as per the linked example. Explanation: ``` N Input as an integer ↨ ²⁵⁶ Convert to base 256 ⭆ Map over values and join ι Current value ℅ Convert to ASCII character Implicitly print ``` ]
[Question] [ Your task is to print out this exact text: ``` - || -|- |--- |-|-- -|-|-- -|----- |-|----- |---|-|-- -|-----|-- ---|-|----- |---|-|----- |---|-----|-- -----|---|-|-- -|-|---|------- ------|---|----- |-|---------|-|-- ---|-----|---|---- -|-----|-|--------- |-|---|-|----------- |-----------|---|-|-- -|-----|-|---------|-- ---|-----|-----|-|----- |---|-|---------|------- ------|---|-|---|-------- -----|-----|---------|-|-- -|-----|-------|-----|----- |---|-----|-------|---|----- --|---------|-|---------|-|-- ---|---|-----|-------|---|-|-- -|-----------|-------|---|----- --|---|-----|-----------|-|----- ------------|-----|---------|---- -|-----|-|-----|---------|-----|-- ---|-|-----|-----|---|-|----------- |---------|-|---|-----|-----|-|----- ------|---|-----|-------|---------|-- -----|---------|-------|-----|-----|-- -|-------|-----|---|-------|---|------- ------|---------|-----------|-|--------- ``` It at first look seems meaningless repititions of `-` and `|`, but it has a nice hidden pattern inside it. I won't reveal it now. Binary matrix or 2D lists are not accepted as output. Exactly this text is required. But output can have trailing whitespace. You can use any non-number character in place of `-` and `|` Shortest code wins. [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` p=n=i=1 while i<41:s='';exec"s+='-|'[p%n];p*=n*n;n+=1;"*i;i+=1;print s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8A2zzbT1pCrPCMzJ1Uh08bE0KrYVl3dOrUiNVmpWNtWXbdGPbpANS/WukDLNk8rzzpP29bQWkkr0zoTxCgoyswrUSj@/x8A "Python 2 – Try It Online") > > *The `|`s mark the position of primes.* > > > The idea here, as with many prime-related tasks in Python, is to use [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem). Essentially, \$ (n - 1)!^2 \bmod n \$ will equal 1 if \$ n \$ is prime, and 0 if it is not. [@xnor](https://codegolf.stackexchange.com/users/20260/xnor) gives a more in-depth explanation [here](https://codegolf.stackexchange.com/a/27022/88546) if you're interested. > > > [Answer] # [J](http://jsoftware.com/), 29 26 25 bytes ``` ({&'-|'/.1 p:#\)@(#~i.41) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NarV1HVr1PX1DBUKrJRjNB00lOsy9UwMNf9rcqUmZ@QrpCmoq/8HAA "J – Try It Online") -3 thanks to an idea from Lynn! -1 thanks to xash! [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 11 bytes ``` 40RRȷR¤ṁẒỌY ``` [Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCI0MFJSyLdSwqThuYHhupLhu4xZIiwiIiwiIixbXV0=) > > The `|`s are at prime indexes > > > I figured out the pattern by smash-printing the rows into one flat string and realizing that the distribution looked familiar :P I had another idea to use base conversion but I decided to flatten the string first and then noticed. Leaky Nun has two tricks in [their answer](https://codegolf.stackexchange.com/a/231195/68942) - firstly, that you can take the range up to `1000` (which is shorter) since `mold` will discard extras, and secondly, I didn't notice other characters were allowed, so the digraph nilad `ØA` is shorter. Jonathan Allan also noticed that we can just use `chr` and output the unprintables 0x00 and 0x01, so thanks to both of them for the byte saves. Please go upvote Leaky Nun's answer as well. ``` 40RRȷR¤ṁẒỌY Main Link (Niladic) 40 Start at 40 R Range; [1, 2, ..., 40] R Range; [[1], [1, 2], [1, 2, 3], ...] ṁ Mold; to the shape of [[1], [1, 2], [1, 2, 3], ...], reshape ȷR¤ Range of 1000 ([1, 2, 3, ..., 1000]) - extra elements are discarded Ẓ x => isprime(x) Ọ chr Y Join on newlines ``` There are a couple of ways to go about this idea - you can swap which list you generate first, you can index into a multitude of other strings, you can prime-check before or after molding since it vectorizes and thus doesn't really care what shape it is, etc. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ȷRẒṁ40RR¤ịØAY ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//yLdS4bqS4bmBNDBSUsKk4buLw5hBWf// "Jelly – Try It Online") Uses `Z` and `A` instead of `-` and `|`. This is basically the same answer as [@hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)'s [answer](https://codegolf.stackexchange.com/a/231193/48934), which was published 3 minutes before mine, but our answers arose independently. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ØYxJĠẒỌY ``` [Try it online!](https://tio.run/##y0rNyan8///wjMgKryMLHu6a9HB3T@T//wA "Jelly – Try It Online") ``` ØY The string "BCDFGHJKLMNPQRSTVWXZbcdfghjklmnpqrstvwxz" xJ Repeat "B" once, "C" twice, "D" thrice... "z" 40 times. Ġ Group indices by values: [[1], [2,3], [4,5,6], …, […820]] ↑B ↑C ↑D ↑z Ẓ Is prime? Ọ Translate 0,1 into "\x00","\x01" Y Join lines ``` [Answer] # Excel, 110 bytes ``` =LET(a,SEQUENCE(820),CONCAT(IF(MMULT((MOD(a,TRANSPOSE(a))=0)*1,a^0)=2,"|","-")&IF(MOD(SQRT(8*a+1),1),""," "))) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnEVkHnsSzG5dz3kf?e=jllJVx) ``` =LET(a,SEQUENCE(820), a = (1..820) CONCAT( concatenate the following IF(MMULT((MOD(a,TRANSPOSE(a))=0)*1,a^0)=2,"|","-")& if a is prime (has 2 factors) then "|" else "-" IF(MOD(SQRT(8*a+1),1),""," if a is triangular (8a+1 is a perfect square) then add a line feed "))) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` A820ÅTüŸ€¦pèJ» ``` [Try it online!](https://tio.run/##ASAA3/9vc2FiaWX//0E4MjDDhVTDvMW44oKswqZww6hKwrv//w "05AB1E – Try It Online") -1 byte thanks to ovs ``` A820ÅT>üŸ€¦pèJ» Full Program A Push "abc...xyz" 820 Push 820 ÅT Pop 820; Push [0, 1, 3, 6, 10, ...] (triangular numbers) üŸ Pairwise range; get [[0, 1], [1, 2, 3], [3, 4, 5, 6], ...] €¦ For each sublist, remove the first element p Primality; get the 2D list of 1s and 0s è Index into "abc...xyz" J Join each row into a string » Join the result into a multiline string ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` jmsm@GP_hkrZ=+ZdS40 ``` [Try it online!](https://tio.run/##K6gsyfj/Pyu3ONfBPSA@I7soylY7KiXYxOD/fwA "Pyth – Try It Online") Uses `a` and `b` instead of `-` and `|`. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 1249 bytes ``` ++++++++++[>+>++++>++++++<<<-]>>.<.>>..<<.>.>.<.<.>>.<...<.>>.<.>.<..<.>.>.<.>.<..<.>.>.<.....<.>>.<.>.<.....<.>>.<...>.<.>.<..<.>.>.<.....>.<..<.>...>.<.>.<.....<.>>.<...>.<.>.<.....<.>>.<...>.<.....>.<..<.>.....>.<...>.<.>.<..<.>.>.<.>.<...>.<.......<.>......>.<...>.<.....<.>>.<.>.<.........>.<.>.<..<.>...>.<.....>.<...>.<....<.>.>.<.....>.<.>.<.........<.>>.<.>.<...>.<.>.<...........<.>>.<...........>.<...>.<.>.<..<.>.>.<.....>.<.>.<.........>.<..<.>...>.<.....>.<.....>.<.>.<.....<.>>.<...>.<.>.<.........>.<.......<.>......>.<...>.<.>.<...>.<........<.>.....>.<.....>.<.........>.<.>.<..<.>.>.<.....>.<.......>.<.....>.<.....<.>>.<...>.<.....>.<.......>.<...>.<.....<.>..>.<.........>.<.>.<.........>.<.>.<..<.>...>.<...>.<.....>.<.......>.<...>.<.>.<..<.>.>.<...........>.<.......>.<...>.<.....<.>..>.<...>.<.....>.<...........>.<.>.<.....<.>............>.<.....>.<.........>.<....<.>.>.<.....>.<.>.<.....>.<.........>.<.....>.<..<.>...>.<.>.<.....>.<.....>.<...>.<.>.<...........<.>>.<.........>.<.>.<...>.<.....>.<.....>.<.>.<.....<.>......>.<...>.<.....>.<.......>.<.........>.<..<.>.....>.<.........>.<.......>.<.....>.<.....>.<..<.>.>.<.......>.<.....>.<...>.<.......>.<...>.<.......<.>......>.<.........>.<...........>.<.>.<......... ``` [Try it online!](https://tio.run/##jVNbCsIwEDxQcU6w5CLihwqCCH4Inj82lbTp7GzSfDSdfWUzs7l9rs/343t/5Tyt65ymVPb0h2Z2uqQEw/yBzRsKWKAB9WcB1bkDoKANQgevhsYvk9hIydWo21sztnByUNPgUnRoRXyVNn9Xkp3NbdrzOixxa7KtAyxiRAczRgwjJskHsEVLqPUIDuqp06vqusTRBtS9HdEQNQXlkapKneBt@EHsDpaXNBgVxYJXMnh3GAgv2JcPSmBqDQMtysr5Bw "brainfuck – Try It Online") Kind of boring; just a hardcoded solution. I'm trying to create a solution that computes it with the prime relation, but I'm not that experienced in brainfuck and also I'll need to find an interpreter that goes up to 820 if I don't want excessive pain and suffering. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 16 bytes ``` 40ɾƛʁƛkA¥›:£æi;ṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=40%C9%BE%C6%9B%CA%81%C6%9BkA%C2%A5%E2%80%BA%3A%C2%A3%C3%A6i%3B%E1%B9%85&inputs=&header=&footer=) -1 byte thanks to @hyper-neutrino > > Replace all those characters with numbers from 1, 2 and so on. The |'s are at prime indices. So then it's easy. > > > > > (pxeger spoiled it, though I came to it independently) > > > [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~23~~ 19 bytes ‒1 thanks to Razetime. Full program. ``` ↑⎕UCS{1⍭⍳≢⍵}⍢∊,\⍳40 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKO94P@jtomP@qaGOgdXGz7qXfuod/OjzkWPerfWPupd9KijSycGKGJiAFL6vwAA "APL (Dyalog Extended) – Try It Online") `⍳40` **i**ndices 1 through 40 `,\` prefixes of that; `[1,[1,2],[1,2,3],`…`,39,40]]` `{`…`}⍢∊` apply the following anonymous lambda to the **e**nlisted (flattened) data:  `⍵` the argument; `[1,1,2,1,2,3,`…`,39,40]`  `≢` the length of that; `820` > > `1⍭` indicate which elements are prime; `[0,1,1,0,1,0,`…`,0,0]` > > > `⎕UCS` convert to characters in the **U**niversal **C**haracter **S**et; `[\x00,\x01,\x01,\x00,\x01,\x00,`…`,\x00,\x00]` `↑` mix the list of strings into a matrix, padding with spaces as necessary to make it rectangular; `["\x00` …`","\x01\x01` …`",`…`\x00\x00\x00\x00\x00\x00`…`\x00\x00"]` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 223 bytes ``` -[>-<-----]>[>++++[<[[->>>+<<<]>]<+>>>-]<-]>>-[--->+<]>[<<<<<[>+[[>]>]>>[->+>]>[[-<+>]<<[-<<<[[<]<]>>[-]-[[>]>]>]+>>>>]<<<<<<<[[<]<]<]>+[->>>]<[-<+>]<-]<<<+<+<--[>[[[-<<<+>>>]>]<<-[---<+>]<.[-]<+<-]++++++++++.[-]>[-<+>]+<<] ``` [Try it online!](https://tio.run/##PY9BCkIxEEMPNIwnCLlIyEIFQQQXguevmf6P6aKleUmnt8/1@X5876@1Wmz0yBQrEqQmWQBMo3JuIz5b4WIExSgBiYHIRCp7ogk4Vo8vGNt0n6CnboCjYANBaj9pnPEeoLI680m7bIIzD/YUG7ukeCDXX3PFoyUf8Fo/ "brainfuck – Try It Online") Uses trial division up to 86 to determine every prime up to 820. Outputs `T` for `-` and `V` for `|`. ``` Populate list of 820 numbers not yet considered composite -[>-<-----]>[>++++[<[[->>>+<<<]>]<+>>>-]<-] tape is 1 0 0 1 0 0 1 etc 1 0 0 1 0 (0) Create 85 to test visibility by up to N=86 (which is high enough and short to create) >>-[--->+<]> working tape will be 1 0 0 1 0 0 1 etc 1 1 0 1 1 0 (0 or 1) x y 0 0 with x plus y = 85 in first iteration For all numbers from 85 down to 1: (N is this number plus one) [ For all numbers to sieve: <<<<<[ Mark number seen >+ Decrement x and increment y if x is nonzero [[>]>]>>[->+>] Otherwise, the last number was divisible by N >[ Move y back to x [-<+>] If this isn't the first time we've seen a multiple of N: <<[ Mark number composite -<<<[[<]<]>>[-]-[[>]>]> Mark that we've seen a multiple of N ]+>>>> ] Go to next number (for loop termination condition) <<<<<<<[[<]<]< Repeat until all 820 numbers checked ] Remove all "seen" markings and "seen multiple of N" >+[->>>] Copy whatever was left of y back to x and decrement <[-<+>]<- ] Now all numbers have been checked and marked composite if applicable We are 5 cells right of first number (1) now Set up counters for triangle shape (x=1 for first row; and y=1 so y is always nonzero) <<<+<+ Mark 1 as nonprime <-- For each number [ While x is nonzero >[ Move x and y left three cells [[-<<<+>>>]>] Add 85 to primality indicator to output ASCII <<-[---<+>] Output and remove number <.[-] Increment y and decrement x <+<- ] Output newline ++++++++++.[-] Copy y to x (now one more than it was; restore y=1) >[-<+>]+ <<] ``` [Answer] # [Python 3](https://docs.python.org/3/), 105 bytes ``` r=range for i in r(1,41): for j in r(i):n=i*~-i//2-~j;print(end="-|"[all(n%y for y in r(2,n))]) print() ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v8i2KDEvPZUrLb9IIVMhM0@hSMNQx8RQ04qLEySUBRHK1LTKs83UqtPN1Nc30q3Lsi4oyswr0UjNS7FV0q1Rik7MydHIU61UAGmphGgx0snT1IzV5OKEKNX8/x8A "Python 3 – Try It Online") One byte longer than wasif's, but no `exec` trick used here. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 98 bytes ``` r=range for _ in r(n:=1,41):s="";exec("s+='-|'[all(n%y for y in r(2,n))and n>1];n+=1;"*_);print(s) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v8i2KDEvPZUrLb9IIV4hM0@hSCPPytZQx8RQ06rYVknJOrUiNVlDqVjbVl23Rj06MSdHI0@1UgGkvBKi3EgnT1MzMS9FIc/OMNY6T9vW0FpJK17TuqAoM69Eo1jz/38A "Python 3.8 (pre-release) – Try It Online") -6 bytes thanks to @hyper-neutrino and @pxeger [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~13~~ 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Uses `f` for composites and `t` for primes. ``` #(õ_ç Ëî°Tj ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=Iyj1X%2bcgy%2b6wVGo) ``` #(õ_ç Ëî°Tj #( :40 õ :Range [1,40] _ :Map each Z ç : Z spaces (could be any character) Ë : Map each character î : Slice the following to length (always 1) °T : Prefix increment T (initially 0) j : Is prime? (Returns a Boolean which gets coerced to a string by î) :Implicit output joined with newlines ``` # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Preserving this version as I quite liked the `ú` trick. Uses `q` for qomposites(!) and `p` for primes. ``` 40õ_ç¬Ëú²g°Tj ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=NDD1X%2besy/qyZ7BUag) ``` 40õ_ç¬Ëú²g°Tj 40õ_ :Map each Z in the range [1,40] ç : Repeat to that length ¬ : "q" Ë : Map each character ú : Left pad ² : With "p" to length 2 g : Get the character at index °Tj : As above, with the Boolean this time coerced to 0 or 1 :Implicit output joined with newlines ``` [Answer] # JavaScript (ES7), 78 bytes A recursive function going from \$k=820\$ to \$k=1\$ and testing whether \$\sqrt{8k+1}\$ is an integer to detect triangular numbers and figure out where line-feeds have to be inserted. ``` f=(k=820)=>k?f(k-1)+'-|'[(g=n=>n%--d?g(n):+!~-d)(d=k)]+[` `[(1+8*k)**.5%1]]:'' ``` [Try it online!](https://tio.run/##BcFBCoMwEADAe3/Rg2Q3YaUpFERYfUgIKMaENrIptfQkfj2dec2/eV8@z/eXpIS11siQubvfkIc8Rshk0Sg6lIPEwoM0RGFMINib60kBIXBGb9x0mRxY0@mMWrePxnrfK1WXInvZ1nYrCSIg1j8 "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, ~~11~~ 14 bytes ``` 40ƛɽ÷Ṡnɾ+æ₁+Cṅ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=40%C6%9B%C9%BD%C3%B7%E1%B9%A0n%C9%BE%2B%C3%A6%E2%82%81%2BC%E1%B9%85&inputs=&header=&footer=) ~~I'm posting this because it's significantly shorter than the other one.~~ I didn't realise the *non-number* rule, but still fairly short. ``` 40ƛ # Map 1...40 to... ɽ÷Ṡ # Sum of 1...n-1 nɾ+ # Added to each of 1...n, this produces the correct indices æ # Is prime (vectorised) ₁+C # Add 100 and get the corresponding character (d or e) ṅ # Joined # (j flag) join by newlines ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞40L£pçJ» ``` Uses unprintables `\0` and `\1` instead of `-` and `|`. [Try it online.](https://tio.run/##yy9OTMpM/f//Ucc8EwOfQ4sLDi/3OrT7/38A) **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] 40L # Push list [1,2,3,...,38,39,40] £ # Split the first list into parts with the lengths of the second list # (removes any unused trailing items): [[1],[2,3],[4,5,6],...] p # Check for each integer whether it's a prime (1 if it's a prime; 0 otherwise) ç # Convert it to a character with this codepoint: \0 and \1 J # Join each inner list together to a single string » # And join those strings by newlines # (after which the result is output implicitly) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~101~~ \$\cdots\$ ~~98~~ 97 bytes ``` p;r;d;f(n){for(n=r=0;++r<41;puts(""))for(;r*-~r>2*n;printf(L"-|"+p))for(p=d=n++;d>1;p=n%d--&&p);} ``` [Try it online!](https://tio.run/##JYtBCsIwEADveUUJWHYbFlS8rekL/ERJSCnoGrYVD7U@3RhxrjMTaAyhlMzKkRMIrumuIF79np3T8@nA@bHMYC3iz7B29Nb@2AlnnWRJcLH0si7/dfbRi3Mc@/p52UWits3IW6ltcxsmATSraSoJkM1WPiFdh3Eu9PwC "C (gcc) – Try It Online") Saved a byte (and got below \$100\$!) thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!! Saved another byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)!!! Saved yet another byte from [Juan Ignacio Díaz](https://codegolf.stackexchange.com/users/112488/juan-ignacio-d%c3%adaz)!!! [Answer] # [Factor](https://factorcode.org/), 75 bytes ``` 820 [1,b] [ prime? 43 45 ? ] ""map-as 40 [1,b] [ cut swap print ] each drop ``` [Try it online!](https://tio.run/##Rcu7DsIwEETRXxmlBsTDSAiKlBENDaKKUixmIVHiB2tH@XzHQEF3NTrzJB2dpNv1fKmOMBTblZfOcPi1kH3l7lksDwj8HtnqPHQOp3TYrlFvFvcGNb6nEmoHtUeJBkVhyC8pQP2RHiPCRP6jbcyISbd4iPMpzQ "Factor – Try It Online") * `820 [1,b]` Create a range from 1 to 820 inclusive. 820 is the number of elements in the triangle sans newlines. * `[ prime? 43 45 ? ] ""map-as` Create a flat version of the triangle as a string, where `43` is the code point for `+` and `45` is the code point for `-`. `|`'s code point has 3 digits so I changed this (as it is allowed by the rules). * `40 [1,b] [ cut swap print ] each drop` Cut the sequence in two at ever-increasing indices, printing each line after it is cut off from the main sequence. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes ``` 820$*| .(?<=^\1+(..+)) - ^. -¶ +`(.)+¶(?=.+$)(?<-1>.)+. $&¶ ``` [Try it online!](https://tio.run/##K0otycxL/P@fy8LIQEWrhktPw97GNi7GUFtDT09bU5NLlytOj0v30DYu7QQNPU3tQ9s07G31tFU0gcp0De2AInpcKmqHtv3/DwA "Retina 0.8.2 – Try It Online") Explanation: ``` 820$*| ``` Insert 820 `|`s. (820 = 40 × 41 ÷ 2) ``` .(?<=^\1+(..+)) - ``` Change most of them to `-`s appropriately. ``` ^. -¶ ``` Change the first one too, and start building the triangle. ``` +`(.)+¶(?=.+$)(?<-1>.)+. $&¶ ``` Build up each row of the triangle to be one character longer than the previous. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` G↓→⁴⁰ψ¤⭆⁸²⁰§-|﹪ΠE⊕ι∨λ±¹⊕ι ``` [Try it online!](https://tio.run/##VYrLCsIwEADvfsXS0wa2oOJB2pMgQg/Vol8Q0pAG1qyE@Cj47zE9OpeBYcykoxHNOQ/Cs5OAzVHegaC5ejclgt2aYFbt6uSZ8ZaiD67XD9xvSz@kLoz2g1X9rQh6GZ8sOMRik3C5umCivduQ7IheEVwiMsHZOp0sblSB4P9ZaHPO9Yt/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` G↓→⁴⁰ψ ``` Draw an empty triangle of side 40. (Unfortunately Charcoal doesn't have a 1-byte shortcut for a triangle in this orientation.) The `y` variable is the null byte, which has a special meaning for the `Fill` function, in that it counts as a fillable area. ``` ¤⭆⁸²⁰§-|﹪ΠE⊕ι∨λ±¹⊕ι ``` Calculate the first 820 factorials, negate them, reduce them modulo the incremented index, and index the results into the string `-|`. Use this to fill the triangle drawn above. (Charcoal's `Fill` works by painting the string across the region to be filled, rather than repeating it horizontally and vertically. See @ASCII-only's answer to [Bake a slice of Pi](https://codegolf.stackexchange.com/questions/93615/) for another example of how it works.) [Answer] # [Julia 1.0](http://julialang.org/), 76 bytes ``` f(y=1)=1:40 .|>i->print.(y:(y+=i).|>j->" -|"[j==y||2+(2==sum(j.%(1:j).<1))]) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P02j0tZQ09bQysRAQa/GLlPXrqAoM69ET6PSSqNS2zZTEyiYpWunxKVboxSdZWtbWVNjpK1hZGtbXJqrkaWnqmFolaWpZ2OoqRmrCTRM8z8A "Julia 1.0 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 73 bytes ``` say join($/,map$"x$_,1..40)=~s/./!$n++|(grep$n%$_==0,2..$n-1)?"-":"|"/ger ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhKz8zT0NFXyc3sUBFqUIlXsdQT8/EQNO2rlhfT19RJU9bu0YjvSi1QCVPVSXe1tZAx0hPTyVP11DTXklXyUqpRkk/PbXo//9/@QUlmfl5xf91fctM9QwNAA "Perl 5 – Try It Online") ``` say # print triangle string, say adds a \n at the end join($/,map$"x$_,1..40) =~ # make multi-line triangle # of $" (spaces) and $/ (newlines) s/ / # replace spaces !$p++ # count position, ! prevent first from becoming "|" | # bit-or instead of || or 'or' (grep $p%$_==0, 2..$p-1) # check if $p position is a prime ? "-" # replace non-prime $p with - : "|" # replace prime $p with | /ger # g=replace all, e=eval, r=return triangle to say ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` Cḣ40mȯc¬ṗN ``` [Try it online!](https://tio.run/##yygtzv7/3/nhjsUmBrkn1icfWvNw53S///8B "Husk – Try It Online") (but you won't be able to easily view the output of non-printable characters) or [Try this online instead](https://tio.run/##ARoA5f9odXNr//9D4bijNDDhuYHIr3PCrOG5l07//w) to see the output switched to `0` and `1` characters. Derived independently to [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/233634/95126), but it turns-out to use almost exactly the same approach... Unfortunately [Husk](https://github.com/barbuz/Husk)'s prime-checker `ṗ` returns the index in the list of primes, rather than `1` or `0`, costing one extra byte. ``` mȯ # map over N # the infinite list of integers: c # character corresponding to ¬ # logical NOT of ṗ # index in list of primes; C # now cut into substrings ḣ40 # with lengths of 1..40 ``` [Answer] # [BBC BASIC](https://github.com/isaacg1/pyth), 147 bytes ``` L=820 T=1 C=0 F.N=1TOL IFFNF(N-1)^2MODN=0TH.P."-";:EL.P."|";:ENDIF C+=1 IFC=T TH. T+=1 C=0 P.'; ENDIF N.N END DEF FNF(A)IFA=1ORA=0TH.=1 =A*FNF(A-1) ``` I won't lie, this is definitely not the best algorithm, but I did at least golf it down as much as I could. [Answer] # [Haskell](https://www.haskell.org), 134 bytes ``` []#n=[] a#n=take n a:drop n a#(n+1) main=putStrLn$foldl(\a b->a++'\n':b)"-"$["|-"!!fromEnum(0`elem`map(x`mod`)[2..x-1])|x<-[2..820]]#2 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWN9uiY5XzbKNjuRKBVElidqpCnkKiVUpRfgGIoayRp22oyZWbmJlnW1BaElxS5JOnkpafk5KjEZOokKRrl6itrR6Tp26VpKmkq6QSrVSjq6SomFaUn-uaV5qrYZCQmpOam5CbWKBRkZCbn5KgGW2kp1ehaxirWVNhowviWBgZxMYqG0FcA3UUzHEA) ]
[Question] [ ## Challenge: Given the input array `l` with a list of strings, only keep the elements in the sequence that have a letter that's repeated at least 3 times. Like `'lessons'` has 3 `s` letters, so it should be kept in the sequence. But, `'lesson'` has only two `s` letters, so it should be removed. ## Notes: * `l` will always be a sequence, and its elements will always be strings with only alphabetical characters. * I am using the example output with Python Lists. You can use any type of sequence in your own language. ## Test cases: ``` ['element', 'photoshop', 'good'] -> ['element', 'photoshop'] ['happy', 'colorful', 'luggage'] -> ['luggage'] ['reference', 'tomorrow', 'today'] -> ['reference', 'tomorrow'] ``` 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/), ~~51~~ 50 bytes ``` lambda l:{s for s in l for c in s if s.count(c)>2} ``` [Try it online!](https://tio.run/##HcdLCoAgEADQq8xOhWhRu6AuUi3MTwbmSNoiorNP2e69eGWHoSXbT@TlvmgJvrsTWDwgwRbA/1SF3y2kWuEZMldiaB6Kx/bZ8pEZb3YTMquARYcZk8NYsiJqNgtBLw "Python 3 – Try It Online") [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 13 bytes Takes linebreak-separated text ``` (.).*\1.*\1 % ``` [Try it online!](https://tio.run/##FcYxDoAgEATAfv9hohYm/seGyAnFweIJMb4etZhkzub81fu4TMu8rT8MvYtKklxRIiuvyIJAeiC6Uh7sVNrRFNpCcEEAk0NM8i6oTDTj/cW75wU "QuadS – Try It Online") Search for… `(.)` any character (1) `.*` zero or more characters `\1` character (1) `.*` zero or more characters and for each match, return: `%` the entire line the match occurred on [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ü d¤ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=/CBkpA&input=WyJyZWZlcmVuY2UiICJ0b21vcnJvdyIgInRvZGF5Il0KLVI) ``` ü d¤ :Implicit filter of input array ü :Group & sort d :Any truthy (a non-empty string) ¤ : Slice off the first 2 characters ``` ## Without flag, 6 bytes ``` fÈü d¤ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Zsj8IGSk&input=WyJyZWZlcmVuY2UiICJ0b21vcnJvdyIgInRvZGF5Il0KLVI) [Answer] # [Python 3](https://docs.python.org/3/), 55 bytes ``` lambda a:filter(lambda x:any(x.count(i)>2for i in x),a) ``` Returns a filter object. The asterisk is used in the output to unpack the filter object automatically. [Try it online!](https://tio.run/#%23LclBCgIxDEDRq2TXRgYXuhvQi6iL1GltoJOUGqFz@uqAq8/j182yynmky30UWsNCQHPiYrH5v/tMsvl@fOpHzDNeT0kbMLBAx4lw1Ma/cUj@5mKJaxRzE7ia1fSdte54qS57iSiE4B6I4ws) # [Python 2](https://docs.python.org/2/), 55 bytes ``` lambda a:filter(lambda x:any(x.count(i)>2for i in x),a) ``` Exactly the same code, just returns a normal Python list instead of a filter object, meaning you don't need to use the asterisk in the output (if that matters). [Try it online!](https://tio.run/##LcnBCsIwDIDhV8mtDQwPOw70RdRDurU20CWlRuievjrw9PPx18OyyjzS9TEK7WEjoCVxsdj8330hOXy/rPoR84y3OWkDBhboOBGO2vg3kr@7WOIexdwErmY1fWetJ16q21kiCiG4J@L4Ag) [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~6.5~~ 5.5 bytes (11 nibbles) *Edit: -2 bytes by using transpose, inspired by [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/255976/95126)* ``` |$>2`'=~$$ ``` ``` |$ # filter each word int the input by =~$ # group the letters by $ # themselves, `' # transpose this list of lists, >2 # and remove the first 2 elements # (so if there is at least one letter # present >2 times, the resulting # list will have nonzero length) ``` [![enter image description here](https://i.stack.imgur.com/15ifu.png)](https://i.stack.imgur.com/15ifu.png) [Answer] # GNU grep -P, 11 bytes ``` (.).*\1.*\1 ``` P.a. to selecting the language flavour for perl, I'm not counting -P (which sets the language flavour to PCRE from the default BRE). "List of string" defined as "text file" (POSIX). Test case typescript: ``` $ printf '%s\n' \ 'element' 'photoshop' 'good' \ 'happy' 'colorful' 'luggage' \ 'reference' 'tomorrow' 'today' \ | grep -P '(.).*\1.*\1' element photoshop luggage reference tomorrow ``` [Answer] # [Python 3](https://docs.python.org/3/), 48 bytes ``` lambda s:[c for c in s if max(map(c.count,c))>2] ``` [Try it online!](https://tio.run/##dYxBDsIgFET3PcVPXABJ40J3JnqRygLpB5oAn1Ca2tNjiEl1obuZzHuTtuIonqu53qtX4TEqmC@DBkMZNEwRZpgMBPXkQSWuj5qWWHotxO0ka8pTLNzwgaHHgLGwHlhyVGh2lFqxRCOTQsAB/kCy@7w4ldLWZk2esll8y36xVlncX/b@JWY0mDFqbEKhQDnT@s6j2nb1Nyahqy8 "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->l{l.grep /(.).*\1.*\1/} ``` [Try it online!](https://tio.run/##dYzBCsIwEETvfsWCh6jYFD/A/kjNIbab5JB2wzZBgvjtkVCRHvQwMLP7ZjjdczHX0nT@6aVlDNAe5FGebpeq9lUCmL4X6HHCOYoziOAo0uIo1GCJRqEU7KHp4A@mduuG0yHk@hrIE5vkq/fJWm1xs/G9fGqMBhnnASseaSJmeqx@1HlT/A0qKG8 "Ruby – Try It Online") [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 11 bytes ``` gFI2<M:^_N_ ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJnRkkyPE06Xl9OXyIsIiIsImVsZW1lbnQgbGlzdCBnb29kIGNpdmlsaXphdGlvbiIsIi1wIl0=) ### Explanation ``` gFI2<M:^_N_ g List of command-line arguments FI Filter by this function: 2< 2 is less than M the maximum of : (force the precedence of unary M to be lower than its rhs) N_ the number of occurrences in the argument string of ^_ each character in the argument string ``` [Answer] # JavaScript, 37 bytes I/O as an array of strings, using [~~GB's~~ Adám's RegEx](https://codegolf.stackexchange.com/a/255906/58974). ``` a=>a.filter(s=>/(.).*\1.*\1/.test(s)) ``` [Try it online!](https://tio.run/##bYtBDsIgEEX3nsIdYJTGA7QXURcTGGjNlCEw1fT0GOLOuPjJ@8l7T3hBdWXJcknssYWxwTiBDQsJFl3HadDW2NP92jdYwSq6GtMcp8qEljjqoG8KCVdMos5HlWcWrjPnfiKzVw9jDr/BDDnv3XBMXMJGnWmLESL@DQoGLJgcdlF45VL4/WUPe0/aBw) ## ~~44~~ 42 bytes I/O as an array of character arrays. ``` a=>a.filter(a=>a.some(c=>(a[c]=-~a[c])>2)) ``` [Try it online!](https://tio.run/##bY1BDoMgEEX3PUV3QNKy6LbBixgTJzigBhgC2MZNr25Fd01X81/@f5kZXpB1mmK5BxpwMwpUYzlID5Fn1bRSytwJcfBegZxpCn0vnlZtB5vJFUxnl8kj16rh0OpO3T/1iOYhxKYpZHIoHVlueMvQocdQ2O3K4kiF8kixgiUa2P7v8iuMEONaF5ocJbO4mt1iLVj8KyQ0mDBorMNCnlKi95kHWKuyfQE) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ 6 bytes ``` 'sĠ'ḢḢ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInc8SgJ+G4ouG4oiIsIiIsIlsncmVmZXJlbmNlJywgJ3RvbW9ycm93JywgJ3RvZGF5J10iXQ==) ## Explained ``` 'sĠ'ḢḢ ' # Filter input where: sĠ # sorted and grouped by consecutive 'ḢḢ # has items where length >= 3 ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-En`, 14 bytes ``` /(.).*\1.*\1/p ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlebSSrmueUuyCpaUlaboW6_Q19DT1tGIMQVi_ACIIlVuwLTUnNTc1r4SrICO_JL84I7-AKz0_PwUiCwA) [Answer] # x86 .COM, 48 bytes ``` 0100 BA 2F 01 B8 03 0A 89 C7-89 C1 F3 AA CD 21 BE 31 0110 01 8A 4C FF 0F B6 D9 C7-40 01 0A 24 AC 89 C3 FE 0120 0F 74 04 E2 F7 EB D9 B2-31 B4 09 CD 21 EB D1 FF org 100h sta: mov dx, bu mov ax, 0x0A03 mov di, ax mov cx, ax la: rep stosb int 21h mov si, bu+2 mov cl, [si-1] movzx bx, cl mov [bx+si+1], word '$'*256+10 lb: lodsb mov bx,ax dec byte [bx] jz ok loop lb jmp sta ok: mov dl, bu+2-$100 mov ah, 9 int 21h jmp sta bu: db -1 ``` Unluckily it behaves bad, input is also displayed [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ĠZṫɗƇ3 ``` A monadic Link that accepts a list of lists of characters and yields the filtered list. **[Try it online!](https://tio.run/##y0rNyan8///IgqiHO1efnH6s3fj/4Xbv//@j1VNzUnNT80rUdRTUCzLyS/KLM/ILQJz0/PwUEJ2RWFBQCWIk5@fkF6WV5oDYOaXp6YnpqSBmUWpaalFqXjKYU5Kfm19UlF8OYackVqrHAgA "Jelly – Try It Online")** ### How? ``` ĠZṫɗƇ3 - Link: words 3 - set the right argument to three Ƈ - filter (words) keeping those for which: ɗ - last three links as a dyad - f(word, 3): Ġ - group indices by value - e.g. "aardvark" -> [[1,2,6],[4],[8],[3,7],[5]] Z - transpose [[1,4,8,3,5],[2,7],[6]] ṫ - tail from index (3) [[6]] - (an empty list is falsey) true (the third "a" gives the 6) ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-p`, 14 bytes ``` {FIaM_Na>2}FIg ``` [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJ7RklhTV9OYT4yfUZJZyIsIiIsImVsZW1lbnQgcGhvdG9zaG9wIGdvb2QiLCItcCJd) ``` {FIaM_Na>2}FIg { }FIg Keep words that return truthy resuts for ... aM_Na>2 Does the letter appear more than two times? FI Filter out falsy results (return either "1" or "") ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 13 bytes ``` G`(.).*\1.*\1 ``` [Try it online!](https://tio.run/##FcZBCoAgEAXQ/ZykWgSdoku0SPKngfplUsLTWy0ePEW5kul93Yd5nKdt@fWOgIhUJHsW3p5ZHGnFm5ybHAysetYgoTpnHERxQpEOSGGkKp8v1rQX "Retina 0.8.2 – Try It Online") Takes newline-separated words. Explanation: `G` is Retina's "grep" operation, which just keeps matching lines, according to the obvious regular expression. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` WS¿⊙ι›№ικ²⟦ι ``` [Try it online!](https://tio.run/##FcqxDgIhDIDhvU/BCMm5uDoZB@Nm4mgcCNcDYo@SWrzw9Hhuf/58IXkJ7GmMLWVCY2@lNn2o5BKtcyYvxp5Lt3kyV0GvKPbCreh/vN1kjm5H912rfeaXO42BhCsWhZpY@ZO4QmSeIflaOwQmbrI0Amox@ogguKBgCQjKK4vwtsfsO4zDl34 "Charcoal – Try It Online") Link is to verbose version of code. Takes newline-terminated words. Explanation: ``` WS ``` Loop through the words. ``` ¿⊙ι›№ικ² ``` If any character appears more than twice, then... ``` ⟦ι ``` ... output the word on its own line. 9 bytes by taking the input in JSON format: ``` Φθ⊙ι›№ιλ² ``` [Try it online!](https://tio.run/##JYmxDgIhEER/hVBxCTa2VsZEW/vLFYTbA5I9Flc4w9cj6DTz3oz1hi0ZbO3JIWZ1D5iB1UuLa6wqaPFgMGO5Uel3H3DS4jz1XFqbZwkIO8QstZDJU6a3pzTEEa2jvUmpDrCEVHgrOASLc8bBQIYNGKL9SaadmOnz59VUuSztdOAX "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array Φ Filtered where ι Current word ⊙ Any character satisfies № Count of λ Current character ι In current word › Is greater than ² Literal integer `2` Implicitly output each match on its own line ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` ĠẈ>2ẸµƇ ``` [Try it online!](https://tio.run/##y0rNyan8///Igoe7OuyMHu7acWjrsfb/h9u9NSP//49WT81JzU3NK1HXUVAvyMgvyS/OyC8AcdLz81PUY3UUotUzEgsKKkFCyfk5@UVppTkgdk5penpieipERVFqWmpRal5yKkimJD83v6govxzCTkmsVI8FAA "Jelly – Try It Online") ## How it works ``` ĠẈ>2ẸµƇ - Main link. Takes a list of words L on the left µƇ - Filter L by the following: Ġ - Group the indices of identical letters Ẉ - Length of each group >2 - Greater than 2? Ẹ - Any true? ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~95~~ ~~90~~ 85 bytes * -5 thanks to l4m2 * -5 thanks to ceilingcat and c-- Lowercase strings only. Iterates through each string and prints it as soon as it encounters 3 of a letter, skipping the string otherwise. Rather than clear the counters each time, I simply create brand new counters. ``` f(int**s){for(char*t,*i;t=*s;*t&&puts(*s),s++)for(i=calloc(99,9);*t&&++i[*t]<3;t++);} ``` [Try it online!](https://tio.run/##fVAxboQwEOz9ihWRTtj40qRCPu4Fp3SpEAUxBiwZFtlLohPi7cS@6xIp23jGO6NZjT4PWh9Hn9uZhAh869Hnemy9ICmsokoEJeh0WlYKedzLUBQ8aWylW@dQ52UpS/7QFIWtBTWXN0VRpPbjxc7arZ2BS6DO2c/X8cpYDGJTa@f8C23H2cYAUh7E9LqpEgV4XlA3HDbIjDOTmSmTkC0jEoYRl0QGxC6@7x@3G@zyr29sl@WehBod@n51Cbt1GNrB/OfzpjfezDqJMsIJvcfvJ@7a@y9nwhHsMt4vSDEWSaqHqqAgfsCjuOycJuMSUjPQ54K4YvvxAw "C (gcc) – Try It Online") [Answer] # Python 3, ~~541 53~~ 50 bytes To get the ball rollin'... *-1 thanks to a fix pointed out by xnor -3 bytes because sets are also fine* ``` lambda n:{i for i in n for y in i if i.count(y)>2} ``` 1: crossed out 54 still looks like 54 :( [Answer] # Java 8, 100 bytes ``` l->{l.removeIf(s->s.chars().noneMatch(c->s.length()-s.replace(""+(char)c,"").length()>2));return l;} ``` [Try it online!](https://tio.run/##dVAxbsMwDJybVxCaJDTW0DWtgY4Fkilj0UGVZVsuLRkinSII8nZXro0gKNDbyDvyeOzMyRRd9TUN4yd6CxYNERyMD3DZbCDDB3apNtbBPrdgRZfn9Mge9d4TPx85@dCUUMt/CFS739nrspTYcHbbA8LLhEV5QZ1cH0/urZZUlKRtaxJJpUMM7mDYttLObXSh4VaqgrJ@wHyVFOJRzmplt0Kom6J8UmqXHI8pAO6u02K/plztT9FX0Oescjnz/QNMakjlnA/HM7HrdRxZD5ljDBJ1LYP7vsv@mpI53@eUfzjShmZeCoeud4HFFsTQRo7UxmEumhgroTJu/7lOPw "Java (JDK) – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 11 bytes Anonymous tacit prefix function taking a list of strings ``` ⊢/⍨3∊¨3⌊⍧⍨¨ ``` [Try it online!](https://tio.run/##HYmxDcIwEEV7pkjnKqLICDTQEhaw4rNTODnLOILUSBGycAQFC9CQAomGCTLKLWKsNF/vv8eNzkXPNaoczg5aASJG8q81hamgq5/T3jyFd/rzFCUNdwoj@QuFD4Xf/C1oeND4LPebtIftrowyY6ChgdaxjJkaHR5rNIkVomCrlGtuTJ9EhRqt7HRC3SnFFSzZggQLbQXJO2zQWjwtKHjP/g "APL (Dyalog Extended) – Try It Online") `⊢` the argument… `/⍨` filtered by… `3∊¨` whether 3 is a member of each,… `3⌊` where 3 caps the values of… `⍧⍨¨` the self-counts for each [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` .-#+GGQ ``` [Try it online!](https://tio.run/##K6gsyfj/X09XWdvdPfD//2j11JzU3NS8EnUdBfWCjPyS/OKM/AIQJz0/P0U9FgA "Pyth – Try It Online") ### Explanation ``` # # filter each element of Q # eval(input()) .- # on the bag-wise subtraction of +GG # two alphabets concatenated ``` [Answer] # [Factor](https://factorcode.org) + `math.unicode`, 43 bytes ``` [ [ histogram values [ 2 > ] ∃ ] filter ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY4xTsQwEEX7PcXv0aagQotEi2hoEFW0heWMHUt2xrHHRNFqq224A02a5QKcZltOgiEIMcWfr9Gbr__2bpQWTsvl4_np4fF-B5Uz64ygpP-RJosSl8X9HpsyOM0dISYSmWNyg2CckGksNGjKuN0cNqgzTgeQp0AViD0L554jLHOH4x_QqxhnaPacTPHwxVpl6R-QyFD6DoZw4JR4qqZTc0WO5yJme3O5atGirx3ZJhXwonypNVpc4w57fL6eqhrnhRL268s5qIhm9cuy7i8) * `[ ... ] filter` Select sequences whose * `histogram` histograms * `values [ ... ] ∃` contain any values * `2 >` greater than two [Answer] # [Haskell](https://www.haskell.org/), 54 bytes ``` import Data.List r=filter(any((>2).length).group.sort) ``` [Try it online!](https://tio.run/##NcoxDoMwDADAva@wIoZEQhnYYerYH1QMHlKwME5kuwOvD1263XA72lGYe6ezVXV4omN@kflD5w@xF40oV4zLlDIX2XxPedP6bdl@PfUTSWCGpiQOAyi8IXAxq2Jh/DPA2m8 "Haskell – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ʒD¢à3@ ``` I/O as a list of lists of characters. [Try it online.](https://tio.run/##yy9OTMpM/f//1CSXQ4sOLzB2@P8/OlopR0lHKRWIi6E4H4jzwOxYHVyyIBmQKEw2F0qD9JWAZQuArAyo@hIoXYwkVgBWlQ7lgXAKWAQknwiWh@BKsGgyVE0OlC4C4jQgLgWLwdwJ4qVDcSKUTgXLFkHdlwali5DcmwxXBXNnLpItRVB2OYqKFKgNQNfFAgA) **Old 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answers with I/O as a list of strings:** ``` ʒ{Åγà3@ ``` [Try it online.](https://tio.run/##LcuxDcIwFEXRXVzTsQB7RBQmebGRHD/rf0coomYBJmAHRkhHwUrmB6W6p7lUf7mitc/zvj6@7/V1PLXWuQRVZnWHXQYkTMjVVCIrNbKYAzlYoi9lsfZMlHFO2ziH4ANMghGC3G@unCjC25@DX9z5Bw) `{Åγà` could alternatively be `D.M¢` for the same byte-count: [Try it online.](https://tio.run/##LcuxDcIwFEXRXVxHaViAIm0mQBQmebGRHD/rf0coazACo1CylPlBVPc0l@pvd7T2eQ79@H6dzq1dXIIqs7ruLwMSVuRqKpGVGlnMgZwt0ZeyWycmyrKlY9xC8AEmwQJBng5XrhTh48fZ7@76BQ) **Explanation:** ``` ʒ # Filter the (implicit) input-list of lists of characters: D # Duplicate the current list of characters ¢ # Pop both, and count how many times each character occurs in the list à # Pop and leave the maximum 3@ # Check whether this maximum is >= 3 # (after which the filtered list of lists of characters is output implicitly) ʒ # Filter the (implicit) input-list of strings: { # Sort the characters in the string Åγ # Run-length encode it; pushing a list of characters and lengths separated to # the stack à # Pop the list of lengths and leave its maximum 3@ # Check whether this maximum is >= 3 # (after which the filtered list of strings is output implicitly) D # Duplicate the current string .M # Pop and push its most frequently occurring character ¢ # Pop both, and count how many times this most frequent character occurs in the # string ``` [Answer] # QB45, 122 bytes ``` for t=1to n:redim p(26):for i=1to len(a$(t)):v=asc(mid$(a$(t),i,1))-96:p(v)=p(v)+1:if p(v)>2then ?a$(t):exit for next:next ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 30 bytes ``` $args|?{$_-match'(.).*\1.*\1'} ``` [Try it online!](https://tio.run/##TYpBCsIwEEX3PUUXwVEhBQ8gXkSQkE6SxaQTJimltD17jLpx8eHx30u8oOSARNqyYFXuvlVlxOf9samXjqbYAOfhMlyft8/gqEfXnZTrAQkjTgV6SIEL58CpsWceoQOt4VcFk9LafsvE4mZqSLP3xuN/JehQcLLYdOHIIrx8cTQr1Dc "PowerShell Core – Try It Online") Or 40 bytes without a regex: [`$args|?{($_|% t*y|group|%{$_|% c*})-ge3}`](https://tio.run/##TYpBDoMgEADvvsIDdlsTTj03fUpDcFkO6JIVYwz4dkrspbfJzETeUVaPIWjLglW5V67KCK3lne/qU4Y@jUch4S2WIV/CjudDEz7PenbdTbkeMOCMS4IeoufEq@fYmJgn6EBr@F3exHg0bzmwuC00DBuRIfy/BB0KLhZbTjyzCO8XTuaA@gU "PowerShell Core – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), ~~62~~ 35 bytes ``` $=>[select&=>[tally&|some?=>[&>2]]] ``` [Try it](http://arturo-lang.io/playground?ELRdsF) -27 due to 0.9.82 introducing `tally`. [Answer] # [Julia 1.7](http://julialang.org/), 37 bytes ``` !l=l[l.|>i->any(count.([i...],i).>2)] ``` [Try it online!](https://tio.run/##TY4xb8IwFIR3fsUjDI6lYAmWSpEStWVj7Rh5cI1xXDl@luOIRuK/B1zA6nb33nen@5msEbvfZQPHpGDH3kDi4EVcfYpRMYmTi6Ws60MvQgVjXX98jzEIGb9iME5TaODBNE0p6Z2gy9o2trPs2pptK9xc/v1Z2RnGGK8MZe2e8uV97PEC665QVg3KxaKCwvcY8X73yWjEU8E3sG2hI0@IVEAyRPgql/TC@zmlJFoM58kmbSethVa55On/54I6q6CcVImPOGAIeHnok5hzMmNpwAsjHJYb "Julia 1.0 – Try It Online") ]
[Question] [ This problem is inspired from [shinh's problem](http://golf.shinh.org/p.rb?Smileys+Triangle). Given an input of positive integer \$n\$, output a smiley triangle (see below) with \$n\$ rows. ## Detailed rules * Can be either a function or a full program. * Standard I/O rules applied. + **RULE CLARIFICATION: Output as exactly a string, rather than an array of strings whose item represent a line.** * Standard loopholes are forbitten. * This is code-golf. Shortest code wins. # Valid output syntax Assuming ASCII encoding. A smiley triangle with \$n\$ rows `triangle(n)`, where n>=1, should be output. `<0xXX>` is a character with such codepoint, in hexadecimal. ``` triangle(n) = triangle(n) <0x0a> | triangle_(n) triangle_(1) = <0x3a> spaces triangle_(n) = triangle_(n-1) <0x0a> row(n) spaces row(2) = <0x3a> <0x2d> row(n) = row(n-1) <0x29> spaces = <0x09> spaces | <0x20> spaces | *empty* ``` ## Example outputs If n is 1, then ``` : ``` If n is 2, then ``` : :- ``` If n=5, then ``` : :- :-) :-)) :-))) ``` [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` s=':-' exec"print s[:-1];s+=')';"*input() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hW3UpXnSu1IjVZqaAoM69EoTjaStcw1rpY21ZdU91aSSszr6C0REPz/39DAwA "Python 2 – Try It Online") **42 bytes** ``` s,c=':-' exec"print s;s+=c;c=')';"*input() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v1gn2VbdSledK7UiNVmpoCgzr0Sh2LpY2zbZGiihqW6tpJWZV1BaoqH5/7@hAQA "Python 2 – Try It Online") **43 bytes** ``` s=':' exec"print s;s+='-)'[s>':'];"*input() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hW3UqdK7UiNVmpoCgzr0Sh2LpY21ZdV1M9utgOKBVrraSVmVdQWqKh@f@/oQEA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` “:-)”ṁ«\)Y ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//4oCcOi0p4oCd4bmBwqtcKVn/w4cpauKBvgoK//81 "Jelly – Try It Online") ``` ) Map over (the range from 1 to) the input: “:-)”ṁ Mold ":-)" to the shape of the argument, cycling its contents. «\ Scan by minimum: replace anything to the right of ) with ). Y Join on newlines. ``` Thanks to Jonathan Allan for salvaging my first attempt, [`”)xⱮa⁾:-Y`](https://tio.run/##y0rNyan8//9Rw1zNikcb1yU@atxnpfv/cHukZhaQycX1/78pAA), for another 10-byter: # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ”)xa⁾:-ṁ)Y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw1zNisRHjfusdB/ubNSM/H@4XTMLyOXi@v/fFAA "Jelly – Try It Online") ``` ) Map over (the range from 1 to) the input: ”)x Repeat ")" by the argument. a⁾:- Zipwith-vectorize logical AND with ":-": overwrite the first two characters with ":-". ṁ Mold to the shape of the argument, trimming the extra "-" for 1. Y Join on newlines. ``` [Answer] # Excel, ~~37~~ 49 bytes *+12 bytes to accommodate clarification that the output should be one string* ``` =CONCAT(LEFT(":-"&REPT(")",A1),SEQUENCE(A1))&" ") ``` This returns one string as opposed to the earlier version which returned multiple cells each containing a string. Due to the Excel string limit, this only works for n <= 254. [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnF_QDKPVdX0hy4-6?e=VpuWvQ) ``` =LEFT(":-"&REPT(")",A1),SEQUENCE(A1)) ``` Previous version that works for n <= 32767. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` …:-).ÞI£Jη» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcMyK11NvcPzPA8t9jq3/dDu//8NDQA "05AB1E – Try It Online") Or, for the same length: ``` ')ׄ:-ì¨¨η» ``` [Try it online!](https://tio.run/##AR8A4P9vc2FiaWX//ycpw5figJ46LcOswqjCqM63wrv//zEw "05AB1E – Try It Online") ``` …:-) # string literal ":-)" .Þ # cycle last character to create infinite list I£ # take the first input characters J # join into a string η # take all prefixes » # join by newlines ')× # repeat ")" input times „:-ì # prepend ":-" ¨¨ # remove the last two characters η» # join the prefixes by newlines ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╞■¼╤╝<Ñ┬ ``` [Run and debug it](https://staxlang.xyz/#p=c6feacd1bc3ca5c2&i=5) outputs with newlines. [Answer] # Haskell, 32 bytes ``` (`take`(":":iterate(++")")":-")) ``` [Try it online!](https://tio.run/##DcIxCoAwDADAr4Tg0FIcXQr9gU6uggZptVhL0Ph9o9ztdB@xFE1hUrMIHXEx6NFniRdJNM6h/fkWrdWTcoUAJ/EwAz8yytVXaCBBp@@aCm23tivzBw "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~11~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Outputs an array of lines. ``` õî":-"ú')U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=9e4iOi0i%2bicpVQ&input=NQotUg) ``` õî":-"ú')U :Implicit input of integer U õ :Range [1,U] î :For each slice the following to that length ":-" : Literal string ú')U : Right padded with ")" to length U ``` [Answer] # [J](http://jsoftware.com/), 17 15 bytes *-1 thanks to Jonah!* ``` [:]\$!.'('&':-' ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o61iY1QU9dQ11NXUrXTV/2tycaUmZ@QrpCkYQhjqukCgDhM0xiZoiiz4HwA "J – Try It Online") Reshape `:-` with fill `(` to length `n`. `[:[\` return each prefix. [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 37 bytes ``` {({(":-",(x-2)#")")[!x]}'!x+1)[1+!x]} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWqNaQ8lKV0lHo0LXSFNZSVNJM1qxIrZWXbFC21Az2lAbxPlfXeuQYGCVpmBk8B8A "K (oK) – Try It Online") My first non trivial K answer, a lot of room for inprovement. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 9 bytes ``` ⇩\)*‛:-p¦ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%E2%87%A9%5C%29*%E2%80%9B%3A-p%C2%A6&inputs=10&header=&footer=) Wasif said I should post my 9-byter as my own answer, but I thought it was too similar to his, so I got rid of the map lambda and the slice, just because why not. :P Explanation: ``` ⇩ # x = input - 2 \)* # Push a 'x' long string of ')' ‛:-p # Prepend the string ':-' ¦ # Prefixes # 'j' flag - Join top of stack on newlines and print ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~10~~ ~~9~~ 8 bytes *Edit: -1 byte simultaneously spotted by Razetime* ``` ↑ḣ¡→":-) ``` [Try it online!](https://tio.run/##yygtzv7//1HbxIc7Fh9a@KhtkpKVrub///9NAQ "Husk – Try It Online") ``` ":-) # the string ":-)" ¡ # construct infinite list by repeatedly appending → # last element of list so far; ḣ # now make list of all prefixes, ↑ # and take number of elements equal to input ``` [Answer] # JavaScript, 37 bytes ``` f=n=>--n?f(n)+(s=n>1?s+')':` :-`):':' ``` [Try it online!](https://tio.run/##lYxBCoAgEADvfWR3iZWsm2B@JSmNItbI6PvWMbp1nRlm9ZfP47HsJ0uaQinRiu2ZxUUUqjFb6bXLNRCYoTI8kAEDZUyS0xbUlmaMqImqNwEGdYQ9@BPb5uMitr/q7letn3m5AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `jr`, 10 bytes ``` ƛ?\)*‛:-+Ẏ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=jr&code=%C6%9B%3F%5C%29*%E2%80%9B%3A-%2B%E1%BA%8E&inputs=10&header=&footer=) Thanks to @emanresuA for -2 bytes # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 12 bytes ``` ‛:-?⇩\)*+¦?Ẏ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%E2%80%9B%3A-%3F%E2%87%A9%5C%29*%2B%C2%A6%3F%E1%BA%8E&inputs=10&header=&footer=) [Answer] # [Python 3](https://docs.python.org/3/), 52 bytes ``` lambda n:[print((':-'+')'*i)[:-1])for i in range(n)] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKrqgKDOvREND3UpXXVtdU10rUzPaStcwVjMtv0ghUyEzT6EoMS89VSNPM/Y/mpChjpmmFZeCQppGpiaQghik@R8A "Python 3 – Try It Online") -1 byte thanks to Mohammad [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 20 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {,\⍵⍴':-',')'⍴⍨|⍵-2} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9aJedS79VHvFnUrXXUddU11IPNR74oaoKCuUS0A&f=S1MwBAA&i=AwA&r=tio&l=apl-dyalog&m=dfn&n=f) Monadic function `{`...`}` monadic function, takes n on right `⍵-2` n minus 2 `|` abs (No. of braces, call it x) `⍨` swap x with `')'` brace for `⍴` dyadic reshape to get x braces `,` concat with `':-'` smiley head `⍵⍴` take first n (monadic reshape) `,\` prefixes (ravel scan) [Answer] # TI-Basic, ~~40~~ ~~35~~ 27 bytes ``` Input N Disp ": ":- For(I,2,N Disp Ans Ans+") End ``` -5 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) -8 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush) [Answer] # [PHP](https://php.net/) -F, 59 bytes ``` for(;$i<$argn;)echo$i++?":-".str_repeat(")",$i-2)." ":": "; ``` [Try it online!](https://tio.run/##DcSxCoAgEADQ3c84HBTTIWhRwa3fCAlLF@8wv7@rNzyqxDHR/4VDBdmizOPuQZezomzGJPAW3DPHMQqVPBVoWGSzq3YgwIMXEJi3F2k27A/b/QM "PHP – Try It Online") Straightforward stuff.. Probably golfable a bit more, I'll try other things later [Answer] # [M4](https://www.gnu.org/software/m4/m4.html), 88 bytes Just a port of the syntax in OP. ``` define(g,`ifelse($1,2,,`)g(decr($1))')')define(f,`ifelse($1,1,:,`f(decr($1)) :-g($1)')') ``` [Try it online!](https://tio.run/##yzX5/z8lNS0zL1UjXSchMy01pzhVQ8VQx0hHJ0EzXSMlNbkIyNXUVAdCqLo0ZHWGOlY6CWkIdVxWuukgBkj9/zQNQ00urjQNIzBpqvkfAA "M4 – Try It Online") ## Usage `f(number here)` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` NθG↓→θ⁺:-×)θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05orID@nMj0/T8PKJb88T0fBKigzPaNER6FQRyEgp7RYQ8lKV0lHISQzNxXI1gQyCzU1Na3//zf9r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ ``` Input `n`. ``` G↓→θ ``` Draw a triangle of size `n`. ``` ⁺:-×)θ ``` Paint the triangle using a smiley with `n` chins. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes ``` .+ $*) ^. : :. :- . $`$&¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRUuTK06Py4rLCkjoculxqSSoqB3a9v@/KQA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $*) ``` Start with `n` chins. ``` ^. : ``` Change the first chin into eyes. ``` :. :- ``` Change the second chin, if any, into a nose. ``` . $`$&¶ ``` Output all of the nontrivial prefixes. [Answer] # [C (gcc)](https://gcc.gnu.org/), 63 bytes ``` f(x){x&&f(x-1)+g(x);}g(x){x&&g(x-1);putchar("\n:-)"[x<3?x:3]);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0KzukJNDUjrGmpqpwO51rXpUMF0sKB1QWlJckZikYZSTJ6VrqZSdIWNsX2FlXEsUOX/zLwShdzEzDwFDc1qLoU0DVNNa67a/wA "C (gcc) – Try It Online") * double recursion [Answer] # [Haskell](https://www.haskell.org/), ~~37~~ 35 bytes ``` f x=($":-"++cycle")").take<$>[1..x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwlZDRclKV0lbO7kyOSdVSVNJU68kMTvVRsUu2lBPryL2f25iZp6CrUJuYoFvvEJBaUlwSZFPnoKKQpqC6X8A "Haskell – Try It Online") * Thanks to @Unrelated String for saving 2! [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 57 bytes This assumes the initial memory location contains *n* in binary (0x05 == 5). The TIO link allows a single ASCII character as input and converts it to binary. ``` ->>++++++++[-<+++++++>]<++.<[->-------------.----<[->.<]] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/q9jpw0F0bo2umBgF2vzX9cOWRzKAkpoa@vZROva6SIDPRABEtWziY39/9/0/38A "brainfuck – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~40~~ 38 bytes ``` ->n{n.times{|i|puts":-#{?)*n}"[0..i]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tbi6JrOmoLSkWMlKV7naXlMrr1Yp2kBPLzO2tva/hqGenqmmXm5iAUhVWnRmrDVIae1/AA "Ruby – Try It Online") [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~43~~ ~~33~~ 28 bytes ``` ':-'+')'*"$args"|% *ve @args ``` [Try it online!](https://tio.run/##bY3BCoJAFEXXM18xDGOmNaJbQxCidZHLiEh7WmFpM1qB@u3TCEotert3OffcsniBkGfIc54UAhRLg0aZPjdnpmXalB1FJmlrEPsJJOwf1WHM4F1CUsHJc0lAqM@t4egCe47jua3RYMQEyDqvNDFhKWEHnYw9nf04nKiOZSUu92zqzjVoYbTbRMtaVsVtHV81tQ@1D0V1koCUfXlQc3h8RZrYjosDoKPVn0mMOtypDw "PowerShell Core – Try It Online") Saved 10 bytes thanks to mazzy! Saved 5 bytes by: * removing gratuitous parenthesis * using `Remove` instead of `Substring` * using splatting [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` i=input() o=':-'+')'*i for x in range(1,i+1):print o[:x] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERDkyvfVt1KV11bXVNdK5MrLb9IoUIhM0@hKDEvPVXDUCdT21DTqqAoM69EIT/aqiL2/38zAA "Python 2 – Try It Online") Without the leading newline # [Python 2](https://docs.python.org/2/), 54 bytes ``` i=input() o=':-'+')'*i for x in range(i+1):print o[:x] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERDkyvfVt1KV11bXVNdK5MrLb9IoUIhM0@hKDEvPVUjU9tQ06qgKDOvRCE/2qoi9v9/MwA "Python 2 – Try It Online") Never going to be a winner. Just an alternative approach. **55 bytes** ``` lambda x:'\n'.join((':-'+')'*x)[:x]for x in range(x+1)) ``` [Try it online!](https://tio.run/##BcExDoAgDADAr3RrK9FEBwcSX6IOGEUxWghhqK/Hu/SVK8pQ/bTUx73b7kAtLoLdHYMQoW3RIGOjPFtdfcygEASyk/MgNT1zTTlIAU8j1x8 "Python 2 – Try It Online") Another alternative using a lambda, surprisingly longer than using `input()`. It's that `join()` that's expensive. [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~109~~ 95 bytes ``` n =input b s =gt(n,1) char(10) ':-' dupl(')',n - 2) s :f(c) n =n - 1 :(b) c output =':' s end ``` [Try it online!](https://tio.run/##FYxLCoQwEAX3OcXbdTcoGNFNIIeZxC9IRybJ@aNui6rKmkK6ptag8KfetZiADL8X1s4K4vH7sx0E5HrCUu@LSahT9BjlFd3GUcwXf8jCcRATkWp5V/DkCNmsurQ2Pw "SNOBOL4 (CSNOBOL4) – Try It Online") [Answer] # [Java (JDK)](http://jdk.java.net/), 82 80 bytes ``` String a(int n){return(n>1?a(n-1):"")+(":-"+")".repeat(n)).substring(0,n)+"\n";} ``` [Try it online!](https://tio.run/##RU/NbsIwDL7zFFZOsbJW9Eo3eILtsuPGwYQwBYpbJS7ShPrsJSSV8MGW7M/fz5luVJ2Pl9l2FCN8kuf7ClJ5FhdOZB18lcWzviV4/gOr0xUY23yYVnlEIfF2XiC0QO7ByRhY87bZkeaqwY1SaLTaVMooVHVwgyPRjFjH8RDzt16/MRr1y6qd5id3WySG8dB5uyjBrfdHuCbDumj@7AlfVk99gOzBwwc0Lfj3Zp26MQgvUM70H8Vd636Uekg00rFO5nEJVwKWPs0P "Java (JDK) – Try It Online") Recursively append longer smileys. A different approach might be shorter... -2 thanks to ceilingcat! [Answer] # Zsh, ~~53~~ ~~39~~ 37 bytes ``` a=:-;for n ({1..$1})a+=\)&&<<<$a[1,n] ``` [Try it online!](https://tio.run/##qyrO@J@moVn9P9HWStc6Lb9IIU9Bo9pQT0/FsFYzUds2RlNNzcbGRiUx2lAnL/Z/anJGfi1XmoIxEBsBsSEQm4BoEMPQ/D8A)  ~~[39 bytes](https://tio.run/##qyrO@J@moVn9P9HWSpcrLb9IIU9Bo9pQT0/FsFYzUds2RlNNzcbGRqU60crASiWv9n9qckZ@LVeagjEQGwGxIRCbgGgQw9D8PwA)~~  ~~[53 bytes](https://tio.run/##qyrO@J@moVn9P9HWSpcrLb9IIU9Bo9pIT0/FsFYzUds2RhMuaAgRtLGxUalOtDKwUsmr/Z@anJFfy5WmYAzERkBsCMQmIBrEMDT/DwA)~~ Realised I was wasting bytes by doing 2 loops when one would suffice. [Answer] # [C (gcc)](https://gcc.gnu.org/), 68 bytes ``` i;f(n){char*s=calloc(n,4);for(s[i=0]=58;n--;s[i]=i++?41:45)puts(s);} ``` [Try it online!](https://tio.run/##ZY5BCsIwEEX3PcVQEBLTgIVWxDF4EO0iRFIDcVqaiovSqxtTUBf6NsP8eR/GyNaYGB1aRnwyVz2sgzLa@84wKiqOthtYODm1aVS9Q5IS09YoJ8SxKvdVzfv7GFjgOEdHI9y0I8ZhyiCRusCWlEBBiWkcYIsgBH2MhX5IimU5qdXlTHlBHL@35Sv8M@UvqfbW5myOT2O9bkOUjxc "C (gcc) – Try It Online") ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/10532/edit). Closed 3 years ago. [Improve this question](/posts/10532/edit) The challenge is to write the most elaborate code, embedded in ASCII art that reads and prints "DFTBA". For example, the following reads DFTBA: ``` oooooooooo. oooooooooooo ooooooooooooo oooooooooo. .o. `888' `Y8b `888' `8 8' 888 `8 `888' `Y8b .888. 888 888 888 888 888 888 .8"888. 888 888 888oooo8 888 888oooo888' .8' `888. 888 888 888 " 888 888 `88b .88ooo8888. 888 d88' 888 888 888 .88P .8' `888. o888bood8P' o888o o888o o888bood8P' o88o o8888o ``` And the following, in bash prints DFTBA ``` echo "DFTBA" ``` The challenge is to write one that does both. ## Winning conditions Valid answers, (all conditions at my discretion) * Can be clearly read as DFTBA * Print DFTBA when executed * Must be functional with no Internet connection * have letters of equal height * must not have more than 80 columns * must not have more than 10 rows Points (highest sum wins) * Rows \* Columns / 32 * Readability: 25 for legible, 50 for very clear * 1 point for each different non-whitespace character used ## Restrictions These may be used for something, so all responses are **assumed** to be released into the public domain. If you can't, or choose not to release your answer into the public domain: post a comment/response to the original question saying "The answer authored and/or shared by me, may not be considered to be in the public domain". Non-public domain answers are welcome too! Just make sure to specify :-) ## What is DFTBA? It sometimes stands for "Don't Forget To Be Awesome", but not always... Long story... This [related song](https://www.youtube.com/watch?v=y0VnI1dI7zw) might help explain (or confuse). [Answer] ## Piet, Score Uncertain (153ish) ![Piet Program](https://i.stack.imgur.com/ShVGT.png) I understand that this doesn't strictly fit within the specifications (requiring ASCII art), however the source code does provide a very readable DFTBA. The trace is below. Piet ignores every colour that doesn't mean anything. As a result, I used gray as the generic "comment colour" to outline and the like. The gray doesn't get interpreted (as you'll see in the trace). I wanted to make it clear which pixels were in the program and which were not. I've used 15 colours, which is 13 without whitespce. It is 89x32 pixels, though could be compressed more. I used 4 op-codes (subtract, divide, push and outputc). Maybe if using scoring how I would think, 153? Probably doesn't warrant a score, but was an interesting exercise. Having never used Piet before, I've never done so much trial-and-error programming! I needed npiet extensively, and its trace. I still can't figure out how the movement of the cursor works with any stability! How it works: * D, F, T are constants for their respective ASCII letters that are then pushed to the stack, and the OUTC command called * B is the ASCII for B x 2 (needed to be to look good), which is pushed to the stack, then divided by two, then duplicated on the stack and the OUTC command called * Note the earlier duplication. That was because I couldn't make A look good in so few characters. I push 1 to the stack, subtract (making the ASCII code for A) and then the whole A character is the opcode for OUTC - doesn't matter the size, because it's an operation not a constant ![Trace](https://i.stack.imgur.com/e28yt.png) [Answer] ## Malbolge (~~71~~ 80 x 10) / 32 + 25 + 94 = ~~141.1875~~ 144 Update: added more spacing between the letters to raise the score. Tested with the official Malbolge interpreter. Of course, it's really not hard to print static text using Malbolge. The encoding used by Malbolge almost guarantees you'll have the whole set of printable ASCII characters in there. ``` bCBA@?>=<; :9876543210 /.-,+*)('&%$# "!~}|{zyxwv uts rqp onm lkjihgfedcb a`_^]\[ZYXWVU TSR QPO NML KJI HGF EDC BA@ ?>= <;: 987 654 321 0/. -,+ *)( '&% $#" !~} |{z yxw vuW srq ponmlkjihg` &^] #a`_A]\[TxX WVU TSR QPO N0L KJIHGFEDCBA @?> =<;:3W16543 ,P0/.-,+*)('& %$# "!~ }|{ zyx wvu tsr qpo nml kji hgf edc ba` _^] \[Z YXW VUT SRQ PO1 lYK JIH GFE DCB A@? >=< ;:98765432 10/ .-, +*)('&%$#"! ~}| {zy ``` Explanation of the code (people said they didn't understand it): (For more information about Malbolge see <http://esolangs.org/wiki/Malbolge>). First, let's normalize the code to the operations given at the above page: ``` iooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *ooooooooooooop<pp<ooo*ooop<ooooooooooo*ooooooooooooooooooop<poooop<oo oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo*<vooooo oooooooooooooooooooooooooooooooooooooooooooo ``` Also note that after each instruction cycle, the executed instruction is re-encoded and the code pointer and the data pointer are increased by 1. * At the beginning, `C` (code ptr) `= D` (data ptr) `= 0`. This means `[D] = 'b' (98)` and the `i` instruction is selected. So we jump to address 99. (`C` is first set to 98 and then increased), the data pointer is now 1. * At 98 there's a string of NOPs (`o`). These do have the effect that they are all re-encoded and that `C` and `D` are incremented. The next real instruction (`*`) is found at address 140, so now `C=140` and `D=42`. * `*` does a right rotate (or division by three) on what the data pointer's pointing at, and stores back into the memory and in the accumulator `A`. `[42] = 'x' (120), so A <- [42] <- '(' (40)`. * Another row of NOPs causes `C=154 (p)` and `D=62 ( [D]='j' (106) )`. * `p` is the *crazy operator*. I'm not going to reproduce its table here, but what happens is `A = [D] = crazy(A, [D])`. `A` is still 42, `[D]` is 106, which means `crazy(A, [D]) = 29504`. * Next up is `<`, which is output. It outputs the accumulator, which is 29504, as an ASCII character. `29504 % 256 = 68`, which is `D`, so now we have the D. * The rest of the letters are output in a similar manner. [Answer] ## Javascript (80 x 10) / 32 + 25? + 94 = 144 Code: ``` eval('for(i =10;i<0x24;42, Number["prot"+ "otype"][(i++ ).toString(36\ )]=Number["p" +"rototype"]/* */["toString"] );alert(((+((- ~{}).a()+(!!{\ }+!!{}+!!{}).b ())).c(+((+!!{ }).d()+(5).e() ))+( +((+!! {}).f()+(2+!!\ {}+! !{}+! !{}). g())). h(+( (+!! {}). i()\ +(7) .j() ))+(+((2) .k()+( /*TVEXFGHZKJP Q*/( 0x1\ +0x1 +0x1 )*0x3).l( ))).m( +((8/4+1).n()+ (+[]).o\()))+\ (+(( +!!{} ).p()+(-~ {}).q( ))). r(+(( +!!{}).s()+(!\ !{}+2/*WARP*/) .t() ))+(+( (+!! {}).u( )+(+ [])\ .v())).w(+((+ !!{} ).y()+ (2/*Y*/).z())) )/** **/\ .toUpperCase ()); "#$%\' /,:>?@^_`9|&M ODLB I"') ``` Demo: <http://jsfiddle.net/4hyyS/3/> To add some explanation: First I map `Number.prototype.toString` to each lower-case letter: ``` for(i=10;i<36;Number.prototype[(i++).toString(36)] = Number.prototype.toString); ``` This allows me to use the lowercase letters efficiently. Next I construct the string 'DFTBA' by converting numbers to characters, eg: ``` (13).a(15) // 'd' ``` (I could have used `fromCharCode` or `toString(36)` for all of the characters, but that would have been too easy) To fill out extra characters, and further obfuscate the code, I use a few tricks to create the numbers: ``` +[] // 0 +!!{} // 1 !!{}+!!{} // 2 ``` Etc. For characters that aren't used in the actual code, I dropped them in either comment blocks `/* ... */` or strings `" ... "`. I started off with an 80x10 grid, then whittled that down to my letters, then adjusted my code to fit that (also, looks better in this font, the last `|` is just the cursor): ![Looks better in a different font](https://i.stack.imgur.com/QtSFf.jpg) [Answer] (I have made a full write up [here](http://null.53bits.co.uk/index.php?page=dftba) as it is quite extensive how I got to these two results) **Brainfuck, Full ASCII range 0 to 255: 80x10=800/32=25+25+219=269** ``` +l+A+O#@e@ /+@+|+2+@@X @*3+}+@+@YZ q4[@>@+@@ @:+@ @+B+"+~@@N @p+K+%>@@v@ dJ+w+@+@+@@ I@+@+@+@@ (@+ @<@ @<@ @-@ @@] U>@ @-@ -@@f @.r +@E +@@ .@@0 @>@+@+@+@@@ @+@ @.@ <@@@ @-' -@@ -€R -9‚ ƒ.„-….†$c‡ˆ ‰Š‹ Œg&Ž6H ‘h’“7”i•–— ˜u™ Qš1› MœL )nG ?žŸ x¡¢£ `¤¥¦j@§{D¨ !©ª «P¬­ ®bm ¬¯° ±²³ ´µ\¶ ·¸F ¹8º »S¼ ½¾¿ ÀVÁ ÂTà ÄÅk _ÆÇÈ ÉÊË ÌÍÎ ÏaÐ;ÑCÒÓsÔ ÕÖ× ØoÙ ÚÛ=Ü5ÝÞßà áâã äåæ çtèéê^ëìíî Wïð ñòó ôõö÷yøùúû üýz þÿ, ``` There is a line through the middle of this top one which is not quite strait, but that is just the display here on CodeGolf. If you download the original file from the above link and view it in the Brainfuck Developer or Notepad instead of Wordpad for example, it will look correct [like this](http://null.53bits.co.uk/uploads/programming/bf/dftba/DFTBA_Golf_Test5_Alignment.PNG). **Brainfuck, Part ASCII range 0 to 127: 80x10=800/32=25+25+95=145** ``` +l+A+O#@e@ /+@+|+2+@@X @*3+}+@+@YZ q4[@>@+@@ @:+@ @+B+"+~@@N @p+K+%>@@v@ dJ+w+@+@+@@ I@+@+@+@@ (@+ @<@ @<@ @-@ @@] U>@ @-@ -@@f @.r +@E +@@ .@@0 @>@+@+@+@@@ @+@ @.@ <@@@ @-' -@@ -@R -9@@ @.@-@.@$c@@ @@@ @@g&@@6@H @h@@7@i@@@ @u@ Q@1@ M@L )nG @?@@@x@@@ `@@@j@@{D@ !@@ @P@@ @bm ¬@@ @@@ @@\@ @@F @8@ @S@ @@@ @V@ @T@ @@k _@@@ @@@ @@@ @a@;@C@@s@ @@@ @o@ @@=@5@@@@ @@@ @@@ @t@@@^@@@@ W@@ @@@ @@@@y@@@@ @@z @@, ``` [Answer] ## Perl (75 x 7) / 32 + 25 + 59 ≈ 107.4 ``` @D=('-4*x^2 8*x^5-72*x^3 56*x^4-260*x^1 +272*x^6', ' 4*x^2 -4*x' );$b++ ,s/ (-) ?(\w +)( .x)? (\^ \d+ )?/ "\$$b \[0$4 ||$2 $3<1 ]$1= $2^I" .!" $$O" /exgemfor +@D; $P=pop@2;$K =( pop @1) /+$P and $_.= chr( --$j ?"$K*x^$j" :"+" .$K), s/^ \+|\ +\B| \b1\ *|\ ^1$/ /gx,map$1[$ j++]-= $_*$K, @2while$j= @1-@2 ;print ``` I'd tell you what it does, but that'd ruin the obfu, wouldn't it ;) [Answer] ## C#, (71\*7)/32+25+45 = 85.53 My first *Programming Puzzles* answer! C# is really not very good for these games... ``` /**/using/* */System;/* */namespace F{class//oo. .o. //8' `Y8b `888' 8888 `888' `Y8b .888. //8 888 888 8888 888 888 .8"888. /*8 8*/ I{static void Main(string [] args ) { /*8 888 " 8888 888 `88*/ {Console. //8 d88' 888 8888 888 .88P .8' `888. WriteLine( /*88 8888 */"DFTBA"); /**/ }}}} ``` [Answer] # Python, (69\*7)/32 + 25 + 49 = 89 ``` oo=getattr; o=__import__ ('sys');O='s' 'tdout';#o. .o. class Y8b :#88' `8 8' 888 `8 `888' `Y8b .888. #88 888 888 888 888 888 .8"888. def a88 (Oo,oO): oo( oo(o,O),'w' 'r' 'it' "e" )(( (oO ) )); 11/ 0b10 ;return[88, 88] #d8` 888 888 888 .88P .8' `888. d=Y8b().a88; d("D" "FT") +[1]+d("BA" '\n' )#1880 ``` It's not easy to do it in Python because of indentation and whitespace. So I did one of many things to make the indentation legit: * defined a class * used concatenation of strings * list with a trailing comma * line continuation character (which I ended up not using) Readability can still be improved a bit... [Answer] ## C, (55\*8)/32+25+55 = 93.35 It's quite easy to make the letters larger, and use a few more characters. ``` main() {p(O(O(O( O(O(O(O(O( O(O(O(O(O (O (p(O(O( p())))))) )))))))))) ));puts("" ,p(o (p (o (o (o (o (o (o (o (o (o (o (o (o (o (o (o (o (o (o()))))) )) )))))))) ))))));}x= 59 ;O () {x ++ ;} o( ){ +x -- ;} p( ){ ;; ;; ;; putchar (x +9 );x;-x;} q( ); ``` [Answer] # Java ``` class Ypnypn {public static void main( String []array ){{}{} {{{{}{ { } { { } } { } { ( System . out). print( ( " " + " " + " " + " DFTBA" ) . trim( ) ) ;}}}}} } } ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/9309/edit). Closed 7 years ago. [Improve this question](/posts/9309/edit) can we print **1 to 100** without using any if conditions and loops in c&c++? Conditon: main point is you must not use recursion...and doesnt hardcode code in it for e.g `print(1 2 3..etc);` [Answer] ## C (90) (79) (59) (47) (42) (40) static int ``` x=1;a(){char b[8];printf("%d\n",x++);b[24]-=5*(1-x/101);}main(){a();return 0;} ``` The function `a` which prints the numbers does not call itself! I exploited a buffer overflow and changed the return address to make the program counter go over function `a` again as long as I need. I don't know if this is considered to be a recursion, but I thought it would worth trying. This code works on my 64-bit machines with gcc 4.6, for other platforms the last statement of function `a`, could be a little different. **Exp1:** I allocated a dummy buffer on stack `b`, and then addressed a passed-by-end location, which is the location of return address. I anticipated the distance between start of buffer and return address location from disassembly of function `a`. **Exp2:** Expression `5*(1-x/101)`, is `5` for all `x<=100` and `0` for `x=101`. By looking at disassembly of `main` (in my case), if you decrease the return address by 5, you will set the PC to calling point of `a` again. In the updated codes, the return value of `printf` is used for checking loop condition. **Update:** After applying [ugoren](https://codegolf.stackexchange.com/users/3544/ugoren)'s suggestions and some other changes: ``` x;a(){int b[2];b[3*(printf("%d\n",++x)&2)]-=5;}main(){a();} ``` **Update2:** After Removing function `a`: ``` x;main(){int b[2];b[6^printf("%d ",++x)&4]-=7;} ``` **Update3:** ``` x;main(b){(&b)[1|printf("%d ",++x)&2]-=7;} ``` **Update4:** Thanks to [mbz](https://stackoverflow.com/users/395573/mbz) :) ``` x;main(b){(&b)[3|printf("%d ",++x)]-=7;} ``` [Answer] # 85 C (gcc) ``` #define c printf("%d ",i++); #define b c c c c c #define a b b b b b main(i){a a a a} ``` Assuming no command line arguments were passed. [Answer] ## C++ (~~159~~ 136) With templates. ``` #include<cstdio> #define Z(A,B,C,D)template<A>struct P B{P(){C;printf("%d ",D);}}; Z(int N,,P<N-1>(),N)Z(,<1>,0,1)int main(){P<100>();} ``` [Answer] ## C 71 70 Assuming the `?` operator is allowed. ``` #define f(a)a a a a a int main(i){f(f(f(printf(i<102?"%d ":0,i++);)))} ``` Edit: `""`->`0` If `?` is too similar to an if statement, then use this instead (78) ``` #define f(a)a a a a #define g(a)f(a)a int main(i){f(g(g(printf("%d ",i++);)))} ``` [Answer] # 267 this is the best I can think of, assuming using the preprocessor is fine. ``` #include <stdio.h> #define a(i)i,i+1,i+2,i+3 #define b(i)a(i),a(i+4),a(i+8),a(i+12) #define c(i)b(i),b(i+16) #define e c(1),c(33) #define f %d %d %d %d #define g f f f f f f f f #define r(m) #m #define s(m) r(m) int main(){printf(s(g g g f),e,c(65),a(97));return 0;} ``` [Answer] # C++ (115) ``` #include <cstdio> template<int i>void p(){printf("%d ",i);p<i+1>();} template<>void p<101>(){} int main(){p<1>();} ``` [Answer] # MATLAB/Octave, (5 chars) ``` 1:100 ``` [Answer] ## PowerShell (6 characters) 1..100 [Answer] # Python 3 (25) ``` print(list(range(1,101))) ``` [Answer] # Python 2 (12) ``` >>> range(1,101) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] ``` [Answer] # Ruby (11) [non-competitive] ``` p *(1..100) ``` (Thanks to histocrat) Previous 14-character solution: ``` p *1.upto(100) ``` This is a non-competitive answer (not C/C++ as requested) [Answer] **Scala (22)** ``` 1 to 100 foreach print ``` [Answer] # Perl 6 (10) ``` print ^101 ``` If one wants to be able to read the numbers and therefore spaces between the numbers would be nice, the following will do the trick. ``` say ~ ^101 ``` [Answer] ## Perl (65) Here's a non-trivial Perl approach (not like `say for 1 .. 100`). The program uses perl's regular expression engine to count its own characters (two times), and that's the reason why I couldn't golfify the content of `$k`. It tries to find a (minimal, non-greedy) group of arbitrary single characters until `(*FAIL)`. ``` $k='$k =~ /^(.+?)(?{print length($1) . "\n"})(*FAIL)/#'x2;eval$k; ``` The output is a list of all integers from 0 to 100 with newlines. [Answer] # Pygmy, (18 characters) ``` alert|[1 100].fill ``` [Answer] # Python 2 (39 chars) ``` p=lambda d:print d+1,;map(p,range(100)) ``` # Python 3 (53 chars) ``` p=lambda d:print(d+1,end=' ');set(map(p,range(100))) ``` or print numbers on separate lines (28 char) ``` set(map(print,range(1,101))) ``` or (tested in Python 3.3.2, set items printing in ascending order - 24 chars) ``` print(set(range(1,101))) ``` [Answer] ## Bash 13 ``` echo {1..100} ``` Some more text so it posts. [Answer] # JavaScript (ES6), 38 bytes ``` alert([...Array(101).keys()].slice(1)) ``` Creates an array of length 101, uses the spread operator to put the array keys (`0` to `100`) into an array, removes the first element (`0`) then `alert`s the numbers within the array. [Answer] # Python - 61 Looping? No this is *list comprehension*. ``` d=[0,1,2,3,4,5,6,7,8,9];print[x*10+y+1 for x in d for y in d] ``` [Answer] # [Hassium](http://HassiumLang.com), 31 Bytes ``` func main()print(range(1, 100)) ``` Run online and see expanded [here](http://HassiumLang.com/Hassium/index.php?code=3823e60014d9eddd70cc53277cd2a6d8) [Answer] # JAVA, 52 chars ``` IntStream.range(1,101).forEach(System.out::println); ``` ]
[Question] [ ## Problem You've stumbled upon a paradoxical mathematical phenomenon related to prime numbers. Consider the following scenario: You have an infinite list of prime numbers: $$2, 3, 5, 7, 11, 13, 17, 19, ...$$ Now, you decide to pair up these prime numbers in a way that each prime is paired with its consecutive prime number and generate fractions by dividing the smaller number of each pair by the larger number. And you start adding them... $$\frac{2}{3}+\frac{3}{5}+\frac{5}{7}+\frac{7}{11}+\frac{11}{13}+\frac{13}{17}...$$ **they seem to be converging!!!???** Your task is to calculate the sum of all fractions in this sequence. Write a program or function that calculates the **sum of these fractions** up to a specified number of pairs (`n`). ## Input: * An **integer** `n` representing the number of prime pairs to consider (1 ≤ `n` ≤ 1000). ## Output * A floating-point number or The accurate fraction representing the sum of the fractions. ## Examples $$n = 3$$ $$\frac{2}{3}+\frac{3}{5}+\frac{5}{7}=1.980952$$ **Smallest code wins** (bytes) #### Some test cases ``` 3 = 1.980952 (208/105) 7 = 5.122912 (24845332/4849845) 9 = 6.742102 (21809669044/3234846615) 185 = 179.189745 564 = 556.886274 849 = 841.414962 999 = 991.228537 ``` [Answer] # [Python 3](https://docs.python.org/3/), 66 bytes ``` f=lambda n,p=3,P=4,d=2:n and P%p*d/p+f(n-P%p,p+1,P*p*p,[d,p][P%p]) ``` [Try it online!](https://tio.run/##DYxBCoMwEADvvmIRBI1rWxsVFdI3eBcPtlEa0HVJ0oOvtzkMDHMYPv33IHmZnQ/rwZ0uCtzc4u3y@VlnDtrMbnxaPoRosmtV27y/9QyErCQOqkKtnj3BTBqGhIW@c76mVARHzkscBAvGUSNPY2hTWBwWCAzBKBHKtkaomwqhrTqEruumPgK2hnwaJ1JD8YI4IYTwzLLrDw "Python 3 – Try It Online") The [Wilson's Theorem generator](https://codegolf.stackexchange.com/a/27022/20260) strikes again. Similar to [the template for the first n primes here](https://codegolf.stackexchange.com/a/152433/20260), but also stores the previous prime as `d` and keeps the running sum of the ratios. [Answer] # [Desmos](https://desmos.com/calculator), 69 bytes ``` L=[2...7920] P=L[∏_{d=3}^Lmod(L,d-1)>0] f(k)=∑_{n=1}^kP[n]/P[n+1] ``` [Try It On Desmos!](https://www.desmos.com/calculator/haqq7zskcv) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/seu5vihk57) Probably golfable but this is the best I could think of for now. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~48~~ 38 bytes Saved 10 bytes thanks to the comment of [@alephalpha](https://f(n)=sum(k=1,n,prime(k)/prime(k+1))*1.) --- ``` f(n)=sum(k=1,n,prime(k)/prime(k+1))*1. ``` [Try it online!](https://tio.run/##jctLCoMwFIXhuau4OEra9BGqRRH34AKcBL3Wi5qGJNLlpxZKaekks//Ad4yydLiZEAamee3WhU21FFoYSwuyiZ/esZec7@QxtC00lrQHPyJYdOvsHTzIj9CjI4s9GIsdObrrpN9iUXMzqw4d1CDPVWJeZ/YxbGAXLuBHbjuFVMA3kkUew/JrFsOKrIxhZfnPeBWe) [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8~~ 7 bytes ``` Σ↑Ẋ`/İp ``` [Try it online!](https://tio.run/##yygtzv7//9ziR20TH@7qStA/sqHg////lgA "Husk – Try It Online") ``` Σ↑Ẋ`/İp Ẋ # map over adjacent pairs of values `/ # flipped division: x ÷ y İp # apply this to the infinite list of primes ↑ # then take the first arg1 values Σ # and sum them ``` [Answer] # [Factor](https://factorcode.org/) + `math.primes math.unicode`, 35 bytes ``` [ 1 + nprimes 2 clump unzip v/ Σ ] ``` [Try it online!](https://tio.run/##LYu7CgIxEEX7/YrbCytqp2ArNjaylViEOLsGk0nITBb0d/wffyk@1ubAPdzTG6sx1@64P@zWMCLRCoYcS3I8IBi9/tCm7AIJbpSZ/KRG@qYyjcLOxgshZVK9f96s2DTNqp6wwAz875ewvoSEwg@XMM7xeuJcrfEe295Ho2jrGw "Factor – Try It Online") ``` ! 3 1 ! 3 1 + ! 4 nprimes ! { 2 3 5 7 } 2 ! { 2 3 5 7 } 2 clump ! { { 2 3 } { 3 5 } { 5 7 } } unzip ! { 2 3 5 } { 3 5 7 } v/ ! { 2/3 3/5 5/7 } Σ ! 1+103/105 ``` [Answer] # [Ruby](https://www.ruby-lang.org/) -rprime, 42+6 = 48 bytes ``` ->n{k=0;Prime.take(n+1).sum{|x|k*1.0/k=x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOtvWwDqgKDM3Va8kMTtVI0/bUFOvuDS3uqaiJlvLUM9AP9u2orb2f4FCWrRxLBeIsrS0jP3/L7@gJDM/r/i/blEBSDcA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÝØü/O ``` [Try it online](https://tio.run/##yy9OTMpM/f//8NzDMw7v0ff//98YAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3MPzzi8R9//v87/aGMdQwtTHVMzEx0LE0sdS0vLWAA). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input] Ø # Convert each to their 0-based n'th prime ü # For each overlapping pair of values: / # Divide them O # Them sum all these decimal values together # (which is output implicitly as result) ``` [Answer] # Python 3, ~~131~~ 112 bytes *-19 thanks to bsoelch* ``` lambda n:sum(x[k]/x[k+1]for k in range(n)) x=[i for i in range(2,7920)if not[i%j for j in range(2,i)if not i%j]] ``` [Try it online!](https://tio.run/##TYrLCsIwEEX3fsVshAwWtC@bCP2SmEVEo9PaSYgV6tfHWgTd3APn3PAab55LGWJy7THd7XA6W@DD4zmISfdmO88mN85H6IEYouXrRTDiamo1wcfTzxdZo4odkgP2o6Z1txy6/wN9K8zVmBQi8SicKDFzIpc1ZuBEva8WykotVEohpjc) Old explanation: ``` lambda n: # lambda with an argument x:=[i for i in range(2,7920)if not[i%j for j in range(2,i)if not i%j]][:n+1] # prime getter till 1000. 7919 is 1000th prime, slice until n+1 sum(x[k]/x[k+1]for k in range(len(x)-1)) # sum it up [1] # and return the latter ``` [Answer] # [Raku](https://raku.org/), 41 bytes ``` [\+] {.(2)Z/.(3)}({grep &is-prime,$_..*}) ``` [Try it online!](https://tio.run/##K0gtyjH7n1up4FCsYPs/OkY7VqFaT8NIM0pfT8NYs1ajOr0otUBBLbNYt6AoMzdVRyVeT0@rVvO/tYJecWKlQlp@EVBntJGOoYWJjqmZsY6FiYWOpaVF7H8A "Perl 6 – Try It Online") This is an expression for the infinite sequence of partial sums. * `{ grep &is-prime, $_ .. * }` is an anonymous function that returns a sequence of primes starting from the number given as its argument. * `{ .(2) Z/ .(3) }` is another anonymous function that is given the previous anonymous function as its argument in the variable `$_`, and evaluated immediately. `.(2)` calls the first function with the number 2, generating the primes starting from 2, and likewise with `.(3)`. `Z/` zips those sequences together with division, producing the sequence of fractions. * `[\+]` produces the infinite sequence of partial sums. [Answer] # [Python](https://www.python.org), 71 bytes ``` lambda n:sum(p(k+1)/p(k+2)for k in range(n)) from sympy import* p=prime ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Tc5NCsIwFATgfU_xwE3iTzQxad8TuvYSbioaLTVpiHXRvbdwUxC9k7exRQVXw_DBMLdnaJtj7bu7zTePS2Nn-FqfCrfdFeBX54tjgVUTyedDKG7rCBWUHmLhD3vmOU9srB2cWxdaKF2oYzNOQh5i6fbfuWtffMMsA1jyKQBIQbggo3jyE4mmF5mRkEiZNjwZ_cikuidjUoGYqkz_EWrqCbUUWmpK1R8RDUQkhVJolhn_fOm6T74B) ## Explanation `prime` computes the n-th prime # [Python](https://www.python.org), 105 bytes longer but faster ``` lambda n:sum(a/b for(a,b)in i.pairwise(i.islice(sympy.primerange(4**n),n+1))) import sympy,itertools as i ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Tc5LTsMwEAbgfU8xS7tNHezYiY3ETdg44MBIsR3ZrlDOwiYSgitwFm5DaKnS1Ujz_fN4_5rm8hrD8jE8PH6eynDUPzha3z9bCPf55ImtexhiIrbqKQZANllMb5gdQYZ5xCdH8uynmU0JvUs2vDgi9_tAq3DglNId-immAudQhcWlEuOYwWbA_4Pf62goZCAAnFYAIOqG7ramuDYPTa2ucBtozgHOjL4zSmzCtVqFd4ZxbTqpNlGtXEWplmndik5uoqVZRUvOJJemvdlmzJ8Yw5kQWjUdvby_LJf6Cw) ## Explanation Uses the fact that the n+1-st prime is less than 4n+1 to obtain a list of the first n+1 primes from the list of the primes less than n (`sympy.primerange`). `pairwise` groups the elements in adjacent pairs [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `+`, 7 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ÆpDḣỊØ. ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyU4NnBEJUUxJUI4JUEzJUUxJUJCJThBJUMzJTk4LiZmb290ZXI9JmlucHV0PTMmZmxhZ3M9JTJC) *2 flags -> 1 flag thanks to Neil* #### Explanation ``` ÆpDḣỊØ. # Implicit input Æp # First (input + 1) primes Dḣ # Push a copy without the first item Ị # Reciprocal of each Ø. # Dot product of the two lists # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 35 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.375 bytes ``` ʀǎ¨p/ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9cyIsIiIsIsqAx47CqHAvIiwiIiwiMTg1Il0=) Works for any n >= 1 (even bigger than 1000). The flag is for display purposes. ## Explained ``` ʀǎ¨p/­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‏​⁢⁠⁡‌­ ʀǎ # ‎⁡First n prime numbers ¨p/ # ‎⁢With every overlapping pair reduced by divison # ‎⁣Automatically sum 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [sclin](https://github.com/molarmanful/sclin), 20 bytes ``` $P"1dp"Q / rev tk +/ ``` [Try it here!](https://replit.com/@molarmanful/try-sclin) For testing purposes: ``` 999 ; 20N>d $P"1dp"Q / rev tk +/ ``` NOTE: the default representation is a rational number, but `20N>d` converts the representation to decimal for convenience. ## Explanation Prettified code: ``` $P 1.dp Q / rev tk +/ ``` Assuming input *n*: * `$P` infinite list of primes * `1.dp Q` duplicate and drop first item * `/` element-wise divide * `rev tk +/` take *n* elements and sum [Answer] # Excel, 127 bytes ``` =LET( a,ROW(1:7327), b,FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2), SUM(EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}))) ) ``` Input in cell `A1`. Fails for `A1>932`. **Explanation** ``` ROW(1:7327) # Vertical array of integers 1 to 7327 TOROW(a) # Transpose the above MOD(a,TOROW(a)) # 2D array of all those integers modulo all those integers MOD(a,TOROW(a))=0) # Which of these is equal to 0 N(MOD(a,TOROW(a))=0) # Convert Booleans to ones and zeroes a^0 # Vertical array of size 7327, each entry unity MMULT(N(MOD(a,TOROW(a))=0),a^0) # Matrix multiplication of the above arrays MMULT(N(MOD(a,TOROW(a))=0),a^0)=2 # Which of these is equal to 2, i.e. only divisors are unity and itself FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2) # Filter array of integers accordingly, i.e. list of primes <=7327 SEQUENCE(A1) # Vertical array from 1 to value in cell A1 SEQUENCE(A1)+{0,1} # Additional column added to above with values offset by 1 INDEX(b,SEQUENCE(A1)+{0,1}) # Index list of primes with these indices INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1} # Reciprocate the last entry in each pair with unity LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}) # Take the natural logarithm MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}) # Matrix multiplication for pairwise summation EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1})) # Take the natural exponentiation SUM(EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}))) # Sum all entries ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IΣEΦυκ∕§υκι ``` [Try it online!](https://tio.run/##ZY3BDoIwEETvfkWP2wQ/ADkRjYZECNGL1wor3VgolC7695UePBjnNvMyM41WrrHKhFAMI/uK@zs6mGS2Ke2CsLtQp/2fe2kyKKCyHk4OlV8rZxw6r4FlIiYppaCHgNwY4ESUtmVj4QYre0ZW86wjWBOZCTQzit/92tHgYa9mD1fuoVQjHMnEG44TiTjQQi1C7ouhxfc3JRmVhZCmadgu5gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→ ``` Input `n` and generate the first `n+1` primes using the same method as for my answer to [Number of bits needed to represent the product of the first primes](https://codegolf.stackexchange.com/q/263531/). ``` IΣEΦυκ∕§υκι ``` Divide each prime by its successor and output the sum. 30 bytes using the newer version of Charcoal on ATO: ``` Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IΣ×υ∕¹Φυκ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZY8xCsJAEEV7T7FYzUIs7IypRFEEE0QtBLFI4iS7uMlqdicexiagosfwGt7GBG3E381__P-Z8yMWYRHrUFXVjWzS6b2e0_xANqAswgKO3Gv5ukToL2Qq7N91ElIhg0BbmBQY2joywzy1Aog77Mg5ZzJhMFAKyGG-3pHSsIaa7Rs2JyMaUDvcY6gMst_-eSFzC8PQWFhSBiuZoWkCI1nKHULXYWOpmlX6NNbyriaKzfeb-6bdKVV7e3Fd9-O8AQ "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: Takes the dot product of the primes with the reciprocals of the odd primes. [Answer] # JavaScript (ES6), 56 bytes ``` n=>(g=(p,d=k++)=>k%d--?g(p,d):d?g(p):n--&&p/k+g(k))(k=2) ``` [Try it online!](https://tio.run/##FYxLDoMwDAX3nMILimzR9LcETK8CIh@1QU4EqBvE2dOwmtHT6H3H37hOyyduSoI2yXIS7tExxqtmX9fEvb9opd7uXKjRp1AjSlVVvPvaoSdCzy9KNiw4mw0EGJ5tRpf5yJJfYC8ApiBrmM1tDg6HEctdDsptuVsUOgZqiyP9AQ "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~43~~ 32 bytes Saved 11 bytes thanks to the comment of [@Roman](https://codegolf.stackexchange.com/users/87058/roman) --- ``` N@Sum[Prime@i/Prime[i+1],{i,#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@9/PIbg0NzqgKDM31SFTH0xHZ2obxupUZ@oo18aqARXpOyhUG@soGFqY6iiYmpnoKFiYWOooWFpa1irog3TklfwHAA) [Answer] # G[AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 49 47 bytes ``` func f(n){t=0;for(i=1;i<=n;)t+=$i/$++i;print t} ``` [Try it online!](https://tio.run/##JZjNiiXHEYXX8lMUYwlmGLAq4zeTUW8MttBC8sYvYIQaGkNrGLXwYphnH58venHj5s/NyMisU@dE3P/8779f//6PH3/65fO//vnzv6@H6813f6vHN1@uv14//vZyffz0269Pfzz9/nz9od6fH78@/vn86/X49vnd55eH@8Pj75/ePj2sD08/PDx/ePfy/uHbp@@/ff/@6cPHT0/PL9fLl6@f//LN41t/h1075zsr5nvHme9z9P3lq11@5dXXWtfya6lxLvPLzuXr8r5iXeFX9JX63blqXdVXr6v96nNtv/a5jlbdWn/LwU37yJ3aprbjl2@NhT6pfqpfmpen1Wyq8a3xw0d9/B2FoZiMWOTHjLDUlh9TTJZ8NC4/VhpTSNbqy49t4vfLFYvLhysW18mcEykWDz46oI7kOpMrDlccrjhca11HcsUQOlPoLKErCeMe@OgyFENwKfIRiiF0KaE4Qn5CPmLrW2cJnSF1JykfqfWps6RiT25T61JrUrGnYk/FnlqXh2vWPWvvUvyl2GvxrTHtX8FHY/JRir94JvNQ1JaPUvylvfvmc/Sk9NH9teJuxd1a27q71v6tda39m2epvVtn3lqzdWfb@Ojpau02HrQ@2m9r3daeW7Fv7bd13xsUaP1RvEdrj/Y8WnN010fxHsV6tPbofo7OerTuaM1RnGewA2BuEHMvWjZYGsMY0LnBzg147hrDRDG2B3CMAZ0bfwPEVxQC6GV0jS4OVtLFwWq6ewy/w4EBZBv0shb8LcAnJ0wAZSMWS0zTBb5gToYWsRhhOK6cWECi3gTNOmfzeTE4B9BbYG85YfjhLSHwYN/gd8HmwG7FvEPBGOcIzhGEEZwj9hjGOEzseeHonnnteO9wmpwjg9a8j3hJvCSxgEUZurhKzgEWF2CU0QSQXOBxFYcpm7cZM@/1vNg1LX5CBDVeCANIrmZZEwuoXB10OVYTSxNLc7FNBABTBoYgDLC5AObanGOzbHOTmy030W@uE2zKsIy1h7XgUxwDwfgwDS3u4HCdp4d56O7hH7qvTCR6ufUYBY2FEcvcNoYJCOlOZmsMXUjohoVApwxjr4S2MJoAjgY5GuxoC0rTA5bBla5XRrGYsa/dECDLZKFEuuxrrBgqtGKMza0ZIwLbw5t0dQ7zGwolAh8ixYGzL3xojheHUR0qdbgUTBqMaFCidhz@HQJeGP0EnCoKWrgCnQYmDTK0IJbAFTxokKCBPxn9BBAaILQcNmdzoKdXiy67ATiD/wysiewZY48a7mejGgUgZvjPIECZaTE7Xoi5ucQm8OYmIUZrnkITECCUocsDaKIHhAb09IYzyyUCQhlHaA5KQ4vjbw6zOQcUaWDSwJ/BjCIGmcOyw4kOJzpg6HARkKMMXQ5zeIwQpQE9v7WlAz2HHf02lA0Zu4MxhAxOlGEMDQN6DuocEtQjx9gIIYpYyGFNi4nNxKarUzqAk9EE/OcAzuE/B2YyzCYTCCeq60aQcJ2P4I7awnXuROqsfVXeoIv2jujCfw7WfLR3RNeJIPASeIH1HJV1ZNbRWUdoHXDJMDEriACGk9FE2pgReBTeaXFXCK8DM4fwHK7z3GMmE5CB5hyGc1DnxRHQXYfhHOX1ek0ZGCNwUOdIrkNzjvA6NOcgzNFeh@Yc9XUk13vyDaJvnlafST00Bq4c5XUYzgGXw3AOrhz5dXTXITdHeX1PqkLMCK@DK0d@/eAAEXa4zg@Bo8OOCPvRsrgnvdGWMpPs0CLVQX8DhgvAFaiuDN3mJ2Q4CG4guAGvBbwWpHsBr@nZOYZW0mKtpERGgQcKG@R2AcJkyK5YhsIGyV3AawHWApiFkWCBtYDcAq0NtDbgtUBNg7wuoLQgswuILJycDHAFuIpJ6Safm2QO5gpIKyCtQFJjsrlJ5VDTQE0DDY3khpIbAmEyZH44AFKRkwgSJBoaoCngsEA@o7hi6CvAkIx@DJBkaLFvTRb5mkKOYQIHzVr0MtDLgK8CNAU5XCCVgUoGKhlQVYAmGbJQ7nkT8yZm9DKgpUAlAwwF8AloKaClADkBXgJtDPK3ADmBQAYEFcAnIKhAL@NMqsuWZ5LdyXZJd@GrBEgJXyUqmQBJhhbZLiqZCGSCoaSCSMqHRCAT0spFpgyGEr5K8rVEFnNtjG43bZJro@WTYjuGbtFtuqxAERO8JBlZIoYJQSVimD4FDvGheTJ0ScWRu4SREkZKNC@pB5JiIBG@jEnpg9lgoifDZ4J9wVAmZ5tSACAl8MmpCKCqRBFzCoKpCKYkSAKHmxIgJTyUICcpABIJTJCT1ABZU0xwseRciQQm6peoX8JIifDJ6HdNzMhdUgskmpfwUAKkROkS5MhQkXBoGCkpBJIqIFE6GVpEgNwluEpSMBkm8AdBJcKXICxhpETzEs3LM/UkPwFDBQUVoCmyqkLf6qbOuSl0yK8KfSsoqKCgQt8KHiqQU2sKJaPlY@jigJy/0Lyi1ixAU1SXhdIVPFTwUKF0BQ@VsSUiV1SXRVZVsE@R7hdZVaF5heYVCVVRXRZoKuSuIKNC7ooSs5C7Qu6KdL9gpKLWLDSvoKWCkYp0v8BQQUaFvhUZVEFGhdIVoCmkrXIKQH6XUwbWGCaIlHKygE9NMTmV5JSQUFBN4fhaORLV1I5wTgGagngK0BTsU2hZoWUF8RTwqZ6Ks6bkZIKNepYJcIWMFQpWgKYoHwstq03xCl4KGSugUpBRUUFqb3XRskLLCi0rJKvI0esQ7mFfKKhIj4pCss5UvGxOtt73FL4CQ6NljYw17NOgqZGxJkdvMNQUir2mTNbFNgrWKFgDmkayGslq0qOmPGxS8QY0TT7eNuU1K@CcRrca@DTi1QhVwzlNZtRwTlMANvlQ@5TkwRi7OVHBOU123TBNkwA1YGiUqUmsG2ppENHUeU2d1yRADbU08tQoU4MS5bJ0g3o/psUYXlCrhmQaqDSSJcMEfx4gWQ1oGt1qiKeRrEayGpJpQNNFGCTbPf85kGc3oGmYppGsnj8foJsmse753wHdatSqwUsjTw1eGqg0KGmSnYZQer/@OzEtZomUcq6BSiNZDas0ktVIVoOXRrKadLqRp40oidbW/wE "AWK – Try It Online") * -2 bytes, thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) : `$(++i)` to `$++i` This one implies that the input file is an infinite list of prime number. The function is still taking an integer `n` as argument. As mentionned by [@Olivier Dulac](https://codegolf.stackexchange.com/users/7017/olivier-dulac), this script need to run using `gawk` or other `awk` variant that support having multiple digits fields. He also suggested a variant that could work with Unix Shell, that would be **61 bytes**, and would take as input file an infinite list of prime number, with one number per record : ``` # HEADER BEGIN{OFMT = "%.6f"} # Get precision set up #HEADER {a[NR]=$0}func f(n){t=0;for(i=1;i<=n;)t+=a[i]/a[++i];print t} # FOOTER END{ f(3) f(185) f(564) f(849) f(999) } # FOOTER ``` --- # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 120 111 109 bytes ``` {for(a[n=1]=2;t=j=n<1e3;a[++n]=m)for(m=a[n]+(i=1);++i<m;)i=m%i<1?2+0*m++:i;for(;j<$0;)t+=a[++j]/a[1+j];$1=t}1 ``` [Try it online!](https://tio.run/##FYzLCsMgEADvfkcKsXtoNo8Suy79EPHgoYW1aKAIOYR@u42nOcwwYf/Uery3bx9cZvQ8UuHI2eJrouAAsuekm098Fh56YdQEIDaRFk4XsfgcYbgmgIdQKynabiBdgNsg@ltweII65PLDWieF66KW@6zW2ShjzB8 "AWK – Try It Online") * -9 bytes, thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) * -2 bytes, replaced `print t` with `$1=t`, then `1` as precision is not necessary This one work with just n as input. It only supplies `999` pair of prime number, but if you change `1e3` with `1e4` it will supplies `9999`, it will just get 10 time longer for each lines. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` _j}jUÄ ä÷ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LXg&code=X2p9alXEIOT3&input=Mw) ]
[Question] [ Not restricted to any one programming language. What I'm saying is you pass 1 to it and it returns Monday, 7 corresponds with sunday and so on. I've managed a 146 byte statement in Java to do the same. ``` return (n<1?"invalid":(n<2?"monday":(n<3?"tuesday":(n<4?"wednesday":(n<5?"thursday":(n<6?"friday":(n<7?"saturday":(n<8?"sunday":"invalid")))))))); ``` Your program should: * output full words (STDOUT) * not crash if the input is less than 1 or greater than 7 [Answer] ## Bash: 47 bytes Still no bash entry? I'm disappointed ... ``` case $1 in [1-7]) date -d "14-08-1$1" +%A esac ``` It uses the days of the current week and simply substitutes the last digit (11-17 August 2014 -- 11 is Monday, 12 is Tuesday, etc.). [Answer] ## Ruby, 69 or 38 bytes Here is a simple way to improve your code (written in Ruby but it works similarly in Java): ``` n>0&&n<8?%w{Mon Tues Wednes Thurs Fri Satur Sun}[n-1]+"day":"Invalid" ``` * Combine the two invalid checks into one. * Put all the days in an array and use `n` as an index. * Factor out the common `day`. You can make it even shorter if you import the names of the days of the week from a library, like Ruby's: ``` n>0&&n<8?Date::DAYNAMES[n%7]:"Invalid" ``` Note that now I don't decrement `n` but instead take it modulo 7 to map `7` to `0`. This is because `DAYNAMES` starts with Sunday. [Answer] # [Marbelous](https://github.com/marbelous-lang/marbelous.py) 192 191 185 181 ``` }0 =1=2=3=4=5=6=7-- &1&2&3&4&5&6&7{0 &8//////////// 4D6F6E547565735765646E65735468757273467269536174757253756E646179 &1&1&1&2&2&2&2&3&3&3&3&3&3&4&4&4&4&4&5&5&5&6&6&6&6&6&7&7&7&8&8&8 ``` Non-zero exit code if the input is invalid Usage: ``` # marbelous.py -r day-of-week.mbl 2 Tuesday ``` [Answer] ## Javascript, 95 88 bytes ``` x=prompt();alert("Invalid 0Mon0Tue0Wednes0Thurs0Fri0Satur0Sun".split(0)[x&~7?0:x]+"day") ``` 7 in binary is 0111, meaning that you can shave off a few characters with a bitwise operation instead of `x>0&&x<8`. Edit: Removed the `s` array with the help of [edc65](https://codegolf.stackexchange.com/users/21348/edc65). [Answer] ## C# - 26 Bytes Expects the day to be stored inside `n`. Does not crash, as expected. Powered by LINQPad™ ``` ((DayOfWeek)(n%7)).Dump(); ``` Special thanks to bmarks and Stephan Schinkel for byte saving and rule bending, respectively [Answer] ## C#, 95 bytes In C# you can do something like this: ``` return(i>7||i<0)?"invalid":new[]{"mon","tues","wednes","thurs","fri","satur","sun"}[i-1]+"day"; ``` [Answer] # [Extended BrainFuck](http://sylwester.no/ebf/): 104 ``` {a))<(->>}+>,49-(-(-(-(-(-((-)<->>|"sun")<(->>|"satur"&a|"fri"&a|"thurs"&a|"wednes"&a|"tues"&a|"mon")|"day" ``` Ungolfed (Idiomatic) ``` {main :flag + :input $input &read_number - (- (- (- (- (- ( $input &reset ; 7-9 $flag &reset |"sun" &reset ) $flag ( &reset ; 6 |"satur" &reset )) $flag ( &reset ; 5 |"fri" &reset )) $flag ( &reset ; 4 |"thurs" &reset )) $flag ( &reset ; 3 |"wednes" &reset )) $flag ( &reset ; 2 |"tues" &reset )) $flag ( &reset ; 1 |"mon" &reset ) |"day" } {reset (-)} {read_number , 48- } ;; call main &main ``` [Answer] ## T-SQL 36 ``` SELECT DATENAME(w,@+6)WHERE(6+@)/7=1 ``` Assumes the variable is stored in @. If it is an invalid input (@>7 or @<1), then it doesn't select anything. Edit: Apparently a date can be a number. Removed 5 characters with that. Edit 2: Based on the first edit. Since it's an int, I don't have to use DATEADD(); I can use normal addition instead. [Answer] # Javascript 93 :( ``` q=prompt();alert(q<8&&q>0?'0mon0tues0wednes0thurs0fri0satur0sun'.split(0)[q]+'day':'invalid') ``` [Answer] # Lua - 57 bytes ``` print(n>0 and n<8 and os.date("%A",9e4*(n+3))or"Invalid") ``` Lua has os.date() in it's standard library, and it has formatting. So you can pass a time (in this case "9e4\*(n+3)") and ask to return the "%A" format, which is the names of the days of the week. Also, very useful in Lua is "a and b or c". If a is true (in the code a is "n>0 and n<8") it returns b, if a is false (or nil) it returns c. [Answer] # Mathematica ~~19~~ 16 bytes ``` DayName@{1,1,#}& ``` As Dr. Rebmu noted, January 1, 1 A.D. is a good place to start. It (presumably) fell on a Monday. ``` DayName@{2014, 9, #} &[1] ``` > > Monday > > > [Answer] # Bash - 21 19 Assuming the input is in variable `D`: ``` date +%A -d$D"Jan1" ``` # HTML + PHP - 26 Let `$d` be an input text ``` <?=date('l',86400*(3+$d)); ``` Timestamp 86400\*3 is the first Sunday from the start of UNIX world. You can test it by executing: ``` <?php $d=3; ?> <?=date('l',86400*(3+$d)); ``` [Answer] # Perl, 60 bytes Something like this: ``` $x&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||die ``` If want to return a message instead and you're concerned about negative indexes you can use this one instead (8 more chars): ``` $x>0&&qw{Mon Tues Wednes Thurs Fri Satur Sun}[$x-1]."day"||"Invalid" ``` [Answer] # Lua ~~134~~ ~~119~~ ~~115~~ ~~100~~ 98 ``` q={"mon","tues","wednes","thurs","fri","satur","sun"}print(n<8 and n>0 and q[n].."day"or"invalid") ``` Basically the same thought [MartinButtner](https://codegolf.stackexchange.com/a/36221/11376) had, except about ~~4.5~~ ~~4.1~~ ~~1.7~~ 1.4 times longer. Does assume `n` is stored as a variable elsewhere. [Answer] # Python (84) ``` lambda a:'imtwtfssnouehrauvneduitnadsnrdudladesaraiyasdydyd yda a ay y y'[a if 0<a<8 else 0::8] ``` I suppose it's an interesting sollution. It takes an idea from another answere I read somewhere (can't find it, I do know it was on this site, so if anyone knows feel free to tell me.) The string was generated with the following J program: ``` ,|:>'invalid';'monday';'tuesday';'wednesday';'thursday';'friday';'saturday';'sunday' ``` Taking some subtle hints from [this](https://codegolf.stackexchange.com/a/36227/18638) answer: ``` lambda a:' mtwtfssouehrauneduitn snr u es r s'[a::7]+'day'if 0<a<8 else'invalid' ``` [Answer] ## Bash 74 48 + error message A different approach since all other answers focus on storing the strings in some form. ``` read x;((0<x&&x<8))&&date -d2007010$x +%A||echo out of range ``` [Answer] # Perl, 54 From STDIN to STDOUT, no date functions, no crash. ``` print((a,Mon,Tues,Wednes,Thurs,Fri,Satur,Sun)[<>].day) ``` [Answer] # PHP (56 bytes) ``` $d=1;echo$d>0&&$d<8?date('D',255600+$d*86400):'Invalid'; ``` [Answer] ## Clojure - 99 chars Plain and simple, despite my best (newbie) attempts: ``` (defn f[x](get{1"monday"2"tuesday"3"wednesday"4"thursday"5"friday"6"saturday"7"sunday"}x"invalid")) ``` [Answer] # JS: 58 Assuming n is already stored as a variable. ``` "0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day" ``` As an ES6 function (same assumptions): **67** ``` let d=n=>"0Mon0Tues0Wednes0Thurs0Fri0Satur0Sun".split(0)[n%8]+"day" ``` This will just print "day" for 0 and loops around for n > 7 [Answer] # [Rebmu](https://github.com/hostilefork/rebmu): 21 characters ``` pcSYSTEM/locale/daysA ``` To run: ``` >> rebmu/args {pcSYSTEM/locale/daysA} 1 == "Monday" ``` Invalid numbers will return "none". ``` >> rebmu/args {pcSYSTEM/locale/daysA} 8 == none >> rebmu/args {pcSYSTEM/locale/daysA} 0 == none ``` For those unfamiliar with Rebmu, it uses case transitions to remove the need for spacing--within the limits of what's legally parseable. Rather than using a InitialCapsToBreak it uses CASEtransitionsTObreak, because that allows a different meaning to be ascribed to an initial run of capitals from if the initial initial run is lowercase. So it is equivalent to the Rebol program `pick system/locale/days a`. (Rebmu by convention names its script parameter as "a"). Saves one character over `system/locale/days/(a)` :-) [Answer] # Haskell - 62 Wraps around; `0` is Sunday, `8` is Monday, and so on. ``` words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day" ``` If printing to stdout is required (**68 bytes**, output is in double quotes): ``` print$words"Mon Tues Wednes Thurs Fri Satur Sun"!!(mod(n-1)7)++"day" ``` [Answer] # LiveScript - 49 Returns `undefinedday` if the input is invalid. ;) ``` <[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day ``` If printing to stdout is required (**60 bytes**): ``` console.log<[Mon Tues Wednes Thurs Fri Satur Sun]>[n-1]+\day ``` [Answer] # Befunge-93 (206 ~~208~~) This one was fun to write. I'm sure it can be done in a better way, but… it works! =) Can be tried out [here](http://www.bedroomlan.org/tools/befunge-93-playground). Would've been even shorter if the `#` would jump over entire strings rather than just the individual cell. ``` &1- v vv"Mon"># :# !_ > 1- v vv"Tues"># :# !_ > 1- v vv"Wednes"># :# !_ > 1- v vv"Thurs"># :# !_ > 1- v vv"Fri"># :# !_ > 1- v vv"Satur"># :# !_ > 1- v vv"Sun"># :# !_ >>:#,_"yad",,,@ ``` The basic idea behind it: Get the number and keep decrementing it. Everytime we decrement it, the cursor moves to the right, wraps around and is sent one level lower. Once we hit zero, move to the left instead and push the (first part of the) day name. From then on, the cursor will move straight to the bottom where the string is printed and "day" is appended. You can see how it works by using the "Step" feature in the link to the online interpreter. *Edit:* I managed to shave two bytes off by doing `>:#,_` instead of `>,,,,,,`, which is pretter as well. [Answer] # **MATLAB : 33** ``` datestr(3:9,'dddd');ans(1:7==n,:) ``` # **MATLAB : 71** ``` {'mon';'tues';'wednes';'thurs';'fri';'satur';'sun'};[ans{1:7==2} 'day'] ``` # **Haskell : 75** ``` g n=((++"day").last.take(abs n).words)"mon tues wednes thurs fri satur sun" ``` # **Haskell : 97** ``` f n=if elem n[1..7]then["mon","tues","wednes","thurs","fri","satur","sun"]!!n++"day"else"invalid" ``` # **Python 3.4.1 : 81** ``` 'invalid mon tues wednes thurs fri satur sun'.split(' ')[n*(n in range(8))]+'day' ``` [Answer] ## Java 8 - 69 64 chars Here's an expression in Java 8, including the import. Now improved (thanks to [Tomáš Dvořák](https://codegolf.stackexchange.com/users/26993/tom%C3%A1%C5%A1-dvo%C5%99%C3%A1k)): ``` import java.time.*; return DayOfWeek.of((i>0&i<8)?i:1).name(); ``` Simply prints `MONDAY` for bogus values of `i` [Answer] # Python - 87 I'm not seeing enough love for dict's .get() This one expects `a` to be the number ``` dict(enumerate("mon,tues,wednes,thurs,fri,satur,sun".split(","),1)).get(a,"bad ")+"day" ``` [Answer] ## Python, 95 bytes ``` "%day"%["mon","tues","wednes","thurs","fri","satur","sun"][n-1] if 0<n<8 else "invalid" ``` [Answer] # Python 2, ~~84~~ ~~83~~ 64 Assuming n is already stored as a variable. ``` import calendar as c;print c.day_name[n-1]if 0<n<8 else'Invalid' ``` [Answer] # Cobra - 43 ``` print if(0<n<8,(n%7)to DayOfWeek,'Invalid') ``` ]
[Question] [ Suppose A and B are two good friends. A has borrowed \$n\$ dollar from B. Now B wants the money back from A and A is also ready to give it. But the problem is A has only \$x\$ dollar notes and B has \$y\$ dollar notes. They both want to keep the number of notes in exchange as low as possible. As an example if \$n=37\$, \$x=5\$ and \$y=2\$, then the least amount of notes in exchange will be nine $5 notes from A and four $2 notes from B, which totals to $37. Your input will be \$n, x, y\$ and your output should be the least of amount of notes possible for \$A\$ and \$B\$ such that \$B > 0\$. Input and output seperator can be anything, no leading zeros in input numbers, no negative numbers in input. Standard loopholes apply and shortest code wins. **Test Cases** ``` 37 5 2 -> 9 4 89 3 8 -> 35 2 100 12 7 -> 13 8 10 1 100 -> 110 1 ``` Input will be always solvable. [Answer] # [J](http://jsoftware.com/), 40 bytes ``` 1 :'1+[:($#:u i.~,)[:+//(,-)*/1+[:i.u+]' ``` [Try it online!](https://tio.run/##TcmxDoIwFEbhnaf4oyZtpS29rQS4iZOJk5MrcTIScXFi9dUrFxwczvKdV954NeDIULAI4DnncbpezpnAisqe9W7LE0b/sabnsqq0dWZfyRn9VN5UNsXj/nyjhk4NBoNYrNDhAMf/vnCqEcUTdNuJt6tTQitOEZpCkNP8DgXQsuTImH/@Ag "J – Try It Online") A bit labored as J code, but the idea is simple. We construct a table with all the possible linear combinations, and just find the coordinates of what we're looking for: [![enter image description here](https://i.stack.imgur.com/X051z.png)](https://i.stack.imgur.com/X051z.png) In the actual code we drop the first column (because of the B > 0) constraint, and then have to add 1 to the returned coords, to adjust for 0-indexing. [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` n,x,y=input() c=n+y while c%x:c+=y print(c-n)/y,c/x ``` [Try it online!](https://tio.run/##JYtRCsMgEAX/PcUiFJRsiZqWpAFPswgRylaKoXp6axJ4HzMwL9W8fdi13xbfAewaSiApZWMsWH3ktGelBXkeqrgaupWVBl9F@kbOiu6sx4o0lnb81DQjPBGcFmp5IUwIS0drDIJ1CPMpnfuM6fLo4o7@Dw "Python 2 – Try It Online") -8 bytes thanks to Jonathan Allan [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 14 12 bytes ``` b;.z₂×ᵐ-~h?∧ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6Ompoe7Omsfbp3wP8larwrIPTwdyNGty7B/1LH8///oaGNzHVMdo1idaAtLHWMdCyDD0MBAx9BIxxzM1DHUAfJjYwE "Brachylog – Try It Online") The albeit strange constraint that the outputs must be `≥1` helps, as Brachylog tries only positive numbers for multiplication. ``` b;.z₂×ᵐ+~h?∧ [37,5,2] b [5,2] ;. [[5,2], output] z₂ [[5, A], [2, B]] ×ᵐ [5 * A, 2 * B] - 5 * A - 2 * B ~h? [5 * A - 2 * B, X, Y] = [37, 5, 2] ∧ return the output [A,B] and solve the constraints ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 54 bytes ``` f=(n,x,y,i=0)=>(i-n)%y||n>i?f(n,x,y,i+x):[i/x,(i-n)/y] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6dCp1In09ZA09ZOI1M3T1O1sqYmzy7TPg0mpV2haRWdqV@hA5bWr4z9n5yfV5yfk6qXk5@ukaZhbK5jqmOkqfkfAA "JavaScript (Node.js) – Try It Online") Javascript beats Python! [Answer] # [JavaScript (V8)](https://v8.dev/), 45 bytes ``` x=>y=>n=>(g=m=>m%x?g(m+y):[m/x,(m-n)/y])(n+y) ``` [Try it online!](https://tio.run/##TcpbCoMwFITh9@5DmMGKN4q2cNKFFB9EUCycICqSrD4NSEEY/oeP@fZHvw3rvOzZ0YZRghPjxVgxmETFaOLeEzT1fH00d3doZpn7jrDRwrLOdseIB1ERdUPe/lQTbdzzQmX8NERZFFc8IYYMPw "JavaScript (V8) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 14 13 12 ~~ 11 [bytes](https://github.com/DennisMitchell/jelly) -1 thanks to [Nick Kennedy](https://codegolf.stackexchange.com/users/42248/nick-kennedy)! (Dividing through and keeping those invariant under flooring is terser than testing divisibility and then integer dividing.) ``` ‘r×ṀɗĖ÷ḞƑƇḢ ``` A dyadic Link accepting `amount owed` and a list of denominations `[y, x]` that yields a list of `[B gives, A gives]`. **[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4oCYcsOX4bmAyZfElsO34biexpHGh@G4ov///zM3/1syLCA1XQ "Jelly – Try It Online")** ### How? ``` ‘r×ṀɗĖ÷ḞƑƇḢ - Link: integer, n; list of integers [y,x] ‘ - increment (n) ɗ - last three links as a dyad - f(n+1,[y,x]): Ṁ - maximum ([y,x]) × - (n+1) multiplied by (that) r - inclusive range -> [n+1, n+2, ..., (n+1)×max([y,x])] Ė - enumerate -> [[1,n+1],[2,n+2],...] (...note that this equals [[n+1-n,n+1],[n+2-n,n+2],...]) ÷ - divide by ([y,x])? (vectorises) Ƈ - keep those which are: Ƒ - invariant under: Ḟ - floor Ḣ - head ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~41~~ 39 bytes ``` (n,x,y)=>g=(B=1)=>(n+=y)%x?g(B+1):[n/x,B] // 41 bytes, original (n,x,y)=>g=B=>(n+=y)%x?g(-~B):[n/x,-~B] // 39 bytes, user l4m2’s improvement ``` ## 41 bytes, original [Try it online](https://tio.run/##bczBCoJAGATge0/hJfb/cSpXCzX4C/Y1ooMEynrYxETWp9@2Q1DgbWC@mb6Zm9djtMO0m6vQSiAHj4Xl0gkZ0TGQS2Xhrb92ZFLN55s7eJh7GEbrJmqpKHFCzsT7/mkdKShORCRRNY6KN19W1ShQrbAirn@czjLoHOWK1PHgT0Ij8jX56RSHNw "JavaScript (V8) – Try It Online") The formula to satisfy is `A * x = n + B * y`, or `A = (n + B * y) / x`. Since we are looking for an `A` that is an integer, we try `B = 1, 2, 3, …` until `n + B * y` is divisible by `x`. For `B = 1, 2, 3, …`, we have `A * x = n + y, n + y + y, n + y + y + y, …`, so we can reuse `n` to store `A * x` and increment it by `y` at the beginning of each iteration. The solution is similar to [Redwolf Programs’](https://codegolf.stackexchange.com/a/225267/103803), and is equally 41 bytes long, but IMHO its form is different enough to merit being a separate answer, and the function accepts the arguments in a more natural form `f(n,x,y)` rather than `f(n,x)(y)`. ## 39 bytes, user l4m2’s improvement [Try it online](https://tio.run/##bczBCoJAGATge0/hJfb/aSxXCzX4DXyN6CCBoodNTGS99OrbdggK9jYw38zQLM3zPvXjHC@Fa8WRgcXKUnVSS0VmJytv7aWj@FXz@WoOFj7d3Dj1ZqaWshwnpEy8Hx69IQXFkYhEqsRR8ebLihIZigDL/PrH6SSBTpEHpPYHfxIanofkp1Ps3g) `~B` gives the 2’s complement of `B`, which for non-negative integers is equivalent to `-(B + 1)`. So `-~B` is equivalent to `B+1`… with the difference that `~B` implicitly casts `undefined` to 0, so we no longer need to initialize `B=0`. What a trick! 🙌 [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes ``` f=lambda x,y,n,s=1:s+n%x and 1j+f(x,y,n+y,0)or n/x ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRoUKnUidPp9jW0KpYO0@1QiExL0XBMEs7TQMsoV2pY6CZX6SQp1/xv6AoM69EI03DVMdIx9hcU5MLJmCsY6FjYYkkYGikY65jaGCALATiA7Gm5n8A "Python 3 – Try It Online") Output as the format `(9+4j)` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` Nθ≔⁺×…·¹θNNη≔⌕﹪ηθ⁰ζI⟦÷§ηζθ⊕ζ ``` [Try it online!](https://tio.run/##bY09C8IwFEV3f0XGF6jQujh0KoqQoVLETRxi8mgD6avNR5H@@VgR0cHhDgfuuVd10qlB2pQE3WM4xv6GDkZerirvTUvQ2OjhbHr0IEgtYCY8SWoRioyNPGO/Hv/D3XfrYEhDPehoB@jedr5kXhqNMxRgJ32Ai6CwN5PRCFUQpPHxKs/8c6cc9kgBNcz8ynmZUrFhW1bkeVpP9gk "Charcoal – Try It Online") Link is to verbose version of code. Takes input in the order `x y n`. Explanation: ``` Nθ ``` Input `x`. ``` ≔⁺×…·¹θNNη ``` Form a range from `1` to `x`, multiply each element by `y`, and add `n`. ``` ≔⌕﹪ηθ⁰ζ ``` Find the index of the first multiple of `x`, which is also `1` less than the number of notes for `B`. ``` I⟦÷§ηζθ⊕ζ ``` Calculate the number of notes for `A` and output the results on separate lines. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~47~~ ~~42~~ 41 bytes *-5 from @Arnauld* *-1 from @tsh* ``` (n,x,b=0)=>g=y=>(++b,n+=y)%x?g(y):[n/x,b] ``` [Try it online!](https://tio.run/##VcpBCoMwEEbhfU@RTWF@MsWoiLEw9iDFhQqKLoKoiDl9tIuCbr/3xnqrl3YepvW12dBJIMc7N2IgZS9eStK6YafF47l/evJ4f110HlWY5sGt1FGas8pACfD4ky1YpSB7odgYVnECym94Gn4NCAc "JavaScript (V8) – Try It Online") **Old:** ``` (n,x,b=0)=>g=y=>(a=++b*y+n)%x?g(y):[a/x,b] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvtfI0@nQifJ1kDT1i7dttLWTiPRVls7SatSO09TtcI@XaNS0yo6UR@oJPZ/QVFmXolGmoaxuY6CqaaGkaYmF0zIwlJHwVhTwwJJyNDAQEfB0EhTwxxFECimCZLT1PwPAA "JavaScript (V8) – Try It Online") **Old:** ``` (n,x,y)=>(g=b=>(a=b*y+n)/x%1?g(b+1):[a/x,b])(1) ``` [Try it online!](https://tio.run/##VchBCsIwEEbhvaeYjTBjf2mmRRqF6EHERSK01EUotZT09DEbQeHxFt/Lr/79nMdpOa429y5zRMIm7sqDC@XehcNWRanTXm8Dh0rlcvd1QngIq@RpHuPCPbcd6ARqRHZfsmdQC7I/pMaAtAF1f1isZIxI/gA "JavaScript (V8) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~21~~ 20 [bytes](https://github.com/abrudz/SBCS) Similar idea as [Jonah's J answer](https://codegolf.stackexchange.com/a/225272/64121), but quite a bit shorter due to APL's 1-indexing. ``` {⊃⍸⍺=⊃∘.-/⍵×⊂⍳⍺+⌈/⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRV/Oj3h2PenfZglgdM/R09R/1bj08/VFX06PezUBx7Uc9HSCh2v9pj9omPOrtA@tY86h3y6H1xo/aJj7qmxoc5AwkQzw8g/8bmyukKZgqGHFZWAIZxgoWXIYGBkCWoZGCOZAJYimARAA "APL (Dyalog Unicode) – Try It Online") A dfn which takes `n` as left input `⍺` and the array `x y` as right argument `⍵`: ``` ⍳⍺+⌈/⍵ ⍝ indices from 1 to n + max(x, y) ⍵×⊂ ⍝ multiply x and y with each index ⊃∘.-/ ⍝ create a table of all pairwise differences ⍺= ⍝ for each value: does it equal n? ⊃⍸ ⍝ get the first index of a 1 ``` [Answer] # [R](https://www.r-project.org/), ~~54~~ 50 bytes ``` function(n,x,y){while((m=n+T*y)%%x)T=T+1;c(m/x,T)} ``` [Try it online!](https://tio.run/##K/rv4@fravs/rTQvuSQzP08jT6dCp1KzujwjMydVQyPXNk87RKtSU1W1QjPENkTb0DpZI1e/QidEsxasUcPYXMdUx0iTC8yxsNQx1rGAcgwNDHQMjXTM4VwdQx2gmOZ/AA "R – Try It Online") Port of [@hyper-neutrino's answer](https://codegolf.stackexchange.com/a/225265/55372). *-4 bytes thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)* --- Port of [@tsh's answer](https://codegolf.stackexchange.com/a/225273/55372): ### [R](https://www.r-project.org/), 53 bytes ``` f=function(n,x,y,s=1)"if"(s+n%%x,1i+f(n+y,x,y,0),n/x) ``` [Try it online!](https://tio.run/##Pcs7CoAwEITh3mMIQpYMmFVELVLaqZcQAmlW8AHJ6aMEsfz@YY40r8tkk7Pulu3yuyhBQMRpmUrvSnVqqaoA9top0TGPhiB1oPxVbY8ODRUZw4gWwwc2Btyg/wnG2yg9 "R – Try It Online") --- Other ports of [@hyper-neutrino's answer](https://codegolf.stackexchange.com/a/225265/55372): ### [R](https://www.r-project.org/), 54 bytes ``` function(n,x,y,K=n+y){while(K%%x)K=K+y;c(K/x,(K-n)/y)} ``` [Try it online!](https://tio.run/##K/rv4@fravs/rTQvuSQzP08jT6dCp1LH2zZPu1KzujwjMydVw1tVtULT29Zbu9I6WcNbv0JHw1s3T1O/UrMWrFnD2FzHVMdIkwvMsbDUMdaxgHIMDQx0DI10zOFcHUMdoJjmfwA "R – Try It Online") ### [R](https://www.r-project.org/), 54 bytes ``` function(n,x,y,K=n){while((K=K+y)%%x)0;c(K/x,(K-n)/y)} ``` [Try it online!](https://tio.run/##K/rv4@fravs/rTQvuSQzP08jT6dCp1LH2zZPs7o8IzMnVUPD29Zbu1JTVbVC08A6WcNbv0JHw1s3T1O/UrMWrFnD2FzHVMdIkwvMsbDUMdaxgHIMDQx0DI10zOFcHUMdoJjmfwA "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` (x#y)n=[(div(n+i*y)x,i)|i<-[1..],mod(n+i*y)x<1]!!0 ``` [Try it online!](https://tio.run/##Xc7BjoIwEAbge59ijCa2WlgKGjVSn8A3IBy6aVcnQkuAKCS@O7ZGL3ub@f6ZyVxVdzNVNU10mI/MyoJqvFO7xtXIBo7siXlUiDguee3013NRzmbJVCu0UjsCFLljefRXq4bq1jWQsrhrlKU/chktWb44XUx/RmsIVKYvLB/4WMrWKO2jh2t1B3gsFP/9h/5006Lt6ec5Sf0M4@99HkoC4Ycp28EWUohOcIAN2R8gg33oMq9EJAmIFHYBhA88gICgAULzAg "Haskell – Try It Online") The relevant function is `(#)`, which takes as input integers `x`, `y`, `n` and returns a pair `(a,b)`, meaning that A should give `a` notes and B should give `b` back. [Answer] # Java, ~~79~~ 63 bytes ``` (n,x,y)->{int a=n/x,b;for(;(b=++a*x-n)%y>0;);return a+" "+b/y;} ``` *Saved 16 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).* [Try it online!](https://tio.run/##hY7BboMwEETP5StWkSrZYSGQKEoqi/xBTxyrHgyByBQMsg0CIb6d2qHXKntZjfbNzFZ84EF1/1lF07XKQGV12BtRh3vmdX1WixzymmsNn1xImD2wI6QpVMnzAtK2Hgo1p0YJ@QDtFLFXkOggGLc1UbY8jX@B2nBj19CKOzQ2lmz@r2/g6qHp7L1tuVAmK5E44kSD2@ySeCIPI2asbBVhJEt8n@/HQNL36RYxylRheiWB@zvY@dlhYsvKnsVu0kmbognb3oSdrTO1JGW4vXy64BmPlDLb/D91/cATXl9RcRRhfMTLaw5jtLDj3HuLt6y/) [Answer] # [C (clang)](http://clang.llvm.org/), ~~60~~ 58 bytes Saved 2 bytes thanks to [G. Sliepen](https://codegolf.stackexchange.com/users/46301/g-sliepen)!!! ``` f(n,x,y,s){(n+=y)%x?f(n,x,y,s+1):printf("%d %d",n/x,s+1);} ``` [Try it online!](https://tio.run/##dVJ/T4MwEP1/n@JCsoSOWwbDZT9w@ofxUzhjSCmTOLsFiLYufHXxKHRjOkmuae@9e313lI/5Lpbbuk5diQo1FuzoSm@t2VDdn3JewFaHPJNl6jrDBIaJg3KiTD6qasrDe5xJt9nE@ZYj8Nc4H42awwcbHAdAXwOWoihf5NMzrOEYzhEWS4TA95ulii5ZqmXNEEKCpxS/GbplELRAmBuhHkWog@ClSKwQ3RSSWNCoBVeJnd4NQitpLzS90Cr4m8iJAw3L2ajH6UYtHyhmDkL/HDpdZbrPwQwlk4lQVOZH3fYWiuxL7FP3bJNNutSol4vA80wFg3aK1rUktW6aBn@OLmBlYXUV1hbWf@Dzb0ZoA8Z3QB1KBIWg2Zlqn4fPLtVNq735X3MgdJ/zvw04TWgF5uWxjSQzgqwI66UaVPU3T3fxtqjHnz8 "C (clang) – Try It Online") Uses the formula from [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)'s comment to [hyper-neutrino](https://codegolf.stackexchange.com/users/68942/hyper-neutrino)'s [Python answer](https://codegolf.stackexchange.com/a/225265/9481). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` ∞*.Δ²@²y-³Ö*}D²α³÷,¹÷, ``` [Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8Lb1zUw5tcji0qVL30ObD07RqXQ5tOrcRyNyuc2gnkPj/39CIy9DAgMscAA "05AB1E – Try It Online") A port of hyper-neutrino's [python answer](https://codegolf.stackexchange.com/a/225265). [Answer] # [Ruby](https://www.ruby-lang.org/), 38 bytes ``` ->n,x,y{[1.step.find{(n+=y)%x<1},n/x]} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp0KnsjraUK@4JLVALy0zL6VaI0/btlJTtcLGsFYnT78itvZ/gUJatLG5jqmOUex/AA "Ruby – Try It Online") ### How The trick is in `1.step.find`: we add y to n at least once, and count iterations until n is divisible by x. Outputs `[B,A]` [Answer] # [Lua](https://www.lua.org/), 75 bytes ``` load('n,x,y='.. .....' c=n repeat c=c+y until c%x==0 print(c/x,(c-n)/y)')() ``` [Try it online!](https://tio.run/##FcZLCsAgDADRq2RTjNT6OYCHkdSFIKmIgp4@bYe3mDqTSH3SjYrNMjsqa8H@KaDI0HPLaXxL54bJo1SgY8XoofXCA8ktg3SxdlsrjVpEgjcQPt6/ "Lua – Try It Online") ]
[Question] [ Seeing as there have been an awful lot of normal Fibonacci challenges, I decided that it might be interesting to calculate the [Reciprocal Fibonacci constant](http://en.wikipedia.org/wiki/Reciprocal_Fibonacci_constant) - namely, the sum of the reciprocals of the Fibonacci sequence. The challenge is to calculate the Reciprocal Fibonacci constant with the number of Fibonacci series to use digit given as input, i.e. an input of 10 means to calculate based on the reciprocals of the first 10 Fibonacci numbers. In the likely case of a tie, shortest code wins. The winner will be chosen in three weeks via standard code-golf rules. [Answer] ## Perl - 35 bytes ``` print!map$\-=1/($%+=$.=$%-$.),0..<> ``` Sample usage: ``` $ echo 10 | perl inv-fib-sum.pl 3.34170499581934 ``` --- ## Further Analysis It's interesting to note that the sum ![](https://chart.googleapis.com/chart?cht=tx&chl=f%3D%5Csum%5Climits_%7Bi%3D0%7D%5E%5Cinfty%7B%5Cfrac%7B1%7D%7BF_i%7D%7D%3D%5Cfrac%7B1%7D%7B1%7D%2B%5Cfrac%7B1%7D%7B1%7D%2B%5Cfrac%7B1%7D%7B2%7D%2B%5Cfrac%7B1%7D%7B3%7D%2B%5Cfrac%7B1%7D%7B5%7D%2B%5Cfrac%7B1%7D%7B8%7D%2B%5Cfrac%7B1%7D%7B13%7D%2B%5Cfrac%7B1%7D%7B21%7D%2B%5Cfrac%7B1%7D%7B34%7D%2B%5Cdots) is convergent. Supposing we wanted to calculate a few thousand digits or so, the naïve approach is almost sufficient. The convergence is quite slow at first, but speeds up rapidly, so that *1000* digits only takes about *4800* terms. A sample Python implementation might be: ``` a=[1,1] for i in range(4800):a=[a[0]+a[1]]+a z=10**1000 print sum(map(lambda i:z/i,a)) ``` which after a second or so outputs: ``` 33598856662431775531720113029189271796889051337319684864955538153251303189966833836154162164567900872970453429288539133041367890171008836795913517330771190785803335503325077531875998504871797778970060395645092153758927752656733540240331694417992939346109926262579646476518686594497102165589843608814726932495910794738736733785233268774997627277579468536769185419814676687429987673820969139012177220244052081510942649349513745416672789553444707777758478025963407690748474155579104200675015203410705335285129792635242062267537568055761955669720848843854407983324292851368070827522662579751188646464096737461572387236295562053612203024635409252678424224347036310363201466298040249015578724456176000319551987905969942029178866949174808096746523682654086938399069873211752166957063859411814553647364268782462926166650100098903804823359519893146150108288726392887669917149304053057745574321561167298985617729731395370735291966884327898022165047585028091806291002444277017460241040417786069190065037142832933 ``` (The last four digits don't quite converge, but we'll ignore that for now.) Let's try to speed up the convergence a bit. A standard trick is to use [Euler's Transform](http://en.wikipedia.org/wiki/Series_acceleration#Euler.27s_transform). After expansion and simplification, this produces a nicer result: ![](https://chart.googleapis.com/chart?cht=tx&chl=f%3D3%2B%5Csum%5Climits_%7Bi%3D0%7D%5E%5Cinfty%7B%28-1%29%5Ei%5Cfrac%7B1%7D%7BF_i%5Ccdot+F_%7Bi%2B1%7D%5Ccdot+F_%7Bi%2B2%7D%7D%7D%3D%5Cfrac%7B1%7D%7B1%5Ccdot+1%5Ccdot+2%7D-%5Cfrac%7B1%7D%7B1%5Ccdot+2%5Ccdot+3%7D%2B%5Cfrac%7B1%7D%7B2%5Ccdot+3%5Ccdot+5%7D-%5Cfrac%7B1%7D%7B3%5Ccdot+5%5Ccdot+8%7D%2B%5Cdots) It should be fairly apparent why this converges more quickly; each term has 3 terms in the denominator rather than just one. Calculating *1000* digits takes only *1600* (one third as many) terms: ``` a=[1,1] for i in range(1601):a=[a[0]+a[1]]+a z=10**1000 print sum(map(lambda i:(-1)**i*z/(a[i]*a[i+1]*a[i+2]),range(1601))) ``` Output: ``` 3598856662431775531720113029189271796889051337319684864955538153251303189966833836154162164567900872970453429288539133041367890171008836795913517330771190785803335503325077531875998504871797778970060395645092153758927752656733540240331694417992939346109926262579646476518686594497102165589843608814726932495910794738736733785233268774997627277579468536769185419814676687429987673820969139012177220244052081510942649349513745416672789553444707777758478025963407690748474155579104200675015203410705335285129792635242062267537568055761955669720848843854407983324292851368070827522662579751188646464096737461572387236295562053612203024635409252678424224347036310363201466298040249015578724456176000319551987905969942029178866949174808096746523682654086938399069873211752166957063859411814553647364268782462926166650100098903804823359519893146150108288726392887669917149304053057745574321561167298985617729731395370735291966884327898022165047585028091806291002444277017460241040417786069190065037142834500 ``` (Here again, the last 4 digits don't converge.) We're not quite done yet. If we combine adjacent terms, we end up with the following: ![](https://chart.googleapis.com/chart?cht=tx&chl=f%3D3%2B%5Cfrac%7B2%7D%7B1%5Ccdot+2%5Ccdot+3%7D%2B%5Cfrac%7B2%7D%7B2%5Ccdot+5%5Ccdot+8%7D%2B%5Cfrac%7B2%7D%7B5%5Ccdot+13%5Ccdot+21%7D%2B%5Cfrac%7B2%7D%7B13%5Ccdot+34%5Ccdot+55%7D%2B%5Cfrac%7B2%7D%7B34%5Ccdot+89%5Ccdot+144%7D%2B%5Cdots%2B%5Cfrac%7B2%7D%7BF_n%5Ccdot+F_%7Bn%2B2%7D%5Ccdot+F_%7Bn%2B3%7D%7D%2B%5Cdots) Factoring out each term from the remainder of the summation gives the nested expression: ![](https://chart.googleapis.com/chart?cht=tx&chl=f%3D3%2B%5Cfrac%7B2%7D%7B2%5Ccdot+3%7D%281%2B%5Cfrac%7B3%7D%7B5%5Ccdot+8%7D%281%2B%5Cfrac%7B2%5Ccdot+8%7D%7B13%5Ccdot+21%7D%281%2B%5Cfrac%7B5%5Ccdot+21%7D%7B34%5Ccdot+55%7D%281%2B%5Cfrac%7B13%5Ccdot+55%7D%7B89%5Ccdot+144%7D%28%5Cdots%2B%5Cfrac%7BF_%7B2n%7DF_%7B2n%2B3%7D%7D%7BF_%7B2n%2B4%7DF_%7B2n%2B5%7D%7D%28%5Cdots%29%29%29%29%29%29) Now we're getting somewhere. Notice that the numerators of follow [OEIS A206351](http://oeis.org/A206351) (with the exception of the first term, which is doubled): ![](https://chart.googleapis.com/chart?cht=tx&chl=b%3D%5B2%2C%5C+3%2C%5C+16%2C%5C+105%2C%5C+715%2C%5C+4896%2C%5C+%5Cldots%5D) and the denominators follow [OEIS A081016](http://oeis.org/A081016) (shifted by one term): ![](https://chart.googleapis.com/chart?cht=tx&chl=c%3D%5B6%2C%5C+40%2C%5C+273%2C%5C+1870%2C%5C+12816%2C%5C+%5Cldots%5D) Each of these have very simple recurrence relations, namely: ![](https://chart.googleapis.com/chart?cht=tx&chl=b_n%3D7b_%7Bn-1%7D-b_%7Bn-2%7D-4%5Cqquad+where%5Cqquad+b_0%3D1%2C%5C+b_1%3D3) and ![](https://chart.googleapis.com/chart?cht=tx&chl=c_n%3D7c_%7Bn-1%7D-c_%7Bn-2%7D-1%5Cqquad+where%5Cqquad+c_0%3D1%2C%5C+c_1%3D6) respectively. Putting it all together, we find that we need only *800* iterations for *1000* digits: ``` b,c=[16,3,1],[273,40,3] for i in range(800):b,c=[7*b[0]-b[1]-4]+b,[7*c[0]-c[1]-1]+c s=z=10**1000 for x,y in zip(b,c):s=(z+s)*x/y print s ``` which outputs: ``` 3598856662431775531720113029189271796889051337319684864955538153251303189966833836154162164567900872970453429288539133041367890171008836795913517330771190785803335503325077531875998504871797778970060395645092153758927752656733540240331694417992939346109926262579646476518686594497102165589843608814726932495910794738736733785233268774997627277579468536769185419814676687429987673820969139012177220244052081510942649349513745416672789553444707777758478025963407690748474155579104200675015203410705335285129792635242062267537568055761955669720848843854407983324292851368070827522662579751188646464096737461572387236295562053612203024635409252678424224347036310363201466298040249015578724456176000319551987905969942029178866949174808096746523682654086938399069873211752166957063859411814553647364268782462926166650100098903804823359519893146150108288726392887669917149304053057745574321561167298985617729731395370735291966884327898022165047585028091806291002444277017460241040417786069190065037142835294 ``` (Here, finally, the last 4 digits converge correctly.) But that's still not quite everything. If we observe the intermediate values for *s*, we find that it converges to a different value entirely before converging on the actual convergence point. The reason for this is the following: ![](https://chart.googleapis.com/chart?cht=tx&chl=%5Clim_%7Bn%5Cto%5Cinfty%7D%5Cfrac%7BF_%7B2n%7DF_%7B2n%2B3%7D%7D%7BF_%7B2n%2B4%7DF_%7B2n%2B5%7D%7D%3D%5Cfrac%7B1%7D%7B%5Cvarphi%5E6%7D) Solving for a stable *s*, we find that: ![](https://chart.googleapis.com/chart?cht=tx&chl=s%3D%5Cfrac%7B1%7D%7B4%7D%28%5Csqrt%7B5%7D-2%29) Because this is a simple root, we can use [Newton's Method](http://mathworld.wolfram.com/NewtonsMethod.html) to get us most of the way there, and then jump in at a much later point in the iteration. Only about *400* digits of precision are necessary (as the *b* and *c* values aren't any larger than that anyway), which can be achieved with just *7* iterations, while saving *320* iterations of the main loop: ``` b,c=[16,3,1],[273,40,3] for i in range(480):b,c=[7*b[0]-b[1]-4]+b,[7*c[0]-c[1]-1]+c z=10**1000;s=z/17 for i in range(7):s-=(s*s+s*z-z*z/16)/(2*s+z) for x,y in zip(b,c):s=(z+s)*x/y print s ``` Output is identical to the previous, runtime is about 0.02s on my system using PyPy v2.1. Even though it needs one tenth the number of iterations as the original, it's significantly faster than 10x due to multiplying and dividing by much smaller terms. I don't think much more can be tweaked out of it, although I'd be happy to be shown wrong. [Answer] # Mathematica (32 characters without built-in Fibonacci) ``` Tr[1/⌈(.5+√5/2)^Range@#/√5-.5⌉]& ``` ![enter image description here](https://i.stack.imgur.com/yWv3U.png) Here I used the rounding formula for Fibonacci numbers ![enter image description here](https://i.stack.imgur.com/lHbH6.png) where `φ` is the golden ratio. [Answer] **K (19)** (or 17 if you skip defining it as a function) ``` f:{+/*+%x(|+\)\|!2} ``` Tested on Kona. Basically, it generates the first x values of the fibonacci sequence into an array (without using builtins), divides 1 by each value of the entire array, transposes and sums it up. (thanks to @tmartin for the better sum method) [Answer] ## Kona (25 21) ``` {+/%(x(|+\)\1 1)[;1]} ``` Probably could be made smaller by experts, but I am still learning the language. ``` f 10 3.341705 f 3 2.8333 f 25 3.359872 f 400 3.359886 ``` The last one didn't actually take any more time than the others. [Answer] # Mathematica ~~30~~ 24 With 6 characters saved thanks to ybeltukov. ``` Tr[1/Fibonacci@Range@#]& ``` --- Before adding the terms: ``` 1/Fibonacci@Range@#&[20] ``` ![image1](https://i.stack.imgur.com/4hwt3.png) --- With addition included: ``` Tr[1/Fibonacci@Range@#]&[20] ``` ![image2](https://i.stack.imgur.com/XWsgt.png) [Answer] # APL, 21 chars/bytes\* ``` {+/÷{↑+\∘⌽⍣⍵⊢0 1}¨⍳⍵} ``` **Example** ``` {+/÷{↑+\∘⌽⍣⍵⊢0 1}¨⍳⍵} 10 3.330469041 ⍪{+/÷{↑+\∘⌽⍣⍵⊢0 1}¨⍳⍵}¨⍳10 1 2 2.5 2.833333333 3.033333333 3.158333333 3.23525641 3.282875458 3.312287223 3.330469041 {+/÷{↑+\∘⌽⍣⍵⊢0 1}¨⍳⍵} 100 3.359885666 ``` ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] # Javascript, 33 *Input:* `n = 10` ``` s=f=t=1;for(;n--;)t+=1/(s+=f=s-f) ``` Based in my first post in Perl, here is the result directly from the *Google Chrome Console*. ![enter image description here](https://i.stack.imgur.com/OOZIq.png) [Answer] # K, 22 ... ``` {+/%x#x{x,+/-2#x}/1 1} ``` [Answer] ## [GTB](http://timtechsoftware.com/?page_id=1309 "GTB"), 35 *Runs on a TI-84 calculator* ``` 1→Y:0→X`N4;N,1,N~1/X:Y→Z:X+Y→Y:Z→X& ``` * Store `1` in `Y` and `0` in `X` * Take `N` as input * Initialize a `For` loop * Display `X` * Store `Y` in `Z` and `X+Y` in `Y` * Store `Z` in `X` * End the `For` loop [Answer] # BC - 116 ``` define f(n){if(n < 2){return n;}else{return f(n-1)+f(n-2);}} define r(n){for(i=1;i<n;++i){m=m+(1/f(i));};return m;} ``` call r(n) with n to solve. The precision can be set arbitrarily, so this is the most accurate solution. [Answer] # PERL, ~~62~~ 43 ``` $s=$t=1;$t+=1/($a=$f+$s),$f=$s,$s=$a,for 0..<>;say $t ``` **Edit:** After some more time looking at my code I was able to save 19 chars: ``` $s=1;$t+=1/($s+=$f=$s-$f)for 0..<>;say $t+2 ``` > > input: 10 > > > 3.35294128575734 > > > [Answer] ## Forth, 64 ``` : r 1 1 rot 1e 0 do 2dup - nip tuck + dup s>f 1/f f+ swap loop ; ``` usage: ``` 10 r f. 3.34170499581934 ok 100 r f. 3.35988566624318 ok 1000 r f. 3.35988566624318 ok ``` [Answer] ## Python (~~55~~ 51) ``` i,r=p=1,1 while i<n+1:r+=1./p[-1];p=p[1],sum(p);i+=1 r ``` ``` i,r,a,b=[1]*4 while i<n+1:r+=1./b;a,b=b,b+a;i+=1 r ``` In interactive mode: ``` n=10 3.341704995819338 n=100 ``` ``` 3.3598856429940778 ``` ``` 3.359885666243178 n=400 ``` ``` 3.3598855578800064 ``` ``` 3.359885666243178 ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 27 bytes ``` {sum 1 X/(1,&[+]...*)[^$_]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFfBUCFCX8NQRy1aO1ZPT09LMzpOJT629n9xYqVCmoahgYGBpvV/AA "Perl 6 – Try It Online") Alternatively ``` {sum 1 xx$_ Z/(1,&[+]...*)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv7q4NFfBUKGiQiVeIUpfw1BHLVo7Vk9PT0uz9n9xYqVCmoahgYGBpvV/AA "Perl 6 – Try It Online") [Answer] # Japt `-mx`, 6 bytes ``` 1/MgUÄ ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=MS9NZ1XE&input=MTAwMAotbXg=) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 66 bytes ``` a=>{double r=1,x=1,y=1,i=0;for(;++i<a;y+=x,x=y-x)r+=1/y;return r;} ``` [Try it online!](https://tio.run/##NY3LCsIwFETX9ivuMqX1Ud0IaQQRBEE3KriO6a0EagI3qTSUfnsNlA4chsMsRrmlsoRj67T5wCM4j18OqpHOwRH6xHnptYJza1RZ2fbdYA5TH6AGMUpx6CcHEkXeRUJEiw2vLTGeZbqUPGSii1tYdillolgHTuhbMkB8GPl88rO6gpvUhqV9sjhZ42yDqxdpj6xm0X9IfvW0F@N3Wzbvd5TVVRtkaQxPhmHc/wE "C# (.NET Core) – Try It Online") Can't use floats because of imprecision. Example where input = 8: * double: 3.28287545787546 (rounds to 3.282875) * float: 3.282876 (off by 0.000001) Ungolfed: ``` a => { double r = 1, // initialize r (sum of reciprocals) - start at 1 to save one byte in for loop x = 1, y = 1, // initialize x (2nd largest Fibonacci) and y (largest Fibonacci) i = 0; // initialize i (loop counter) for(; ++i < a; y += x, x = y - x) // from 1 to a, while incrementing the Fibonacci numbers r += 1 / y; // increment the reciprocal Fibonacci return r; // return the reciprocal Fibonacci } ``` [Answer] **RPL (HP 49G/G+/50g), 50 bytes** ``` « 0. 1. DUP2 5. ROLL START SWAP OVER + ROT OVER INV + UNROT NEXT DROP2 » ``` Examples: 10 -> 3.33046904076 11 -> 3.34170499582 30 -> 3.35988372158 55 -> 3.35988566622 In theory, the sum of the first 55 digits would give 12 correct digits. The last digit should be '4' instead of '2'. This should be fixed by adding up the terms backwards, but the code would be slightly longer. If the constant were to be computed to 1000 decimal places using the definition the sum should be carried out to at least the first 4790 terms, which would take too much time on the HP 50g, if possible at all. For this task a more efficient method is required, like the one used in the following RPL program (464 bytes, checksum # 207Eh) whose argument is the desired number of decimal places: ``` %%HP: T(3)A(R)F(.); \<< PUSH RAD -105 CF -3 CF R\->I DUP 1 + 2 INV SWAP 100 LN * 5 LN + OVER ASINH / \v/ * CEIL DUP 2 MOD + DUP 0 ROT [[ 1 1 ] [ 1 0 ]] SWAP DUP2 ^ 3 GETI UNROT GET 4 ROLLD 4 ROLLD DUP + ^ 1 GETI UNROT GET 1 + 0 1 8 ROLL 2 / START PICK3 + DUP PICK3 * NEG 6 PICK SQ + / 4 PICK SQ * EXPAND ROT PICK3 - ROT OVER - ROT 6 ROLL 6 ROLL 6 ROLL + LASTARG * LASTARG 5 ROLLD 5 ROLLD / + ROT PICK3 - ROT OVER - 6 ROLL 6 ROLL 6 ROLL NEXT ROT + INV 5 ROLL + EXPAND 4 ROLLD 3 DROPN FXND PICK3 ALOG OVER - PICK3 * SWAP IQUOT + \->STR DUP HEAD -51 FC? { "." } { "," } IFTE + SWAP TAIL + 1 ROT 2 + SUB POP \>> 'RFC' STO ``` 1000 RFC --> 3.3598856662431775531720113029189271796889051337319684864955538153251303189966833836154162164567900872970453429288539133041367890171008836795913517330771190785803335503325077531875998504871797778970060395645092153758927752656733540240331694417992939346109926262579646476518686594497102165589843608814726932495910794738736733785233268774997627277579468536769185419814676687429987673820969139012177220244052081510942649349513745416672789553444707777758478025963407690748474155579104200675015203410705335285129792635242062267537568055761955669720848843854407983324292851368070827522662579751188646464096737461572387236295562053612203024635409252678424224347036310363201466298040249015578724456176000319551987905969942029178866949174808096746523682654086938399069873211752166957063859411814553647364268782462926166650100098903804823359519893146150108288726392887669917149304053057745574321561167298985617729731395370735291966884327898022165047585028091806291002444277017460241040417786069190065037142835294 (22 min 23 sec, on the real HP 50g) --- For one thousand digits the first 50 terms of the series plus another 50 terms of a continued fraction are evaluated, two at a time in only 25 iterations (48 terms of each would have sufficed, though). An equivalent DECIMAL BASIC program takes just 10 milliseconds on my computer (Intel(R) Core(TM) Duo CPU E4700 @ 2.6 GHz). [Answer] # JAEL, ~~9~~ 7 bytes Changing the diacritics from one character to another gave me 1 byte Still working on SBCS encoding. ``` #`&@uȦ ``` ### Explanation (generated automatically): ``` ./jael -u explain '#`&@uȦ' ORIGINAL CODE: #`&@uȦ EXPANDING EXPLANATION: Ȧ => .a! EXPANDED CODE: #`&@u.a! COMPLETED CODE: #`&@u.a!, # , repeat (p1) times: ` stack 1 & push number of iterations of this loop @ push nth fibonacci number u push p2 / p1 . push the value under the tape head a push p1 + p2 ! write p1 to the tapehead ␄ print machine state ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` RÆḞİS ``` [Try it online!](https://tio.run/##y0rNyan8/z/ocNvDHfOObAj@//@/KQA "Jelly – Try It Online") ### How it works ``` RÆḞİS Main link (monad). Input: integer R Range ÆḞ nth Fibonacci number İ Reciprocal S Sum ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), ~~13~~ 11 bytes ``` ;/b$ =1:Z+Y ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/31o/SYXL1tAqSjvy/39DAwMDAA "cQuents – Try It Online") ## Explanation ``` ; The sum of the first n terms of the sequence / which are 1 divided by b$ the nth term in the sequence on the second line =1:Z+Y Fibonacci with starting indexes 1,1 ``` ]
[Question] [ Given the input `tilesX` and `tilesY` create a method that would make a rectangular ring from the tiles. The function must order the tiles in a ring like this: [![enter image description here](https://i.stack.imgur.com/Be2zp.jpg)](https://i.stack.imgur.com/Be2zp.jpg) * `tilesX` and `tilesY` are always positive integer values, cannot be 0 * `tilesX` and `tilesY` are not always equal, expect values like: `2x5`, `6x3` etc. * Checking for invalid input is not necessary * You can use any way to display the tiles, including 2d arrays, ASCII art or printed text. * There's no strict way how the input is passed as long as it's two integers. * Cannot be a line, drawing a rectangle size of `tilesX` and `tilesY` pixels is not valid * The shortest code wins [Answer] # Dyalog APL, 8 bytes ``` ×/¨1<⊂|⍳ ``` This monadic function train takes height and width as right arguments and returns a 2D array of **0**'s (border) and **1**'s (interior). Test it on [TryAPL](http://tryapl.org/?a=f%20%u2190%20%D7/%A81%3C%u2282%7C%u2373%20%u22C4%20f%207%2013&run). ### How it works ``` ×/¨1<⊂|⍳ Right argument: h w ⍳ Generate all index pairs (1-based) of a h×w array. ⊂ Enclose (h w), so it depth matches the one of the index array. | For each pair (i j) compute the remainders of the division by (h w). 1< Compare all remainders with 1. ×/¨ Reduce each pair of Booleans by multiplication. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 2$l3XyZ+3= ``` Input arguments are height and width as integers. The output is a matrix of size `height x width` where the boundary tiles are 0 and the inner values are 1. [**Try it Online!**](http://matl.tryitonline.net/#code=MiRsM1h5WiszPQ&input=NQo2) **Explanation** Same logic as my [other answer](https://codegolf.stackexchange.com/a/77990/51939) with fewer bytes. ``` % Grab two input parameters implicitly 2$l % Create a matrix of ones that has the dimensions specified as inputs 3 % Number literal 3 Xy % Create a 3x3 identity matrix Z+ % Perform 2D convolution (preserving size) 3= % Create a logical matrix where values == 3 are 1 and 0 otherwise (boundary) % Implicitly display output. ``` [Answer] # MATLAB, ~~32~~ 31 bytes ``` @(x)conv2(ones(x),eye(3),'s')>2 ``` This creates an anonymous function which can then be run as `ans([4 5])` within the workspace. Input is `[height, width]` and output is a matrix with 1 in the center and 0 for the boundary. The way that this works is a matrix of ones the size of the input is created. It is then convolved with a 3 x 3 identify matrix with ones on the diagonal. We use the `same` input to `conv2` (shortened to `'s'` here) to keep the result the same size as the input. We then want to convert the output to a binary value with 0 around the boundary and 1 inside. We use the inequality `>2` because all edge pixels will have a result < 3 and all non-boundary elements will have a result equal to 3. For graphical output: ``` @(x)imagesc(conv2(ones(x),eye(3),'s')>8) ans([6,9]) ``` [![enter image description here](https://i.stack.imgur.com/wbgzk.png)](https://i.stack.imgur.com/wbgzk.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 2$lO6Lt4$( ``` This outputs an array containing zeros and ones. [**Try it online!**](http://matl.tryitonline.net/#code=MiRsTzZMdDQkKA&input=NQo3) ``` 2$l % Implicit inputs M, N. Generate M×N array of ones O % Push number 0 6Lt % Push [2 -1] twice, corresponding to index "2:end-1" 4$( % Fill the center of the array with value 0. Implicit display ``` --- For graphical output, add `1YG` at the end to display the array as an image (**13 bytes**) : ``` 2$Ol6Lt4$(1YG ``` Try it at [**MATL Online!**](http://matl.io/?code=2%24Ol6Lt4%24%281YG&inputs=5%0A7&version=16.1.0) For example, ``` >> matl 2$Ol6Lt4$(1YG > 5 > 7 ``` produces [![enter image description here](https://i.stack.imgur.com/MqOzS.png)](https://i.stack.imgur.com/MqOzS.png) [Answer] ## HTML/JS/CSS, ~~198~~ 194 bytes Graphical output version. The byte count doesn't include `f=` nor the three `<input>` elements which are used for demonstration purposes only. Saved 3 bytes thanks to @IsmaelMiguel. ``` f=(n,m)=>{with(d.style)width=n*25+'px',height=m*25+'px'} ``` ``` <input id=w placeholder=width><input id=h placeholder=height><input type=button value=Go! onclick=f(w.value,h.value)> <div id=d style="border-image:radial-gradient(#fff 0,#fff 0)0 fill/25px;background:radial-gradient(#000 0,#000 8px,#fff 9px)0 0/25px 25px"> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` p%€,>1P€G ``` Returns a grid of **0**'s (border) and **1**'s (interior). [Try it online!](http://jelly.tryitonline.net/#code=cCXigqwsPjFQ4oKsc0c&input=&args=NQ+Ng) ### How it works ``` p%€,>1P€sG Main link. Arguments: h (height), w (width) p Cartesian product; return all pairs in [1, ..., h] × [1, ..., w]. , Yield the pair [h, w]. %€ For each pair [i, j] in the product, compute [i % h, j % w]. >1 Compare all resulting moduli with 1. P€ Compute the product of each pair of Booleans. s Split the resulting flat list into rows of length w. G Display the results in a 2D grid. ``` [Answer] # Julia, ~~46~~ 34 bytes ``` f(n,m)=[n>i>1<j<m for i=1:n,j=1:m] ``` This is a function that accepts two integers and returns a 2-dimensional boolean array. We construct an *n* × *m* matrix using an array comprehension with a double `for` loop. For each index from 1 to *n* and 1 to *m*, i.e. each element of the matrix, we set the value to `true` if *n* > *i* > 1 and 1 < *j* < *m*. This is true everywhere but the boundaries, so the resulting array will have `true`s in the middle and `false`s around the border. Examples: ``` julia> f(n,m)=[n>i>1<j<m for i=1:n,j=1:m] f (generic function with 1 method) julia> f(4,4) 4x4 Array{Bool,2}: false false false false false true true false false true true false false false false false julia> f(1,1) 1x1 Array{Bool,2}: false julia> f(2,5) 2x5 Array{Bool,2}: false false false false false false false false false false ``` Saved 12 bytes thanks to Dennis! [Answer] # [J](http://jsoftware.com/), 12 bytes ``` */&(<:*@|i.) ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/7X01TRsrLQcajL1NP9rcinpKain2VqpK@go1FoppBVzcaUmZ@QrmCukKVhCmOrqENoUKGSKKmQEFDL@DwA "J – Try It Online") Coming back to this, almost 3 years later. An idea inspired by Dennis answer, though not a translation. * `i.` Create 0 based index lists from each arg * `<: |` remainders when divided by the arg minus 1 * `*@` signup the results. Now, eg, if an arg was 4, we'll have a list like `0 1 1 0` * `*/` Create a multiplication table of those lists. ## Original Answer, 16 bytes ``` 0(<2#<<0 _1)}$&1 ``` Use shape `$` to create a rectangle of all ones the size of the inputs, and then use the complementary form of Amend `}` to turn the interior to zeros. [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/w00bIyUbWwMFOINNWtV1Az/a3Ip6Smop9laqSvoKNRaKaQVc3GlJmfkK6QpmCtYQpjq6jAhUwXT/wA "J – Try It Online") [Answer] ## CJam, 20 bytes ``` l~S*a*{3a.f|W%z}4*N* ``` Input should be in the form `height width`, output is an ASCII grid using spaces for the centre and `#` for the boundary. [Test it here.](http://cjam.aditsu.net/#code=l~S*a*%7B3a.f%7CW%25z%7D4*N*&input=4%205) ### Explanation ``` l~ e# Read and evaluate input, dumping h and w on the stack. S* e# Create a string of w spaces. a* e# Create an array of h copies of that string. { e# Repeat this block 4 times... 3a.f| e# For each character in the first row, take its bitwise OR with 3, turning e# spaces into # and leaving # unchanged. W%z e# Reverse and transpose the grid, rotating it by 90 degrees. }4* N* e# Join the lines of the result with linefeeds. ``` [Answer] ## Pyke, ~~16~~ 15 bytes ``` jQ]Uajt%!RQt%!| ``` [Try it here!](http://pyke.catbus.co.uk/?code=jQ%5DUajt%25%21RQt%25%21%7C&input=5%0A4) Explanation: ``` - Q = eval_input() j - j = eval_input() jQ] - [Q,j] U - create a 3d array sized Q by j with coords a - for each coord (2d for) jt%! - not (coord_1 % j-1) | - ^ or V Qt%! - not (coord_2 % Q-1) ``` For prettified output, [use this code](http://pyke.catbus.co.uk/?code=jQ%5DUajt%25!RQt%25!%7C%29P&input=3%0A4). Or 13 bytes with a zeroed out mask round the edge (middle chars non-zero) ``` jQ]Uajt%RQt%& ``` [Try it here!](http://pyke.catbus.co.uk/?code=jQ%5DUajt%25RQt%25%26&input=5%0A5) [Answer] # JavaScript (ES6), 80 ~~82 85~~ **Edit** 3 bytes saved thx @Neil **Edit** 2 bytes saved using `reduce` for once Anonymous function returning a multi line string ``` (w,h)=>[...Array(h)].reduce(o=>o+(w>1?'O'+' O'[!--h|!o].repeat(w-2):'')+`O `,'') ``` **Test** ``` f=(w,h)=>[...Array(h)].reduce(o=>o+(w>1?'O'+' O'[!--h|!o].repeat(w-2):'')+`O `,'') function test(){ var [w,h] = I.value.match(/\d+/g) w=+w,h=+h // convert to numeric O.textContent=f(w,h) } test() ``` ``` <input value='5 4' id=I><button onclick='test()'>Test</button><pre id=O></pre> ``` [Answer] # Ruby, 63 bytes Anonymous function, prints to STDOUT. Border is `#`. ``` ->x,y{h=?#;puts t=h*x,y>1?[[h+(x<2?'':' '*(x-2)+h)]*(y-2),t]:p} ``` [Answer] # Perl 5, 45 + 1 (`-p`) = 46 bytes ``` $_=join$/,(1x$_)x<>;1while s/ .+\K1(?=.+ )/ / ``` following 45 bytes doesn't handle tileY=1 ``` $_=1x<>.$/;say$_.s/(?!^.|.$)./ /gr x(<>-2).$_ ``` [Try it online](https://tio.run/##K0gtyjH9/18l3jYrPzNPRV9Hw7BCJV6zwsbO2rA8IzMnVaFYn0tPO8bbUMPeVk@bS1NfQf//f1Muk3/5BSWZ@XnF/3ULAA) [Answer] ## JavaScript (ES6), 97 bytes ``` (n,m)=>Array(n).fill(' '.repeat(m).replace(/^ | $/g,0)).join` `.replace(/^.+|.+$/g,'0'.repeat(m)) ``` Creates a ring of `0`s. Probably a terrible approach but I wanted to avoid edge cases. [Answer] # JavaScript (ES6), 77 bytes ``` h=>w=>[...Array(i=h)].map(_=>(a=Array(w).fill(h-i--&&i?0:1),a[0]=a[w-1]=1,a)) ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~45~~ 43 bytes ``` \d+ $* S_`1(?=.* (1+))|. T`1`#`^.+|.+$|.?¶. ``` Input should be in the form `height width`, output is an ASCII grid using `1` for the centre and `#` for the boundary. [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqClNfYDEoPz0uKiAoMSspKXwuClRgMWAjYF4uK3wuKyR8Lj_Cti4&input=NCA1) ### Explanation ``` \d+ $* ``` Convert each number `N` to a string of `N` ones (i.e. convert the input to unary). ``` S_`1(?=.* (1+))|. ``` Match each `1` in `height` and replace it with `width`, while also matching everything else and removing it. We do this by abusing a split stage. This creates a `w x h` grid. ``` T`1`#`^.+|.+$|.?¶. ``` Finally we replace every `1` with a `#` that is either found in the first line, the last line or at the beginning or end of a line. [Answer] ## [Actually](https://github.com/Mego/Seriously/tree/v2), 23 bytes ``` ;'#*;))¬' *'#;)@+(+nXX( ``` [Try it online!](http://actually.tryitonline.net/#code=OycjKjspKcKsJyAqJyM7KUArKCtuWFgo&input=Mwo0) This approach is very similar to my approach in [this related challenge](https://codegolf.stackexchange.com/a/73646/45941). Explanation: ``` ;'#*;))¬' *'#;)@+(+nXX( (implicit) push all input to stack ;'#* push a string containing X #s ;)) dupe, and push both to bottom of stack ¬' * push a string containing (X-2) spaces '#;)@+(+ add a # to the front and the back of the string nXX make (Y-2) copies ( bring one of the "#"*X strings back to the top (implicit) pop and print each stack item, separated by newlines ``` [Answer] # QBasic, 69 bytes ``` INPUT x,y FOR i=1TO y FOR j=1TO x ?i MOD y<2OR j MOD x<2; NEXT ? NEXT ``` Takes dimensions as `width,height`. The boolean value from the is-it-on-the-border test is simply printed: `-1` for true and `0` for false. A sample run looks like: ``` ? 5,3 -1 -1 -1 -1 -1 -1 0 0 0 -1 -1 -1 -1 -1 -1 ``` **Bonus: Graphical version, 88 bytes** ``` INPUT x,y SCREEN 9 FOR i=1TO y FOR j=1TO x PSET(j*3,i*3),i MOD y<2OR j MOD x<2 NEXT NEXT ``` I believe this counts as "not a line." When the `MOD` expression is false (0), `PSET` plots a black pixel; when it's true (-1), `PSET` apparently plots a white pixel. Here's `17,31`, shown at 2x size: [![Graphical rectangle](https://i.stack.imgur.com/SQqsi.png)](https://i.stack.imgur.com/SQqsi.png) [Answer] # TSQL, ~~107~~ ~~105~~ 97 bytes ``` DECLARE @ INT=3,@y INT=5 PRINT REPLICATE(1,@)+ISNULL(' '+REPLICATE('1'+ISNULL(SPACE(@-2),'')+'1 ',@y-2)+REPLICATE(1,@),'') ``` > > 1. generating first line > 2. adding hollow lines + line breaks > 3. adding last line(when needed) > > > [Answer] # [Perl 5](https://www.perl.org/), 76 + 1 (`-a`) = 77 bytes ``` print(1x($a=$F[0]),$/,((1,$"x($a-2),1 x($a>1),$/)x($F[1]-2),1x$a)x($F[1]>1)) ``` [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRMOwQkMl0VbFLdogVlNHRV9HQ8NQR0UJJKhrpKljqABi2RmCpDSBTLdow1iweIVKIowPlNX8/99UwfhffkFJZn5e8X9dX1M9A0OD/7qJAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` «¾6ÅÈΛ ``` Input as a pair of integers, where the first is the height and the second is the width. Outputs with `0` as characters. [Try it online.](https://tio.run/##yy9OTMpM/f//0OpD@8wOtx7uODf7//9oYx3TWAA) **Explanation:** ``` Λ # Use the Canvas builtin with the following three options: # (after which the resulting shape is output implicitly immediately afterwards) « # - line lengths: use the (implicit) input-integer, merged with itself: [h,w,h,w] 6ÅÈ # - the directions: push a list of even integers <= 6: [0,2,4,6] ¾ # - what to draw: push the counter variable, which is 0 by default ``` The Canvas builtin uses three arguments to draw a shape: * Character/string to draw: character `0`, which could alternatively be `1`/`2` by replacing the `¾` with `X`/`Y` respectively. * Length of the lines we'll draw: the input-list twice. Since there is more than one input-length, these are leading for the Canvas builtin, so we'll need the additional merge `«` at the start, otherwise it would only draw the top and left borders, instead of the entire box. * The direction to draw in: `[0,2,4,6]`. The digits in the range \$[0,7]\$ each represent a certain direction: ``` 7 0 1 ↖ ↑ ↗ 6 ← X → 2 ↙ ↓ ↘ 5 4 3 ``` So the `[0,2,4,6]` in this case translate to the directions \$[↑,→,↓,←]\$. Here a step-by-step explanation of the output (we'll use input-lengths `[3,5]` as example here): Step 1: Draw 3 `0` characters in direction `0↑`: ``` 0 0 0 ``` Step 2: Draw 5-1 `0` characters in direction `2→`: ``` 00000 0 0 ``` Step 3: Draw 3-1 `0` characters in direction `4↓`: ``` 00000 0 0 0 0 ``` Step 4: Draw 5-1 `0` characters in direction `6←`: ``` 00000 0 0 00000 ``` [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) [Answer] # [Unicorn](https://www.theedkins.co.uk/jo/games/unicorn/unicorn.htm), ~~26~~ 23 bytes ``` P3G$PG@PS@S$L2B$T1B@T1N ``` Because who doesn't like unicorns?! Explanation ("list program" output): ``` P3 Paint current square with 3 G$P Get: sets $ from input P G@P Get: sets @ from input P S@ Subtract 1 from @ S$ Subtract 1 from $ L2 ~Loop 2 times B$ ~Brush $ more square T1 ~Turn 1 right angle clockwise B@ ~Brush @ more square T1 ~Turn 1 right angle clockwise N ~Next (loop) ``` Output for `tilesX` = 3, `tilesY` = 5: ![](https://i.stack.imgur.com/xrST2.png) Note: This version only works for `tilesX` up to 6 and `tilesY` up to 5. The question does not mention what range we need to support though, so I'm assuming this is OK. Otherwise, a small addition to the program produces this alternative, which supports a slightly larger range: # Unicorn, ~~30~~ 27 bytes ``` x0y9P3G$PG@PS@S$L2B$T1B@T1N ``` By adding `x0y9`, which starts the box at (0,9), the program works for `tilesX` up to 9 and `tilesY` up to 9 (because input only goes up to 9). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal/wiki), 4 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` BNN* ``` First input is the width, second input is the height. [Try it online (verbose)](https://tio.run/##S85ILErOT8z5/98pv0LDM6@gtMSvNDcptUhDUweVp6SlpPn/vwmX8X/dshwA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nkXv96wDIq3//024jAE). **Explanation:** ``` BNN* Box(InputNumber(),InputNumber(),"*") ``` Builtin: draw a box using the two input as width/height respectively and character `*` as border. (The `*` can be replaced with other ASCII characters that are available in the Charcoal codepage.) [Answer] # [Python 3](https://docs.python.org/3/), ~~71~~ ~~67~~ 63 bytes ``` lambda n,m:[[n>i+1>1<j+1<m for i in range(n)]for j in range(m)] ``` Returns a 2 dimensional array. [Try it online!](https://tio.run/##RcixCoAgEADQX7lR0UXCJcwfMQejLCVPEZe@/qKpN772jKviRHFZ6Q5l2wOgLLNzaJNQVpkslCkQa4cECaEHPA@G3H@T/yncU@sJB4tMS805Eb0 "Python 3 – Try It Online") Port of [Alex A.](https://codegolf.stackexchange.com/a/77995/109916)'s answer. -4 thx to @Steffan ]
[Question] [ You left your computer for too long, and it went to sleep. Wake it up again by printing the following coffee maker. ``` ________._________ | | \ - / | || | \ - / | || |___\___/ | || | X | | ___ | | / - \ |______| / - \ | ____ | /_______\ ||7:30||__________ ||____| | |_________________| ``` [Reference image I used.](http://ghk.h-cdn.co/assets/17/28/1499887621-cuisinart-coffee.jpg) # Specs * Any input must be included in the byte total. * Leading newlines and trailing whitespace is allowed. * Shortest code in bytes wins. [Answer] # [CoffeeScript](http://coffeescript.org/), 219 bytes *Thanks to @totallyhuman for saving 4 bytes!* ``` ->"""#{l="________"}.#{l}_ #{s="| |"} \\ - / #{t="| || |"} \\ - / #{t}___\\___/ #{t} X #{s} ___ #{s} / - \\ |______| / - \\ | ____ | /_______\\ ||7:30||#{l}__ ||____| | |#{l}#{l}_|""" ``` [Try it online!](https://tio.run/##PY@xCgMhDIZ3n0Jyy93gWehQKNjn6CA4iFcKUku97eKz2xhtA0r@/zMx8WnbQsj@83zv1bMwVd0AYDqiATcCykq6ODEd2QBKDoQiraVE0dGEdkaIHTFTgxRqYi1dXXH9vXXjlPxfrqnEWoH9X2xGa9Ks9sxJlHoM1Ty8XM8nRB7OkRxF/0DBjDnSVrTjK6cY1pgec993Xpb6BQ) [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 78 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ≈p⁽.*%θ|»Y?v▼mB8█[=ρļiρKτ¾Γb 2⁴⅟┼¤Μ╬(׀⁾⌠○Yyλ{╝<-³|k¤↑E*UH∙æ¹ΘNσx↔§÷πm‛⁾ņμ׀⁴@≤‘ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjQ4cCV1MjA3RC4qJTI1JXUwM0I4JTdDJUJCWSUzRnYldTI1QkNtQjgldTI1ODglNUIlM0QldTAzQzEldTAxM0NpJXUwM0MxSyV1MDNDNCVCRSV1MDM5M2IlMDkyJXUyMDc0JXUyMTVGJXUyNTNDJUE0JXUwMzlDJXUyNTZDJTI4JXUwNUMwJXUyMDdFJXUyMzIwJXUyNUNCWXkldTAzQkIlN0IldTI1NUQlM0MtJUIzJTdDayVBNCV1MjE5MUUqVUgldTIyMTklRTYlQjkldTAzOThOJXUwM0MzeCV1MjE5NCVBNyVGNyV1MDNDMG0ldTIwMUIldTIwN0UldTAxNDYldTAzQkMldTA1QzAldTIwNzRAJXUyMjY0JXUyMDE4) SOGL compression beats bubblegum! [Answer] # Befunge, ~~166~~ 162 bytes ``` 55+31p"kvvvvvvvvgf:::::kvugvvvvvj6,jHvvvs>?vqg[@:P>vvvg[|P:f::>Jv"v :0 /\|_-37X.v"vvvv{vvvvg:::>=:@:G>f>f:=|:G>f>fv`vUg:j:>::N>::f::"< g1+2%+56:-*49<_@#:,g1/+56, ``` [Try it online!](http://befunge.tryitonline.net/#code=NTUrMzFwImt2dnZ2dnZ2dmdmOjo6OjprdnVndnZ2dnZqNixqSHZ2dnM+P3ZxZ1tAOlA+dnZ2Z1t8UDpmOjo+SnYidgo6MCAgL1x8Xy0zN1gudiJ2dnZ2e3Z2dnZnOjo6Pj06QDpHPmY+Zjo9fDpHPmY+ZnZgdlVnOmo6Pjo6Tj46OmY6OiI8CmcxKzIlKzU2Oi0qNDk8X0AjOixnMS8rNTYs&input=) **Explanation** This is using a fairly simple compression scheme where every two characters are encoded into a pair as a base 11 number. We start by translating the characters into indices in a lookup table to minimise their size - this gives us one index in the range 0 to 11, and a second in the range 0 to 8. These indices are combined into a single number as `n = i1 + i2*11`. We then add a additional offset to translate that number into the range of printable ASCII characters, so it can be stored in a Befunge string. When decoding we just perform this process in reverse. We subtract the offset, split the value into two parts with `i1 = n%11` and `i2 = n/11`, and then lookup those indices in the translation table to obtain the final characters to output. **Bonus Coffee Mug** ``` 55+37p"kvvvvvvvvgf::"v v",6jvvvvvguvk:::" < >"jHvvvs>?vqg[@:P" v v"vJ>::f:P|[gvvv>" < >"::f::>N::>:j:gU" v v"f>f:=|:G>f>fv`v" < >">G:@:=>:::gvvvv" v :0 X/\|_-37X.v"vvvv{"< @v2%+56:-*49<<_> >+7g,65+/7g,:^ ``` [Try it online!](http://befunge.tryitonline.net/#code=NTUrMzdwImt2dnZ2dnZ2dmdmOjoidgp2Iiw2anZ2dnZ2Z3V2azo6OiIgICA8Cj4iakh2dnZzPj92cWdbQDpQIiAgIHYKdiJ2Sj46OmY6UHxbZ3Z2dj4iICAgPAo+Ijo6Zjo6Pk46Oj46ajpnVSIgICB2CnYiZj5mOj18Okc+Zj5mdmB2IiAgIDwKPiI+RzpAOj0+Ojo6Z3Z2dnYiICAgdgo6MCBYL1x8Xy0zN1gudiJ2dnZ2eyI8CiBAdjIlKzU2Oi0qNDk8PF8+CiAgPis3Zyw2NSsvN2csOl4&input=) [Answer] # JavaScript (ES6), 176 bytes ``` _=>`22__.222511| 31-1/4636-6/4232/416X511| 12511|1/ - 3522|6/6-635 2_ | /2_235|7:0||222_5|2_|6111|522222__|`.replace(/\d/g,s=>[30,' ','___','\\',` | || |`,` |`,' '][s]||s) ``` [Try it online!](https://tio.run/##HYzBCoMwEETv/Yq9RUGN2ZgUCvodBZWNqJUWUTGlp/13Gz3MsMy8nU/363y/v7dvuqzDeLygPKisHCJRhohGKQatUiULq21qZYEaZaHs82rUBSgJKWiDyFYGRhtAAgaJhNrw/ZEzhykyjMRWhYeAngGxy/Zxm7t@jGQzyCnxZVXrPBEAIBJBRMGbRiTuxgB8yp23OwnR1r5l9vHRr4tf5zGb1yl6RXF8/AE "JavaScript (Node.js) – Try It Online") # [RegPack](https://siorki.github.io/regPack.html)'d version, ~~186~~ 184 bytes ``` _=>[...'CaFfEiNe!'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),`!E_.C! f| \\a-aiN\\e-ei|!\\!iNaX fNe! fN / - FCN/e-eF E | /!EF|7:30||CE ||Efea| |CCE_|E__a N|ei/ N|NE!_fNeeF\\ |ae C!!`) ``` [Try it online!](https://tio.run/##DY6xigMhFAB7v@JZRSHrBlIcHGwa0dL64AxGzDMYlnWJSUjx/n1jM83AMPf4ji09yvoclnrFLcO0hen0r5Ta6WizKQ757qweeH0lFKLtk5xO4jM11da5PEWSUt1rWcRHrXUVUu4v3ASlOcsE3schFuc9DliIe8@Li38s92YHjDCA1W7s1oIBgpEbSz@/xwORNozIZIzESGsTyIQQwRGWkTlyhodeQes9o4igOb/ILdWl1RnVXG8i95XtCw "JavaScript (Node.js) – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 83 bytes ``` 00000000: 4d8c d501 0230 1403 ff3b 4507 c01d 16c1 M....0...;E..... 00000010: c922 199e abf7 9eab 2a2b 3582 63c6 f183 ."......*+5.c... 00000020: 5f62 eb60 4a0c a5b7 9c3b 923e d8bc 028f _b.`J....;.>.... 00000030: f104 e6a7 d89a 0f9f 6065 4c9d 5fd2 8902 ........`eL._... 00000040: 56d6 2ad0 f2f9 b6df d8ea d0aa 671d d75f V.*.........g.._ 00000050: 33fe 03 3.. ``` [Try it online!](https://tio.run/##hdC9TgQxDATgnqcYUR6S5fxuwkl0NAha2rs4ia@B8p5/8cKio2OkSCmcLyPLVeRjXq6f68p7HhFH6RiJHdgHhoscoBoEMfGCzm7A5e6AN7KwnePzdqO7H8GZ0av3cLVONNEFdTaBb14QUvHIoWeoKwGg@@@ndHhI1G@GNyNp9piSGbFxR0tiULce1YeJUaRbwaLASej8siFHevrTI5ihjiNmbovN1wbWqsicE2Kvw34YHqWytx57zvOVTjcjbj3yyFZ@MNRrheShps2Gwa0hL7aPsSTr8U6HX4YuRKfdSGaEoBO2x38TiNb1Cw "Bubblegum – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 169 165 bytes Thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul) for saving 4 bytes! ``` base64 -d<<<H4sIAECtIFoCA1WOUQqAMAxD/3uKXmBO8EPwJH4MepEc3sRVrQ86WJZkjZgs8WDwG/jg2ThdEjQurVWFgcGpFnJ+JeRXyjAbhmH+Bt1VSUXGoKXnJpSwH9sKRNkOGXuBlfcEdgGenVY82QAAAA==|zcat ``` [Try it online!](https://tio.run/##DcHJDkNAAADQX@ldGrFENOEwGMOIKoqpm62EWmqItum/a9/LM9rse57RShIPx1JRFEukNoD6YpujDrjEi/wncMHLYIXVIb3myfCyYUt0qwkWAg3i2ZelBKddm9ZUTowNsW3NX5sStv46x4lZF2gyB8zgKiDvFuRNbzHawsVhRNDokAFP4WadqBOcOw@RVXvcC1jWqBrim8z74E9Vv58iW/b9Bw "Bash – Try It Online") `gzip` seems to compress it a lot better than `bzip2` and `xz`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 189 bytes ``` ()=>@"uu__.uuu |ss| \s-s/ | || | \ - / | || |u\u/ | || |s X |ss| su |ss|s/ - \ |uu| / - \ | u_ | /u_u\ ||7:30||uuu_ ||u_| sss| |uuuuu__|".Replace("u","___").Replace("s"," ") ``` [Try it online!](https://tio.run/##VY/BSsQwFEXX5isuWTVgW8GFYJ1hYMCVA6ILXRRCiRkNdBrpyxNkMt9eXx2kuMjinndP4DoqXRz9xBSGdzx/U/KHRrm@I8LjUVHqUnC458HdURqls8Y27vfe7zr3EQaPFabCrNYbzWxtxcwqE2W0VFKtMpDnB7RACSyEW14CAa9njc461dJuVWaWc/2rSgJb@apmyxLyze31VZYGWwlspUhizs7MbNbVk//sO@cLzfpSW2u1WRAJAqDN1Ki/lV8xvGHXhaEw6qgutnGg2PvqZQzJP8jW4t/ywphGndRp@gE "C# (.NET Core) – Try It Online") --- The lazy solution: # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 223 bytes ``` ()=>@"________._________ | | \ - / | || | \ - / | || |___\___/ | || | X | | ___ | | / - \ |______| / - \ | ____ | /_______\ ||7:30||__________ ||____| | |_________________|" ``` [Try it online!](https://tio.run/##VVDBCsIwDD2brwietsNU8CA4J4LgSUHwoIfBGLXTgrawVkGM3z5T3XR7kJK@vvcaImwkTCmrm1X6hLuHdfIag7jk1uL2CdblTglc3bSYWVeyZo5LUxRSbnJxVlpiglUQJvNFP6sxaJoMCD8gTPmMuIaeIl/ouajNsCHlaksYh38IoxPKZk5Igb6/kb/7SGa8MGPJsJ6EKZpMxyOirDUd1bYfCFrvNahfxdDs4W7UETe50kEIT@gtjbbmIgf7Ujm55m0End0EYRjDC17VGw "C# (.NET Core) – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 689 bytes ``` +++++++++>+++>++++++++++++>++++>+++++++++>+>++++>++++>++++>+++++>+++++>++++++++>+++++<<<<<<<<<<<<[[->>>>>>>>>>>>>>++++++++++<<<<<<<<<<<<<<]>]>+++++>++>++++>+++++++>++>>+++++>++++++>++++++++>+>+++++>++++++++>++++++++<<<<<<<<<<<<........>>>>>>>.<<<<<<<.........>>>>>.<<<.<......>.<.>>>.<<<...>>>>>.<<<<<...>>.>>.<<<.<..>..<..>.<..>>>.<<<..>>>>>.<<<<<..>>.>>.<<<.<..>..<..>.<<...>>>>.<<<<...>>>.>>.<<<.<......>.<.....>>>>>>>>>>.<<<<<<.<<<.<......>.<....<...>>>>>.<<<.<......>.<...>>.<<.>>>>>.<<<<<.>>>.>.<<<.<<......>>.<..>>.<<..>>>>>.<<<<<..>>>.>.<<<.<.<....>.>.<.>>.<<<.......>>>>.>.<<<..>>>>>>>>.>>.<<<.<.<<<<<<..<<..........>>>>>.<<<..<<....>>.<...........>.>>>.<<<.<<.................>>. ``` [Try it online!](https://tio.run/##dVBLCkIxEDuQmBOUXOTxFioIIrgQPH/9dD6ZUgdaOmlIMnN@nm6P6@ty7/3gRTsFEIQCyJfe8WhS23ZkqXRopXbuIVa8v32x4ZRptp@kYWX@mGAECsM@DRySb@uQZGLcDckv9DXbVRGaSvMEEjlTL0jt3wgYoiXRz2oQnWnxsQgf3CFL2wxye0xShM1ZfNGybIlqMH1YTx6jKBxhe38D "brainfuck – Try It Online") First I generate a table of 13 characters that are used. To save bytes, I first generate their closest character codes that are divisible by 10. Then I add 0-9 to each of them. Finally I just print them in particular orders. Unminified source: ``` +++++++++>+++>++++++++++++>++++>+++++++++>+>++++>++++>++++>+++++>+++++>++++++++>+++++<<<<<<<<<<<< [[->>>>>>>>>>>>>>++++++++++<<<<<<<<<<<<<<]>] > +++++>++>++++>+++++++>++>>+++++>++++++>++++++++>+>+++++>++++++++>++++++++ <<<<<<<<<<<< ........>>>>>>>.<<<<<<<.........>>>>>. <<<.<......>.<.>>>.<<<...>>>>>.<<<<<...>>.>>. <<<.<..>..<..>.<..>>>.<<<..>>>>>.<<<<<..>>.>>. <<<.<..>..<..>.<<...>>>>.<<<<...>>>.>>. <<<.<......>.<.....>>>>>>>>>>.<<<<<<. <<<.<......>.<....<...>>>>>. <<<.<......>.<...>>.<<.>>>>>.<<<<<.>>>.>. <<<.<<......>>.<..>>.<<..>>>>>.<<<<<..>>>.>. <<<.<.<....>.>.<.>>.<<<.......>>>>.>. <<<..>>>>>>>>.>>.<<<.<.<<<<<<..<<..........>>>>>. <<<..<<....>>.<...........>.>>>. <<<.<<.................>>. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~282~~ 265 bytes ``` a,b,c,d,e,u='_ . | \ / ||'.split();s=' ';t=s*2;z=c+t;y=c+s*6;v=z+u+t for x in a*8+b+a*9,y+c+s+d+s*3+a+s*3+e,v+z+d+t+a+t+e,v+c+a*3+d+a*3+e,v+c+s*5+"X",y+c+s*4+a*3,y+c+s*3+e+s+a+s+d,y+z+e+t+a+t+d,c+s+a*4+s+c+s+e+a*7+d,u+"7:30"+c*2+a*10,u+a*4+c+s*11+c,c+a*17+c:print x ``` [Try it online!](https://tio.run/##LY3NDoJADITvPkXDBd02yo@Kutn38GBi1gUjiQHCLkYI745d8NJ0vk5nmt696iqZJk0PMpRTQZ0K77CFEW6wg3EMt7Z5l269kVaFEEqnrEjkoAw62fO04ig/asAO3epZt/CFsgItTvhALc7UI1swZ1uKep4FfXBg4li7WRl2pkz0/@pDDxhcg@Vb7P3lv7OD87TPZDKwWnJy8j2avXZuLHjPmHYYZJc0CtCIhFEcMfEunxXHaMiXxxmaS9OWlYPvNP0A "Python 2 – Try It Online") Actually a fair bit longer than just ``` print'''TheCoffeePot''' ``` which would be 227 but it works so posting it anyway as it's the shortest (and so far only) Python answer :) [Answer] # [J](http://jsoftware.com/), 174 164 bytes Some silly RLE-like compression, lengths encoded as base 99 number :) ``` _19]\(10#.inv 99x#._28+a.i.' Ls}DR#Er-B{SBh(+dXQwBE=]| LrC$v:x5u}sa"z> f=#Y*?Tzzo8PmK7rZay')#,'_._||\-/|||\-/|||_\_/|||x||_||/-\|_|/-\|_|/_\|7:30|__|_| ||__|',.' ' ``` [Try it online!](https://tio.run/##NYdLD8FAFEb3fgNxYyTj0Y4iQicpSemKhdcCGblpMEGCpA2qbn97VcLiO@d851SHjgQLsqXYtLeq0rSYOF0fYNsRE9jq1X1xErwwCZPRnHmB6b4X7rFS369mT9dztlSYBMPyQ0adexL6pbif1w5b1wbLuBjfetPLuBts/BevMoOjQCJlNuhPVPhVlBVRw1SZfkRFXdm2CDF7QF9zQ3DgaTVXEsC1I7kBiQQd5g674w10@gE "J – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 546 bytes ``` -[+>+[+<]>+]>>++++++++++>------->-[<++>-----]<........<<.+>>.........<.>>>++++[<++++++++>-]--->--[<+>--]++>-[<+>-----]+++>-[<+>---]<<<.<......>.<.<---.>...<<<--.++>>>...<<<.>.>>>.<..>..<..>.<..<.+++>..<<<--.++>>>..<<<.>.>>>.<..>..<..>.<<...---.+++...<<.>.>>>.<..>..<..>.<.....>>>.<<<<<.>>>.<......>.<....<...<.>>>.<......>.<...<<<.>>>.<<<--.++>>>.<---.+++<.>>>.<<......>>.<..<<<.>>>..<<<--.++>>>..<---.+++<.>>>.<.<....>.>.<.<<<.>>.......---.+++<.>>>..>++.+++.-------.---.<..<<..........<.>>>..<<....>>.<...........>.<<<.>>>.<<.................>>. ``` [Try it online!](https://tio.run/##bVFLCkMhDDxQMCcIcxFx0RYKpdBFoee3@enTx8tC85lJJnr/3l6f5@/x7r1UAlWSBmoATUMJQ6kyoiacJsIE8AwZwTXs4DdnG13PZplwi0dH2ES7ZWeoI5pj@BB1WZHISLPmi@HiFLut2Ql9DbYhxUEUO1z1MxWWFO8BrNJ81Vx3z0/wokJy1qgkPlQn/iR7Z8QIxKs4Id97g7G@vK@UP@ZVH8H7B43UoX0sILvEtQju/Q8 "brainfuck – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~220~~ ~~216~~ 213 bytes ``` b=0;c='\n -./037:X\\_|' for i in r"*Z_7stu{NzKBNJ,IOOe-0qj9?s7C?r/XYUX_Fs\hM-\NY+VJ+A.E]?vAx&=gUVSBRq4>PB+]OtO3%PWn%^0c0'B]d5P-$X,(7U$nVq02NRjMp'AAvl!Da(zyVyI":b=b*92+ord(i)-32 while b:print(c[b%13],end='');b//=13 ``` [Try it online!](https://tio.run/##Dc//ToJAAADg/32Ky0mHAnJCjYm7GFht2gRmg7COWAcU59zxMwvr3a3vDb6q74qS6@czxWiRYkg4UKYq0g0zIiT5hYP3sgEMMA6a4eQ5Mdru88c9PTjuWl55Xq6gej@3WmNpNWq0C6LkviXFRiHuTgrXkj29i62j/X2JP4Lw0dnWVze@I8Ve5@mC/8SFV5Qi6MTZta@MIlk0ghEPa6S52/2mgrZ9PFzcvomnPuxXQ5NiOplrUtlkIhsrujb4KtghB9SsGsY7MX2hwkyP5ZxnGMLxgqoqnv23/gA "Python 3 – Try It Online") [Code to generate code](https://tio.run/##VZHrboMwDIX/5ykspIqkNyhMmkrFnmNSqRCBbDBBQIHd1OzZmcOlpZaM4OT4sx2a3y6vpd/3aQUhWJYVT7GfX2KiYQgNET53mI6RtEkw2m6pYEGEubRgvN4hGA9QLEZCFBE9ttNGMEwjGWuMJmeaxWj6OfBdrePFgHoqvIUmi/MpNG5H0jxRLW5aFm1H21p1IqOt6GhaMcYISdpYflZcKLS45K1WUEAhQYkvoVq0oi0gAHfbGlFC0gHLHk42IQzqvpCZ@KGFoZdNnnDRIfyc5go1uLdI5LugvreFg/fELqRE0w1GJIx9ZgIj/HhAzbbJd16UAsoX1wwGMOqz71yu5AU2Rh1OS3CcECQhaZ2J8Yfz0D2l4fVvsa11/bMCHvL10dvUKsM5d743NeJBowqJF3bmq4N/2QqZhbbNThzBBx95e@RUSUeVaBTFz4@6mO@Hbc0geBETAmdgpO//AQ "Python 3 – Try It Online") [Answer] # [Bash](https://www.gnu.org/software/bash/), 108 bytes `zcat` Input is a 104 byte sequence on stdin (represented in hexadecimal below) of the coffee pot compressed in gzip format: ``` 1F 8B 08 01 0F 2D 32 5A 02 00 5D 8C 41 0A 80 30 0C 04 EF 7D 45 3E A0 15 3C 08 BE C4 43 20 1F D9 C7 3B B1 96 56 87 A6 90 21 BB F1 B2 46 A7 C8 1E 64 CE BF 30 35 95 18 9E A3 66 43 C0 99 F9 04 AE 51 02 9F 52 C2 34 78 11 16 94 3B 22 8D 05 70 52 A3 81 D2 71 EE 9B B8 ED A0 5A 6C 20 BA FE A8 DC 9E 9D 56 3C D9 00 00 00 ``` [Answer] # [Cubically](//git.io/Cubically), ~~652~~ 626 bytes ``` ⇒@@@@@@@@ RU+532f1-411@+411f1@-3320@+5432@-4422@@@@@@+4422@-4422@+220@-220@@@+4-0@-4+0@@@+1@-4000@+5432@-4422@@+4422@@-4422@@+4422@-4422@@+220@-220@@+4-0@-4+0@@+1@-4000@+5432@-4422@@+4422@@-4422@@+4422@-50+4@@@-1+00@+1-00@@@-50@-4000@+5432@-4422@@+4422@@-4422@@+4422@-4422@@@@@+311@-333@+5432@-4422@@@@@@+4422@-4422@@@@+510@@@-3320@+5432@-4422@@@@@@+4422@-4422@@@+1@-1@+4-0@-4+0@+220@-3311@+5432@-50+4@@@@@@+50-4@-4422@@+1@-1@@+4-0@-4+0@@+220@-3311@+5432@-4422@+510@@@@-510@+4422@-4422@+1@+50@@@@@@@-1+00@-3311@+5432@@-52@+1-00@-3+4@-1+00@+541@@-50+4f1@@-3320@+5432@@-50+4@@@@+50-4@-4422f1@@@+4422@-5432@+5432@-50+4f1f1@+50-4@ ``` Found via [this tool](https://codegolf.stackexchange.com/a/141839/61563) and golfed via search-and-replace, plus a couple custom optimizations. [Try it online!](https://tio.run/##lVJBCgIxDLz7lRBomvTeNwg@QBcWhL168AXefaIfqUlTd1sFxT10kzKTzCSdLqfzdFyWaymP2z23b7c/QOI4EwpRBj1mysgcQ4YkHDOKxOhYqKFfQFQE2mH3qLFAjZUtIbyxnTlmr2Qr1NX5o0wKINoYCQxOGEyG3v6pw7QzVe/83bqliWqX33NyK9R5c8NsvRqzOah1A8oqrxKHqXxQfReuRgvpf1iS4ULbtA@oZyshtokhq4Q2wiSUXdRMo8dNaifUQOsuDNW5mu01ObaUJw) ]
[Question] [ This is a very simple challenge. The joke language InterpretMe consists of one command; `*`, which causes the program to take input of an InterpretMe program and execute it. An InterpretMe program will interpret as many InterpretMe programs as there are `*` in input. --- Your goal is to create a program that interprets InterpretMe in as few bytes as possible. --- ## Input Input will consist of one line ASCII strings, unicode utf-8 strings if you really want, or any character encoding that your language uses, if you want it that much. These strings can either be inputted at the start, or at the start of every run of InterpretMe interpreter. If they are all inputted at the start, the program must output every program line as it begins it. ## Output In this challenge, there will be no output unless the option of one input is chosen, otherwise only termination and non-termination --- Test cases consist not of input and output, but input and termination. A newline denotes a new input to be interpreted as InterpretMe. If using one input at the start, this could be considered what is outputted when these programs are inputted, followed by inactive (do nothing) lines. ``` 1. * (executes input as an interpret me program, finishes) 2. * (^same) 3. ** (executes input as an interpret me program, then does this again after the first program is done, finishes) 4. hi (nothing, first star of previous line finishes) 5. ** (same as the other two star line) 6. hi (nothing, first star of previous line finishes) 7. hi (nothing, second star of line 5 finishes, so second star of line 3 finishes, so line 2 finishes, so line one finishes) [termination] (not outputted) ``` ``` hi (does nothing and finishes) [termination] ``` ``` *hi (executes inputted program, finishes) *yo (executes inputted program, finishes) hey (nothing) [termination] ``` Again, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewer bytes is better [Answer] # Python 3, 35 bytes ``` i=1 while i:i+=input().count('*')-1 ``` sets i to one, adds the amount of '\*' -1 to i ~~I think I can reduce this with `~` trickery~~ I couldn't [Answer] ## Python 3, ~~39~~ 38 bytes ``` def f():[f()for c in input()if c=="*"] ``` Saved 1 byte thanks to @atlasologist [Answer] # Ruby, 29 bytes ``` i=1 i+=gets.count ?*while$.<i ``` Ruby's magical variable `$.` keeps track of the number of lines read from stdin. Keep reading input while this number is lower than the count of asterisks (plus the initial 1). [Answer] ## JavaScript, ~~53~~ ~~45~~ 44 bytes ``` f=_=>{for(i in prompt().match(/\*/g))f()}f() ``` This program is rather annoying to use due to JavaScript's lack of good I/O. Asks for a program, then asks for another program for every `*` in the input program. [Answer] # Java only ~~45 60 101 100~~ 99 bytes Reverse code-golf :D. I noticed that I missread the specs (twice), but now it should work. Seems simple enough, perhaps there is a better way of writing this as a lamda expression. ``` void a(char[]a){for(char b:a)if(b==42)a(new java.util.Scanner(System.in).nextLine().toCharArray());} ``` Slightly sleazy cheating for only 17 bytes! ``` void a(char[]a){} ``` This version will take input via really fast typing [Answer] # Mathematica, 38 bytes ``` f:=StringCases[InputString[],"*":>f];f ``` [Answer] # APL, 15 bytes ``` {⍵='*':∇¨⍞⋄⍬}¨⍞ ``` Test: ``` {⍵='*':∇¨⍞⋄⍬}¨⍞ * * ** hi ** hi hi ⍝ termination ``` Explanation: ``` ⍞ read a line from the keyboard { }¨ for each character: ⍵='*': if it is *: ⍞ read another line from the keyboard ∇¨ do the same for each character ⋄⍬ otherwise, return empty list (which displays as nothing) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes Code: ``` [¬'*QiIJ}¦Ž ``` Explanation: ``` [ # Enter an infinite loop ¬ # Get the first character of the input string (leaves the input on the stack) '*Qi } # If equal to an asterisk... I # Request another line of input and J # Join it to the string that was left on the stack ¦ # Remove the first character Ž # If everything is processed, terminate ``` Uses the **CP-1252** encoding. [Try it online?](http://05ab1e.tryitonline.net/#code=W8KsJypRaUlKfcKmxb0&input=KgoqCioqCmhpCioqCmhpCmhp). [Answer] ## Perl, 33 bytes ``` for(my$c;$c+=()=<>=~/\*/g;$c--){} ``` Counts the number of times that \* occurs in the input and adds that to the number of times it loops. I feel like there should be a way to do the decrementing in the same step as incrementing but I couldn't figure it out. ]
[Question] [ ## Challenge Given an array of single digit number, work out if any 2 of them add up to 10 and print them out ## Example **Input** > > (1,2,3,4,5,5,6,7) > > > This returns `((4,6),(5,5),(3,7))` **Input** > > (1,2,3,4,5) > > > This returns `()`. as there is only one 5 **Input** > > (5,5,5,5,5) > > > This returns `((5,5),(5,5))` as there is odd number of 5s and each 5 can be used only once ## Rules Here are the rules! * Assume input will only be an unsorted array of positive single digit integers * Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7) * For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers. * For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array) ## Test Cases ``` (1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7)) (1,2,3,4,5) = () (5,5,5,5,5) = ((5,5),(5,5)) (1,2,3,3,4,5,6,7)=((3,7),(4,6)) (9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4)) ``` ## Good luck! The `shorter` an answer is, the better! Edit 1: update the rules and Testcases from comments Edit 2: update rules to define format of input. Edit 3: update rules to define format of output. trying to be as accommodating as possible. [Answer] # Python 2.7 (70) ``` y=input() while y: g=10-y.pop() if g in y:y.remove(g);print(g,10-g) ``` Testcases: ``` $ echo '[1, 2, 3, 4, 5, 5, 6, 7]' | python p.py (3, 7) (4, 6) (5, 5) $ echo '[1,2,3,4,5]' | python p.py $ echo '[5,5,5,5,5]' | python p.py (5, 5) (5, 5) $ echo '[1,2,3,3,4,5,6,7]' | python p.py (3, 7) (4, 6) $ echo '[9,8,7,6,4,4,3,1]' | python p.py (9, 1) (7, 3) (6, 4) ``` One byte extra for the nice parenthesis. [Answer] ### GolfScript, 45 42 37 chars ``` ~{([.~11+.])@{1$=.{2$p!\}*!},\;\;.}do ``` The new approach does also take arrays with a single item as input. Moreover, it is several chars shorter. Previous version: ``` ~{$(\)@.2$+10-.{0>{\}*;+}{;[\]p}if.,1>}do; ``` The algorithm used in this code is described as follows: * Sort the array. * Take the sum of the first and the last item. + If the sum is 10 print both numbers and remove them from the array. + If the sum is greater than 10, discard the larger number. + If the sum is less than 10, discard the smaller number. * Loop until the array contains only a single digit or is even empty. The code expects an array of at least two digits on STDIN. Examples (see [online](http://golfscript.apphb.com/?c=OyJbOSA4IDcgNiA0IDQgMyAxXSIKfnskKFwpQC4yJCsxMC0uezA%2Be1x9KjsrfXs7W1xdcH1pZi4sMT59ZG87CgoiLS0tLS0tLS0tLS0icHV0cwoKOyJbNSA1IDUgNSA1XSIKfnskKFwpQC4yJCsxMC0uezA%2Be1x9KjsrfXs7W1xdcH1pZi4sMT59ZG87Cg%3D%3D&run=true)): ``` >[9 8 7 6 4 4 3 1] [1 9] [3 7] [4 6] >[5 5 5 5 5] [5 5] [5 5] ``` [Answer] ## Javascript, ~~188~~ ~~183~~ ~~181~~ ~~153~~ ~~141~~ ~~121~~ ~~123~~ ~~112~~ *105* ~~98~~ chars Golfing in JS is somewhat difficult, but I just wanted to have a bash on this problem, so here's the code: ``` for(a=eval(prompt(i=o=[]));k=a[j=++i];)for(;p=a[--j];)k+p-10||(k=a[i]=a[j]=-o.push([p,k]));console.log(o) ``` Input: e.g. `[1,2,3,3,4,5,6,7]`. Output e.g. `[[4,6],[3,7]]` to the console. ~~105->98: Used Daniel's awesome algorithm to completely rewrite the code! See [his answer](https://codegolf.stackexchange.com/a/8999/6689) for a readable algorithm.~~ Completely messed up stuff so reverted to **105** chars. 112->105: Initialised `i` to zero, used output of `o.push` to set `k` (`k=a[i]=a[j]=-o.push...`) and logged output to console instead of alerting to eliminate `"["+` and `+"]"` since the console outputs nicely already. 123->112: Now removed outer brackets in output, since golfscript may :) Also finally applied suggestion of removing `|=0`. 121->123: Changed `o+="("+p+","+k+"),"` to `o.push("("+[p,k]+")")` (adds 2 chars :( ) and made `o` an array instead of a string (`o=""`->`o=[]`). Now output isn't wrong anymore (like `((5,5),(5,5),)`). 141->121: From now on assumed that the question meant that we could get input in the language's array format, which in JS's case is `[a,b,c,...]` and made `o`, the output "accumulator" a string instead of an array (`o.push(...),`->`o+=...,`). 153->141: Reset array entries instead of removing them after usage. 181->153: Applied changes to `u=[]`, rearranged loops, `a[i]`&`a[j]`->temp vars, converted if logic and converted int logic to `a[i]|=0`. 183->181: Replaced `i<=0` with `i+1` and the same for `j`. 188->183: Placed `o=[]` inside `prompt()` (~~`;`~~) and replaced `for(j=i;` with `for(j=i-1;` (~~`i==j&&`~~). *(Thanks mellamokb, Paul Walls and ryan!)* [Answer] ## J, 54 53 50 46 45 44 characters ``` (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/ ``` Usage: ``` (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/5 5 5 5 5 5 5 5 5 (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/9 8 7 6 4 4 3 1 1 9 3 7 4 6 ``` The algorithm is basically: * count the instance of each number `+/|:(1+i.9)=/` * pair the counts of each pair that would add to 10 `(<.|.)` (so 1 and 9, 2 and 8 etc.) * take the minimum of those counts (so if you have three 9s but only one 1, you'll only have one `1 9` pair) and drop everything after the first five pairs * the 5s are a special case so divide that by 2 (`<.4({.,-:@{::)` implements both previous steps) * take the first five items of the list and output the number and 10`-`the number `(>:,.9&-)I.` [Answer] ## Python (142) Input should be given with square brackets instead of round brackets. <http://ideone.com/p2QR11> ``` from itertools import* a=input() c=lambda:[i for i in product(a,a[1:])if sum(i)==10] d=c() while d:print d[0];[a.remove(j)for j in d[0]];d=c() ``` Algorithm: ``` 1. Get input 2. Generate all pairs of input where the sum is 10 3. If there are no pairs, then END PROGRAM 4. Take the first pair's items and remove them from the input 5. Go back to step 2 ``` If seriously malformed output is allowed **(90)**: <http://ideone.com/GR762f> ``` a=input() c=a.count for i in range(6):print(`i`+`10-i`+' ')*(min(c(i),c(10-i))/(1+(i==5))) ``` [Answer] ## C, 142,138, 124 ``` char*p,*q; main(int a,char**s){ for(p=s[1];*p;p++) if(q=strchr(p+1,106-*p))a=*q=printf("%c(%c,%c)",38+a,*p,*q); puts("()"+a/6); } ``` Testing: ``` ./a.out "(1,2,3,4,5,5,6,7)" ((3,7),(4,6),(5,5)) ./a.out "(1,2,3,4,5)" () ./a.out "(5,5,5,5,5)" ((5,5),(5,5)) ./a.out "(1,2,3,3,4,5,6,7)" ((3,7),(4,6)) ./a.out "(9,8,7,6,4,4,3,1)" ((9,1),(7,3),(6,4)) ``` Implementation notes: * initially a=2 (program has two args), set to 6 (printf prints 6 chars) once a match occurs * 106 = '0'+'0'+10, i.e. uses the sum of the ascii codes * 38+a, is either 44/40, i.e. '(' or ',' * By setting string characters to 6 it ensures they wont add to 106 on other passes * "()"+a/6, is either "()" or ")" [Answer] # Perl 52 ``` perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++' ``` Proof : ``` > cat test 1 2 3 4 5 5 6 7 > perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++' < test 5,5 4,6 3,7 ``` And there is an ungolfed commented code : ``` while(<>) { # made by the -n option # We are looking for (P,Q) pairs where P+Q=10 # Each P entry will come in $_="P\n" (because $_ will not be chopped) # We choose to store the number of occurence of P in $a{P-1} # (For instance, if there have been five '3's in the input, then $a{2}=5) $y=9-$_; # if Q=P-10, then $y=Q-1 if ($a{$y}) { # check if there was a Q (so $a{Q-1} != 0) $a{$y++}--; # If so 'consume' this Q, and let $y=Q print"$y,$_"; # ... and output "Q,P\n" } else { $a{$_-1}++; # P is not forming a new pair, so 'count it'. # $a{$_} would not work because of the un-chopped \n, thus the '-1' } } ``` Maybe the explanations looks like pidgin French (I'm not a native english writer), so if someone wants to edit it and make it more understandable, please do so. [Answer] # Javascript - 131 129 125 chars ``` for(i=eval(prompt(r=[])),k=j=i.length;j--;)for(m=k;m--;)if(m!=j&&i[j]+i[m]==10)r.push([i[j],i[m]]),i[j]=i[m]=0;console.log(r) ``` I assume, the order of and in the nested result arrays is not compulsory :) Evaluated test cases: ``` [1,2,3,4,5,5,6,7] returns [[7,3],[6,4],[5,5]] [1,2,3,4,5] returns [] [5,5,5,5,5] returns [[5,5],[5,5]] [1,2,3,3,4,5,6,7] returns [[7,3],[6,4]] [9,8,7,6,4,4,3,1] returns [[1,9],[3,7],[4,6]] ``` **Edit**: As the problem description says 'Array', we're talking about the language specific notation of an array, right? [Answer] # Mathematica 70 ``` Cases[#//.{x___,n_,y___,d_,z___}/;n+d==10:>{x,y,z,n~f~d},a_~f~b_:>{a,b}]& ``` **Usage** ``` Cases[# //. {x___, n_, y___, d_, z___} /; n + d == 10 :> {x, y, z, n~f~d}, a_~f~b_ :> {a,b}] &[{1, 2, 3, 4, 5, 5, 6, 7}] ``` > > {{3, 7}, {4, 6}, {5, 5}} > > > [Answer] **PostScript (46)** This uses hand-coded binary tokens, therefore, here is a hexdump: ``` 00000000 7b 7b 92 1a 92 3f 7b 32 92 19 92 01 31 30 92 3d |{{...?{2....10.=| 00000010 7b 32 92 09 92 0b 3d 3d 5b 92 40 7d 69 66 92 1a |{2....==[.@}if..| 00000020 31 92 87 7d 92 83 92 75 7d 92 65 7d 92 a3 |1..}...u}.e}..| 0000002e ``` I [uploaded the binary file](http://www.mediafire.com/?as1zbr0q2d6hb9l) if you want to try it out. This expects the numbers to be on the stack. They can be prepended to the code or be supplied on the command line, e.g. when using Ghostscript like so: ``` gsnd -c 2 8 5 5 @ 10_golfed.ps ``` If you insist on array syntax for input, then this requires two more tokens (`aload pop`) right at the beginning. In binary tokens, this is four more bytes. Un-golfed and commented: ``` { % stopped % we use stopped because we want to catch a % stackunderflow when all numbers have been used up { % loop % repeat until all numbers have been popped off the stack % Test for all numbers on the stack whether they add up to 10 with the topmost number count{ % ... nextNumber number currentTestNumber exch % ... nextNumber currentTestNumber number 2 copy add 10 eq{ % ... nextNumber currentTestNumber number 2 array astore == % ... nextNumber % We push "[" on the stack because we want to pop the topmost object after each iteration. % As [ is a one byte self delimiting token, this is nice for golfing. [ exit % ... nextNumber [ }if % ... nextNumber currentTestNumber number count 1 roll % number ... nextNumber currentTestNumber }repeat % number ... nextNumber currentTestNumber pop % number ... nextNumber }loop }stopped ``` [Answer] # Python 84 Requires input in brackets instead of parenthesis. ``` a=input();r=[] while a: n=a.pop(0);m=10-n if m in a:a.remove(m);r+=[(n,m)] print r ``` For roughly the same answer golfed better see [Daniel's answer](https://codegolf.stackexchange.com/a/8999/2621). [Answer] # PHP 150 149 148 146 142 --> 140 Use with PHP CLI. ``` <?$a=fgetcsv(STDIN);for($i=0;$i<$c=count($a);$i++){for($j=$i+1;$j<$c;$j++)if($a[$i]+$a[$j]==10){echo"({$a[$i]},{$a[$j]})";$a[$i]=$a[$j]=0;}} ``` Input: `1,2,3,4,5,5,6,7` Output: `(3,7)(4,6)(5,5)` Un-golfed: ``` <?php $a = fgetcsv(STDIN); $c = count($a); for ($i = 0; $i < $c; $i++) { for ($j = ($i + 1); $j < $c; $j++) { if ($a[$i] + $a[$j] == 10) { echo "({$a[$i]},{$a[$j]})"; $a[$i] = 0; $a[$j] = 0; } } } ?> ``` [Answer] # SED, 112 chars Probably somewhat simpler than the other solutions ``` s/.*/@&;12345678987654321/ : s/\(@.*\)\(.\)\(.*\)\(.\)\(.*;.*\2.\{7\}\4\)/(\2,\4),\1\3\5/ t s/^\(.*\),@.*/(\1)/ ``` [Answer] # Perl, 72 with the `-p` flag ``` perl -p -e 's/^/@/;1while s/(@.*)(.)(.*)((??{10-$2}))/($2,$4)$1$3/;s/(.*)@.*/($1)/' ``` ]
[Question] [ # The Question Given a set of 9 numbers, `m[]`, which contains only numbers 1 through 9 in a random order, with no two numbers being the same, create a program in any language which rearranges the number to be in numerical order (1, 2, 3, etc. etc.) by **only** switching two numbers which are next to each other (ie. 1, 3, 2 → 1, 2, 3). # Rules * You may only modify the set by switching two numbers which are next to each other * The ending numbers (1 through 9 in order) should be contained in `m[]` * You can use any language you would like * The answer with the smallest amount of bytes wins ## Edit: Your code does **not** have to print the output, but the rearranged array must be in `m[]`. [Answer] # CJam, 15 bytes ``` q~A{{a+$~}*]}*p ``` How it works: ``` q~ e# Read the CJam styled input array (For ex. [1 3 4 2 5 6 8 7 9]) A{ }* e# Run the loop 10 times. This is enough times for a 10 length e# input array in a bubble sort { }* e# reduce a+$~ e# Rearrange the pair so that they are sorted ] e# After each loop, wrap the numbers back into the array p e# Print the array after the loops are done ``` [Try it online here](http://cjam.aditsu.net/#code=q%7EA%7B%7Ba%2B%24%7E%7D*%5D%7D*p&input=3%202%204%201%205%207%206%208%209%5D) [Answer] # Mathematica, 38 bytes ``` #//.{a___,b_,c_,d___}/;b>c:>{a,c,b,d}& ``` This is an unnamed function taking an array, which applies a replacement rule until the pattern cannot be found any more. The pattern is a list which has two consecutive elements `b` and `c` where `b > c`, and the rule says to swap the `b` and `c` but otherwise leave the array untouched. There's a lot of syntactic sugar here, but the code is actually very readable if you know a bit of Mathematica: ``` # //. {a___,b_,c_,d___} /; b>c :> {a,c,b,d} & ^ ^ ^ ^ ^ ^ ^ | | | | | | | | | | | Declares an unnamed function | | | | | | | | The function's argument | | | | | | | Replace while possible... | | | | | | Zero or more list elements. | | | | A single list element | | | A condition for the pattern | | What to replace the pattern with ``` [Answer] # Python 3, 72 bytes ``` from random import* while m!=sorted(m):p=randrange(8);m[p:p]=m.pop(p+1), ``` The [bogosort](http://en.wikipedia.org/wiki/Bogosort) (aka stupid sort) approach: swap neighbor elements randomly until the array will be sorted. Usually runs under a second. 2 bytes thanks to @xnor. [Answer] # Python 2, 45 ``` for i in range(8)*8:m[i:i+2]=sorted(m[i:i+2]) ``` Cycles around the list, sorting consecutive pairs of elements. The index `i` cycles through `0,1,2,3,4,5,6,7` eight times, which guarantees all elements bubble through and the list is sorted. [Answer] # Pyth, 13 - 15 bytes Solution which performs the requested swapping, and produces no output: ``` #X=Qhf>FT.:Q2 ``` Solution which performs the requested swapping, and prints out the intermediate state of the list at every step: ``` #QX=Qhf>FT.:Q2 ``` Solution which performs the requested swapping, and prints out the final state of the list: ``` #X=Qhf>FT.:Q2;Q ``` [Demonstration of the middle solution above.](https://pyth.herokuapp.com/?code=%23QX%3DQhf%3EFT.%3AQ2&input=%5B9%2C3%2C7%2C4%2C2%2C5%2C1%2C6%2C8%5D&debug=0) The method of swapping adjacent values is taken from @Jakube's answer. The program uses `#`, the loop until error statement, to swap an adjacent pair of misordered elements until no such pair exists, at which point `h`, the head function, throws an error, ending the program. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~95~~ 93 bytes Not particularly competitive (and probably still golfable), but here we go... ``` (.)1 1$1 ([^1])2 2$1 ([4-9])3 3$1 ([5-9])4 4$1 ([6-9])5 5$1 ([7-9])6 6$1 (8|9)7 7$1 )`98 89 <empty> <empty> ``` Where `<empty>` should be an empty line. Since all numbers are single digits, this just expects a string with all 9 digits as the input and will print `123456789` after successfully sorting it. Each stage performs a single swap and the `)1`` indicates that all but the last stage should be repeated until the result stops changing. The empty stage at the end is necessary, because otherwise we would get intermediate results every time the `98` stage is processed. Here are all the intermediate results (whenever it changes) for an example run: ``` 451629387 451269387 451263987 451263978 415263978 412563978 412536978 412536798 412536789 142536789 124536789 124356789 123456789 ``` (I obtained this by adding the `:` option to each stage, and got rid of consecutive duplicates manually.) [Answer] # Pyth, 17 bytes ``` uXGhaf>FT.:G2]Z)Q ``` Switching items in a list is really expensive in Pyth. So here's a fun solution, that stretches the rules a little bit. It's probably not valid. Try it online: [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=uXGhaf%3EFT.%3AG2%5DZ)Q&input=%5B2%2C+6%2C+9%2C+1%2C+4%2C+7%2C+8%2C+5%2C+3%5D&debug=0) ### Explanation First of all, the time complexity of my code is `O(n^3)`. But this is not the interesting part. The question doesn't say anything about the complexity. The critical part is, how I switch two elements in the list. Let's say I want to switch the elements `m[3]` and `m[4]`. I don't care about the indices `3` and `4` at all. I simply create a second list, that replaces every element equal to `m[3]` with the number `m[4]` and every number equal to `m[4]` with the value `m[3]`. Since the list doesn't contain duplicates, this simulates switching these two values. If there were duplicates, like in the input `[1, 3, 2, 2]`, the output would be `[1, 2, 3, 3]`. And if you give the input `[1, 2, 1]`, it would end in an infinite loop. I don't explicitly create the second list, it's just part of Pyth's implementation of the translate-method. If you print out the current lists ([see here](https://pyth.herokuapp.com/?code=u%7CpbGXGhaf%3EFT.%3AG2%5DZ)Q&input=%5B2%2C%206%2C%209%2C%201%2C%204%2C%207%2C%208%2C%205%2C%203%5D&debug=0)), it give the correct values, which you would expect. ``` implicit: Q = input list u Q set G = Q, update G as long with the following statements, until it stops changing: .:G2 all pairs (G[i],G[i+1]) f>FT filter for pairs T, where T[0] > T[1] a ]Z add to this list of pairs [0] (ensures that the filtered list is always non-empty) h take the first element XG ) translate G by this pair (switches the values T[0] with T[1]) print implicitly at the end ``` [Answer] # JavaScript (ES6) 56 A recursive function that rearranges the given list in place. ``` F=l=>l.some((v,i)=>v>l[++i]&&[l[i-1]=l[i],l[i]=v])&&F(l) ``` Notes * In JS, for any numeric value v : v > undefined == false, v < undefined == false. So going outside the array bounds is not a problem if we use the right comparison * When the array at last is sorted, the function inside 'some' return false and recursion ends * The value returned in case of a swap is a 2 element array, and its value is always 'truthy'. That works even when one or more array elements are 0 * In fact the function works with any numeric input, not only single and not repeated digits. Did not found a way to take advantage from this OP constraint. Test using snippet (in Firefox) - the snippet version output the current list values at each step. ``` F=l=>(log('L='+l), l.some((v,i)=>v>l[++i]&&[l[i-1]=l[i],l[i]=v])&&F(l)) function log(x) { L.innerHTML = L.innerHTML +x+'\n' } function go() { l = I.value.split(/\D+/g).map(x=>x|0) F(l) O.innerHTML = '' + l } go() ``` ``` Unsorted: <input id=I value="2 8 4 7 5 3 9 1 6"><button onclick="go()">-></button> <br>Sorted: <span id=O></span> <br>Operations log:<br> <pre id=L></pre> ``` [Answer] # Javascript (*ES6*), 66 61 53 bytes Thanks to the new rule, I can reduce even further :) ``` f=x=>x.map((a,i)=>a<(b=x[--i])&&f(x,x[i]=a,x[i+1]=b)) // Snippet demo: (Firefox only) f(z=prompt().split(/\D+/).map(x=>+x)) alert(z.join(', ')); ``` ### Commented ``` f=x=> // recursive function f x.map( // map function to array (a, i)=> // a = current value, i = current index a < (b = x[--i]) && // poll value of previous index, compare less than // comparison always false at first index as undefined will always be less f(x, x[i] = a, x[i + 1] = b) // if true, swap values and call f ) ``` [Answer] # C, 183 ``` main(c,d,s){int a[10];for(c=0;c<10;c++)scanf("%d", &a[c]);for (c=0;c<10;c++){for(d=0;d<10-c-1;d++){if(a[d]>a[d+1]){s=a[d];a[d]=a[d+1];a[d+1]=s;}}}for(c=0;c<10;c++)printf("%d", a[c]);} ``` It's not golfed yet, other than variable names. [Answer] # Haskell, 59 bytes ``` s e(h:t)=min e h:max e h:t f l=iterate(init.foldr s[9])l!!9 ``` The function `s` puts an element `e` in front or at the second place of a list depending on if it's less or greater than the first element of the list. Folding `s` into the input list lets the smallest element bubble to the front. I'm folding into a list containing a single `9` which I immediately remove afterwards with `init`, so that I don't have to check for empty lists in `s`. `iterate` repeats the folding process forever creating a list of intermediate results. The final result is the 9th element of this list. [Answer] # Perl, 68 bytes ``` {for(0..7){if($m[$_]>$m[$_+1]){splice@m,$_,2,$m[$_+1],$m[$_];redo}}} ``` Ungolfed code ``` { # Block runs once unless redo is called for (0..7) { # Loop index is in $_ if ($m[$_] > $m[$_+1]) { # Check if swap needed splice @m, $_, 2, $m[$_+1], $m[$_]; # Replace a two element slice of # the array with those # two elements reversed redo # Restart the block over } } } ``` ]
[Question] [ A ragged matrix, is a matrix that has a different number of elements in each row. Your challenge is to write a program in any favorable language to find the indices of all occurrences of target in the ragged matrix. # Input: A list of ragged lists (can be empty) of positive integers and a target range e.g. `26-56`. The target range, given 2 positive integers. For languages that do not support this type of list, you can input it as a string representation You may assume that `a<=b` # Output: If a number in the ragged list is within the range or equal to `a` or equal to `b`, output the index of the ragged list then the index of the number in that ragged list e.g. `0 4` - The `0` is the first ragged list in the input and the `4` is the index of the number in the first ragged list # Test cases: ``` [[[1,3,2,32,19],[19,2,48,19],[],[9,35,4],[3,19]],19-53] -> [[0,3],[0,4],[1,0],[1,2],[1,3],[3,1],[4,1]] [[[1,2,3,2],[],[7,9,2,1,4]],2-2] -> [[0,1],[0,3],[2,2]] ``` You can choose to follow the output format above or output it in the following as well: ``` [[[1,3,2,32,19],[19,2,48,19],[],[9,35,4],[3,19]],19-53] -> 0 3 0 4 1 0 1 2 1 3 3 1 4 1 ``` 0-based and 1-based indexing is allowed You can output your answers in any way as long as it is distinguishable what the indexes of the number and matrix are You may assume the integers in the list are always positive and non-zero This is code-golf, so shortest code wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 23 bytes ``` Position[a_/;#<=a<=#2]& ``` [Try it online!](https://tio.run/##JYvBCsIwEETv/Y1AUViRbFo02Mh@Qu@lSBCLObSFmtuSb48bAnOYGd5bffx@Vh/D2@fF5XH/hRj2bfKv60MNzg9O4dzm8QhbnFipdHmeFiKFZ1JzS0TcMLMGAwgGQdsErK2M7l6HxILpoZNiylWB3kipKha5kjcoqhZYBsqbmpT/ "Wolfram Language (Mathematica) – Try It Online") Input `[a, b][list]`. Returns 1-indexed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` r/iⱮⱮŒṪ ``` [Try it online!](https://tio.run/##y0rNyan8/79IP/PRxnVAdHTSw52r/v//H21oqWNqHPs/OtpQx1jHSMfYSMfQMlYHJGykY2IB4QCRpY6xqY4JkGEMEooFAA "Jelly – Try It Online") ## Walkthrough ``` / Reduce input range list by r range ⱮⱮ Foreach at depth 2 (on the right argument) i Find first index of RHS in LHS (Or, in this case, checks whether current item (RHS) is within range (LHS)? ) ŒṪ All truthy multidimensional indices ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes Full program. Prompts for range, then array. ``` ⍸↑⎕∊¨…/⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@P@rd8ahtIlDwUUfXoRWPGpbpA9n/gVL/FcCggMvQUsHUmAso6hXs76ceHW2oY6xjpGNspGNoGasTbWgJ5JhYQDhAZKljbKpjAmQYg4Ri1blgxhgpGKEYYgQyBqLHXAdkiCFQW6w6AA "APL (Dyalog Extended) – Try It Online") Explained from the right: `⎕` prompt (for range) `…/` reduce using the range function (gives enclosed list of all number in the range) `∊¨` check if the elements of each of the following lists are in the entire (because it is enclosed) range:  `⎕` prompt for array `↑` mix list of Boolean lists into a matrix, padding with Falses `⍸` indices of Trues [Answer] # [R](https://www.r-project.org/), 87 bytes Or **[R](https://www.r-project.org/)>=4.1, 80 bytes** by replacing the word `function` with a `\`. ``` function(l,a,b,`[`=lapply)cbind(rep(seq(l),lengths(w<-l[`%in%`,a:b][which])),unlist(w)) ``` [Try it online!](https://tio.run/##TY1dCsIwEITfe40iZGEEk1S0ol4kBPpjawMhVlspnr5uikIf9tudgZ15ze1lbt@hHt0jCI8SFQpTXHzZ9/5DdeXCTbyaXgzNU3iCb8J97AYxnbfeFBsXNgXKU2XN1Lm6s0R4B@@GUUxEcyuWsxYSGgpaQeYEljmr7PhTcXLoPbJ46egSA3tNSbq9JqkxO2gLZsaU2C1UC6PPL8yMaZNk1ali67/hgFgquYR4q1W0XKJjEPvWzl8 "R – Try It Online") --- Solution shorter in [R](https://www.r-project.org/)>=4.1: ### [R](https://www.r-project.org/), 92 bytes Or **[R](https://www.r-project.org/)>=4.1, 78 bytes** by replacing two `function` occurrences with `\`s. ``` function(l,a,b)cbind(rep(seq(l),lengths(w<-lapply(l,function(x)which(x%in%a:b)))),unlist(w)) ``` [Try it online!](https://tio.run/##TY1dCoMwEITfvYYIu7AFkyitpe1FxAe1WgMhtf6gPb3dhLYYyJedITszbO11a2dbT/ppwVBJFdaVtncYmh7G5gUGyTT2MXUjLJeDKfvevPnjf2fFpdN1B2ukbVSeK@RDszV6nGBB3FrwYw2CFElSkkSGxDJjlZy@yt2MVEqJm5RzkUGpwiA83IIwz2NSBTETpqDYU3o6n1eYCbMIgl2ndK2/hiO5UsElyK/cRQsf7YLYL4rtAw "R – Try It Online") --- Outgolfed by [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). See [that answer](https://codegolf.stackexchange.com/a/241887/55372) for a detailed explanation and comparison of our approaches. [Answer] # [Python 3](https://docs.python.org/3/), 69 bytes ``` lambda l,r,e=enumerate:[[X,Y]for X,x in e(l)for Y,y in e(x)if y in r] ``` [Try it online!](https://tio.run/##JczBCoQgAATQe1/hUWEuZsG64H8UrgdjdTcwCzGor3dtgznMm8NsZ/6uUZSgtOYQaCFacGmguazoHjdqJESPrhZxTaaxistmUr1ovHqVYJfpbUlAglMu7otLNrun1gNG49dEBhxkjsTRwC6OOG8ebPbk35MpW5pjpp7WGxs/jlpMjLHyAw "Python 3 – Try It Online") -3 thanks to @tsh [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` {+&~(y+!2)'x} ``` [Try it online!](https://ngn.codeberg.page/k#eJw9jtFugzAMRd/zFZk0baCGEtthLUTaV/QNRSqiQFFb2IBJVFX77XPotCi+smPf49TZbfX2CK6rFwzf57sQu+z2ml8fQ1bLtZztvj/ZYF8X7dnO9mqH0N3FLg8CkCRREkpILaScmq1PX7RNJSXSWOIy9K2EQhtoSVbzK0jNgRzkJ6yRELo/IHqkJ2ykB4I0oUWJixusJ/jKCT6xOE7T15jFcdkfqqY/1+txKspTNZfHomuqddlf4u+fapzavhtjNLA1H/FQNE11iC7FNLRz1HaHam67RuR5DooUKkIFqVM5pFyY7bPgmypKlOGE/JNjiRJyIvpkq1bEDb20QelFcVF6GlgNK3972YN+0xO7UX4PsNUpjPAfCAvQ25FH3S9U+Gh4) Takes the ragged matrix as `x` (first arg, a list of lists) and the range as `y` (second arg, a pair of integers). * `(y+!2)` convert the range from e.g. `19 53` to `19 54` (to do a `[lb;ub]` comparison rather than `[lb;ub)`) * `(...)'x` do a binary lookup of `x` in the list generated by `(...)`. if a value in `x` is between the (adjusted) indices, `0` is returned * `~` not the above; values within the range become `1` and all others `0` * `&` use "deep-where" to return indices of 1's * `+` transpose the result It's likely that the final `+` (transpose) can be elided depending on what constitutes acceptable output. [Answer] # [R](https://www.r-project.org/), 78 bytes ``` function(l,a,b)cbind(rep(seq(l),L<-lengths(l)),sequence(L))[unlist(l)%in%a:b,] ``` [Try it online!](https://tio.run/##TY1bCoMwFET/3YYIuTAFkyitpe0K3IHkQ21sAyFtfazf3kgLfuQkcyAz4zpc12EJ/exeQXi06KjvXLiL0b7FZD/CE@rLwdvwmJ8TJwLbxYbeipqoWYJ308w@cyFrzx3MOohN9UJCQ0EryIrAseJUnH4pngq6RBFfOlpioNSUpIdbkjZNDm3ALJgS@Ua1MXr@wiyYJkl2myqu/heOiKOSR4hvtauWW3UsYm/M@gU "R – Try It Online") Originally posted as a comment on [pajonk's answer](https://codegolf.stackexchange.com/a/241854/67312), so uses that test harness. That answer is a very natural way to approach the problem in R, so if I hadn't peeked first, I probably wouldn't have found this gem. Using R-style indexing, a single value in `l` is `l[[i]][j]`, i.e., the `j`th (vector) element of the `i`th element of the list `l`. pajonk's answer generates a list of all the indices `j` for each `i` such that `l[[i]][j] %in% a:b` and then joins them with an appropriately-sized list of `i`, as below: ``` function(l,a,b){ in_ab <- sapply(l,`%in%`,a:b) # for each element of l, return TRUE/FALSE where elements are in a..b j_idx_list <- sapply(in_ab,which) # now return the 1-based indices of the TRUE values j_idx <- unlist(j_idx_list) # and collapse into a single vector i_lengths <- lengths(j_idx_list) # take the # of valid j-indices in each sublist i_idx <- rep(seq(l),i_lengths) # and generate i-indices to match cbind(i_idx,j_idx) # and combine } ``` This answer instead uses some functions rarely used in golfing, `sequence` and `lengths` to generate all the valid pairs `i,j` and then filters them directly. In fact, `sequence` is such an odd function in R that the docs used to say1 that "it mainly exists in reverence to the very early history of R", as I have [mentioned before](https://codegolf.stackexchange.com/a/167578/67312). Ungolfed a bit: ``` function(l,a,b){ L <- lengths(l) # find the lengths of each element of l j_idx <- sequence(L) # for each Length h, generate 1..h and append them together in order i_idx <- rep(seq(l),L) # replicate each of 1..length(l) times equal to the length of l[[i]] filter_idx <- unlist(l)%in%a:b # index for filtering cbind(i_idx,j_idx)[filter_idx,] # combine i,j indices as columns of a matrix, and filter the rows } ``` 1 Starting in version 4.0.0, `sequence` was updated to accept a `from` and `by` argument, much like `seq`, and this line was removed. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 (or 7?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` εNUεIŸsåiXN‚? ``` First input is the matrix; second the range as pair of integers. Outputs pairs of 0-based indices without delimiter to STDOUT. [Try it online](https://tio.run/##yy9OTMpM/f//3Fa/0HNbPY/uKD68NDPC71HDLPv//6OjDXWMdYx0jI10DC1jdaINLYEcEwsIB4gsdYxNdUyADGOQUCwXSIGpcex/Xd28fN2cxKpKAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCuu6hhWH/z231Cz23NfLojuLDSzMj/B41zLL/X1tbe2ib/f9oIDDUMdYx0jE20jG0jNWJNrQEckwsIBwgstQxNtUxATKMQUKxOkqGlrqmxkqxOgpgrUYgzRCV5jogrYZAxUBVRrpGSrGx/3V18/J1cxKrKgE). Not sure if this is a valid output-format: ``` ŸIåεƶ0K ``` First input is the range as pair of integers; second the matrix. Outputs the 1-based truthy indices of each row. [Try it online](https://tio.run/##yy9OTMpM/f//6A7Pw0vPbT22zcD7//9oQ0sdU@NYruhoQx1jHSMdYyMdQ8tYHZCwkY6JBYQDRJY6xqY6JkCGMUgo9r@ubl6@bk5iVSUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCuu6hhcVh/4/uiDy89NzWY9sMvP/X6vyPBgJDHWMdIx1jIx1Dy1idaENLIMfEAsIBIksdY1MdEyDDGCQUq6NkaKlraqwUq6MA1moE0gxRaa4D0moIVAxUZaRrpBQbCwA). **Explanation:** ``` ε # Map over each row of the (implicit) first input-matrix: NU # Store the row-index in variable `X` ε # Map over each integer in the row: I # Push the second (implicit) input-pair Ÿ # Convert it to an inclusive ranged list såi # If the current integer is in this list: XN‚ # Pair `X` with the inner map-index ? # Pop and output it Ÿ # Convert the (implicit) first input-pair to an inclusive ranged list I # Push the second input-matrix å # Check for each inner-most value if it's within this range ε # Map over these integers: ƶ # Multiply each value by its 1-based index 0K # Remove all 0s # (after which the list of lists is output implicitly) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔⮌I⪪η-η≔…·⊟η⊟ηηFLθF⌕AE§θι№ηκ¹I⟦⟦ικ ``` [Try it online!](https://tio.run/##LU7BCsIwDL37FWWnFLJDrQPHTkMQBAXRY@mhbHUtlm6uc/j3tZtCIHkv772kMWpseuVirEOwnYebnvUYNBxUmOA@ODuBQZLlGaUUiaHV5i88@ca9g531TflOw7UfwCTFr/@lj34kcNa@mwy8KCUrPlrf1s7BRQ1QTyff6g@8kNjkOfRvv957LgksOa6jTcz6jBA2LaSktIpRCMGQ4xb5FlkpUbAygd3@B1KVyAvcpYEvlMSMlXnBMxnz2X0B "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⮌I⪪η-η≔…·⊟η⊟ηη ``` Convert the second input into a range. ``` FLθ ``` Loop over the sublists. ``` F⌕AE§θι№ηκ¹ ``` Loop over the indices where the element lies within the range. ``` I⟦⟦ικ ``` Output the outer and inner indices on separate lines double-spaced between each pair of indices. [Answer] # [Factor](https://factorcode.org/), 71 bytes ``` [ '[ [ _ _ between? ] arg-where ] map <enumerated> expand-values-push ] ``` [![enter image description here](https://i.stack.imgur.com/zJIi2.gif)](https://i.stack.imgur.com/zJIi2.gif) ## Explanation * `'[ [ _ _ between? ] arg-where ] map` Map the indices inside the range to each row of the ragged matrix. * `<enumerated>` Zip a list with its indices. * `expand-values-push` Combine each key with each of the elements in its value, collecting the results in a single list of pairs. ``` ! { { 1 3 2 32 19 } { 19 2 48 19 } { } { 9 34 4 } { 3 19 } } 19 53 '[ [ _ _ between? ] arg-where ] map ! { V{ 3 4 } V{ 0 2 3 } V{ } V{ 1 } V{ 1 } } <enumerated> ! { { 0 V{ 3 4 } } { 1 V{ 0 2 3 } } { 2 V{ } } { 3 V{ 1 } } { 4 V{ 1 } } } expand-values-push ! V{ { 0 3 } { 0 4 } { 1 0 } { 1 2 } { 1 3 } { 3 1 } { 4 1 } } ``` [Answer] # [JavaScript (V8)](https://v8.dev/), ~~58~~ 56 bytes ``` (a,l,r)=>a.map((x,i)=>x.map((y,j)=>l>y|y>r||print(i,j))) ``` [Try it online!](https://tio.run/##JchRCoMwEATQ62xgLMRVMB/mIsGPRRAitoRUxEDunm4RhmHe7HLJd80xnd01tW1uJDiQzezl9ZZEdCMq7gcFu@LwpRafa005fk6KehrTNgrBgtGDe1i3IFinGKYHGgceMejg/7VoYWTTfg "JavaScript (V8) – Try It Online") *Saved 2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563).* [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` ṫ÷r£hƛ¥vc;ÞT ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyIiLCIiLCLhuavDt3LCo2jGm8KldmM7w55UIiwiIiwiW1tbMSwzLDIsMzIsMTldLFsxOSwyLDQ4LDE5XSxbXSxbOSwzNSw0XSxbMywxOV1dLFsxOSw1M11dIl0=) Needs input in form: `[<main_arr>, [a, b]]` ``` ṫ # Get [a, b] ÷r # Get range a..b £ # Set to register h # Main array ƛ # Begin map ¥ # Push register vc # Is item inside range (vectorized) ;ÞT # Close map and print truthy indices ``` [Answer] # Python3, 80 bytes ``` lambda l,a,b:[ [X,Y] for X,x in enumerate(l) for Y,y in enumerate(x) if a<=y<=b] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PycxNyklUSFHJ1EnySpaITpCJzJWIS2/SCFCp0IhM08hNa80N7UosSRVI0cTLB6pU4kqXqGpkJmmkGhjW2ljmxT7/z8A) [Answer] # [Scala](https://www.scala-lang.org/), 112 bytes for a 2d matrix, find all indices where element is between the Range. --- Golfed version. [Try it online!](https://tio.run/##VZAxT8MwEIX3/oobbclUSkMlYujAWIkBERBDlMFNnPQq1ymOQQlRfnu4GKWCwWfd905@z9cWyqipOZx04eG598fGvjbpDGFYAZS6grNCy5SrWwmPzqk@S71DW@dcwptFD7swCfClDBgJT9j6LJS99XlO8tywUCIBsYANVTpRwsWvFiUB3t79hctNWrwlcenjMMSvlkoCGZFNlFzZYWHbeJq/UDEjU/2RzSekEk6@KFtrvhuqxg2sE8gfbsz6Gy/v6I97W@runvXiRLT7RwErcOuisZ7W0rKejz1qUwI9zZDmx2kOcaENeWMZGQtQ8Gk9UqqQelyN0w8) ``` def f(l:Seq[Seq[Int]],r:Range)={for{(x,i)<-l.zipWithIndex;(y,j)<-x.zipWithIndex if r.contains(y)}yield Seq(i,j)} ``` Ungolfed version. [Try it online!](https://tio.run/##bVDLTsMwELznK@ZoS6ZSCJVIBAeOlTggCuJQ5eDmVVfGqRyDElC@PWwcEqjg4LU9M6ud2SaTWg5DvT8WmcND5w61eaq3I4rPAMiLEq9SGSZt1SS4s1Z2u62zylQpT/BslMOtVwLvUkMnuFeN2/myMS5NiR4/zJdQIBK4pEonjLmYuDD24NX1b3C@iYvWRM7/yIv4MlImoEE0JowXbD9j6yjw4JijZH/dCdgEj9JUBf/P@RQMKGu7vAHWCiiOmwvo1Yc6vSh32Ji8aH8EncDRC9ozAVQJu8pq42ilDev4d0ePThU6n/KpsdcT/eT9RNt22jDyLyDxZpyihH4DfdAHw/AF) ``` object PythonToScala { def main(args: Array[String]): Unit = { val l: List[List[Int]] = List(List(1, 3, 2, 32, 19), List(19, 2, 48, 19), List(), List(9, 35, 4), List(3, 19)) val a: Int = 19 val b: Int = 53 def f(l: List[List[Int]], r: Range): List[List[Int]] = { for { (x, i) <- l.zipWithIndex (y, j) <- x.zipWithIndex if r.contains(y) } yield List(i, j) } println(f(l, a until b)) } } ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/18435/edit). Closed 6 years ago. The community reviewed whether to reopen this question 2 years ago and left it closed: > > Original close reason(s) were not resolved > > > [Improve this question](/posts/18435/edit) Let a function receive two integers `i` and `j` between `0` and `3`, it should return the value in position `(i,j)` in the following 2D array: ``` 1, 0, -1, 0 1, 0, -1, 0 0, 1, 0, -1 0, -1, 0, 1 ``` Shortest code in any variant of C / C++ wins. [Answer] # 40 ``` f(i,j){return~-(2434352710>>8*i+2*j&3);} ``` A hackish **35** solution (xxd dump): ``` 0000000: 6628 692c 6a29 7b72 6574 7572 6e7e 2d28 f(i,j){return~-( 0000010: 695b 2246 4619 9122 5d3e 3e32 2a6a 2633 i["FF.."]>>2*j&3 0000020: 293b 7d );} ``` If proper octal escapes are used, it's the same **40** characters: ``` f(i,j){return~-(i["FF\31\221"]>>2*j&3);} ``` [Answer] # C99, 34 ``` f(i,j){return(i<3?1-j+i/2:j-2)%2;} ``` [Answer] ## 32 ``` f(i,j){return~-(j+2-i*i/3&3)%2;} ``` [Answer] # C, 29 I know this one seems kinda unfair but does it actually work for anyone? ^\_^ ``` f(i,j){j=("&&4+"[i]>>j)%3-1;} ``` [Answer] # 38 ``` f(i,j){return(i/2+j+1)*(1-(i-j&2))%2;} ``` # 37 ``` f(i,j){return(i/2+j+1)*-~-(i-j&2)%2;} ``` [Answer] # C++, ~~70~~, ~~45~~, 44 ``` f(i,j){return(j/2&i^~i&~j>>1)*~-(j-i&2)%2;} ``` The Karnaugh map approach, mixed with a bit of fsw's solution. If A is (j>>1) and D is (i&1), the function should return "-~-(j-i&2)%2" (fsw's solution) multiplied by the Karnaugh map ~A~D + AD. I feel there is a better solution for this using the Karnaugh map, but it's too late to think of it. Maybe tomorrow :) Thanks for the comments, shaved off many chars. [Answer] # C# ``` int f(int i,int j){return "2101210112101012"[i*4+j]-49;} ``` [Answer] # 48 ``` f(a,b){return 10308>>4*a+b&1?-1:43605>>4*a+b&1;} ``` [Answer] ## C, 45 ``` f(i,j){i=i+(j>1)*(7-2*j)&3;return i&1?0:1-i;} ``` ]
[Question] [ For context, this problem is based on a old chat-bot project I did. # Problem: Given a string of words containing any of the characters: ``` " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" ``` Find the frequency of each triplet of words. All non-alphanumeric characters should be ignored, and input/output will be case-insensitive. For this challenge, the "triplets" of a phrase are each consecutive chunk of 3 words along the string. For example, in the string ``` "Oh hi there guy. What's up? Oh hi there." ``` The "triplets" of the string are ``` [["oh", "hi", "there"], ["hi", "there", "guy"], ["there", "guy", "whats"], ["guy", "whats", "up"], ["whats", "up", "oh"], ["up", "oh", "hi"], ["oh", "hi", "there"]] ``` The frequency of each triplet is 1, except for `["oh", "hi", "there"]`, which appears twice. # Input Input will be a string of space-delimited "words" that may contain any of the characters mentioned above. Although punctuation is to be ignored, it must be handled. You can assume the input will always contain at least 3 words, and that there won't be consecutive whitespace. # Output Output can be anything that shows the frequency of each triplet. For the string "Oh hi there guy.", possible outputs could be: ``` {"oh hi there":1, "hi there guy":1} ["oh hi there", 1, "hi there guy", 1] "oh hi there|1 hi there guy|1" ^ Or any other delimiter ``` # Test Cases (Output order doesn't matter): ``` "Oh hi there guy. What's up? Oh hi there." {["oh" "hi" "there"] 2, ["hi" "there" "guy"] 1, ["there" "guy" "whats"] 1, ["guy" "whats" "up"] 1, ["whats" "up" "oh"] 1, ["up" "oh" "hi"] 1} "aa aa aa aa" {["aa" "aa" "aa"] 2} "aa bb a bb a bb a cc a bb a" {["aa" "bb" "a"] 1, ["bb" "a" "bb"] 2, ["a" "bb" "a"] 3, ["bb" "a" "cc"] 1, ["a" "cc" "a"] 1, ["cc" "a" "bb"] 1} "99 bottles of beer" {["99" "bottles" "of"] 1, ["bottles" "of" "beer"] 1} "There are two main types of chatbots, one functions based on a set of rules, and the other more advanced version uses artificial intelligence. The chatbots based on rules, tend to be limited in functionality, and are as smart as they are programmed to be. On the other end, a chatbot that uses artificial intelligence, understands language, not just commands, and continuously gets smarter as it learns from conversations it has with people." {["main" "types" "of"] 1, ["rules" "and" "the"] 1, ["of" "chatbots" "one"] 1, ["to" "be" "limited"] 1, ["artificial" "intelligence" "understands"] 1, ["it" "has" "with"] 1, ["chatbots" "based" "on"] 1, ["smarter" "as" "it"] 1, ["the" "chatbots" "based"] 1, ["other" "more" "advanced"] 1, ["commands" "and" "continuously"] 1, ["chatbots" "one" "functions"] 1, ["tend" "to" "be"] 1, ["a" "chatbot" "that"] 1, ["continuously" "gets" "smarter"] 1, ["advanced" "version" "uses"] 1, ["functionality" "and" "are"] 1, ["are" "two" "main"] 1, ["based" "on" "rules"] 1, ["on" "a" "set"] 1, ["there" "are" "two"] 1, ["the" "other" "more"] 1, ["just" "commands" "and"] 1, ["the" "other" "end"] 1, ["that" "uses" "artificial"] 1, ["based" "on" "a"] 1, ["limited" "in" "functionality"] 1, ["smart" "as" "they"] 1, ["are" "as" "smart"] 1, ["from" "conversations" "it"] 1, ["other" "end" "a"] 1, ["intelligence" "the" "chatbots"] 1, ["functions" "based" "on"] 1, ["in" "functionality" "and"] 1, ["intelligence" "understands" "language"] 1, ["chatbot" "that" "uses"] 1, ["more" "advanced" "version"] 1, ["gets" "smarter" "as"] 1, ["rules" "tend" "to"] 1, ["on" "rules" "tend"] 1, ["as" "it" "learns"] 1, ["are" "programmed" "to"] 1, ["and" "the" "other"] 1, ["understands" "language" "not"] 1, ["and" "are" "as"] 1, ["of" "rules" "and"] 1, ["has" "with" "people"] 1, ["end" "a" "chatbot"] 1, ["set" "of" "rules"] 1, ["and" "continuously" "gets"] 1, ["as" "they" "are"] 1, ["they" "are" "programmed"] 1, ["as" "smart" "as"] 1, ["two" "main" "types"] 1, ["a" "set" "of"] 1, ["uses" "artificial" "intelligence"] 2, # <----- 2 Here ["it" "learns" "from"] 1, ["be" "limited" "in"] 1, ["programmed" "to" "be"] 1, ["types" "of" "chatbots"] 1, ["conversations" "it" "has"] 1, ["one" "functions" "based"] 1, ["be" "on" "the"] 1, ["not" "just" "commands"] 1, ["version" "uses" "artificial"] 1, ["learns" "from" "conversations"] 1, ["artificial" "intelligence" "the"] 1, ["to" "be" "on"] 1, ["on" "the" "other"] 1, ["language" "not" "just"] 1} ``` Your submission can be a function or full program, and can take input via stdin, or as an argument. It may output by returning, or printing to the stdout. This is code golf, so the shortest number of bytes wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 13 bytes ``` ŒlḲf€ØBṡ3ṢŒr' ``` A monadic link (function) that returns a list, each entry contains a list of 3 lists of characters (the words) and a count. **[Try it online!](https://tio.run/nexus/jelly#@390Us7DHZvSHjWtOTzD6eHOhcYPdy46OqlI/f/hdm@gIAhH/v@v5J@hkJGpUJKRWpSqkF5aqacQnpFYol6sUFpgr4Akp6cEAA)** - the footer formats the results (as a full program everything just gets smushed together by the implicit print). ### How? ``` ŒlḲf€ØBṡ3ṢŒr' - Main link: s Œl - convert s to lowercase Ḳ - split on spaces ØB - base digit yield "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" f€ - filter keep for €ach ṡ3 - all overlapping slices of length 3 Ṣ - sort ' - call the previous monadic link without vectorising Œr - run length encode ``` [Answer] # [Perl 6](https://perl6.org), ~~67~~ 57 bytes ``` *.words.map({[~] .lc.comb(/\w/)}).rotor(3=>-2)».join(' ').Bag.perl ``` [Try it](https://tio.run/nexus/perl6#fZHNitRAEMfveYo6yCaRsQcUhGXYFXyBPSh4cEUqnUrSS3@E7uoZw7K@mDdfbKyezOichCRU6uP//3V1TgT790rvKrfAjQ49wd3xtTqE2CflcG6ev/78BspqpYPrmu3jYdu@tCoGDrF5d3f/5m37@5d6CsY3NdSt@oijmina464aQgRrPKWmhecKwNMPhuwtpQTbx0/bneTmzHAyffX98lvX1cvxYYLJAE8UCca8KPgyIdcJ8vwBrmqqQoTLU@Kug@uP1ueour2FLjCLOYQBOqJYVZ9P8igvHwI4NB54mdcOLX4ykDYQPMGQvWYTfIIOE/WSE91EXDpjFtENoO8LE4QCBi4U5X6PXkv7nmKSachJxDGyGYw2aMF4JmvNSNKlQHD@2v7zOcszFf0g5LJTZ1iKgnvhQmt4WRnKcTBBcuJTAsFZTsk5hjGic3TWUfDgr4hFf1M2tgJIAfm/vBu5yl7OxWKawKIfM46S9TL8lFO5VudKbcXSwbPxOeRkFxiJz4RiLIyGwRJGWe8Qgyu9ZWO4blyKk/QcDE8wU5it3Pof "Perl 6 – TIO Nexus") ``` *.words.rotor(3=>-2).map({lc S:g/<-:L-:N-:Z>//}).Bag.perl ``` [Try it](https://tio.run/nexus/perl6#fZFNa9tAEIbv@hVzKLFd7BW0UIjdpNBzSA4pFEqhjFYjacN@iN1ZuyLkt7uzkd34FJDEaD7e99nZnAj2X5TeVW6CKx1agpvjR3UIsU0qBg5x@fnmdvNppRyOy2er4XHb118327vN9n6z/XVb1y8r9R17NVK0x13VhQjWeErLFTxXAJ7@MmRvKSWofz/WO8mNmaFYLT/8WZ3/F4vq5fgwwGCAB4oEfZ4U/ByQFwny@A0uaqpChPNT4qaBy4/Wp6i6voYmMIs7hA4aolhVP17lUV4@BHBoPPA0zh1a/GQgrSF4gi57zSb4BA0maiUnuom4dMYsomtA3xYmCAUMXCjK7R69lvY9xSTTkJOIY2TTGW3QgvFM1pqepEuB4Py3ffM5yTMV/SDkslRnWIqCe@ZCa3iaGcpxMEFy4lMCwZlek2MMfUTn6KSj4MFfEIv@umxsBpAC8ru8a7nLVs7FYprAou8z9pL1MvyUU7lX50ptxtLBs/E55GQn6IlPhGIsjIbBEkZZbxeDK71lYzhvXIqD9BwMDzBSGK3c@j8 "Perl 6 – TIO Nexus") ## Expanded: ``` *\ # WhateverCode lambda (this is the parameter) .words # get a list of words .rotor( 3 => -2 ) # grab 3, back up 2, repeat .map({ # take those list of 3 elements lc # lower case the following S # remove :global # globally / <- :L # not a letter - :N # not a number - :Z # not a space (inserted when the current list is stringified) > // }) .Bag # turn it into a Bag .perl # return the structure as an `EVAL`able Str ``` returns something like ``` ("bb a cc"=>1,"aa bb a"=>1,"a cc a"=>1,"a bb a"=>3,"bb a bb"=>2,"cc a bb"=>1).Bag ``` [Answer] # [Retina](https://github.com/m-ender/retina), 50 bytes ``` T`lLd p`lld _ M!&`(\b\w+ ??){3} O` $ ¶ D` ¶+ :$.&¶ ``` [Try it online!](https://tio.run/nexus/retina#@x@SkOOTolCQkJOTohDP5auolqARkxRTrq1gb69ZbVzL5Z/ApcJ1aBuXSwKQ1OayUtFTO7Tt/3//DIWMTIWSjNSiVIX00ko9hfCMxBL1YoXSAnsFJDk9AA "Retina – TIO Nexus") ### Explanation ``` T`lLd p`lld _ ``` Replace all uppercase letters with lowercase ones, keep other letters, digits and spaces unchanged and delete other characters. ``` M!&`(\b\w+ ??){3} ``` Find all possible matches of three words in a row. ``` O` ``` Sort the matches, so equal triplets end next to each other. ``` $ ¶ ``` Add a newline at the end. ``` D` ``` Remove duplicate lines (this will keep the newlines at the end of them). ``` ¶+ :$.&¶ ``` Sequences of newlines are now the counts we need, replace them with a delimiter (`:`) followed by the count and a newline. [Answer] # [Ruby](https://www.ruby-lang.org/), 60 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` ->s{s.upcase.gsub(/[^A-Z0-9 ]/,'').split.each_cons(3).tally} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3bXTtiquL9UoLkhOLU_XSi0uTNPSj4xx1owx0LRVi9XXU1TX1igtyMkv0UhOTM-KT8_OKNYw19UoSc3Iqa6FmpBYouEUr-WcoZGQqlGSkFqUqpJdW6imEZySWqBcrlBbYKyDJ6SnFcoHVJyYqwBCSUFKSAjKRnAxlKcVCLFuwAEIDAA) [Answer] # Mathematica, 75 bytes ``` Tally@Partition[ToLowerCase@#~StringSplit~RegularExpression@"[_\\W]+",3,1]& ``` Pure function taking a string as input and returning a list of ordered triples of strings together with their number of appearances. For example, on the input `"aa bb a bb a bb a cc a bb a"` the output is `{{{"aa", "bb", "a"}, 1}, {{"bb", "a", "bb"}, 2}, {{"a", "bb", "a"}, 3}, {{"bb", "a", "cc"}, 1}, {{"a", "cc", "a"}, 1}, {{"cc", "a", "bb"}, 1}}`. The expression `RegularExpression@"[_\\W]+"` recognizes all runs of one or more non-word characters (that's what `\\W` does, except it calls `_` a word character whereas we don't want to). `ToLowerCase@#~StringSplit~` then splits the input string at all of those runs, after converting all letters to lowercase. `Partition[...,3,1]` partitions the resulting list into all triples of consecutive words, and `Tally` does exactly what we want to that list of triples. [Answer] # Java 8, ~~376~~ 372 bytes ``` import java.util.*;public interface T{static void main(String[]k)throws Exception{String s="";int c;while((c=System.in.read())>10)if(c==32|(""+(char)c).matches("[A-Za-z]"))s+=(char)c;k=s.toLowerCase().split(" ");Map<String,Integer>o=new HashMap<>();for(int i=0;i<k.length-2;i++){s=k[i]+" "+k[i+1]+" "+k[i+2];o.put(s,(o.containsKey(s)?o.get(s):0)+1);}System.out.print(o);}} ``` Ungolfed: ``` import java.util.HashMap; import java.util.Map; public interface T { static void main(String[] k) throws Exception { String s = ""; int c; while ((c = System.in.read()) > 10) if (c == 32 | ("" + (char) c).matches("[A-Za-z]")) s += (char) c; k = s.toLowerCase().split(" "); Map<String, Integer> o = new HashMap<>(); for (int i = 0; i < k.length - 2; i++) { s = k[i] + " " + k[i + 1] + " " + k[i + 2]; o.put(s, (o.containsKey(s) ? o.get(s) : 0) + 1); } System.out.print(o); } } ``` Never use Java for actual golfing. **EDIT**: Saved 4 bytes by abusing the fact that the main method has a `String[]` as its parameter so I don't have to initialize one >:-) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 20 bytes ``` žLðìÃ#Œ3ù©Ùvyðý®y¢‚ˆ ``` [Try it online!](https://tio.run/nexus/05ab1e#@390n8/hDYfXHG5WPjrJ@PDOQysPzyyrBIrsPbSu8tCiRw2zTrf9/5@YqJCUpIBMJCdDWV/z8nWTE5MzUgE "05AB1E – TIO Nexus") **Explanation** ``` žL # push a string of alphanumeric characters ðì # prepend a space à # keep only those characters from input # # split on spaces Œ3ù # get all sublists of length 3 © # save a copy in register Ù # remove duplicates v # for each unique triplet yðý # join the triplet by spaces ®y¢ # count the triplets occurrences in the list saved to register ‚ # pair the string with the count ˆ # push it to global list # output global list at the end of the program ``` [Answer] # [Python](https://docs.python.org/), 143 bytes ``` lambda s:Counter(tuple(''.join(filter(str.isalnum,w))for w in s.lower().split())[i:i+3]for i in range(s.count(' ')-1)) from collections import* ``` **[Try it online!](https://tio.run/nexus/python3#Tcw5DsIwEIXhnlOMaOxhsYToIiEKDkBJARQm2Mmg8SIvijh9iDva93969vSYWbvXW0PuLqH6YpIsNbKRQqhPIC8tcRtzSYqyZl/dbkK0IcEE5CErDtPSUeXIVCTinTraHp9NUBNJ@8HIrPp2LwUI3B8QVzYFB31gNn2h4DOQiyGVzRwTLc7K9XWEkaCMJhkY6lfBbdRFZKjxDH9NrRHnHw "Python 3 – TIO Nexus")** Unnamed function which returns a dictionary (specifically a Counter object) which has keys that are tuples of the triples (in the correct order) and values that are their counts. [Answer] # [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 117 bytes ``` s=[^\ ]* p=s/^$s\ // tr A-Z a-z|tr -cd \ a-z0-9|sed "p;$p;p;$p"|sed "s/\($s $s $s\) /\1\n/g"|grep ' .* '|sort|uniq -c ``` [Try it online!](https://tio.run/nexus/bash#TYxBCsIwFET3PcVQAtVCEl1KKeIJXAr6LRQbmm7amJ8ulNw9troRhsc8BiZxfWsI9zJzNetGMEHrLHic5BWtfMelykcHWmUnD5FNh9xVwlUr8p@zpo1gfENbaNrTqPs89t44FFAlisiTD3Eeh@fyl9LZwg4I1niDfn4pXGwbCsbsjvjb1Ac "Bash – TIO Nexus") Input on stdin, output on stdout. Sample run: Input: ``` Oh hi there guy. What's up? Oh hi there. ``` Output: ``` 1 guy whats up 1 hi there guy 2 oh hi there 1 there guy whats 1 up oh hi 1 whats up oh ``` [Answer] # JavaScript (ES6), 124 ``` s=>s.toLowerCase().replace(/\S+/g,x=>t.push(x.replace(/[\W_]/g,''))>2&&(k[t]=-~k[t],t.shift()),t=[],k={})&&JSON.stringify(k) ``` Note that the output *shows* the frequency of each triplet, as requested. If the output could just *contain* the frequency data in a machine usable format, I could save 16 bytes of `JSON.stringify()` *Less golfed* ``` s => { s = s.toLowerCase() // force to lowercase t = [] // init current group (or triplet) k = {} // init frequency list s.replace(/\S+/g, x => ( // execute for each sequence of non space chars x = x.replace(/[\W_]/g,''), //remove non alphanumeric chars t.push(x) > 2 // add to end of current group && ( // if there are 3 elements in group (it's a triplet) k[t] = -~k[t], // add to frequency list incrementing count t.shift() // remove first element of current group ) ) return JSON.stringify(k) // return in human readable format } ``` **Test** ``` let F= s=>s.toLowerCase().replace(/\S+/g,x=>t.push(x.replace(/[\W_]/g,''))>2&&(k[t]=-~k[t],t.shift()),t=[],k={})&&JSON.stringify(k) ;["Oh hi there guy. What's up? Oh hi there." ,"aa aa aa aa" ,"aa bb a bb a bb a cc a bb a" ,"99 bottles of beer" ,"There are two main types of chatbots, one functions based on a set of rules, and the other more advanced version uses artificial intelligence. The chatbots based on rules, tend to be limited in functionality, and are as smart as they are programmed to be. On the other end, a chatbot that uses artificial intelligence, understands language, not just commands, and continuously gets smarter as it learns from conversations it has with people."] .forEach(t=>{ O.textContent += t + '\n'+ F(t).replace(/,"/g,'\n"')+'\n\n' }) ``` ``` <pre id=O></pre> ``` [Answer] # JavaScript (ES6), ~~200~~ ~~198~~ 187 bytes *(-2 bytes thanks to Luke)* *(-11 bytes thanks to edc65)* ``` H=(h,k=[],i=0)=>i+2<(z=h.toLowerCase().replace(/[^\w ]|_/g,'').split` `).length?H(h,k.concat(z.slice(i,i+3)+''),-~i):new Set(k.map(a=>a+':'+k.filter(b=>b==a).length)).forEach(m=>alert(m)) ``` A recursive solution. Takes input as a single string and outputs dialog boxes containing each triplet's count in the format `<Triplet>:<Count>`. As always, golfing tips are greatly appreciated. ## Test Snippet ``` H=(h,k=[],i=0)=>i+2<(z=h.toLowerCase().replace(/[^\w ]|_/g,'').split` `).length?H(h,k.concat(z.slice(i,i+3)+''),-~i):new Set(k.map(a=>a+':'+k.filter(b=>b==a).length)).forEach(m=>alert(m)) ``` ``` <input type="text" id="i" value="Oh hi there guy._ What's up? Oh hi there."></input> <input type="button" value="Submit" onclick="H(document.getElementById('i').value)"></input> ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~151~~ 149 bytes ``` s="".join(c for c in input()if c.isalnum()or c==" ").lower().split() k=[tuple(s[i:i+3])for i in range(len(s)-2)] print(*((x,k.count(x))for x in{*k})) ``` [Try it online!](https://tio.run/nexus/python3#TYy9CsIwFEb3PsWli/dWzaCbUHwER4fSoYTYXBuTkB@siM9eUyfhWz7O4SyxrWtxd2xRws0FkMC2zOeExDeQguNgbH4grbBta6hJGPdUAUlEb7h41dR2KXujMHZ84u2xpzXFayoMdlRolMVI@wP1lQ9sEzaI824S0uVyZvr5c/HfzfQhWpaLBs2QtAoKxvwScNVD2kTI/gx/THwB "Python 3 – TIO Nexus") [Answer] # [CJam](https://sourceforge.net/p/cjam), 25 bytes ``` qel"␡{a:0!":,:^-S/3ew$e`p ``` ␡ represents a Delete character (ASCII 127). [Try it online!](https://tio.run/nexus/cjam#@1@YmqNUX51oZaCoZKVjFacbrG@cWq6SmlDw/79/hkJGpkJJRmpRqkJ6aaWeQnhGYol6sUJpgb0CkpweAA "CJam – TIO Nexus") **Explanation** ``` q Read all input el Convert it to all lowercase "␡{a:0!" Push this string :, Map each character in the string to the range of chars up to, but excluding it :^ Reduce the array of ranges with symmetric set differences The result will be an array containing all disallowed characters - Remove all instances of these characters from the input S/ Split the input on spaces 3ew Take overlapping slices of length 3 $ Sort them e` Take the run-length encoding p Print it ``` [Answer] # Python 2, ~~164~~ 159 bytes ``` s=filter(lambda k:k.isalnum()or k==' ',input()).lower().split() k=[tuple(s[i:i+3])for i in range(len(s)-3)] l={} for i in k:l[i]=l[i]+1if i in l else 1 print l ``` Not a really great solution, I know. Pretty straightforward. Thanks to @ovs for saving 5 bytes overall. [Answer] # R, 114 bytes ``` x=readline();y=strsplit(tolower(gsub('[[:punct:]]','',x)),' ')[[1]];s=3:length(y);table(paste(y[s-2],y[s-1],y[s])) ``` Reads input, removes punctuation, splits it into words and counts triplets. [Answer] # [J-uby](https://github.com/cyoce/J-uby), 58 bytes -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` :upcase|~:gsub&''&/[^A-Z0-9 ]/|:split|~:each_cons&3|:tally ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWN62sSguSE4tTa-qs0otLk9TU1dX0o-McdaMMdC0VYvVrrIoLcjJLgLKpickZ8cn5ecVqxjVWJYk5OZVQE1ILFNyilfwzFDIyFUoyUotSFdJLK_UUwjMSS9SLFUoL7BWQ5PSUYrnA6hMTFWAISSgpSQGZSE6GspRiIZYtWAChAQ) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #žLδÃlü3{Åγø ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/112081/52210), so make sure to upvote him as well. [Try it online](https://tio.run/##yy9OTMpM/f9f@eg@n3NbDjfnHN5jXH249dzmwzv@/09MVEhKUkAmkpOhLAA) or [verify all test cases](https://tio.run/##fZI/b9swEMX3fooHZegieOnkLp4LBPBSIEPQ4SSdJQb8I5BHG0LGop@oQdCh6FCjq7@Se7SUxFMASSDvHt/78aCQqDF83ldf/JjlM6rNVH@otlnmXT2db/79uT09Hb/b4@9Pj8cfp5/HX@f67/PmfF9tBwwGMnBk9Hla4W4g@ZiQxw2uequqRkWEl2fZNg2uP227rEp7vUYTRCwnhB0a5liqXy9JpK8cAhwZD5nGWdNqtB5JNYJn7LJvxQSf0FDiTmtqnliKMma1rUG@K3gIhREuFOduT75V@Z5j0tPISc0pitmZ1pCF8cLWmp5VtYLivMa@5Sz2wsU/KDuscUa0qbgvXGSNTDNDuQ4lJKc5ZaE406U4xtBHco4XnxW2/opY/esythlAGyTv8tbIvtN7iYYmWPJ9pl6rXg8/5CRog3OlN2O1wYvxOeRkJ/QsC6EGK6MRWKao493F4Iq2TIzmiWtzUM3ByICRw2j1B/j2Hw). **Explanation:** ``` # # Split the (implicit) input-string by spaces δ # Map over each word: à # Only keep all žL # alphanumeric characters (a-zA-Z0-9) of the word l # Convert everything to lowercase ü3 # Convert it to a list of overlapping triplets { # Sort this list of triplets Åγ # Run-length encode it, resulting in a list of triplets and list of counts # pushed separately to the stack ø # Pair the items in the two lists together # (after which the result is output implicitly) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` ⇩⌈krF3lĊ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6nijIhrckYzbMSKIiwiIiwiXCI5OSBib3R0bGVzIG9mIGJlZXJcIiJd) Outputs a list of `⟨ triplet | count ⟩` ## Explained ``` ⇩⌈krF3lĊ ⇩⌈ # Split the lowercase input on spaces krF # remove all non-alphabet/non-number characters and keep only strings with alphabet letters 3l # group into windows of 3 Ċ # get the count of each triplet. ``` ]
[Question] [ Let's say I've got a list (or array) of: ``` l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` I want to get the third Cartesian power of the above list, where we take every possible triple of elements from `l`. Then I want to filter and only keep the sublists where the sum of that sublist equal to the maximum value of the list. Then I only want one sublist, which is the sublist where the difference of the three numbers that add up to the maximum value is the smallest. The algorithm to see the smallest difference could be something like (in Python): ``` max(v1,v2,v3) - min(v1,v2,v3) ``` So the expected output for this case would be: ``` (3, 3, 4) ``` The order of the elements within the output could be in any order. ## Test cases: ``` l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -> (3, 3, 4) l = [1, 2, 3, 4, 5] -> (1, 2, 2) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] -> (33, 33, 34) l = [1, 4, 5, 2, 3, 9, 8, 7, 10, 6] -> (3, 3, 4) l = [1, 4, 8, 12, 13, 16, 20, 24, 27] -> (1, 13, 13) ``` This is tagged with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! There will always be an output, never would be a case where no 3 elements would add up to the maximum value. [Answer] # [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 83 bytes ``` [ dup supremum swap 3 selections [ Σ = ] with filter [ minmax - abs ] infimum-by ] ``` [Try it online!](https://tio.run/##NU5LTsMwEN3nFO8AtIrdpi0g1ogNG8QqysJxJ62F7RiPoxJQT8N9uFJwSVnNvN/M65ROfZxeX56eH@/gVDoude9a41WmjWYcyFNU1nyqZHrPeKPoyc7OqPyBGEzvA3mdtz928Eb3e5oBp5zjdLl0wQiRUhpDND7hvihEiVrctE1RXaco/5kvCKxRQWKFW@ywRTZvcL4KOwgJsYLYQJaQa8gtzlON/RDAQ37jBgc@qZDjTJb0XL/Gzzce0OBkcpvO2EQxk854pz6wgGo5i8Z3JucX7YhmquBVCHbEkqEtqTj9Ag "Factor – Try It Online") ## Explanation ``` ! { 1 2 3 4 5 } dup ! { 1 2 3 4 5 } { 1 2 3 4 5 } supremum ! { 1 2 3 4 5 } 5 swap ! 5 { 1 2 3 4 5 } 3 selections ! 5 { { 1 1 1 } { 1 1 2 } ... } [ Σ = ] with filter ! { { 1 1 3 } { 1 2 2 } ... } [ minmax - abs ] infimum-by ! { 1 2 2 } ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ 55 bytes ``` l#&@@SortBy[l~Tuples~3,Abs[Max@l-Tr@#]|Max@#-Min@#&] ``` [Try it online!](https://tio.run/##PYxNCoJAAEb3XmPA1Sc4M/61KKb2QqQ7cTGJlqAWOkFheohu0Ak7wqQk7R7fe3y1VOe8lqrMpC7Wuvq83sQUIrq0avdIqjG@Xau8Gzm2xy4J5V1UVtwKkj5nJlZYNoKYqd63ZaMSYm2KyZljlMlm7I2DbE65oDYWcmH0FA5cMHCsEMDHZL1h2QNQBspBPTAbzAHzf4rDm1M@4P9pG4P@Ag "Wolfram Language (Mathematica) – Try It Online") Slow for larger input lists. [Answer] # [R](https://www.r-project.org/), ~~105~~ 96 bytes (or 89 bytes in [R](https://www.r-project.org/)≥4.1 by using `\` for `function`) *Edit: -9 bytes thanks to pajonk* ``` function(l,a=expand.grid(l,l,l),b=apply(a[rowSums(a)==max(l),],1,sort))b[,order(b[3,]-b[1,])[1]] ``` [Try it online!](https://tio.run/##VY27CsMwDAD3fokEaonJFvBXdDQe5DgNgfiBbNP0611vpdx03HDSg1/zXLkV3V8trvVIEU5ivV2Zo3/scvjhAySnOefzA2wkvZ8tFGDUOvAFI1pSVJJURGcoid8EnJnJ3p1RZNEoa38vUIua8PbvE/Yv "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes ``` 3ÞẊ'∑?G=;µ÷Ȯε^ε+;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIzw57huoon4oiRP0c9O8K1w7fIrs61Xs61KztoIiwiIiwiWzEsIDIsIDMsIDQsIDVdIl0=) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` 3ÞẊ'∑?G=;µ₌Gg-;h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIzw57huoon4oiRP0c9O8K14oKMR2ctO2giLCIiLCJbMSwyLDMsNCw1LDYsNyw4LDksMTBdIl0=) -2 thanks to Bubbler's insight. ``` 3ÞẊ # Combinations of input of length 3 ' ; # Filter by... ∑ = # Sum equals ?G # Maximum of input µ ;h # Minimum by... ₌Gg- # Difference of min + max ``` [Answer] # [Python 3.8](https://www.python.org/), ~~130~~ ~~115~~ ~~99~~ ~~85~~ 80 bytes: -14 Thanks to @tsh -5 Thanks again to @tsh ``` lambda l:max([((z:=max(l)-x-y)in l,x<=y<=z,x-z,x,y,z)for x in l for y in l])[3:] ``` [Try it Online!](https://tio.run/##HdDLisMwDIXhV9EyAQXqux2aJ8lkkWEoU0gvlC6SvHz6uwuBQB@ydZ7b@/9xd/n5Oi7Dz7HMt9@/WZb@Nq/N2DR7P9Ruabu129rrXRZdz8N2HnZdO0o33dvL4yWr1KHUdvu2Uzu6fjqer@v93Vya0ahYFafiVYJKVEkqWaWomBPF3AAMwkAMxoAMysAMzuJs3YOzOIuzOIuzOIuzOIdzOFcfxDmcwzmcwzmcw3mcx3mcrz/DeZzHeZzHeVzABVzABVyoJ@ACLuACLuAiLuIiLuIiLtZbcREXcRGXcAmXcAmXcAmXaii4hEu4jMu4jMu4jMu4jMs1PVzGFVzBFVzBFVzBFVzBlRrzN@fT1LbHBw) Get's the Cartesian Product by looping the list 3 times, and summing it up. [Answer] # [Jelly (fork)](https://github.com/cairdcoinheringaahing/jellylanguage), 11 bytes ``` ṗ3SƘṀṀ_ṂƊÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8///hzunGwY8a9xxaeqz94c4GIIp/uLPpWNfheQ93LPr//3@0oY6CkY6CsY6CiY6CqY6CmY6CuY6ChY6CpY6CoUEsAA "Jelly – Try It Online") (this is the equivalent in normal Jelly) This uses my fork of Jelly which includes the `Ƙ` (keep-like) quick to replace the commonly used `<link>⁼¥Ƈ` pattern. You can see this in the TIO link. ## How it works ``` ṗ3SƘṀṀ_ṂƊÞḢ - Main link. Takes a list L on the left ṗ3 - Cartesian Cube Ṁ - Maximum of L Ƙ - Keep triples whose is like the maximum S - sum ƊÞ - Sort the remaining triples by: Ṁ - maximum _ - minus Ṃ - minimum Ḣ - Take the first ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 13 bytes -1 byte thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) ``` ◄§-▼▲fo=▲¹Σπ3 ``` [Try it online!](https://tio.run/##yygtzv7//9H0lkPLdR9N2/No2qa0fFsgeWjnucXnG4z///8fbahjpGOsY6JjqmOmY65joWOpY2gQCwA "Husk – Try It Online") ### Explanation ``` ◄§-▼▲fo=▲¹Σπ3 π3 cartesian product of 3 * input fo filter by composed function =▲¹Σ max of input equals sum ◄§ min by composed binary function -▼▲ max - min ``` [Answer] # APL+WIN, 53 bytes Prompts for list ``` ↑((⌊/m)=m←(⌈/¨l)-⌊/¨l)/l←((⌈/i)=+/¨l)/l←,i∘.,,i∘.,i←⎕ ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##TcxNCoJAGMbx/ZziWSppOqP5sfAAQdEZxDAGRgxcdQGTqKhF0BHad4OOMheZ3imhVvPnNw9vuVX@eleqduNXquw6WRl9vi0Xur9EjGq@ouJMD/va6P7qOPp4CBq3aIiph@D1UK5v0UagLH9cusXkZ57Uw33qjY8koduGrjJTMw6BCDFmSJAiQw4esj@m1qcnD79od/Yjp2VKSyQjZ@ACPAJPIEKIGCJlbw "APL (Dyalog Classic) – Try It Online") [Answer] # Python/NumPy, 77 bytes ``` lambda l:min(l[argwhere(sum(ix_(l,l,l))==max(l))],key=ptp) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddJvatswGMdx2EufQi_loUJlyfoT8G6wE2RheNRZTO3EuM7asKPsTWFsd9pOs69ip4R1wxiM9NEj6fn528_hNO0O--fv2-rDj-O0vQm_3nd1_-muFt2qb_eyW9fj58ddMzby4djL9umj7BRPnldVXz9JPjbqvjlVwzTk2XY89GJ_7IeTaPvhME5vl6L1467tGqFXmWjVoWq-1J1s98NxkvnarDa5ejWSiWFs95N8oEpzJ7eyHsf6JNs87bwMHnLYsmje6Pn3m6-dqMRaK1EoYZSwSpRKOCW8EkGJqIS-3WQ374Q083yeZa9XzGIeKv4p_q7Jy7wGaISGaIwGaZSGaVyBK1KdVBdX4ApcgStwBa7AGZzBmbRhOijO4AzO4AzO4CzO4izOppPhLM7iLM7iLK7ElbgSV-LKdAVciStxJa7EOZzDOZzDOZxLd8U5nMM5nMd5nMd5nMd5nE9NwXmcxwVcwAVcwAVcwAVcSN3DBVzERVzERVzERVzERVxMbT73-RKeuTTmKp05lzmjeI7Gz9G4_yVuz-olNbcklFLxL__AecpcrTKX8LW5LuyXn_AP) Takes and returns numpy arrays. Approach is straightforward. `ix_(l,l,l)` is essentially the cartesian product. This is then summed over coordinates and compared to the maximum. `argwhere` extracts the coordinates where the comparison succeeds and these are used to index back into `l`. It remains to select a triplet that minimises the spread (difference between `min` and `max`). Rather conveniently, numpy has a function for the spread: `ptp` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~73 72 68~~ 61 bytes ``` ->l{l.product(l,l).min_by{|x|[(l.max-x.sum)**2,x.max-x.min]}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevoCg/pTS5RCNHJ0dTLzczLz6psrqmoiZaI0cvN7FCt0KvuDRXU0vLSKcCygeqia2t/V@gkBYdbahjpGOsY6JjqmOmY65joWOpY2gQG/sfAA "Ruby – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~28~~ 25 bytes ``` 3Z^!tsGX>=Z)ttX<-X>&S1)Z) ``` [Try it online!](https://tio.run/##XdG7TgMxEIXhPk8xNESRvJDx@CpBaJDoaKBYbbQISiSo2CJvv/zOBgQpXFjzyZdzPt@mj/lV3mUaHuVODlcyymzDy8X09dDvbofNNPU3Xb@7fNLNsJll3XXdWvp7GQ7yPM57deKdmJPgJDpJTrKT4qQ60e24@j8/3597FnMFKEIhilGQohSmOI/z7Rycx3mcx3mcx3mcxxnOcNYuxBnOcIYznOEMF3ABF3ChvQwXcAEXcAEXcBEXcREXcbF9ARdxERdxEZdwCZdwCZdwqf0Vl3AJl3AZl3EZl3EZl3G5hYLLuIwruIIruIIruIIruNLSwxVcxVVcxVVcxVVcxVVcbTEfcz4Vs1Sw1FGPLeSlhfQ7L3/qSKfoW9x5EfbToNq42l5vvwE "MATL – Try It Online") ``` 3Z^ % Third Cartesian power !ts % Sum of each sublist GX> = % See which ones' sums equal input's maximum Z) % Filter to keep only those ttX<- % Subtract from each sublist its Minimum X> % Maximum of each. Effectively this is (Max - Min) &S % Get the indices that would sort this result 1) % Get the first index of those i.e. the argmin Z) % Extract the sublist at that index ``` ([Equivalently](https://tio.run/##XdG7TgMxEIXhPk8xNESRvBB77LEtQWiQ6GigWC1aBCUSVGwRnn75nQ0IUriw5pMv53y8Tu/zi7zJNNzLjewvZJRZh@ez6fOu310Pm6nfffVX3fmD3wybWdZd162lv5VhL4/j/OSdBCfqJDpJTsxJdlKcVCd@O67@z0/3p57F3AM8wkM8xoM8ysM8LuBCOwcXcAEXcAEXcAEXcIpTnLYLcYpTnOIUpzjFRVzERVxsL8NFXMRFXMRFXMIlXMIlXGpfwCVcwiVcwhnOcIYznOGs/RVnOMMZLuMyLuMyLuMyLrdQcBmXcQVXcAVXcAVXcAVXWnq4gqu4iqu4iqu4iqu4iqst5kPOx2KWCpY66qGFvLRgv/Pypw47Rt/izovQnwa9jqvt5fYb), perhaps slightly more clearly, `3Z^!tsGX>=Z)tX>yX<-&S1)Z)` - instead of "effectively" doing `max - min`, just explicitly does `max - min`.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes ``` FθFθFθ⊞υ⟦ικλ⟧≔Φυ⁼Σι⌈θυ≔Eυ⁻⌈ι⌊ιθI§υ⌕θ⌊θ ``` [Try it online!](https://tio.run/##XY1BC4JAEIXv/Yo5zsIGaVGBJ4mEDoLQUTwsajm0rq3rhv9@241C6PCY92bex9SdGOtBSOduwwioGfzPwpoOLYeSODw4yIolq9QYuivMSE7tGI5nbYU0eLU9EuOQi5l67zVjPtmFyMUz1HNS1uCv9SFIfX0gtCeKkdSEJ2EmTKeLato5kBmpBvXSDx8YS5wry4jDjsORQxR7bb32HOKNl1/Hh6py65d8Aw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FθFθFθ⊞υ⟦ικλ⟧ ``` Create the Cartesian product of three copies of the list. ``` ≔Φυ⁼Σι⌈θυ ``` Extract those triples that sum to the maximum of the original list. ``` ≔Eυ⁻⌈ι⌊ιθ ``` For each triple, find the difference between its largest and smallest entries. ``` I§υ⌕θ⌊θ ``` Output the first triple with the smallest difference. [Answer] # [Perl 5](https://www.perl.org/) List::Util, 140 bytes ``` sub{$"=',';my$m;($d=max(@$_)-min@$_)<($m//9e9)and($m,@r)=($d,@$_)for grep max(@_)==sum(@$_),map[split$"],glob"{@_},{@_},{@_}";sort{$a-$b}@r} ``` [Try it online!](https://tio.run/##fZBfb5swFMXf@RRHnjtAumkDJKWEeeO90/rSPWUoShYHoYU/BaK1ivLZ2bXRqm2qZgkb33N@vsdudXdcjqde43PZD6vV16E84umnV5U1qu0z@lPlp448qLE/7c5SKJfctHqRVerJvWKHl8mNP2O7WT94srq5SXTib@s9/1PW@YqNZMRD06HodAtLbXyl@HCLU7Vt1317LAcpciqOzU6cs82FXieR9k03nOV2JneXrLuMqcOneQ6wxjoghISIsCAsCbeEmHBHSAjBPAegPmIdTY4cOb1BGde/w1CTKbTUO0tdXwfz@Vv2P6jINDPf3@2meFPTxCaMTUJO/L@QC@sMGAtYC/h2ISMhl8M4/x3SSpHl/DOj1YsnS5LaV/y8qS1khXovD/zcpW8KbVfWw0Fc9UBZt6dBXc3CiDfQz63@Pug9F2KzLxrW@m@1MJEAkRUC@olXqQU@wW1@uFjB/fLwiId7l4xQCpp0svbUuTjjyDEXtKSQIkrojmLim9/mvwA "Perl 5 – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 85 bytes ``` a=>(for{x<-a;y<-a;z<-a if x+y+z==a.max}yield Seq(x,y,z)).minBy(l=>l.max-l.min).sorted ``` [Try it online!](https://tio.run/##jVBBa4MwGL37K94x0q@2ibbWbQrbbbDbLoPSQ1YVHKk6DUMt/e0uUbZD2dgS8hG@vPe@99IepZJj9fqWHTVekHU6K9MW93WNswN8SIX85jl73z@W@hAn37dRxgnLq@bc3S3lbW/LYAqKHN2iXwxxLL2T7C59kakUhsY66mlwXe9UlA89U3GiLGCpbMP12qrRWToCdVOUWpUMOZtonCAIPiEgbAhbQkjYESICX7uwG1itLMKCnD8UvhjXyyjMOHGlwDh0ZUatXU9XT0Wrf@bPHqwJe36xMUeYzURTitCmMKn@GySYWNxIcAPi5jeEoQvTFuGsMQeZXn3nMo57TgFtSJBPEe0oJDNve/gE "Scala – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 97 bytes ``` import Data.List f x=head$sortOn(\t->m t-minimum t)$filter((==m x).sum)$sequence[x,x,x] m=maximum ``` [Try it online!](https://tio.run/##FYuxCoMwEEB3v@KGDApREKGd0qljoR9gHQ6b1KO5mJoT8vVNLW95PHgLprf1vhTiuG4CVxTsbpSkcpDNYvGp0tHvoX5Ie2GQlikQ74c1ypEXu9W1MQy56dLOjUr2s9sw2zHrg6liw5j/Q2GkAAbiRkFAgYOx1zBoOGk4a@iHqXxn5/GVSjvH@AM "Haskell – Try It Online") [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~~280~~ \$\cdots\$ ~~211~~ 210 bytes ``` #import<regex> #define S(v)std::sort(&v[0],&*end(v)) using V=std::vector<int>;int f(V&v){V r=v,x;S(v);int m=v.back(),n=m,t;for(int a:r)for(int b:r)for(int c:r)x={a,b,c},S(x),t=x[2]-x[0],v=t<m&a+b+c==n?m=t,x:v;} ``` [Try it online!](https://tio.run/##1dTdbtowFAfwe57iiEooKQaVfIcQejHtCSpxQ7kIwbCoJUGJyaKhvPrY/zgwkNpq14sUZOyf7eNjO@nhMNql6fn8kO0PRalmpdzJZt572Mhtlkt6MWqzUpvptEKjMaiXTysxeJT5BvVm71hl@Y4WsRa1TFVRzrJczSP80NZYDGrztKAyrkUT8Ui6fh/X43WSvhmmyOO9UNG2KA1uSKaleS2v78opyk18SsRapK14MRpTqLhZWqtRw@HUsZrtB8lwPUzjOH/ex0o00zpqsaQ8fT9uJM2yolKlTPbzryPu6dCSLDfMU4/wpEVeYe4fSfmIX5m@yXK5ophO/dfmu/XahN/wun1B9//tfhvp3vfjL@akZKUq7nyaCLIFeYJ8QRO7FcQ1liC3q5ncasAcXd/hQFAI8PQB/LMHD4vX4gnxgkxgJkATnhJsAmfBWTwOnAVnwVlwFpwFZ8FZcDaczavgCeFsOBvOhrPhbDgbzoFz4Bw4hyODc@AcOAfOgXPgXDgXzuUkwLm8BDgXzoVz4Vw4D86D8@A8TiGcx2uF8@A8OA/Oh/PhfDgfzofzObucFDgfzocL4AK4AC6AC@ACuAAu4OzBBXAhXAgXwoVwIVwIF8KFcCGnWef5ujXdHnT7Eept8Ltt8G4guNsQ75J8Trjffn6AZHNAWW70GbL10P5lNPdyBrpa53YcLF1rX7fpo9Gz29cZcd1I37cs38gGEz1Fl@KsO7/jKvslDTOi4VDXm9TdFH4WpNBDs6VuXEV/2/RS0uKoaDaj/rJ/a9FTdhctOapiQJkqaUrqfuQPIxgDVnFMg0c1XssdX1l6pn4fPfk6moxAbtO0X4SyotGc7sMxlPlfhH0Xy4IkEn89Hp/nXn@75XVSQXLMH3Dzbq3roninQ1LxN0pykOqLPFy/hGxXOprX/BJN22vPv9Pte7KrzqOffwA "C++ (gcc) – Try It Online") *Saved ~~3~~ 4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a vector of integers. Replaces the input vector with the cartesian product of 3 elements of the input vector that add up to the maximum of the input vector and that have the minimum difference between the smallest and the largest element from all of the cartesian products. ]
[Question] [ Given a list of coordinate pairs, output the Trapezoidal Riemann Sum of the values given between the first and last x-coordinates. You will be given a sorted list of coordinate pairs, like this: ``` [ [1,2], [3,5], [5,11] ] ``` Note that x-coordinates will always be in increasing order, ys may not. My way to do this is (you might find a different way): Get pairs of coordinates: ``` [1,2],[3,5] and [3,5],[5,11] ``` For each pair (let's start with the first): * Take the average of the y-values: (2 + 5) / 2 = 7/2 * Take the difference of the x-values: 3 - 1 = 2 * Multiply the two together to get the area of that section, which is 7/2 \* 2 = 7. Do this for all pairs. Let's quickly go through the next, [3,5],[5,11]. Average of y values = (5 + 11) / 2 = 8 Difference of x values = (5 - 3) = 2 Product of the two = 2 \* 8 = 16 Now take the sum of all the values, resulting in 16+7 = 23. # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! # Testcases ``` [ [1,2], [3,5], [5,11] ] => 23 [ [3,4], [4,1], [7,5] ] => 11.5 [ [0,0], [9,9] ] => 40.5 [ [1,1], [2,3], [3,1], [4,3] ] => 6 ``` Note that input will always contain *non-negative integers*. Tell me if any of the testcases are wrong as I worked them out by hand. You may take a flat list, or the list with x and y swapped. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~54 49~~ 47 bytes ``` ->l{(r,=l).sum{|a|x,y,z,w=r+r=a;(y+w)/2r*z-=x}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWqNIxzZHU6@4NLe6JrGmQqdSp0qn3LZIu8g20VqjUrtcU9@oSKtK17aitvZ/gUJadHS0oY5hrE60kY4xkDQGs02A7NjY/wA "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ṁΠTzẊe-o½+T ``` [Try it online!](https://tio.run/##yygtzv7//@HOxnMLQqoe7upK1c0/tFc75P///9HRhjpGsTrRxjqmQNJUx9AwNhYA "Husk – Try It Online") A rare question where you get to use a list of functions! ## Explanation ``` ṁΠTzẊe-o½+T T transpose z zipwith e list of 2 functions: - difference o½+ average Ẋ using pairwise reduce T transpose back ṁ map to and sum: Π product ``` [Answer] # [Python 3](https://docs.python.org/3/), 56 bytes ``` lambda p:sum((b+d)*(c-a)/2for(a,b),(c,d)in zip(p,p[1:])) ``` [Try it online!](https://tio.run/##LYxLbsMwDET3PgV3IVsmNf1pEQPqRVQv5DhGBPhDJHKK9vJuVGX1gHkzoz/hsszlNpivbXRT1zvQ5rZOiN1rTy942jt6K4blio47YjxxT36GX6@orFaalmj7vvjxDNJk4GdlWNagYGByiue7Gzmma0A63HT0AXdgPmFHlIFe/RxwwIcnhkQw5v@ANgtWuGgZbMl1RM0iLbRxXpSZjXkV84ol4uPRSlbkUEefcx7FkY9PUeVJSFoUXKZ7STfls/b@Bw "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ạ+ƭ"P¥ƝSH ``` [Try it online!](https://tio.run/##y0rNyan8///hroXax9YqBRxaemxusMf/w@2Pmtb8/x@tEG2oYxSroxBtrGMKokx1DA1jFUAskJAJiGGiYwiizIEKoBIGOgYghqWOJUzEEKLGSMcYYpYhRKMxUB4A "Jelly – Try It Online") ``` ạ+ƭ"P¥ƝSH Main Link ¥Ɲ For each (overlapping) pair " Vectorize; apply to x coordinates then the y coordinates ƭ Tie: ạ - for the x coordinates, absolute difference + - for the y coordinates, sum P Product S Sum H Halve ``` [Answer] Two more 9-byte answers: # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḣ€IḋSƝF$H ``` [Try it online!](https://tio.run/##y0rNyan8///hjkWPmtZ4PtzRHXxsrpuKx////6O5FBSiDXWMYnVADGMdUwjDVMfQMJYrFgA "Jelly – Try It Online") # and [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ZIḋSƝ}ɗ/H ``` [Try it online!](https://tio.run/##y0rNyan8/z/K8@GO7uBjc2tPTtf3@P//fzSXgkK0oY5RrA6IYaxjCmGY6hgaxnLFAgA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes I don't think there are as many 9-byters as in Jelly, but here is one: ``` ø`ü+;s¥*O ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8I6Ew3u0rYsPLdXy//8/OtpYxyRWJ9pExxBImuuYxsYCAA "05AB1E – Try It Online") ``` # implicit input [[1,2],[3,5],[5,11]] ø` # tranpose and push x and y seperately to the stack [1,3,5], [2,5,11] ü+ # for y coordinates: sum adjacent numbers [1,3,5], [7,16] ; # halve each value to get means [1,3,5], [3.5,8.0] s # swap to x coordinates [3.5,8.0], [1,3,5] ¥ # get deltas, consecutive differences [3.5,8.0], [2,2] * # element-wise multiplication [7.0,16.0] O # take the sum 23.0 ``` [Answer] # [R](https://www.r-project.org/), ~~60~~ 52 bytes ``` function(l)diff(l[1,])%*%(c(l[,-1])+l)[2,-ncol(l)]/2 ``` [Try it online!](https://tio.run/##Xc3NCsIwEATge58iIIWsTjWbH6WH@iKlB4kECjGFGsG3rxEvrcxh5/AtMy95fnZLeCWfxynJSPcxBBl7xkD1vpa@dDQ80CFSr9EkP8WihpP@fsrHLc/juyiGhoErYSZoIiF2orsKbaqNM7AljAvcmjEf3RYqKLRo18iqf8T47ZpyLcwan6vlAw "R – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~55~~ 45 bytes ``` function(x,y)diff(x)%*%(y[-sum(x|1)]+y[-1])/2 ``` [Try it online!](https://tio.run/##PY3LCsJADEX3fsWAFBKN2syj4qL@iHQ1MtCFLfQBU/DfpxO0XVzC5ZxwhzQNY53C3Pmp7TuItOC7DQEiFqcCltdlnD8Qv4zNORdu8KblBTwwGXJIHjQ5YkZU6qjqp9Lm8BMMWbqLYImzuXHmq/sbJT2Ey9moLXfKpPOEFUO2cnarSis "R – Try It Online") *-6 bytes thanks to @Dominic* --- For input as matrix: ### [R](https://www.r-project.org/), 50 bytes ``` function(a)diff(a[1,])%*%(a[2,-ncol(a)]+a[2,-1])/2 ``` [Try it online!](https://tio.run/##Xc3BCsIwDAbg@56iIINWf7VpV2WH@SKyQ6kUCm6DWsG3r1UvnfyHJOQLiTnFx5D9c3YpLDO34ha85/ZKGEW7bUunsJ/dci@rcfedaBRH9bnjk00xvLjjBAUNU0IkoIRgbMOGC1O6WTmNroRwhqkZ0cGsoYREj75GnfxHhN9fXWoHXeNTk98 "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ר-+PʋƝSH ``` [Try it online!](https://tio.run/##y0rNyan8///w9MMzdLUDTnUfmxvs8f9w@6OmNZH//0dHK0Qb6hjF6ihEG@uYgihTHUPDWIVYHa5okJAJSMhExxBEmQMVQCUMdAxAIpY6ljARQ4gaIx1jiFmGEI3GQPlYAA "Jelly – Try It Online") Assumes the second test case is in fact meant to be 11.5. Although I did admit to trying this while it was still in the Sandbox like ten minutes ago, this contains absolutely none of the code I tried while it was there :P [Answer] # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` n=>n.reduce((z,[a,b],i)=>z+=i--&&(b+n[i][1])*(a-n[i][0])/2,0) ``` [Try it online!](https://tio.run/##dc2xDoIwGATg3adgMq38xf4UYhjKizQdChRTQ1oD6sDLVwujOt0NX@5u5mWWfnb3B/NhsHGU0cvWF7Mdnr0lZAVloNPgqGzXXDrGjkfS5V45rVDTEzFs61zTcwmcxj74JUy2mMKVjERlCqHUkCkBdYoaEHWmKT18QQFVEhVgisvH/3YceAINNH8A7gsliP0Y91mx8fgG "JavaScript (Node.js) – Try It Online") Doing it with `map` is just as long: --- # [JavaScript (Node.js)](https://nodejs.org), 61 bytes ``` n=>n.map(([a,b],i)=>z+=i--&&(b+n[i][1])*(a-n[i][0])/2,z=0)&&z ``` [Try it online!](https://tio.run/##dc2xDoIwGATg3adgalr5iy2FGIbyIs0/FARTgy0R48DLVwujOt0NX@5u9mWX/uHmJ/fhMsRRR69bX9ztTKmx0CE4pts1145zQmiXe@PQSGRHavnWBbJTCasWjJA19sEvYRqKKVzpSE1mJJQImVFQp6hBSsyQscMXVFAlUYFMcf74306ASKCB5g@Q@0IJaj@W@6zaeHwD "JavaScript (Node.js) – Try It Online") --- Thanks EliteDaMyth for saving 1 byte off both answers (was a general tip) [Answer] # [Python 3](https://docs.python.org/3/), 62 bytes ``` lambda l:sum((y[0]-x[0])*(x[1]+y[1])/2for x,y in zip(l,l[1:])) ``` [Try it online!](https://tio.run/##DcZLCoMwEADQfU@R5cSOtKO4ETzJdBaWEgyMMfiBxMun2TxezOeyhb7oxEzYCXKPQ3VAIpGHmz5F5/X7m42Ox7UCZH5Lmyq2gcQkz1yxr85tu0mYjQ/m9hEUlWkUa0vcfTjBgdb/AQ "Python 3 – Try It Online") -2 bytes thanks to @NahuelFouilleul [Answer] # JavaScript (ES6), 52 bytes Given \$n\$ coordinate pairs, this computes \$\sum\_{i=0}^{n-2}(y\_i+y\_{i+1})/2\times(x\_{i+1}-x\_i)\$ recursively. ``` f=([[x,y],...a])=>a+a?([[X,Y]]=a,y+Y)/2*(X-x)+f(a):0 ``` [Try it online!](https://tio.run/##bc5RC4IwEAfw9z7FHrc8585pYWB9DWXsYZhGIS4yQj/9cihU2L0cHPe7/93My/TV43p/hp091841OVVqgFED59xolh9NYE7TrIBS69zAGJQsire0CAcWNNSwg3CV7Xrb1ry1F9pQRRRCrIEoCalvKSBqohkjS0URieVmpSQkfj0B9G0/4W/kFSJP106A8CCD7Bd8XCL@OZyDYpDzsziny@XK5HbuDQ "JavaScript (Node.js) – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/) / MATLAB, 6 bytes ``` @trapz ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en99@hpCixoOp/mka0oYKxgmmsjkK0kYKpgqFhrCYXUNBYwUTBHCRoomAIlAWLGShYgkRAFJhvqGAE1GoCEgOZAcSxmv8B "Octave – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) (`-p`), 56 bytes ``` s;(\d+),(\d+)(?= (\d+),(\d+));$\+=($3-$1)*($2+$4)/2;ge}{ ``` [Try it online!](https://tio.run/##TYo7CgIxFAD7PUWEVyTmRfPyQZYQPIE3SCO4yoK4wdiIeHWfwcpmYJip0/0aGUpeteMTynyGkrglWU5a4Y9yn8WfqgRFZwneAKm1BKchqK1Ll@n9YiZ0wmMUEYkGj0EEJLHDOFi0YsRxoO4OfZ@oN/9Z6mNebo1NZXOIG0tf "Perl 5 – Try It Online") `-M5.01` option and `say($\),$\=""if$\;` header are needed only to run all tests otherwise the program works for one line. example: `perl -pe 's;(\d+),(\d+)(?= (\d+),(\d+));$\+=($3-$1)*($2+$4)/2;ge}{' <<< '1,2 3,5 5,11'` trick: `-p` option with `}{` at the end so that continue block is not executed on each iteration but at the end, and `$_` is empty so only `$\` is printed deparse: `perl -MO=Deparse -pe 's;(\d+),(\d+)(?= (\d+),(\d+));$\+=($3-$1)*($2+$4)/2;ge}{'` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `s`, 11 bytes ``` ÞT÷2lvṁ$¯ȧ* ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%C3%9ET%C3%B72lv%E1%B9%81%24%C2%AF%C8%A7*&inputs=%5B%5B3%2C4%5D%2C%5B4%2C1%5D%2C%5B7%2C5%5D%5D&header=&footer=) ``` ÞT # Transpose ÷ # Push each to stack (y is on top 2l # Groups of 2 vṁ # Averaged $ # Swap to get x coords ¯ȧ # Deltas * # Multiply the two # Sum that. ``` There's probably a better way :p [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 63 bytes ``` \d+ * |""L$vm`^(_*),(_*)¶\1(_+),(_*) $.3*$($2$4 ^(__)* $#1 _ .5 ``` [Try it online!](https://tio.run/##JYoxCsJAEEX7f4w4wmYzhMzOLiHMFexsgxtBCwtTiFh5rhzAi60rNg8e7z2uz9t6lrJ3x8XKfOng8W6aA73uy8ll3/IPn20Wl7u/gHr15ChQRF1y60E7QUafShEOppwssQiUo0UWGzlh4MEmniDVA2udpDb9Ag "Retina – Try It Online") Takes newline-separated pairs but link is to test suite that splits on semicolons for convenience. Explanation: ``` \d+ * ``` Convert to unary. ``` |""L$vm`^(_*),(_*)¶\1(_+),(_*) ``` Match overlapping sets of four values from two lines. ``` $.3*$($2$4 ``` Multiply the difference between the first and third value by the sum of the second and fourth value. ``` ^(__)* $#1 _ .5 ``` Divide by 2 and convert to decimal. [Answer] # [Japt](https://github.com/ETHproductions/japt), 16 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÕÌä+ í*UÕÎäa)x÷2 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=1czkKyDtKlXVzuRhKXj3Mg&input=W1sxLDJdLFszLDVdLFs1LDExXV0) ``` ÕÌä+ í*UÕÎäa)x÷2 :Implicit input of array U Õ :Transpose Ì :Last element ä+ :Consecutive pairs, reduced by addition í* :Interleave with, reducing each pair by multiplication UÕÎ : Last element of transposed U äa : Consecutive pairs, reduced by absolute difference ) :End interleave x :Reduce by addition ÷2 :Divide by 2 ``` [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 70 bytes ``` 1k[sysxdly+2/syrdlxr-sxrlxly*lad1+sa:az4!>L]dsLxc[la1-ddsa;ar0<L+]dsLx ``` [Try it online!](https://tio.run/##HcgxDoAgDADAr@AqIVrURY0v4AfEoaFxsRNdip@vxtx2VAxcdJNbPgAGd5YmStx8HKRVYq1BtLJy6xkJvOCKz9wd6SRJWjIjBCLBDeu4J/@vXfYC "dc – Try It Online") One decimal place of precision (`1k`) is sufficient because the longest fractional part we can have is 0.5. There could be better ways of twiddling the bits around. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes ``` I⊘ΣEΦθκ×⁺§ι¹⊟§θκ⁻§ι⁰⊟§θκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyMxpyw1RSO4NFfDN7FAwy0zpyS1SKNQRyFbU0chJDM3tVgjIKe0WMOxxDMvJbVCI1NHwRAoE5BfABcCK9YECvpm5qGqNMCuEgKs//@Pjo421jGJ1VGINtExBFHmOqaxsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array Φ Filtered on κ Current index E Map over tail §ι¹ Current Y-coordinate ⁺ Plus ⊟§θκ Previous Y-coordinate × Multiplied by §ι⁰ Current X-coordinate ⁻ Minus ⊟§θκ Previous X-coordinate Σ Take the sum ⊘ Divide by 2 I Cast to string Implicitly print ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~74~~ 72 bytes -2 thanks to @ceilingcat ``` a;r(int*x){for(a=0;~x[2];)a+=(x[2]-*x)*(*++x+x++[2]);printf("%f",a/2.);} ``` Takes input as a flat list terminated with `-1` (e.g. `{x1, y1, x2, y2, ..., -1}`) [Try it online!](https://tio.run/##TY/haoMwFIV/N08hQiHRa2cSuzGCT1L7I7OxFLa0OAcBca/uTmq3mQO5uffLPTdpi3PbzrM1Pb/4IQti7K49t3VpvsNBHY2wec3jqQDLeJbnAcpREObWo6Xj6bZLyT6pnTDTjEoyuM9hcaPT9evt3SUu3Fw7uJMYWZL0PAiD@Nve@G3X@AKr8Sn9XTVsYizafdiL5@jcxCTIw7EeJSnStIekpEJO5gFVhJoqSNIL8IrpyEoq6RVa1avFcLHUiBX2O2eb@08CkMZzHpnCzN3@P8e4cp1X9BzfPv8A "C (gcc) – Try It Online") --- # [C (gcc)](https://gcc.gnu.org/), ~~78~~ 75 bytes -3 (indirectly) thanks to @ceilingcat ``` a;r(int*x,int*y){for(a=0;~*++x;)a+=(*x-x[-1])*(*y+++*y);printf("%f",a/2.);} ``` [Try it online!](https://tio.run/##bZBha4MwEIY/N79ChEI0Z2di2jGCv6T2Q2a1FDZbrIML4v66u9h1y2CBhOThuZfL1dmprufZmp6fuyFF8KdLxvbSc1vm5jMVAk1iRclTzHCfyUOS8tQJIUgz1578lsfrNgb7pDaJmWYi0dDchjAQjpeP17cmavDa1ENzTEYWRT1HoAy6PWKqbt1WXUar6mL4kQ2bGPOx7/bccapd@QfK/aEcJRSwhUxO5k7dQhUxKQOMyuMCNDyH8kI1yD8RWHiaw0to/sNQ3xtQ4HMDVz8a83vhbLVMBCU48gv60TdQ4BR1utn@ogIc5eUh0uA07Pwc5i8 "C (gcc) – Try It Online") Takes input as a list of `x`s and a list of `y`s, terminated with `-1`. ]
[Question] [ A class has N student and the class room has N switches (all turned OFF and numbered 1 to N). Each student has an enrollment number assigned from 1 to N. Each student serially (by number) toggles the switches that has a number which is divisible by his/her enrollment number. Example: Student 1 will turn all the switches ON. Student 2 will turn all even switches OFF. Student N just toggles the Nth switch. Write a function that takes N as input as returns number of ON switches. sample I/O ``` Input: 10 Output:3 ``` No upper bound for N is given, but greater the scope, better the code. Shortest and innovative function wins [Answer] # Python, 19 characters ``` f=lambda n:n**.5//1 ``` Perfect squares are the only numbers with an odd number of divisors. This used to be a **21-character** answer: ``` f=lambda n:int(n**.5) ``` but since I originally wrote it in 2011, the floor-division `//` operator was introduced, which can replace the `int` call. As a consequence, the answer is now returned as a floating-point number. (But `f(10) == 3.0` is still a correct number of lockers!) [Answer] ## dc - 5 chars ``` [v]sf ``` Square root in `dc` is `v`. Using stdin/stdout takes 3 chars (`?vp`) [Answer] ## J, 9 chars (Just for a simple example on J) ``` f=:[:<.%: ``` floor (`<.`) of square root (`%:`) [Answer] # Haskell - 12 Some text so that my post is long enough. ``` f=floor.sqrt ``` [Answer] # TI-BASIC, 3 ``` int(√(Ans ``` Or in **Stuck** (invalid, since it's from 2015): ``` i/) ``` Or in [**QWERTY Reverse Polish Notation**](https://esolangs.org/wiki/Qwerty_Reverse_Polish_Notation) (valid, from 2009): ``` @r[ ``` Not an interesting answer, but I think they win, since I can't find a language that has either one-character integer square root or implicitly reads from input and performs the calculation in two bytes. [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 2 bytes ``` ⌊√ ``` Floor of root of the input. [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//1FP16OOWf/THrVNeNTb96ir@VHvmke9Ww6tN37UNvFR39TgIGcgGeLhGfw/TcEMAA "APL (Dyalog Extended) – Try It Online"), [Verify 50 test cases](https://tio.run/##AUsAtP9hcGwtZHlhbG9nLWV4dGVuZGVk///ijIriiJr/ZuKGkOKNjuKKg@KNrOKNtMKvM@KGkeKOlVNSQ@KOlVRISVP/4o2qZsKo4o2zNTA "APL (Dyalog Extended) – Try It Online") [Answer] ## GS2, 2 bytes ``` V- ``` The two instructions are parse number, and integer square root, in order. The reason this works is that the only switches that are on are perfect squares. Those are the only numbers with an odd number of divisors. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` tï ``` [Try it online](https://tio.run/##yy9OTMpM/f@/5PD6//8NDQA) or [verify the first `N` test cases](https://tio.run/##yy9OTMpM/e/qZ6@k8KhtkoKSvd//ksPr/@v8NzUAAA). **Explanation:** ``` t # Square-root the (implicit) input-integer ï # Cast it to an integer (a.k.a. floors) # (after which the result is output implicitly) ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 18 bytes ``` (int)Math.sqrt(n); ``` [Try it online!](https://tio.run/##ZY2xDoMwDETn8hUek6ERQ7ds3ZkYqw4uIBoaHJo4SKji29OkYuvk893p3YQrnqf@lcy8OM8w5V9ZpFE1yE9dLfFhTQedxRCgQUPwqQAONzByPoYYri4Sb6JIkrlz8gNHT6k4sqBUeHsWJHUC2P8QqzM9zBkvWvaGxtsd0I9B/tYA2i3wMCsXWS05ZkviGLzUtZS6Ksw9fQE "Java (JDK) – Try It Online") # [Java (JDK)](http://jdk.java.net/), 133 bytes ``` boolean[]a=new boolean[n]; int c,i=c=0; for(;++i<=n;) for(int j=0;++j<= n;) a[j-1]=j%i==0?!a[j-1]:a[j-1]; for(boolean b:a) c=b?++c:c; ``` [Try it online!](https://tio.run/##ZU8xjsIwEOzziqVAiuUD5SSqmBXS9VSUUYqNCcgmrJHtcEKIt@cckqvYZndmVqMZS3da2eNluPVNZzTojkKAPRmGZwYwsyFSTMtwhB/Xc3zk48kCnkPjXNcSVzUht7/wD7lW2fijvwxqLFR2cj5XUpotshJvNMo2SVLaLcLIUmVX3zXapUEsdosJltOaHGZ7aEoSmcZmJ6UutRogjW9j7xm0SrlfH9nvzhzhmnrlh@gNn6sayJ@DeNcEODxCbK9r18f1Lcmx43xuuikKISbP1/AH "Java (JDK) – Try It Online") [Answer] # Moonscript 23 Pretty simple and self-explanatory ``` s=(n)->math.floor(n^.5) ``` [Answer] # [Math++](http://esolangs.org/wiki/Math%2B%2B), 6 bytes ``` _sqrt? ``` (Filler Text Because 30-char minimum) [Answer] # [Wren](https://github.com/munificent/wren), 23 bytes Basically square-root and floor. ``` Fn.new{|x|x.sqrt.floor} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkKhgq/DfLU8vL7W8uqaipkKvuLCoRC8tJz@/qPZ/cGVxSWquXnlRZkmqRqJecmJOjoahgabmfwA "Wren – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 9 bytes ``` $_=0|sqrt ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3tagpriwqOT/f0ODf/kFJZn5ecX/dQsA "Perl 5 – Try It Online") ]
[Question] [ Inspired by a challenge from the [OUCC 2022 Seniors competition](https://challenge.bebras.uk/index.php?action=anon_join&grp_id=12427). ### Background Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball. ### Your Task Write a program that calculates which team won based on who had the smallest accumulated time. ### Clarifications * There are two teams. * There will be an even number of rounds played. * Both teams will attack an equal number of times but it could be in any order. ### Example Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list: * `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20. * `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47. * `['B', 40, 6]`: This time it's 22 * `['B', 20, 2]`: 14. B is now at 36. Now we get the team with the lower score, in this case B, and output. ### Test cases ``` Input -> Output [['A', 100, 5], ['B', 95, 2]] -> A [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B ['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B [] -> Draw ``` ### Input / Output formats * You must take an arbitrary even number of inputs (these can all be in a list, or taken separately). * Each input must be a list of three items (in whatever order you prefer): + The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc. + The time taken for the team to get the flag (a positive integer of seconds) + The number of hits they got (a positive integer)Note: The number of hits will never exceed the time taken / 5, so the score will never be negative. * You must have three distinct output possibilities: + One for the first team winning + One for the second team winning + One for a draw * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!** [Answer] # JavaScript (ES6), 43 bytes *-2 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects `1` for `'A'` and `-1` for `'B'`. Returns `false`, `true` or `0` for *A wins*, *B wins* and *draw* respectively. ``` a=>a.map(([i,t,n])=>s+=i*=t-n*3,s=0)|s&&s>0 ``` [Try it online!](https://tio.run/##ndCxDoIwEAbg3afoRFosUCjFOJRE41s0HRoUg0FKKNHFd69FJTIQjd50f3LNd9eTuihTdFXbB43eH2zJreK5Cs@qhVBUuMeNRDw3S1753M34FBtO0M14nsmJLXRjdH0Ia32EJRQixiAmBAMmMRCBS2uGQSIlQuD3iiKwWcwIiQPIALieuj4esdSFbAzD1DfZCds5gbm39CWspudQ9qYTNqGzhzbZI33Sc8J/v/Hhhl2nrvYO "JavaScript (Node.js) – Try It Online") ### Commented ``` a => // a[] = input array a.map(([i, t, n]) => // for each entry (i = team, t = time, n = hits): s += // update the sum s: i *= // either add or subtract: t - n * 3, // t - 3n s = 0 // start with s = 0 ) // end of map() | s // return 0 if s = 0 && s > 0 // return true if s is positive, false otherwise ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ ~~10~~ 8 bytes ``` ƛ÷T-*;∑± ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixpvDt1QtKjviiJHCsSIsIiIsIltbLTEsIDEwMCwgNV0sIFsxLCA5NSwgMl1dXG5bWy0xLCAyMCwgMF0sIFstMSwgMzAsIDFdLCBbMSwgNDAsIDZdLCBbMSwgMjAsIDJdXVxuW1stMSwgNTAsIDNdLCBbLTEsIDcwLCA1XSwgWzEsIDM1LCAwXSwgWy0xLCAyNSwgMV0sIFsxLCA2MCwgMl0sIFsxLCA0MCwgNF1dXG5bXSJd) Inspired by [Arnaulds answer](https://codegolf.stackexchange.com/a/256965/116074). Expects `-1` for 'A' and `1` for 'B'. Returns `1`, `-1` or `0` for A wins, B wins and draw respectively. ``` ƛ ; # map: ÷ # push each on stack T # triple - # subtract * # multiply ∑ # sum ± # sign ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 21 bytes ``` ≔↨¹Eθ×⊟ι↨±³ιθI∧θ÷θ±↔θ ``` [Try it online!](https://tio.run/##PY65DsIwEER7vmLLtbSRckJBFaChAKWgs1KYxAqWgnPY5PeNYwWmem9HI23zEnMziN650hjVaTwJIzEhuIkRJ4KHekuD1TCiYgShvMtOWImZd8V8CCZ23FWz0hbPwlgsdbtOr9pe1KJauco2Kp9m6D8eJhZydI5znhEUMUGU1AS8IDj8xUPmD4H9U2nxK1KCfbwVOUEeuK5dtPRf "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of `[hits, time, team]` where `-1` is `A` and `1` is `B` and outputs the winning team or `0` for a tie. Explanation: ``` ≔↨¹Eθ×⊟ι↨±³ιθ ``` Calculate sum of the accumulated times for each round with `A`s times being negative and `B`'s times being positive. ``` I∧θ÷θ±↔θ ``` Output the negated sign of the result. No actual "base conversion" going on here - base `-3` is used to calculate accumulated time and base `1` is used to take the sum of a list in case it's empty. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), ~~6~~ 5.5 bytes ``` `$+.$*-@*3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWqxJUtPVUtHQdtIwhAlDxm9rRStEaBjpGBjqGmjoahjrGEIaZjomBji6IZQSSA7JilWKhegA) Takes a list of tuples `(hits,time,team)` with `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw. ## Explanation ``` `$ Sign of + sum of . map $ input (x,y,z) => * multiply - subtract @ y *3 multiply by 3 x z ``` Nibbles' implicit tuple unpacking came in really handy here. -0.5 by using my freedom to choose the order of the tuple. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` x_Ì*3)nZg1)*ZÎ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=eF/MKjMpblpnMSkqWs4&input=W1stMSwgMTAwLCA1XSwgWzEsIDk1LCAyXV0) or [verify all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eF/MKjMpblpnMSkqWs4&footer=Zw&input=WwpbWy0xLCAxMDAsIDVdLCBbMSwgOTUsIDJdXQpbWy0xLCAyMCwgMF0sIFstMSwgMzAsIDFdLCBbMSwgNDAsIDZdLCBbMSwgMjAsIDJdXQpbWy0xLCA1MCwgM10sIFstMSwgNzAsIDVdLCBbMSwgMzUsIDBdLCBbLTEsIDI1LCAxXSwgWzEsIDYwLCAyXSwgWzEsIDQwLCA0XV0KW10KXS1tUg). Port of @AndrovT's Vyxal answer. Takes -1 for A and 1 for B. Outputs 1 for A, -1 for B, and 0 for draw. ``` x_Ì*3)nZg1)*ZÎ implicit input array x_ sum after mapping each to: Ì*3) the last item (hits) * 3 nZg1) subtracted from the second item (time) *ZÎ multiplied by first item (A or B, -1 for A and 1 for B) -g flag: output sign of the number ``` [Answer] # Wolfram Language, ~~39~~ 35 bytes **Solution 2.** Thanks to [these tips](https://codegolf.stackexchange.com/questions/12900/tips-for-golfing-in-mathematica), we can remove 4 bytes: ``` Sign@Tr[#&@@#(#[[2]]-3#[[3]])&/@#]& ``` * `Tr` is the same as `Total` for 1-dimensional lists (-3 bytes) * `a[[1]]` is the same as `#&@@a` (-1 byte). Note that we now have three anonymous functions stacked within each other like matryoshka dolls! **Solution 1.** We encode 'A' as 1 and 'B' as -1. ``` Sign@Total[#[[1]](#[[2]]-3#[[3]])&/@#]& ``` The solution converts each list element {a,b,c} into an expression a(b-3c), using an anonymous function. We then calculate the sum (total) of this list and compute its arithmetic sign. It returns 1 if 'A' wins, 0 if there is a tie, and -1 if 'B' wins (for obvious reasons). Some comments about the notation: * `@` is function application: `f[x]` is the same as `f@x`. * `Sign` and `Total` does what they say on the tin (`Total` accepts a list argument). * `#` and `&` define an anonymous function: `#+1&` is a function that adds 1 to its argument. * `a[[i]]` is the $i$-th element of list `a`, and list elements are enumerated starting from 1. * `/@` is `Map`, which applies a function on the left to list on the right. * Finally, Wolfram Language does not require explicit multiplication signs in obvious cases like `a(b+c)` or `2x`. One final comment: the solution is 39 bytes but 33 *glyphs*, as Wolfram allows using `U+301A`〚 and `U+301B` 〛instead of double brackets. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 33 bytes ``` [ [ first3 3 * - * ] map Σ sgn ] ``` [Try it online!](https://tio.run/##ZU/LCoJAFN37FadtoYyPMSoIiiDatIlW4kJsLBepjSMR4tf0P/2S3SxxoLkMnHM5D24SxSqX7fGw22/nuEbqYlVZGucngVLcKpHFouzWKKRQ6lHINFNYGEZtgF5NY9qwGQNHQ2RiY8bhEG4wgrnEStc5DKyTEXYZ7N7iMfg9Jo1mX@t2zuD29qnW6PIh1uFDrP@N6iu8/9gf3cjobjRtgABJKkvlUs8YJv2Qji/weqI8ZwjbD7HaNw "Factor – Try It Online") This answer uses the following values: * `-1` for Team A * `1` for Team B * `1` for Team A victory * `-1` for Team B victory * `0` for draw ### How? For each triplet, * Multiply the last number by three * Subtract this value from the second number * Multiply this by the first number (the team value [-1 or 1]) Then, * Sum the results * Get the sign (returning -1, 0 or 1 for negative, zero, and positive) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Employs the team identification trick from [Arnauld's JavaScript ES6 answer](https://codegolf.stackexchange.com/a/256965/53748). ``` Ḣ×)ḅ-3SṠ ``` A monadic Link that accepts a list of triples, `[team, hits, time]` with teams represented as `-1` and `1`, and yields the losing team or `0` for a draw (i.e. `-1` if `1` won and vice versa). **[Try it online!](https://tio.run/##y0rNyan8///hjkWHp2s@3NGqaxz8cOeC////R0cb6igY6yiYGcTqKETrAjmWOgoWcI6pjoIJmANkgxQaxMYCAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjkWHp2s@3NGqaxz8cOeC/4fbHzWt@f8/Ojpa11BHwVRHwdDAIFZHIRrIMdJRsDSNjdXhUoBIGgCFwHIgDhAZwxSa6SiYIGkCKkJoMgYaCtcENN4cphBomrEpkmlGpggTzGCKTMAmg00DErEA "Jelly – Try It Online"). ### How? ``` Ḣ×)ḅ-3SṠ - Link: list of [team, hits, time] triples ) - for each triple: Ḣ - head -> removes team and yields it × - multiply by ([hits, time]) -> [team * hits, team * time] ḅ-3 - convert (each) from base -3 -> -3 ** 1 * team * hits + -3 ** 0 * team * time = team * (time - 3 * hits) S - sum Ṡ - sign ``` --- Equivalently, `Ḣ×ḅ-3)SṠ`. Similarly, `Ḣ)ḋḅ-3$Ṡ` (using a dot-product). [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of [Jonathan's Jelly solution](https://codegolf.stackexchange.com/a/256988/58974). ``` xÈm*Xv)ì3n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=eMhtKlh2Kewzbg&input=W1sxLCAzLCA2MF0sIFstMSwgOSwgODBdLCBbLTEsIDUsIDQwXSwgWzEsIDEsIDMwXV0) ``` xÈm*Xv)ì3n :Implicit input of 2D array x :Reduce by addition after È :Passing each X through the following function m* : Map & multiply by Xv : Remove & return the first element, mutating the original array ) : End map ì : Convert from base 3n : -3 :Implicit output of sign of result ``` [Answer] # [Arturo](https://arturo-lang.io), 52 bytes ``` $[a][n:sum map a't->t\0*t\1-t\2*3(0=n)?->0->n/abs n] ``` [Try it](http://arturo-lang.io/playground?WaFmuA) A port of my [Factor answer](https://codegolf.stackexchange.com/a/256975/97916), though it suffers from a lack of sign function. ``` $[a][ ; a function taking an argument a n: ; assign n to sum ; sum map a 't -> ; map over a and assign current element to t t\2 * 3 ; last number in triplet times three t\1 - ; subtracted from second number in triplet t\0 * ; times first number in triplet (0=n)? ; is n zero? -> 0 ; zero if so -> n / abs n ; n divided by the absolute value of n if not ] ; end function ``` [Answer] # Julia,44 bytes ``` a->sign(mapfoldl(i->i[1]*(i[2]-3*i[3]),+,a)) ``` I'm taking the strategy everyone else is using by using -1 for A and 1 for B, then multiplying that by the number of seconds after deductions. Outputting the sign of the output is the team who wins, and zero is a draw. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ε`3*-*}O.± ``` Port of almost any other answer, with input-triplets in the order `[team, time, hits]` and using `1` and `-1` for teams \$A\$ and \$B\$ respectively, with an output of `-1`, `1`, or `0` for Team \$B\$ wins; Team \$A\$ wins; and draw respectively. [Try it online](https://tio.run/##yy9OTMpM/f//3NYEYy1drVp/vUMb//@PjjbUMTLQMYjVATKMDXQMgQxdQx0TAx0zCAssGQsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1sTjLV0tWr99Q5t/K/zPzo62lDH0MBAxzRWJ1rXUMfSVMcoNlZHASRsZKBjABQ11DE20DGESJsY6JhBWGBJqEJTAx1jsEJzuDnGplC9RqYwvWYGQKNhppiA9cbGAgA). A port of [*@JonathanAllan*'s Jelly's answer](https://codegolf.stackexchange.com/a/256988/52210) is 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well: ``` εć*3(β}O.± ``` Takes the inputs in the order `[team, hits, time]` instead. The other I/O is the same. [Try it online](https://tio.run/##yy9OTMpM/f//3NYj7VrGGuc21frrHdr4/390tKGOgY6RQawOkGGoYwxi6BrqmOmYQFlGIMlYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1uPtGsZa5zbVOuvd2jjf53/0dHRhjqmOoYGBrE60bqGOkY6lqaxsToKIGEDHSOQqKGOoY4xVNpMxwSuECgJVWisYwpRaKpjDpU20DE2heo1MoXpMINKmoBMAemNjQUA). **Explanation:** ``` ε # Map over the (implicit) input-list of triplets: ` # Pop and push all three values separately to the stack 3* # Multiply the top `hits` by 3 - # Subtract it from the `time` * # Multiply it to the `team` }O # After the map: sum the list together .± # Pop and output its sign # (which is output implicitly as result) ε # Map over the (implicit) input-list of triplets: ć # Extract head; pop and push remainder-list [hits,time] & head `team` separately * # Multiply `team` to the values in the pair: [hits*team,time*team] 3(β # Convert it from a base-(-3) list to an integer: team*(time-3*hits) }O.± # After the map: same as above (and also output implicitly) ``` [Answer] # [Nim](https://nim-lang.org/), 77 bytes ``` import math,sequtils proc c[S](s:S):int=sgn sum s.mapIt it[0]*(it[1]-3*it[2]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3fTNzC_KLShRyE0sydIpTC0tLMnOKuQqK8pMVkqODYzWKrYI1rTLzSmyL0_MUiktzFYr1chMLPEsUMkuiDWK1NICUYayusRaQNorVhBpqkJqcka-QrOEQrWGoY2SgY6CpA2QYG-gYAhm6hjomBjpmEBZQ0kgTpg_mKAA) Takes `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw. [Answer] # awk, ~~78~~ ~~76~~ ~~71~~ 69 bytes In the following, remove newline (that's only for readability) and save one byte. 1. 79 bytes ``` {s[$1]=s[$1]+$2-(3*$3)} END{print (s["A"]>s["B"])?"A":(s["A"]<s["B"])?"B":"="} ``` 2. 77 bytes ``` {s[$1]=s[$1]+$2-(3*$3)} END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="} ``` 3. 72 bytes ``` {s[$1]+=$2-(3*$3)} END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="} ``` 4. 70 bytes ``` {s[$1]+=$2-3*$3} END{a=s["A"];b=s["B"];print (a>b)?"A":(a<b)?"B":"="} ``` There must be some tricks, I dunno, to make it shorter. ## Usage and notes Use of AWK require some adaptation of the input. * The outer list is a file to pass to the script. * The inner lists are lines of the input file. * Items in sub lists are separated by blanks only. The example given (1 line for 57 bytes) ``` [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] ``` becomes then (4 lines for 28 bytes) ``` A 20 0 A 30 1 B 40 6 B 20 2 ``` Once the data file created, let's say `match.list`, call the script, let's say `twist.awk`, by issuing the command line ``` awk -f twist.awk match.list ``` You can also replace `-f twist.awk` with the script directly. ## Ungolfed/explanation For golfing purposes I've used `s` instead of a more useful variable name. ``` { # This is the main block, executed for each line s[$1]=s[$1]+$2-(3*$3) # Update Score table indexed by first field (team) # precisely, creation then update next iterations } END{ # This block is executed once after main processing print "A=" s["A"], # add this for debug purpose "B=" s["B"], "" ; (s["A"]>s["B"]) # if team A scores more than team B ? # then print "A" # says that A wins : # else (s["A"]<s["B"]) # if team A scores less than team B ? # then print "B" # says that B wins : # else print "=" # says it's a drawn } ``` For golfing purpose, we use [ternary operator](https://www.tutorialspoint.com/awk/awk_ternary_operators.htm) in place of the [if-then statement](https://linuxhandbook.com/awk-if-else/), and replace the `if (cond) {foo} else {bar}` becomes `(cond)?{foo}:{bar}` By the same way, `if (cond) {foo} else if (alt) {baz} else {bar}` becomes `(cond)?{foo}:(alt)?{baz}:{bar}` and here we can factorise `print`. [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 42 bytes Anonymous tacit prefix function. ``` ((2⊸=≠)+(⊢⊐⌊˝))(({𝕨-3×𝕩}´+˝)¨(⊐⊏˘)⊔(1⊸↓˘)) ``` [Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiJcbnRhYiDihpAg4p%2BoWydBJywgMjAsIDBdLCBbJ0EnLCAzMCwgMV0sIFsnQicsIDQwLCA2XSwgWydCJywgMjAsIDJd4p%2BpXG50ZXN0MCDihpAgW1snQScsIDEwMCwgNV0sIFsnQicsIDk1LCAyXV0gIyBBXG50ZXN0MSDihpAgW1snQScsIDIwLCAwXSwgWydBJywgMzAsIDFdLCBbJ0InLCA0MCwgNl0sIFsnQicsIDIwLCAyXV0gIyBCXG50ZXN0MiDihpAgW1snQScsIDUwLCAzXSwgWydBJywgNzAsIDVdLCBbJ0InLCAzNSwgMF0sIFsnQScsIDI1LCAxXSwgWydCJywgNjAsIDJdLCBbJ0InLCA0MCwgNF1dICMgQlxudGVzdDMg4oaQIOKfqOKfqSAjIERyYXdcblxuU29sMCDihpAgezA94omg4qWK8J2VqT8yOyjiipHiiqLiipDijIrCtCl7KHvwnZWoLTPDl%2FCdlal9wrQoK8ud4oi%2By5gpKcKoKOKKkOKKj8Ko8J2VqSniipQoMeKKuOKGk8Ko8J2VqSl9PMuY8J2VqX1cblNvbDEg4oaQICgoMuKKuD3iiaApKyjiiqLiipDijIrLnSkpKCh78J2VqC0zw5fwnZWpfcK0K8udKcKoKOKKkOKKj8uYKeKKlCgx4oq44oaTy5gpKVxuU29sMiDihpAgKOKKkSgy4oq4PeKJoCkrKOKKouKKkOKMisudKSkoKHvwnZWoLTPDl%2FCdlal9wrQry50pwqgo4oqQ4oqPy5gp4oqUKDHiirjihpPLmCkpXG5cblxuXG4iLCJwcmV2U2Vzc2lvbnMiOltdLCJjdXJyZW50U2Vzc2lvbiI6eyJjZWxscyI6W10sImNyZWF0ZWRBdCI6MTY3NTAwNTg3MTMzNX0sImN1cnJlbnRDZWxsIjp7ImZyb20iOjAsInRvIjo0NjYsInJlc3VsdCI6bnVsbH19) ### Explanation ``` ((2⊸=≠)+(⊢⊐⌊˝))(({𝕨-3×𝕩}´+˝)¨(⊐⊏˘)⊔(1⊸↓˘)) ⊔ Partition... (1⊸↓˘) the input with the first column dropped (⊐⊏˘) by the first column. ( )¨ Then for each partition (team)... +˝ sum-reduce it... {𝕨-3×𝕩}´ and calculate its score. ( + ) Then sum... (⊢⊐⌊˝) the index with the minimum value... (2⊸=≠) to whether the length is 2 ``` Some positives include that the code works on the original input *as is* (i.e. ``` [['A', 100, 5], ['B', 95, 2]] ``` is a valid input), and that it accepts any labelling of the teams (A/B, -1/1). Some negatives include that it doesn't apply the neat sign trick that everyone else is using and that it's (albeit lightly) hardcoded the number of teams to 2. Oh and that it's so damn long. Any help translating the regular strategy to an array language (APL, J, K etc.)? [Answer] # [C (clang)](http://clang.llvm.org/), ~~59~~ 58 bytes ``` s;f(*p){for(s=0;*p;)s+=*p++*(*p++-*p++*3);*p=(s>0)-(s<0);} ``` [Try it online!](https://tio.run/##bVLbjpswEH3PV4yQItkGVMDLtluH7UPVr0jQKgKzhW4dhGkaNeLXS8cYKGQTgT2cOXPmksn87O2oXvtei4Kwml6LU0N0EghWC6rdhNWuy4g5/cHkFD0J0c8B9YneBVR0/flU5lA3pWoJvuxM4boB/A1QQZy9Q8UAoDYYCpSQQCDgvOesTAW4bjnFLOO22vGQ/wVP57Pj0FFlpVRZpQp2wI1QtRRai21zI1eNcliUZwsAF6p0od29KySdGuhWfaVg8G5j6vh5LBWZchuglbp9CfYp1ncNPQiDwIPYAx/tJ7wjD4JOrNnhzI6QjA9a3F4m7AHNR2sa/z2FaFaIkcGH0I//E/N4ko3iWfbRak0ZHu7Iciu7wNng0Ba3rXpjE@MdjTe/EVM2BhsJkRJ@WqeTl1pmrcwtydRkn4mTnZRuIft@bBieMvshG0t1Dpdv0eHy9BXf2PzDi2/udLf7p3J5sZtjzR3o8o88FWQqgMKHCWIzNmyq4S@XzE4DxexEBn8q1jtE2uXurr5MOWqMVu@ijVcb717doBLReVp3k@KG@s@wzWGrDwpHor15ZDpJZLra6Ua2vxqFA9l0/d@seDu@6t7//Q8 "C (clang) – Try It Online") *Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!* Inputs a pointer to a \$0\$ terminated (because pointers in C don't carry any length info) array of integer triplets of the side (\$1\$ for the first team and \$-1\$ for the second), the time, and the number of hits. Returns (at the end of the input array) \$-1\$ for a win by the first team, \$1\$ for a win by the second, and \$0\$ for a draw. [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 35 bytes ``` ${$F[0]}+=$F[1]-$F[2]*3}{$\=$A<=>$B ``` [Try it online!](https://tio.run/##K0gtyjH9/1@lWsUt2iC2VtsWSBvG6gJJo1gt49pqlRhbFUcbWzsVp////@UXlGTm5xX/1/U11TMwNPivW5AIAA "Perl 5 – Try It Online") Teams are A & B. Input is one turn per line with numbers space separated from the team name. Output is -1 for team A, 0 for draw, 1 for team B. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96) \approx \$ 9.05 bytes ``` eAu3*-*ESza ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharUx1LjbV0tVyDqxIhIlCJBTe9o6N1DXUUTA10FIxjdRTAHHMgxxTEAbKNTXUUDGASRkCOIVTCDKjICMo2AbJNYmMhZgIA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wSLP6qWlJWm6FqtTHUuNtXS1XIOrEiEii6K8IYyl0UopSrE350RH6xrqKBgaGOgomMbqKEQDOZamOgpGsbFcECkjoIwBSAbEMQZyDKHKTIBsMygbpAihxRTIM4ZpMUcy2dgUySwjU4RZZmD9CHNNQGbFQlwKAA). Port of AndrovT's Vyxal answer #### Explanation ``` eAu3*-*ESza # Implicit input e E # Map over the input: Au # Dump the contents onto the stack 3* # Triple (the hits) - # Subtract (from the time) * # Multiply (by the team) S # Sum za # Sign # Implicit output ``` ]
[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/15678/edit). Closed 6 years ago. [Improve this question](/posts/15678/edit) Inspired by [The Most Useless Machine Ever](https://www.youtube.com/watch?v=Z86V_ICUCD4). Write the shortest program that does the following: * create a graphical window, then immediately close the window and exit the program. * do this in some visually apparent manner. Like the "arm" that pushes the switch in the machine, the program must use some visual method in the GUI to close itself. * this visual method must be what causes the program to close; you cannot just show it as something on the side (though there may be other things off to the side) Note: * The program does not have to be visible long enough for the visible activity to be seen by a human as long as the activity is the cause of the closing. * The window must be a GUI (must display a graphical window that contains the visible exit method). * The visual method needs to be something the user could do if it wasn't done automatically. Explain what needs to be changed in the code for the user to be able to do this (Thanks to Iszi). * The program must close if there is no interference from the user, but if the user interferes, then it does not need to close automatically. * Please include an explanation of what it is that causes the program to close. Example: a window containing a button which is programmatically clicked, running a short snippet of code that closes the program. [Answer] # Ruby with [Shoes](http://shoesrb.com), 110 ``` Shoes.app{button('Close'){exit} p=para t=Time.now animate{u=(t-Time.now).to_i+10 exit if u<0 p.text=' '*u+?<}} ``` Makes a little arrow that pushes a "Close" button. (Pushing the close button manually also closes the window.) ![screenshot](https://i.stack.imgur.com/YRRhl.png) [Answer] ## Windows Batch, 4 bytes Save the following program to a `.bat` file in your user folder (C:\Users\username): ``` Exit ``` When executed from the **Start, Run** prompt, a new window opens, types the command `Exit` and executes it. [Answer] # TI-Basic, 3 bytes ``` DispGraph:1 hex: 31 3E DF ``` **Explanation** `DispGraph` Displays the graph (a graphical window) `:1` Simulates a press of `1` (by storing `1` to `Ans` at the last step of a program), which takes the calculator back to the home screen. A user could do the same thing. [Answer] ### JavaScript: ~~133~~ 117 (You need to allow popups in your web browser for this to work) Code-golfed: ``` (function(){w=window.open(),d=999,i=setInterval(function(){w.resizeTo(d-=9,d),d<0&&(clearInterval(i),w.close())})})() ``` Source: <http://jsfiddle.net/gt2t8/2/> [Answer] ## [Golf-Basic 84](http://timtechsoftware.com/?page_id=1261 "Golf-Basic 84"), ~~5~~ 4 ``` g`:1 ``` Display the graph, simluate a press of 1, closing the graph and returning home. [Answer] ## x86 / Win32 assembly (~~337~~ ~~310~~ 271 bytes) ``` .586 .model flat option casemap:none include kernel32.inc include windows.inc include user32.inc i textequ <invoke> .code s:i CreateThread,0,0,$+46,0,0,0 i MessageBox,0,$,$,0 i ExitProcess,0 i Sleep,999 i FindWindow,0,$ i PostMessage,eax,256,13,0 ret END s ``` Assembles with MASM32 (`ml /c /coff /Gz /I<include path> test.asm` / `link /SUBSYSTEM:WINDOWS /LIBPATH:<library path> test.obj kernel32.lib user32.lib`). It creates a MessageBox with an *"OK"* button, and a thread that simulates a carriage return press from the user after 999 ms. The `$` is substituted with the address of the beginning of the `code` section by the assembler/linker. The first instruction is a `push byte 0` (implicitly, since it's generated by the `invoke`), which is encoded as `6A 00`, which equals the null-terminated string `"j"`. I take advantage of this when calling `MessageBox` and `FindWindow`. [Answer] # Bash with X Window System, 10 chars ``` xterm -e : ``` Open an xterm window, run the bash no-op `:`, after which the xterm window closes. If you want to see the useless window for a second, you can change the `:` to `sleep 1`: ``` xterm -e sleep 1 ``` [Answer] # Tcl/Tk, 131 ``` grid [button .b -command exit] event generate .b <Button-1> -warp 1 -x 5 -y 5 event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5 ``` # Tcl/Tk, 136 ``` grid [button .b -command exit] event generate .b <ButtonPress-1> -warp 1 -x 5 -y 5 event generate .b <ButtonRelease-1> -warp 1 -x 5 -y 5 ``` It needs to be ran on an interactive shell, line by line and user can not move the mouse between. 1. Application starts [![enter image description here](https://i.stack.imgur.com/QbGdd.png)](https://i.stack.imgur.com/QbGdd.png) 2. Button whose behaviour is to close the app is added to the app window [![enter image description here](https://i.stack.imgur.com/AGRzW.png)](https://i.stack.imgur.com/AGRzW.png) 3. Generate an event that presses down the mouse on the button — Altough the cursor is not visible in the screenshot it is over the button; it is visible the buttonhas been pressed because it now sunken in, and before it was embossed out. [![enter image description here](https://i.stack.imgur.com/9N4Dy.png)](https://i.stack.imgur.com/9N4Dy.png) 4. Finally generate an event that releases the mouse button up. a. Image before really sending it (before pressing Enter) [![enter image description here](https://i.stack.imgur.com/AmD9C.png)](https://i.stack.imgur.com/AmD9C.png) b. After Enter the interactive shell and the app windows just disappeared. [![enter image description here](https://i.stack.imgur.com/S1RUW.png)](https://i.stack.imgur.com/S1RUW.png) **Note to tcl'ers:** Tried to do the same directly on the window's X Close button using: ``` event generate . <ButtonPress-1> -warp 1 -x 175 -y -10 event generate . <ButtonRelease-1> -warp 1 -x 175 -y -10 ``` but I was not successful. [Answer] ## Bash - echo (50 bytes) **Not golfed, 54 bytes:** ``` s=sleep;echo -n \>\\;$s 1;echo -ne "\b\b >/";$s 1;echo ``` **Golfed, 50 bytes** I can't exactly display the golf version here because the backspace characters actually backspace. For the golf version, change both of the "^H" to single backspace (^H) characters: ``` s=sleep;echo -n \>\\;$s 1;echo -n ^H^H \>/;$s 1;echo ``` **Notes:** * The activity is visible for 2 seconds. * It doesn't use a window manager or anything of that sort, but I count the ASCII art as a "gui". If you are running the command in a terminal window, which is now the usual case, the activity is displayed in that window. It does not open up a new window. * The user can close the program sooner than the automatic close by hitting "CTRL-C" within 2 seconds of starting the program. Users who are more comfortable using their GUI can put their cursor on the little "X" in the corner of the terminal window, quickly, and "click" it. * The program closes after 2 seconds if there is no interference from the user. The user can only cause it to close sooner. * What causes the program to close is the completion of the final "echo". ]
[Question] [ There is a [question](https://codegolf.stackexchange.com/questions/487/implement-division) on the site that asks to implement division without using division. In my case, I am asking you to do the same, but only using addition. What this means is basically: addition is the only operator or function allowed that operates on numbers and returns other numbers (i.e. no subtraction, multiplication, exponentiation, bitwise inversion, etc.). Stuff like if statements, assignment and comparison operators, and for loops are still allowed, provided that within those, you still only use addition. Your task is to build a function `divide(a, b)` that takes two positive integers `a` and `b` and returns the result of `a` being divided by `b` and rounded toward zero, but using addition and no other arithmetical operators, and no other data constructs besides numbers. The code that wins will be the one that requires the fewest addition operations to be performed over the set of inputs where `a` varies from `1` to `200` and `b` varies from `1` to `a`. To keep track of this, you can build an alternate version of your code that replaces every instance of `a + b` with `add(a, b)` and program `add` to increment a global `add_used` variable as well as returning the sum of the two numbers. [Answer] Writing rules is hard, these rules in particular contain incentive to avoid additions at all costs. Is there a prize for the most ridiculous answer? ### JavaScript - 0 additions Now with fallback method that does a hulking solution for larger `a`'s and `b`'s, and a slightly more compact structure in order not to bust the character limit. (Pfff, 30000 characters. What is this? Twitter?) Still no additions in the measured scope. ``` function divide(a,b){ if(a<b){ return 0 } if(b==1){ return a } if(b==2){ if(a<4){return 1} if(a<6){return 2} if(a<8){return 3} if(a<10){return 4} if(a<12){return 5} if(a<14){return 6} if(a<16){return 7} if(a<18){return 8} if(a<20){return 9} if(a<22){return 10} if(a<24){return 11} if(a<26){return 12} if(a<28){return 13} if(a<30){return 14} if(a<32){return 15} if(a<34){return 16} if(a<36){return 17} if(a<38){return 18} if(a<40){return 19} if(a<42){return 20} if(a<44){return 21} if(a<46){return 22} if(a<48){return 23} if(a<50){return 24} if(a<52){return 25} if(a<54){return 26} if(a<56){return 27} if(a<58){return 28} if(a<60){return 29} if(a<62){return 30} if(a<64){return 31} if(a<66){return 32} if(a<68){return 33} if(a<70){return 34} if(a<72){return 35} if(a<74){return 36} if(a<76){return 37} if(a<78){return 38} if(a<80){return 39} if(a<82){return 40} if(a<84){return 41} if(a<86){return 42} if(a<88){return 43} if(a<90){return 44} if(a<92){return 45} if(a<94){return 46} if(a<96){return 47} if(a<98){return 48} if(a<100){return 49} if(a<102){return 50} if(a<104){return 51} if(a<106){return 52} if(a<108){return 53} if(a<110){return 54} if(a<112){return 55} if(a<114){return 56} if(a<116){return 57} if(a<118){return 58} if(a<120){return 59} if(a<122){return 60} if(a<124){return 61} if(a<126){return 62} if(a<128){return 63} if(a<130){return 64} if(a<132){return 65} if(a<134){return 66} if(a<136){return 67} if(a<138){return 68} if(a<140){return 69} if(a<142){return 70} if(a<144){return 71} if(a<146){return 72} if(a<148){return 73} if(a<150){return 74} if(a<152){return 75} if(a<154){return 76} if(a<156){return 77} if(a<158){return 78} if(a<160){return 79} if(a<162){return 80} if(a<164){return 81} if(a<166){return 82} if(a<168){return 83} if(a<170){return 84} if(a<172){return 85} if(a<174){return 86} if(a<176){return 87} if(a<178){return 88} if(a<180){return 89} if(a<182){return 90} if(a<184){return 91} if(a<186){return 92} if(a<188){return 93} if(a<190){return 94} if(a<192){return 95} if(a<194){return 96} if(a<196){return 97} if(a<198){return 98} if(a<200){return 99} if(a<202){return 100} } if(b==3){ if(a<6){return 1} if(a<9){return 2} if(a<12){return 3} if(a<15){return 4} if(a<18){return 5} if(a<21){return 6} if(a<24){return 7} if(a<27){return 8} if(a<30){return 9} if(a<33){return 10} if(a<36){return 11} if(a<39){return 12} if(a<42){return 13} if(a<45){return 14} if(a<48){return 15} if(a<51){return 16} if(a<54){return 17} if(a<57){return 18} if(a<60){return 19} if(a<63){return 20} if(a<66){return 21} if(a<69){return 22} if(a<72){return 23} if(a<75){return 24} if(a<78){return 25} if(a<81){return 26} if(a<84){return 27} if(a<87){return 28} if(a<90){return 29} if(a<93){return 30} if(a<96){return 31} if(a<99){return 32} if(a<102){return 33} if(a<105){return 34} if(a<108){return 35} if(a<111){return 36} if(a<114){return 37} if(a<117){return 38} if(a<120){return 39} if(a<123){return 40} if(a<126){return 41} if(a<129){return 42} if(a<132){return 43} if(a<135){return 44} if(a<138){return 45} if(a<141){return 46} if(a<144){return 47} if(a<147){return 48} if(a<150){return 49} if(a<153){return 50} if(a<156){return 51} if(a<159){return 52} if(a<162){return 53} if(a<165){return 54} if(a<168){return 55} if(a<171){return 56} if(a<174){return 57} if(a<177){return 58} if(a<180){return 59} if(a<183){return 60} if(a<186){return 61} if(a<189){return 62} if(a<192){return 63} if(a<195){return 64} if(a<198){return 65} if(a<201){return 66} } if(b==4){ if(a<8){return 1} if(a<12){return 2} if(a<16){return 3} if(a<20){return 4} if(a<24){return 5} if(a<28){return 6} if(a<32){return 7} if(a<36){return 8} if(a<40){return 9} if(a<44){return 10} if(a<48){return 11} if(a<52){return 12} if(a<56){return 13} if(a<60){return 14} if(a<64){return 15} if(a<68){return 16} if(a<72){return 17} if(a<76){return 18} if(a<80){return 19} if(a<84){return 20} if(a<88){return 21} if(a<92){return 22} if(a<96){return 23} if(a<100){return 24} if(a<104){return 25} if(a<108){return 26} if(a<112){return 27} if(a<116){return 28} if(a<120){return 29} if(a<124){return 30} if(a<128){return 31} if(a<132){return 32} if(a<136){return 33} if(a<140){return 34} if(a<144){return 35} if(a<148){return 36} if(a<152){return 37} if(a<156){return 38} if(a<160){return 39} if(a<164){return 40} if(a<168){return 41} if(a<172){return 42} if(a<176){return 43} if(a<180){return 44} if(a<184){return 45} if(a<188){return 46} if(a<192){return 47} if(a<196){return 48} if(a<200){return 49} if(a<204){return 50} } if(b==5){ if(a<10){return 1} if(a<15){return 2} if(a<20){return 3} if(a<25){return 4} if(a<30){return 5} if(a<35){return 6} if(a<40){return 7} if(a<45){return 8} if(a<50){return 9} if(a<55){return 10} if(a<60){return 11} if(a<65){return 12} if(a<70){return 13} if(a<75){return 14} if(a<80){return 15} if(a<85){return 16} if(a<90){return 17} if(a<95){return 18} if(a<100){return 19} if(a<105){return 20} if(a<110){return 21} if(a<115){return 22} if(a<120){return 23} if(a<125){return 24} if(a<130){return 25} if(a<135){return 26} if(a<140){return 27} if(a<145){return 28} if(a<150){return 29} if(a<155){return 30} if(a<160){return 31} if(a<165){return 32} if(a<170){return 33} if(a<175){return 34} if(a<180){return 35} if(a<185){return 36} if(a<190){return 37} if(a<195){return 38} if(a<200){return 39} if(a<205){return 40} } if(b==6){ if(a<12){return 1} if(a<18){return 2} if(a<24){return 3} if(a<30){return 4} if(a<36){return 5} if(a<42){return 6} if(a<48){return 7} if(a<54){return 8} if(a<60){return 9} if(a<66){return 10} if(a<72){return 11} if(a<78){return 12} if(a<84){return 13} if(a<90){return 14} if(a<96){return 15} if(a<102){return 16} if(a<108){return 17} if(a<114){return 18} if(a<120){return 19} if(a<126){return 20} if(a<132){return 21} if(a<138){return 22} if(a<144){return 23} if(a<150){return 24} if(a<156){return 25} if(a<162){return 26} if(a<168){return 27} if(a<174){return 28} if(a<180){return 29} if(a<186){return 30} if(a<192){return 31} if(a<198){return 32} if(a<204){return 33} } if(b==7){ if(a<14){return 1} if(a<21){return 2} if(a<28){return 3} if(a<35){return 4} if(a<42){return 5} if(a<49){return 6} if(a<56){return 7} if(a<63){return 8} if(a<70){return 9} if(a<77){return 10} if(a<84){return 11} if(a<91){return 12} if(a<98){return 13} if(a<105){return 14} if(a<112){return 15} if(a<119){return 16} if(a<126){return 17} if(a<133){return 18} if(a<140){return 19} if(a<147){return 20} if(a<154){return 21} if(a<161){return 22} if(a<168){return 23} if(a<175){return 24} if(a<182){return 25} if(a<189){return 26} if(a<196){return 27} if(a<203){return 28} } if(b==8){ if(a<16){return 1} if(a<24){return 2} if(a<32){return 3} if(a<40){return 4} if(a<48){return 5} if(a<56){return 6} if(a<64){return 7} if(a<72){return 8} if(a<80){return 9} if(a<88){return 10} if(a<96){return 11} if(a<104){return 12} if(a<112){return 13} if(a<120){return 14} if(a<128){return 15} if(a<136){return 16} if(a<144){return 17} if(a<152){return 18} if(a<160){return 19} if(a<168){return 20} if(a<176){return 21} if(a<184){return 22} if(a<192){return 23} if(a<200){return 24} if(a<208){return 25} } if(b==9){ if(a<18){return 1} if(a<27){return 2} if(a<36){return 3} if(a<45){return 4} if(a<54){return 5} if(a<63){return 6} if(a<72){return 7} if(a<81){return 8} if(a<90){return 9} if(a<99){return 10} if(a<108){return 11} if(a<117){return 12} if(a<126){return 13} if(a<135){return 14} if(a<144){return 15} if(a<153){return 16} if(a<162){return 17} if(a<171){return 18} if(a<180){return 19} if(a<189){return 20} if(a<198){return 21} if(a<207){return 22} } if(b==10){ if(a<20){return 1} if(a<30){return 2} if(a<40){return 3} if(a<50){return 4} if(a<60){return 5} if(a<70){return 6} if(a<80){return 7} if(a<90){return 8} if(a<100){return 9} if(a<110){return 10} if(a<120){return 11} if(a<130){return 12} if(a<140){return 13} if(a<150){return 14} if(a<160){return 15} if(a<170){return 16} if(a<180){return 17} if(a<190){return 18} if(a<200){return 19} if(a<210){return 20} } if(b==11){ if(a<22){return 1} if(a<33){return 2} if(a<44){return 3} if(a<55){return 4} if(a<66){return 5} if(a<77){return 6} if(a<88){return 7} if(a<99){return 8} if(a<110){return 9} if(a<121){return 10} if(a<132){return 11} if(a<143){return 12} if(a<154){return 13} if(a<165){return 14} if(a<176){return 15} if(a<187){return 16} if(a<198){return 17} if(a<209){return 18} } if(b==12){ if(a<24){return 1} if(a<36){return 2} if(a<48){return 3} if(a<60){return 4} if(a<72){return 5} if(a<84){return 6} if(a<96){return 7} if(a<108){return 8} if(a<120){return 9} if(a<132){return 10} if(a<144){return 11} if(a<156){return 12} if(a<168){return 13} if(a<180){return 14} if(a<192){return 15} if(a<204){return 16} } if(b==13){ if(a<26){return 1} if(a<39){return 2} if(a<52){return 3} if(a<65){return 4} if(a<78){return 5} if(a<91){return 6} if(a<104){return 7} if(a<117){return 8} if(a<130){return 9} if(a<143){return 10} if(a<156){return 11} if(a<169){return 12} if(a<182){return 13} if(a<195){return 14} if(a<208){return 15} } if(b==14){ if(a<28){return 1} if(a<42){return 2} if(a<56){return 3} if(a<70){return 4} if(a<84){return 5} if(a<98){return 6} if(a<112){return 7} if(a<126){return 8} if(a<140){return 9} if(a<154){return 10} if(a<168){return 11} if(a<182){return 12} if(a<196){return 13} if(a<210){return 14} } if(b==15){ if(a<30){return 1} if(a<45){return 2} if(a<60){return 3} if(a<75){return 4} if(a<90){return 5} if(a<105){return 6} if(a<120){return 7} if(a<135){return 8} if(a<150){return 9} if(a<165){return 10} if(a<180){return 11} if(a<195){return 12} if(a<210){return 13} } if(b==16){ if(a<32){return 1} if(a<48){return 2} if(a<64){return 3} if(a<80){return 4} if(a<96){return 5} if(a<112){return 6} if(a<128){return 7} if(a<144){return 8} if(a<160){return 9} if(a<176){return 10} if(a<192){return 11} if(a<208){return 12} } if(b==17){ if(a<34){return 1} if(a<51){return 2} if(a<68){return 3} if(a<85){return 4} if(a<102){return 5} if(a<119){return 6} if(a<136){return 7} if(a<153){return 8} if(a<170){return 9} if(a<187){return 10} if(a<204){return 11} } if(b==18){ if(a<36){return 1} if(a<54){return 2} if(a<72){return 3} if(a<90){return 4} if(a<108){return 5} if(a<126){return 6} if(a<144){return 7} if(a<162){return 8} if(a<180){return 9} if(a<198){return 10} if(a<216){return 11} } if(b==19){ if(a<38){return 1} if(a<57){return 2} if(a<76){return 3} if(a<95){return 4} if(a<114){return 5} if(a<133){return 6} if(a<152){return 7} if(a<171){return 8} if(a<190){return 9} if(a<209){return 10} } if(b==20){ if(a<40){return 1} if(a<60){return 2} if(a<80){return 3} if(a<100){return 4} if(a<120){return 5} if(a<140){return 6} if(a<160){return 7} if(a<180){return 8} if(a<200){return 9} if(a<220){return 10} } if(b==21){ if(a<42){return 1} if(a<63){return 2} if(a<84){return 3} if(a<105){return 4} if(a<126){return 5} if(a<147){return 6} if(a<168){return 7} if(a<189){return 8} if(a<210){return 9} } if(b==22){ if(a<44){return 1} if(a<66){return 2} if(a<88){return 3} if(a<110){return 4} if(a<132){return 5} if(a<154){return 6} if(a<176){return 7} if(a<198){return 8} if(a<220){return 9} } if(b==23){ if(a<46){return 1} if(a<69){return 2} if(a<92){return 3} if(a<115){return 4} if(a<138){return 5} if(a<161){return 6} if(a<184){return 7} if(a<207){return 8} } if(b==24){ if(a<48){return 1} if(a<72){return 2} if(a<96){return 3} if(a<120){return 4} if(a<144){return 5} if(a<168){return 6} if(a<192){return 7} if(a<216){return 8} } if(b==25){ if(a<50){return 1} if(a<75){return 2} if(a<100){return 3} if(a<125){return 4} if(a<150){return 5} if(a<175){return 6} if(a<200){return 7} if(a<225){return 8} } if(b==26){ if(a<52){return 1} if(a<78){return 2} if(a<104){return 3} if(a<130){return 4} if(a<156){return 5} if(a<182){return 6} if(a<208){return 7} } if(b==27){ if(a<54){return 1} if(a<81){return 2} if(a<108){return 3} if(a<135){return 4} if(a<162){return 5} if(a<189){return 6} if(a<216){return 7} } if(b==28){ if(a<56){return 1} if(a<84){return 2} if(a<112){return 3} if(a<140){return 4} if(a<168){return 5} if(a<196){return 6} if(a<224){return 7} } if(b==29){ if(a<58){return 1} if(a<87){return 2} if(a<116){return 3} if(a<145){return 4} if(a<174){return 5} if(a<203){return 6} } if(b==30){ if(a<60){return 1} if(a<90){return 2} if(a<120){return 3} if(a<150){return 4} if(a<180){return 5} if(a<210){return 6} } if(b==31){ if(a<62){return 1} if(a<93){return 2} if(a<124){return 3} if(a<155){return 4} if(a<186){return 5} if(a<217){return 6} } if(b==32){ if(a<64){return 1} if(a<96){return 2} if(a<128){return 3} if(a<160){return 4} if(a<192){return 5} if(a<224){return 6} } if(b==33){ if(a<66){return 1} if(a<99){return 2} if(a<132){return 3} if(a<165){return 4} if(a<198){return 5} if(a<231){return 6} } if(b==34){ if(a<68){return 1} if(a<102){return 2} if(a<136){return 3} if(a<170){return 4} if(a<204){return 5} } if(b==35){ if(a<70){return 1} if(a<105){return 2} if(a<140){return 3} if(a<175){return 4} if(a<210){return 5} } if(b==36){ if(a<72){return 1} if(a<108){return 2} if(a<144){return 3} if(a<180){return 4} if(a<216){return 5} } if(b==37){ if(a<74){return 1} if(a<111){return 2} if(a<148){return 3} if(a<185){return 4} if(a<222){return 5} } if(b==38){ if(a<76){return 1} if(a<114){return 2} if(a<152){return 3} if(a<190){return 4} if(a<228){return 5} } if(b==39){ if(a<78){return 1} if(a<117){return 2} if(a<156){return 3} if(a<195){return 4} if(a<234){return 5} } if(b==40){ if(a<80){return 1} if(a<120){return 2} if(a<160){return 3} if(a<200){return 4} if(a<240){return 5} } if(b==41){ if(a<82){return 1} if(a<123){return 2} if(a<164){return 3} if(a<205){return 4} } if(b==42){ if(a<84){return 1} if(a<126){return 2} if(a<168){return 3} if(a<210){return 4} } if(b==43){ if(a<86){return 1} if(a<129){return 2} if(a<172){return 3} if(a<215){return 4} } if(b==44){ if(a<88){return 1} if(a<132){return 2} if(a<176){return 3} if(a<220){return 4} } if(b==45){ if(a<90){return 1} if(a<135){return 2} if(a<180){return 3} if(a<225){return 4} } if(b==46){ if(a<92){return 1} if(a<138){return 2} if(a<184){return 3} if(a<230){return 4} } if(b==47){ if(a<94){return 1} if(a<141){return 2} if(a<188){return 3} if(a<235){return 4} } if(b==48){ if(a<96){return 1} if(a<144){return 2} if(a<192){return 3} if(a<240){return 4} } if(b==49){ if(a<98){return 1} if(a<147){return 2} if(a<196){return 3} if(a<245){return 4} } if(b==50){ if(a<100){return 1} if(a<150){return 2} if(a<200){return 3} if(a<250){return 4} } if(b==51){ if(a<102){return 1} if(a<153){return 2} if(a<204){return 3} } if(b==52){ if(a<104){return 1} if(a<156){return 2} if(a<208){return 3} } if(b==53){ if(a<106){return 1} if(a<159){return 2} if(a<212){return 3} } if(b==54){ if(a<108){return 1} if(a<162){return 2} if(a<216){return 3} } if(b==55){ if(a<110){return 1} if(a<165){return 2} if(a<220){return 3} } if(b==56){ if(a<112){return 1} if(a<168){return 2} if(a<224){return 3} } if(b==57){ if(a<114){return 1} if(a<171){return 2} if(a<228){return 3} } if(b==58){ if(a<116){return 1} if(a<174){return 2} if(a<232){return 3} } if(b==59){ if(a<118){return 1} if(a<177){return 2} if(a<236){return 3} } if(b==60){ if(a<120){return 1} if(a<180){return 2} if(a<240){return 3} } if(b==61){ if(a<122){return 1} if(a<183){return 2} if(a<244){return 3} } if(b==62){ if(a<124){return 1} if(a<186){return 2} if(a<248){return 3} } if(b==63){ if(a<126){return 1} if(a<189){return 2} if(a<252){return 3} } if(b==64){ if(a<128){return 1} if(a<192){return 2} if(a<256){return 3} } if(b==65){ if(a<130){return 1} if(a<195){return 2} if(a<260){return 3} } if(b==66){ if(a<132){return 1} if(a<198){return 2} if(a<264){return 3} } if(b==67){ if(a<134){return 1} if(a<201){return 2} } if(b==68){ if(a<136){return 1} if(a<204){return 2} } if(b==69){ if(a<138){return 1} if(a<207){return 2} } if(b==70){ if(a<140){return 1} if(a<210){return 2} } if(b==71){ if(a<142){return 1} if(a<213){return 2} } if(b==72){ if(a<144){return 1} if(a<216){return 2} } if(b==73){ if(a<146){return 1} if(a<219){return 2} } if(b==74){ if(a<148){return 1} if(a<222){return 2} } if(b==75){ if(a<150){return 1} if(a<225){return 2} } if(b==76){ if(a<152){return 1} if(a<228){return 2} } if(b==77){ if(a<154){return 1} if(a<231){return 2} } if(b==78){ if(a<156){return 1} if(a<234){return 2} } if(b==79){ if(a<158){return 1} if(a<237){return 2} } if(b==80){ if(a<160){return 1} if(a<240){return 2} } if(b==81){ if(a<162){return 1} if(a<243){return 2} } if(b==82){ if(a<164){return 1} if(a<246){return 2} } if(b==83){ if(a<166){return 1} if(a<249){return 2} } if(b==84){ if(a<168){return 1} if(a<252){return 2} } if(b==85){ if(a<170){return 1} if(a<255){return 2} } if(b==86){ if(a<172){return 1} if(a<258){return 2} } if(b==87){ if(a<174){return 1} if(a<261){return 2} } if(b==88){ if(a<176){return 1} if(a<264){return 2} } if(b==89){ if(a<178){return 1} if(a<267){return 2} } if(b==90){ if(a<180){return 1} if(a<270){return 2} } if(b==91){ if(a<182){return 1} if(a<273){return 2} } if(b==92){ if(a<184){return 1} if(a<276){return 2} } if(b==93){ if(a<186){return 1} if(a<279){return 2} } if(b==94){ if(a<188){return 1} if(a<282){return 2} } if(b==95){ if(a<190){return 1} if(a<285){return 2} } if(b==96){ if(a<192){return 1} if(a<288){return 2} } if(b==97){ if(a<194){return 1} if(a<291){return 2} } if(b==98){ if(a<196){return 1} if(a<294){return 2} } if(b==99){ if(a<198){return 1} if(a<297){return 2} } if(b==100){ if(a<200){return 1} if(a<300){return 2} } if(b<=200 && a<=200){ return 1 } var result=0 var counter=b for(;a>=counter;counter=add(counter,b)){ result=add(result,1) } return result } ``` [Answer] # Tcl, 0 additions ``` proc divide {a b} { set sa [string repeat . $a] set sb [string repeat . $b] set sr "" while 1 { append sc $sb if {[string le $sc]>[string le $sa]} break append sr . } return [string le $sr] } ``` Why not use strings? [Answer] ## Haskell 0 additions, 29 bytes ``` n/m=[i|i<-[0..],_<-[1..m]]!!n ``` this redefines the division operator (`/`). it works by making a list of `0` to infinity where each item is repeated `m` times, and then choosing the nth element of the list (using a 0-based index). [Answer] Use this implementation in java, 199206 additions ``` public int divide(int a, int b){ int counter = 0; int c = 0; if(b==1){ return a; } if(a==b){ return 1; } else{ boolean done = false; while(!done){ c = add(c, b); if(a<c){ done = true; } counter = add(counter,1); } return counter; } } ``` Following are the helper functions ``` public static void main(String[] args) { Main main = new Main(); for(int a = 1; a<=200; a++){ for(int b=1;b<=a;b++){ main.divide(a, b); } } System.out.println("Number of additions: "+numberOfAdds); } public int add(int a, int b){ numberOfAdds++; return (a+b); } ``` [Answer] ## Python - 0 additions ``` from itertools import repeat, count def divide(a, b): i = repeat(0, a) try: for j in count(): for k in repeat(0, b): next(i) except: return j ``` This uses an iterator of length `a`, and consumes it in groups of `b` until `StopIteration` is raised. At this point `j` contains the result. [Answer] My solution is C/C++ code and it makes many additions (200402), but anyway... ``` #include <iostream> int total = 0; int sum(int a, int b) { ++total; return a + b; } int divide(int a, int b) { int x = 1; if (a < b) return 0; else return sum(x, divide(sum(a, -b), b)); } int main() { for (int i = 1; i <= 200; ++i) for (int j = 1; j <= 200; ++j) { if (divide(i, j) != (i / j)) std::cout << "Failure: a=" << i << " b=" << j << "\n"; } std::cout << "Total additions: " << total << std::endl; system("pause"); } ``` And the output is: ``` Total additions: 200402 Press any key to continue . . . ``` [Answer] # Python, 320703 additions ``` def divide(a, b): quotient = 0 c = 0 d = 0 while add(d, b) <= a: c = add(c, 1) d = add(d, b) return c ``` As always, a last-place reference answer. This simply adds `1` to a "quotient" and `b` to a "remultiplication" variable until it hits `a`. Here is the debugging code: ``` add_used = 0 def add(a, b): global add_used add_used += 1 return a + b for a in range(1, 201): for b in range(1, a+1): print "%d / %d = %d" % (a, b, divide(a, b)) print "Additions used:", add_used ``` [Answer] # Tcl, 0 additions. Well, I had to find a way that does not use other data structures but is still not what you want: ``` # coroutine counter. proc ccnt {} {yield [info level]; ccnt} # add implementation without add. proc cadd {a b} { set last 2 coroutine cadda ccnt coroutine caddb ccnt while {[cadda]<=$a} {} while {[caddb]<=$b} {set last [cadda]} rename cadda {} rename caddb {} return $last } proc divide {a b {c 0}} { if {$c == 0} {set c $b} {set c [cadd $b $c]} if {$c>$a} {tailcall info level} divide $a $b $c } ``` Uses the current stack size of different green threads. [Answer] C++ ,100201 ``` for(int a = 1; a<=200; a++){ for(int b=1;b<=a;b++){ iter1 = iter2 = b; cout<<a<<" "<<b<<endl; c1 =0; while(iter1 <= a) { iter1 = iter1 + iter2; c1 ++; nadd++; } cout<<"Quotient : "<<c1; cout<<" Remainder :"<<a - (iter1 - iter2)<<endl; } } cout<<"total of add "<<nadd; ``` [Answer] # Mathematica 100201 additions This adds the divisor, `b`, to `c` (which is initialized at 0) as long as the running total is less than or equal to the dividend, `a`. It also appends the current value of `c` to a list, `t`, without performing any arithmetic operation. When the `While` loop terminates the function outputs the length of `t`, which will correspond exactly to the quotient of integer division. Thus the number of additions for any given `divide[a,b]` will equal precisely the quotient. 100201 is the sum of the quotients in the 200 by 200 table. That's how many times `c` was incremented by `b`. No other additions were required. Only positive integers were used. ``` divide[a_, b_] := Module[{c = 0, t = {}}, While[c <= a, t = Append[t, c]; c += b]; Length[Rest@t]] ``` --- It's more efficient to make a lookup table, after which each search will be almost instantaneous. ``` n = 200; d[a_, b_] := Module[{c = 0, t = {}}, While[c <= a, t = Append[t, c]; c += b]; Length[Rest@t]] quotients = PadRight[#, n] & /@ Table[d[i, j], {i, 1, n}, {j, 1, i}]; divide[a_, b_] := quotients[[a, b]] ``` **Usage** ``` divide[97, 13] ``` > > 7 > > > [Answer] ### R - 0 addition ``` divide<-function(a,b){ options(warn=-1) A<-matrix(1:b,nrow=a,ncol=1) length(split(A,A)[[b]]) } ``` Uses R vector recycling. Second line creates a matrix of length `a` populated by a vector of length `b`which is recycled until reaching length `a`. Third line split the matrix according to its value and return the length of the last element (hence the result of the integer division of `a` by `b`). Populating a matrix with a vector which length is not a multiple of the length of the matrix throws a warning but if we suppress warning beforehand (line 1) it works. To give a concrete example if we divide 5 by 3, `A` will be a vector containing 1 2 3 1 2 (i. e. 1 2 3 recycled to a length 5). The result of the splitting operation will be a list with the first element containing 1 1, the second 2 2 and the third 3 (since there is only one 3 in `A`). The result is therefore 1. [Answer] In Ruby, ``` def divide(a,b) n, d = 'x' * a, 'x' * b l = [] (l << 'x'; d << 'x' * b) while n.size >= d.size l.size end ``` I don't know TCL, but I suspect this is the same approach as @Johannes ' (first) answer. [Answer] **Java: 92 987 additions** I use binary recursion, that `a/b == 2 * a/(2b) + maybe 1`. For that divisor *and* remainder are needed. There would normally be a subtraction a % (2b) - b, but that is resolved by holding the remainder as `(rem, remNegative)`. And `2b = b+b` of course. ``` static int add_used; static int add(int a, int b) { if (a == 0) return b; if (b == 0) return a; ++add_used; return a + b; } private static class DivRem { int div; int rem; int remNegative; DivRem(int div, int rem) { this.div = div; this.rem = rem; } } public static int divide(int a, int b) { add_used = 0; return divrem(a, b).div; } public static DivRem divrem(int a, int b) { if (b > a) { return new DivRem(0, a); } DivRem dr = divrem(a, add(b, b)); dr.div = add(dr.div, dr.div); if (dr.rem >= add(b, dr.remNegative)) { dr.div = add(dr.div, 1); //dr.rem = add(dr.rem, -b); dr.remNegative = add(dr.remNegative, b); } return dr; } private static void test(int a, int b) { boolean okay = a/b == divide(a, b); System.out.printf("%d / %d = %d :: %d : #%d %s%n", a, b, a/b, divide(a, b), add_used, okay); } public static void main(String[] args) { //test(2352, 324); int n = 0; for (int a = 1; a <= 200; ++a) { for (int b = 1; b <= a; ++b) { //test(a, b); divide(a, b); n += add_used; } } System.out.println("Additions: " + n); } ``` [Answer] ``` //a lies between 1 and 200, b lies between 1 and a. int divide(int a,int b){ int x=a,y=b; int count=1; while(y<x){ y+=y; count++; } return count; } ``` [Answer] ## C# - 0 additions ``` using System.Collections.Generic; using System.Linq; static int Divide(int a, int b) { var ints = new List<int>(a); while (ints.Count < a) ints.AddRange(Enumerable.Range(1, b)); return ints.Select((x, i) => x == b && i < a).Count(x => x); } ``` Populates a list of integers with `1..b` repeated `a` times. The number of times `b` appears (except for the occurrence with an index > `a`) is the result. I'm not sure if the list is allowed by the rules, but I'm submitting this in the spirit of the other posts which aren't taking the rules all that seriously (after all, not using addition at all is basically bypassing the challenge altogether). [Answer] ## C — 85591 Additions Here we go. I think this might be optimal. It uses a technique of "reverse division" whereby through long multiplication it builds up the largest number `q` such that `q * b <= a`, using only `+` and `<=`. It is very, very fast. ``` #include <stdio.h> #include <assert.h> // Division function. q,u,v,z=0;s(a,b){return!a?b:!b?a:(z++,a+b);} d(a,b,p){if((v=s(b,b))<=a)d(a,v,s(p,p));if((v=s(u,b))<=a)u=v,q=s(p,q);} divide(a,b){u=q=0;d(a,b,1);return q;} // Test driver. main(){for(int a=1;a<=200;a++)for(int b=1;b<=a;b++)assert(divide(a,b)==q); printf("%d additions\n",z);} ``` **Notes:** 1. `s(a,b)` returns the sum `a+b` and increments counter variable `z` each time an addition is performed. If either `a` or `b` is zero, the unnecessary addition is avoided. 2. `d(a,b,p)` is a recursive function to build up the internal portions for comparison and addition. It uses global variables `q`, `u`, and `v`. Maximum recursion depth is the number of bits in `a`, and the recursion is linear rather than a tree. (Note: the `b` in this function is the original `b` multiplied by a power of 2.) 3. `divide(a,b)` returns floor(a/b) as required. 4. Compiles with warnings (because code is golfed). Runs fine. [Answer] ## J, 0 additions, 14 bytes Inspired by [Alexei Kopylov's answer](https://codegolf.stackexchange.com/a/38581/1426). ``` f=:[{]#i.@>:@[ ``` Uses no maths at all: ``` f=: NB. define function f [ NB. take left argument, >:@ NB. increment it, i.@ NB. generate the list [0..left arg+1) ]# NB. replicate each item in the list by the right argument NB. (so if ]=2, list becomes 0 0 1 1 2 2 3 3 ...) [{ NB. select the ['th item from that list. ``` ]
[Question] [ Yesterday, as part of a IQ-style test, I got this interesting question: > > The time on a 24-hour clock is 11:43. What is the least number of minutes I should wait before the same digits are on the screen again (in any valid 24-hour time order)? > > > The answer's 91 minutes, if you were wondering! This stuck in my mind, and it finds its way... here. In an adapted form, however... Your task is, given a 24-hour time string in the format `HH:MM` (or in any other way as long as it provides `HH` and `MM`), shift the digits around until you find 24-hour time strings that would be in the same day counting forwards, and pick the one whose distance to the input is the shortest. Then return the number of minutes to the picked time string as an integer, using default output rules. ## Method: See above. ## Input: Allow facilities for input such that 2 digits of hours and 2 digits of minutes are provided. Do not worry about invalid input (example: `25:12`, `1:34` [`01:34` will be correct, however], and `05:89`). You cannot use 12-hour system. ## Output: An integer. Note that it should be in minutes, not seconds or any other unit (this is fixed) Return a distinct value (like 1440, an error, etc. I'm using "Nil" in the test-cases) when no valid shifted 24-hour time string can be created until 23:59. ## Test cases: ``` Input (HH:MM) -> Output (Int or "Nil") 11:43 -> 91 01:01 -> 9 17:38 -> 59 14:21 -> 413 13:20 -> 413 23:41 -> Nil 00:00 -> Nil ``` # Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 135 bytes ``` Min@(s=Select)[(x@#~f~60-a~f~60)&/@s[Permutations[p=#],(w=x@#;24>w[[1]]>=#&@@(a=x@p)&&w[[2]]<60)&],#>0&]& x=BlockMap[f=FromDigits,#,2]& ``` [Try it online!](https://tio.run/##LcxNa4QwEIDh@/6KQiAoTFGjdAvdSPpBbwsLPYYcgkQbNlGraRVk96@n06WHMA8vM/E6fBqvg210fHVGT8/OyRVa6OEHFvDwBVrtOh6PthfJzD@MM01IZbIKcm2vD/m9vo2UZmKWJzP574C/Df0sR04UJAvHzSdW1YuUhVI1J1SIRGMdU0oxMqUOf/cKSJ1TRXcrf3FDcz7qUbb8fRr8m@1smIEAUzSeJtuHu0x0mdi2AgqooLzAlqPwoQrYQwmPN1XA/luJylEMVWG7xPgL "Wolfram Language (Mathematica) – Try It Online") -6 bytes from @att [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` œ2δôʒŽ9¦2ô‹P}60δβć-ʒ0›}ß ``` Input as a single 4-digit string in the format `HHmm`. Outputs an empty string if there is no result available. [Try it online](https://tio.run/##ATYAyf9vc2FiaWX//8WTMs60w7TKksW9OcKmMsO04oC5UH02MM60zrLEhy3KkjDigLp9w5///zExNDM) or [verify all test cases](https://tio.run/##AWAAn/9vc2FiaWX/dnk/IiDihpIgIj95/8WTMs60w7TKksW9OcKmMsO04oC5UH02MM60zrLEhy3KkjDigLp9w5//LP9bMTE0MywiMDEwMSIsMTczOCwxNDIxLDEzMjAsMjM0MV0). **Explanation:** ``` œ # Get all permutations of the (implicit) input-string δ # Map over each permutation: 2 ô # Split it into parts of size 2 (to split HH and mm) ʒ # Filter this list of [HH,mm] by: Ž9¦ # Push compressed integer 2460 2ô # Split it into parts of size 2 as well: [24,60] ‹ # Check [HH<24,mm<60] P # And check if both are truthy by taking the product } δ # After the filter: map over the remaining [HH,mm]: 60 β # Convert it from a base-60 list to a base-10 integer ć # Extract head; pop and push remainder-list and first item separately - # Subtract this head (the input) from all other valid permutations ʒ0›} # Only keep all positive integers from the list with a filter on 0> # (a.k.a. keep all integers for times later than the input-time) ß # After the filter: pop and leave the minimum # (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¦` is `2460`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 84 bytes ``` x=>(g=y=>++y>2399?+g:y%100<60?(e=t=>[...1e4+t+g].sort()+0)(x)==e(y)||g(y)+1:g(y))(x) ``` [Try it online!](https://tio.run/##fc5NCoMwEAXgfU/hppgwNGZM@qM0eoNeoHQhbQwWMUVDUfDuVqHShdJZzMD7eDDP7J0197p4uV1lH3rI1dCqhBjVqQSgS0IRRSmYuNsi5@cDT4lWTiVXxhhqCQ7MjTW2doQCp6SlSmnS0b434waMpzPFw91WjS01K60hkBPwEaXwKfWCwItws2COHGdeKh7F6av7NZbhXJYoVlyE/J@HQs79S1GuPDfOz4cP "JavaScript (Node.js) – Try It Online") [Answer] # JavaScript (ES6), 96 bytes Expects `("HH")("MM")`. Returns `NaN` for `Nil`. ``` h=>F=(m,s=h+m)=>(m=-~m%60)||++h<24?(g=s=>[...s].sort().slice(-4)+0)(s)==g("00"+h+m)||1+F(m,s):+F ``` [Try it online!](https://tio.run/##dc7LCsIwEIXhvU8hAWGG2Ji08YpTd136AuJCam/SNtKIq@KrV1IVweJmNufjZy6n@8nGTXG9ebU5J11KXU5hRFBNLeW8QgqhIu9RTRYS25bzfOvrHWRkKTwIIexRWNPcAIUtizgBTyOXCBaJMmBSMu4ibat45JK44VEXm9qaMhGlySAFphRDYDpgiOPZbLxWox8ge@DuC/zuaun2YPXe50OgHfA/Aa2CgQh6If8Lvxf609gX5eBN2b8pv6J7Ag "JavaScript (Node.js) – Try It Online") ### Commented ``` h => // outer function taking h = hours F = ( // inner recursive function taking m, // m = minutes s = h + m // s = concatenation of the original hours and minutes ) => // (m = -~m % 60) // increment the minutes modulo 60 || // ignore the next statement if the result is not 0 ++h < 24 // otherwise, increment the hours and make sure they are ? // less than 24; if successful: ( g = s => // g is a helper function taking a string s [...s] // split s into a list of characters .sort() // sort them lexicographically .slice(-4) // take the last 4 characters + 0 // coerce back to a string with a trailing '0' )(s) == // invoke g with s and compare the result with g( // the same operation applied to ... "00" + // two leading zeros h + m // followed by h, followed by m ) // || // stop if it matches; otherwise, 1 + // increment the final result F(m, s) // and do a recursive call : // else: +F // force the result to NaN and stop ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `g`, ~~24 23~~ 22 bytes ``` Ṗ½'‛0xC½<Π;ƛE60β;ḣ$-'Ṡ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJnIiwiIiwi4bmWwr0n4oCbMHhDwr08zqA7xptFNjDOsjvhuKMkLSfhuaAiLCIiLCJcIjExNDNcIiJd) Port of Kevin Cruijssen's 05AB1E answer. Input as a string, `"HHmm"`. *-1 thanks to AndrovT [in chat](https://chat.stackexchange.com/transcript/message/62965671#62965671)* *-1 thanks to lyxal* #### Explanation ``` Ṗ½'‛0xC½<Π;ƛE60β;ḣ$-'Ṡ # Implicit input Ṗ # Permutations ½ # Split each in half ' ; # Filter: ‛0xC½ # Push [24, 60] < # Less than [24, 60]? Π # Both are true? ƛ ; # Map: E # Convert to integer 60β # Convert from base-60 ḣ$ # Extract head and swap - # Subtract head from rest ' # Filter: Ṡ # Positive integers only # g flag gets minimum # Implicit output ``` [Answer] # [Python](https://www.python.org), 132 bytes ``` lambda x:(a:=x.split(':'),b:=int(a[0])*60+int(a[1]),*[i for i in range(b+1,1440)if sorted(f"{i%60:02}:{i//60:02}")==sorted(x)])[2]-b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NTsMwEIX3nMIKquppE-qx3R9GMkfgAiELR63BUppEqZGCKna9QxdsIiG4E7dBKCXpambeN0_vfXzXb-GlKrtPZ56-XoNLNj-nwu7zrWUtcUumvTvUhQ98SlOIczK-DNymIoPZSsz7AzOIZ6lnrmqYZ75kjS2fdzyfY4xaC_COHaom7LbcRUc_WQkS8p2OfrHo1wiMuTy0kEEqsyS_dDnXzV-G4xEiaRUB3LLkgd3jzQAEksABjDquSW3-9eU10CQHg0Z1RRRJMVrESKQiPXgefdHX67p-_gI) Throws a error if there is no valid output. # [Python](https://www.python.org), 113 bytes ``` lambda x,y:(b:=x*60+y,*[i for i in range(b+1,1440)if sorted((e:="%02d%02d")%divmod(i,60))==sorted(e%(x,y))])[1]-b ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bc5NCsIwEAXgvacISiHTTiFp4l8hHsELqIuWNBqwrdYq9giewU1B9E7eRsVWXbgYBj4eb-Z821TlKs_qi1Hz6740_ui-XUdprCNyxCqkcaiO7oB5FbozS0xeEEtsRoooWyY09jhyKRlYQ3Z5USaa0iRUXYcF-jVdcLQ9pLmmFgcMQKkmlTj02Q6wgBlf-HFz-LQpbFZSQzlHKQB6xJ-QMe98GHmLXxuiGDXa_2GJQRuWXHxdYMD-eCBQtvmpXb8fquv3fgA) Takes input as 2 numbers [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes ``` ≔↨I⪪θ:⁶⁰ηI⌊Φ…¹⁻¹⁴⁴⁰η⬤I…¹χ⁼№θλ№I↨¹⁰⁰↨⁺ηι⁶⁰λ ``` [Try it online!](https://tio.run/##PU5LCoMwEN33FMHVBFJIinShKyvtriDtCYKIDoyx5tPrpzGBzmKYebzfuGg7bppi7JzD2cBNuwl67Ty8P4QedsGqpuJcsKtMa@HtabBofOE80eAaVngg@cnCS5t5AiVYwoMDVdfykCRdR1QUf4qSB37fgyYH/RZMzqKElSezcxslk0u@Bkqui2BY6hwGxMu0Maq6uah4/tIP "Charcoal – Try It Online") Link is to verbose version of code. Outputs `None` if there is no solution. Explanation: ``` ≔↨I⪪θ:⁶⁰η ``` Calculate the number of minutes since midnight. ``` I⌊Φ…¹⁻¹⁴⁴⁰η⬤I…¹χ⁼№θλ№I↨¹⁰⁰↨⁺ηι⁶⁰λ ``` Create a range from `1` until the number of minutes until the next midnight, filter on those that, when formatted as a time, contain identical counts of digits, and output the minimum. Note that I don't count `0` digits as all times have four digits so if the counts of the other digits are correct then so will the counts of the zero digits be; this avoids having to actually format the time. [Answer] # JavaScript, 109 bytes Without recursion: ``` (h,m)=>{for(k=1,t=h*60+m;t++<1440;++k)if((a=(h,m)=>+[...''+h+m].sort().join``)(h,m)==a(t/60|0,t%60))return k} ``` Try it ``` f=(h,m)=>{for(k=1,t=h*60+m;t++<1440;++k)if((a=(h,m)=>+[...''+h+m].sort().join``)(h,m)==a(t/60|0,t%60))return k} [ '11:43', // -> 91 '01:01', // -> 9 '17:38', // -> 59 '14:21', // -> 413 '13:20', // -> 413 '23:41', // -> undefined ].forEach(t => { const [hours, minutes] = t.split`:`.map(x=>+x); const additional = f(hours, minutes); if (additional === undefined) { console.log(undefined); return; } const getTime = (h,m) => { const now = new Date(); now.setHours(h+1); now.setMinutes(m); const timeParts = now.toJSON().split`T`.flatMap(x=>x.split`:`); return [timeParts[1], timeParts[2]].join`:` } const oldTime = getTime(hours, minutes); const newTime = getTime(hours, minutes + additional); console.log(`${oldTime} + ${additional} minutes = ${newTime}`); }) ``` [Answer] # [Perl 5](https://www.perl.org/), 99 bytes ``` sub{"@{[grep{s|1(..)([0-5].)|$1:$2@{[sort/./g]},|}1e4..12359]}"=~/$_[0]((.+),.*?)\2/&&$1=~y///c/16} ``` [Try it online!](https://tio.run/##XcvBToNAFIXhPU9xJRNgFGe4A6idBtu9id24o6SJ7UAaFRBoYkPpq1Ngqgu33zl/qarPsCdp1NeH99ZctnFWqbKtT@gwRp3Yuw8TRk8EJRHDWBdVwxnPks49dagCxlD44SzpzOjMySb2Esdhd9Rltwu6FtyyCEbnI@d8y/Gh6@dGWlSOEYONKAPfhugZZgiJO5KH0kNNV8FH6T9NEv5RIIU@Bej/mi@F99@EFEKngXc14ctAt4d8p9JRaWsAfB0dIPu8dIGonxIoRLAkm/m0AMmKZgCLpPoEdBzKap83@q6@9WcBdvFhgwT7dfUGq5cb2wUTYEgOjdQpwBCobaN2UrcAQymnfp2bc6PrLw "Perl 5 – Try It Online") Creates a long string of all HH:MM in a day (all 24\*60 of them) and adds the four digits sorted after each of those timestamps in the same long string. Searches the long string for the five char input HH:MM and collects the sorted digits behind it with `(.+),` and searches for those same sorted digits further down the long string with `\2`. The number of chars jumped ahead to find them divided by 16 is the number of minutes. [Answer] # Excel, ~~175~~ 171 bytes ``` =LET( a,A1, b,1440, c,{1;2;4;5}, d,TEXT(SEQUENCE(,b)/b,"hh:mm"), e,BYCOL(MID(d,c,1),LAMBDA(x,CONCAT(SORT(x)))), f,0+IF(e=CONCAT(SORT(MID(a,c,1))),d), b*(XLOOKUP(a+1/b,f,f,,1)-a) ) ``` Input as *string* in format `"hh:mm"` in cell `A1`. Error returned if no valid output. [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 42 \log\_{256}(96) \approx \$ 34.57 bytes ``` DLzP.Je2APiEgAu60<s24<&ke60AdEDAJsZT_g0>km ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY3tVx8qgL0vFKNHAMyXdMdS80MbIqNTGzUslPNDBxTXF0cvYqjQuLTDeyycyE6oBoXLFMyNDQxVoLwAA) Port of Kevin Cruijssen's 05AB1E answer. Input as a string, `"HHmm"`. #### Explanation ``` DLzP # Get the permutations of the input string .J # Join each inner list into a single string e # Map over this list: 2APi # Split into two pieces and convert to an integer E # (End map) g # Filter this list: Au # Dump onto the stack (last item of list on top of stack) 60< # Is the last item less than 60? s24< # Is the first item less than 24? & # Are both of the above true? k # (End filter) e # Map over this list: 60Ad # Convert from base-60 E # (End map) DAJ # Duplicate and get the first item sZT # Swap and remove the first item _ # Subtract the first item from the rest g # Filter this list: 0> # Is the number greater than 0? k # (End filter) m # Push the minimum value of this list # Implicit output ``` [Answer] # [Julia 1.0](http://julialang.org/), ~~107~~ 102 bytes ``` using Dates !x=(f=Minute;~q=sort(["$q"...]);t=Time(x);max(f(tonext(i->~i==~t,t,step=f(1))-t).value,0)) ``` [Try it online!](https://tio.run/##RcmxUoNAEIDhWp5iw1jszhCGDTjRYzZVWjs7hoKRI15MwOQWPRteHTUUlt//H8eTazjM8@hdf4B9o9ZHqyDYybPrR7XldBE/XBWr@P4Sp2laU6ny4s4WA5XnJmCHOvQ2KLr1bnIikyaaeLUf0iETrZXSz@Y02iQjmlsQ2LtXxeguZjZFHoPs4ImTX2dsMl78R96a/PHGh8WF2Sy74PwWcrPJ/gNFkX8bvrBqq1CDCKwCdMMVArge3u23x5Zqmn8A "Julia 1.0 – Try It Online") In Julia 1.8, the function will return 0 for inputs with no solution (example: `!"23:41"`). The TIO link only supports Julia 1.0, which fails for these inputs, since `Dates.tonext` doesn't stop at "23:59". * Renaming `Dates.Minute` a `f` saves a byte. * The subfunction `~` returns a sorted list of digits for comparison. * This solution relies on `Dates.tonext`, which I've [used in another challenge](https://codegolf.stackexchange.com/a/254623/114865). In Julia 1.8, it returns a negative value for inputs with no solution, so `max` is used to filter these out. A `limit` parameter also exists, but this would return an error instead of a NULL value. * -5 bytes thanks to MarcMush: replace `string(q)` with `"$q"` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 24 bytes ``` ↕ᵃ{¢b100B"<∩"e<60d}-_Paṁ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FjcVH7VNfbi1ufrQoiRDAwMnJZtHHSuVUm3MDFJqdeMDEh_ubFxSnJRcDFW-4KZrtKGOoY6JjnEsV7QBkAXEQJahjrmOsY4FmGWiYwQVMwayDIAsIyDLBCxmoAOGsRDTAA) Another port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/257635/9288). Take input as a list of four digits. ``` ↕ Get a permutation of the input ᵃ Apply the following block to both the input and the permutation { Start the block ¢b Get a number from base 10 digits 100B Convert the number to a list of digits in base 100 "<∩"e< Check that the two numbers are smaller than [24,60] respectively 60d Get a number from base 60 digits } End the block -_ Subtract and negate P Check if the result is positive a Get a list of all possible results ṁ Get the minimum ``` [Answer] # [J](http://jsoftware.com/), 59 58 bytes ``` (e.*1+i.~)&([:/:~@,"%.10 10&#:)(+1+[:i.1440-])&.(24 60&#.) ``` [Try it online!](https://tio.run/##Xc1NT4NAEAbgO7/iLURg@zHuALaysYZq4sl48IqbBnEbsU01gl6a8NdxZU@azCQzz0xm3oZ8olgvJyqPIs/W6UpLbGHT8ynaYa0QYW57ZXNBuH28vxtiQ1OeNdSLMC7VueqLuX9GLMEyDJSIZzwrVUOcZXKhRUhxkmFpRyQG4T3cEKpDZz6PVdd8G3TV3rRojh9fHQ7N3qDCM2q8jIulik8Ul4tennTQX01/T15rYV@Kwl0NaJsE1Icsn3zWouipoWJSBBvSnqlf37EDM7LUNVFn2g511Zo2cpIz1n938hEk23Bw4YRXSC@dZJw6ypDwP0qRSDiToySpHQ4/ "J – Try It Online") * `(+1+[:i.1440-])&.(24 60&#.)` Calculates every absolute minute of the day (0 to 1439 scale), starting at the current hour and up, and then converts back to hh:mm form. * `...&([:/:~@,"%.10 10&#:)` Converting both the input and the candidate list from the previous step into sorted lists of digits... * `(e.*1+i.~)` Is the input an element of the candidate list (returns 0 or 1) times one plus its index within the candidate list. This returns 0 for no match, and the number of minutes we have to wait otherwise. ]
[Question] [ # Challenge Write a program that greets a user depending on what time of day (GMT) it is. # Output A string (printed or returned) according to these rules: * If the time is 06:00 to 11:59 the greeting has to be "Good morning" * If the time is 12:00 to 17:59 the greeting has to be "Good afternoon" * If the time is 18:00 to 19:59 the greeting has to be "Good evening" * If the time is 20:00 to 05:59 the greeting has to be "Zzz" # Clarifications * There is no input * The times and greetings must be *exactly* as shown * The time zone is +0 GMT # Examples ``` Time: 14:45 -> Good afternoon Time: 05:59 -> Zzz Time: 9:23 -> Good morning Time: 18:00 -> Good evening ``` [Answer] # JavaScript (ES6), 87 bytes *As noticed by [TFeld](https://codegolf.stackexchange.com/a/170222/58563), my original formula was overcomplicated. We can just do:* ``` _=>['Zzz','Good morning','Good afternoon','Good evening'][new Date().getHours()%20/6|0] ``` [Try it online!](https://tio.run/##TYuxCsIwFEV3vyKLJIFai4ODUCdBnVycLEVC@xoi7XvyEiMU/z2KUHQ859x7M9H4ht09LJBaSF2ZruW2kpdxlJncE7ViIEaHdkLTBWAkwklAhG@vK4Sn2JkASucWwoEe7JWer4rl@lXUqSH01EPek1XyfDwJDxyBRXADbGQmfm89@992H5He "JavaScript (Node.js) – Try It Online") Or [test this version](https://tio.run/##NYrBDoIwEETvfMVezLYBdSXGA1o9@g8SDgRaisGuKYQD6rdXNOE0M@/NvRzLvvLtc1g7rnUwKlh1zvE2TZjglbmGB3vXumaZpRm0d8xuAXrUf1/kdpXS9vCmIhj2woICOoKFE6T7OeNYwisCqNj13OlNx40QP7sjuAASQjyfM7ByLpgRYQJGWCmjT/gC) that takes the hour as parameter. --- # JavaScript (ES6), 90 bytes ``` _=>['Zzz','Good morning','Good afternoon','Good evening'][new Date().getHours()*7%20%7>>1] ``` [Try it online!](https://tio.run/##TYyxCsIwFEV3vyJLSSq1qEtBaCZBnVycLEVC@xIi7XuSxAj9@ShC0fGcc7l3FZXvnH2EFVIPSdfpVsuGX6eJF/xA1LORHFo0MyodwCERzgIifHvbILzYXgUQeWkgHOnpvMiXVbZdZ5WUmzZ1hJ4GKAcygl9OZ@bBRXAs2BF2vGC/g3zxv9Ufkd4 "JavaScript (Node.js) – Try It Online") Or [test this version](https://tio.run/##NYpBDoIwFET3nmI2pK2gKcSEBAWX3kHCgkBLMdhvCmGB8ewVTVjNzHvzqOd6bFz/mg6WWuV17k1elOy@LCxiN6IWT3K2t902az0pZ4nsBtSs/r4qzT4NEhmkRRFXXpPjBjnkGQYXJKc1w1DgvQMasiMN6jhQx/nPxhJXMMkQrucMRqyFZVKyCJobIXYf/wU) that takes the hour as parameter. ### Formula Given the current hour \$h\$, we find the appropriate greeting index \$i\$ with: $$i=\left\lfloor\frac{((7\times h) \bmod 20) \bmod 7}{2}\right\rfloor$$ A good thing about this formula is that it does not require any parenthesis once converted to JS: ``` h * 7 % 20 % 7 >> 1 ``` ### Table ``` Hour | *7 | mod 20 | mod 7 | >> 1 ------+-----+--------+-------+------ 0 | 0 | 0 | 0 | 0 1 | 7 | 7 | 0 | 0 2 | 14 | 14 | 0 | 0 3 | 21 | 1 | 1 | 0 4 | 28 | 8 | 1 | 0 5 | 35 | 15 | 1 | 0 6 | 42 | 2 | 2 | 1 7 | 49 | 9 | 2 | 1 8 | 56 | 16 | 2 | 1 9 | 63 | 3 | 3 | 1 10 | 70 | 10 | 3 | 1 11 | 77 | 17 | 3 | 1 12 | 84 | 4 | 4 | 2 13 | 91 | 11 | 4 | 2 14 | 98 | 18 | 4 | 2 15 | 105 | 5 | 5 | 2 16 | 112 | 12 | 5 | 2 17 | 119 | 19 | 5 | 2 18 | 126 | 6 | 6 | 3 19 | 133 | 13 | 6 | 3 20 | 140 | 0 | 0 | 0 21 | 147 | 7 | 0 | 0 22 | 154 | 14 | 0 | 0 23 | 161 | 1 | 1 | 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~120~~ ~~106~~ 102 bytes ``` import time print['Zzz','Good morning','Good afternoon','Good evening'][int(time.time()/3600%24%20/6)] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEkMzeVq6AoM68kWj2qqkpdR909Pz9FITe/KC8zLx3GTUwrSS3Ky8/PgwmklqWC5WOjgTo1QIbogQgNTX1jMwMDVSMTVSMDfTPN2P//AQ "Python 2 – Try It Online") Testable here: [Try it online!](https://tio.run/##NU5PC4IwHL3vU/wwZJsIjhUSgqeKjt0TDyunDtp@MkaUX97UEN7lvcf7M3xDj05Op9v5UkZRNO08WgjGajB2QB8SMnjjQkXv40hTekVswKJ3xnUbVW3Q3iG6TdBvvfp1NSfZUsZ4fMwPQmT7XIhYiizn9TTPEdKihx6MA69cp5k88IL890t4KftoVMFykczoOYH1C9BYyIbGrOcpAf3RT1juTz8 "Python 2 – Try It Online") --- Similar to [Arnauld's answer](https://codegolf.stackexchange.com/a/170232/38592), but slightly different: ``` h %20 /6 --------- 0 0 0 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 1 7 7 1 8 8 1 9 9 1 10 10 1 11 11 1 12 12 2 13 13 2 14 14 2 15 15 2 16 16 2 17 17 2 18 18 3 19 19 3 20 0 0 21 1 0 22 2 0 23 3 0 ``` --- Saved: * -3 bytes, thanks to Arnauld * -1 byte, thanks to N. P. [Answer] **R, ~~97~~ ~~95~~ 93 Bytes** Using methods found above in R ``` c("Zzz","Good morning","Good afternoon","Good evening")[as.POSIXlt(Sys.time(),"G")$h%%20/6+1] ``` **Explanation:** ``` c("Zzz","Good morning","Good afternoon","Good evening") # Creates a vector with the greetings [ # Open bracket. The number in the bracket will extract the corresponding greeting from the vector below as.POSIXlt( # as.POSIXlt converts the object to one of the two classes used to represent date/times Sys.time(), # Retrieves the current time on the OS "G") # Converts the time to the desired time zone. Does output a warning, but still converts properly to GMT $h # Extracts the hour from the object created by as.POSIXlt %%20/6 # Methodology as used by other golfers +1] # Vectors in R start from 1, and not 0 like in other languages, so adding 1 to the value ensures values range from 1 to 4, not 0 to 3 ``` **Example** Notice how this line of code, without adding 1, is short 10 elements ``` c('Zzz','Good morning','Good afternoon','Good evening')[0:23%%20/6] [1] "Zzz" "Zzz" "Zzz" "Zzz" "Zzz" "Zzz" [7] "Good morning" "Good morning" "Good morning" "Good morning" "Good morning" "Good morning" [13] "Good afternoon" "Good afternoon" ``` Adding 1 ensures that the result obtained is greater than 0 ``` c('Zzz','Good morning','Good afternoon','Good evening')[as.integer(0:23)%%20/6+1] [1] "Zzz" "Zzz" "Zzz" "Zzz" "Zzz" "Zzz" [7] "Good morning" "Good morning" "Good morning" "Good morning" "Good morning" "Good morning" [13] "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon" "Good afternoon" [19] "Good evening" "Good evening" "Zzz" "Zzz" "Zzz" "Zzz" ``` [Answer] # T-SQL, 153 bytes ``` SELECT CASE WHEN a>18THEN'Good afternoon'WHEN a>12THEN'Good morning'WHEN a>2THEN'Zzz'ELSE'Good evening'END FROM(SELECT(DATEPART(hh,GETUTCDATE())+6)%24a)a ``` [Try the SQL Fiddle](http://sqlfiddle.com/#!18/9eecb/28696/0) ### Explanation: ``` SELECT CASE WHEN a>18 THEN'Good afternoon' --CASE returns the first value in order whose condition is met WHEN a>12 THEN'Good morning' WHEN a>2 THEN'Zzz' ELSE 'Good evening' END FROM( SELECT ( --Use a subquery to treat the time like a 1x1 table - shorter than declaring a variable DATEPART(hh, --Returns the hour part (hh) of the date GETUTCDATE()) --Returns current UTC time (as far as the SQL Server is concerned) +6)%24 --Virtual time zone where no period crosses midnight, so everything is ordered a) --Give column a 1-letter alias a --Give subquery an alias so SQL Server doesn't complain ``` [Answer] ## [Perl 5](https://www.perl.org/), 77 bytes ``` $_=(gmtime)[2]%20;say$_<6?Zzz:"Good ".($_<12?morning:$_<18?afternoon:evening) ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lYjPbckMzdVM9ooVtXIwLo4sVIl3sbMPqqqykrJPT8/RUFJTwMoYmhkn5tflJeZl24F4lnYJ6aVpBbl5efnWaWWpYLENf///5dfUJKZn1f8X9fXVM/A0AAA "Perl 5 – Try It Online") [Answer] # Excel, 97 bytes ``` =VLOOKUP(Hour(Now()),{0,"Zzz";6,"Good morning";12,"Good afternoon";18,"Good evening";20,"Zzz"},2) ``` Start with the list of cases > > 0 <= HOUR < 6 : "Zzz" > > 6 <= HOUR < 12 : "Good morning" > > 12 <= HOUR < 18 : "Good afternoon" > > 18 <= HOUR < 20 : "Good evening" > > 20 <= HOUR : "Zzz" > > > Then just use a Range-based `Vlookup` (default if you ommit the 4th argument) with an Array of values: > > `H= 0` | `"Zzz"` > > `H= 6` | `"Good morning"` > > `H=12` | `"Good afternoon"` > > `H=18` | `"Good evening"` > > `H=20` | `"Zzz"` > > > ``` {0,"Zzz"; 6,"Good morning"; 12,"Good afternoon"; 18, "Good evening"; 20,"Zzz"} ``` I experimented with using `MOD(HOUR(NOW())+18,24` to shift the hour back by 6 and reduce the cases by 1, but that resulted in 99 bytes. :( [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 36 bytes ``` ”‚¿”…•´¯âžÖ#1ú«…Zzz¸«ža•1Ý;`{ùí4²•èè ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcPcRw2zDu0H08seNSw6tOXQ@sOLju47PE3Z8PCuQ6uBolFVVYd2HFp9dF8iUN7w8FzrhOrDOw@vNTm0Ccg/vOLwiv//AQ "05AB1E – Try It Online") --- ``` ”‚¿” # Push 'Good' …•´¯âžÖ # Push 'morning afternoon evening' # # Split on spaces. 1ú # Pad each with 1 space. « # Concat good onto it: ['Good morning',...,'Good evening'] …Zzz¸« # Concat 'Zzz' onto it. ža # Get current hour. •1Ý;`{ùí4²• # Push 33333000000111111222. è # indexes[current_hour]->i[6:00AM]->0 è # phrases[indexes[current_hour]]->p[i[6AM]]->'Good morning'. ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 91 bytes ``` Write("Zzz,Good morning,Good afternoon,Good evening".Split(',')[DateTime.UtcNow.Hour%20/6]) ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFVDKaqqSsc9Pz9FITe/KC8zLx3CSUwrSS3Ky8/Pg3BTy1JBckp6wQU5mSUa6jrqmtEuiSWpIZm5qXqhJcl@@eV6HvmlRapGBvpmsZr//wMA "C# (Visual C# Interactive Compiler) – Try It Online") Uses Utc Now to get the UTC time. # If it can be a function instead of a full program: # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 88 bytes ``` ()=>"Zzz,Good morning,Good afternoon,Good evening".Split(',')[DateTime.UtcNow.Hour%20/6] ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXbpdm@19D09ZOKaqqSsc9Pz9FITe/KA8oAeEkppWkFuXl5@dBuKllqSA5Jb3ggpzMEg11HXXNaJfEktSQzNxUvdCSZL/8cj2P/NIiVSMDfbPY/9Zc4UWZJakaaRqamtb/AQ "C# (Visual C# Interactive Compiler) – Try It Online") [Test with all the hours(code stolen shamelessly from Arnauld)](https://tio.run/##JYw/C8IwFMT3forHA2lCq0YRh/5z08XNQVAcpCYmoImk0aHiZ4@vdLq73x3XdtO2M3H7tm1lbMi74I29N6qOum7w1Pf5zrkbPJ23xMdwVUF665wdo/zIocPZ4fUwgaV5ys96shTz9SWWiXKe0TFoqEGUJBUsV6RZxuGbHL0Jcm@sZGxoFgI2gAIho2FBI0ROHgshYICKac7L5Bf/ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Powershell, ~~82~~ 72 bytes Port of [TFeld's answer](https://codegolf.stackexchange.com/a/170222/80745) ``` ('Zzz','Good morning','Good afternoon','Good evening')[(date).Hour%20/6] ``` [Answer] # [Common Lisp](http://www.clisp.org/), 103 bytes ``` (nth(floor(mod(nth-value 2(get-decoded-time))20)6)'("Zzz""Good morning""Good afternoon""Good evening")) ``` Ungolfed ``` (nth (floor (mod (nth-value 2 (get-decoded-time)) 20) 6) '("Zzz" "Good morning" "Good afternoon" "Good evening")) ``` Common Lisp mostly ignores whitespace as long as it can unambiguously determine where each sub-expression ends, so much of the golfing here is just removing whitespace. Common Lisp also provides the ability for functions to return multiple values, with all but the first discarded if the caller hasn't explicitly requested the 2nd/3rd/etc return values. This allows functions to return auxiliary data, like the `floor` function performs floor division, but as a secondary return value returns the remainder. This also allows for functions to avoid the overhead of having to package up their return values in a datastructure if the caller is likely to immediately destructure it again. `(get-decoded-time)` (really itself a shorthand for `(decode-universal-time (get-universal-time))`) returns the most values of just about any standard function in common lisp... 9, to be exact. The 3rd return value (`(nth-value 2 ...)` ) is the current hour in 24 hour time. Then it's just computing the proper index into the list of responses and passing that to `nth`. I have to use `floor` here as CL would return a proper fraction if I used `/` for division. [Try it online!](https://tio.run/##Lc1BCsMgEIXhfU8hbjoTEEIWvULv0J1kxlTQGbE2hFzeNiHLjx/em1P8lA7EofjqMzeuZtiGDtLeEJJqhax0yK0@fdlMsHBzxLMSk2sxM@I04gPvYF/7bu1TlUzWKlGWSz78Z0VVLvPKZ0XseINSo7TjFPsP "Common Lisp – Try It Online") [Answer] ## Batch, 178 bytes ``` @for /f "tokens=3" %%a in ('wmic path Win32_UTCTime') do @set/ag=%%a%%20/6 @for %%a in (Zzz.0 "Good morning.1" "Good afternoon.2" "Good evening.3") do @if %%~xa==.%g% echo %%~na ``` Uses @TFeld's formula. Locale-dependent version is only 128 bytes: ``` @set/ag=%time:~,2%%%20/6 @for %%a in (Zzz.0 "Good morning.1" "Good afternoon.2" "Good evening.3") do @if %%~xa==.%g% echo %%~na ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 177 bytes ``` using System;namespace a{class b{static void Main(string[] a){Console.WriteLine(new String[]{"Zzz","Good morning","Good afternoon","Good evening"}[DateTime.Now.Hour%20/6|0]);}}} ``` [Try it online!](https://tio.run/##NYtBC4JAEEb/yiIECmXSoYvHgjpUF4Mg8TBtUyzoTOysStr@dpPI43vv@7QsNFschloMPVX2FodVSlChvECjgl6XIKJuvThwRquGzV0dwVAozo6XvFAQ9Rsm4RLjizUOD4YwJGxV9l/0wbXrgnmwY76rii2NdkJ4OLTETJPABn/d51tweDYVxidu4z3XdrZKlutPUkSp934Yvg "C# (.NET Core) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 52 bytes ``` `Zzz,Good ¶rÍÁ,Good af’rÍ9,Good evÀxg`q, gKd %20/6|0 ``` [Try it online!](https://tio.run/##y0osKPn/PyGqqkrHPT8/ReHQtqLDvYcbIZzEtEOTgFxLCC@17HBDRXpCoY5CuneKgqqRgb5ZjcH//wA "Japt – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ža7*20%7%2÷U”‚¿”Xi'•´ëX<i'¯âë'žÖ]ðýX>i…Zzz ``` `(h*7%20%7)//2` ported from [@Arnauld's JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/170232/52210). [Try it online](https://tio.run/##AUoAtf8wNWFiMWX//8W@YTcqMjAlNyUyw7dV4oCd4oCawr/igJ1YaSfigKLCtMOrWDxpJ8Kvw6LDqyfFvsOWXcOww71YPmnigKZaenr//w) or [verify all hours](https://tio.run/##AVwAo/8wNWFiMWX/MjRGTj8iOjAwIOKGkiAiP07/NyoyMCU3JTLDt1XigJ3igJrCv@KAnVhpJ@KAosK0w6tYPGknwq/DosOrJ8W@w5Z9fcOww71YPmnigKZaenr/fSxc/w). --- **Original 45 bytes answer:** ``` žaDV6÷U”‚¿”Xi'•´ëX<i'¯âë'žÖ]ðýX3%>iY2÷9Êi…Zzz ``` [Try it online](https://tio.run/##AU8AsP8wNWFiMWX//8W@YURWNsO3VeKAneKAmsK/4oCdWGkn4oCiwrTDq1g8aSfCr8Oiw6snxb7Dll3DsMO9WDMlPmlZMsO3OcOKaeKAplp6ev//) or [verify all hours](https://tio.run/##AWIAnf8wNWFiMWX/MjRGTj8iOjAwIOKGkiAiP07/RFY2w7dV4oCd4oCawr/igJ1YaSfigKLCtMOrWDxpJ8Kvw6LDqyfFvsOWfX3DsMO9WDMlPmlZMsO3OcOKaeKAplp6ev99fSxc/w). **Explanation:** ``` ža # Get the current hours DV # Duplicate it, and store it in variable `Y` 6÷U # Integer-divide it by 6, and store it in variable `X` ”‚¿” # String "Good" Xi # If `X` is 1: '•´ # Use string 'morning' ëX<i # Else-if `X` is 2: '¯â # Use string 'afternoon' ë # Else: 'žÖ # Use string 'evening' ] # Close all if-elses ðý # Join the two string literals with a space X3%>i # If `X` modulo-3 is 0: Y2÷9Êi # And if `Y` integer-divided by 2 is not 9: …Zzz # Output string "Zzz" instead # (Implicit else: # output top of stack, which is the "Good ...") ``` [See the explanation here](https://codegolf.stackexchange.com/a/166851/52210) to understand why `”‚¿”` is "Good"; `'•´` is "morning"; `'¯â` is "afternoon"; and `'žÖ` is "evening". [Answer] # Noether, 106 bytes ``` "Good "~g{2D~d5>d12<&}{g"morning"+P}d{11>d18<&}{g"afternoon"+P}d{17>d20<&}{g"evening"+P}d{20>d6<&}{"Zzz"P} ``` [**Try it online!**](https://beta-decay.github.io/noether?code=Ikdvb2QgIn5nezJEfmQ1PmQxMjwmfXtnIm1vcm5pbmciK1B9ZHsxMT5kMTg8Jn17ZyJhZnRlcm5vb24iK1B9ZHsxNz5kMjA8Jn17ZyJldmVuaW5nIitQfWR7MjA-ZDY8Jn17Ilp6eiJQfQ&input=) The command `2D` returns the hour part of the current the time and the rest is a load of if statements. [Answer] # Haskell, 174 bytes ``` import Data.UnixTime v h|h<10="Zzz"|1>0="Good "++y h y h|h<16="morning"|h<22="afternoon"|1>0="evening" main=do;t<-getUnixTime;print$v$mod(div(read.show.utSeconds$t)3600+4)24 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 127 bytes The only really sneaky trick is coercing the hours into `unsigned int` so that I can force the night values to >14. As the `struct tm` structure only has integers, I can pretend that it's an array being passed from `gmtime_r`. ``` char*s[]={"morning","afternoon","evening"};t,u[9];f(){t=time(0);gmtime_r(&t,u);printf(u[2]-6U>13?"Zzz":"Good %s",s[u[2]/6-1]);} ``` [Try it online!](https://tio.run/##HY3RCsIgGEbv9xTyQ6GxUSsYlKwue4JuEonhdPNCDed2sbFnN9fd4TsHPlF0QsQo@sYfBsbrBYzzVtsOcmhUkN46ZxPLSf7XlYZ8ZFdOFSZLqIM2Ep8I7cxGH4/3SRP69doGhUd25kX1upeXB7znGW7wdK5FuwHygW3yWBUlJ3SNKUem0RZPTrcELRlC6YBma/wB "C (gcc) – Try It Online") [Answer] # J, 65 bytes Another port of TFeld's answer. ``` ('Zzz','Good '&,&>;:'morning afternoon evening'){~<.6%~20|3{6!:0'' ``` * `3{6!:0''` gets the hour, which is index 3 of the current time vector, from the builtin `6!:0''` * `<.6%~20|` is floor of ((hour mod 20) divided by 6) * use that as an index `{~` into a 4x14 character array containing the greetings. * save a few chars by concatenating (`,`) the string `Good` to the words `morning`, `afternoon`, and `evening` which are split on whitespace by the J "words" tokenizer (`;:`). It technically is for tokenizing J sentences, but since J has bare words it ends up splitting on whitespace. ]
[Question] [ This is the robbers' thread. For the cops' thread, click [here](https://codegolf.stackexchange.com/questions/99469/quine-anagrams-cops-thread). ### Cops' Task For the cops' thread, click [here](https://codegolf.stackexchange.com/questions/99469/quine-anagrams-cops-thread). ### Robbers' Task * Find an uncracked submission on the cops' thread. (A submission may only be cracked once.) * Unscramble the code to find a working quine. * Post an answer on the robbers' thread. Include the language, the byte count, the user who posted the scrambled code, a link to that answer, and the unscrambled code. Here is an example of a robber submission: > > # Python, 29 bytes, [Oliver](http://localhost/i/cant/post/a/link/to/a/quote) > > > > ``` > _='_=%r;print _%%_';print _%_ > > ``` > > ### Scoring The user with the most cracks will be the winner of this section. [Answer] # Vim, 22 bytes, [Loojvo](https://codegolf.stackexchange.com/a/99485/31716) ``` qtiqtqx0l"tp^V^[^[qx0l"tp ``` [Try it online!](http://v.tryitonline.net/#code=cXRpcXRxeDBsInRwFhsbcXgwbCJ0cA&input=) Explanation: ``` qt " Start recording in register 'q' i " Enter insert mode qtqx0l"tp " Enter this string ^V^[ " Enter a literal 'esc' character ^[ " Exit insert mode q " Stop recording ``` At this point, the buffer looks like this: ``` qtqx0l"tp^[ ``` And the cursor is on the last column (the 'esc' key). ``` x " Delete the esc character 0l " Move to the second character on this line "tp " And paste register 't' ``` [Answer] ## [Underload](http://esolangs.org/wiki/Underload), 20 bytes, [ais523](https://codegolf.stackexchange.com/a/99541/8478) ``` (:a~*(*S)):a~*(*S)*S ``` [Try it online!](http://underload.tryitonline.net/#code=KDphfiooKlMpKTphfiooKlMpKlM&input=) ### Explanation The basic quine in Underload is this: ``` (:aSS):aSS ``` Here is how it works: ``` Stack: Output: (:aSS) # Push string. (:aSS) : # Duplicate. (:aSS) (:aSS) a # Wrap in (...). (:aSS) ((:aSS)) S # Print. (:aSS) (:aSS) S # Print. (:aSS):aSS ``` The first issue was to reduce the number of `S` we need, because we've only got 3 for use here. We can do this by making use of swapping (`~`) and concatenation (`*`): ``` (:a~*S):a~*S ``` Here, instead of printing twice, we put the `(...)` version and the plain version of the string together and print that only once. The bigger puzzle is how print an odd number of `*` and `S`. I'm not even sure how I actually arrived at the final solution, but it turns out that we can do this by putting the tail of the output in a separate string. That string itself is duplicated in the first string, but the contents are not, which gives us the extra occurrences of `*` and `S` we need. Here is a breakdown of the final solution: ``` Stack: Output: (:a~*(*S)) (:a~*(*S)) : (:a~*(*S)) (:a~*(*S)) a (:a~*(*S)) ((:a~*(*S))) ~ ((:a~*(*S))) (:a~*(*S)) * ((:a~*(*S)):a~*(*S)) (*S) ((:a~*(*S)):a~*(*S)) (*S) * ((:a~*(*S)):a~*(*S)*S) S (:a~*(*S)):a~*(*S)*S ``` [Answer] ## MATL, 20 bytes, [Luis Mendo](/a/99510/62101) ``` 'wo&GzL0fk'tl#DwI-ch ``` [Try it online!](http://matl.tryitonline.net/#code=J3dvJkd6TDBmayd0bCNEd0ktY2g&input=) I've never used MATL before, so my understanding may be slightly off, but this is basically how it works: ``` 'wo&GzL0fk' This is a string representation of the code, offset by 3 t Creates a duplicate copy of the string l#D Adds quotes to the second copy w Swap the unquoted version to the top of the stack I- Offset the characters in that version by 3 c Convert back to characters h Join with the quoted string ``` [Answer] # Python 2, 54 bytes, [Loojvo](https://codegolf.stackexchange.com/a/99481/38368) ``` l= ['l=', ';print l[0],`l`,l[1]'] ;print l[0],`l`,l[1] ``` Had a hard time finding it, as I have basically almost never touched python [Answer] # Retina, 20 bytes, [Martin Ender](https://codegolf.stackexchange.com/a/99905/34718) ``` \)1S*`\(? \)1S*`\(? ``` [**Try it online**](http://retina.tryitonline.net/#code=ClwpMVMqYFwoPwpcKTFTKmBcKD8&input=) I found this simply by messing around attempting to create a quine. I found the "shorter quine" that he hinted at first (or a similar one, at least), simply by experimenting (14 bytes): ``` \)1S*` \)1S*` ``` [**Try it online**](http://retina.tryitonline.net/#code=ClwpMVMqYApcKTFTKmA&input=) It took me about half an hour to an hour. Very clever, Martin! [Answer] # JavaScript ES6, 49 bytes, [Mama Fun Roll](https://codegolf.stackexchange.com/a/99573/42545) ``` function f(){return `${(((((k=>f+'')(f)))))}`} ``` Pretty much the standard JS function quine, with a little obfuscation. [Answer] ## [><>](http://esolangs.org/wiki/Fish), 36 bytes, [Erik the Golfer](https://codegolf.stackexchange.com/a/99655/8478) ``` '''000**rd3*:::?!;od0.!!+..233??dfrr ``` [Try it online!](http://fish.tryitonline.net/#code=JycnMDAwKipyZDMqOjo6PyE7b2QwLiEhKy4uMjMzPz9kZnJy&input=) I'm quite sure that this is not the intended solution. However, ><> quines make it fairly easy to get rid of most unwanted characters, except the `'`. Fortunately, the `:` made it quite easy to take care of those as well. ### Explanation ``` ''' Push everything except these quotes onto the stack. 000** In effect, pushes a zero. r Reverse the stack. d3* Push 39 (the quote character). :: Make two copies. The stack now holds a null-terminated representation of the entire code. The print loop begins here... : Duplicate top of stack. ?!; Terminate if zero. o Otherwise, print. d0. Jump back to position 13, i.e. the beginning of the print loop. !!+..233??dfrr Unused characters. ``` [Answer] # JavaScript, 147 bytes, [jrich](https://codegolf.stackexchange.com/a/99589/42545) ``` +function e(){window[(w=[``>``]+``)[i=9/9]+w[i+i]+"ert"]('+'+e+'()');" +./;;;;;=======>[]````````ccddddddeeeeeeeefiinnnnoooooorrrrrrrsttuwwx{}"}() ``` With all those extra chars, this is definitely not the intended solution :-) [Answer] ## Haskell, 86 bytes, [Laikoni](https://codegolf.stackexchange.com/a/99551/34531) ``` y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!" ``` Nice idea to get the `"` via `succ$'!'` (ascii char after `!`). There were some missing chars to get them the usual way, i.e. implicitly via `show` or `print`. [Answer] ## [Befunge](http://esolangs.org/wiki/Befunge), 15 bytes, [James Holderness](https://codegolf.stackexchange.com/users/62101/james-holderness) ``` <:0:+1_@#%9,:g- ``` [Try it online!](http://befunge.tryitonline.net/#code=PDowOisxX0AjJTksOmct&input=) ### Explanation The catch here is that the loop terminates when the current character is divisible by 9, which is only the case for `-`. Hence, that needs to go at the end. ``` < Run code from right to left. - There will always be 2 zeros on top of the stack at this point, and this just reduces them to 1 zero. g Get the character at the coordinates given by the top two stack values, (0, 0) initially. ,: Print a copy of that character. %9 Modulo 9. _@# Terminate if that is 0. +1 Increment the x coordinate. : Duplicate it. :0 Push two zeros. ``` [Answer] ## PHP, 110 bytes, [Oliver](https://codegolf.stackexchange.com/questions/99469/quine-anagrams-cops-thread/99476#99476) ``` <?php $x='<?php $x=0; echo strtr($x, array(chr(39).$x.chr(39)));'; echo strtr($x, array(chr(39).$x.chr(39))); ``` Thanks, I had fun and the `strtr([])` trick was a new one for me that I hope will save me some bytes in the future. [Answer] ## [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes, [Erik the Golfer](https://codegolf.stackexchange.com/a/99650/8478) ``` ”ṘṘ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCd4bmY4bmY&input=) There aren't really that many options... (Plus, this is the standard quine.) [Answer] ## Python 2, 105 bytes, [Erik the Golfer](https://codegolf.stackexchange.com/a/99652/21487) ``` a='a=%r;print a%%a ###(((())))**-01::@@@@@[[]]gggiiirrr~';print a%a ###(((())))**-01::@@@@@[[]]gggiiirrr~ ``` It's just the standard Python string formatting quine... [Answer] ## Ruby, 53 bytes, [wat](https://codegolf.stackexchange.com/a/100084/8478) ``` puts <<ENDIT*2,"ENDIT" puts <<ENDIT*2,"ENDIT" ENDIT ``` Just a modification of the standard heredoc quine: ``` puts <<2*2,2 puts <<2*2,2 2 ``` ]
[Question] [ Inspired by <http://meta.codegolf.stackexchange.com/questions/547/write-a-code-golf-problem-in-which-script-languages-are-at-a-major-disadvantage> question on meta, I've decided to make a question which could be problematic for scripting languages. The goal is to calculate fast inverse square root, just like it was done in Quake III Arena. You will get the floating point number as first argument after program name and you should implement it. Simply doing `** -0.5` is disallowed as it doesn't implement the algorithm. Your program will be called like this. The `12.34` could be other value. ``` $ interpreter program 12.34 # for interpreted languages $ ./a.out 12.34 # for compiled languages ``` For comparison, this is original Quake III Arena implementation. ``` float Q_rsqrt( float number ) { long i; float x2, y; const float threehalfs = 1.5F; x2 = number * 0.5F; y = number; i = * ( long * ) &y; // evil floating point bit level hacking i = 0x5f3759df - ( i >> 1 ); // what the heck? y = * ( float * ) &i; y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed return y; } ``` You have to do just one iteration because the second was commented out. Winning condition: Shortest code. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes ``` l2Ḟ©.*×+®µ23 .*ד9®ġ’_Hµ‘_Ḟ×Ḟ2*$$µ²×³3_×H ``` [Try it online!](https://tio.run/nexus/jelly#@59j9HDHvEMr9bQOT9c@tO7QViNjBRD7UcMcy0Prjix81DAz3uPQ1kcNM@KB6g5PBxJGWioqh7Ye2nR4@qHNxvGHp3v8///fCAA "Jelly – TIO Nexus") I know this challenge was designed in the hope that golfing languages would have a hard time. In a way, they do; Jelly doesn't have any primitives for looking at the representation of a floating point number in memory. However, it's still possible to solve the challenge via working out "manually" what the representation would look like using the basic definitions of floating point arithmetic, and in fact there's some amount of mathematical interest in doing things "the hard way". Jelly's so much terser than (say) C, that the fact it has to do more work doesn't prevent the program being considerably shorter. ## Explanation The input is a floating-point number, as a number. In order to run the fast inverse square root algorithm, we need to find how it would be represented in memory. Jelly doesn't have a way to do that by looking at the bit pattern, but we can do it arithmetically. First, note that the input must be positive (or its inverse square root would be undefined). As such, it's laid out in memory as follows, from most to least significant: * A zero bit (the sign bit, zero means nonnegative so this will always be zero); * The exponent (dividing the number by 2 to the power of the exponent scales it into the range 1 to 2), represented in 8 bits as its value minus 127; * The mantissa (the result of the above division), represented in 23 bits via subtracting 1, then multiplying by 223. The results of each of these calculations can be represented directly in Jelly. As such, we could generate the same output as C's convert-`float`-to-`int` memory hack does like this: * Calculate the exponent * Calculate the mantissa * Take ((exponent + 127) × 223) + (mantissa × 223 - 1) However, the last expression shown here simplifies to the following rather simpler form: * 223 × (exponent + mantissa + 126) * alternatively, 8388608 × (exponent + mantissa) + 1056964608 (the result of multiplying the above out) Let's call the exponent + mantissa of the input floating point number *em* for short. (The exponent + mantissa of a floating point number uniquely defines it.) In other words, after the `// evil floating point bit level hacking` comment, the C program is currently working with `i` = 8388608 × *em* + 1056964608. The next steps in the C program are to halve *i*, and subtract it from `0x5f3759df` (which, in decimal, is 1597463007). *i* is (8388608 × *em* + 1056964608); halving it gives (4194304 × *em* + 528482304); the subtraction gives (1068980703 - 4194304 × *em*). Then, C convert this number back to a floating point number `y`. Let's call the exponent + mantissa of `y` *em'*. What the C program is therefore effectively doing in the floating point representational hacking is solving the following equation: * (1068980703 - 4194304 × *em*) = (8388608 × *em'* + 1056964608), which simplifies to: * 12016095 = 4194304 × *em* + 8388608 × *em'* * *em'* = (12016095 - 4194304 × *em*) ÷ 8388608 = (12016095 × 2-23) - *em* / 2 Now, to convert this into Jelly. We have a nice arithmetic definition of *em* and of *em'*, so we can translate it directly. First, here's how to calculate *em*: ``` l2Ḟ©.*×+® l2 Logarithm of the input, base 2 Ḟ Round down to the integer below (produces the exponent) © Store the exponent in a variable .* Take (½ to the power of the exponent) × Multiply by {the original value, by default} +® Add the value of the variable (i.e. the exponent) ``` The original value multiplied by ½ to the power of the exponent is equal to the original value divided by 2 to the power of the exponent, i.e. the mantissa, so this is *em*. Getting *em'* is very straightforward from here, if we want it. However, we're going to need to convert the exponent+mantissa format back into a floating point number. This can be done unambiguously (the exponent's always an integer, the mantissa runs from 1 inclusive to 2 exclusive). However, to extract the exponent, we're going to want to floor and subtract 1. As such, it's actually shorter to generate *em'* -1. * *em'* = (12016095 × 2-23) - *em* / 2, so * *em'*-1 = (3627487 × 2-23) - *em* / 2 We can encode this formula in Jelly directly: ``` µ23 .*ד9®ġ’_H µ set this point as the new default for missing arguments 23 restart with 23 .* ½ to the power of that (i.e. 2 to the power -23) × times “9®ġ’ 3627487 (compressed representation) _H minus half {the value as of the last µ command} ``` Incidentally, we need the space because `23.` is a single token in Jelly (which evaluates to 23½). The next step is to convert from *em'-1* to an actual floating point number `y`. We can extract the exponent using `Ḟ`; then the mantissa is *em'-1* + 1 - the exponent. To produce the floating point number, we want to calculate mantissa × 2exponent: ``` µ‘_Ḟ×Ḟ2*$$ µ set this point as the new default for missing arguments ‘ increment (producing em'-1 + 1) \_Ḟ subtract the exponent (producing the mantissa) × multiply by Ḟ2\* 2 to the power of the exponent $$ parse the previous three links as a group ``` Finally, we just need to handle the line marked `// 1st iteration`. This is just regular arithmetic, so encodes into Jelly really easily. The formula is: * `y` × (1.5 - (`x2` × `y`²)), where `x2` is half the original input; this is shorter to express as * `y` ÷ 2 × (3 - (`x` × `y`²)), where `x` is the original input. And here's how it looks in Jelly: ``` µ²×³3_×H µ set this point as the new default for missing arguments ² square ׳ multiply (×) by the original input (³) 3_ subtract (_) from 3 ×H multiply by half {the value as of the last µ command} ``` ## Verification Running this program on the input `2` produces the output `0.7069300386983334`. This is the same value (allowing for differences in the float-to-string conversion) as produced by [this VBA answer](https://codegolf.stackexchange.com/a/9036/62131), and not equal to the mathematically correct value for 2-0.5. [Answer] # FORTRAN, ~~124~~ 113 Chars saved 11 Bytes thanks to rafa11111 I know that this question is rather old, but it deserves a FORTRAN answer. It cannot outgolf Perl or Jelly, but it is at least not the worst. ``` character*9 c equivalence(r,i) call getarg(1,c) read(c,*)y r=y i=Z'5f3759df'-ishft(i,-1) print*,r/2*(3-y*r*r) end ``` The hardest thing is to get command line arguments into FORTAN. Fortunately there is `getarg()` as alias for `get_command_argument()`. Note the use of an equivalence statement to avoid type casting. `r` and `i` are simply the same bytes but can be addressed as different datatypes. Since FORTRAN pointers cannot be casted into another datatypes like in C this is the way to go in FORTRAN. [Answer] ## Perl, 89 85 chars includes the necessary symbols for declaring and implementing a function **edit:** standalone program. receives input parameter as command line argument ``` $_=unpack'f',pack'i',0x5f3759df-unpack('i',pack'f',$n=shift)/2; print$_*1.5-$n/2*$_**3 ``` [Answer] ## vba, 171 ``` Type x q As Long End Type Type z w As Single End Type Function q(n) Dim i As x,y As z x=n/2 y.w=n LSet i=y i.q=&H5F3759DF-i.q/2 LSet y=i q=y.w*(1.5-x*y.w*y.w) End Function ``` finding a way to do the pointer cast was the hardest part. unfortunately, as there is no real direct way, I had to define my own type, which added to the length of the program call from the immediate window with ?q(number) result: > > ?2^-0.5 > > 0.707106781186548 > > ?q(2) > > 0.706930038698333 > > > [Answer] # Portable C99, 114 bytes ``` float g(f,t,e)float f,t;{t=1.93243-frexp(f,&e);t-=.5*(e&1);t=ldexp(t+(t<1),-(e>>1)-(t<1));return(1.5-.5*f*t*t)*t;} ``` [Try it online!](https://tio.run/##LY/RCoIwGIWv3VP8FMW23HCZVMz5JN2EbibYlPUHQfjsNqu773DOgXNq0db1PLt@uCK01KWYWvZTkfUbjZLnfH/IhQv2NcbA1jKNwsiCU7tVkU3fLA7uKJaKpYLaqlJMfBXTweIzeKpkIWLFceTIOOppXne@7p@NhfKBTTfIW0VI5xHu185TBm@SuCEA/W8BA5nMMqUjlqBsvgA3oOTpm03GEMuOrjYneXAgKtjIY3vxqzT@WI7FKSSZSPLbA5km0/wB "C (gcc) – Try It Online") A solution in a more portable subset of C99. Uses `frexp` and `ldexp` from `math.h` instead of bit twiddling. Has very slight rounding errors. Here's a documented version that should be exact: ``` float my_rsqrt(float f) { int e; float r = frexp(f, &e); // Subtract from magic mantissa. int prev_mode = fegetround(); fesetround(FE_UPWARD); r = (0x0.3759dfp1f + 1.5f) - r; fesetround(prev_mode); // Handle LSB of exponent that spills into mantissa. if (e & 1) r -= 0.5f; // Handle overflow. if (r < 1.0f) { r += 1.0f; e += 2; } // Scale with adjusted exponent. r = ldexp(r, -(e>>1)); return r * (1.5f - 0.5f * f * r * r); } ``` [Answer] ## C#, 157 chars Horrible for golfing, but why not... ``` class C{unsafe static void Main(string[]a){var n=float.Parse(a[0]);var i=*(int*)&n/-2+0x5f3759df;var y=*(float*)&i;System.Console.Write(y*1.5f-y*n/2f*y*y);}} ``` Readable version: ``` class C { unsafe static void Main( string[] a ) { var n = float.Parse( a[0] ); var i = *(int*) &n / -2 + 0x5f3759df; var y = *(float*) &i; System.Console.Write( y * 1.5f - y * n / 2f * y * y ); } } ``` [Answer] # C, 173 chars Might as well put code golfed version of example above. Could be less if I would ignore portability. ``` #include<stdio.h> #include<stdint.h> main(int _,char**a){float n,g;sscanf(a[1],"%f",&n);int32_t o=0x5f3759df-(*(long*)&n>>1);g=*(float*)&o;printf("%g\n",g*(1.5-(n/2*g*g)));} ``` [Answer] ## Java, 175 bytes I decided to give this question a Java answer since it didn't have one, and then it got tweeted and bumped while I was golfing... weird. As a lambda, `101 bytes`: ``` f=n->{float y=Float.intBitsToFloat(0x5f3759df-(Float.floatToIntBits(n)>>1));return y*(1.5f-n/2*y*y);} ``` As a full program, `175 bytes`: ``` class Q{public static void main(String[]a){float n=Float.parseFloat(a[0]),y=Float.intBitsToFloat(0x5f3759df-(Float.floatToIntBits(n)>>1));System.out.print(y*(1.5f-n/2*y*y));}} ``` Darn it, two bytes more than portable C. It's the darn `Float.floatToIntBits()`&`Float.intBitsToFloat()`, for Java doesn't like it when you try to say `"You know this float that I just defined? Make it an int. You know that int I just defined? Make it a float."` [Answer] # Julia, 96 characters ``` F=Float32;\ =reinterpret;n=parse(F,ARGS[]);y=F\(0x5f3759df-UInt\n>>1);print(y*(1.5f0-(n/2*y*y))) ``` # Julia (function), 73 characters ``` n->(\ =reinterpret;y=Float32\(0x5f3759df-UInt\n>>1);y*=(1.5f0-(n/2*y*y))) ``` Needs to be run on a 32-bit system for `UInt` to mean `UInt32`. Unfortunately, there isn't a similar alias for `Float32`, and if I tried to just `parse(ARGS[])`, it would be `Float64`. [Answer] # X86-64 Machine Code, Microsoft Calling Convention - ~~65~~ 61 bytes ``` 48 8B 4A 08 mov rcx,qword ptr [rdx+8] 48 83 EC 28 sub rsp,28h E8 C5 FD FF FF call strtof (07FF62D2A1642h) 48 83 C4 28 add rsp,28h 66 0F 7E C0 movd eax,xmm0 D9 E8 fld1 D9 E8 fld1 D8 C0 fadd st,st(0) D8 F9 fdivr st,st(1) DC C1 fadd st(1),st 50 push rax D8 0C 24 fmul dword ptr [rsp] 5A pop rdx D1 F8 sar eax,1 B9 DF 59 37 5F mov ecx,5F3759DFh 2B C8 sub ecx,eax 51 push rcx D9 04 24 fld dword ptr [rsp] D9 C0 fld st(0) DE C9 fmulp st(1),st DE C9 fmulp st(1),st DE E9 fsubp st(1),st D8 0C 24 fmul dword ptr [rsp] D9 14 24 fst dword ptr [rsp] 58 pop rax C3 ret ``` Might be a little shorter in 32 bit. About 20 bytes used in string conversion. -4 bytes by using `strtof` [Answer] # [Tcl](http://tcl.tk/), 110 bytes ``` rename binary B proc R n {B s [B f f $n] i i B s [B f i [expr 0x5f3759df-($i>>1)]] f y expr $y*1.5-$n/2*$y**3} ``` [Try it online!](https://tio.run/##PYmxCoMwAAX3fMUbMqigNdogHerg1tWOksHaCAFN02ghIn57GjqUg8fxbh0m763U/SzxULq3Gxpi7GtAC429wYKuwRigWkBBkf@l0ElnLHLHx7Lil@eYRlTVNYuFCHkjv0q3hGU8pfpUJMGT8vDT3Bs47KzIyjPyrOBhcnZgN591we3@thF18bVrQZ04/Bc "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 112 bytes ``` rename binary B proc R n {B s [B f f $n] i i B s [B f i [expr 0x5f3759df-($i>>1)]] f y expr $y*(1.5-$n/2*$y*$y)} ``` [Try it online!](https://tio.run/##PYmxCoMwFEV3v@IOb1Ch1mhD6VAHt652lAzWKgQ0TaOFBPHb09ChHLhw7ln7yXszqG4e8JCqMw51pM2rRwOFrcaCtsYYICUgIaP/JdEOVhvklo/lmV@e4yEmWVUsESJkF/0quTRmGT@QOhZpEHLJ7qe507DYWJGVJ@RZwcPkbMemP@uC2/1tYrLJtW1AVuz@Cw "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 113 bytes ``` rename binary B proc R n {B s [B f f $n] i i B s [B f i [expr 0x5f3759df-($i>>1)]] f y expr $y*(1.5-$n*.5*$y*$y)} ``` [Try it online!](https://tio.run/##PYmxCoMwAAV3v@INGVQwGG0oHerg1tWOksFahYCmabSQIPn2NHQoBw/u3T4uIZhJDeuEh1SDcWgTbV4jOigcLTb0LeYIUQISMvlfEv1ktUFp@Vyf@eU5FymRTcMyIWJ2ya8Sl6eM8oKonPI8GnGZD8s6aFgcrKL1CSWteJySeRz6s2@43d8mJTa79h2IFT58AQ "Tcl – Try It Online") --- # [Tcl](http://tcl.tk/), 129 bytes ``` rename binary B proc R n {B scan [B format f $n] i i B scan [B format i [expr 0x5f3759df-($i>>1)]] f y expr $y*(1.5-$n*.5*$y*$y)} ``` [Try it online!](https://tio.run/##ZYuxCoMwAAV3v@INGVRoMNpQOtTBrasdJUNqDQQ0ptFCgvjtqXTtcnAct/ZjjG4wchrw1Ea6gCaxbu7RwmBrsPTSoGugZjfJFQrECGjo5C9pdIO3DoXnqrrw60udUqLrmmVCHF9IfpWEPGWUn4jJKc8PIyHb4zhJC4@NlbQ6o6AlP1CwHZv9rAvuj7dLic9uXQvixR6/ "Tcl – Try It Online") # [Tcl](http://tcl.tk/), 133 bytes ``` proc R n {binary scan [binary format f $n] i i binary scan [binary format i [expr 0x5f3759df-($i>>1)]] f y expr $y*(1.5-$n*.5*$y*$y)} ``` [Try it online!](https://tio.run/##fYyxCoMwAAV3v@INGVQwGG0oDnXvakfJkNoGAhrTaCFB/PZUSucuB8c93jqMMVo3D@hgsN21kS5gGaRB/xM1u0muUCBGQEMnf0Ya/dNbh9JzVZ9581BFSnTbskyI4yEk30pCnjLKC2JyyvPDSMj2OE7SwmNjFa1PKGnFD5Rsx2bf64Lr7eVS4rNL34F4sccP "Tcl – Try It Online") # [Tcl](http://tcl.tk/), 142 bytes ``` proc R n {binary scan [binary format f $n] i i set i [expr 0x5f3759df-($i>>1)] binary scan [binary format i $i] f y expr $y*(1.5-$n*.5*$y*$y)} ``` [Try it online!](https://tio.run/##fYyxCoMwFEV3v@IOb1BBMdpQOtS9qx3FwVoDAY1pTCFB/PZUSucu93KGc@wwhaDNMqCBwvaQqjce69ArtD8Qi5l7CwFSHSRktI72@HZ02qBwXFRnfnmKLCZZ1yzpoj8RCZLdkfLR1yafxiznGak05@lB5JM9THOv4bCxMq9OKPKSH1OwHZt@2xW3@8vE5JJr24Bct4cP "Tcl – Try It Online") ]
[Question] [ ## Story The god of base is opening heaven’s gate for mortals to join the base party. You, as one of the believers, want to follow their steps to ascend to heaven. But not everyone can get in. The god posts this question to let you prove you are worthy of their party. ## Task You will get 2 inputs * First being `X` which is a non-negative integer in base 10. * Second being `base` which is a list of bases to iterate over. * **bases will always be positive integers which in range of 1~10** * The base will contain at least one not `1` base You will need to present(print) `X` in the form of iterating bases. Example: ``` X ,[base] -> ans 6 ,[2] -> 110 It has only 1 base in base list, thus it converts number into base2 6 ,[2,4] -> 30 First base is 2, so 6%2=0 is the first digit and (6-0)/2 =3 is forwarded to next base. Second base is 4, so 3%4=3 is the second digit and there is no remaining. 30 ,[2,3] -> 2100 First two digits come from 30%2=0, 15%3=0, with 15/3=5 is passed to next base, which loops back to 2 => 5%2 = 1,pass 2=> 2%3 = 2 10 ,[9,2] -> 11 20 ,[3,4,5] -> 122 0 ,[any bases] -> 0 ``` ## Rules * No standard loopholes * Input, output in any reasonable, convenient format is accepted. The god requires short code—they will give access to the shortest code in each language. Fulfill their task to ascend! [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 8 bytes [SBCS](https://github.com/abrudz/SBCS) A re-implementation of [Jonah's answer](https://codegolf.stackexchange.com/a/224736/43319). ``` 10⊥⌽⍤⍴⊤⊣ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=MzR41LX0Uc/eR71LHvVuedS15FHXYgA&f=M1NIUzDiMgOROiZcxgZghjGXIYhhqWPEZQRiGOuY6JhygViGOkBZAA&i=AwA&r=tryAPL&l=apl-dyalog&m=train&n=f) An anonymous tacit infix function taking `base` on the right and `X` on the left. `⊣` the value `X` `⊤` represented in base… `⌽⍤⍴` reversed `base` cyclically-repeated until length `X` `10⊥` evaluated as base-10 [Answer] # [J](http://jsoftware.com/), 12 11 bytes ``` 10#.|.@$#:[ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DQ2U9Wr0HFSUraL/a3KlJmfkKxgppNUpmMHYxiCesQGEawmRNIRyjRVMFExBAkZQAXMFC6AQUMDgPwA "J – Try It Online") -1 after reading Adam's APL answer and realizing I could get rid of the `~`. Other than that, we both found the exact same answer. J has a mixed base primitive that does the heavy lifting `#:`. * `|.@$~` Repeat the base as man times as the number we're converting, and then reverse. Extra left digits will become 0, and this ensures we always have enough digits. * `#:]` Using the previous result, convert the input using mixed base. * `10#.` Convert back to a base 10 number to remove the extra zeros. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~13 11~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╨¬ª₧}ÄM☻☻. ``` [Run and debug it](https://staxlang.xyz/#p=d0aaa69e7d8e4d02022e&i=0,%5B345%5D%0A6+,%5B2%5D%0A6+,%5B2,4%5D%0A30,+%5B2,3%5D%0A10,+%5B9,2%5D%0A20,%5B3,4,5%5D%0A&m=2) Having another stack based language to compete with gave some golfing motivation. ## Explanation ``` n^*{|%mr$A|b n^* repeat bases X+1 times { m map to |% divmod(puts quotient on stack for next iteration) r reverse $ join to string A|b interpret as base 10 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` sиvy‰`s}JRï ``` I have the feeling this can be shorter, but I'm a bit rusty on code-golfing. Takes the list of bases as first input and integer \$X\$ as second input. [Try it online](https://tio.run/##yy9OTMpM/f@/@MKOsspHDRsSimu9gg6v//8/2kjHOJbL2AAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCy9EFxf@LL@woq3zUsCGhuNYr6PD6/zr/o6OjjWJ1zGJ1FIAMHRME0zhWx9gAzLbUAaowhLCNdUx0TGN1jKC8WB0DqHILEDMWAA). **Explanation:** ``` s # Swap the two (implicit) inputs, so the stack is bases-list, integer X и # Repeat the bases-list X amount of times v # Loop over each value `y` in this list: y‰ # Divmod `y` ([v//y, v%y]), which will use the second (implicit) input-integer # X as value in the very first iteration ` # Pop this list, and push both separated to the stack s # Swap their order, so the v//y is at the top, as value for the next iteration }J # After the loop: join all integers on the stack together R # Reverse it ï # And cast it to an integer to remove any leading 0s # (after which the result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), 41 bytes A massive improvement from my previous solution, based on a clever observation by [@att](https://codegolf.stackexchange.com/users/81203/att), to use the fact that bases are \$ \le 10 \$. ``` f=lambda x,y,*b:x and 10*f(x//y,*b,y)+x%y ``` [Try it online!](https://tio.run/##RY3LDoIwEEX3/YrZGFoctQ80kQR/xLgoUWOTgo0Wha/HKb52c86duROGeLm2ZhzPlbdNfbTQ44B5XfZg2yMomZ95v1olhYOY97NhfF6cP4EqGbg2IFy7GKBKcxe5WN6Dd5FnsNhBJhi1QU3p6WE9pxUyn33v7pE3NpCN7xJBYbgRcnqJkNfi48cN4F4fUqVSkk2ExcRGMiMnNhNrJSVTyWzxe8F0YoMFrt9Ga5aMQrr6Wcn0/4t8AQ "Python 3 – Try It Online") ### [Python 3](https://docs.python.org/3/), 48 bytes Outputs the number as a list of digits. A couple of bytes are needed to handle the edge cases where \$ X = 0 \$. ``` f=lambda x,y,*b:x//y and f(x//y,*b,y)+[x%y]or[x] ``` [Try it online!](https://tio.run/##PY3LDoIwEEX3/YrZGFodtQ800QR/hLAoUSNJgUar0q/HKai7OefO3PEx3PrOjOO1cLatzxYGjLisj8N2G8F2Z7jyNJLCKFblsIhVfy@HanzfGncBdWTQdB6hfwYPRZqfgYvNw7sm8AzWJ8gEo1KoKb28rOO0Qua775pH4K31ZMNcIij0d0JOnxGWtfj6cQ9Y6ipVKiXZRJhPbCQzcmIzsVZSMpXMAX8XTCc2mONuNlqzZBTS1d/KDw "Python 3 – Try It Online") [Answer] # JavaScript (ES6), 43 bytes ``` f=(n,[b,...a])=>n&&+f(n/b|0,[...a,b])+[n%b] ``` [Try it online!](https://tio.run/##bc7NCsIwEATgu0@RiyWha5psquKhvkjYQ1NbqZRErHjy3WME/wjOcfhg5tTe2rm7jOfryodDH@PQcA/WgZSyJdHsfVGUA/eVuyuwzxIcidL6paPYBT@HqZdTOPKBb4BZJJYiBKsqprVa/BFQ01uYHJi0gWA@ALXKiU5kB0jflQxgAgZqWNMLIGZCpRvbn6MqPgA "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 57 bytes ``` f=lambda x,a,*b,j=0:x and f(x//a,*b[1:],a,j=[])+[x%a]or j ``` [Try it online!](https://tio.run/##VcxBCoMwEIXhfU8xm0JiBzTGCgo5SchiREIbahRxkZ4@TdMu4vZ7j397H4/VyxitetEyzQQBCasJnWrGAORnsCzU9de0GE0andKG33S4kll3cHHbn/5glvUIlW4N55ezIHQlyuavslSRdUA4BdqsMhUQ7uWQXaT3LxM/ "Python 3 – Try It Online") -5 bytes borrowing the idea from Arnauld to use splat. [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` 0?_=0 n?(h:t)=mod n h+10*div n h?(t++[h]) ``` [Try it online!](https://tio.run/##PY1BboMwEEX3PsUoygLKEI1NUqlNDKvuegOEGiLcYsXYFbFS4PLUBLW7/57@/Gnr21UZM89UfEhitojaVx/LzjVgoU04PTX6vsQi8klStlU8d7W2snEMSosXdNUp/XF9c9t9auNVH52t829GdedNmm/i0zb/Uv5dW8XAKA@D7FUdto/jGi7HaQ1h77vX1kdDMUo54YAjTjGD5dv8DKWoIM2Bc2IL4P6BGbGMFsweKDgR40G84F@diYAZ7vGwCiFYEBzDyb@kXw "Haskell – Try It Online") [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 15 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ê├Ä_]─k\É‼%/]xy ``` First input is \$X\$, all other inputs are the values in the bases-list. [Try it online.](https://tio.run/##y00syUjPz0n7///wqkdT5hxuiY99NKUhO@Zw56OGPar6sRWV//@b6RhxAbGOCZexAZAy5jI00LEEihkZ6BjrmOiYchnoGHKB2BYA) **Explanation:** ``` ê # Push all inputs as an integer-list ├ # Pop its first item (the integer X), and push it to the stack Ä # Loop that many times, using a single character as inner code-block: _ # Duplicate the list at the top of the stack ] # After the loop, wrap all list on the stack into a list ─ # Flatten this list of lists of integers k # Push the first integer-input X again \ # Swap, so the list we created earlier is at the top of the stack É # For-each over this list, using three characters as inner code-block: ‼ # Apply the following two commands separated on the top value: % # Modulo / # Integer-divide ] # After the loop, wrap all values on the stack into a list x # Reverse this list y # Join it together, and convert it to an integer, removing leading 0s # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~38~~ 39 bytes ``` #>=#2&&#0[⌊#/#2⌋,##3,#2]||#~Mod~#2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X9nOVtlITU3ZIPpRT5eyvrLRo55uHWVlYx1lo9iaGuU63/yUOqCC/wFFmXkl0cq6dmkODsqxanXByYl5ddVc1WY6RrU6YErHBMQwNgCyjEEsQwMdS4ikkYGOsY6JjimIbQAVAlJctf8B "Wolfram Language (Mathematica) – Try It Online") Input `[X, bases..]`. Returns an `Or` of digits. `MixedRadix` exists and would perform the task easily (in conjunction with `IntegerDigits`), but it isn't cyclic. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes ``` \d+ $*_ +`^(_+),(?>(.*,)?)(\1)+(_*) $2$1,$#3$*_$.4 (_+,)+(_*) $.2 ``` [Try it online!](https://tio.run/##NYqxDoMwDAV3/wZGspOnKHFopS4w8hOIUKkdujAg/j@NkFhuuLvje/72d@1l3ury8cSukN9WKV4h0yjBQSeVJamX4pTYOIG73D4OA7UPdwlWq@FJhuFiRo70giFFys09YJES4h8 "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `X` as the last argument. Explanation: ``` \d+ $*_ ``` Convert to unary. ``` +`^(_+),(?>(.*,)?)(\1)+(_*) ``` Repeat until `X` is less than the first base, divmod `X` by that, and... ``` $2$1,$#3$*_$.4 ``` ... move the first base to the end, then append the quotient in unary and the remainder in decimal (ironically Retina gives me the quotient in decimal and the remainder in unary...). ``` (_+,)+(_*) $.2 ``` Convert the final digit to decimal. This also handles the `0` case. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 23 bytes ``` M|&J/GhHagJ.<H1%GhH]GgF ``` [Test suite](http://pythtemp.herokuapp.com/?code=M%7C%26J%2FGhHagJ.%3CH1%25GhH%5DGgF&test_suite=1&test_suite_input=6%2C+%5B2%5D%0A6%2C+%5B2%2C4%5D%0A30%2C+%5B2%2C3%5D%0A10%2C+%5B9%2C2%5D%0A20%2C+%5B3%2C4%2C5%5D%0A0%2C+%5B1337%5D&debug=0) Direct translation of [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)['s Python 3 answer](https://codegolf.stackexchange.com/a/224746/78186). ## Pyth, 25 bytes ``` AQWG=+k%G@HZ~/G@H~hZ)|_k0 ``` [Test suite](http://pythtemp.herokuapp.com/?code=AQWG%3D%2Bk%25G%40HZ%7E%2FG%40H%7EhZ%29%7C_k0&test_suite=1&test_suite_input=6%2C+%5B2%5D%0A6%2C+%5B2%2C4%5D%0A30%2C+%5B2%2C3%5D%0A10%2C+%5B9%2C2%5D%0A20%2C+%5B3%2C4%2C5%5D%0A0%2C+%5B1337%5D&debug=0) Naïve solution. Surprised it's only 2 bytes longer... [Answer] # [R](https://www.r-project.org/), ~~66~~ ~~59~~ ~~58~~ 55 bytes *Edit: -7 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)'s comment on [dingledooper's answer](https://codegolf.stackexchange.com/a/224746/95126): previous version uselessly worried about handling bases >10* ``` f=function(n,b)`if`(n,10*f(n%/%b,c(b[-1],b))+n%%b,0)[1] ``` [Try it online!](https://tio.run/##Tc7BCsIwDMbxu08xkEKrEZN0DjzsScZwtqzQS4W5PX9tp2Bu4f@Djyw5rvPycM/33OfQhy35Nb6STuDMFMNUDsJT0EldlQOv3XChsZg5J1UCmoHG/4TugE1zbIjwIKPXDK2pYiVY3MXuwoTSqNr9Z0RCuIqFFm5fYxaI5d1aMX8A "R – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 68 bytes Solved via recursion: we keep storing the modulo, dividing by the base, and drilling down until we hit zero. Then we print each digit on the way back up. ``` f(n,v)=my(m=n%v[1]);n\=v[1];n&&f(n,vector(#v,i,v[i%#v+1]));print1(m) ``` [Try it online!](https://tio.run/##JczBCoMwEATQe39DlCzdgjFaKCFfkuYgopJD1hBkoV9vk3h7wwwT5@Rfe7yuTRAymPATwVDLVjrQ9DUFmrqu1utyHkk0jB7Z@rbhZ16BjsnTKUWA8vJGOzh43MCxUvXFqlpmf/CeDNkKR5xqKsHBHw "Pari/GP – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes Returns in list. ``` def f(x,b,s=[],n=0): while x:s,x,n=[x%b[n]]+s,x//b[n],(n+1)%len(b) return s ``` [Try it online!](https://tio.run/##LYpBCsMgFET3nuJvAn4iTdrsAp5EXESqRJAfUUPt6a1CVzPz3sRvOS/aWntbB45XYUSWSguSK@4MPqcPFuqeRe1I1cko0nruc1lGFZzmJ07BEjfIINlyJ4LcDpDgqXBP8S4ckQUJagBCcFcC6hb@8pFj8D01i2lcHD8EBMS2rewF2w8 "Python 3 – Try It Online") ``` while x: ``` Keeps self-updating while **X** is larger than the selected element in **[base]**. [Answer] # [C (gcc)](https://gcc.gnu.org/), 82 bytes ``` a;c;i;r;f(x,b,l)int*b;{for(a=1,r=i=0;x;x/=c)c=b[i++%l],r+=x%c*a,a*=10,x-=x%c;x=r;} ``` [Try it online!](https://tio.run/##bZNhb5swEIa/51eckJAwOCoYmNS63j5M@xUJmsCYzipLKxxp1iL@@jIbA8Fpo5DLvY/f0/l08P0L59drTTmVdKBdpHGDeyRP57ihl@5tiGqW4YFJllJN9QPjiLPmIJMk7Cs8JEyHPK5xHbMsxXpvU6rZQMfr@2CKRLZQjcEE6BFcwFQEK4IEBik14Rl6CkkiEUyOLgpCFbYBjuS3AEPwFAQIQ32QFaIw7qz1dy1PEdpddmA@VjgLdU4Plal4ISNdpWyWcLERySLmGzF34iPe2gsn5rjA5UYuPXnpIZ6YcmzqB7seXCAu5C4ULmzsU/6zd3Yl/4q3LpqqoIc5i12KYUMzn2Y@JT4lPs19mvu08Gnh09KnJbq/iHYX@YLBfHMzCrMcQMyTbk4K/S74WbTubGaP2KMkS63BDC4j5Obgv@ohNr@Cv4rBWMCagqP@QY768bt5SrstmzwPZudt5U6t0PPaTX@fl0strdzutSrTbtrTZnunckv7ttJ82YlXdIvjZsbqMwr9Yu4/xcrg5VX0iTBkHdy9dX2BWgwHMw6N7ljUYOjRR0MF@68QthCq48n4FF4HLRhT1ewYd@P1H@/6@kVd93/@Aw "C (gcc) – Try It Online") Inputs a non-negative integer in base \$10\$, a pointer to the array of bases, and the array's length (since C pointers don't carry any length info). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` F¬θ0WθFη¿θ«←I﹪θκ≧÷κθ ``` [Try it online!](https://tio.run/##JcuxCsIwFIXhuX2KS6cEIhS76SS6CFbEtXQIbdpcDIlJrnUQnz2GOp6f7wxahsFJk9LkArCrI@Y5h1tAS6yqK74v3xqNgpxhJZoDTuv8lMXf7S5qIgFHGYm1bnwZx7yAB@f5XbTyeYgRZ3vHWRM7WzrhgqPKQIDP4ptS19QCuq2Apu/TZjE/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F¬θ0 ``` Special-case an input of `0`. ``` WθFη¿θ« ``` While the input is non-zero, loop over all the bases while the input is non-zero. ``` ←I﹪θκ ``` Output the next digit in reverse order. ``` ≧÷κθ ``` Divide by the base. ]
[Question] [ When I was in grade 3, we were taught how to solve a very simple math problem. It was equaling the denominators of two or more fractions. Let's take two proper fractions:- $$ \frac{1}{2},\frac{2}{3} $$ First we will take the Least Common Multiple of the denominators of the two fractions, the LCM of \$2,3\$ are \$6\$. Then we divide the LCM (\$6\$) by the denominators of both fractions (\$6\$) and we get \$3,2\$ and serially multiply them with the numerators of the both fractions and get $$ \frac{3}{6},\frac{4}{6} $$ And that's the result. # Challenge Take two or more fractions, and equalize their denominators. # I/O format You can take an array/list of `(numerator,denominator)` pairs. Pre-defining them in TIO header is allowed. You can take in other better ways too. ``` Input: ((1,2),(2,3)) or 1,2 2,3 1/2 2/3 Output: (3,6),(4,6) or 3,6 4,6 3/6 4/6 Input: ((1, 8), (5, 12)) 1,8 5,12 1/8 5/12 Output: ((3, 24), (10, 24)) 3,24 10,24 3/24 10/24 Input: ((1, 2),(2, 3),(4, 6)) Output: 3/6 4/6 4/6 ``` # Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. (except use of TIO headers to pre-define input) * Trailing whitespace in output is allowed. * If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on. * Please explain your answer. This is not necessary, but it makes it easier for others to understand. * Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` f=(a,t=1)=>a.some(v=>t%v[1])?f(a,1+t):a.map(([p,q])=>[p*t/q,t]) ``` [Try it online!](https://tio.run/##ZcrBCgIhEADQe/8RODUZGkEsuH2IzGHYNIrd1c3B3zc7d37vzZXL9HllOa3pEVqLTjGKM@BG1iUtQVU3yr56Q3CP3cxRYGC9cFbKZ9yoT58Pct5QCNqU1pLmoOf0VFF5b9ASeosXIoDdv966XtHYH7cv "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 63 bytes ``` f=(a,t,b=a.map(([p,q])=>[m=p*t/q,o&=m%1||t],o=t))=>o?b:f(a,-~t) ``` [Try it online!](https://tio.run/##ZctBCsIwEEDRvfdQEplWEhGkMPYgQxZpbURpOqkduipePca18HeP//KrX/r3M0k18X3IAUvKg0CHvo4@KUUJZqfxRhHTUU4z8AHj3mybOGAUXYjbrgnlqj6ic8/TwuNQj/xQQREZsA7Iwtk5rXf/ei16AWN/nL8 "JavaScript (Node.js) – Try It Online") `m=p*t/q` cannot be changed to `p*=t/q` due to floating point errors. For example, `11*15/11` is `15`, but `11*(15/11)` is `14.999999999999998`. :( * The first answer here will output `[[6, 12], [6, 12]]` for input `[[2, 4], [3, 6]]`. * The second one will output `[[1, 2], [1, 2]]` for input `[[2, 4], [3, 6]]`. --- # [JavaScript (Node.js)](https://nodejs.org), 62 bytes * [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) had modified the code to make it work in 62 bytes. This one would support positive fractions. ``` f=(a,t,o=-~t,b=a.map(([p,q])=>[p*t/q,t+=p*t%q]))=>t<o?b:f(a,o) ``` [Try it online!](https://tio.run/##bY1BDoIwEEXXeIpuTIoOYAsoNVYP0nRREYwGaZHGpVfHCZiYqJnNm595f67mYfryfnE@au2pGoZaUgMerIyeHo7SxDfjKFUOOh3KvXILn3TglxJhjhFmfmcPx22Nmg2H0ra9baq4sWdaU6UYcA2KQ6rxNgiShCicFMiaaEDKRiJ69isWKObA@LfJs0llq4n/yFkOAu1CABu/MzaWvDvyHAhjU4nYiM/CJyR6eAE "JavaScript (Node.js) – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes ``` LCM@@(q=Last/@#)/q#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n27738fZ18FBo9DWJ7G4RN9BWVO/UFntf0BRZl6JgkN6dHW1oY6CUa2OQrWRjoJxbW0sF6qUBUjKVEfB0AhTDqENSJvoKJgBlfz/DwA "Wolfram Language (Mathematica) – Try It Online") Fractions are in the form `{numerator, denominator}` We simply multiply the fractions by the LCM of denominators divided by the denominators [Answer] # [Factor](https://factorcode.org/), ~~73~~ 64 bytes -9 bytes thanks to chunes! ``` [ dup 1 [ lcm ] reduce [ swap n/v v* dup length ] keep <array> ] ``` [Try it online!](https://tio.run/##TY9PC8IwDMXvfop3Fpxu/kFUvIoXL@JJPJQa3djW1aabDOlnn7VDkRzykvzySG5C2sp0p@P@sFtBMFeSkZNRVKAUNo1utZI2qxSD6VGTksT9oKHPJkMYI1qGNmRtq02mLNaDFz4RI4HzOcHUZxd6U8yCWvj49mIsg5ojTv7ApCfjSa/cz3P2c@09XHfGtdZ@dkYhS1xg6FpL8iU/hYYaN2iGASlI3W3qiZxIYxOO3@LShc9HpYej7g0 "Factor – Try It Online") Takes the input as two separate lists for numerators and denominators # [Factor](https://factorcode.org/), 73 bytes ``` [ unzip dup 1 [ lcm ] reduce swap over [ n/v v* ] dip '[ _ 2array ] map ] ``` [Try it online!](https://tio.run/##TY7NCsIwEAbvfYrvJnhQGn8QfQDx4kU8FZGQbrHYJnGTVGrps9dUPPSyCzOzsIVU3vBwvZzOxz2exJoqSOeMcqilfyyKoJUvjXZw9AqkFf1FQ@Olg2SWrUPBLSyT963lUnuUBoekSzp0SCHQxy2wirv/s92PbZCKCZyGHdbYjg5Jn2DIEPSntMiDjWGGStW4gSkPiuDe0sI0xFHoZYNmHl0e61mGO8Tvx0jqWN2GcS6GLw "Factor – Try It Online") Takes the input as a list of (numerator,denominator) pairs. I thought it would be shorter using fractions but I didn't manage to make it nice. Except this the Factor version TIO has normalizes the fractions. [Answer] # [J](http://jsoftware.com/), 14 10 bytes ``` ,.**./@]%] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/dfS0tPT0HWJVY/9rcnGlJmfkKxgqGCmkAbExhKuuDhM2BQpbKBgaoYsbKZhANCiY/QcA "J – Try It Online") -4 after realizing taking a list of numerators and a list of denominators was allowed Works like `<list of numerators> f <list of denominators>`. * `*./@]` LCM of denominators (right hand arg)... * `%]` Divided elementwise by the denominators... * `,.*` Times the zip of the numerators and denominators. [Answer] # [Ruby](https://www.ruby-lang.org/), 57 bytes ``` ->l{k=l.reduce(1){|s,x|s.lcm x[1]};l.map{|a,b|[a*k/b,k]}} ``` [Try it online!](https://tio.run/##FctBCoAgEEDRq7SKisnQCIKoiwyz0NKNBlEEhXp2s9XjL/55qzeZObWL83Z27NTbveqK1z5c8ISLuXUvHuQUJ8d2efggQQWUje0UWIoxHQUichgJcAAuKJtTZAT0RPRfVWnq9AE "Ruby – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` aæl/Ṅ:Ʋ× ``` [Try it online!](https://tio.run/##y0rNyan8/z/x8LIc/Yc7W6yObTo8/f///9FGOsY6ZrH/ow11jHRMYgE "Jelly – Try It Online") Full program. Takes a list of denominators \$[d\_1, d\_2, ...]\$ on the left and a list of numerators \$[n\_1, n\_2, ...]\$ on the right. Outputs a list of denominators, then a list of numerators Would be [7 bytes](https://tio.run/##y0rNyan8///wshz9hztbrI51HZ7@////aCMdYx2z2P/RhjpGOiaxAA) if we could just output the dominator once. ## How it works ``` aæl/Ṅ:Ʋ× - Main link. Takes denominators D on the left and numerators N on the right Ʋ - Group the previous 4 links into a monad on D: æl/ - Reduce by LCM a - AND; Replace each element in D with the LCM Ṅ - Print the list of LCM : - Divide each by the corresponding element of D × - Multiply this list with N elementwise ``` [Answer] # [Haskell](https://www.haskell.org/), 45 bytes ``` n#d=($d).zipWith(div.(*foldr1 lcm d))<$>[n,d] ``` [Try it online!](https://tio.run/##PczNCgIhFEDhfU8xMLPwxkXQfmiRvUHrFiIhOjGSmqgT1MtbUbT8OHAmXa6j963F3goyWKBPl06uTsS6OyXLy83bzDpvQmcB9sNBRrSq1bFUo8tYhCSSIVcoOa4U4Eebt3bI@I8c19@MWwVqEbSLIuh0PJOUXax0jmbO@UF6gP@2vQA "Haskell – Try It Online") Takes two lists (`n=numerators` and `d=denominators`) as input, returns two lists with the same format as output. Assumes fractions in the input are reduced. # [Haskell](https://www.haskell.org/), ~~72~~ ~~69~~ 66 bytes ``` f x|l<-foldr(\(n,d)->lcm.div d$gcd n d)1x=[(div(n*l)d,l)|(n,d)<-x] ``` [Try it online!](https://tio.run/##PcxNDoIwEAXgvafowsWMGUiKP3EB3sATYGMaBpQwVEIbw4K7VzTq8nvv5d2t72qRGBs1zZInzUN4hAs4YkxOUvUpt0/F61vFyilGPRUlLBG4jSCT4PyZ5slkYqh9qKyvfVGWoClDgoy2aOit46I96ezLX0mwowMas@pt64reDucrDGPrQtrg/y@@AA "Haskell – Try It Online") Takes a list of pairs as input, returns a list of pairs as output. Works for unreduced fractions as well. # [Haskell](https://www.haskell.org/), 79 bytes ``` f x|let(z,l)=foldr(\(n,d)(y,a)->((div(n*l)d,l):y,lcm(d`div`gcd n d)a))([],1)x=z ``` Takes a list of pairs as input, returns a list of pairs as output. Works for unreduced fractions as well. Quite a bit longer than the other answer, but I decided to post it anyway since there is some Haskell magic going on! The LCM of the (reduced) denominators `l` appears both on the left hand side and the right hand side of the `let` expression. This is only possible because of Haskell's lazyness. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 33 bytes ``` K1JEFkJ=K/*kKikK;FkE[/*kKhJK)=JtJ ``` [Try it online!](https://tio.run/##K6gsyfj/39vQy9Ut28vWW18r2zsz29vaLds1GsTO8PLWtPUq8fr/P9pIR8FYxyyWK9pQx0jHJBYA "Pyth – Try It Online") Takes two lines of input: first line should contain the list of denominators, and the second line should contain the list of corresponding numerators. # Explanation ``` K1 # Initialize K to 1 JE # Initialize J to evaluated input (in this case, list of denominators) FkJ # For loop over elements of J, with iterator as k =K # Set K to *kK # Product of k and K ikK # GCD of k and K / # Divide them to get the LCM FkE # Another for loop over the next evaluated input (the numerators) hJ # First element of J /*kKhJ # Convert the numerator accordingly K # Denominator [...) # Put that inside a list and print it tJ # Tail J (first element removed) =J # Assign J to it ``` [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes ``` import numpy f=lambda a,i=0,k=1:i<len(a)and f(a,i+1,numpy.lcm(k,a[i][1]))or[(p*k//q,k)for p,q in a] ``` [Try it online!](https://tio.run/##TctLDsIgFIXheVdxh6A3VmhMTCMrIQyuViKhPEpw0NUjOnJ6vvPnvb5SnFpzIadSIb5D3gerVgr3hYDQqTN6JWZ3W5@REae4gGV9Pwr8nU/rIzCPpJ3RwnCeimb54MdxQ89tKpBxAxeBTMvFxcos01rg1aC@oJCmJ8M/gOwiEaavtA8 "Python 3 – Try It Online") Takes a list of lists and computes the LCM of denominators. This result is stored in `k` and at the end the fractions are converted to the same denominator (`k`). [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 82 bytes ``` \d+ * +`(_+)/((_+)(\3)*) (_+)/(?!\2\b)(\3)+\b $#6*$1/$#6*$2 $#4*$5$5/$#6*$2 _+ $.& ``` [Try it online!](https://tio.run/##LYlLDsIwDET3PoVRrSqJJYydpuqOi1jqR3TBhgXi/gHSbmbmvXnvn@dr1Vr9wZCAlzBzlPDP4DmmiIe4X9x8a459A@rGRCqtDKkbEhUqJ8PMQNe@VhVDkwwqExZRg1PgICNksdtvaGnXFw "Retina – Try It Online") Link includes test cases. Explanation: ``` \d+ * ``` Convert to unary. ``` +` ``` Repeat until all denominators are equal. ``` (_+) ``` Match a numerator... ``` /((_+)(\3)*) ``` ... and the largest factor of a denominator... ``` (_+) ``` ... and another numerator... ``` /(?!\2\b)(\3)+\b ``` ... and a denominator that is not equal to the first denominator but with the shared (greatest) common divisor. ``` $#6*$1/$#6*$2 $#4*$5$5/$#6*$2 ``` Multiply the first fraction by the multiplicity `$#6` of the GCD in the second fraction, and also update the second fraction. ``` _+ $.& ``` Convert to decimal. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ≔Eθ⊟ιη≔¹ζW⌈﹪ζη≦⊕ζIEθ⟦÷×ζ⊟ι§ηκζ ``` [Try it online!](https://tio.run/##PY4/D8IgFMR3PwXjI8HBalycGl06NOngRhhIIULkTy20Nv3yCLE6vVze/e6uV3zsPTcp1SHoh4OWD/AiqPMDaIwJUviy214Hgtas3kobibJx0Xay0HoxGQ9rsWKMMr/ZG9eP0koXpfiC3ahdhCsP8ddCGxdvetZCwl1bGUrKv7mOjRNyAUXQs@iV5fxLSpTSvKRiGa8IOpZ7IujMGEv72XwA "Charcoal – Try It Online") Link is to verbose version of code. I/O is standard Charcoal array format. Explanation: Uses brute force. ``` ≔Eθ⊟ιη ``` Get the denominators. ``` ≔¹ζ ``` Assume the LCM is 1. ``` W⌈﹪ζη≦⊕ζ ``` Keep incrementing the LCM until all the denominators divide it. ``` IEθ⟦÷×ζ⊟ι§ηκζ ``` Scale the fractions to the new denominator. [Answer] # [R](https://www.r-project.org/), ~~69~~ 66 bytes *Edit: -3 bytes thanks to Giuseppe* ``` function(m)m/m[,2]*which(!rowSums(outer(1:prod(m),m[,2],"%%")))[1] ``` [Try it online!](https://tio.run/##bcxBCsIwEIXhfU8RK4UZGahJYxHBU7gsXUi0NNA0JU2onj5GF@qiDG9WP5@LszbToLvnOXZhVF7bEQya0jQk2t3Sa9XDxtnlEswMNvi7A36anL2lij4R5UWRI2LD2y8G5uqdfoACTiJdhSQQ2ZZVZc1kWrZWHuhIXPxSIRnfp5@ts/INU41J/6fT4gs "R – Try It Online") Input & output as 2-column matrices, with each row representing a pair of numerator & denominator. [Answer] # Excel, 130 bytes ``` =LET(n,COUNT(A:A),b,OFFSET(B1,,,n),q,SEQUENCE(PRODUCT(b)),MIN(IF(MMULT(1*(MOD(q,TRANSPOSE(b))=0),b^0)=n,q,""))/b*OFFSET(A1,,,n,2)) ``` Uses columns A&B for input ``` =LET( n,COUNT(A:A) ' Number of fractions b,OFFSET(B1,,,n) ' List of denominators q,SEQUENCE(PRODUCT(b)) ' 1..product of all denominators MIN(IF(MMULT(1*(MOD(q,TRANSPOSE(b))=0),b^0)=n,q,""))/b*OFFSET(A1,,,n,2) ' final calculation 1*(MOD(q,TRANSPOSE(b))=0) ' matrix of q by b where 1 indicates q mod b = 0 IF(MMULT( ,b^0)=n,q,"") ' if q is divisible by all n numbers then q else "" (list of all common multiples) MIN( ) ' least common multiple /b*OFFSET(A1,,,n,2) ' multiply each row by the number need to change denominator to LCM ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .¿©¹÷*®δ‚ ``` Input as two separated lists, first the list of denominator, second the list of numerator. Output as a list of pairs of [numerator, denominator]. [Try it online](https://tio.run/##ASoA1f9vc2FiaWX//y7Cv8KpwrnDtyrCrs604oCa//9bMiwzLDZdClsxLDIsNF0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCsUvof71D@w@tjDi8XevQunNbHjXM@q/zPzo62kjHOFYn2lDHKDZWRyE62kLH0AjMN4XwgdI6ZhAFOiaxsbEA). **Explanation:** ``` .¿ # Get the Least Common Multiple (LCM) of the first (implicit) input-list of # denominators © # Store this value in variable `®` (without popping) ¹÷ # Integer-divide it by each value of the first input-list * # Multiply each value at the same positions to the second (implicit) # input-list of numerators δ # For each value: ® ‚ # Pair it with the stored LCM of variable `®` # (after which the resulting list of pairs is output implicitly as result) ``` [Answer] # [Julia](http://julialang.org/), 22 bytes ``` n$d=(l=lcm(d))n./d.=>l ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P08lxVYjxzYnOVcjRVMzT08/Rc/WLue/Q3FGfrlCtKGOUaxKtJGOcSwXVMRYxwQoYqZjBhcx1DEFiljoGBohKTI0AOkz0TEyQVJnBNYLNA1Ft5GOBVQUaMJ/AA "Julia 1.0 – Try It Online") * expects `[numerators] $ [denominators]` * outputs an array of pairs : `[num1 => den1, num2 => den2,...]` * could be [20 bytes](https://tio.run/##yyrNyUw0rPj/P08lxVYjxzYnOVcjRVMzT08/RSfnv0NxRn65QrShjlGsSrSRjnEsF1TEWMcEKGKmYwYXMdQxBYpY6BgaISkyNADpM9ExMkFSZwTWCzQNRbeRjgVUFGjCfwA "Julia 1.0 – Try It Online") with the denominator only once in the ouput ]
[Question] [ ## Input Take a list of values **xi** each paired with a key **yi**. ``` [(x1, y1), (x2, y2), ...] ``` ## Output Return a list **L** containing only values from the set {**xi**}. * The length of **L** must be equal to the number of unique keys **k** in the set {**yi**}. * For each unique key **k** there must be a value from {**xi**} that has key **k**. ## Details * Standard loopholes disallowed. * You can assume all values in the input will be nonnegative integers. * There may be duplicate values and keys. * You can assume there is at least one value/key pair in the input. * If you prefer to take two lists of equal length as input (one for values, one for keys) that is fine. * You may not take any other input. * The order of the list you output does not matter. * The **xi** you choose for each key does not matter. For example, with input `[[0, 0], [1, 3], [2, 3]]` you can return either `[0, 1]` or `[0, 2]` or any permutation of these. ### Examples ``` [[1, 2], [3, 2], [3, 0]] -> [1, 3] or [3, 3] [[7, 2], [7, 0], [7, 1]] -> [7, 7, 7] [[4, 0], [4, 0], [9, 1], [5, 2]] -> [4, 9, 5] [[9, 1], [99, 10], [5, 5], [0, 3]] -> [9, 99, 5, 0] ``` Fewest bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 34 bytes ``` lambda a,b:dict(zip(b,a)).values() ``` [Try it online!](https://tio.run/##K6gsycjPM/qfYxvzPycxNyklUSFRJ8kqJTO5RKMqs0AjSSdRU1OvLDGnNLVYQ/N/QVFmXolCjka0oY6CMRDF6ihEG@koAJFBrCYXXNZSx9JSx1THACRtqGNoAGQbx2r@BwA "Python 2 – Try It Online") Takes input as list of values and list of keys. Generate dictionary, swapping keys and values, which leaves only unique y values. Return all corresponding x values [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Ḣƙ ``` [Try it online!](https://tio.run/##y0rNyan8///hjkXHZv7//z/aSEcBiAxi/0cb6igYA1EsAA "Jelly – Try It Online") Takes two lists of equal length, first is keys, second is values. [Answer] # [J](http://jsoftware.com/), 4 bytes ``` {./. ``` ## How? The left argument `x` is a list of key, the right one `y`- a list of values `/.` groups `y` according `x` `{.` takes the first element of each group [Try it online!](https://tio.run/##NcsxCoAwDIXhvad4uBRBYtpapEJPIwZxcegonr1Gi/xTPl6OKiUTGAu4XjRS7U1HsJLJYsC9QIox27qf8BpD4BAQfmI9BfNbI/7IK05aQmzs4BhRP0UtKeusPg "J – Try It Online") [Answer] ## Clojure, ~~20~~ 18 bytes ``` (comp vals zipmap) ``` This takes lists of values and keys as arguments, in that order. [Answer] # [Python 3](https://docs.python.org/3/), 42 bytes ``` lambda a,b:[dict(zip(b,a))[q]for q in{*b}] ``` [Try it online!](https://tio.run/##DcJLCoAgEADQq8xyjFlU7oJOYrPQRBLKH24qOrv5eOmuRwyyuXVrp76M1aDJLMr6veLjExrSQqjMLhbI4MM7mI9bKj5UdKgmAtkzgZoJ@pGFaD8 "Python 3 – Try It Online") a = values b = keys [Answer] # [Haskell](https://www.haskell.org/), ~~49~~ 47 bytes ``` map fst.nubBy((.snd).(==).snd) import Data.List ``` [Try it online!](https://tio.run/##RYuxDoIwAER3vuISlzbBBkRCGFjUURNGE2SoSrURKqF18OetVEqc3uXd3Z3rR9O2dnFthFQNBE624z2ENky9zps3IUyrK2WkKOgvBbLrn4PBjhvO9lKbcS8VCoy3A0g/SGXAICgCVBWJQ6xoCJL8GdE6QFiRzKvMqYmxr9ZezcxdNTJ1l2kyq9yFyJepYxQicaPafi6i5Tdtl8dtWX4B "Haskell – Try It Online") Input as a list of tuples, e.g. `[(1, 2), (3, 2), (3, 0)]`. --- **Input as list of lists (49 bytes)** ``` map(!!0).nubBy(\a b->a!!1==b!!1) import Data.List ``` [Try it online!](https://tio.run/##RYuxDoIwFEV3vuI1LpAUUkRDGHBQR00YTUqHolQboRKogz9vbUOJyzsv59774NOz7TqzurVCqhYE1KbnQ4gQiRL1bvafsObQxDuOUFqWjb1RIPvhNWo4cs2Tk5y0XUgFJdjhGcJhlEpDAiKCACilKYY1w0CzPwljAWBKc69yp2amPtp4tbBwkeXWTebKogr3EB9uHQmGzJWY@V5Fx@@TiS@HqvoB "Haskell – Try It Online") [Answer] # JavaScript (ES8), 43 bytes Takes input as 2 distinct lists in currying syntax `(values)(keys)`. ``` v=>k=>v.filter(o=(x,i)=>o[j=k[i]]?0:o[j]=1) ``` [Try it online!](https://tio.run/##ZY/RDoIwDEXf/Yo@bkmVTTQGk@GHLHsgCGZAqAFC/Pu5TTAGm/vQrvfcdE0xF2M52Oe07@leuVq5WeWtyudDbbupGhgp9kLLVU66Ua22xtzE1fdGSe5K6kfqqkNHD1YzLRFSL8OZPiJ4CcM5fCtJIFoM0AA6OnebhAtC0JIgEORfwmrZoicErwzhHGjxof0VS0BA1/0W9Y9ZWMSD4zekiGMa4YD@Wtwb "JavaScript (Node.js) – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ṁhüt ``` [Try it online!](https://tio.run/##yygtzv7//@HOxozDe0r@//8fHW2iYxCrAyUtdQyBpKmOUWwsAA "Husk – Try It Online") ### How? ``` ṁhüt – Full program. üt – Group by tail (the lists without the first element). ṁh – Map heads (the lists without the last element) and concatenate the results. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╠HB%§ ``` [Run and debug it](https://staxlang.xyz/#p=cc48422515&i=[1,3,3]+[2,2,0]%0A[7,7,7]+[2,0,1]%0A[4,4,9,5]+[0,0,1,2]%0A[9,99,5,0]+[1,10,5,3]&a=1&m=2) Takes two arrays, first values, then keys. Explanation: ``` cu:I@J Full program, unpacked cu Push a unique copy of the keys. :I Indices of the unique elements @ Index the values array J Join by space Implicit output ``` [Answer] # [R](https://www.r-project.org/), 30 bytes ``` function(x,y)x[!duplicated(y)] ``` [Try it online!](https://tio.run/##Lcw7CoAwEATQ3lvY7cIU@SiSwpOIhSQGBIkiEfT0McGwzfCG2Sv5Mfk72LgdgR68/Eytu899s0tcHb08J0@WJDQ0w5KCgmBuCg7I96OArNihg0FfWBSGqoWByZ7HKO@kyFkzpw8 "R – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes ``` â £VgUbX ``` [Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.5&code=4iCjVmdVYlg=&input=WzIsMiwwXQpbMSwzLDNd) Thanks to Shaggy for saving 1 last byte Completely reworked the logic. Takes some cues from Luis' answer, but I think it's still improved. Now takes input as two lists, `keys, values`. Apparently I'm still short of optimal though. Explanation: ``` â £ For each unique Key X Ub find the first index in "keys" X which is equal to X Vg then take the "value" with the same index ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 27 bytes ``` ->a,b{b.zip(a).to_h.values} ``` [Try it online!](https://tio.run/##RYtBCsIwEEX3PcUsVeKQWkvpQi8SBkkkpYLY0KSCtj177NAUV294708/mE9sLvF41cKMBr8Pt9N7DN2txbd@DtbPUWVK5QJOJEAVf0oisZQqmYrNynwt52Q21lwWlvxBwJNN1XzIFEumFFAQZYRW39txChM4aNQhYOj1y7vOW5rjDw "Ruby – Try It Online") Takes input as two arrays (the footer transforms the original test cases into this format). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` DÙkè ``` Take two input lists: first the values, then the keys. [Try it online](https://tio.run/##MzBNTDJM/f/f5fDM7MMr/v@PNtAx0DHUMYrlijbRMdGx1DGNBQA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/m9t/l8Mzswyv@6/yPNtAx1jGO5QLShjpGQNpIx0jHAEgbQsWBPB1DIG2uA4RgdTCVJjomOpY6pmC1hgY6pmDlljqWQDGwCRCVBshqdUxiAQ). **Explanation:** ``` D # Duplicate the values-list Ù # Get all unique items of the values-list # i.e. [0,0,1,0,2] → ['0','1','2'] k # Get all (first) indices of these unique values # i.e. [0,0,1,0,2] and ['0','1','2'] → [0,2,4] è # And use this index to get the key from the keys-list # i.e. [0,2,4] and [4,4,9,5,4] → [4,9,4] ``` [Answer] # Java 8, 82 bytes A lambda from a stream of `int[]` pairs to `java.util.Collection<Integer>`. ``` m->m.collect(java.util.stream.Collectors.toMap(a->a[1],a->a[0],(a,b)->a)).values() ``` [Try It Online](https://tio.run/##nZDBisIwEIbP7VPMMYEYWhcPohaWhYU9ePIoPYw1lbhpUpq0i0ifvRtrZHXX057mY4bvZ2aO2OHE1EIf959D3e6ULKBQaC2sUWo4x1FoWofOl1JqVHD0Fm@dVLxsdeGk0fw9wPJnZl0jsOKbsSyldts8Y3fum1FKXKUP7cRBNFkGJazioZpkFS@uY/InMHimsdyZNdYEJxlu05yNNckZQbajninlHapWWEKHOFrEv4/pjNxD5e8kfkepD9scsDlYejk7Gvf1Hf@FFWjxBbfGZRidEwZJz0ZMGbwEnN6wXzxETJ9mzBmkQZxf@BY4YzALmDwEbk7WiYqb1vHaL@yUJiXHulanuy@9Ng2ebHgWkZpS@m93epX7uI@Hbw) [Answer] # [Julia 0.6](http://julialang.org/), 36 34 32 bytes ``` A->values(Dict(y=>x for(x,y)=A)) ``` [Try it online!](https://tio.run/##yyrNyUw0@5@WZ/vfUdeuLDGnNLVYwyUzuUSj0tauQiEtv0ijQqdS09ZRU/N/QVFmXklOnkZankZ0tKGOglGsjkK0MYI2iI3V1FTgQlFmDpU2B0lDaEMsykyg0jDaEqQMSJuCtGMqh0lbghgGUIWmINpAR8EYrOE/AA "Julia 0.6 – Try It Online") *(shaved off two bytes thanks to @JonathanFrech)* *(another two bytes by replacing `∈` with `=` in comprehension)* The input format specified in the question `[[1, 2], [2, 7]]` works as it is in Julia as an array of arrays containing (potential) key value pairs, the only thing to take care of is that the key comes second and value first. --- Slight change, for the same bytecount, ``` A->values(Dict((y,x)for(x,y)∈A)) ``` [Try it online!](https://tio.run/##yyrNyUw0@5@WZ/vfUdeuLDGnNLVYwyUzuURDo1KnQjMtv0ijQqdS81FHh6Om5v@Cosy8kpw8jbQ8jehoQx0Fo1gdhWhjBG0QG6upqcCFoswcKm0OkobQhliUmUClYbQlSBmQNgVpx1QOk7YEMQygCk1BtIGOgjFYw38A "Julia 0.6 – Try It Online") [Answer] # [Julia 0.6](http://julialang.org/), 29 ~~26~~ 19 bytes ``` values∘Dict∘zip ``` [Try it online!](https://tio.run/##yyrNyUw0@5@WZ/u/LDGnNLX4UccMl8zkEiBVlVnwv6AoM68kJ08jLU8j2khHAYgMYnUUog11FIyBKFZT8z8A "Julia 0.6 – Try It Online") Point-free style. Takes input as an array of keys and an array of values. --- Older solution: ### 29 26 bytes ``` v\k=values(Dict(zip(k,v))) ``` [Try it online!](https://tio.run/##Vcu9CsMwDATgvU/hUYIb5Py0eOjWt7A9hJLBjQmhSTz05V1lKSm6QfDdvfachmutJUz3MuR9XOmRnht90kITCjPX5Z3mLc/kLUyricE3MBqJfPmhg3PoIaoWVvRtTxzI36AXYXQssJH/sEMHnR8sB6PRQv0C "Julia 0.6 – Try It Online") *-3 bytes using operator syntax instead of lambda* Takes input as an array of values and an array of keys. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` viiQ(5Mu) ``` [Try it online!](https://tio.run/##y00syfn/vywzM1DD1LdU8///aEMdBWMwstRRMNVRMInlijbSUQAiAx0Fc7CEeez//wA "MATL – Try It Online") Probably suboptimal, but hey, it works! Uses the facts that (a) input is guaranteed to have only non-negative integers, (b) MATL extends an array of you try to assign to an index that doesn't exist. `v` - create an empty array in the stack `i` - get array of values `iQ` - get array of keys, increment by 1 (so the minimum value is 1, not 0, since MATL indexing is 1-based) `(` - assignment indexing - use the array of keys as indices and assign the values to those indices (if any keys are repeated, only the last value remains in that location) `5M` - gets the last input of the last call - which would be the array of indices we used `u)` - take a unique list of those indices, index with that list, and leave that result (which is a list of values of unique keys) in the stack [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~24~~ ~~20~~ ~~16~~ 8 bytes *-4 bytes thanks to @Shaggy* Takes input as `key, values` ``` â £VgUbX ``` [Try it online!](https://tio.run/##y0osKPn///AihUOLw9JDkyL@/4820jHSMYjlijbUMdYxjgUA "Japt – Try It Online") --- # [Japt](https://github.com/ETHproductions/japt), ~~20~~ 18 bytes ``` r@bY <Z?X:XpVgY}[] ``` [Try it online!](https://tio.run/##y0osKPn/v8ghKVLBJso@wiqiICw9sjY69v//aCMdIx2DWK5oQx1jHeNYAA "Japt – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` hMhM.ge ``` [All testcases](http://pyth.herokuapp.com/?code=hMhM.ge&test_suite=1&test_suite_input=%5B%5B1%2C+2%5D%2C+%5B3%2C+2%5D%2C+%5B3%2C+0%5D%5D%0A%5B%5B7%2C+2%5D%2C+%5B7%2C+0%5D%2C+%5B7%2C+1%5D%5D%0A%5B%5B4%2C+0%5D%2C+%5B4%2C+0%5D%2C+%5B9%2C+1%5D%2C+%5B5%2C+2%5D%5D%0A%5B%5B9%2C+1%5D%2C+%5B99%2C+10%5D%2C+%5B5%2C+5%5D%2C+%5B0%2C+3%5D%5D&debug=0). [Answer] # [Perl 5](https://www.perl.org/) `-pa`, 24 bytes ``` %a=@F;$_=join$/,values%a ``` [Try it online!](https://tio.run/##K0gtyjH9/1810dbBzVol3jYrPzNPRV@nLDGnNLVYNfE/SExJJT4mLyZP6b@RgqGCkYKxgoGCMZeRgjmQNgeKmHMZKJgogLChgiVQ3pQLRBsaKFhaKpgCIVD9v/yCksz8vOL/ugWJAA "Perl 5 – Try It Online") Takes input in the format `key value key value key value ...`. TIO footer is only to separate test cases. [Answer] # [Perl 6](https://perl6.org), 25 bytes ``` {.unique(:as(*[1]))[*;0]} ``` [Try it](https://tio.run/##TY5Ba4NAFITv@yvmIEXtVlatkSiG9tBbj6WXZSlitkVqjI0aGtL8drtP1qawMMPO9@a9Th@a1TT2GsdVUOWM7U64qfZbjWI6B2Nbf43azcre9WWoPE/6uVCXyUAPg@4HFGjqVvfBruwy@MHT6@Oz6aC6FxPnrGvKFrczm7P3/cGO3W3gvMHNPvXJdeq2GwePIzuWjVnm6O9OV4Peeh7ODKh70D1X7g/gCD5qKr5MUgoOoThkyBGTRqQKKDagLFT4mU2kmCQoIii@qljguYDgmIyBUwuldkNKbRY2nh5h9zZedE2Y0YTGLW4y850QvsRrMsKCCan4d7kJCUio8xc "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter $_ .unique( # find the unique results (implicit method call on $_) :as( # use this code to compare *[1] # the second value (WhateverCode lambda) ) )[ # index into that *; # all in the top level 0 # only the first value from each ] } ``` [Answer] ## C-Sharp, 63 bytes ``` object _(int[][]p)=>p.GroupBy(i=>i[1]).Select(g=>g.First()[0]); ``` Returns an enumerable of integers. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 25 bytes ``` #&@@#&@@@#~GatherBy~Last& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19ZzcEBhB2U69xBUkVOlXU@icUlav8DijLzSqKVFXTtFNKilWNjFdQU9B0UqqurDXUUjGp1FKqNEbRBLYhRbQ4VMQeJQGhDiIwJVARGW4JkgLQpSAdYBUzEEsQwgMqZgmgDHQXj2tra/wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 81 bytes ``` |a,b|b.zip(a).collect::<std::collections::HashMap<_,_>>().into_iter().map(|v|v.1) ``` [Try it online!](https://tio.run/##VY4xD4IwEIV3fsXB1CaViG4H4iqDq4sxTcE2NoFCoDII/HasRBO83HAv7@7d1z47OysDldCGUBg8cFVKCwpBGcIZdPaO2MsCMTO2zqxsE55S2KTA4TCPguVjHr50QwQNi7osZWERk@XqK3VtOsST6B5n0SSc8TQlNNQujWsX5@ZKNGTsxz6M6PwBiBeMpnU7pfFJMOBxChgo4jj865ZBxGB3W0cw@Fl713/WGusii2R5T2Nvmt8 "Rust – Try It Online") Takes two iterators, returns an iterator. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 12 bytes ``` {%$_.values} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pVJV6vLDGnNLW49n9xIkhYI9pQwdZOwUhHwQhEG@sogPkmsZrWXDAVYBlDhAoDMI2swkDHRAeEDXUsdYx0TGM1/wMA "Perl 6 – Try It Online") Coerces the given list to a Hash and then returns the values. This works on both a list of pairs, and a list of `key, value, key, value...`. ]
[Question] [ ## Challenge You must write a program which takes a string and a flag as input and performs one of the following functions. ## Input If your language does not support command line arguments, you may take the arguments as input via STDIN. The flag will be two characters: a dash and an ASCII character such as `-d` or `-c`. ## Functions The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function. ### Counting: `-c` This counts the number of duplicate lines in the input file. For example, if the input is: ``` aa aa bb bb bb xx ``` The output will be: ``` 2 aa 3 bb 1 xx ``` Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines. ### Duplication: `-d` This shows which lines are duplicates. For example, using the above example string (`aa\naa\nbb\nbb\nbb\nxx`), the output would be: ``` aa bb ``` Because these are lines which have been duplicated. You should only output each line once. ### Duplication: `-D` This is almost the same as `-d` except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be: ``` aa aa bb bb bb ``` Because aa occurs twice and bb occurs three times. ### Unique: `-u` Similar to above except it only prints unique lines. For example, using the example file, the output will be: ``` xx ``` Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once. ## Example Note that although the input string will not always be sorted, ***the output must be sorted alphabetically***. For example, for the following input: ``` hello world apple pie zebra dog hello world apple pie apple pie apple pie ``` The output for each of the flags would be: `-c` ``` 4 apple pie 1 dog 2 hello world 1 zebra ``` `-d` ``` apple pie hello world ``` `-D` ``` apple pie apple pie apple pie apple pie hello world hello world ``` `-u` ``` dog zebra ``` ## Rules Your programs must not use the UNIX program uniq as, frankly, that is plain cheating. All output should be to STDOUT. The file will only ever contain lowercase, alphabetical characters, newlines and spaces: ``` abcdefghijklmnopqrstuvwxyz ``` The output should be sorted alphabetically. In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX. As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string. ## Winning As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. [Answer] ## GNU sed, ~~496~~ 485 + 2(rn flags) = 487 bytes ``` 1h;1b;$bb;2{:r;$!N;$!br;s/.*/echo "&"|sort/e};:b;x;/[dD]/bd;/c/bc;/u/!b;x;s/^/\n/ s/(\n.*)\1+//g;s/\n//p;b;:d;x;/^(.*)\n\1/!D;:l;x;/D/{x;P;x};x;s/^[^\n]*\n// /^(.*)\n\1/bl;P;D;:c;s/$/#/;G;x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/ /([^:\n]*)\n\1$/{s/\n[^\n]*$//;:i;s/9(@*:)/@\1/;ti;s/8(@*:)/9\1/;s/7(@*:)/8\1/ s/6(@*:)/7\1/;s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/;s/2(@*:)/3\1/;s/1(@*:)/2\1/ s/0(@*:)/1\1/;s/@+:/1&/;y/@/0/;bc};s/:/ /;s/[^\n]*$/1:&/;bc;:p;x;s/...//;s/..$//;s/:/ /gp ``` The code size is not going to compete, but it was fun emulating the `uniq` command. I wanted to add a simple [selection sort](https://en.wikipedia.org/wiki/Selection_sort "selection sort") to get rid of the `sort` call, thus solving it in pure sed only, but the code got too long already. The input is read entirely from STDIN, with the flag expected on the first line. **Run:** ``` (echo "-c";cat input_file)|sed -rnf uniq_emulator.sed ``` **Output:** ``` 4 apple pie 1 dog 2 hello world 1 zebra ``` **Initially submitted code and explanation:** (sections are separated by an extra newline) ``` # The main # store the flag in hold space and start next cycle 1h;1b # usually a cycle starts with each line read, but I also start it manually, #so I need to skip some lines that should run only once $bb 2{ # read the entire input into pattern space :r;$!N;$!br # executes a shell call to sort the pattern space s/.*/echo "&"|sort/e } # based on the flag, the appropriate jumps to "functions" are made :b;x;/[dD]/bd;/c/bc;/u/!b # Unique: -u # all duplicate lines are deleted and what remains is printed x;s/^/\n/;s/(\n.*)\1+//g s/\n//p;b # Duplication: -d and -D # if the first 2 lines are different, delete the first and start new cycle :d;x;/^(.*)\n\1/!D :l # if -D, print the first duplicate line x;/D/{x;P;x};x # otherwise (-d), delete the first duplicate line s/^[^\n]*\n// # loop condition, go back to :l if the first 2 lines are duplicate /^(.*)\n\1/bl # print only the first line and start a new cycle P;D # Counting: -c # in order to count line occurrences, I simulate reading the input again # In a loop I append all pattern space to hold space, delete first line of #pattern space and from hold space all lines except the first one appended. :c;s/$/#/;G x;/^$/bp;s/[^\n]*\n?//;x;s/#(\n[^\n]*).*/\1/ # if the new line "read" is the same as the previous one, increment the #counter of that line (format is "counter:line"), delete and go back to :c /([^:\n]*)\n\1$/{s/\n[^\n]*$//;bi;:I;bc} # otherwise, stop the counter for the previous line, add a counter for the #current one and go back to :c s/:/ /;s/[^\n]*$/1:&/;bc # when the loop ends, the hold space with all counts is printed :p;x;s/...//;s/..$//;s/:/ /gp # Increment function that works by manually updating the changing digit(s) :i;s/9(@*:)/@\1/;ti s/8(@*:)/9\1/;s/7(@*:)/8\1/;s/6(@*:)/7\1/ s/5(@*:)/6\1/;s/4(@*:)/5\1/;s/3(@*:)/4\1/ s/2(@*:)/3\1/;s/1(@*:)/2\1/;s/0(@*:)/1\1/ s/@+:/1&/;y/@/0/;tI ``` [Answer] ## Perl, 92 + 4 (`-sn` flags) = 96 bytes ``` $h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h ``` This code needs to be in a file to run. And it needs `-sn` flags, as well as `-M5.010` (free). For instance : ``` $ cat input.txt hello world apple pie zebra dog hello world apple pie apple pie apple pie $ cat prog.pl $h{$_}++}{$v=$h{$_},print$c?"$v $_":($D||$d)&&$v>1||$u&&$v<2?$_ x($d?1:$v):''for sort keys%h $ perl -M5.010 -sn prog.pl -c < input.txt 4 apple pie 1 dog 2 hello world 1 zebra ``` [Answer] # R, 128 bytes Using a different method than @Billywob and implemented as a unnamed function ``` function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep=' ')} ``` Ungolfed ``` function(s,o){ R=rle(sort(s)); # do the run length encoding for the sorted input cat( # output to STDOUT switch(o # switch on option to provide output lines ,'-d'=R$v[R$l>1] # RLE values with length > 1 ,'-D'=s[s%in%R$v[R$l>1]] # string values in RLE values with length > 1 ,'-c'=paste(R$l,R$v) # RLE length and values pasted together ,'-u'=R$v[R$l<2] # RLE values with length < 2, eg 1 ) ,sep=' ' # set separator to carriage return ) } ``` Test Run ``` function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep=' ')} > s = c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie") > f = function(s,o){R=rle(sort(s));cat(switch(o,'-d'=R$v[R$l>1],'-D'=s[s%in%R$v[R$l>1]],'-c'=paste(R$l,R$v),'-u'=R$v[R$l<2]),sep=' ')} > f(s, "-c") 4 apple pie 1 dog 2 hello world 1 zebra > f(s, "-d") apple pie hello world > f(s, "-D") hello world apple pie hello world apple pie apple pie apple pie > f(s, "-u") dog zebra > ``` [Answer] ## R, 179 bytes ``` f=function(s,o){s=sort(s);n="\n";z=cat;for(i in unique(s)){v=sum(s%in%i);if(v>1&o=="-d")z(i,n);if(o=="-c")z(v, i,n);if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="");if(o=="-u"&v<2)z(i,n)}} ``` ### Input Input is assumed to be an "R-vector" of strings (inspired by @Arnauld's JS array input, see below) and a string containing the type of function e.g. `-d`. ### Example An example of how to execute the function where I pre-define the vector of strings (not necessary). ``` strings <- c("hello world", "apple pie", "zebra", "dog", "hello world", "apple pie", "apple pie", "apple pie") f(strings,"-c") f(strings, "-d") f(strings,"-D") f(strings, "-u") ``` ### Ungolfed ``` f=function(s,o){ s=sort(s) # sort vector alphabetically n="\n" # generate string for newline (used 5x times) z=cat # generate alias for cat (used 4x times) for(i in unique(s)){ # for each unique string of vector v=sum(s%in%i) # count number of occurences if(o=="-d"&v>1)z(i,n) # if occurences >1 & "-d": print each unique string if(o=="-D"&v>1)z(rep(c(i,n),v),n,sep="") # repeat string #occurences and then print if(o=="-u"&v<2)z(i,n) # if occurences <2 & "-u": print each uniquely occuring string if(o=="-c")z(v,i,n) # if "-c": print number of occurence and each unique string } } ``` I'm sure this can be golfed further by shortening the control flow statements but couldn't figure out a smart way to do it yet. [Answer] # [JavaScript (V8)](https://v8.dev/), ~~170 164~~ 140 bytes Expects `(array_of_strings)(flag_string)`. Prints the output. ``` a=>c=>[...new Set(a)].sort().map(k=>(a.map(v=>n+=v==k,n=0),o={c:n+' '+k,d:n>1&&k,D:n>1&&Array(n).fill(k).join` `,u:n<2&&k}[c[1]])&&print(o)) ``` [Try it online!](https://tio.run/##fY7fSsMwFMbv9xSHXHQJzYLzSjpPQJhP4GUpLKZJ1zUmIe06dOzZa6s3IujV@X1/4HwnNapepzYOm/FhsjgplBplKYTw5gIvZqCKVaIPaaBMvKlIO5RUfdGI0uc4Inbc4x3jAa@68Pka1nnH68LLbZZ1fP8NTympd@qZsK1ztGPiFFp/WB34ufCP93PxVupyW1Usy2Jq/UADY9Nu2UF0vT@TStiQnpU@UutUAyjhugLQwffBGeFCQ8mGQA5LynZzZGkJ5GicC3AJydWEA1ExOgOxNYv4MK9JLVCHZjn/df8QULHfb38umo0bmz4B "JavaScript (V8) – Try It Online") [Answer] # Bash(coreutils, grep), 265 bytes ``` IFS=$'\n' for l in `sort -u $1`;do r=$r$(grep -c "$l" $1)" $l\n" done case $2 in -c)printf $r;;-d)printf $r|grep -v "1.*"|cut -d' ' -f2-;;-D)s=$(sort $1) for l in `sh $0 $1 -u`;do s=$(grep -v "$l"<<<"$s") done echo "$s";;-u)printf $r|grep "1.*"|cut -d' ' -f2-;;esac ``` **Usage** ``` $ sh unique.bash input -D apple pie apple pie apple pie apple pie hello world hello world $ sh unique.bash input -c 4 apple pie 1 dog 2 hello world 1 zebra $ sh unique.bash input -u dog zebra $ sh unique.bash input -d apple pie hello world ``` **Explanation** * Constructs `$r` which is the output of `-c`. To construct it, it uses `sort -u` which sorts the input file and returns only unique results (I know, somewhat cheat but it wasn't specified in the rules. Feel free to ignore the answer if you don't like it :-). Also, it uses `grep -c` to count the occurrences of each word. * For `-d` it gets the output of `-c` and with grep it prints everything that does not start with 1. With `cut` it ignores the first column (number of occurrences). * For `-u` it does exactly the same as `-d` except from `grep`, where it selects everything that starts with 1. * For `-D` it get the sorted input and remove all the words that are printed with `-u` in a for loop by using `grep -v` again. [Answer] # [jq](https://stedolan.github.io/jq/) -r, 115 bytes Takes an array of strings and the flag as separate string. ``` group_by(.)|map(select(has(1)))as$m|{c:map("\(length) \(.[0])"),d:[$m[][0]],D:[$m[][]],u:[.-$m|.[][]]}[input[1:]][] ``` Example and explanation: ``` echo '["aa", "aa", "bb", "bb", "bb", "xx"] "-c"' | jq -r ' group_by(.) | # sort and group by item map(select(has(1))) as $m | # store the slice of non-uniques { # create a lookup object c: map("\(length) \(.[0])"), # map to length and one item d: [ $m [][0]], # take one of each from the slice D: [ $m [][ ]], # take all of them from the slice u: [. - $m | .[][ ]] # subtract the slice from the input } # and take all of them [input[1:]] # lookup by the 2nd char of flag [] # iterate and output ' 2 aa 3 bb 1 xx ``` [Try it online!](https://tio.run/##vY1BDoIwEEX3nqKZsGgT2siWNbcojSnQAKbQWmiMile3FuJSl7KZeS9/Jv98CaF1xttTdcOMLIO0eFJa1TPu5IQzQoickmF51PkaQYm1Gtu5I6jEjB8FAZI2OU8GLqKJtPhwRJ9zRuMr2/TJ@9H6mWe5iBoCh05pbdDVON1ACtJarZDtVeS7qpyMuzFtnL/vvrNAQGs4cKCUbuJX@Wdbs2tbsWubh5exc2/GKVD3Bg "jq – Try It Online") [Answer] # [J](http://jsoftware.com/), 84 bytes ``` ('cDdu'i.1{[)>@{[:(~.@]((],' ',[)&":"p.;D;~.@D;[-.D=.#~]*1<])1#.=@])@/:~];._1@(LF,]) ``` [Try it online!](https://tio.run/##dY5Ni8IwEIbv@RVDBSdZ2nFzTe0S2ODJk9cQpLapHwRarLKg2L9eraIX18PAw/My886ujwgryBQgxPAN6jYJwe9iPus5FqY84pbk2YoffbaKd6Qd5y5GwNiKcaSihlKT3rRJbUImo1HnvuTUCTmiTDuhJ6pzKS2l5vNZ7EQvWCuHuot6tLGND6GGv3ofSpY3TfDQbD07@dU@Z2W9/pD/R4IdfHsYjvtiU2tEsA@qnsCxCvla3Z9ngwFMCoT7Wiufpnwz5s0cX6a/Ag "J – Try It Online") A bit cumbersome, but I've progressively golfed it down from about 100b. I expect more golfing opportunities may be had, but I'm not quite sure where at this point. ## Explanation This answer can be divided into a bunch of components. Here's an easier to read version of the above ([Try it online!](https://tio.run/##dVHLboMwELzvV6wSqYYqoeEKjcQh6ql/gCxEYUvcujbFWOlDza9TmyQkUlohS@uZndnx8jIMDfWFUDV94DpBVm1qy1BEGOM35iCFIuMJnkZFnAWPD7hAHoLRXe/hu2QPb1b2oqht64H5HjneOvU9ctBKfhZaVeSZHJcRTr1ghGoknWT7KDtTlbaqL6Qw44iAu5HMfQvMw5tZMotxdWgZg8U4j3CdcbBKvFs6mnEoldlRN7kc2eDCOz2ncfVFnhSn4CEeJo3uhfP0XueNtaJ6xYtJmd9LNi5tMLHv/Ulwhe7AlqTUuNOdrKFsW0lOTPBFT10JtW7@4f@qQoCeDq@iaqszxtxux2oKebwH7FmWjfurizwEjyBbVgxHtYlPSH2FbK4QOyHDLw)) (technically functions *slightly* differently since we're not actually doing `answer_list@sort`, but rather, `(answer_list@/:)~`, which is happens to be the same thing.) ``` get_index =: 'cDdu' i. 1 { [ lines =: ];._1@(LF , ]) sort =: /:~ multi_dup =: #~ ] * 1 < ] only_once =: [ -. multi_dup single_dup =: ~.@multi_dup count_list =: (] , ' ' , [)&":"1 0 counts =: 1 #. =@] unique =: ~.@] answer_list =: unique (count_list ; multi_dup ; single_dup ; only_once) counts uniq_ans =: get_index pick answer_list@sort@lines ``` [Answer] # Python 2, 115 bytes ``` f,a=input() f=ord(f[1])%5 for w in sorted(set(a)):C=a.count(w);exec"print'%d '%C*(f>3)+w;"*[C>1,0,C<2,(C>1)*C,1][f] ``` Example: ``` golf % python2.7 uniq.py <<<'["-c",["hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"]]' 4 apple pie 1 dog 2 hello world 1 zebra ``` [Answer] ## Lua, 270 Bytes Well, that ended being way longer than I though it would, but I'm happy with it. Takes in a filename via command-line and forms two array while reading it's content (`t={line, repetitions}` and `T={index, line}`). Sorts `T` then outputs via STDOUT depending on the flag. ``` f,m=...io.input(f)t={}T={}for l in io.lines()do l=l.."\n"t[l]=t[l]and t[l]+1or 1T[#T+1]=t[l]<2 and l or nil end table.sort(T)o=""for i=1,#T do k=T[i]v=t[k]o=o..(m=="-c"and v.." "..k or m=="-D"and k:rep(v)or m=="-d"and v>1 and k or m=="-u" and v<2 and k or'')end print(o) ``` ### Explanation ``` f,m=... -- shorthands for the inputs io.input(f) -- set the file f as the current input stream t={} -- set the array linking a line to its number of occurrence T={} -- set the array containing each line once for sorting purpose for l in io.lines() -- iterate over each line in the file do l=l.."\n" -- add a newline at the end of it t[l]=t[l] -- if it's not the first time we see this line and t[l]+1 -- increment its number of occurence or 1 -- else set it to 1 occurence T[#T+1]=t[l]<2 and l or nil-- and set it in our listing end table.sort(T) -- sort the list of line o="" -- initialise the output to an empty string for i=1,#T -- iterate over each entry in T do k=T[i] -- shorthand for the line's string v=t[k] -- shorthand for its number of occurence -- the following nested ternaries are basically a chained if/elseif o=o.. -- at the end of our current output string (m=="-c" -- if the flag is -c(ount) and v.." "..k -- add the number of occurrence and the corresponding string or m=="-D" -- if the flag is -D(uplicates) and k:rep(v) -- add v times the line or m=="-d" and v>1 -- if the flag is -d(uplicates) and it has appeared >2 times and k -- add this line or m=="-u" and v<2 -- if the flag is -u(niq) and it has appeared only once and k -- add this line or '') -- if neither of these cases are true, had an empty string end print(o) -- output what we formatted previously :) ``` [Answer] # Java, 19(import java.util.\*;) + 315 = 334 bytes ``` String f(String[]r,String q){TreeMap<String,Integer>m=new TreeMap();for(String s:r)m.put(s,m.get(s)==null?1:m.get(s)+1);int a=q.charAt(1),v;String o="",k;for(Map.Entry<String,Integer>e:m.entrySet()){v=e.getValue();k=e.getKey()+"\n";while(68==a&&v-->1)o+=k;o+='u'==a&&v<2||'d'==a&&v>1?k:99==a?v+" "+k:"";}return o;}} ``` **Usage** ``` String[] input = {"hello world","apple pie","zebra","dog","hello world","apple pie","apple pie","apple pie"}; System.out.println("-c"); System.out.println(f(input,"-c")); System.out.println("-d"); System.out.println(f(input,"-d")); System.out.println("-D"); System.out.println(f(input,"-D")); System.out.println("-u"); System.out.println(f(input,"-u")); ``` **Output** ``` -c 4 apple pie 1 dog 2 hello world 1 zebra -d apple pie hello world -D apple pie apple pie apple pie hello world -u dog zebra ``` **Explanation** A `TreeMap<String, Integer>` is used to store pairs of words and how many times they were repeated. The TreeMap is sorted so no extra call to sort it is required. Ternary operator is used to construct the output string regarding the input argument. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 44 bytes ``` ⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigb1S4oChJ3TEizt2aOKAoSd0xIvCrDt2aOKJrCd0xIs7xpvDtyR34bqLO2ZX4oCbx43in4c/dOG4n2kkc8SKJOKAoFfigYsiLCIiLCJcIi1EXCJcbltcImFhXCIsIFwiYWFcIiwgXCJiYlwiLCBcImJiXCIsIFwiYmJcIiwgXCJ4eFwiXSJd) A fun little answer that gets to use a list of lambdas. Takes input as `flag`, `list of lines`. ## Explained ``` ⁽R‡'tċ;vh‡'tċ¬;vh≬'tċ;ƛ÷$wẋ;fW‛Ǎ⟇?tḟi$sĊ$†W⁋ W # Wrap the stack into a single list: ⁽R # A function that reverses each item in a list ‡'tċ;vh # A function that keeps only non-unique items ‡'tċ¬;vh # A function that keeps only unique items ≬'tċ;ƛ÷$wẋ;f # A function that repeats non-unique items by their count ‛Ǎ⟇?tḟi # Get the function at index "cdu".find(input[-1]) $sĊ$† # Call that function on a list of the counts of each item in the input, sorted alphabetically W⁋ # Wrap into a single list (needed because of a bug) and join on newlines. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` C|ÅγøíIÅγ2@ÏIDÅγÏDŠK)ćè» ``` 05AB1E doesn't support custom system arguments, so it takes the inputs through STDIN. The first input-line is the flag, and every other input-line is the input-file. [Try it online](https://tio.run/##yy9OTMpM/f/fueZw67nNh3ccXusJYhg5HO73dAEL9bscXeCteaT98IpDu///103mSkwEoaQkKKqoAAA) or [verify all four flags](https://tio.run/##yy9OTMpM/R9aExNRpuSZV1BaopuWk5hupaBkX6nDpeRfWgIUAvJ0Kv87ex5uPbf58I7Da8EMI4fD/Z4uYKF@l6MLvDWPtB9ecWj3f51D2@z/RyvpJivpKOmmgAgXEFGqFMuVmAhCSUlQVFEBAA). **Explanation:** ``` C # Convert the first (implicit) input-flag from a binary-string to an integer† | # Get all other input-lines as a list of strings Åγ # Run-length encode it, and push the list of values and counts separated to # the stack ø # Pair the values and lengths together í # Reverse each from [value,count] to [count,value] I # Push the list of input-lines again Åγ # Run-length encode it again 2@ # Check for each count if it's >=2 Ï # Only leave the values at the truthy indices I # Push the list of input-lines yet again D # Duplicate it Åγ # Run-length encode it a third time Ï # Only leave the values at the truthy (==1) indices D # Duplicate this list of unique items Š # Triple-swap the input,unique,unique lines to unique,input,unique lines K # Remove the unique lines from the input ) # Wrap the entire stack into a list ć # Extract head; pop list and push remainder-list and first item separately to # the stack è # Use that C(input-flag) to 0-based modular index it into the list » # Join each inner list by spaces first (for the list of [count,value] pairs), # and then join each string by newlines # (after which the result is output implicitly) ``` † `C` on strings basically gets the index of each character in the string `0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzǝʒαβγδεζηθвимнт ΓΔΘιΣΩ≠∊∍∞₁₂₃₄₅₆ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~Ƶ€Λ‚ƒ„…†‡ˆ‰Š‹ŒĆŽƶĀ‘’“”–—˜™š›œćžŸā¡¢£¤¥¦§¨©ª«¬λ®¯°±²³\nµ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ•`, and then converts this list of indices to a base-2 integer: | Flag | `C` | 0-based modular index | | --- | --- | --- | | `"-c"` | 252 | 0 | | `"-d"` | 253 | 1 | | `"-D"` | 270 | 2 | | `"-u"` | 227 | 3 | [Answer] # Groovy (185 Bytes) ## Golf'd: ``` x={m,l->u=[];u.addAll(l);u.unique();c=u.collect{v->[v,l.count{it==v}]};D=c.collect{a,b->if (b>1){(1..b).collect{a}}};D.remove(null);m=='d'?D.collect{it.unique()}:['D':D,'c':c,'u':u][m]} ``` <https://groovyconsole.appspot.com/edit/5173563388592128> ## Ungolf'd (Kinda): ``` x = { m,l-> u=[]; u.addAll(l); u.unique(); c = u.collect { v-> [v, l.count {it==v}] } D = c.collect { a,b-> if (b>1) { (1..b).collect{a} } } D.remove(null) m == 'd' ? D.collect{it.unique()} : ['D':D,'c':c,'u':u][m] } ``` ## Output * > > **u Results** aa bb xx > > > * > > **c Results** [aa, 3] [bb, 2] [xx, 1] > > > * > > **D Results** [aa, aa, aa] [bb, bb] > > > * > > **d Results** [aa] [bb] > > > ]
[Question] [ **This question already has answers here**: [Simplify a fraction](/questions/35587/simplify-a-fraction) (20 answers) Closed 8 years ago. **Note: as this question has been marked as a duplicate, I have accepted an answer. However, I will still check this question if users can find a shorter way of doing it, and accept that answer.** Given two numbers (which are multiples of `0.5`) representing `heads-percentage` and `tails-percentage` from a series of coin-flipping, output the *minimum* amounts of heads and tails to produce percentages such as those. Input and output can be in any form. However, output must be in a readable format (Good examples are `x y`, `[x y]`, etc). Examples: * Input: `25 75` (25% heads, 75% tails) Output: `1 3` (an output of `25 75` is invalid since that is not the *minimum* amounts of heads and tails to produce those percentages) * Input: `30 70` (30% heads, 70% tails) Output: `3 7` * Input: `99.5 0.5` (99.5% heads, 0.5% tails) Output: `199 1` You may assume that there will always be a digit before and after a decimal point in an input (no `.5`s or `15.`s). You may also assume the input adds up to 100%. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins! [Answer] # Dyalog APL, 3 bytes ``` ,÷∨ ``` This is a dyadic function train that accepts the percentages as left and right arguments: ``` ┌─┼─┐ , ÷ ∨ ``` It is equivalent to the following, train-less function: ``` {(⍺,⍵)÷⍺∨⍵} ``` Try it online on [TryAPL](http://tryapl.org/?a=99.5%28%2C%F7%u2228%290.5&run). ### How it works ``` ∨ Compute the GCD of both arguments. , Concatenate both arguments. ÷ Divide the latter by the former. ``` [Answer] ## Python 2, 47 bytes ``` A,B=a,b=input() while b:a,b=b,a%b print A/a,B/a ``` Takes input like `15,20` and prints the output like `3 4`. Performs the Euclidian algorithm to find the gcd, then scales the numbers by it. Fortunately, Python will happily compute `%` on fractions, so inputs like `0.5 99.5` behave just the same. More type-strict languages (cough, Haskell) aren't so lucky. [Answer] # J, 4 bytes ``` ,%+. ``` Explanation: ``` (x +. y) NB. GCD of the left and right inputs % NB. divided by (x, y) NB. a vector consisting of the inputs ``` [Try it online](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=99.5%20(%2C%25%2B.)%200.5) [Answer] # CJam, ~~25~~ 14 bytes ``` {_~{_@\%}h;f/} ``` This is an unnamed function that pops a list from the stack and leaves one in return. Like @xnor's answer, it uses the Euclidean algorithm to find the GCD, then divides the list elements by it. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%0A%20%20%7B_~%7B_%40%5C%25%7Dh%3Bf%2F%7D%0A~p&input=%5B99.5%200.5%5D). ### How it works ``` _ Push a copy of the input array. ~ Dump its elements on the stack. { }h Do: _ Push a copy of the topmost integer. @ Rotate the bottom-most integer on top of it. \ Swap them. % Calculate the residue of their division. While the residue is positive, repeat the loop. ; Discard the last residue (0). This leaves the GCD on the stack. f/ Divide the elements of the input array by their GCD. ``` [Answer] # Pyth, 12 bytes ``` J/R.5Q/RiFJJ ``` Like @xnor's answer, this divides each list item by their GCD. Pyth has the GCD as a built-in, but it doesn't work for floats out of the box. [Try it online.](https://pyth.herokuapp.com/?code=J%2FR.5Q%2FRiFJJ&test_suite=1&test_suite_input=%5B25%2C+75%5D%0A%5B30%2C+70%5D%0A%5B99.5%2C+0.5%5D&debug=0) ### How it works ``` (implicit) Save the evaluated input in Q. /R.5Q Divide each element of Q by 0.5. This transforms the array's floats into integers. J Save the result in J. iFJ Compute the GCD of the elements of J. /R J Divide the elements of J by their GCD. ``` [Answer] # APL, 20 bytes ``` {⍺⍵÷⍺{0<⍵:⍵∇⍵|⍺⋄⍺}⍵} ``` This creates an unnamed dyadic function that accepts the inputs on the left and right and returns an array. Unlike Dennis' super slick [Dyalog solution](https://codegolf.stackexchange.com/a/62065/20469), this works with other versions of APL because it doesn't use trains and it doesn't assume that GCD (`∨`) works for floats. Explanation: ``` ⍺{0<⍵:⍵∇⍵|⍺⋄⍺}⍵} ⍝ Compute the GCD of the inputs using the Euclidean algorithm {⍺⍵÷ ⍝ Divide the inputs by their GCD ``` [Try all test cases online](http://tryapl.org/?a=f%u2190%7B%u237A%u2375%F7%u237A%7B0%3C%u2375%3A%u2375%u2207%u2375%7C%u237A%u22C4%u237A%7D%u2375%7D%u22C425%20f%2075%u22C430%20f%2070%u22C499.5%20f%200.5&run) [Answer] # Mathematica, 21 bytes ``` #/GCD@@Rationalize@#& ``` Another program with the same byte count is ``` #/GCD@@(Floor[2#]/2)& ``` Mma has never supported FP well... [Answer] # TI-BASIC, ~~31~~ ~~22~~ 24 bytes Forgot to count new lines before... ``` Prompt A,B gcd(2A,2B➡C Disp 2A/C,2B/C ``` This was done in the middle of math class... [Answer] # Common Lisp, ~~168~~ 94 ``` (let((x(floor(*(read)2)))(y(floor(*(read)2))))(format t "~A ~A"(/ x(gcd x y))(/ y(gcd y x)))) ``` I missed the original bit about everything being a multiple of 0.5 (thanks xnor!), so this is a good bit shorter than my first go (Gotta' love that almost a third of those bytes are parentheses.) ]
[Question] [ **This question already has answers here**: [Prime Factorization - but on the exponents too](/questions/226691/prime-factorization-but-on-the-exponents-too) (7 answers) Closed 2 years ago. Your job is to take the prime factors of a number taken from input (omitting any exponents equal to 1) then take the prime factors of all of the exponents, and so on, until no composite numbers remain; and then output the result. To make what I'm asking slightly clearer, here's a javascript program that does it, but, at 782 bytes, it's not very well golfed yet: ``` var primes=[2,3]; function nextPrime(){ var n=2; while(isAMultipleOfAKnownPrime(n)){n++} primes.push(n); } function isAKnownPrime(n){return primes.indexOf(n)!=-1}; function isAMultipleOfAKnownPrime(n){ for(var i=0;i<primes.length;i++)if(n%primes[i]==0)return true; return false; } function primeFactorize(n){ while(primes[primes.length-1]<n)nextPrime(); if(isAKnownPrime(n)||n==1)return n; var q=[];while(q.length<=n)q.push(0); while(n!=1){ for(var i=0;i<primes.length;i++){ var x=primes[i]; if(n%x==0){q[x]++;n/=x} } } var o=""; for(var i=2;i<q.length;i++){ if(q[i]){if(o)o+="x";o+=i;if(q[i]>1){o+="^("+primeFactorize(q[i])+")"}} } return o; } alert(primeFactorize(+prompt())); ``` You are required to make order of operations as clear as possible, and sort the prime factors in ascending order on each level. You get a -50 byte bonus if you produce the output as formatted mathprint or valid latex code. [Answer] # Pyth, 27 - 50 = -23 bytes ``` Lj\*m+ed?+\^jyhd`HthdkrPb8 ``` This defines a recursive function `y`. Try it online: [Demonstration](https://pyth.herokuapp.com/?code=Lj%5C*m%2Bed%3F%2B%5C%5Ejyhd%60HthdkrPb8%0Ay10%0Ay120%0Ay16384%0Ay66430125&debug=0) The output is valid LaTeX code, so I claim the bonus. The call `y66430125` returns the string `3^{2^{2}*3}*5^{3}`, which renders to ![pic_small](https://i.stack.imgur.com/VNiIt.png) Quite proud for finding a way to print the curly brackets without using curly brackets in my code. # Explanation: ``` L define a function y(b): return ... Pb prime factorization of b r 8 run-length-encoded, gives pairs of (exponent, prime) m map each pair d (exponent, prime) to: ed prime + + yhd recursive call j `H join repr(H) by ^ H is preinitialized with an empty dictionary so the repr(H) gives the string "{}" and join inserts the prime-factorization of the exponent between the chars of "{}" +\^ add "^" at the beginning ? thd if exponent - 1 != 0 else k "" (empty string) j\* join by "*" ``` [Answer] # CJam, ~~32~~ ~~31~~ ~~29~~ ~~27~~ 25 - 50 = -25 bytes *7 bytes saved by Dennis.* Woooo, Dennis reduced this by an amazing seven bytes and managed to beat Pyth! ``` q~S2*{mF{~'^'{@j'}'*}/;}j ``` [Test it here.](http://cjam.aditsu.net/#code=q~S2*%7BmF%7B~'%5E'%7B%40j'%7D'*%7D%2F%3B%7Dj&input=66430125) ## Explanation ``` q~ e# Read and eval input. S2* e# Push the string " ". The second space will be our e# memoised result for input 1. This way, 1-exponents become e# ^{ } later which do not affect the rendered output of the e# generated LaTeX. { }j e# Initialise a recursion with the above base case. mF e# Compute prime factorisation as list of pairs. { }/ e# For each pair... ~'^'{@ e# Unwrap the pair and put a '^' and a '{' in the middle. j e# Recursively run the outer block on the exponent. '}'* e# Push a '}' and a '*' character. ; e# Discard the last '*'. ``` All those stack contents will be printed automatically back-to-back at the end of the program. [Answer] # Pyth - ~~39~~ ~~34~~ ~~32~~ 28 bytes Thanks [Jakube](https://codegolf.stackexchange.com/users/29577/jakube) Defines a function `y` which takes an integer: ``` L?j\xm+ed+"^("+yhd\)rPb8tPbb ``` Explanation: ``` L define y(b): return j\x "x".join( m map(lambda d: +ed+"^("+yhd\) d[1] + "^(" + y(d[0]) + ")", rPb8 tally(prime_factors(b)))) ? tPb if len(prime_factors(b)) != 1 else b b ``` If `^(1)` isn't allowed I have to use 33 bytes: ``` L?j\xm+ed?+"^("+yhd\)thdkrPb8tPbb ``` [Answer] # Mathematica, ~~106~~ ~~102~~ 101 - 50 = 51 bytes ``` If[PrimeQ@#,#,(a=CenterDot)@@{b,c}~Function~If[c<2,b,b~Superscript~#0@c]@@@FactorInteger@#/.a@b_:>b]& ``` Formats as nested exponents with dot multiplication. Unicode representations of example input and output: * `10` → `2 · 5` * `120` → `2³ · 3 · 5` * `16384` → `2²˙⁷` [Answer] # Bash + coreutils + bsdgames, 117 - 50 = 67 ``` f()(factor $1|tr \ \\n|sed 1d|uniq -c|while read e m;do ((e>1))&&m+=^{`f $e`} printf {$m} done) f $1|sed s/}{/}\*{/g ``` ### Output ``` $ ./recprimefac.sh 2985984 {2^{{2^{{2}}}*{3}}}*{3^{{2}*{3}}} $ $ ``` I'm claiming the -50 bonus, because this output is LaTeX formatted and with a tool like <http://www.sciweavers.org/free-online-latex-equation-editor> renders to: ![enter image description here](https://i.stack.imgur.com/L27aw.png) Let me know if this is not acceptable. [Answer] # [Clip](https://esolangs.org/wiki/Clip), ~~36~~ 33 ``` jm[z.y(z?()z{'^'(M)z')`]L]}qfnx"* ``` ## Explanation ``` qfnx .- Prime factors of the input, with exponents -. m[z } .- For each factor z... -. .y(z .- The prime number -. ?()z L] .- If the exponent is 1, nothing -. { `] .- Otherwise, the following: -. M)z .- Apply the main function to the exponent... -. '^'( ') .- ...inside ^(..) -. j "* .- Join the factors with "*" -. ``` [Answer] # Javascript, 388-50=338 ``` l="length";function g(n){for(;m(++n););p.push(n)}function m(n){for(i=0;i<p[l];i++)if(n%p[i]==0)return 1;return 0}function f(n,x,q,o){while(p[p[l]-1]<n)g(2);if(p.indexOf(n)>=0||n==1)return n;q=[];while(q[l]<=n)q.push(0);for(i=0;i<p[l];i++){x=p[i];while(n%x==0){q[x]++;n/=x}}o="";for(i=2;i<q[l];i++)if(q[i]){if(o)o+="*";o+=i;if(q[i]>1){o+="^{"+f(q[i])+"}"}}return o}alert(f(+prompt(p=[2]))) ``` Since LaTeX code is now eligible for the bonus, I decided to include the requisite modifications as part of the golfing for this. It can probably still be golfed further though. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/12876/edit). Closed 7 years ago. [Improve this question](/posts/12876/edit) Find the shortest mirror quine in a language of your choice. A mirror quine is a quine whose source code is equal to the reverse of its own source code. **Note:** 1) Length of source code should be **atleast 2**. 2) Quines **not allowed are the one whose text can be echoed directly.** Example: Let L' be any language, then a quine with source code like ABBA or ABCBA is a mirror quine. [Answer] # HQ9+, 3 Characters Am I cheating? ``` +Q+ ``` [Answer] ## Perl, 53 characters Perl's multifaceted text-handling features once again prove useful for golfing. ``` ---BEGIN--- say$/.reverse$_=<<'';say yas;''<<=_$esrever./$yas ----END---- ``` Ignore the `BEGIN` and `END` markers; they're just there to keep the blank lines at the beginning and end from being suppressed from display. Yes, the source really does have two blank lines at the top and one blank line at the bottom. This apparent lack of symmetry may throw you at first, but that's just the nature of line breaks. What's really happening, of course, is that the source both begins and ends with two line break characters. [Answer] # Golfscript, 33 characters ``` ""~.{'""~.'print tnirp'.~""'}.~"" ``` Since every language uses parentheses of some form, I assert the "`(` mirrors to `(`" version of this challenge is impossible (under rule #2), and assume `(` mirrors to `)`. Additionally, this version provides more visual symmetry. If trailing whitespace is allowed, empty strings can be replaced with newlines (**29 characters**): ``` n~.{'n~.'print tnirp'.~n'}.~n ``` Proceeds as follows: * `""~.` pushes an empty string onto the stack, evaluates it and clones the input (empty string) * `{...}` is a block * `.~""` clones the block, evaluates one copy and pushes an empty string to the stack. That block: * `'""~.'` pushes the string `""~.` onto the stack * `print` outputs it directly and removes it from the stack * `tnirp` is an undefined symbol and does nothing * `'.~""'` pushes the string `.~""` onto the stack After the program finishes, the stack contents are printed: * the empty string (twice) * the main block, including delimiters * the program suffix as a string * another empty string [Answer] # Befunge 98 - ~~40~~ ~~35~~ 31 or 29 characters ``` #r:0g,:a3*`!e*j@j*e!`*3a:,g0:r# ``` Saved another 4 characters, for 31 total, and [complied with specs](https://codegolf.stackexchange.com/questions/12876/shortest-mirror-quine-challenge/15830#comment25439_12876 "It says that I need to not just reverse my first part; the whole thing has to be used"). Or, if the other code can just be filler (29): ``` >:0g,:e2*`!e*j@j*e!`*2e:,g0:> ``` --- # Old Version ``` #r:0g,:'#`3+ja+1r@r1+aj+3`#':,g0:r# ``` Saved 5 characters by using `'` to fetch the length of the program --- ``` #r:0g,:a4*`3+jb+1r@ @r1+bj+3`*4a:,g0:r# ``` Just a variation on a normal quine, but made into a palindrome. ``` :0g get the character at a location (counter, 0) , print it : take the counter a4* get 10 * 4 (40, length of program) ` compare them (0 if counter is less or equal, 1 if greater) 3+ add 3 j jump that amount (4 or 3) if 4: @ end program if 3: r head the other way (to the left) 1+ increment counter bj jump 11 chars (to beginning r (reverse direction again)) ``` [Answer] # [Mouse-2002](https://github.com/catb0t/mouse15), 73 bytes ``` 2 0&FOPEN (x.74<^2&F?' !'x.1+x:)36!'~'!63):x+1.x'!'? F&2^<75.x( NEPOF&0 2 ``` ]
[Question] [ This quite literally came to me in a dream. A common combination padlock design has letters on the dials so you can set the combination to a word. Unfortunately, I can't read, but I can count. Considering I am in a hurry, send the shortest path around the dials to open the 4 letter lock, given the current letters and the correct combination. The lock is set up so that the downward direction means going through the alphabet forwards `A->B->...Y->Z->A...` and upwards is in reverse `B->A->Z->Y....C->B->A->Z...` One turn refers to moving one letter in either direction. ## Input Any of * two strings `"Position", "Combo"` * a list of strings `["Position", "Combo"]` * A list of each character in the position, and a list for the combo `['p1', 'p2' 'p3', 'p4'], ['c1', 'c2', 'c3', 'c4']` The order of position and combo may be switched but the letters cannot be rearranged or interleaved in any way. ## Output A list of the number of turns and the directions in which to turn. The directions can be indicated however you want, but it must be consistent and it cannot be a number. It can be a single list of tuples, paired `[turns, direction]` or `[direction, turns]` or two lists, one of turns and one of directions as long as direction[a] corresponds to turns[a]. Positive/Negative for Up/Down works as well. You can use either direction for zero turns or equidistant letters ## Test cases: ``` [position, combo] -> [[turn[1], direction[1]], [t[2],d[2]], ...] ["NLWX", "GOLF"] -> [[7, up], [3, down], [11, up], [8, down]] ["CODE", "COOL"] -> [[0, up], [0, up], [11, down], [7, down]] ["AUGH", "NOPE"] -> [[13, up], [6, up], [9, down], [3, up]] ``` [Answer] # [Uiua 0.8.0](https://www.uiua.org/), 10 bytes [SBCS](http://tinyurl.com/SBCSUiua "SBCS for Uiua 0.8.0") ``` -13◿26+13- ``` [Try on Uiua Pad!](https://uiua.org/pad?src=0_7_1__RiDihpAgLTEz4pe_MjYrMTMtCgpGICJHT0xGIiAiTkxXWCIKIyMKRiAiQ09PTCIgIkNPREUiCiMjCkYgIk5PUEUiICJBVUdIIgojIwoiQUJDRCIgIlRFU1QiCgotICAgIyBzdWJ0cmFjdCB0aGUgc3RyaW5ncywgZ2V0IGRpc3RhbmNlcyBiZXR3ZWVuIGxldHRlcnMKKzEzICMgYWRkIDEzCuKXvzI2ICMgbW9kIDI2Ci0xMyAjIHN1YnRyYWN0IDEzCgojIwo=) Outputs positive and negative values. ## 18 bytes [SBCS](http://tinyurl.com/SBCSUiua "SBCS for Uiua 0.8.0") ``` +@a↥0⊃±⌵-13◿26+13- ``` [Try on Uiua Pad!](https://uiua.org/pad?src=0_7_1__RiDihpAgK0Bh4oalMOKKg8Kx4oy1LTEz4pe_MjYrMTMtCgpGICJOTFdYIiAiR09MRiIKIyMjCkYgIkNPREUiICJDT09MIgojIyMKCiJBQkNEIiAiVEVTVCIKCi0gICAjIHN1YnRyYWN0IHRoZSBzdHJpbmdzLCBnZXQgZGlzdGFuY2VzIGJldHdlZW4gbGV0dGVycworMTMgIyBhZGQgMTMK4pe_MjYgIyBtb2QgMjYKLTEzICMgc3VidHJhY3QgMTMK4oqDwrHijLUgIyBnZXQgdGhlIHNpZ25zIGFuZCBhYnNvbHV0ZSB2YWx1ZXMK4oalMCAgIyB0YWtlIHRoZSBtaW5pbXVtIHdpdGggMCwgdHVybnMgLTEgc2lnbnMgaW50byAwCitAYSAjIGFkZCAiYSIgdG8gdGhlIHNpZ25zLCBtYWtlcyB1cD0iYSIgYW5kIGRvd249ImIiCgojIyMK) Outputs 2 arrays, values and letters. Up is "a" and down is "b". ## Explanation ``` - # subtract the strings, get distances between letters +13 # add 13 ◿26 # mod 26 -13 # subtract 13 ⊃±⌵ # get the signs and absolute values ↥0 # take the minimum with 0, turns -1 signs into 0 +@a # add "a" to the signs, makes up="a" and down="b" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` O_/æ%13 ``` [Try it online!](https://tio.run/##y0rNyan8/98/Xv/wMlVD4//e1o8a5ijo2ik8aphrfbj94c59KlyH2x81rYn8/z@aK1rJzyc8QklHyd3fx00pVgco4Ozv4goUcPb394EIOIa6ewAF/PwDXJViuWIB "Jelly – Try It Online") A monadic link taking a list of two strings and returning a list of integers with negative integers as down and positive as up. ## Explanation ``` O | To codepoints _/ | Reduce by subtraction æ%13 | Symmetric mod 13 ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 51 bytes ``` x=>y=>x.map((c,i)=>parseInt(c+57+y[i],36)%97%26-13) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q7S1q5CLzexQEMjWSdT09auILGoONUzr0QjWdvUXLsyOjNWx9hMU9XSXNXITNfQWPN/cn5ecX5Oql5OfrpGmka0np6ekp9PeIRSrCaE4@7v4wbkaHJhUejs7@IKV@js7@8DUvgfAA "JavaScript (Node.js) – Try It Online") Output pos/neg # [JavaScript (Node.js)](https://nodejs.org), 68 bytes ``` x=>y=>x.map((c,i)=>[i=(c=parseInt(c+57+y[i],36)%97%26-13)<0,i?-c:c]) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q7S1q5CLzexQEMjWSdT09YuOtNWI9m2ILGoONUzr0QjWdvUXLsyOjNWx9hMU9XSXNXITNfQWNPGQCfTXjfZKjlW839yfl5xfk6qXk5@ukaaRrSenp6Sn094hFKsJoTj7u/jBuRocmFR6Ozv4gpX6Ozv7wNS@B8A "JavaScript (Node.js) – Try It Online") > > The directions can be indicated however you want, but it must be consistent and it cannot be a number. > > > I don't understand why but here `true` and `false` used [Answer] # [Scala 3](https://www.scala-lang.org/), ~~78~~ 75 bytes A port of [@l4m2's Javascript code](https://codegolf.stackexchange.com/a/269061/110802) in Scala. Saved 3 bytes thanks to the comment of @l4m2 --- ``` (x,y)=>x.zip(y).map{case(c,v)=>Integer.parseInt(s"${c}57${v}",36)%97%26-13} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY7LSsNAFIb3eYrD0MIMTAI19GIggtQLYjSLUhRCFuM4CSntJM6MtTHkSdx0Yzd9or6No8nK1c_5v8M539dBc7Zm_jFBriw_mJIoPY3Ll5XgBh5YIaFxAF5FBhkEgPHCqELmtAsSXizEW3InTUog_H43mTs73eMdrS3ZeZ9FhWvibVjVcKYF5nRre7stcqG8iikt7IA1GjS8HU8HzbZF1J-Q4fl0eDZxR37bnyyd3mFjhTBTuQ7gUilWJ51HSgJYysJA-GcLUNnWrCXOMHqMnp4RBXQbRzeIkP94Hl9d_-J5HEcdbp3-7X7f5Q8) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç`-13+₂%13- ``` Port of [*@Tbw*'s Uiua's answer](https://codegolf.stackexchange.com/a/269063/52210), so also uses negative values for down and positive for up. [Try it online](https://tio.run/##yy9OTMpM/f//cHuCrqGx9qOmJlVDY93//6OVHEPdPZR0lPz8A1yVYgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w@0JuobG2o@amlQNjXX/6/yPjlby8wmPUNJRcvf3cVOK1YlWcvZ3cQXynf39fcB8x1B3DyDfzz/AVSk2FgA). **Explanation:** ``` Ç # Convert both strings in the (implicit) input-pair to a list of codepoint # integers ` # Pop and push both integer-lists separated to the stack - # Subtract the values at the same positions from one another 13+ # Add 13 ₂% # Modulo-26 13- # Subtract 13 # (after which the result is output implicitly) ``` [Answer] # [R](https://www.r-project.org), 38 bytes ``` \(s,t,`+`=utf8ToInt)(+s-+t--13)%%26-13 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY31WI0inVKdBK0E2yBAhYh-Z55JZoa2sW62iW6uobGmqqqRmZAGqp6b5qGkp9PeISSjoKSu7-Pm5KmsoKunUJ0tLmOQmlBrI5CtLGOQkp-eR6IaWgIE7SACsZyAfU7-7u4gvQ7-_v7wPUbwJTCGSDdMJPMkfU7hrp7gPT7-Qe4wvUbGsP0mcEYlgj9EMlYiCcWLIDQAA) Port of [@Tbw's Uiua answer](https://codegolf.stackexchange.com/a/269063/55372). # [R](https://www.r-project.org), 42 bytes ``` \(s,t)strtoi(paste0(t,57,s),36)%%97%%26-13 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3tWI0inVKNItLikryMzUKEotLUg00SnRMzXWKNXWMzTRVVS3NVVWNzHQNjaE67iXUJdjGaFRopuZoALUVF-RklmhU6CgpaWpypWnUKfn5hEco6SjUKbn7-7gpaSor6NopREeb6yiUFsTqKEQb6yik5JfngZiGhjBBC6hgLNgEZ38XV7AJzv7-PnATDGCK4QyQfphZ5igmOIa6e4BN8PMPcIWbYGgM02kGY1giTIBIxkJ8uWABhAYA) Port of [@l4m2's JavaScript answer](https://codegolf.stackexchange.com/a/269061/55372). # [R](https://www.r-project.org), ~~73~~ 66 bytes ``` \(s,t,`+`=utf8ToInt)Map(\(x,a=c(x,x-26))a[order(abs(a))[1]],+s-+t) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3nWI0inVKdBK0E2yBAhYh-Z55JZq-iQUaMRoVOom2yUCyQtfITFMzMTq_KCW1SCMxqVgjUVMz2jA2Vke7WFe7RBNq0t40DSU_n_AIJR0FJXd_HzclTWUFXTuF6GhzHYXSglgdhWhjHYWU_PI8ENPQECZoARWM5QLqd_Z3cQXpd_b394HrN4AphTNAumEmmSPrdwx19wDp9_MPcIXrNzSG6TODMSwR-iGSsRBPLFgAoQE) Straightforward (?) implementation of the task. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), 15 bytes [SBCS](https://github.com/abrudz/SBCS) ``` 13-26|13+-⍥⎕UCS ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=MzTWNTKrMTTW1n3Uu/RR39RQ52AA&f=U3f393FTV0hTUPfzCY9Q51J39vf3AfOd/V1cgXw//wBXMN8x1N1DHQA&i=AwA&r=tryapl&l=apl-dyalog-extended&m=train&n=f) A tacit function which takes strings on the left and right and returns an array of positive and negative values. Port of my Uiua answer, but we have to get from letters to numbers first. This is done using [`⎕UCS`](https://help.dyalog.com/latest/Content/Language/System%20Functions/ucs.htm), which takes a string and converts to Unicode code points. [Answer] # Google Sheets, 45 bytes ``` =index(mod(code(A1:A4)-code(B1:B4)+13,26)-13) ``` Put the position in cells `A1:A4`, the combination in cells `B1:B4` and the formula in cell `C1`. The output will be in positive/negative integers. Uses [Tbw](https://codegolf.stackexchange.com/a/269063/119296)'s method. # Microsoft Excel for the web, 38 bytes ``` =MOD(CODE(A1:A4)-CODE(B1:B4)+13,26)-13 ``` Only works in Excel versions that spill result arrays by default. [Answer] # [Perl 5](https://www.perl.org/) `-lF`, 48 bytes ``` say+($_=(ord shift@F)-ord)-($_>13)*26for<>=~/./g ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJbQyXeViO/KEWhOCMzrcTBTVMXyNHUBQrbGRprahmZpeUX2djZ1unr6af/twbqUNKFAyXr/34@4RFc7v4@blzO/i6uQMLfh8sx1N2Dy88/wPVffkFJZn5e8X9dX1M9A0OD/7o5bgA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` I⁻¹³﹪⁻¹³Eθ⁻℅ι℅§ηκ²⁶ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw9BYR8E3P6U0Jx9ZILFAoxBIgQX8i1Iy8xJzNDI1dRRgbMcSz7yU1AqNDB2FbE0Q0FEwMgPR1v//O4a6e3D5@Qe4/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Similar to @Tbw's method, but subtracts the 13 in a different way to save bytes. (@l4m2's method would take 21 bytes in Charcoal.) ``` ¹³ Literal integer `13` ⁻ Vectorised subtract ¹³ Literal integer `13` ⁻ Vectorised subtract θ First input E Map over characters ι Current character ℅ Ordinal ⁻ Subtract η Second input § Indexed by κ Current index ℅ Ordinal ﹪ Vectorised modulo ²⁶ Literal integer `26` I Cast to string Implicitly print ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 90 bytes ``` O$#`. $.%` ¶ M!`.. (.). $&-$1 %{`.*?([A-Z])(-?)(#*)\1.* $2$.3 T`L`ZL`^. T`ZL`L`.$ .- #$&# ``` [Try it online!](https://tio.run/##DchLCsIwFEbh@b8LyU1JQnKhuoBSaq2D2AgqlfrgOnDgxIE4c18uwI3Fjs7Hed3fj@cta7MTnxMpYRBrwe8LbGbCDMN2ekWgEvoj7CpzqsN4sSZU1ihnzyU70Jx4gb1EGaNcedLUKEzgAEWFyrmPw9F3Ka6AJi1b36QUgfrQrX2ftu0f "Retina 0.8.2 – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation: ``` O$#`. $.%` ¶ M!`.. ``` Transpose the input. ``` (.). $&-$1 ``` Duplicate the starting letters, but prefixed with `-`s, to indicate these copies are the ones going backwards. ``` %{` ``` Repeat the rest of the script on each line separately. ``` .*?([A-Z])(-?)(#*)\1.* $2$.3 ``` If the current line contains two identical letters, record the count of how long it took with the sign if appropriate. ``` T`L`ZL`^. ``` Advance the first letter forwards. ``` T`ZL`L`.$ ``` Wind the last letter backwards. ``` .- #$&# ``` Increment the count. ]
[Question] [ [OEIS sequence A003242](https://oeis.org/A003242) comprises the numbers of Carlitz compositions for any given positive integer. This is the number of integer partitions of the integer for which no two adjacent parts are equal. For example, for 4: 1. Generate the possible integer partitions (and their permutations): `[1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [1,3], [3,1], [2,2], [4]` 2. Filter out those which have adjacent equal parts, leaving: `[1,2,1], [1,3], [3,1], [4]` 3. Count, giving us our result of 4 The first 16 terms, using zero-indexing are: `1, 1, 1, 3, 4, 7, 14, 23, 39, 71, 124, 214, 378, 661, 1152, 2024` Pleasingly, the recently arrived year, 2024, is the value of this sequence where \$n = 15\$. This is code golf, so the shortest answer in bytes per language wins. Standard loopholes are forbidden. This is also a sequence challenge, so you may take an integer argument and return the nth term, take an integer argument and return the first n terms, or take no arguments and return the infinite sequence. You may use zero- or one- indexing. [Answer] # [Maxima](http://maxima.sourceforge.net/), 54 bytes The G.f.(Generating function) of the sequence is: $$ \frac{1}{1 - \sum\limits\_{k>0} \frac{x^k}{(1+x^k)}} $$ --- Golfed version (process-oriented programming, 42 bytes). [Try it online!](https://tio.run/##NY5BCoMwFET3OcVfJvbXmEU35g6eoFhCiRDi15IoxNPHX2lXMwzzhiFXArk69GAeFkA3ofUtwkKuNFrQkX0KPkMPz7q5Y16TNFqae95JljGyvbEojGhwUAoLdqzVivfqp@k1h7wxSy76r5VXKv@rCAWBYYgIHfIBZcUnheXXu2hl6wk) ``` taylor(1/(1-sum(x^k/(1+x^k),k,1,N)),x,0,N) ``` Golfed version (lambda function that returns the first `N` terms, 54 bytes). [Try it online!](https://tio.run/##bY6xDoIwFEV3v@KNLdZgBxZYdeUHjJKKr/gCLYSWpH59LZA4Od2b3JucY1Qgo2KewQU1WQT/RtCLbT2NFhZHtoNBmedLQZYf2hG1bhzOhK75vUqI@4Xd6rvw6jOMM5M5kye3GBYefarHFFz0QoqacxHEec1YHRL4GpSZBkww1WEJHfpdgmbnQRawQakltN7BqLdxV1iVppmsZ3/FmCw4r@IX) ``` lambda([N],taylor(1/(1-sum(x^k/(1+x^k),k,1,N)),x,0,N)) ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-n`, 5 bytes ``` řJĉᵐz ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJunlLsgqWlJWm6FiuPzvQ60vlw64SqJcVJycVQ0QXbDLgMuYy4jLlMuEy5zLjMuSy4LLkMDSCyAA) ``` řJĉᵐz Take input n ř Generate a list of n copies of n e.g. 3 -> [3,3,3] J Non-deterministically split into a list of sublists e.g. [3,3,3] -> [[3],[3],[3]] or [[3],[3,3]] or [[3,3],[3]] or [[3,3,3]] ĉ Split into runs of identical elements e.g. [[3],[3],[3]] -> [[[3],[3],[3]]] [[3],[3,3]] -> [[[3]],[[3,3]]] [[3,3],[3]] -> [[[3,3]],[[3]]] [[3,3,3]] -> [[[3,3,3]]] ᵐz Check if each run has length 1 e.g. [[[3],[3],[3]]] fails, others pass ``` `-n` counts the number of solutions. In the example above, there are 3 solutions that pass the final check, so the output for `3` is `3`. [Answer] # [Haskell](https://www.haskell.org/), ~~64~~ 44 bytes ***-20 bytes** thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)!* ``` p#0=1 p#n=sum[i#(n-i)|i<-[1..n],i/=p] f=(0#) ``` [Try it online!](https://tio.run/##JYtBCsMgEEX3OcWAXSgYqyZNWqjn6EJcCG3I0ESk2k3p3a1S@MzMe8NffXo@tq2USKRRXSTBpPdukdDQI/vitbdKiOA4Hk103WKoJKzsHgMYiC8MGQ7gw73OD8Yb5hWoMQzo7iMsYKUQjkFOXU61YBWHfwYOI4e53nXpSsOlYvvpJpod5jOHaWpOnXSVUo@u/AA "Haskell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 11 bytes ``` ṄvṖÞfU'¯A;L ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCI4IMabIiwi4bmEduG5lsOeZlUnwq9BO0wiLCIiLCIiXQ==) ``` Ṅ # Integer partitions vṖÞf # All permutations of each U # Uniquified ' ; # Filtered by ¯ # Consecutive differences A # Are all nonzero L # Length ``` [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 13 bytes ``` l<pST(fo<pnq) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GuzNyC_KIShYCi1JzSlFQFDU0umMjS0pI0XYv1abY5NgXBIRpp-TYFeYWaENGbCrmJmXkKtgoFRQoqCmkKNgrRhgpWVgp-iSUKenoKRgaxEHULFkBoAA) ## Explanation Does the task as straight forward as possible: * `l` number of * `pST` partitions such that * `fo` all * `pnq` consecutive elements are non-equal Notably because `pST` works on any type of free monoid, you can give this a list as well. # Reflection I am quite happy with this answer. The one thing I would add is a function which precomposes `l` with `pST`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 44 bytes ``` f=(n,e,i=n)=>i?f(n,e,i-1)+(i^e&&f(n-i,i)):!n ``` [Try it online!](https://tio.run/##JcpBDkAwEEbhs9jITNqKblFuIhFa@UVmBHH9kli@L2@bnumaTxy3E11izimQ2GgRhEOPIf3lPBvCGMvyAwcL5qaQnPQkBN@i83VrDHhWuXSP1a4rwSb6vvwC "JavaScript (Node.js) – Try It Online") n(input) e(last choice) i(loop) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes ``` ⊞υ⟦¹⟧FN⊞υE⁺²ι∧κΣE§υ±κ∧⁻νκμIΣ⊟υ ``` [Try it online!](https://tio.run/##NYyxDoIwFEV3vuKNr0kdMHFiIk4MkCaMxqFClablQUqf8e8rJXrHe869w6TDsGifkuJtQpZwK@@iKp5LAGxo5djx/DABhYC/0eoVlecNzxKskFDTiE5CzzNmVMeGRvPJZmdeOhp04me1lvYZSXB7MYsjVaGCpYhXvUXMH2pZkQ@SUnlJp7f/Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses dynamic programming to calculate the number of permutations of `n` that end in each of the values `1` .. `n`. ``` ⊞υ⟦¹⟧ ``` Start with `1` empty permutation for `n=0`. ``` FN ``` Repeat `n` times. ``` ⊞υE⁺²ι∧κΣE§υ±κ∧⁻νκμ ``` For each `i` from `1` to `n`, calculate how many of the permutations of `n-i` do not end in `i`. ``` IΣ⊟υ ``` Output the total number of permutations for `n`. [Answer] # [R](https://www.r-project.org), ~~91~~ 84 bytes ``` \(n)sum(sapply(unique(combn(rep(0:n,n),n,\(x)x[x>0],F)),\(y)sum(y)==n&all(diff(y)))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3Q2I08jSLS3M1ihMLCnIqNUrzMgtLUzWS83OT8jSKUgs0DKzydPI0dfJ0YjQqNCuiK-wMYnXcNDWB3EqwvkpNW9s8tcScHI2UzLQ0IBcIoGYrp2kYanKlaRiBCGMQYQIiTEGEmSYXUNocqnTBAggNAA) Starts from `1`. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~34,25~~21 bytes [SBCS](https://github.com/abrudz/SBCS) ``` {≢⍸(∧/2≢/⊂⍨)¨2|⍳2⌊⍳⍵} ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UuehR7w6NRx3L9Y2AbP1HXU2PeldoHlphVPOod7PRo54uIPWod2stAA&f=K0ktLil@1DbhUe9mQ1OuEhBPJ9pAzzQ27dAKMA8A&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) -4 bytes thanks to att. A function which takes a positive integer on the right and returns the numbers of Carlitz compositions for that number. ### Explanation ``` {≢⍸(∧/2≢/⊂⍨)¨2|⍳2⌊⍳⍵}­⁡​‎‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌­ ⍳⍵ ⍝ ‎⁡‎⁡1,2,3,...,input 2⌊ ⍝ ‎⁢‎⁢min each with 2 ⍳ ⍝ ‎⁣range ⍝ ‎⁣ on an array, all combinations of ranges 2| ⍝ ‎⁤each mod 2 ( )¨ ⍝ ‎⁢⁡for each: ⊂⍨ ⍝ ‎⁢⁢partition itself, splitting on 1s 2≢/ ⍝ ‎⁢⁣tests if consecutive runs don't match ∧/ ⍝ ‎⁢⁤AND reduce ⍝ ‎⁢⁤ tests if all consecutive don't match ⍸ ⍝ ‎⁣⁡locations of 1s ≢ ⍝ ‎⁣⁢count 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` и.œʒÅγP}g ``` Port of [*alephalpha*'s Nekomata answer](https://codegolf.stackexchange.com/a/268938/52210), so make sure to upvote that answer as well! [Try it online](https://tio.run/##yy9OTMpM/f//wg69o5NPTTrcem5zQG36//@mAA) or [verify all test cases](https://tio.run/##ASkA1v9vc2FiaWX/MTVFTj8iIOKGkiAiP05E/9C4LsWTypLDhc6zUH1n/yz/NQ). A straight-forward approach would be **12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` ÅœεœÙεüÊP]˜O ``` [Try it online](https://tio.run/##ASAA3/9vc2FiaWX//8OFxZPOtcWTw5nOtcO8w4pQXcucT///NQ) or [verify the first 9 test cases](https://tio.run/##ATEAzv9vc2FiaWX/OUVOPyIg4oaSICI/TiL/w4XFk861xZPDmc61w7zDilBdy5xP/yIuViz/). **Explanation:** ``` и # Repeat the (implicit) input the (implicit) input amount of times as list .œ # Get all partitions of this list ʒ # Filter it by: Åγ # Run-length encode it; pushing a list of values and lengths P # Take the product of the list of lengths # (only 1 is truthy in 05AB1E) }g # After the filter: pop and push the length # (which is output implicitly as result) ``` ``` Åœ # Get all (sorted) lists of positive integers that sum to the (implicit) inpt ε # Map over each inner list: œ # Get all its permutations Ù # Uniquify this list of lists ε # Inner map over each unique permutation-list: ü # Map over each overlapping pair of values: Ê # Check that they are NOT the same P # Check that this is truthy for all of them in this permutation ] # Close the nested maps ˜ # Flatten the list of lists O # Sum all truthy values together # (which is output implicitly as result) ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~106~~ 104 bytes ``` f(k)=1+∑_{n=2}^{k^k}0^{(B.total-k)^2}sgn(BB[2...]-BB)^2.min B=mod(floor(n/k^{[floor(log_kn)...-1]}),k) ``` [Try It On Desmos!](https://www.desmos.com/calculator/ce4k5ta4io) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/j2hunozfgp) Brute force but horribly inefficient. I tried looking at the other answers for some other methods but I'm too smooth brained to understand any of it so I just decided to do brute force lmfao. This is definitely slower than \$O(k^k)\$ time complexity, where \$k\$ is input. It can only run inputs \$0\$ through \$7\$ in a reasonable amount of time, and \$8\$ took a couple minutes to run, but still returned the right answer, \$39\$ (you can try this yourself if you have a bit of time to kill lol). I would not suggest you try \$9\$, unless you got supercomputers or something. But with that being said, I still like this answer because it involves a bit of ingenuity by combining two conditions into one with `sgn(BB[2...]-BB)^2.min`. I tried to combine the third condition, `0^{(B.total-k)^2}`, into there as well, but couldn't think of a way to make it work. I might post an explanation in the near future to elaborate further on this. ]
[Question] [ The autokey cipher is closely related to the Vigenère cipher (both were invented by Blaise de Vigenère). Decryption involves the encrypted message and the key. For simplicity, let us assume all characters in the message and key are lowercase letters (no spaces, numbers or symbols etc.). ## How to decrypt the cipher 1. Convert all letters in the message and key into their 0-indexed counterparts. For example, 'A' is converted to 0, while 'Z' is converted to 25. 2. Subtract the first letter of the key from the first letter of the message, and wrap the result to be within 0 to 25 inclusive. For example, `2 - 6 = 22`. 3. Append this result to both the plaintext message and the key. 4. Repeat steps 2 and 3 for each letter in the message. Notice that after the initial key runs out, the key becomes the plaintext. 5. Convert the plaintext message back into a string of capital letters. ## Challenge Write a program or function that, when given a message encrypted using an autokey cipher and its key, outputs the decrypted plaintext message. * The message and key both contain only letters. * You may assume that the message and key both contain at least 1 letter, but you *cannot assume* that the message is longer than the key. * You may choose to have only lowercase or only capital letters. * You may choose to instead take the input and output strings as lists of integers from 0 to 26 inclusive, however a program that processes letters is preferred. + For example, `hyezvazczz, auto ==> helloworld` would instead be `[7, 24, 4, 25, 21, 0, 25, 2, 25, 25], [0, 20, 19, 14] ==> [7, 4, 11, 11, 14, 22, 14, 17, 11, 3]` + You may also mix between string input/output and list input/output (e.g. input as two lists, output as string) ## Test Cases ``` (format: message, key ==> plaintext) hyezvazczz, auto ==> helloworld amrkegkaikmoqsuwyacegikmoq, alphabet ==> abcdefghijklmnopqrstuvwxyz lavxxwgwgusgfaugth, amet ==> loremipsumdolorsit nlfpe, verylongkey ==> short ``` [Answer] # [Haskell](https://www.haskell.org), ~~39~~ 35 bytes ``` m#k=(`mod`26)<$>zipWith(-)m(k++m#k) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=nZJBS8MwFMfBYz_Fow5saQuubM4Nt4t4EHbz4GEMFtc0LUmamiXr2q_iZRfxM81PY1KnG7jLhDyS93_v938E3ttHhlYUM7bdvmuVRre7qwQ40LG34CJZxDf-XWfS5OVzrjIv8rlHg6Bt8L_bPy8uUyn4FCuFJYxGcJ8hCdEEHgvlHFWWMAabPhSamySC4cBxlDhwpt9iFj_ouaGUaJmOSYKW4igvjJ4IB0qZG6wDCcwGIcS9EMyJ-ya6IVzvn_urP4eZlUx0hyZ6c8Nr9aTktDAWHJXwO9c6elY5-oGb1bhZo2bZNK7_t4q0Eq5_piXikmJCUU65eF3pqkZLTNrk5AhWZugFq7PHMLTebCpSEb0iKdJEZSft-T-sC5aW-JTbGsuaiYJQXLv7XflZsS8) Takes and returns lists of ints. The test suite adds a couple functions to convert to and from strings for convenience. ### Explanation The core thing we're doing here is zipping two lists on subtraction, followed by mod 26: ``` m#k=(`mod`26)<$>zipWith(-)m k m#k= -- Operator # takes m(essage) and k(ey): zipWith(-)m k -- Subtract elementwise, clipping to shorter length (`mod`26)<$> -- Mod 26 each element ``` But we also need to recycle the plaintext as part of the key. Haskell's lazy evaluation makes this task straightforward. Instead of using `k` as the key directly, we use ``` k++m#k k -- The original key ++ -- concatenated with m#k -- the result of the decryption ``` [Answer] # x86-64 machine code, ~~27~~ 17 bytes **EDIT**: -6 bytes thanks to @Command Master noting the "upwards" modulo branch can be deleted. **EDIT**: -4 bytes thanks to @Neil pointing out `sub al, [rdx]`. ``` ac 2a 02 79 02 04 1a 48 ff c2 aa 48 39 ce 75 f0 c3 ``` Input is provided via the `RDI`, `RSI`, `RDX` and `RCX` registers: * `RSI` points to the input array * `RCX` points to the end of the input array * `RDX` points to the key array * `RDI` points to the end of the key array Output is written to `RDI`; there must be enough space after the end of the key array to store the output. Input and output are in integer array form; one byte per number. The register allocation matches the following C function prototype using the Linux x86-64 ABI: ``` extern void decrypt(char* output, const char* input, const char* key, const char* inputEnd); ``` **Disassembly** (Intel Syntax): ``` decrypt: 0: ac lodsb ; read input byte 1: 2a 02 sub al, [rdx] ; subtract key byte ; manual modulo operation: 3: 79 02 jns .no_mod ; if non-negative, don't adjust ; value range is [-25; 25], so this is fine 5: 04 1a add al,26 .no_mod: 7: 48 ff c2 inc rdx a: aa stosb ; write output b: 48 39 ce cmp rsi,rcx e: 75 f0 jne decrypt 10: c3 ret ``` [A test suite is available here](https://gist.github.com/Fayti1703/233625bda128c5e4af5116d54e79917d). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ˆε¯˜Nè-₂%Dˆ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//dNu5rYfWn57jd3iF7qOmJlWX023//0cb6CgYAbGhJRCbxHJFmwP5JjoKQGRkCsSGOgoGUCaUMo0FAA "05AB1E – Try It Online") ## Explanation This might be the first 05AB1E program I ever wrote which properly utilizes the global array. It saves the key in the global array, and each time appends something to it. ``` ˆε¯˜Nè-₂%Dˆ­⁡​‎‎⁡⁠⁡‏⁠‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌­ ˆ # ‎⁡Add the key to the global array ε # ‎⁢For each element in the ciphertext: ¯ # Push the global array ˜ # Flatten it, to account for the first element being a list N # Push the iteration index è # And index it to the global array - # subtract that from the current element ₂% # mod 26 D # create a duplicate ˆ # and add it to the global array (the other one is left for the map) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 84 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 10.5 bytes ``` £⟑¥ḣ£-₄%:&J ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiwqPin5HCpeG4o8KjLeKChCU6JkoiLCIiLCJbMCwgMjAsIDE5LCAxNF1cbls3LCAyNCwgNCwgMjUsIDIxLCAwLCAyNSwgMiwgMjUsIDI1XSJd) Or, [try a test suite](https://vyxal.pythonanywhere.com/?v=2#WyJ+IiwiXCLDuEHigLnCqFMiLCLCo+KfkcKl4bijwqMt4oKEJTomSiIsIjvigLrDuEHhuYUiLCIhKFxcdyspLCAoXFx3KykgPT0+IChcXHcrKSAhPT4gc3NzXG5oeWV6dmF6Y3p6LCBhdXRvID09PiBoZWxsb3dvcmxkXG5hbXJrZWdrYWlrbW9xc3V3eWFjZWdpa21vcSwgYWxwaGFiZXQgPT0+IGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6XG5sYXZ4eHdnd2d1c2dmYXVndGgsIGFtZXQgPT0+IGxvcmVtaXBzdW1kb2xvcnNpdFxubmxmcGUsIHZlcnlsb25na2V5ID09PiBzaG9ydCJd) Takes key then ciphertext. Uses lists of numbers for input and output, although the test case suite uses strings for convenience. ## Explained ``` £⟑¥ḣ£-₄%:&J­⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠⁠‎⁡⁠⁢⁢‏⁠‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠⁠⁠⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌­ £ # ‎⁡Put the key in the register ⟑ # ‎⁢For each number in the ciphertext: ¥ḣ - # ‎⁣ Subtract the head of the key from the ciphertext number ḣ£ # ‎⁤ and behead the key ₄% # ‎⁢⁡ Modulo the result by 25 :&J # ‎⁢⁢ and append it to the key, leaving a copy on the stack 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ⭆θ§β↨⊞Oη⁻ι§ηκ⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDiWeOalpFZoJOkoOCUWp2oElBZn@BekFiWW5BdpZOgo@GbmlRZrZCIUAsWyNTU1dRQMgKSm9f//0dHmOgpGJjoKQGRkCsSGQDkoE0qZxuooRIPEgNjQEohNYmP/65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two integer arrays and outputs a string. Explanation: ``` θ Input message ⭆ Map over values and join β Lowercase letters § Cyclically indexed by ι Current value ⁻ Minus η Input key § Indexed by κ Current index ⊞Oη Push to input key ↨ ⁰ Last integer (i.e. the one just pushed) ⭆ Implicitly print ``` 16 bytes to output as an array: ``` I﹪Eθ↨⊞Oη⁻ι§ηκ⁰Lβ ``` [Try it online!](https://tio.run/##LYrLCsIwEEV/ZZYTGMGWFhFX6kow2H3IIrbBFENS8xD/PqZQmHPv5TCjUWH0ypYyhNklvKqYkPspW49cLfghuKioccjRPBYdVPIBDQGfXY44E5zTzU36t7o3Y4xgv8Zdu1cy@KyGnUoR4kDQdgT12r7S1L9tbtVLArG6SnOsdFKW3df@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above, but the `§β` is removed, `⭆` is replaced with `E` to generate an array rather than a string, the `%Lβ` reduces modulo `26` (a literal `26` would require a separator from the literal `0`), and `I` casts to string for implicit print. 16 bytes to input the message as a string and the key as an array and output a string: ``` ⭆θ§β↨⊞Oη⁻⌕βι§ηκ⁰ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKDiWeOalpFZoJOkoOCUWp2oElBZn@BekFiWW5BdpZOgo@GbmlRZruGXmpYCUZGoidAAlszU1gQIGQFLT@v//aKWMytSqssSq5KoqJR2FaAMdBSMgNrQEYpPY2P@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The `⌕β` converts the message from letters to integers. 23 bytes to input the key as a string: ``` ⭆θ§⊞Oυ§β⁻⌕βι⌕β§⁺⪪η¹υκ±¹ ``` [Try it online!](https://tio.run/##RUvLDsIgELz7FXvcJnjouScvJh6qTfoFKyWFSADp0ig/j3BQJ5nMIzNSU5SebClTNI5x5irrSAGfAk58cYt64ZQ2fQsqEvuI6d/fBYzGpQ3Pxi0tmU7A1//Otg7mYA2jFtDXRap8dA0CrmolVti3NJSi3yrvlGXOB0rsy3G3Hw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input message ⭆ Map over characters and join β Lowercase letters § Cyclically indexed by ι Current message letter ⌕β Convert to integer ⁻ Minus η Input key ⪪ ¹ Split into characters ⁺ Concatenated with υ Predefined empty list § Indexed by κ Current message index ⌕β Convert to integer ⊞Oυ Push to predefined empty list § ±¹ Last value i.e. character just pushed Implicitly print ``` I tried several interesting alternative algorithms and the next best one was 24 bytes: ``` ≔Eη⟦⌕βι⟧η⭆θ§β↨⊞O§ηκ⌕βι±¹ ``` [Try it online!](https://tio.run/##RYyxCsIwFEX3fkXGF4iDc6c6CA5qwVEcnukjCZa0TV6L5udjMoh3uVzu4WiLQU845tzF6IyHM85glbgfnR/gqYSTD6mElW3TB@cZblzKVGpRouOTH@hduQNGgn6N9jpTQJ4C/M5iexXFX1jGhQwywV7WtDnbD6UNk06pwZWnvNvGLw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔Eη⟦⌕βι⟧η ``` Convert the key from a string to a list of lists of integers e.g. `[[0], [20], [19], [14]]`. ``` ⭆θ§β↨⊞O§ηκ⌕βι±¹ ``` Convert each letter from the message to an integer, push it to the cyclically indexed key list, convert that from base `-1`, and convert back from an integer to a letter. [Answer] # [R](https://www.r-project.org), ~~58~~ 51 bytes ``` \(m,k){for(i in seq(m))k=c(k,m[i]<-(m-k)[i]%%26);m} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGGlNTkosqCkvjE0pL87NRK26WlJWm6FjeNYzRydbI1q9PyizQyFTLzFIpTCzVyNTWzbZM1snVyozNjbXQ1cnWzNYEsVVUjM03r3Fqo1rKCnMTMvJLUihJbNMM1coG6zXUUjEx0FIDIyBSIDXUUDKBMKGWqqQOyBSQKxIaWQGyiqcmVnFiikZNaUpJaVBwNt0HbMFanOLXAVklJE2L7ggUQGgA) --- # [R](https://www.r-project.org), 58 bytes ``` f=\(m,k)if(sum(m|1))c(l<-(m-k)[1]%%26,f(m[-1],c(k[-1],l))) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY1NCsIwEEb3nqIUCjOYgCmtf5iT1CIlJlCSaGlTseBN3NSFe6_jbYwaXAjz8T6GYd711o6PvRTt0Lhd1bujlgO_907R5XOt-BYs0Vgr6HoL9sIQBZgNBUs1FqxMknROFNiCspII0B8aRAwfTo2p6oOTZ8f_HGC5gAWJ0oxEftLch5FoFmpAjkT7u_fWh618MsSJqBwY6Zxsu-JnmHp1Jxsex8E-jl--AA) Original recursive approach. [Answer] # [Python](https://www.python.org), 55 bytes ``` lambda m,k:[k.append(v:=c-K)or v%26for c,K in zip(m,k)] ``` Uses the fact that list iterator (and so `zip` too) does not copy, it holds a "reference", and `zip`'ping a growing array works as expected here. Saves 3 bytes by moving `%26` to output part — key bytes do not have to belong to \$[0;\,25]\$, modulus can be applied later. Accepts and outputs numeric lists. Test cases taken from @SuperStormer's [answer](https://codegolf.stackexchange.com/a/265672/110585). [Attempt This Online!](https://ato.pxeger.com/run?1=TZBBboQgFIbTVRNOQUiagVRn0UXbmHiCOYJ18QYRHRQoKo5epRuTpr1Te5oqZpKufnh87-V7fHzbqa-MXj7L9O1r6Mv49eelgfZcAG4jlWTqCNYKXVCfpDw-MeOwf3h6Ltfk0QnXGs-1pSvK8r399-6eQyc6nOIMZaSaxOxh5vNMIkxg6A3Jo7UOrVNCKqhVa967YZyACxkugWtsBWfR72wD_nod5SiHTpYwyL4KTHt7101pxVbywk2N0VKJieQoR8Fyldk0g1SCtq02tcy4gnIWb3GAA8OB3UCfh7O_NeUIu7QMKyJsXa17SsjxYmpNeeUox4_4NuTfFMfY_h_Lsucf) [Answer] # JavaScript (ES6), 47 bytes Expects `(msg)(key)` as two arrays of integers in \$[0\dots25]\$. Returns an array in the same format. ``` m=>k=>m.map((c,i)=>k.push(v=(c-k[i]+26)%26)&&v) ``` [Try it online!](https://tio.run/##ddHdasMgFAfw@z6FBFYMTS3sYmOUFEbZE@wy5OLMGrXRmKpJmow9e2ZsYTA2QfBw/P/w4ww9OGpl67eNObG5ymedH@r8oImGFmOayTTUpO2cwH2O6bYuZLl5fEofwlyv@3TeFyuECpSIkU09THSakgwl0HmToDJDf43dDgmmlBmMVadbGrStGa9B1tpcXDeMQBmPRdRUK@CD@SiGNHzQE6u4kOda6ca0F@t81w/XcbppCvrrdeAD7xyvoONeREXfhV9nUcYyLVvX6ZMJayf9TWlU1bIl2DM7KtPwmo0h/8@NnDDWr8oVqYx9AyowoPyAPgOlmA@cdjxDQQhAjiA@r1t2FIQQV8aaLjUlVIA9ht949ThFW/TynKb7O2NZyKAKByzFAYsNahpnFCPKcBw2/FDv3sqGk8oafbybobGJIjkb2eAkWeyvdD9/Aw "JavaScript (Node.js) – Try It Online") [Answer] # [Python](https://www.python.org), 57 bytes ``` def f(m,k,i=0): for c in m:m[i]=v=(c-k[i])%26;k+=v,;i+=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZBNbsMgEIXVRTc-BUKqArIdNV1UrSOk3sNiQTDYFAOuf0jsq3STTXun9DS1caNmw8Dw5tN78_ndjH3l7PnyJknNzKFgwCQ6USTdZbnesqYRtkA-I4inOlcZUfGO4oenZ-xa4IGcTw6UBYZ-Db1MXy6vhZBAohXyiLPoRpOZXFHi_1gBs9cx8clexWS3An7u7jnrRAcIyKMcVqOYPJv4NMEEQDb0DtJk7jPTalFqprRxH91wHBkXZXgEXd1U7CD6VVszfzody2M5dKVkQ9lXQWOu_7aWjVhaXrRj7WypxQhpRKPgfDazmA-m5jRzsMVa7toCcZwuZcM2-D-lp-Hur0M0WteBI9C0yvYIwu27UxbxqkUcxOCKuGEYjNdtnM9r_QU) [Outputs by modifying arguments.](https://codegolf.meta.stackexchange.com/a/4942/70761) [Answer] # [Scala](http://www.scala-lang.org/), ~~128~~ 124 bytes Saved 4 bytes thanks to the comment of @SuperStormer --- Golfed version. [Try it online!](https://tio.run/##bU9RS8MwEH7frzgGsoTGspVtYqWCiA8@@DR9GnuIWbbFpllMglhKf3u9uNIiCLm7L8d3333nBde8O79/SBHghSsDTbeXB9gTkW/k5/bZhB0rR2gHWCAglI5/dSAiVf6psqGmFqT2svniGkxBBJnT6xJTkq3pVba@Q/k0cKVZ@VvyxKByYmjbTQDi/gqtEO6OPocH53i93QSnzHFHc3gzKkABDTIB4gKh7Em6V/kd29HVDYNsyQBftsJYMJj3sC8rOgyXsu6nIgdjcYuxHAlWo5VeHG0Pu1gc/Yf2eOLOI3dopBW3xEJxD5gTmPEZTcM50i7TFg8L2pC/CmlVXk4m0ymNxHbSdj8) ``` def d(c:Seq[Int],k:Seq[Int],p:Seq[Int]=Seq()):Seq[Int]=if(c.isEmpty)p else{val n=(c(0)-k(0)+26)%26;d(c.tail,k.tail:+n,p:+n)} ``` Ungolfed version. [Try it online!](https://tio.run/##jVJNa4NAEL3nVwyBkpVYaSRpqWAh9NJC2kubU@hharbRRo2s0w8p/nY7qxs1IYWCs647772ZN2seYIxVtXt9lwHBA0Yp/AwA1vKNI1BFRvMP2m1lIYIoC6V6lt/kwSLKaXWf0osNnOp9W709@LXUgdj/VGzIYu7kCHWk3SlBghSEphhAgLk02TuJa/C8PRajGPwbMDiAT4whlV8LSSQVS4oe61z35IR6Owb30oIzXlvmkR0Wrj04pEt44061Z@Xg3DJS/Z4fm/ZaQp0rByfqcbKuZ9cTEZZWKwfm3hKmC1Sb3IO5UlisnkhF6UbPb5lG1F6Ldt8bot9oXdngTm3gx51xTGy4MFvzmlktmzvY0zSIY3LNMe0QnXn/7/@ptnKCcxuiypnYHjgJZiLTM@J1DCMcWQ7tNKxhZ@yT4lQcKjjJtpmAGA7NpMqq@gU) ``` object Main { def decryptAutokey(cipherText: List[Int], key: List[Int]): List[Int] = { def decrypt(cipherText: List[Int], key: List[Int], plainText: List[Int]): List[Int] = cipherText match { case cipherHead :: cipherTail => val newLetter = (cipherHead - key.head + 26) % 26 decrypt(cipherTail, key.tail :+ newLetter, plainText :+ newLetter) case Nil => plainText } decrypt(cipherText, key, List()) } def main(args: Array[String]): Unit = { val cipherText = List(7, 24, 4, 25, 21, 0, 25, 2, 25, 25) val key = List(0, 20, 19, 14) val plainText = decryptAutokey(cipherText, key) val plainTextChars = plainText.map(p => (p + 'a').toChar) println(plainTextChars.mkString("")) } } ``` ]
[Question] [ ## Challenge To quote [Wikipedia](https://en.wikipedia.org/wiki/Scale_(music)#Background): > > An octave-repeating scale can be represented as a circular arrangement > of pitch classes, ordered by increasing (or decreasing) pitch class. For instance, the increasing C major scale is C–D–E–F–G–A–B–[C], with the bracket indicating that the last note is an octave higher than the first note. > > > Major scales are defined by their combination of semitones and tones (whole steps and half steps): ``` Tone – Tone – Semitone – Tone – Tone – Tone – Semitone ``` Or in whole steps and half steps, it would be: ``` Whole – Whole – Half – Whole – Whole – Whole – Half ``` So, for example, in the C major scale, we first start with the C note. [![enter image description here](https://i.stack.imgur.com/lsoxz.png)](https://i.stack.imgur.com/lsoxz.png) Then we go up a tone (whole step) to a D [![enter image description here](https://i.stack.imgur.com/EkAma.png)](https://i.stack.imgur.com/EkAma.png) Another tone (whole step) to an E [![enter image description here](https://i.stack.imgur.com/vZLIO.png)](https://i.stack.imgur.com/vZLIO.png) Now a semitone (half step) to an F [![enter image description here](https://i.stack.imgur.com/GcZGF.png)](https://i.stack.imgur.com/GcZGF.png) Tone (whole step) to a G [![enter image description here](https://i.stack.imgur.com/zxGB8.png)](https://i.stack.imgur.com/zxGB8.png) Tone (whole step) to an A [![enter image description here](https://i.stack.imgur.com/hTO7L.png)](https://i.stack.imgur.com/hTO7L.png) Tone (whole step) to a B [![enter image description here](https://i.stack.imgur.com/xVxpT.png)](https://i.stack.imgur.com/xVxpT.png) And finally, a semitone (half step) to a C again [![enter image description here](https://i.stack.imgur.com/893bt.png)](https://i.stack.imgur.com/893bt.png) A minor scale (I'm talking about the natural minor scale as opposed to the harmonic minor scale and the melodic minor scale) follows the following formula ``` Tone – Semitone – Tone – Tone – Semitone – Tone – Tone ``` or ``` Whole – Half – Whole – Whole – Half – Whole – Whole ``` So, the C minor scale will look like [![enter image description here](https://i.stack.imgur.com/o1uUz.png)](https://i.stack.imgur.com/o1uUz.png) or, as letters: `C, D, D#, F, G, G#, A#` So, your job today is: given a major or minor scale, print the notes. ## Input/Output * Input/Output can be taken in any reasonable format for taking the name of the scale and returning the set of the increasing octave-repeating notes of that scale. * You don't need to print out the last note. * If the *notes* are enharmonic equivalent (same note but different names, eg A#/Bb), you can print either of them, but you can't print C as B# or E as Fb) * If the *scales* are enharmonic equivalent (same scale but different names eg G#m and Abm), you have to handle both of them. ``` Input -> Output C -> [C, D, E, F, G, A, B] Cm -> [C, D, Eb (D#), F, G, Ab (G#), Bb (A#)] G -> [G, A, B, C, D, E, F# (Gb)] F#m -> [F# (Gb), G# (Ab), A, B, C# (Db), D, E] ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins! [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 27 bytes *-1 byte thanks to [AndrovT](https://codegolf.stackexchange.com/users/116074/androvt)* First input is the note, second is the scale; 0 for minor and 1 for major. `kA7Ẏ:\#ẊY3⟇8⟇~ḟǓ»°f»b⁰9*ǔ*ꜝ` I'm a bit rusty. [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrQTfhuo46XFwj4bqKWTPin4c44p+HfuG4n8eTwrvCsGbCu2LigbA5KseUKuqcnSIsIiIsIkYjXG4wIl0=) | [35 bytes if you have to handle flats](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJcXGJva0E34bqOOlxcI+G6ilkz4p+HOOKfh37huJ/HkyTCueKJoMOfx5TCu8KwZsK7YuKBsDkqx5Qq6pydIiwiIiwiQWJcbjAiXQ==) **Explanation:** ``` kA7Ẏ:\#ẊY3⟇8⟇~ḟǓ»°f»b⁰9*ǔ*ꜝ kA7Ẏ Uppercase alphabets A-H :\#ẊY Duplicate, take cartesian product with "#", interleave 3⟇8⟇ Remove third and remove eight char (I know, very cringe) ~ḟǓ Find index of note, rotate list by index »°f»b Compressed number 2906, binary "101101011010" ⁰9* Multiply scale by 9, pushes 9 for major and 0 for minor ǔ Rotate "101101011010" by 0 or 9 *ꜝ Filter out list by binary string ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 137 bytes ``` (B,[E]=B.split`m`,h=E=>E[1]>{}?E[0]:E[1]||{B,E}[E]?'ABCDEFG'['0x'+E[0]-9|0]:E+'#',g=k=>[E,...k?g(k>>1,E=h(k&1?h(E):E)):[]])=>g(E<B?45:59) ``` [Try it online!](https://tio.run/##bcrdCoIwGIDh825DaBvNoVAHSdto9uVFjIFipTb/yIggu/aVHYaH78tzzR7ZkN@q/u633ensLtxhRTUYrtjQ19U9bVJacuACdGjE6y1BByaaYhxfisL7ayXaq/gAxwRpFDzRaiL@dpzcCnmIFtxyoYEyxqwssBUipMBLbJehLDGQCAiJtDGEiwLDTsn1Jtpsicu7dujqM6u7Al8wihEhi//XzMxk5h29n3Qf "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), 140 bytes ``` f=(x,i,g=k=>[R[i%12],...k?g(k>>1,i+=7-k%2*5):[]])=>x==R[i]?g(59):x==R[i]+'m'?g(45):f(x,-~i) R='BGbDbAbEbBbFCGDAEBF#C#G#D#A#'.match(/.#?b?/g) ``` [Try it online!](https://tio.run/##bcy7CoMwGIbhvbcRJEnViFIpFaJ4zO4qDsaqTeOhVClOvXUbSqci/Mv38vDfq1c110/xWMxxujZbS9Wh1RBGRyX1i7wQmu2UBiFEBh2Svm8bQqdnU2rO0cVeUZaY@iulCpYKuBfs/ZYOB6jKSalWfTTfAh9yCiPGEx7ylEc8i1kSplEGYsBAAkIAyVAt9Q1ZBAQ8sDq81dM4T31D@qlDLYIxxPjw34adyHZaBr5y@wA "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 119 bytes ``` m=>E=>(B=a=>[E,...a?B(a>>1,E=(h=E=>E[1]>B?E[0]:E[+!{B,E}[E]]?'ABCDEFG'['0x'+E[0]-9|0]:E+'#')(a&1?h(E):E)):[]])(m?45:59) ``` [Try it online!](https://tio.run/##bcrLCoJAFIDhfW8RQnMOXlDIhcLM0NjRhxhmMZlm4SUyIqie3XIZuP3@/2Ifdixv5@vd74djNdV86rggLkBxy4UmLwgCKxVYISKPODT8F0lHRihJOjQpaXf9Uh59NBkj2U5le8oLpln4ZO58@Ml73lzmMAS7iWQDhCkhptoYhE5u4zROcCqHfhzaKmiHE9QQIrCMIa7@OVrm@S6W79xZ9uIw@/QF "JavaScript (Node.js) – Try It Online") taking minor as argument As reference since others do this ``` m=>E=>( h=E=>E[1]>B? // B == 'a=>...', >B is 'b' E[0] // remove 'b' : E[+!{B,E}[E]]? // if E=='B' or E=='E' // then +!truthy=0 aka len>=1 // else +!falsy=1 aka len>=2 'ABCDEFG'['0x'+E[0]-9|0] // 0xA-9==1 0xF-9==6 0xG-9==NaN :E+'#', // Else sharpen B=a=>[ E, // This ...a?B( // Loop through a>>1, E=h(a&1?h(E):E) ):[]] // twice for set bit )(m?45:59) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Au'#æâJŽyhbÏDIkƵ;ºŽ∍ÁĆ‚Iè.¥+è ``` Two loose inputs, where the first input is the note and second is the scale as `1` for major and `0` for minor. Output as a list of notes. I/O uses high-pitched notes (with `#`). [Try it online](https://tio.run/##AToAxf9vc2FiaWX//0F1JyPDpsOiSsW9eWhiw49ESWvGtTvCusW94oiNw4HEhuKAmknDqC7CpSvDqP//Qwox) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmeBSpJSXX5Jqe3i/QmJeikJxcmIOiKNkr5SbmZdfpJCbmJVfpKRcfHiFkoLG4f2aCo/aJiko2VcmhIb9dyxVVz687PAir6N7KzOSDve7RGYf22p9aNfRvY86eg83Hml71DAr4vAKvUNLtQ@v@K/zPzpayVlJxzBWB0wbgGh3KN9NGSQQCwA). **Explanation:** ``` Au'#æâJŽyhb '# Push notes-list ["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"]: Au # Push the uppercase alphabet '# '# Push character "#" æ # Pop and push its powerset to pair it with an empty string: ["","#"] â # Take the cartesian product with the alphabet J # Join each inner pair together to a string Žyh # Push compressed integer 15343 b # Convert it to binary: 11101111101111 Ï # Keep the strings at the truthy (==1) indices D # Duplicate the list of notes Ik # Pop the copy, and get the index of the first input-note Ƶ; # Push compressed integer 212 º # Mirror it to 212212 Ž∍Á # Push compressed integer 22122 Ć # Enclose; append its own head: 221222 ‚ # Pair them together: [212212,221222] Iè # Keep the one at the second input-scale's index .¥ # Undelta with leading 0 (212212→[0,2,3,5,7,8,10]; 221222→[0,2,4,5,7,9,11]) + # Add the index of the input-note to each è # Use that list to index into the notes-list # (after which the resulting list of notes 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 `Žyh` is `15343`; `Ƶ;` is `212`; and `Ž∍Á` is `22122`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes ``` ≔FCGDAEBηF⁺⁻⁵I⪪§⪪”)¶▶↷“Mν&”⁷№θm¹⁺⌕η§θ⁰×⁷⁻№θ#№θb«§ηι×#÷ι⁷×b±÷ι⁷→ ``` [Try it online!](https://tio.run/##ZY7RasIwFIav9SlCvDmBDHRa69xVp6t4oRTnC1Qb2wNtqk0sg@GzZydTkWEuDvzJl@/8@yJt9nVaOhcZg7kGHs8W8@jzg0tWiPfuoW4YJOXZwAo1zUCyWWosfB1LtBDZpc7U9y3xYDgYj177wXAyHr2FZAgF4fVZWzhJxisuKA@En3/KGHUGhWR3DUF9/7jFShkIJbvufBh6/J9wR0J/2E@3kzSoH4VIioLq366vQvou2VLbObaYKUDf7xnaEbRWeWoVPLEeXtWtgukG88JSvDgX9yr30pa/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Based on my answer to [Output the 12 Bar Blues](https://codegolf.stackexchange.com/questions/242323) so has all of the caveats of that answer i.e. it uses strict music theoretical scales and works with any number of sharps or flats except that it uses `##` instead of `x`. ``` ≔FCGDAEBη ``` Get the list of fifths. ``` F⁺⁻⁵I⪪§⪪”)¶▶↷“Mν&”⁷№θm¹⁺⌕η§θ⁰×⁷⁻№θ#№θb« ``` Split the compressed string `53164205386497` into digits, taking the first or second half depending on whether a major or minor scale is required, subtract each digit from `9`, and add on the index of the input in the list of fifths, adding `7` for each `#`, and subtracting `7` for each `b`. Loop over the resulting list. ``` §ηι ``` Output the appropriate note by cyclic indexing. ``` ×#÷ι⁷×b±÷ι⁷ ``` Output the appropriate number of sharps or flats. ``` → ``` Leave a space between notes. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 108 bytes *-3 thanks to [@l4m2](https://codegolf.stackexchange.com/users/76323/l4m2)* Expects `(m, s)`, where `m` is a binary flag (0 for major, 1 for minor). Returns a comma-separated string of notes. ``` f=(m,s,n=59-14*m)=>n?s+[,f(B=Buffer,B((h=([a,b])=>a%3*!b?[a,35]:[b%5?a:~-a%7+65])((n&1?h:B)(B(s)))),n>>1)]:s ``` [Try it online!](https://tio.run/##lY1BTsMwEEX3nGJoFDRuJ5SopIhIThQ3NIeIvLBL3IJaB9XAkqsHW4qKQNng1f8av/df1adyu/PL23ti@@duGAzHEzmyPHtM0vv5ifHClm7RkkHBxYcx3ZkE4oFjq0hLf1bxan6tS19XmcxbHWelyr8SFT8s1plkiPYmLQ@5YCjQMf/IFkXKZO6GXW9df@xuj/0eDd4RzDYzxgCWS2g3BDXBE8GWoCGoCIS8@g2kU4AGrCN2wXxtQhU@VBH7qwibzUUx7hD8jEee12xqeRsFLmDjJz/oQxXCaPG1DjW4phSN/p9i@AY "JavaScript (Node.js) – Try It Online") ### How? The algorithm is designed to go directly from one note to the next by adding a semitone. Depending on the scale structure, this is done either once or twice per iteration. ### Commented ``` f = ( // f is a recursive function taking: m, s, // m = 'minor' flag, s = note string n = 59 - 14 * m // n = scale bitmask (major: 111011, minor: 101101) ) => // n ? // if n is not equal to 0: s + [, // append s, followed by a comma, followed by ... f( // ... the result of a recursive call: B = Buffer, // B = alias for Buffer (m is not needed anymore) B( // turn back into a string ... ( h = // ... the result of the helper function h ([a, b]) => // taking (a, b) = (note, symbol) as ASCII codes a % 3 * // if the note is neither 'B' nor 'E' !b ? // and there's no symbol: [ a, 35 ] // leave the note unchanged and append a '#' : // else: [ b % 5 ? // if the symbol is 'b': a // just remove the 'b' : // else: ~-a // advance to the next note % 7 // (make sure to wrap from 'G' to 'A') + 65 // and don't put any symbol ] // )( // invoke h: ( n & 1 ? h // twice if the LSB of n is set --> h(h(B(s)) : B // or just once otherwise --> h(B(B(s)) )(B(s)) // note that B(B(s)) is equivalent to B(s) ) // ), // end of Buffer() n >> 1 // right-shift n by 1 position ) // end of recursive call ] // : // else: s // append the last note and stop the recursion ``` --- # [JavaScript (Node.js)](https://nodejs.org), 131 bytes Supporting the format used in the test cases (e.g. `F#m`) is rather costly. ``` f=(n,s=n.replace(/m/,_=>(n=45,''),n=59))=>n?s+[,f(n>>1,(B=Buffer)((h=([a,b])=>a%3*!b?[a,35]:[b%5?a:~-a%7+65])((n&1?h:B)(B(s)))))]:s ``` [Try it online!](https://tio.run/##lY3RToNAEEXf/YqxBDtrpyVNRSPJQtjS8hGEmF0Eq6FLw6qP/jruNsQaeXKe5ibn3vMmP6Wp@tfT@1J3z/UwNBw1Ga5XfX1qZVVjcAzoiceo@V1I8zkjzcNHxnisE7MoqEEdx2tCwcVH09Q9QzxwLCSp0jLS39xeq8TGTVhGhfLDREZfS@k/LO7D0rL6Zp0cIsFQoGHuysgMVadN19artnvBBmfbGWMAEARQbAkygh3BniAnSAlEefUXP575X7gCzDz2U7Ixd1HYJ/XYZCC/@EYHwUXs2baalvbeWetKI2Jl9kndM27YmLnolqZW9c@B4Rs "JavaScript (Node.js) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~211~~ ~~209~~ 203 bytes * -6 thanks to ceilingcat Takes a key in note[accidental][minor] form: e.g. `C`, `Bb`, `G#m` ``` char*a="A#BC#D#EF#G#",*d="b-#",*u;t,l,v;f(char*s){t=index(a,*s++)-a;(u=index(d,*s))&&*u&&(s++,t=(t+u-d+11)%12);l=*s?180:236;for(t--;l/=2;printf("%c%c ",a[v-35?t:(t+11)%12],v-35?32:v))v=a[t=(l%2-~t)%12];} ``` [Try it online!](https://tio.run/##dZLfTsIwFMbveYqmC9hubRzDf6FUo6A8xNhF6ZwWJpCtmyYGH915NsBhgjcn7fc75@vpaTV/0bqq9KvKXCXxvfMwdibO45MzdTBzY4nnvF4UwrKUlSIhTWZOP600q/j5gyjm5p5HuRKk2EsxSJT2em7R6xGAzEpivYLHXr9Pu/2AilS6@V3/xh8GgyuRrDNiORfpuQzEJjMrmxDc1V2NMFNhyQeXd3YIBrviiDXKIBiWlJZShWCedgP@ZRsqthUYoDdlVqRcm5iizw5CtWQYWjC0ZGizzgVo9UWQLrIs1yp9Di8i0QG1bsZIXyAzuoYAN2sMdmBRg8VoAKEFO7Ss0XIUQDhGqD4N0O@2PRCA50Uw8ofx5PFpikMTtWkGRjCf@Q4OFxE9UXRgfytm/hsOlycL9uifRiJ5NvPPmgHsuz48Q47kLbxDm04Fgk9wtNsUNicY04P1tnOI2862@tZJql7yir//AA "C (gcc) – Try It Online") ``` char*a="A#BC#D#EF#G#", // Notes (ignoring sharps/flats) *d="b-#", // Sharp/nothing/flat (used to adjust a note) *u; // Used for determining the existence of a sharp/flat t,l,v; // Index into notes, scale pattern, current note when doing scale f(char*s){ t=index(a,*s++)-a; // Find base note (u=index(d,*s))&&*u&&(s++,t=(t+u-d+11)%12); // Find sharp/flat: adjust index accordingly l=*s?180:236; // Find major/minor pattern (each has a starting +1 to help the upcoming loop) for(t--; // Decrement the starting index to allow the code to do the printing stuff once in the loop l/=2; // Keep printing the scale until done printf("%c%c ", a[v-35?t:(t+11)%12], // Adjust to the base note if needed v-35?32:v)) // Print a sharp if needed v=a[t=(l%2-~t)%12]; // Get the next note } ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 70 \log\_{256}(96) \approx \$ 57.62 bytes ``` AZ7RAI'#d""TrsZ!.J15343bZZgAJ'1=k.AKDz0sAh212212 221222ZPz1AIdz(0ZN+AI ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhY33RyjzIMcPdWVU5SUQoqKoxT1vAxNjU2Mk6Ki0h291A1ts_UcvV2qDIodM4wMjYBIAUQYGUUFVBk6eqZUaRhE-Wk7ekJMgxq6YLEzlyGECQA) A very long port of [Kevin Cruijssen's 05AB1E answer](https://codegolf.stackexchange.com/a/256934/114446). #### Explanation ``` AZ7RAI # The first 7 letters of the alphabet, A to G '#d '# The list ['#'] ""T # With "" appended to it r # Reversed sZ! # Then take the cartesian product of that and A-G .J # Join each inner list 15343bZZ # Zipped with the binary representation of 15343 g # Filtered of where: AJ # the first element '1= '# is a 1 k # (End filter) .AK # Last element of each D # Duplicate this z0sAh # Get the index of the first input in this list 212212 # The number 212212 221222 # And the number 221222 ZP # Paired together z1AI # Index the second input into this list dz( # Cumulative sums of this number 0ZN # With a 0 prepended + # Added to the index of the first input in the list AI # Indexed into that list # Implicit output ``` ]
[Question] [ # What is elementary cellular automata? Since I'm not sure I'll be able to explain this so that somebody who has never heard of this is able to understand, I'm giving an explanation from <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html> > > Elementary cellular automata have two possible values for each cell (0 or 1), and rules that depend only on nearest neighbor values. As a result, the evolution of an elementary cellular automaton can completely be described by a table specifying the state a given cell will have in the next generation based on the value of the cell to its left, the value the cell itself, and the value of the cell to its right. Since there are 2×2×2=2^3=8 possible binary states for the three cells neighboring a given cell, there are a total of 2^8=256 elementary cellular automata, each of which can be indexed with an 8-bit binary number. For example, the table giving the evolution of rule 30 (30=00011110\_2) is illustrated above. In this diagram, the possible values of the three neighboring cells are shown in the top row of each panel, and the resulting value the central cell takes in the next generation is shown below in the center. > [![Rule 30](https://i.stack.imgur.com/qJkAf.gif)](https://i.stack.imgur.com/qJkAf.gif) > > > The evolution of a one-dimensional cellular automaton can be illustrated by starting with the initial state (generation zero) in the first row, the first generation on the second row, and so on. For example, the figure bellow illustrated the first 20 generations of the rule 30 elementary cellular automaton starting with a single black cell. > [![Rule 30 evolution](https://i.stack.imgur.com/vIHUr.gif)](https://i.stack.imgur.com/vIHUr.gif) > > > # The task Given a ruleset n, where n is positive and less than 256, produce an image like the one above, with 15 generations (+1 starting gen-0) and 2 colors of your choice. The starting gen-0 is one active cell in the center, like in the image above. You can choose to start from the bottom and work upwards. # Input You can take input either as a: * Binary number (for example, rule 30 would be 00011110 or the reverse 01111000) * Decimal number (rule 30 would be 30) You **cannot** take images from external resources, the image should made from scratch by your program. # Output Your output should be a 31x16 image, with each row representing a separate generation. Generations should not be given in a mixed order. # Submissions Your submission should always contain the following: 1. Your code 2. An image produced by your program, representing a ruleset of your liking. Standard loopholes apply. Your program should work for any n in the range [0,256). **Scoring is done by byte count** ## EDIT As requested, adding some test cases specifically for edge handling. rule 222: [![rule 222](https://i.stack.imgur.com/yJi1g.png)](https://i.stack.imgur.com/yJi1g.png) rule 201: [![rule 201](https://i.stack.imgur.com/V2TdE.png)](https://i.stack.imgur.com/V2TdE.png) rule 162: [![rule 162](https://i.stack.imgur.com/s0Bcg.png)](https://i.stack.imgur.com/s0Bcg.png) rule 16: [![rule 16](https://i.stack.imgur.com/kVX0y.png)](https://i.stack.imgur.com/kVX0y.png) [Answer] # [Python 2](https://docs.python.org/2/), ~~178 167 ...~~ 128 bytes *-13 bytes thanks to @Surculose Sputum!* *-2 bytes thanks to @dingledooper!* *thanks @Surculose Sputum again for saving some bytes and fixing the boundary bug!!!!* ``` n=input() print'P1 31 16' c='%061d'%10**30 exec"print' '.join(c[15:46]);c='0'+''.join(n[int(c[u:u+3],2)]for u in range(60));"*16 ``` [Try it online!](https://tio.run/##VY7BbsMgEETvfMVqowjjVBVrJxwc@R96j3ywHBoTuYAoVtKvd4H00rnN29nd8T9xdrbZdnB1EGfzDdFB0F6PMVkNPrhbGL/g0wUYlwWM9Wtkj9ksGqjTTz0BIm62L4NKMB@MjfyDoCUgxdnU871UdOV7knXdSpZ38JUC/n53xlbThU7dUQ3inNKSH/gft5eUStO1Ww/t8NaIIddYUwkIo73pSkkhzliT2spB7P8JWa6GkpKklAg7SP@RCqDiqTllkJRIBk0BVPwLHNtf "Python 2 – Try It Online") Output a 31x16 pbm image in stdout. You might need a magnifying glass to see those tinnie images though. > > '01111000' => [![30](https://i.stack.imgur.com/uZ6Py.png)](https://i.stack.imgur.com/uZ6Py.png) (30 in reverse) > > '01011000' => [![26](https://i.stack.imgur.com/LabYe.png)](https://i.stack.imgur.com/LabYe.png) (26 in reverse) > > > [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 42 bytes ¯\\_(ツ)\_/¯ ``` Image@CellularAutomaton[#,{{1},0},15]& ``` > > > > > > **n=30** > > > > > > > > > [![enter image description here](https://i.stack.imgur.com/V9j8M.png)](https://i.stack.imgur.com/V9j8M.png) > > > > > > **n=26** > > > > > > > > > [![enter image description here](https://i.stack.imgur.com/psb5r.png)](https://i.stack.imgur.com/psb5r.png) Since this challenged changed to gode-golf I applied the changes that @Dan the Man proposed and saved some bytes. The images now should have inverted colors [Answer] # Sledgehammer, ~~24~~ 19 bytes (alternatively, 18.625) Obtained from the Wolfram code `ExportString[ArrayPlot[CellularAutomaton[Input[], {{1}, 0}, {15, All}]], "SVG"]`. Outputs via (as you could easily tell) SVG. The ExportString part can be dropped, but then it will output a Graphics object - it's basically an image, but it's hard to view without loading it into Mathematica or exporting it via Export/ExportString. ``` ⣕⢼⡔⡼⣂⡏⢂⠌⢤⡾⣧⣾⢴⠮⣯⠴⢒⣈⣱ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 57 bytes ``` "P1 31 16",¾16иJD"ÿ1ÿ"16E©D¦¨Sðý,31Lε<®s.$3£C7αIsè}J"0ÿ0" ``` a (bad) port of [this python answer](https://codegolf.stackexchange.com/a/203376/92727) [Try it online!](https://tio.run/##AVoApf9vc2FiaWX//yJQMSAzMSAxNiIswr4xNtC4SkQiw78xw78iMTZFwqlEwqbCqFPDsMO9LDMxTM61PMKucy4kM8KjQzfOsUlzw6h9SiIww78wIv//MDAwMTEwMTA "05AB1E – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~175~~ ~~158~~ 154 bytes ``` t=take 16 f=t$0:f (a:b)!s=s<$>p(a:a:b) p(a:b:c:d)=(4*a+2*b+c):p(b:c:d) p[a,b]=[4*a+3*b] m s=putStr"P1 33 16 ">>mapM_ print`mapM_`t(iterate(!(s!!))$f++1:f) ``` [Try it online!](https://tio.run/##LY1LCsMgGIT3nsKELDRmEZvShdTcoFDoMoRGU6UhD0T/nN/GtszmmxmYeaswm2WJESSo2WB@QVZCUQuLiBKaZkGGa9G6wySLEmgxiheV5Fwqdio1G6lw5Bci16lK97JLXVPqHq04SLfDA3x@57hpjgect@2q3O2JnZ82GL48AJnAeAWGZCRkGaWFZYwLS6PfFyO7uuJ/1UnHspo2ueLUxg8 "Haskell – Try It Online") Outputs to a pbm file with white being off and black being on. You can switch the on and off colors at no cost to bytes. ## Sample outputs ### Rule 30 * Raw [![enter image description here](https://i.stack.imgur.com/ykMUd.png)](https://i.stack.imgur.com/ykMUd.png) * Increased size [![enter image description here](https://i.stack.imgur.com/PCMR3.png)](https://i.stack.imgur.com/PCMR3.png) ### Rule 121 * Raw [![enter image description here](https://i.stack.imgur.com/m9Gwn.png)](https://i.stack.imgur.com/m9Gwn.png) * Increased Size [![enter image description here](https://i.stack.imgur.com/SErvU.png)](https://i.stack.imgur.com/SErvU.png) [Answer] # [MATL](https://github.com/lmendo/MATL), 36 bytes *Thanks to [@AdHocGarfHunter](https://codegolf.stackexchange.com/users/56656/ad-hoc-garf-hunter) for pointing out a mistake, now corrected* ``` l30Ya!15:"GyFTYa3YC!XBQ)]v16:46Z)0YG ``` Input is binary in reverse order. Output is white for active cell, black for inactive. Try it at [**MATL Online!**](https://matl.io/?code=l30Ya%2115%3A%22GyFTYa3YC%21XBQ%29%5Dv16%3A46Z%290YG&inputs=%5B0+1+1+1+1+0+0+0%5D&version=22.2.1) ### Explanation ``` l % Push 1 30Ya % Padarray: pads 1 with 30 zeros on each side. Gives a column vector. % This large amount of padding is necessary to avoid edge effects in % the output ! % Transpose into a row vector 15:" % Do the following 15 times G % Push input y % Duplicate from below: pushes a copy of the latest row vector FTYa % Pad with one zero to the left and one to the right 3YC % Matrix of length-3 sliding blocks arranged as columns ! % Transpose. Each block is now a row XB % Convert each row from binary to a number Q % Add 1 (this is needed because indexing is 1-based) ) % Index the input with these numbers. This applies the automaton % rule to each length-3 block, producing a new generation ] % End v % Concatenate all row vectors into a matrix 16:46 % Push [16 17 ... 46]: indices of the columns to be kept Z) % Use as column indices 0YG % Write to image file. This is implicitly displayed by MATL Online ``` [Answer] # Java, 247 bytes ``` import java.awt.image.*;r->{BufferedImage i=new BufferedImage(31,16,1);int[]p=((DataBufferInt)i.getRaster().getDataBuffer()).getData();p[15]=-1;for(int a=31;a<496;a++)p[a]=r<<31-(p[a==31?0:a-32]<<2&4|p[a-31]<<1&2|p[a==495?0:a-30]&1)>>31;return i;} ``` [repl.it](https://repl.it/repls/PolishedMadeupMonad) Before minimizing: ``` rule -> { BufferedImage image = new BufferedImage(31, 16, BufferedImage.TYPE_INT_RGB); int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData(); pixels[15] = -1; for (int i = 31; i < 496; i++) pixels[i] = rule << 31 - (pixels[Math.max(0, a - 32)] << 2 & 4 | pixels[i - 31] << 1 & 2 | pixels[i == 495 ? 0 : i - 30] & 1) >> 31; return image; }; ``` Inner magic ungolfed: ``` BOTTOM_LEFT_PIXEL_WHICH_IS_WRITTEN = 465; int upLeft = pixels[Math.max(0, i - 32)]; int up = pixels[i - 31]; int upRight = pixels[i - 30 == BOTTOM_LEFT_PIXEL_WHICH_IS_WRITTEN ? 0 : i - 30]; int code = ((upLeft << 2) & 4) | ((up << 1) & 2) | (upRight & 1); int newBit = (rule >> code) & 1; pixels[i] = newBit == 0 ? 0x00000000 : 0xFFFFFFFF; ``` Notes: The code could be even shorter if the output image was allowed to be 32 pixels wide instead of 31. It could be even shorter if 'active' pixels may be impossibly invisible dark blue (#000001) It could surely be shorter with pbm output, but I like to see my stuff directly. ]
[Question] [ Write a program that prints the RGB color of a given pixel on the screen. The program should read a line from stdin in the format `x,y`, where x and y are unsigned integers. The pixel (0,0) is the top left pixel in the screen. The program should then output a line to stdout in the format `RRR,GGG,BBB`, which represents the color of the pixel at (`x`,`y`). `RRR`, `GGG`, and `BBB` should be floating-point numbers between 0 and 1, **OR** integers in the range [0, 255]. Leading zeros do not matter, for example: both `074` and `74` are acceptable. **Undefined Behavior** It is okay for the program to exhibit undefined behavior (crash, give incorrect output, etc) in the following conditions: * The user inputs a string, signed integer, float, or any other invalid data type * The user input is not in the format `x,y` * The specified pixel is off-screen **Notes:** * The program cannot modify the pixel at the given coordinates. * If you have multiple monitors, it does not matter which monitor the pixel is on, as long as the same monitor is used each time the program runs. The answer with the fewest bytes wins. [Answer] # Java 10 (lambda function), ~~105~~ 75 bytes ``` x->y->(new java.awt.Robot().getPixelColor(x,y)+"").replaceAll("[^\\d,]","") ``` A function taking two integer parameters and returning a String `RRR,GGG,BBB`, where the colors are integers in the range `[0, 255]`. -30 bytes thanks to *@LukeStevens* by using `java.awt.Color`'s default `toString()` output and modifying it so only the digits and commas remain. **Explanation:** ``` x->y-> // Method with two integer parameters and String return-type (new java.awt.Robot() // Create a AWT-Robot instance .getPixelColor(x,y) // Get the pixel AWT-Color at position x,y +"") // Call the default toString() of the AWT-Color // i.e. "java.awt.Color[r=213,g=230,b=245]" .replaceAll("[^\\d,]","") // Remove everything except for digits and commas ``` NOTE: The default `toString()` implementation of the `java.awt.Color` has always been the same across JVM versions as far as I know, but can potentially change in the future. I tested it in both Java 8 and Java 10 and it returned `"java.awt.Color[r=#,g=#,b=#]"`. --- But, since the challenge states: * Full program * Taking input in the format `x,y` from STDIN * Output in the format `R,G,B` to STDOUT * Have the `R`, `G`, `B` as floating points in the range `[0.0, 1.0]` The code becomes A LOT more verbose: # Java 10 (full program), 266 bytes ``` interface M{static void main(String[]a)throws Exception{var s=new java.util.Scanner(System.in).next().split(",");var c=new java.awt.Robot().getPixelColor(new Short(s[0]),new Short(s[1]));System.out.print(c.getRed()/255d+","+c.getGreen()/255d+","+c.getBlue()/255d);}} ``` **Explanation:** ``` interface M{ // Class static void main(String[]a) // Mandatory main method throws Exception{ // Mandatory throws clause for `new Robot()` var s=new java.util.Scanner(System.in) // Create a Scanner for STDIN .next() // Get the String user input .split(","); // Split it on "," and save it as String-array in `s` var c=new java.awt.Robot() // Create a AWT-Robot instance .getPixelColor( // And get the pixel AWT-Color at position: new Short( // Convert String to Short (and implicitly to int): s[0]), // x-coordinate input by user from String-array `s` new Short( // Convert String to Short (and implicitly to int): s[1])); // y-coordinate input by user from String-array `s` System.out.print( // Print to STDOUT: c.getRed() // The red part of RGB as integer in the range [0,255] /255d // Converted to a floating point in the range [0.0, 1.0] +"," // Appended with a comma delimiter +c.getGreen() // Appended with the green part of RGB as integer in the range [0,255] /255d // Converted to a floating point in the range [0.0, 1.0] +"," // Appended with a comma delimiter +c.getBlue() // Appended with the blue part of RGB as integer in the range [0,255] /255d);}} // Converted to a floating point in the range [0.0, 1.0] ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 280 260 bytes ``` 00 C0 A2 00 20 CF FF C9 0D 9D 02 C1 F0 03 E8 D0 F3 20 D2 FF A5 7A 85 FB A5 7B 85 FC A9 01 85 7A A9 C1 85 7B 20 73 00 20 6B A9 A5 14 85 FD A5 15 85 FE 20 73 00 20 6B A9 A5 FB 85 7A A5 FC 85 7B A5 14 4A 4A 4A AA 20 F0 E9 A5 FD 46 FE 6A 4A 4A A8 A5 14 29 07 AA A9 00 38 6A CA 10 FC 85 FE B1 D1 0A 26 FC 0A 26 FC 0A 26 FC 85 FB A5 D2 29 03 09 D8 85 D2 B1 D1 85 02 A9 02 18 2D 18 D0 0A 0A 65 FC 29 0F 09 D0 85 FC A9 33 85 01 A5 FD 29 07 A8 B1 FB A2 37 86 01 25 FE D0 05 AD 21 D0 85 02 A6 D6 20 F0 E9 A5 02 29 0F AA BC D2 C0 20 BC C0 BC E2 C0 20 B7 C0 BC F2 C0 A9 2C 20 D2 FF 98 0A A9 30 90 02 A9 31 20 D2 FF A9 2E 20 D2 FF 98 29 7F 4C D2 FF 30 B0 35 35 36 33 32 39 36 33 38 33 35 37 34 37 30 B0 32 38 32 37 32 39 33 32 34 33 35 B0 34 37 30 B0 32 38 36 33 36 34 32 30 34 33 35 36 39 37 ``` I expected this to be possible in a lot fewer bytes, but unfortunately... well, since I finished it, posting it now anyways. At least, the restrictive format helped with one thing: Something similar to `stdin` (input from a current device) only exists on the C64 in text mode, because the OS only supports this mode -- so no need to consider other modes of the graphics chip. Note on the output of the color values: the C64 graphics chip doesn't use RGB colors but directly generates a video signal with YUV colors, with a fixed 16 colors palette. I used rounded values of the [colodore](https://www.colodore.com/) conversion to RGB with "default" monitor settings here. **-20 bytes**: better output routine, encoding the 3 character output per color channel in a single byte. Regarding the comment: It's theoretically possible to use even multicolor character mode of the VIC with the stock C64 OS, but it requires a custom font that's actually legible with only 4 horizontal pixels of doubled width. Not entirely impossible, but very unlikely. Likewise, extended color mode (or extended background mode, which is the same) *could* be used with the C64 OS, but requires to reconfigure the graphics chip directly. I opt to ignore all these possibilities in the sense of code golfing here: It's not the standard environment you find on a Commodore 64 with running stock OS. What's possible with stock OS is switching between two builtin fonts (shift + commodore key), the program does account for that. ### [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%22pixcol.prg%22:%22data:;base64,AMCiACDP/8kNnQLB8APo0PMg0v+leoX7pXuF/KkBhXqpwYV7IHMAIGuppRSF/aUVhf4gcwAga6ml+4V6pfyFe6UUSkpKqiDw6aX9Rv5qSkqopRQpB6qpADhqyhD8hf6x0Qom/Aom/Aom/IX7pdIpAwnYhdKx0YUCqQIYLRjQCgpl/CkPCdCF/KkzhQGl/SkHqLH7ojeGASX+0AWtIdCFAqbWIPDppQIpD6q80sAgvMC84sAgt8C88sCpLCDS/5gKqTCQAqkxINL/qS4g0v+YKX9M0v8wsDU1NjMyOTYzODM1NzQ3MLAyODI3MjkzMjQzNbA0NzCwMjg2MzY0MjA0MzU2OTc=%22%7D,%22vice%22:%7B%22-autostart%22:%22pixcol.prg%22%7D%7D) Usage: `SYS49152` to start. **Commented disassembly**: ``` 00 C0 .WORD $C000 ; load address .C:c000 A2 00 LDX #$00 ; loop index for input .C:c002 .input: .C:c002 20 CF FF JSR $FFCF ; character from input device .C:c005 C9 0D CMP #$0D ; compare with enter .C:c007 9D 16 C1 STA .buf,X ; store to buffer .C:c00a F0 03 BEQ .parse ; was enter -> start parsing .C:c00c E8 INX ; next character .C:c00d D0 F3 BNE .input ; and repeat input loop .C:c00f .parse: .C:c00f 20 D2 FF JSR $FFD2 ; output the enter character .C:c012 A5 7A LDA $7A ; save pointer of BASIC parser .C:c014 85 FB STA $FB .C:c016 A5 7B LDA $7B .C:c018 85 FC STA $FC .C:c01a A9 15 LDA #$15 ; set pointer of BASIC parser to .C:c01c 85 7A STA $7A ; buffer-1 .C:c01e A9 C1 LDA #$C1 .C:c020 85 7B STA $7B .C:c022 20 73 00 JSR $0073 ; get next character .C:c025 20 6B A9 JSR $A96B ; BASIC routine to parse number .C:c028 A5 14 LDA $14 ; lowbyte of parsed number to $fd .C:c02a 85 FD STA $FD .C:c02c A5 15 LDA $15 ; highbyte to $fe .C:c02e 85 FE STA $FE .C:c030 20 73 00 JSR $0073 ; get next character .C:c033 20 6B A9 JSR $A96B ; parse as number ... .C:c036 A5 FB LDA $FB ; restore pointer of BASIC parser .C:c038 85 7A STA $7A .C:c03a A5 FC LDA $FC .C:c03c 85 7B STA $7B .C:c03e A5 14 LDA $14 ; load y coordinate .C:c040 4A LSR A ; divide by 8 for character row .C:c041 4A LSR A .C:c042 4A LSR A .C:c043 AA TAX ; -> to X .C:c044 20 F0 E9 JSR $E9F0 ; set pointer to character row .C:c047 A5 FD LDA $FD ; divide x coordinate by 8 .C:c049 46 FE LSR $FE .C:c04b 6A ROR A .C:c04c 4A LSR A .C:c04d 4A LSR A .C:c04e A8 TAY ; -> to Y .C:c04f A5 14 LDA $14 ; load y coordinate .C:c051 29 07 AND #$07 ; mask pixel position in character .C:c053 AA TAX ; -> to X .C:c054 A9 00 LDA #$00 ; initialize pixel mask to 0 .C:c056 38 SEC ; set carry for bit to shift in .C:c057 .bitnum: .C:c057 6A ROR A ; shift bit in mask .C:c058 CA DEX ; and repeat until .C:c059 10 FC BPL .bitnum ; in correct position .C:c05b 85 FE STA $FE ; store pixel mask to $fe .C:c05d B1 D1 LDA ($D1),Y ; load character code .C:c05f 0A ASL A ; multiply by 8 .C:c060 26 FC ROL $FC .C:c062 0A ASL A .C:c063 26 FC ROL $FC .C:c065 0A ASL A .C:c066 26 FC ROL $FC .C:c068 85 FB STA $FB ; and store to $fb/$fc .C:c06a A5 D2 LDA $D2 ; move pointer to position in color RAM .C:c06c 29 03 AND #$03 .C:c06e 09 D8 ORA #$D8 .C:c070 85 D2 STA $D2 .C:c072 B1 D1 LDA ($D1),Y ; load color of character .C:c074 85 02 STA $02 ; and store to $2 .C:c076 A9 02 LDA #$02 ; check which charset is active .C:c078 18 CLC .C:c079 2D 18 D0 AND $D018 .C:c07c 0A ASL A ; and calculate offset .C:c07d 0A ASL A .C:c07e 65 FC ADC $FC ; add to (character code * 8) .C:c080 29 0F AND #$0F .C:c082 09 D0 ORA #$D0 ; and add offset to character ROM .C:c084 85 FC STA $FC .C:c086 A9 33 LDA #$33 ; bank in character ROM .C:c088 85 01 STA $01 .C:c08a A5 FD LDA $FD ; load y coordinate .C:c08c 29 07 AND #$07 ; mask pixel-row number .C:c08e A8 TAY .C:c08f B1 FB LDA ($FB),Y ; load pixel row from character ROM .C:c091 A2 37 LDX #$37 ; bank out character ROM .C:c093 86 01 STX $01 .C:c095 25 FE AND $FE ; apply pixel mask .C:c097 D0 05 BNE .pixelcol ; not 0 -> pixel is set .C:c099 AD 21 D0 LDA $D021 ; otherwise load background color .C:c09c 85 02 STA $02 ; and store to $2 .C:c09e .pixelcol: .C:c09e A6 D6 LDX $D6 ; restore screen row pointer for .C:c0a0 20 F0 E9 JSR $E9F0 ; current cursor position .C:c0a3 A5 02 LDA $02 ; load color .C:c0a5 29 0F AND #$0F ; mask low nibble (only 16 colors) .C:c0a7 AA TAX ; -> to X .C:c0a8 BC D2 C0 LDY .red,X ; load encoded output for red .C:c0ab 20 BC C0 JSR .out2 ; call output without comma .C:c0ae BC E2 C0 LDY .green,X ; load encoded output for green .C:c0b1 20 B7 C0 JSR .out1 ; call output with comma .C:c0b4 BC F2 C0 LDY .blue,X ; load encoded output for blue .C:c0b7 .out1: .C:c0b7 A9 2C LDA #$2C ; load "," .C:c0b9 20 D2 FF JSR $FFD2 ; and output .C:c0bc .out2: .C:c0bc 98 TYA ; encoded output to A .C:c0bd 0A ASL A ; shift top bit to carry .C:c0be A9 30 LDA #$30 ; load "0" .C:c0c0 90 02 BCC .firstdig ; carry clear -> to output .C:c0c2 A9 31 LDA #$31 ; load "1" .C:c0c4 .firstdig: .C:c0c4 20 D2 FF JSR $FFD2 ; and output .C:c0c7 A9 2E LDA #$2E ; load "." .C:c0c9 20 D2 FF JSR $FFD2 ; and output .C:c0cc 98 TYA ; encoded output to A .C:c0cd 29 7F AND #$7F ; mask out top bit .C:c0cf 4C D2 FF JMP $FFD2 ; to output and exit .C:c0d2 .red: ; encoded values for red .C:c0d2 30 B0 35 35 .BYTE $30,$B0,$35,$35 ; ASCII digit ($30-$39) after .C:c0d6 36 33 32 39 .BYTE $36,$33,$32,$39 ; decimal point, with bit 7 .C:c0da 36 33 38 33 .BYTE $36,$33,$38,$33 ; indicating 0 or 1 before .C:c0de 35 37 34 37 .BYTE $35,$37,$34,$37 ; decimal point .C:c0e2 .green: ; encoded values for green .C:c0e2 30 B0 32 38 .BYTE $30,$B0,$32,$38 ; ... .C:c0e6 32 37 32 39 .BYTE $32,$37,$32,$39 .C:c0ea 33 32 34 33 .BYTE $33,$32,$34,$33 .C:c0ee 35 B0 34 37 .BYTE $35,$B0,$34,$37 .C:c0f2 .blue: ; encoded values for blue .C:c0f2 30 B0 32 38 .BYTE $30,$B0,$32,$38 ; ... .C:c0f6 36 33 36 34 .BYTE $36,$33,$36,$34 .C:c0fa 32 30 34 33 .BYTE $32,$30,$34,$33 .C:c0fe 35 36 39 37 .BYTE $35,$36,$39,$37 .C:c102 .buf: ; buffer for input ("stdin") ``` [Answer] # TI-BASIC (TI-83/84+), 22 bytes Since the screen is black and white, we just need to test if the specified pixel is on or off and map that to black or white RGB. Also, the pixels are only accessible through row and column in that order, so that's why the coordinates are reversed. ``` Prompt X,Y 255 Ans-{Ans,Ans,Ans}pxl-Test(Y,X ``` [Answer] ## bash, 103 / 86 bytes With a strict interpretation of the spec (input from STDIN and output on STDOUT are both comma-separated): ``` read x import -window root -crop 1x1+${x/,/+} ppm:-|od -dj13|awk 'NR<2{n=2^16;print$2/n","$3/n","$4/n}' ``` With a looser input format (plus-separated input as a command line argument, space-separated output: ``` import -window root -crop 1x1+$1 ppm:-|od -dj13|awk 'NR<2{n=2^16;print$2/n,$3/n,$4/n}' ``` Depends on imagemagick, awk, and coreutils. [Answer] # TI-Nspire assembly - 112 bytes ``` 50 52 47 00 30 40 2D E9 FF FF FF FA 00 F0 17 F8 04 1C 00 F0 14 F8 85 00 2D 18 AD 01 2D 19 6C 00 C0 21 09 06 09 69 08 5B 3F 25 42 09 2A 40 1F 25 03 1C 2B 40 C1 0A 29 40 0A A0 0A DF 30 BD 00 20 0A 23 07 49 10 25 8A 69 2A 42 FC D1 0A 68 FF 25 2A 40 30 3A 0B DB 85 00 2D 18 6D 00 A8 18 F1 E7 00 00 02 90 25 64 2C 25 64 2C 25 64 0A 00 70 47 ``` This program outputs integers in the range 0-31 for R and B and 0-63 for G, because the device natively uses a RGB565 framebuffer. It uses serial for input and output. ## Source: ``` .string "PRG" push {r4, r5, lr} blx main .thumb main: @ read x and y from serial into r4 and r0 bl read_int mov r4, r0 bl read_int @ turn x and y into framebuffer offset @ r4 = ((r0 * 320) + r4) * 2 lsl r5, r0, #2 add r5, r0 lsl r5, #6 add r5, r4 lsl r4, r5, #1 @ load pixel from framebuffer @ r0 = ((uint16_t **)0xc0000000)[0x10][r4 / 2] mov r1, #0xC0 lsl r1, #24 ldr r1, [r1, #0x10] ldrh r0, [r1, r4] @ unpack RGB565 value into r1, r2, r3 mov r5, #0x3f lsr r2, r0, #5 and r2, r5 mov r5, #0x1f mov r3, r0 and r3, r5 lsr r1, r0, #11 and r1, r5 @ call printf adr r0, fmt swi #10 @ return pop {r4, r5, pc} @ subroutine to read an integer from serial read_int: mov r0, #0 mov r3, #10 ldr r1, serial_base @ loop until characters come in on serial 2: mov r5, #(1<<4) 1: ldr r2, [r1, #0x18] tst r2, r5 bne 1b @ read character from serial and mask out status bits ldr r2, [r1] mov r5, #0xff and r2, r5 @ subtract 48 ('0') from byte; if result is negative, return sub r2, #48 blt 1f @ multiply existing numbers by 10 and add new number to them lsl r5, r0, #2 add r5, r0 lsl r5, #1 add r0, r5, r2 b 2b serial_base:.word 0x90020000 fmt:.string "%d,%d,%d\n" @ this instruction is over here because serial_base and fmt need to be word-aligned 1:bx lr ``` [Answer] # [Python 2](https://docs.python.org/2/) + PIL library, ~~96~~ 91 bytes ``` import PIL.ImageGrab as i print','.join('%.1f'%(x/255.)for x in i.grab().getpixel(input())) ``` Implements the specification literally as requested. Windows only though - doesn't work on Linux, and produces extra output (alpha value) on Mac. [Answer] ## Mathematica, 69 Bytes Just the function is 34 bytes. `CurrentScreenImage[]~PixelValue~#&` Takes input in the form {x,y}. The image is the merging of images on all monitors. If you want a particular screen, use the integer index - e.g. `CurrentScreenImage[1]` Full program exactly as specified is 69 Bytes `CurrentScreenImage[]~PixelValue~ToExpression["{"<>InputString[]<>"}"]` [Answer] # AutoHotKey, 113 bytes ``` CoordMode,Pixel InputBox,x InputBox,y PixelGetColor,c,x,y MsgBox % c&255 . "," . c>>8&255 . "," . c>>16&255 ``` Use dialog boxes instead of stdin/stdout. [Answer] # Bash on Linux with xserver, 30 bytes ``` xset dpms force off;echo 0,0,0 ``` Using the idea presented in my comment on the question, this solution should turn off the display output completely, and then echo that the screen is indeed black. I was also thinking of using `xbacklight =0`, but that doesn't change the pixel colors. [Answer] # Bash + coreutils + scrot + netpbm, 90 bytes ``` scrot -e'pngtopnm $f'|(read a;read w h;read m;head -c$((3*(w*$2+$1)))>f;od -t u1 -N3 -An;) ``` Loose I/O version Takes `x` and `y` as separate command-line arguments. Prints `r`, `g`, `b` as ints from 0-255 on separate lines --- # Bash + coreutils + scrot + netpbm + bc + sed, 172 bytes ``` IFS=, read x y scrot -e'pngtopnm $f'|(read a;read w h;read m;head -c$((3*(w*$y+$x)))>f;od -vw1 -tu1 -N3 -An|while read p;do bc<<<"scale=2;$p/$m"|tr '\n' ,;done;)|sed s/,$// ``` Strict I/O version Input on stdin as `x,y` Output on stdout as `r.rr,g.gg,b.bb` (no newline). [Answer] # TI-BASIC (TI-83/84+), 15 bytes ``` Input Y 255not(rand(3)pxl-Test(Y,Ans ``` Takes one integer from `Ans` and one from the prompt. `rand(3)` creates a list of 3 nonzero random numbers, so the product is zero iff the pixel is dark. ]
[Question] [ Inspired and looted from [this dice challenge by Arnauld](https://codegolf.stackexchange.com/questions/169919/how-much-is-my-dice-matrix-worth) # Input You are given a 5x1 or 1x5 (your choice) dice matrix which consist of binary 3x3 sub-matrices. # Goal Given a valid dice matrix, you are to score it using the rules of 6,5,4 which are as follows: * If the roll contains 6,5,4, add the other two dice together and that is your score. E.g. 4,X,5,6,Y = X+Y * Otherwise, the score is 0. E.g. 5,5,5,4,1 = 0 [Wiki article for the game](https://en.wikipedia.org/wiki/Ship,_captain,_and_crew) ## Dice patterns $$\begin{align} &1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0} &&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\ &3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0} &&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\ &5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1} &&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1} \end{align}$$ # Rules * The matrix is guaranteed to only contain valid faces but will include the 2,3 and 6 permutations. You can also take it in either orientation in whatever way is convenient. Please state the chosen orientation in your answer. * Output the calculated score * Standard Loopholes are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). # Examples ``` // 2,5,2,4,6: Output should be: 4 [ [ 0,0,1 ], [ 0,0,0 ], [ 1,0,0 ], [ 1,0,1 ], [ 0,1,0 ], [ 1,0,1 ], [ 0,0,1 ], [ 0,0,0 ], [ 1,0,0 ], [ 1,0,1 ], [ 0,0,0 ], [ 1,0,1 ], [ 1,1,1 ], [ 0,0,0 ], [ 1,1,1 ] ] // 1,6,2,4,6: Output should be: 0 [ [ 0,0,0, 1,0,1, 1,0,0, 1,0,1, 1,1,1 ], [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0 ], [ 0,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1 ] ] // 5,6,6,4,6: Output should be: 12 [ [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1 ], [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0 ], [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1 ] ] // 3,3,4,5,6: Output should be: 6 [ [ 0,0,1, 1,0,0, 1,0,1, 1,0,1, 1,1,1 ], [ 0,1,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0 ], [ 1,0,0, 0,0,1, 1,0,1, 1,0,1, 1,1,1 ] ] // 2,5,2,5,6: Output should be: 0 [ [ 0,0,1, 1,0,1, 1,0,0, 1,0,1, 1,1,1 ], [ 0,0,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0 ], [ 1,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1 ] ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` 3ôO<O©3LsK_P®O* ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f@PAWfxv/QyuNfYq94wMOrfPX@v8/OtpAx0DHMFYHSBvqGABpIIlCw8Rh6gzh6hHqUMUN0cQN0dSD@LEA "05AB1E – Try It Online") or [Check out a test suite!](https://tio.run/##MzBNTDJM/V9TVvnf@PAWfxv/QyuNfYq94wMOrfPX@m/7PzraQMdAxzBWB0wbAGlDJBoibojGJ6QelW8I1I8qDuLHckXDRWA2YOrEpJHVGaDJE28zLr/hprGZRK6f0W02QPGbIZF@w@UDrDYDAA) Uses the same trick as Chas Brown and Lynn use: decrementing each integer in each 3x3 sub-matrix rather than subtracting 15 at the end. Expects input in column format. ### How it works ``` 3ôO<OD3LsK_PsO* – Full program. 3ô – Split the input in 3x3 matrices representing dice faces. O<O – Sum each, subtract one and sum each again. This works because after the first O there are 3 elements in each list and there are 5 lists in total, so 3 * 5 = 15 = 4 + 5 + 6. © – Copy this to the register. 3LsK – Push [1, 2, 3] and perform set subtraction. In this scenario, we have already subtracted 3 from each list, so [1, 2, 3] represent the actual dice values [4, 5, 6]. If the resulting list is empty, that means that those values do exist in our roll. Therefore: _P – Produce a list of zeros of that length and take the product (4,5,6 isn't in the dice roll if the list is empty and this method assures that in this case the product is 1, else 0) ®O* – Sum what's in the register and multiply by that. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` s3§’§µ3Rœ-⁸ṆaS ``` [Try it online!](https://tio.run/##y0rNyan8/7/Y@NDyRw0zDy0/tNU46Ohk3UeNOx7ubEsM/v//f7RCtIKBjoGOoUKsDpcClGMA4xhCOQpwHpI6Q1R1hnB1ZJpngMs8Q6BVuNSBZRRiAQ "Jelly – Try It Online") Accepts a column of dice. ``` With the input (a 15×3 binary matrix): s3 Split into threes: now we have 5 dice, each a 3×3 matrix. § Sum-each. Now we have a list of triples. ’ Decrement: turn each triple [x,y,z] into [x−1,y−1,z−1]. § Sum-each. Now we have a list of dice pip sums minus 3. µ With these sums X: 3Rœ-⁸ Subtract them from {1, 2, 3} as a multiset. Ṇ Is the result empty? (This means {1, 2, 3} ⊆ X.) aS If so, yield sum(X). Else the result stays 0. ``` Just like Chas Brown’s Python answer, this offsets each dice value by −3 so that we don’t need to subtract 15 (4+5+6) from the very last sum. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` f=lambda a,r=[]:a and f(a[3:],r+[sum(sum(a[:3],[]))-3])or({1,2,3}<=set(r))*sum(r) ``` [Try it online!](https://tio.run/##rZJNasMwEIX3PsVANlY7BY0VayHqM/QAQgsFJ6SQ2EaWF6X07Kritnbzo2JKEAI93mMeH5ruze/bpghhVx3scVNbsOgqbVR8NDXscquFMugedT8c89O1WgmD2jD2JAxrXf5OWKD4eK76rc8dYw@nlGNhBQWW0VqjVPAy@G7w0O/b4VDDZqtgnXXutfGxQkMGoIEjRwKDk@A/gr4FTOpXjs5zNOX@OY@n5lGsSuVGBwzLshXISFygRLpFzS@oCeMooK9BCwUfBU866dgsKBlLOHx0@LkD2Yws4ylvIVMxM98feblYgnxZSlelM3IZoQWKa2SQdwGmBcDLV4GSq/DnH5OJvCF8Ag "Python 2 – Try It Online") All input is expected to be in the column form. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~48~~ 46 bytes *Thanks to Ramillies for -2 bytes* ``` {(^3+4⊂.flat.rotor(9)>>.sum)*(.flat.sum-15)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojzljb5FFXk15aTmKJXlF@SX6RhqWmnZ1ecWmuppYGRBjI1jU01az9X5xYqZCmoaGgoWCgY6BjqKCpw6UA5RjAOIZQjgKch6TOEFWdIVwdmeYZ4DLPEGgVLnVgGQVNzf8A "Perl 6 – Try It Online") An anonymous code block that takes the matrix vertically and returns an integer. ### Explanation: ``` { } # Anonymous code block (.flat.sum-15) # Get the total sum of the array minus 15 * # Multiply by: (^3+4⊂ ) # Whether 4,5,6 is a sub-array of: .flat.rotor(9)>>.sum # The value of each dice ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` 9es3-I:ymp*s ``` [Try it online!](https://tio.run/##y00syfmf8N8ytdhY19OqMrdAq/i/S8j/aEMdBQMdBUMwgjMMsYooWEP5aCR2BFRNitmxXNFwvWj6DKjgFEyzDXA5DuEUXC7A6RSs7jDEGioGOFyA5hQA "MATL – Try It Online") Takes input in horizontal orientation as a 3x15 matrix. [@Chas Brown's trick](https://codegolf.stackexchange.com/a/170177/8774) of subtracting 3 early (instead of 15 later) saved multiple bytes in different ways. ``` 9e % reshape input to have 9 rows - each dice matrix is linearized into a column s % sum each column (to get dice values) 3- % subtract 3 from each value, let's call this array A I: % form range 1 to 3 y % bring a copy of array A to the top of stack m % check if each of 1, 2, 3 are members of A % returns a logical array of 3 boolean values p % product of that result - 0 if any were not members, 1 if they all were * % multiply the original array A by this result s % sum ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 22 bytes ``` +ᵐ-₁ᵐḍ₅+ᵐJo⊇~⟦₁3∧J+|∧0 ``` * +3 bytes but prints out 0 instead of false if no 4,5,6 (Fatalize) * -2 4 bytes (sundar) One of my first branchylog programs. Can probably be golfed more. Prints false if there is no 4,5,6. idk how to make it output 0. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO3kdNrdoPt044tEn3UVMjmAHieuU/6mr3fNSx3PjR/GVACRDTS/v//2iFaAUDHQMdQ4VYHQUo2wDKNoSzoRyEIkMURYYwRWSYZIDdJEOgFdgVgcUVYv9HAQA "Brachylog – Try It Online") [Answer] # [R](https://www.r-project.org/), 56 bytes ``` function(m)sum(x<-by(c(m),0:44%/%9,sum)-3)*all(1:3%in%x) ``` [Try it online!](https://tio.run/##rZJvS8MwEMbf51McyGgit5rsT8Gx4itfC6KvuoFdl7lC2402lYr62ed1G7G2TiZI6CWXPvf0l/Ty3QWsdbLVOazKLDLxJgOzgWiTvejcwFMQuK47x0OswxMYXRiIwkIXkIYmjyNaxBkV3ducpRVM@9aRm8qINwZAc73/XJQL7vDZLBDvFOcUQbwjv/HhcjbLhIOOg6RFwkr8h/vHW0HFYeHu/Sue63DpmnCRaG50ZfxaWuitT3VCsA/G2Mrf2Y@noihTXk37i1ceUYZyMhr1rnrXSPuiPxSXYZJwNRn24qxXCbqQAY5xgCP0JnBXmm1poFhvymQJCz2BEVvxtOLMCSAAiRIVDbl/vtb7AXMk7KNKWk1rWJWyGoXf13svmNeHYxek807TyTadRDjYHP2/stq1gagaL4@FzQlap2lKVcfVwo4J1jsFqwZNWtV1@gfac1wt7RCHxDr@mdbr/vjOnf4CayfZzqDVAp07/Rn20KXjM/tAndsH8o@wZ/TB7hM "R – Try It Online") * -6 bytes thanks to JayCe * -1 byte thanks to Giuseppe [Answer] # [Pyth](https://github.com/isaacg1/pyth), 20 bytes ``` *-ssQ15}j456TySsMc5s ``` Expects input as a column of dice (as in test case 1). Try it online [here](https://pyth.herokuapp.com/?code=%2A-ssQ15%7Dj456TySsMc5s&input=%5B%5B0%2C0%2C1%5D%2C%5B%200%2C0%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%5D&debug=0), or verify all test cases at once [here](https://pyth.herokuapp.com/?code=%2A-ssQ15%7Dj456TySsMc5s&test_suite=1&test_suite_input=%5B%5B0%2C0%2C1%5D%2C%5B%200%2C0%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%5D%0A%5B%5B0%2C0%2C0%5D%2C%5B0%2C1%2C0%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C0%5D%2C%5B0%2C0%2C0%5D%2C%5B0%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%5D%0A%5B%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%5D%0A%5B%5B0%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B1%2C0%2C0%5D%2C%5B0%2C1%2C0%5D%2C%5B0%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B1%2C1%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B1%2C1%2C1%5D%5D&debug=0). ``` *-ssQ15}j456TySsMc5sQ Implicit: Q=eval(input()), T=10 Trailing Q inferred sQ Flatten input into a single array c5 Chop into 5 pieces sM Take the sum of each piece S Sort y Take the power set } Does the above contain... j456T ... [4,5,6]? 1 if so, 0 otherwise <a> ssQ Deep sum of input (total pips) - 15 Subtract 15 <b> * Multiply <a> and <b>, implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ ~~29~~ 22 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3ôOOJ456vyõ.;}Dg<iSOë0 ``` Takes the dice-matrices below each other. [Try it online](https://tio.run/##MzBNTDJM/f/f@PAWf38vE1OzssrDW/Wsa13SbTKD/Q@vNvj/PzraUMdAxzBWJxpI6hgAaShfAbeEAVzCAC5hgKrDAN0oQzQJED8WAA) or [verify all test cases](https://tio.run/##MzBNTDJM/W/m5ulir6TwqG2SgpL9f@PDW/z9vUxMzcoqD2/Vs651SbfJDPY/vNrgf63O/@hoAx0DHcNYHTBtAKQNIbQCmAGRMIRLGIIkiNBhgKrDEGgEqgSIH8sVDReBWWKAbhYarQCzDUknkgSJtuP0Ih7bsZlFvt/RbTdA9aIh0V7E6RGy/U7TeCcn5AkGCk6PIDsrFgA). **Explanation:** ``` 3ô # Split into sub-lists of 3, so we now have our dices # i.e. [[A],[B],[C],[D],[E],[F],...] → [[[A],[B],[C]],[[D],[E],[F]],...] OO # Sum each row, and then sum the total # i.e. [[0,0,1],[0,0,0],[1,0,0]] → [1,0,1] → 2 J # Join everything together to a single string # [5,4,2,5,6] → '54256' 456v } # For each `y` in [4,5,6]: yõ.; # Replace the first occurrence with an empty string # i.e. '54256' → '52' D # Duplicate the result g # Take the length # i.e. '52' → 2 <i # If the length is exactly 2 (and thus we've successfully removed [4,5,6]): SO # Split the string into digits again, and sum them as result ë # Else: 0 # The result is 0 instead ``` [Answer] # JavaScript (ES6), 78 bytes Takes input as a column of dice. ``` a=>!(a+0).replace(/.{18}/g,s=>(t+=n=s.split`1`.length,a|=1<<n),t=-20)|a>223&&t ``` [Try it online!](https://tio.run/##vZJBbsIwEEX3OYW7QbaYOB6HRF3gXAQhYaUmUEVOhK1ugLOnUVvSIpw2pVKXX/7zZ55nnvWLduVh3/rYNk@m26pOq@KB6rlg/GDaWpeGJvyIj@ekAqcK6ufKKsddW@/9Bje8NrbyO9AnhculZeBVLAU76ULKdDbzXdlY19SG101Ft3RFkoRIyEDCAnISF2QREbIiAgQgWcMgxEXghyCD@uLDax8OvjvzxFge9q3GfG8v0ZqxKMCKkH@yitvyK4bgABNEOECM1nzX507OrOfML5woJy7rd@KH0f4HNIW0x8zeQfPQseHtsYU2hX/d1MTPncDZvQI "JavaScript (Node.js) – Try It Online") ### How? By doing `a + 0`, we implicitly flatten and coerce the input array to a string and add a trailing `"0"`, which gives exactly **5x18 = 90** characters. For instance, the first test case leads to: ``` 0,0,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,1,1,1,0,0,0,1,1,10 \____dice #1____/ \____dice #2____/ \____dice #3____/ \____dice #4____/ \____dice #5____/ ``` For each dice substring **s** of 18 characters, we compute the number **n** of pips **+ 1** and we update the total number of pips **t** with: ``` t += n = s.split`1`.length ``` We re-use the input array **a** as a bitmask to keep track of each dice that was encountered at least once: ``` a |= 1 << n ``` If the roll contains at least one **4**, one **5** and one **6**, the bitmask **a** will have the following bits set: ``` 11100000 (224 in decimal) ``` We test this by doing `a > 223`. If successful, we return **t**. Because we count one extra pip for each dice and because we don't want to count **4+5+6** in the result, **t** is initialized to **-(5 + (4+5+6)) = -20**. [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~28~~ 27 bytes ``` {+/⍵×∧/∨/⍉⍵∘.=⍳3}¯3+(+/¨,¨) ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbhGpt/Ue9Ww9Pf9SxXP9RxwogpxPIf9QxQ8/2Ue9m49pD6421NbT1D63QObRCE6hFQcNYwfhR7xYDBQMFQwUDBTitCZZRAEoZQoXgWBOnHqiEIZqEIULCEEkCCDUB "APL (Dyalog Classic) – Try It Online") Takes a 1x5 matrix of 3x3 dice matrices as input. `+/¨,¨` adds up the pip values of each of the dice. Then subtract 3, use `∨/⍉⍵∘.=⍳3` to check if there is at least one instance each of (1, 2, 3), AND the results together with `∧/` and multiply the result (0 or 1) by the sum of the adjusted dice values (`+/⍵`). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` ¶ M!`.{9} %M`1 O` ¶ G`4.*5.*6 . $* 1{15} 1 ``` [Try it online!](https://tio.run/##K0otycxL/P//0DYuLl/FBL1qy1ouVd8EQy7/BC6QmHuCiZ6WqZ6WGZcel4oWl2G1oWktF5fh//8GBoZcBgYGXIZgDGQbQml0cShtaAhlGxoCAA "Retina 0.8.2 – Try It Online") Takes vertical dice. Explanation: ``` ¶ M!`.{9} ``` Reshape the dice into 5 individual rows. ``` %M`1 ``` Get the values of each row. ``` O` ``` Sort them into order. ``` ¶ ``` Join them into a single string. ``` G`4.*5.*6 ``` Ensure that the three required dice are present. ``` . $* ``` Convert each die to unary. ``` 1{15} ``` Subtract the matching 4, 5 and 6. ``` 1 ``` Sum and convert to decimal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` s3§§µṬṚḄ>55×S_15»0 ``` A monadic link **[Try it online!](https://tio.run/##y0rNyan8/7/Y@NByINz6cOeahztnPdzRYmdqenh6cLyh6aHdBv///49WiFYw0DHQMVSI1eFSgHIMYBxDKEcBzkNSZ4iqzhCujkzzDHCZZwi0Cpc6sIxCLAA "Jelly – Try It Online")** [Answer] # [Octave](https://www.gnu.org/software/octave/), 54 bytes ``` @(M)sum(prod(ismember(1:3,v=sum(reshape(M,9,5))-3))*v) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330HDV7O4NFejoCg/RSOzODc1Nym1SMPQylinzBYkXpRanJFYkKrhq2OpY6qpqWusqalVpvk/M6@gtKQYaEZ1tKGOgoGOgiEYwRmGWEUUrKF8NBI7AqomxexYHa5ouGY0jQZUcAum2Qa4XIfkFlxOwOkWrA4xxBouBjicgOaWWmuutPwihUxbYKxyKSikZBYX5CRWaqRpQCKxOrNWU5MrNS@F6z8A "Octave – Try It Online") Port of my MATL answer. [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` ->a{s=->x{x.flatten.sum};t=4,5,6;q=a.each_slice(3).map(&s);(t&q==t)?s[a]-15:0} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cusbrYVteuorpCLy0nsaQkNU@vuDS31rrE1kTHVMfMutA2US81MTkjvjgnMzlVw1hTLzexQEOtWNNao0St0Na2RNO@ODoxVtfQ1Mqg9n@BQlp0allijkZwiIunn15RamKKZuz/aIVoBQMdAx1DhVgdLgUoxwDGMYRyFOA8JHWGqOoM4erINM8Al3mGQKtwqQPLKMQCAA "Ruby – Try It Online") ]
[Question] [ ## Description While support is getting better and better for people to write in various scripts around the world using unicode, and now you can even write in emojis as well, unfortunately most fonts[citation needed] are still missing Latin characters based on the double acute accent, which is required to write properly in Hungarian. These characters are the following four: * U+0150 LATIN CAPITAL LETTER O WITH DOUBLE ACUTE (Ő) * U+0151 LATIN SMALL LETTER O WITH DOUBLE ACUTE (ő) * U+0170 LATIN CAPITAL LETTER U WITH DOUBLE ACUTE (Ű) * U+0171 LATIN SMALL LETTER U WITH DOUBLE ACUTE (ű) ## Task Your task is to write a program / script / function, that given a font or a font's name gives out a truthy value in case the font contains **all** of the four glyphs described above, or a falsey value if at least one of them is missing from the font. ## Scoring This is code-golf, so lowest byte-count wins ## Test cases These fonts are from [Google Fonts](https://fonts.google.com/). Note that some fonts on Google Fonts (for example Lato) have an updated version on other sites which already contain the missing glyphs, if you have the updated ones then obviously your results might be different from the test cases below. Truthy values: ``` Roboto Open Sans Lalezar Source Sans Pro Arial Times New Roman Cinzel ``` Falsey values: ``` Voltaire Rosario Heebo Bitter Arvo Lato (see note above) Molengo (contains ű and Ű, but not ő or Ő) Sue Ellen Francisco (contains only the uppercase variants) Germania One (contains only the lowercase variants) Garamond (the one installed on OSX by Office for Mac) ``` ## Notes * It's up to you if your program requires a font's name as a parameter or the actual font (or the font's location on the system) * If it's a font's name the program should check the system font registered at that name (for example if you specify `"Arial"` it should use the Arial font in your system's font registry) * If it's a location the program should use that specific font, even if there is a system font registered with that same name (for example if you specify `"/home/user/Arial.ttf"` it should use that font even if there's an Arial registered in the system's store) * Google Fonts above is just a convenient place you can download fonts for testing purposes, but your code doesn't need to use those fonts * It is enough if your program works with only one specific font type, e.g. TTF, OTF, WOFF, SVG font, Type 1, Metafont, etc. However you should support a font format that has generic support for the four glyphs and for signalling missing glyphs mentioned above, e.g. you cannot chose a font format where the answer will always be falsey or truthy * Some fonts might have the above glyphs incorrectly hardcoded to a fake value (e.g. the replacement box) instead of not specifying in the font file at all. Your code doesn't need to be able to differentiate between a fake glyph and a real glyph, but it's also acceptable if it does the check based on that. Please specify in your answer how you have to pass in the font, and what kind of fonts it works with. [Answer] # Scala, 56 bytes ``` s=>new java.awt.Font(s,0,0).canDisplayUpTo("ŐőŰű")<0 ``` `canDisplayUpTo` is a method of the Font object that returns the index of the first charater that cannot be displayed by the font. It return -1 if all characters can be displayed. [javadoc](https://docs.oracle.com/javase/7/docs/api/java/awt/Font.html#canDisplayUpTo(java.lang.String)) [Answer] # Mathematica, ~~80~~ ~~72~~ 76 bytes ``` xFreeQ[f=Rasterize@Style[#,FontFamily->x]&;f/@("Ő""ő""Ű""ű"),f@"�"] ``` Takes the name of a font as a string. For each of the characters in question, generates an image of the character in the given font, and checks if they're all different from a similar image of the replacement character "�". (The other weird character, ``, is `\[Function]`.) In almost all cases, the following **67-byte** solution works instead: ``` xLength[Rasterize@Style[#,FontFamily->x]&/@("Ő""ő""Ű""ű")]>3 ``` Here, we just check if all four images are different, which is valid under several assumptions about the fonts: * If the font can actually represent these characters, the results are all different. * If it fails to represent one of them, it fails on at least two (both the lowercase ones, or maybe "Ő" and "ő" but not "Ű" and "ű") replacing them both by the same "�"-looking character. Unfortunately, the first assumption fails in very rare cases. For example, maybe the font doesn't distinguish between uppercase and lowercase characters. One example of this is a variant of [EB Garamond](https://www.fontsquirrel.com/fonts/eb-garamond), "EB Garamond 12 All SC". (On my laptop, there are 360 fonts installed, and this is the only one of them that the second solution fails on.) Neither solution can be tried on Try It Online because the script version of Mathematica, unsurprisingly, has no support for different fonts. If you have Mathematica installed and want to try this, the system variable `$FontFamilies` lists the valid inputs (the fonts you have installed). --- *-4 bytes thanks to Martin Ender* [Answer] # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~107~~ 100 + 23 bytes *-7 bytes thanks to [briantist](https://codegolf.stackexchange.com/users/30402/briantist), whose [Powershell answer](https://codegolf.stackexchange.com/a/149694/72358) helped me realise I'm a dummy and can shave off some bytes.* ``` s=>"ŐőŰű".All(x=>new Windows.Media.GlyphTypeface(new Uri(s)).CharacterToGlyphMap.ContainsKey(x)) ``` +23 bytes from ``` namespace System.Linq{} ``` It takes path to a font file (local or internet uri), and only supports OpenType fonts. Unfortunately doesn't work on TIO because it needs reference to PresentationCore.dll, but here's the full program code anyway: [LINK](https://tio.run/##VVBLTsMwEF2TUwxZVLYEvkBJJVQJFhAJQVEXiIVxpo0lxw4ehzaqege4CRwi5wr5iKK8xWjmzdObp1F0qUi1VhZIpVQITzUFLMS9tu/RIYIOykgiePBu62UxMCPfg4IMWsGH0xmkUltGwWu7fXkF6bfET7pDdGp73FRWXY3SC3hzzixgA0lLySJuPpuv5rv5icW1MWyfLCzuYK1t5nYkUsy0FLemLvNVXeKmC8z6/bPXjDgXy1x6qQL6lRtEqSzF0tnQJaM7rNme83YenY3J@@ugbVmF@STcLtcGgbFhBQl0BuQMikeUWfcWZJzDeQK2MgZms9GhJ@KYT3wOk6nHn9Pa64CD1Wa8wvk0wvH/XcdorMf2Fw) Explanation: GlyphTypeface class loads font from provided uri, CharacterToGlyphMap loads all possible characters to a map, in which the characters are the keys. So we just take every tested character and check if the keys exist (which means the font supports them). [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 86 bytes ``` ([Windows.Media.GlyphTypeface]::new("$args")|% C*p|? K* -in 336,337,368,369).Count-eq4 ``` This is a shameless port of [Grzegorz Puławski's Answer](https://codegolf.stackexchange.com/a/149575/30402) in PowerShell, using some golfing tricks. I'm confident this could be golfed further but I have run out of time at the moment. ]
[Question] [ There are 3 (commonly used) trigonometric functions `sin` `cos` and `tan` each of these functions has an inverse function You goal is to write 3 programs or functions (one for each inverse trigonometric function `asin` `acos` `atan`) that take a (real) number a input and return the result of the corresponding inverse trigonometric function ## Examples/Test-cases (rounded to four decimal places) ``` x asin(x) acos(x) atan(x) 0 0 1.5708 0 1 1.5708 0 0.7854 -1 -1.5708 3.1416 -0.7854 0.2 0.2014 1.3694 0.1974 0.4 0.4115 1.1593 0.3805 0.6 0.6435 0.9273 0.5404 -0.5 -0.5236 2.0944 -0.4636 -0.7 -0.7754 2.3462 -0.6107 // you do not need to support these inputs for asin&acos 2 1.5708-1.317i -1.317i 1.1071 5 1.5708-2.292i -2.292i 1.3734 10 1.5708-2.993i -2.993i 1.4711 15 1.5708-3.400i -3.400i 1.5042 20 1.5708-3.688i -3.688i 1.5208 100 1.5708-5.298i -5.298i 1.5608 ``` ## Rules * Please add built-in solutions to the community wiki * You may declare multiple functions in the same program, if you provide a way to choose which of the trigonometric functions is applied to the argument (e.g function names, a second argument) * It is allowed to return a tuple containing the results of multiple functions * You may take a second parameter, to distinguish between different functions * Your solutions for `asin`/`acos` only have to work for arguments between `-1` and `1` (inclusive) * Your solution only has to be accurate up to three decimal places * Your score is the sum of the lengths of your program(s)/function(s) ## Optional additional requirements * Also support inputs that give a complex result * Do not use the complex logarithm *(see the [Sandbox Post](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/25969#25969) for how the complex logarithm might be useful)* [Answer] # JavaScript (ES7), 94 bytes Probably not the golfiest way, especially for edge cases. Returns `[atan(x), acos(x), asin(x)]`. ``` x=>[(p=1.571,g=x=>1/x?x/(h=k=>k+++k+(k>>9?0:k*k*x*x/h(k)))``:p)(x),c=2*g((1-x*x)**.5/++x),p-c] ``` [Try it online!](https://tio.run/##ZU9Nb8IwDL3zK6wewGnaNGF8aEwJp@0PcERIRAVKKEuqtkKRtv32LmE7MM1S/J7tp@f4om@6K1vT9Ll1h@NwkoOXaouNFGy@FFklQykKv/YFnmUtVU0prSnWSj2v@apO69SnvjhjTQjZ71cNQU@yUk7TClHkYUbSlM0LSkO7ycvdUDrbueuRXV2FCQB4@ATQvbZwJ6XrfkhnbEJeRn/keQya/8Y/EvVbnoHIIA@Ps2lMs5gWocXZ/J6XGYRB4CJqA04jcr5jJ9e@6vKMHqSCjxHA43bPerfpW2MrJKzRh02v2x5nBChMwo8nAU/hePauG8RbBoZEFzSggMN4HA5VIGANiS10Aiu4Bb83448HfCIPhotQXJyxeDclZPRFhm8 "JavaScript (Node.js) – Try It Online") ### Formulas The arctangent is approximated with the continued fractions: $$\arctan(x)=\dfrac{x}{1+\dfrac{(1x)^2}{3+\dfrac{(2x)^2}{5+\dfrac{(3x)^2}{7+\ddots}}}}$$ We then use: $$\arccos(-1)=\pi\\\arccos(x)=2\arctan\left(\frac{\sqrt{1-x^2}}{1+x}\right),\:-1<x\le1$$ and: $$\arcsin(x)=\frac{\pi}{2}-\arccos(x)$$ (source: [Wikipedia](https://en.wikipedia.org/wiki/Inverse_trigonometric_functions)) [Answer] # [R](https://www.r-project.org), 45 bytes ``` \(x,f,y=0:4e8/1e8)y[match(T,(f(y)-x)^2<1e-7)] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGKzLyykqLMdNulpSVpuhY3dWM0KnTSdCptDaxMUs31DVPNNSujcxNLkjM0QnQ00jQqNXUrNOOMbAxTdc00Y6GaIpM1Eosz8zQM9Ew1daAGgjg6QEFNTS6gbHJ-MaYsUBAiW5KYp2FoYICQBXJ0gIKamhALFiyA0AA) with slightly reduced precision to enable it to run with ATO's reduced memory allowance. Single function with arguments `x`=input number, `f`=trigonometric function to inverse (one of `sin`, `cos` or `tan`). Just within the 3rd-decimal place precision limit, but precision can be increased by increasing the `e8` & `e-7` in the code to `e9` & `e-8`. --- # [R](https://www.r-project.org), 67 bytes ``` \(x,f){while((f(F/T)-x)^2>1e-8)T=`if`(T-1,T+F-(F=F+1),F+(F=1));F/T} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY_BisIwEIbv-xSBvczQRK0gCFIvQp6gRxFLSdaAJpqkGhCfxEuF3TfxJXwbx61L2dNMvv-bGXK9-fbb2GPx00Qtpo_FEhLXeD5tzFYBaJDDEkXC1XieKzHFslgbvYZS5LzMpABZyCxHLjPqcsQZ6Zf3qnsNVTAWRoMJcjrxajgBxA9Kahf-JwS6JFYW3nzC6UH0kwW3U8zFjfJMN7aOxtnAomNkKR9pbOu--imV9r-7qPaQDILh0FReFX9LIGFajUkNBx97t7NI7_7Stl19Ag) Generalized "inverse" function, which, with arguments `x`=input number and `f`=any function, will output a non-negative real number (if it exists) corresponding to the inverse of `f` applied to `x`, within a precision of `1e-4` (in other words, the difference between `f(inv(x,f))` and `x` is less than `1e-4`). [Answer] ## Built-in solutions ### [APL(Dyalog Unicode)](https://dyalog.com), 1 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ○ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=ezS9GwA&f=q3jUNsFAwVDh0HpDBQM9IyA2AWIzIN9AzxRMmisYKZgqGAIVmSoYAUkDA65HvZ0a6hXqCuqJxZl5GhWaIFZyfjGUVZIIFtPUedS7CogOrdB41NVUoakDsuLQeiMgNlZIO7RCASQKAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) Left argument chooses function: ``` ¯1○⍵ ⍝ asin ¯2○⍵ ⍝ acos ¯3○⍵ ⍝ atan ``` ### C, 31 Bytes ``` #include<math.h> asin acos atan ``` ### C++, 30 Bytes ``` #include<cmath> asin acos atan ``` ### [Go](https://go.dev) #### 28 bytes (reals only) ``` import."math" Asin Acos Atan ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5BasMwELzrFUIQkGBtZBOnpaCDf5B7W8oiqtSkloK8CYbgl_RiCr31A31Kf9NtUtPDzs4suzvz9r5L89cB_R53z7LHLoquP6RMpQo9qY8jheL22yyzHulFiRNmLQbXDrztXevTIMi1hFGYv4PPcIz-8k4beRYhZfkEo7xzMmNko_vH8JqQNuuzhQqKCmxZc625NlDYsvmFG6ihgYo3GqgZrZ34l5Tb3EUKWiH761UwbhUeCDnFv-Asi4gK5Ahy0KO5EL8QYmLEJKZr5nm-9h8) #### 34 bytes (includes complex numbers) ``` import."math/cmplx" Asin Acos Atan ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5BasMwELzrFUIQkGDtyKZOQ0AH_6D3phQhosSkkoysBEHwS3IxhZ577lP6m26Tmh52dnbZmZ3r-z5MX702R73fUac7TzrXh5hKZl1iH6dki_X3ct45nQ5L4_q3zMhZR04G1Q6oMao1YSBJtUl7Iv5kn_bkzc2UC3ohNkT6CpluFI3a47vnFxPQa5eren2RUEFRgSxrrAesFRSybH7hEWpooMKLBmpEKUe0o_Qpdj5ZzjRG4Asr1MJuk8Yg_wPGmQfPgGagA8_iRsxMEhJBRjLeY0_Tvf8A) ### JavaScript, 29 bytes ``` Math.asin Math.acos Math.atan ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVC7TgMxEBStv8Jy5RV31h0KEAmFAol00FDyUIzPASOfffiBwrfQpIC_gA-Br4nvHAUCFGvNjsazs_vyamwjl583whofsDJdDHiCnXyMyklK5p4Ac5I3U6XlxbMRtCowiWE-TrzvtAqUXJmEW97R89jeSgdHKJs56aMOPtnN3tKPcvxxxsM9414ZlJGwfo0CN1nztXMyY8Gplv71n0cj8OQ4pxwY-cT1QAOsx1otmbZ3lCwI63hzaho6BryLST-WLmDD1lWmU4b_6BToFw1b_tvdetV0qSYKSSkXosAiOujjIoxTP-SlWhlZYDXwPU6zkuxSXbNgp2ohGzqCrZnFj21N_8tslDV8bwjAHmxacDgW5FMu3ytUo7JGFdtLNUp1gMqK7ffPYdasAA) ### Pascal, 6 bytes (only arctan) ``` arctan ``` Unfortunately, there is no built-in function to *inverse* the operations of `sin` and `cos`. See the [Pascal submission](/a/264796) for a full implementation of the task. ### [Python](https://www.python.org), 32 bytes (reals only) ``` from math import* asin acos atan ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31dKK8nMVchNLMhQycwvyi0q0uIptE4sz87iSbROT84u5SmwTSxLzoKrvpuUXKVQoZOYpRBvoGOroGuoY6BkBsQkQm-noGuiZggjzWCsuBYWCosy8Eo00JZBhGtUVVia1mrbVxRoVmlZ6pmm1MSUg0-HiyUjiQOvg4iUwcSVNLoTdRjqmOoZAB5jqGAFJAwOc9tnHlKBaBBHAYQPEk7CgAQA) ### [Python](https://www.python.org), 33 bytes (includes complex numbers) ``` from cmath import* asin acos atan ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31dOK8nMVknMTSzIUMnML8otKtLiKbROLM_O4km0Tk_OLuUpsE0sS86DKe9LyixQqFDLzFKINdAx1dA11DPSMgNgEiM10dA30TEGEuY6RjqmOIVCFqY4RkDQwiLXiUlAoKMrMK9FIUwKZrlFdYWVaq2lbXaxRoWmlZ5pWG1MCsg4unowkDrQfLl4CE1fShLgJ5hUA) ### Rust, 29 bytes ``` f64::asin f64::acos f64::atan ``` ### [sclin](https://github.com/molarmanful/sclin), 14 bytes ``` sin_ cos_ tan_ ``` [Try it on scline!](https://scline.fly.dev/##H4sIALRD8WQCA4s2UDBUMIxX0DNS0DNR0DNT0DMFcszjFWL1uKIVYooz8.IVYpLzi4FkSSKQHasQqGCi52eXolCUm1gAADMLI8g.AAAA) ### [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) each ``` Æs # arcsin Æc # arccos Æt # arctan ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSU1QiZjb2RlPSVDMyU4NnMlMEElM0IlMEElQzMlODZjJTBBJTNCJTBBJUMzJTg2dCZmb290ZXI9JmlucHV0PS0wLjUmZmxhZ3M9) ### [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes each ``` ∆S # Arcsine ∆C # Arccosine ∆T # Arctangent ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLiiIZTXG7iiIZDXG7iiIZUIiwiIiwiIl0=) ### [PHP](https://php.net/), 14 bytes ``` asin acos atan ``` [Try it online!](https://tio.run/##bZDBagMhEIbvPoUsPaQha2Z0HFda6IO0PciSsoWSXbohl9Jn36okrg0ZcBz//xscnYZpeX6ZYl4@xu9D6IfNK@wk7mQbFyidEqXEUQJlc3bvMszy4Ry@Hn@EjHHohzGfpZJNEppYhPnzuMnQP7Uf5zvqKVTs27F5Er9C7LcC5DXWKgcq66C7ekLifeemL87eWRJtodsb2igk5It3odM/lH4NSNVVhj0VD73L9KoQoq1otN4Uz3RgE81FYTK2GtVrt9KWIM4d9zKb1YYLrRV4ouIRG060W1/iLFW0IdbFYwQntvvlDw "PHP – Try It Online") ### [Zsh](https://www.zsh.org/), 36 bytes ``` zmodload zsh/mathfunc asin acos atan ``` [Try it online!](https://tio.run/##VYlBCoAgFAWv8hZFuqg0CIKu0kYMUahvpEF4eaNaRJsZhknB5pxWPy9ezUjBtquK1hyks/E7TjhCLVGLpofATTli2x1Fg6qUXTMY/DRRhYIxFRyxk3P@hPbhi6jeky8 "Zsh – Try It Online") [Answer] ## Pascal, ~~162~~ 194 bytes “Extended Pascal” (ISO standard 10206) defines that `complex` numbers are part of the language. When calling one of these functions, a `real` argument is automatically promoted to a `complex` value (because the formal parameter list says the `function` requires a `complex` number). ``` const i=cmplx(0,1);type r=complex;function s(x:r):r;begin s:=−i*ln(sqrt(1−x*x)+i*x);end;function c(x:r):r;begin c:=−i*ln(sqrt(x*x−1)+x);end;function t(x:r):r;begin t:=i/2*ln((1−i*x)/(1+i*x));end ``` Ungolfed: ``` const i = cmplx(0, 1); function arcsin(protected x: complex): complex; begin arcsin := −i * ln(sqrt(1 − sqr(x)) + i * x); end; function arccos(protected x: complex): complex; begin arccos := −i * ln(sqrt(sqr(x) − 1) + x); end; function arctan(protected x: complex): complex; begin arctan := i / 2 * ln((1 − i * x) / (1 + i * x)); end; ``` Arc tangent is actually already part of the language. Both in ISO standard 7185 (“Standard Pascal”) and ISO standard 10206 (“Extended Pascal”) the built-in function `arctan` is available. Since `complex` numbers are defined by EP, only the latter accepts and can return `complex` values. [Answer] # [Perl 5](https://www.perl.org/), 172 bytes ``` sub asin{n(@_,\&CORE::sin)} sub acos{n(@_,\&CORE::cos)} sub atan{n(@_,sub{sin(@_)/cos(pop)})} sub n{$f=pop;$x=1;$x+=(&$f($x)-$_[0])/((&$f($x-1e-6)-&$f($x))*1e6)for 1..9;$x} ``` [Try it online!](https://tio.run/##lZJfa8IwFMWf109xcdHmbmltmBOm6yYMn/Yg9FVFqiabsP6h7aBS/Oz1pnai7GXLQ8g9J7/kXJJUZV@PdZ1/ryHMd3EV88lKLHpvs2A6GpGAB6vxNkl@7ZHw4xVhy1FVEUNL7JPP0yTFQ7srrpj2SRiz0pc03fu8xzRnJTpsNfeW2Oet4EjlDNFpXbyTaog6yUC67hOBh9oU0R5YofICuAU0eBSmc7BNC7YAk4GuycJ4yx9cOegPEMF/AVbCUphzpIfiiqO0xJnM/@OodeJo/gOHVYNGe860YKVgqkzRnzRtjFsL2EdSgA9t8yc5zXZxoaHTzakg34euHLhSaippHyl4KdGxalOo7aW23Wl9rhdxR1g34ZqaJdZpcsAzeK7nSbj9jJpLzXgFe/ZuwwjsaRDMApsok5ugJrw449bpjc1H@PX@9RE "Perl 5 – Try It Online") Uses Perl's builtin trig functions `sin` and `cos`. Since asin, acos and atan aren't builtin, they're rather found in the core lib [Math::Trig](https://perldoc.perl.org/Math::Trig), but here they're instead written in a [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method)-ish solver in `sub n`. **Or 259 bytes:** ``` sub si{my$x=pop;abs$x<1e-8?$x:2*si($x/2)*co($x/2)} sub co{my$x=pop;abs$x<1e-8?1:co($x/2)**2-si($x/2)**2} sub ta{&si/&co} sub asi{n(@_,'si')} sub aco{n(@_,'co')} sub ata{n(@_,'ta')} sub n{$f=pop;$x=1;$x+=(&$f($x)-$_[0])/((&$f($x-1e-6)-&$f($x))*1e6)for 1..9;$x} ``` [Try it online!](https://tio.run/##dVPfT7MwFH2Wv@LG1dFiYXTOfbqJ@uKTMSZ7VWOQFSX5@JEVE@ayv33eFsbQuT5A77nn3HO5LYVc/D/fbNTnG6hklS5JFRR5MQ3fFKmuhHQvbkg1GToqoaQaDJkT5fVmbWlJlP8pEZMtzXGGbqt1hrWqDFd9lQz6UV7HITpn9PaV2yqxm8ohlq6xKG8xFNZYGW6xbEViY49dCHycBrRPYjRkLnl98l/YgDaAi62NmdtkmSPkmMX5AoTnXaJwvflUEh5kmidfcgppvaGmpU6ou5laWpcugZRSlUAtwPUENn6HzXGMVHj@iEFwDXoDLxygh2xMsN/UbJ/bK/BIlMnt6GjLcdrqIF3ndnScD8cx77H37X3P/2cYetNltI4HGVuTg4SOybghjA9Y/JnfGfxMp2Hxozwe/SLM5vTMEyO8Z4ZLKj0cPNsz39RjK/NKl5TEnFScyKpgwa05wWmTAvKelxBAc0VquFgkWRnD8YnCAPMBnIiRJ0SMIfIQYV0Iy8qolPMuNk/iuI2fs2NuHeHPQrWba/qAKz07X0DvIzWmet2A/XhvwwTsu9nscWajSveNItM8b@XWevMN "Perl 5 – Try It Online") ...which replaces Perl's `sin` and `cos` with `si` and `co` that uses the property that sin(x) = x and cos(x) = 1 for small x and the formulas for half angles. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~132~~ 125 bytes ``` NθNη⊞υ¹⊞υ∧›⁰ηθ≔⁰ζ≔²εF⁵⁰«≔₂⊕Xε²δ≔¹ιFχ«≔⊘⁺ιδι≔₂×ιδδ»≔∨⎇⊕η⁼›⁰§υη⎇η›θ§υ⁰›§υ¹θ›⁰§υ¹±¹δUMυ⁺κ×××δε§υ¬λ∨λ±¹≧⁺×∨η¹×δ∕ειζ≧×₂⊕×εεθ≦⊘ε»Iζ ``` [Try it online!](https://tio.run/##dZLBTsMwDIbP9ClyTKQMtZN24jQBgh0Y09gLhNUsEWm6pumAoT17cdJ2S6VxqeL49xf7d7dS2G0pdNsuzL5xy6Z4B0srdpfEscR41dSSNpxk0XlucvpkQTjUpJxIxknFMD@va7Uz/up4iaacAEYfpSV0ljLym9z0mbeqERbWZenowmwtFGAc5HRVfiEXOJkyhuQci4eKjBPlwwDLOtiQexb64Kt1U1Ply1gvvvLcRhVwUYUXTudHXi3dgDXC/oza8lM@IkLX8exztzA5fHtXpGcNlZKTQVWNVKlXDanoPutMvOTG8Cx4sYQd5mh27vpF7O/LohC4EBSF2T@xiTBe/M39EkbAJdqgAxTn1TGasZ7c@bFWO@mCrQMYC2TX8Bn@oA4qB780FZjHK4gg5uSfrXco8H2yYEUM6Jfb/UmnZGWVcfRe1I4esdm2naS3syRrJwf9Bw "Charcoal – Try It Online") Link is to verbose version of code. Takes the function as the second argument where `-1=atan`, `0=asin` and `1=acos`. Explanation: Uses [CORDIC](https://people.math.sc.edu/Burkardt/py_src/cordic/cordic.html) to calculate the inverse functions. Edit: Switched to single-angle CORDIC for `asin` and `acos` to save 7 bytes. ``` Nθ ``` Input the real value. ``` Nη ``` Input the function code. ``` ⊞υ¹ ``` Start with `z[0]=1`. ``` ⊞υ∧›⁰ηθ ``` Start with `z[1]=0`, except for `atan`, where the input is used. ``` ≔⁰ζ ``` Start with a resulting angle of `0`. ``` ≔²ε ``` Start with `2` as the first power of `0.5`. This is needed for `acos` to work with negative inputs, but doesn't affect `asin` or `atan`. ``` F⁵⁰« ``` Loop `50` times, as unfortunately `10` isn't accurate enough. ``` ≔₂⊕Xε²δ≔¹ιFχ«≔⊘⁺ιδι≔₂×ιδδ» ``` Start calculating the `atan` of the power of `0.5`. (Yes, I could do the `atan` separately, but that would duplicate code, increasing my byte count.) ``` ≔∨⎇⊕η⁼›⁰§υη⎇η›θ§υ⁰›§υ¹θ›⁰§υ¹±¹δ ``` Determine whether we are increasing or decreasing the angle. ``` UMυ⁺κ×××δε§υ¬λ∨λ±¹ ``` Rotate `z` by the `atan` of the power of `0.5`. ``` ≧⁺×∨η¹×δ∕ειζ ``` Update the angle. ``` ≧×₂⊕×εεθ ``` Compensate for rotation's scaling factor (no effect for `atan`). Note that in a real FPGA you would approximate the square root but that doesn't help me here. ``` ≦⊘ε ``` Get the next power of `0.5`. ``` »Iζ ``` Output the final angle. ]
[Question] [ ## Task Given a finite permutation output its inverse. You may take input and output in any reasonable format equivalent to a list of natural numbers. You may choose to use 0 indexing or 1 indexing. Your input and output format should be the same. You may assume a permutation has at least 1 element. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source as measured in bytes. ## Permutations A finite permutation is a function which takes an \$n\$-tuple and produces an \$n\$-tuple such that every element of the input is present in the output, and the ordering does not rely on the values of the inputs. We can unambiguously represent these permutations with an \$n\$-tuple where each element is the index of where it will end up. For example: $$ (3 \,\, 2 \,\, 1 \,\, 0) $$ This permutation reverses a \$4\$ element tuple. The first element goes to the 3rd (last) position, the second goes to the 2nd (penultimate) position etc. With this representation a valid permutation is just any list of size \$n\$ which contains the numbers \$0\$ through \$n-1\$. For a permutation \$A\$ the inverse permutation of \$A\$ is a permutation such that when applied after \$A\$ it restores the list to it's initial state. For example \$(3\,\,2\,\,1\,\,0)\$ is the permutation that reverse the order of 4 elements. It is its own inverse since reversing twice gets you back to where you started. \$(1\,\,2\,\,3\,\,4\,\,0)\$ takes the first of 5 elements and moves it to the end, it has an inverse of \$(4\,\,0\,\,1\,\,2\,\,3)\$ since that takes the last of 5 elements and moves it to the front: $$ (A,B,C,D,E) \\ \underset{\,(1\,\,2\,\,3\,\,4\,\,0)\,}{\xrightarrow{}}\\ (B,C,D,E,A) \\ \underset{\,(4\,\,0\,\,1\,\,2\,\,3)\,}{\xrightarrow{}}\\ (A,B,C,D,E) $$ Every permutation has an inverse. ## Test cases ``` [0] -> [0] [0,1,2] -> [0,1,2] [2,1,0] -> [2,1,0] [1,2,0] -> [2,0,1] [0,2,1] -> [0,2,1] [1,2,0,5,4,3] -> [2,0,1,5,4,3] ``` [Answer] # [R](https://www.r-project.org/), 5 bytes ``` order ``` [Try it online!](https://tio.run/##K/r/P78oJbXo/38A "R – Try It Online") # [R](https://www.r-project.org/), 26 bytes ``` function(x)match(seq(x),x) ``` [Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NCMzexJDlDozi1EMjWqdD8X2GbrGGkY6xjqGOmY6pjoslVEZ0GlIrlAkkYAiWM4EL/AQ "R – Try It Online") Both 1-indexed. [Answer] # JavaScript (ES6), 28 bytes Modifies the input list in-place. ``` a=>[...a].map((v,i)=>a[v]=i) ``` [Try it online!](https://tio.run/##XYzLDoIwEEX3fMUs22QsWHVF2p1f0XQxQVAMUgKGjfHba6n1OauZc@beM800VWM7XFe9O9S@UZ6UNkIIsuJCA2MztlxpMrNVLfelyQBMYRHek@cLiBjXKF8q4ggWJcNWfKsnWFR4@VchlwrD22@hTCqmcIdb3NhPKoHMZqJx456qEyNQGm7QMOIlVK6fXFeLzh3jfeelfwA "JavaScript (Node.js) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 2 bytes ``` &S ``` [Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKvwXy34v0KEi0JUhUJI7P9ow1gFrmhDHSMdYxDDGMgAiwD5OlApoBhcRMdMx1THBMg10Dfg4uICAA "MATL – Try It Online") Built-in, 1-indexed. Get the second output of `sort`. Implicit input, implicit output. ### [MATL](https://github.com/lmendo/MATL), 4 bytes ``` fG&m ``` [Try it online!](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKvwP81dLfe/QoSLQlSFQkjs/2jDWAWuaEMdIx1jEMMYyACLAPk6UCmgGFxEx0zHVMcEyDXQN@Di4gIA "MATL – Try It Online") Just to make use of the "restricted to permutations" aspect of this question (mentioned in the question comments). Construct an array of 1:length(input), and find the position of each element of that in the input array. Another option [at 6 bytes](https://tio.run/##y00syfmfoJCpUBLlp2CvUKGnEKvwv0QpwsFB43@sQoSLQlSFQkjs/2jDWAWuaEMdIx1jEMMYyACLAPk6UCmgGFxEx0zHVMcEyDXQN@Di4gIA "MATL – Try It Online"): `t"X@@(` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes ``` Ordering ``` [Try it online!](https://tio.run/##Tcm7CoUwEEXRXzlYTxNfnZ299iFFuEoM4gMZq5Bvz02Cgs2cxZ5N8zJvmu1PB9OF4Zrmy@4m9IfEGMWysPt5MzoUhJXSPW5@i5GrUgQXHw5O@DiCUBKqxCoz15QeiszyUwktoSHUHt5DhT8 "Wolfram Language (Mathematica) – Try It Online") 1-indexed (while the input can be either 0- or 1-indexed, the output is always 1-indexed). Plot twist: this generic builtin beats the specific builtin `InversePermutation` (not to mention that that builtin operates on Mathematica's custom permutation type, which would be hard to justify as being "equivalent to a list of natural numbers"). [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), ~~7~~ 1 bytes ``` < ``` built in. old answer `{x?!#x}` [Try it online!](https://tio.run/##y9bNS8/7/7@6wl5RuaIWRisYKhgpGCiYKpgoGP8HAA "K (ngn/k) – Try It Online") ### Explanation ``` {x?!#x} a function that takes a list x x? indices of the elements in x !#x in the range to length x ``` [Answer] # [Python 3](https://docs.python.org/3/), 35 31 bytes ``` lambda l:map(l.index,sorted(l)) ``` [Try it online!](https://tio.run/##TYs9DoIwGIb3nuILEzUfBEEXknKRylACxCalNLQxcA4HF07HRbAgRqf373nN5O69ztaW3VYluqoWoPJOmFDFUtfNiLYfXFOHitJVdsYHsJMlbT@AAqm3EFtXS50TEFgBg@3cPIRCFVujpAuDqAgoJTAyfmpDQUsCZpDaD8v8WuZnwEfGqhIFjljRlSclRAV4ITzBM6ZH3C3hqdeD@FjC/fCrPLcf/fg9pnu1U3jFC2Z/7FG8AQ "Python 3 – Try It Online") Thanks to Jonathan Allan for the -4 bytes! [Answer] # [Python 3](https://docs.python.org/3/) NumPy (not using builtin), 23 bytes ``` lambda L:L.put(L[L],+L) ``` [Try it online!](https://tio.run/##TYtBTsMwFET3PsVXVjb9jUIKm1buCXwDk8VPSoQlx7FsFyXnYMGmp@tFgglBsJqZNzN@Tm@jOyy9fFksDe2FQB1V6a@JK60a3CmxmMGPIYG7Dn4GiuA821CcI@vHABaM@w5lTBfjjgwIW5AwkOev72TRltFbk3ixPxdC5DqXzpcUAs2cMugk7apTzztxmqR@6BoGPhiXH/fb5/32UehJyrZBwglbseiqgf0ZsjBd4SPWW1wt03XWbfFjmc7FH8q79ZjL32O9onWFz/iEh3/bDXwB "Python 3 – Try It Online") Expects a numpy array and modifies it in-place. # [Python 3](https://docs.python.org/3/) NumPy (not using builtin), 29 bytes ``` lambda L:sorted(L,key=L.item) ``` [Try it online!](https://tio.run/##TYtBTsMwEEX3PsUoqwRNo5LCppJ7gtzAZDFREmFhO5btovgcLNj0dL1IGEIQrOb/99/4nF5nd1on@bIasv1A0J7jHNI4lC2@jVm2tU6jrVZtPWNwV@szUATnxY5ijmKaAxjQ7rvUMQ3anQUQ9iDBki/HdzJo6uiNTmVxuBRVxTOPztcUAuWSGCxSPUycOgE@aMfm/fZ5v30UapGy75Bwwb5a1bGDwwX4CHXER2z2ukWhGr678ROF4uEPsbc98vj72Gxos/AZn/D0z93BFw "Python 3 – Try It Online") This doesn't really use numpy except for the shorter `item` member which replaces the cumbersome `__getitem__` # [Python 3](https://docs.python.org/3/) NumPy (builtin), 20 bytes ``` lambda L:L.argsort() ``` [Try it online!](https://tio.run/##TY1BDoIwEEX3PcWEFZiRKOqGpJ7AG1QWQxRtUkrTooFzuHDj6bwIjojR1fx5/03G9e25sauhkvvBUF0eCHb5LiV/Co1v42TQteMA9lK7HiiAdWJCoQ@iajwY0Pa9pKE9aJsLICxBQk0uPl7JoEmDM7qNo/k2ShKuubSOX3jqY2LQSTWrOBUCnNeWzefj/nzcItVJWRZI2GGZDGpRwHwLPIRa4BKzaR2jUBnPyfhEobj4IfbGQy6/h9mIRgs3uMbVnzuBFw "Python 3 – Try It Online") This one requires the input to be a numpy array. # [Python 3](https://docs.python.org/3/) NumPy (builtin), 26 bytes ``` from numpy import* argsort ``` [Try it online!](https://tio.run/##TYtNDoIwEIX3c4oJKzADQdCNSblIw6JE0SbQNi0aOIcLN5yOi2AFjK7e9/7M0N20yue5trpFdW/NgLI12nY7EPbqPMw12wjWBt3goNYWG5TqYxLXnaU6AQqqkGErTHh5iIaaxJlGdmEQF0EUAfaM7@pQRCWgsVL5Yhpf0/gMeM9YVZKgnqpo5mmJcYFegKe0p2yzCwLPvG6LFYH74hf53XL05feYLdGyoiMdKP/bbsEb "Python 3 – Try It Online") [Answer] # Builtin solutions ### APL / BQN, 1 byte ``` ⍋ ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TbDQA&f=e9Q31dP/UdsEA640BR0QYaBgqGAEpI2ANIgP5ClAxIEiML6CqYKJgjEA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f) / [Run with BQN!](https://mlochbaum.github.io/BQN/try.html#code=RuKGkOKNiwoK4p+oCkYg4p+oMOKfqQpGIDDigL8x4oC/MgpGIDLigL8x4oC/MApGIDHigL8y4oC/MApGIDDigL8y4oC/MQpGIDHigL8y4oC/MOKAvzXigL804oC/Mwrin6k=) ### [J](http://jsoftware.com/), 2 bytes ``` /: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/9a3@a3KlJmfkO6QpqOnZKRhYGygYKhhZGwFJA2sgCywC5EHYCqYKJgrG/wE "J – Try It Online") ### [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` Ụ ``` [Try it online!](https://tio.run/##y0rNyan8///h7iX/D7c/alrz/3@0YayOQrShjoKRjoIxiGkMZoJFQUJQpiGYaYQkqqNgpqNgqqNgEgsA "Jelly – Try It Online") (1-indexed) [Answer] # [Factor](https://factorcode.org/), 8 bytes ``` arg-sort ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpYmpqXnFqsl1pRUpRYrFBQlFpSUllQlJlXomDNxVWtYKhgpGCgYKpgomCsUPs/sShdtzi/qOS/3n8A "Factor – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 16 bytes ``` p->vecsort(p,,1) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmD7v0DXriw1uTi/qESjQEfHUPN/YkFBTqVGgYKunUJBUWYeUFhBCcRRUkjTKNDU1FGIjjaMBZKGOkY6xiCGMZABFgHydaBSQDG4iI6ZjqmOSWys5n8A "Pari/GP – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` \d+ $* (?<=(?=(1*,)*(?<-2>1)*(?(2)^)(?!1))^(1*,)*)1* $#1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0vD3sZWw95Ww1BLR1MLyNE1sjMEMTSMNOM0NewVDTU14yCSmoZaXCrKhv//G3AZ6BjqGHEZAUkDLiBLByQC5EHYOqY6JjrGAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` 1* ``` For each element... ``` (?<=^(1*,)*) ``` ... find its index, ... ``` (?=(1*,)*(?<-2>1)*(?(2)^)(?!1)) ``` ... then find the index of the element with that as its value. ``` $#1 ``` Replace the element with that index (in decimal). [Answer] # [Julia 1.0](http://julialang.org/), 8 bytes ``` sortperm ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/vzi/qKQgtSj3v2KFbUFRZl5JTp5GhZ62oYKtnQJMDiygqcnFpRhtEAsidAx1jEAMIyADLALk60ClgGJwER1THRMd49j/QG0KunYKIN1QzRAuxByoMWAhqIlQA6FCBiAjoUZDNYJtQbEEoRYqAAA "Julia 1.0 – Try It Online") 1-indexed [Answer] # [flax](https://github.com/PyGamer0/flax), 1 byte ``` ⍋ ``` Builtin \o/ Unlike Jelly, flax is 0-indexed. [Answer] # [Desmos](https://desmos.com/calculator), 20 bytes ``` f(l)=sort(sort(l),l) ``` [Try It Desmos!](https://www.desmos.com/calculator/dufhphziaj) [Try It Desmos! - Prettified](https://www.desmos.com/calculator/gdej6nc7n2) [Answer] # x86-64 machine code, 11 bytes ``` 8B 04 96 89 14 87 FF CA 79 F6 C3 ``` [Try it online!](https://tio.run/##TVJNb@MgED2bXzH1qlsc0yhN0qqKN730vJc9reT4QAEnVA6OALeOLP/19Q50E@0FeB/zZsAWp9P9Xohp4u4IFH6llMz3TfvGG6iZJXaTHNsPULxnUFqn8/XMyr4ikS2tjATvKwZK9qTeJFKJeEzejQNLEqs8yVLICqJ6r6yB9DWF4aPVEmqqjYeZZSBa4zxExFncTVZANFmaFSMh37QRTScV/HBe6nZ@eCHEee61AOdtJzx45bzgTsEQ64sYw8vnCssvmisr2MJAhgc2LMaRkWGFB/bAlhewRHBVkGf/2VCL4Omfwh7Zmq0CNRYkdDtybWhGBpLUrQX6dSve@Ra@e9hcJ3QZSdCThBKrXNf4MCUSNf2CDPychwVfIdAhLJg1Dr/Ai8HNNoh4ynPMSpKTRbmm6a2GlF0ydRWrT50XB27p3c7cBWIkV/vO/OTioI3CDyDVJg1y6NOHPgzOCGULw8UOt4vlb8w/byntjNN7oySE7Flms7LPc2w4wudBNwroOQy56F9XIfSaQHHCtzM@RLYzmNSjOE7TH1E3fO@m@@PTGhf8E7foV81f "C++ (gcc) – Try It Online") 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 an array of 32-bit integers; the address of the given permutation, as an array of 32-bit integers, in RSI; and the length of that array in EDX. The starting point is after the first 6 bytes. In assembly: ``` r: mov eax, [rsi+4*rdx] # Load the entry at index EDX into EAX. mov [rdi+4*rax], edx # Store the value of EDX into the result array at index EAX. f: dec edx # (Start here.) Count down from the length in EDX. jns r # Jump back if it isn't negative. (This will iterate from n-1 to 0.) ret # Return. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {k ``` 0-based. [Try it online](https://tio.run/##yy9OTMpM/f@/Ovv//2hDHSMdAx1THRMd41gA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/@rs/zr/o6MNYnUUog10DHWMQAwjIAMsAuTrQKWAYnARHVMdEx3j2FgA). **Explanation:** ``` { # Sort the (implicit) input-list k # Get the 0-based indices of each value in the (implicit) input-list # (after which the list is output implicitly as result) ``` [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` import Data.List f p=snd<$>sort(zip p[0..]) ``` [Try it online!](https://tio.run/##bc2xDoMgEIDhnae4waFNKEHbbtWpY9/AMJBYU1LFizD58hT0EoPpeD93fB/tvu9hCMGMOM0entpr8TLOsx6wdrZ7FI2LD6fFIGArhVDnMGpjoYZuYoCzsR4K6KGVCvKZl7xSWapiknmKO8ckYyr/bPE7v/GrCkm6NAlkhGzj5hGyJvIIoSTT54TQ4eplyL5L4Qc "Haskell – Try It Online") Alternative 47 bytes using association list. * saved 7 Bytes thanks to @Unrelated String * added a maybe() to convert *maybe int* to just *int*, if a *just int* is acceptable it can be 37 Bytes. ``` f p|i<-zip p[0..]=maybe 0id.(`lookup`i).snd<$>i ``` [Try it online!](https://tio.run/##bc2xDoIwEMbxvU9xA4MmR9OCbMCLNE2oKcQLhTagg8Z3rzW61Dh@v/sndzH7PDoX4wThSW35oABBCc51t5j7eQRBlh8G5/18CwMd@b7atugpLoZW6MB6BmGj9QoFTKCEhnyjxEpnVCUSOaXml0Qi@afCBk9Y65gtKHtgn19YJ2k0Y@p9lt/gBQ "Haskell – Try It Online") [Answer] # Python3, 27 bytes ``` def f(l):return l.argsort() ``` [Try it online!](https://tio.run/##Dcg7DoAgDADQ3VMwtoYYP5tXMQ4kgpJAIbUMnL76xle7PIU21csHEyDhzl4ak0mT4/stLIAauGRDLdduYq7/jUPlSAIBHLPrcCx2tfOJiPoB) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 1 byte ``` ⇧ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6ciLCIiLCJbMSwyLDBdIl0=) I suppose grading the list up also works. ## [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes ``` Ṗ'2(?~İ)⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZYnMig/fsSwKeKBvCIsIiIsIlswLDIsMV0iXQ==) ## Explained ``` Ṗ'2(?~İ)⁼ Ṗ # From all permutations of the input ' # Keep those where 2( # Getting the result of ?~İ # [input[x] for x on tos] ) # twice ⁼ # equals the original item. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` IEθ⌕θκ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexQKNQR8EtMy8FRGdrAoH1///R0YY6RjoGOqY6JjrGsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ Input array E Map over elements ⌕ Find index of κ Current index θ In input array I Cast to string Implicitly print ``` ]
[Question] [ Given a non-negative integer, \$n\$, yield the \$(n^2)^\text{th } n\$-gonal number. ### Further Detail: The \$x\$-gonal numbers, or *polygonal numbers*, are also known as the *two-dimensional figurate numbers*. Many people will be familiar with the triangular numbers, these are the \$3\$-gonal numbers: $$F(3,n)=\sum\_{i=1}^{n}(i)=\frac{n(n+1)}{2}$$ The triangular numbers are [OEIS A000217](https://oeis.org/A000217): ``` 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, ... ``` Probably even more will be familiar with the square numbers, these are the \$4\$-gonal numbers: $$F(4,n)=\sum\_{i=1}^{n}(2i-1)=n^{2}$$ The square numbers are [OEIS A000290](https://oeis.org/A000290): ``` 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, ... ``` In general the \$k^\text{th }x\$-gonal number is the number of pebbles required to iteratively build up an \$x\$-sided polygon by adding pebbles to \$x-2\$ of the sides, here are a few formulae: \begin{align} F(x,k)&=\sum\_{i=1}^{k}\left(1+\sum\_{j=2}^{i}(x-2)\right) \\ &=\frac{k^2(x-2)-k(x-4)}{2} \\ &=\frac{k(k-1)}{2}(x-2)+k\\ &=(x-3)\sum\_{i=1}^{k-1}(i)+\sum\_{i=1}^{k}(i)\\ &=(x-2)(k-1)+1+F(x,k-1) \end{align} I'm sure there are plenty more. Note that the last one is recursive but that \$F(x,0)=0\$. ### The challenge ...is to golf code for \$G(n)=F(n,n^2)\$ for non-negative \$n\$. i.e. Given a non-negative integer, \$n\$, yield the \$(n^2)^\text{th } n\$-gonal number. This is not (currently) in the OEIS: ``` 0, 1, 4, 45, 256, 925, 2556, 5929, 12160, 22761, 39700, 65461, 103104, 156325, 229516, 327825, 457216, 624529, 837540, 1105021, ... ``` ### Notes You may yield a list of these numbers up to and including the required one if preferred. For example, given an input of `5` you may yield either: * the integer `925`, or * the list `[0, 1, 4, 45, 256, 925]` * ...**but not `[0, 1, 4, 45, 256]` or `[1, 4, 45, 256, 925]`** Results may also be results of floating point calculation and may deviate as such, so long as infinite precision floating point arithmetic would yield correct results. --- Win by creating the shortest code in bytes in a language. The overall winner will be the shortest across all languages, but please don't let golfing languages dissuade you from entering in your favourite language - the primary goals are to challenge yourself and have fun! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` #(4-#-2#^2+#^3)#/2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8V9Zw0RXWddIOc5IWznOWFNZ30jtv6Y1V0BRZl5JtLKCrp1CmoNyrJq@Q1BiXnpqtIGOoUHsfwA "Wolfram Language (Mathematica) – Try It Online") Just a golfy version of the second formula. ## With [`PolygonalNumber`](http://reference.wolfram.com/language/ref/PolygonalNumber.html) built-in, 23 bytes ``` PolygonalNumber[#,#^2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T8gP6cyPT8vMcevNDcptShaWUc5zihW7b@mNVdAUWZeSbSygq6dQpqDcqyavkNQYl56arSBjqFB7H8A "Wolfram Language (Mathematica) – Try It Online") As expected, the Mathematica built-in is longer than the golfed version. [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` ᛦℙ ``` [Try it online!](https://tio.run/##y0vNzP3//@HsZY9aZv7/bwoA "Neim – Try It Online") ¯\\_(ツ)\_/¯ First Neim answer, right tool for the job. By the way, the advice I give on my *About me* page still holds for my own posts: [Don't upvote trivial solutions, please](https://codegolf.meta.stackexchange.com/questions/10127/how-can-we-help-users-who-are-put-off-by-the-use-of-golfing-languages/10132#10132). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ²Ḷ×_2$‘S ``` [Try it online!](https://tio.run/##y0rNyan8///Qpoc7th2eHm@k8qhhRvD///8tAQ "Jelly – Try It Online") In short, it generates the range \$[0,1,2,\dots,(n-1)^2]\$, multiplies every integer in that range with \$n-2\$, increments each of them (to avoid adding \$n^2\$ at the end, saving 1 byte), then sums the resulting list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` nsÅU ``` [Try it online!](https://tio.run/##yy9OTMpM/W9ocHhuWaW9koKunYKSfWXl/7ziw62h/21r/wMA "05AB1E – Try It Online") [Answer] # Pyth, ~~14~~ 9 bytes ``` smh*d-Q2* ``` [Try it online!](https://tio.run/##K6gsyfj/vzg3QytFN9BI6/9/UwA) [Answer] # [Python 2](https://docs.python.org/2/), ~~31~~ 30 bytes ``` lambda k:(k*k*(k-2)-k+4)*k*k/2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHbSiNbK1tLI1vXSFM3W9tEE8jJ1gcqyS9SyFTIzFMoSsxLT9UwNNC04lIoKMrMK1HI1EnTyNT8DwA "Python 2 – Try It Online") --- Saved: * -1 byte, thanks to joH1 [Answer] # JavaScript (ES7), 26 bytes ``` n=>n**4*(n-2)-n*n*(n-4)>>1 ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i5PS8tESyNP10hTN08rD8Qy0bSzM/yfnJ9XnJ@TqpeTn66RpmGpqfkfAA "JavaScript (Node.js) – Try It Online") --- # Recursive (ES6), 33 bytes A quick attempt from mobile. Not really optimized for \$(n,n^2)\$. ``` x=>(g=k=>k&&(x-2)*--k-~g(k))(x*x) ``` [Try it online!](https://tio.run/##BcExDoAgDADA35CWpA5uDuUvBIFoCTViTCe/jndnfONI93E91HXPs/A0DlBZOIhzYLSiJxL6KggimDecSfvQlpemFQpsiPMH "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` I⊘↨⟦¹±²±¹¦⁴¦⁰¦⁰⟧N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyMxpyw1RcMpsThVI9pQR8EvNT2xJFXDSBPONAQyTXQUDIAoVkfBM6@gtMSvNDcptUhDEwSs//83/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses the second formula expanded into the polynomial \$ \frac{1}{2} ( x^5 - 2x^4 - x^3 + 4x^2 ) \$ which is calculated by treating it as an arbitrary base conversion before halving and casting to string for implicit output. [Answer] # [cQuents](https://github.com/stestoltz/cQuents/tree/cquents-0), 20 bytes ``` $0:$$+$$/2($$-1)($-2 ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/X8XASkVFW0VF30hDRUXXUFNDRdfo/38A "cQuents 0 – Try It Online") ## Explanation ``` $0 Zero indexing : Mode: sequence (output nth term) Each term equals: $$+ index * index + $$/2 index * index / 2 * ($$-1)($-2 (index * index - 1) * (index - 2 ) ) implicit ``` [Answer] # [Physica](https://github.com/Mr-Xcoder/Physica), 25 bytes ``` ->n:(n^4-n^2)/2*(n-2)+n^2 ``` [Try it online!](https://tio.run/##K8ioLM5MTvzvZhvzX9cuz0ojL85ENy/OSFPfSEsjT9dIUxvI@R9QlJlXEu0W7ZlXUFqiEhv73xIA "Physica – Try It Online") --- ``` ->n:n^2*(4-n-2*n^2+n^3)/2 ``` [Try it online!](https://tio.run/##K8ioLM5MTvzvZhvzX9cuzyovzkhLw0Q3T9dIC8jUzosz1tQ3@h9QlJlXEu0W7ZlXUFqiEhv73xIA "Physica – Try It Online") --- ``` ->n:n^5/2-n^4-n^3/2+2*n*n ``` [Try it online!](https://tio.run/##K8ioLM5MTvzvZhvzX9cuzyovzlTfSDcvzgSIjfWNtI208rTy/gcUZeaVRLtFe@YVlJaoxMb@twQA "Physica – Try It Online") | **[Try all of them at once as a test suite!](https://tio.run/##K8ioLM5MTvz/31HBVkHXLs9KIy/ORDcvzkhT30hLI0/XSFMbyOFygsoC2VoaQHldIy0gEyhlDFTH5QyXNdU30oUYYKxvpA1UpJXHxeWWX6TgqfCoo0Mh2kDhUcMyBUODWCsuzoCizLyS6OCSomjPWL2crNLikmjjWGsFJaBRStYKIHFHB7iMoWksRMwJi5gziljs//8A "Physica – Try It Online")** [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 38 bytes ``` import StdEnv $x=x^2*(x^3/2-x^2-x/2+2) ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLpcK2Is5IS6MizljfSBfI1K3QN9I20vwfXJIIVGWroKJg@v9fclpOYnrxf11Pn/8ulXmJuZnJxQA "Clean – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 17 bytes ``` ×⍨×2+×⍨-⍨.5×*∘3-⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TD0x/1rjg83UgbzNAFYj3Tw9O1HnXMMNZ91LUIqEjh0IpHvZsNDQA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 bytes ``` ²µ½_2×’H×+ ``` [Try it online!](https://tio.run/##ASoA1f9qZWxsef//wrLCtcK9XzLDl@KAmUjDlyv/UjA7w4figqw7IkAkR///MTA "Jelly – Try It Online") Uses the formula \$F(x,k)=\frac{k(k-1)}{2}(x-2)+k\$ as given in the challenge. [Answer] # [MATL](https://github.com/lmendo/MATL), 9 bytes ``` U:qG2-*Qs ``` [Try it online!](https://tio.run/##y00syfn/P9Sq0N1IVyuw@P9/cwA "MATL – Try It Online") This uses [Mr. Xcoder's Jelly approach](https://codegolf.stackexchange.com/a/171257/36398). [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 23 bytes ``` {((x-2)*k%2%k-1)+k:x*x} ``` [Try it online!](https://tio.run/##y9bNz/7/P82qWkOjQtdIUytb1Ug1W9dQUzvbqkKrovZ/mrqikcF/AA "K (oK) – Try It Online") Prefix function; implementation of the second formula: \$\frac{k(k-1)}{2}(x-2)+k\$ ### How: ``` {((x-2)*k%2%k-1)+k:x*x} # Main function, argument x. k:x*x # def k = n² ((x-2)*k%2%k-1)+ # calculate k + (((k/2)/(k-1))*(x-2)) ``` [Answer] # Haskell (31 bytes) ``` g k=(k*k*k*k*(k-2)-k*k*(k-4))/2 ``` [Answer] # [Haskell](https://www.haskell.org/), 27 bytes ``` f k=(k^4*(k-2)-k^2*(k-4))/2 ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00h21YjO85ESyNb10hTNzvOCMQy0dTUN/qfm5iZp2CrUFCUmVeioKKQpmBo8B8A "Haskell – Try It Online") My first attempt at golfing in Haskell, basically same as almost any answer : Nothing worth explaining here. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~60~~ ~~36~~ 34 bytes -24 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/questions/171235/find-the-leftn2-right-textth-n-gonal-number#comment413854_171460) -2 bytes by factorizing again an `n*n` expression. ``` g(n){return(n*n*(n-2)-n+4)*n*n/2;} ``` [Try it online!](https://tio.run/##jc/LCoMwEIXhdX2KIaWQ2NqLN6iWPokbm6QxEEfRpBTEZ7cB6d7l8A8fHB4pzpe9Rm6ckPAYrdDduXkuiiKbBmndgBRDDClGMYvwmDJ/4CUu50WjhbbWSD@dFgymYNc7O1Jytw0kkeqwNoCufcmBsHKNAJTIby@5lQKggDRb0@CtNyW8NtyZ2scCDqLCCskJFE2Yf/rrt9zz6TY@zvItfrr661q4lsG8/AA "C (gcc) – Try It Online") Factored version of the second formula, uses a single function. Entry point is function `g(n)`, value is returned as integer. [Answer] # [Ruby](https://www.ruby-lang.org/), 25 bytes ``` ->n{(4-n+(n-2)*n*=n)*n/2} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWsNEN09bI0/XSFMrT8s2D0jqG9X@1zDQ0zM00NTLTSyorqmoKVBIi66Irf0PAA "Ruby – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), 4 bytes ``` Đ²⇹ᑭ ``` [Try it online!](https://tio.run/##K6gs@f//yIRDmx6173w4ce3//9GGOkY6xjomOqaxAA "Pyt – Try It Online") ### Explanation: ``` Implicit input Đ Duplicate ² Square ⇹ Swap top two elements on the stack ᑭ Get the (n^2)th n-gonal number Implicit output ``` ]
[Question] [ Write the shortest function that returns the content of the first result of a Google search ("I'm feeling lucky"). Example: ``` lucky('cat'); ``` Might return something like: ``` <!DOCTYPE html> <html> <head> <title>Cats are cool</title> <meta charset="utf-8" /> </head> <body> <h1>CAAAAAAAAAAATSSSSSSSSSS!!!!!!!!</h1> <p> Cats are so cool! </p> </body> </html> ``` [Answer] # Bash, 46 bytes ``` l()(wget -UM -qO- "gogle.de/search?btnI&q=$1") ``` Uses the actual *I'm feeling lucky* feature, just like the other answers. Gogle blacklists some user agents (including WGet's, cURL's and Java's), but **M** seems to work just fine. [Answer] # Ruby, 79 / 145 I borrowed the `btnI` trick from @rink.attendant.6 for this solution. Thanks Beta Decay for shortening it by 2 characters. ``` require'open-uri' f=->q{URI(URI.escape"http://gogle.de/search?btnI&q="+q).read} ``` I also have a solution which actually gets the first result from the results page, which is 145 bytes. ``` require'open-uri' f=->q{open(URI.extract(URI(URI.escape"http://google.com/search?q=#{q}").read.split('class="r"')[1])[0].split("&amp;")[0]).read} ``` [Answer] ## PHP, ~~157~~ ~~105/87~~ ~~102/87~~ 100/85 ### Using [`file_get_contents`](https://php.net/manual/en/function.file-get-contents.php) ``` <?php function l($q){return file_get_contents("https://google.ca/search?btnI&q=".rawurlencode($q));} ``` Without allowing for spaces in the search term it's only 87 characters: ``` <?php function l($q){return file_get_contents("https://google.ca/search?q=$q&btnI");} ``` ### Original versions using [cURL](https://php.net/manual/en/book.curl.php) I suppose that short array syntax can be used on PHP 5.4+: ``` <?php function l($q){$ch=curl_init("https://google.ca/search?btnI=1&q=".rawurlencode($q));curl_setopt_array($ch,[19913=>1,52=>1]);return curl_exec($ch);} ``` Otherwise it's five more characters with the normal array initializer, 162: ``` <?php function l($q){$ch=curl_init("https://google.ca/search?btnI=1&q=".rawurlencode($q));curl_setopt_array($ch,[19913=>1,52=>1]);return curl_exec($ch);} ``` Version that **does not allow spaces in the search term**: No need for URL encoding (138): ``` <?php function l($q){$ch=curl_init("https://google.ca/search?q=$q&btnI=1");curl_setopt_array($ch,[19913=>1,52=>1]);return curl_exec($ch);} ``` Ungolfed using constants ``` <?php function l($q){ $ch = curl_init("https://google.ca/search?btnI=1&q=" . rawurlencode($q)); curl_setopt_array($ch, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1 )); return curl_exec($ch); } ``` [Answer] ## C#, ~~183~~ ~~180~~ 178 This is my first time ever writing code in C# so it could probably use improvement. Feedback is welcome! ``` string l(string q){return System.Text.Encoding.UTF8.GetString((new System.Net.WebClient()).DownloadData("https://google.ca/search?btnI&q="+System.Web.HttpUtility.UrlEncode(q)));} ``` ### Unminified ``` string l(string q) { return System.Text.Encoding.UTF8.GetString( (new System.Net.WebClient()).DownloadData( "https://google.ca/search?btnI&q=" + System.Web.HttpUtility.UrlEncode(q) ) ); } ``` [Answer] ## CJam, 40 bytes Thought, I'll finally give the `g` method a try ``` {"gogle.de/search?btnI&q="\S/"%20"*+g}:F ``` This creates a method/block `F` which can be used like ``` {"gogle.de/search?btnI&q="\S/"%20"*+g}:F; "cats and dogs"F ``` This is how functions work in CJam .. Doesn't work in online interpreter, so you will have to [download and use](http://sourceforge.net/p/cjam/wiki/Home/) the Java one. Note that Google denies all requests with Java user agent, so you will have to start CJam with an additional flag `-Dhttp.agent=M` [Answer] # Python 3 - 78 Uses `gogle.de` for brevity. Run as `f(query)`. ``` f=lambda x:__import__("requests").get("http://gogle.de/search?btnI&q="+x).text ``` If you want to have spaces in your query it's 98 characters. ``` f=lambda x:__import__("requests").get("http://gogle.de/search?btnI&q="+x.replace(" "," %20")).text ``` ]
[Question] [ Given a word list, find all sets of five words of five letters each, such that the words of each set have 25 distinct letters in total. This challenge was inspired by [this](https://www.youtube.com/watch?v=c33AZBnRHks&t=1424s) video by Matt Parker. ### Testcases Use [this file](https://github.com/dwyl/english-words/blob/master/words_alpha.txt) if you want to test your code against the English vocabulary. Sample output sets: * `["fjord", "vibex", "waltz", "nymph", "gucks"]` * `["fjord", "vibex", "waltz", "gymps", "chunk"]` [Here](https://pastebin.pl/view/abd25c9d)'s a shorter version of the same file, with only words of five letters and no repeated letters. [Here](https://pastebin.pl/view/84e373d5)'s an even shorter version with just 2000 words. ### Rules * Standard I/O rules apply. * Words contain only lowercase (or alternatively, uppercase) alphabetic characters. * You can assume there are no empty words (i.e. words of length zero). * The input can contain words that cannot belong to any set that satisfies the property, such as words with less than five letters, words with more than five letters, and words with repeated letters. * You do not need to output every permutation of each valid set/list of five words. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins [Sandbox](https://codegolf.meta.stackexchange.com/a/25245/73593) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes ``` 'L5=;5ḋ'∑Þu ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInTDU9OzXhuIsn4oiRw551IiwiIiwiW1wiZmpvcmRcIiwgXCJ2aWJleFwiLCBcIndhbHR6XCIsIFwibnltcGhcIiwgXCJndWNrc1wiLCBcImd5bXBzXCIsIFwiY2h1bmtcIiwgXCJhYmNcIl0iXQ==) Get all 5 letter words, and all 5 word combinations where all the letters are unique. ## Explained ``` 'L5=;5ḋ'∑Þu 'L5=; # keep only words that are length 5 5ḋ # combinations without replacement of size 5 '∑Þu # keep only those where the sum of all strings has all unique letters ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 5ù5.ÆʒJDÙQ ``` Outputs as a list of lists. [Try it online.](https://tio.run/##yy9OTMpM/f/f9PBOU73Dbacmebkcnhn4/3@0UnJ@SqqSjoJSen5OGojOSM3JyQcxyvOLclJAjLSs/CIwoywzKbUCLJWYU1IFYuRV5hZkgHWXJmcXgxlAETAjOaM0LxvMyM9NysxLLMnMzwNLJCYlQ2wEMkBURWWVUiwA) **Explanation:** ``` 5ù # Keep all words of the (implicit) input-list of length 5 5.Æ # Get all 5-element combinations of the remaining words ʒ # Filter this list of quintuplets by: J # Join the five words together to a single string DÙQ # Check that all characters are unique: D # Duplicate the string Ù # Uniquify its characters Q # Check if the two strings are still the same # (after which the filtered list of quintuplets are output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~14~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) [12 bytes](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=bDUg4DUgbaxmyLbi&input=WyJnaXZlbiIsImEiLCJ3b3JkIiwibGlzdCIsImZpbmQiLCJhbGwiLCJzZXRzIiwib2YiLCJmaXZlIiwid29yZHMiLCJsZXR0ZXJzIiwiZWFjaCIsInN1Y2giLCJ0aGF0IiwidGhlIiwic2V0IiwiaGF2ZSIsImRpc3RpbmN0IiwiaW4iLCJ0b3RhbCIsInRoaXMiLCJjaGFsbGVuZ2UiLCJ3YXMiLCJpbnNwaXJlZCIsImJ5IiwidmlkZW8iLCJtYXR0IiwicGFya2VyIiwidGVzdGNhc2VzIiwidXNlIiwiZmlsZSIsImlmIiwieW91Iiwid2FudCIsInRvIiwidGVzdCIsInlvdXIiLCJjb2RlIiwiYWdhaW5zdCIsImVuZ2xpc2giLCJ2b2NhYnVsYXJ5Iiwic2FtcGxlIiwib3V0cHV0IiwiZmpvcmQiLCJ2aWJleCIsIndhbHR6IiwibnltcGgiLCJndWNrcyIsImd5bXBzIiwiY2h1bmsiLCJoZXJlIiwicyIsInNob3J0ZXIiLCJ2ZXJzaW9uIiwic2FtZSIsIndpdGgiLCJvbmx5IiwiYW5kIiwibm8iLCJyZXBlYXRlZCIsImFuIiwiZXZlbiIsImp1c3QiLCJydWxlcyIsInN0YW5kYXJkIiwiaSIsIm8iLCJhcHBseSIsImNvbnRhaW4iLCJsb3dlcmNhc2UiLCJvciIsImFsdGVybmF0aXZlbHkiLCJ1cHBlcmNhc2UiLCJhbHBoYWJldGljIiwiY2hhcmFjdGVycyIsImNhbiIsImFzc3VtZSIsInRoZXJlIiwiYXJlIiwiZW1wdHkiLCJlIiwibGVuZ3RoIiwiemVybyIsImlucHV0IiwiY2Fubm90IiwiYmVsb25nIiwiYW55Iiwic2F0aXNmaWVzIiwicHJvcGVydHkiLCJhcyIsImxlc3MiLCJ0aGFuIiwibW9yZSIsImRvIiwibm90IiwibmVlZCIsImV2ZXJ5IiwicGVybXV0YXRpb24iLCJ2YWxpZCIsImlzIiwiZ29sZiIsInNvIiwic2hvcnRlc3QiLCJieXRlcyIsIndpbnMiLCJzYW5kYm94Il0tUg) if the words in each set do not need to be delimited. ``` l5 à5 fȬ¶X¬â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=bDUg4DUgZsistlis4g&input=WyJnaXZlbiIsImEiLCJ3b3JkIiwibGlzdCIsImZpbmQiLCJhbGwiLCJzZXRzIiwib2YiLCJmaXZlIiwid29yZHMiLCJsZXR0ZXJzIiwiZWFjaCIsInN1Y2giLCJ0aGF0IiwidGhlIiwic2V0IiwiaGF2ZSIsImRpc3RpbmN0IiwiaW4iLCJ0b3RhbCIsInRoaXMiLCJjaGFsbGVuZ2UiLCJ3YXMiLCJpbnNwaXJlZCIsImJ5IiwidmlkZW8iLCJtYXR0IiwicGFya2VyIiwidGVzdGNhc2VzIiwidXNlIiwiZmlsZSIsImlmIiwieW91Iiwid2FudCIsInRvIiwidGVzdCIsInlvdXIiLCJjb2RlIiwiYWdhaW5zdCIsImVuZ2xpc2giLCJ2b2NhYnVsYXJ5Iiwic2FtcGxlIiwib3V0cHV0IiwiZmpvcmQiLCJ2aWJleCIsIndhbHR6IiwibnltcGgiLCJndWNrcyIsImd5bXBzIiwiY2h1bmsiLCJoZXJlIiwicyIsInNob3J0ZXIiLCJ2ZXJzaW9uIiwic2FtZSIsIndpdGgiLCJvbmx5IiwiYW5kIiwibm8iLCJyZXBlYXRlZCIsImFuIiwiZXZlbiIsImp1c3QiLCJydWxlcyIsInN0YW5kYXJkIiwiaSIsIm8iLCJhcHBseSIsImNvbnRhaW4iLCJsb3dlcmNhc2UiLCJvciIsImFsdGVybmF0aXZlbHkiLCJ1cHBlcmNhc2UiLCJhbHBoYWJldGljIiwiY2hhcmFjdGVycyIsImNhbiIsImFzc3VtZSIsInRoZXJlIiwiYXJlIiwiZW1wdHkiLCJlIiwibGVuZ3RoIiwiemVybyIsImlucHV0IiwiY2Fubm90IiwiYmVsb25nIiwiYW55Iiwic2F0aXNmaWVzIiwicHJvcGVydHkiLCJhcyIsImxlc3MiLCJ0aGFuIiwibW9yZSIsImRvIiwibm90IiwibmVlZCIsImV2ZXJ5IiwicGVybXV0YXRpb24iLCJ2YWxpZCIsImlzIiwiZ29sZiIsInNvIiwic2hvcnRlc3QiLCJieXRlcyIsIndpbnMiLCJzYW5kYm94Il0tUg) (Test case borrowed from Neil) ``` l5 à5 fȬ¶X¬â :Implicit input of word array l5 :Filter words of length 5 à5 :Combinations of length 5 f :Filter by È :Passing each X through the following function ¬ : Join ¶ : Is equal to X¬ : Join X â : Deduplicate ``` [Answer] # [Python](https://www.python.org), ~~87~~ 113 bytes (+26 for word length filter) i'm really interested in knowing if there's a way i could golf the 5-letter word length filter. ``` lambda x:[i for i in combinations([j for j in x if len(j)==5],5)if len({*''.join(i)})==25] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Lc1BboMwEAXQfU4xYoONaBeVkKpI3CF7wsIQHMbBM8SYlrTqSbJBito75TaNCat58780c_3rL75lmm863_-OXr-838-dstVBwbQtEDQ7QECCmm2FpDwyDaIwS2FCMQFq6BoSRuZ5VqaZXPfvJI5fDSMJlD-P7i0rN9qxBfSN88zdAGh7dj5ZH-96h-SFFkWkDbtDlEL0gVUzBXyqzn8F0MX2bcBxrE_DgkeyoG5HOgWoqo5KKZ935_k5_wE) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ẉẹ5ịœc5FQƑ$Ƈ ``` [Try it online!](https://tio.run/##y0rNyan8///hro6Hu3aaPtzdfXRysqlb4LGJKsfa/x9u937UtCby//9opbSs/KIUJR0FpbLMpNQKEKM8MaekCsTIq8wtyAAx0kuTs4vBDKAImJGcUZqXDWIkJiWnpEIZIKqiskopFgA "Jelly – Try It Online") Outputs the sets of words. [-1 byte](https://tio.run/##y0rNyan8///hro6Hu3aaPtzd/XDndFO3wGMTVY61/z/c7v2oaU3k///RSmlZ@UUpSjoKSmWZSakVIEZ5Yk5JFYiRV5lbkAFipJcmZxeDGUARMCM5ozQvG8RITEpOSYUyQFRFZZVSLAA) to output all permutations. ## How it works ``` Ẉẹ5ịœc5FQƑ$Ƈ - Main link. Takes a list of words W on the left Ẉ - Lengths of each word ẹ5 - Indexes of 5s ị - Index into W œc5 - All combinations without replacement of 5 words $Ƈ - Filter by the following: F - when flattened... Ƒ - ...the list is unchanged after... Q - ...only keeping unique elements ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes ``` ⊞υωWSF⁼⁵Lι≔⁺υ⁺Φυ⬤ι¬№λνιυEΦυ⁼²⁵Lι⪪ι⁵ ``` [Try it online!](https://tio.run/##VVFBbtwwDLzzFT56ge2lQE45BUULFGiLAHkBbdOWGq2oipQ3zue3o0UO7cGyZXJmOMM5cJ2V0@323CyM7TxcT490DTHJMH7PpfmL15i38XQaVq3D@PVP42Tjw3n4IXnzMMYTSk9mccvjc2rWOe7vbzG51H59SmmM5@GX@vhFW/YxnYcM2Ok8xH40SD5DxcefXP7BfWh9/l/sPLyUFL0zPuD6eLttcZdMTFetC6VoTmvMC3FKZOJGuuLHLve6URIHv5HwHMgaDg/sOKR3U2B0LiCJeXaKmVydE8rRaA7gxCSgYkPNSqyy0HTQHhdRurA7Fa6vUsnFfGYTo2YC/SQUVzq0AZshp/eO/qPSrIsQbwxGJ/DDQ6BdZ55a4nqQ8aUAr82xEFp/d597nOQNXMnfKR@XEmhr86vRhu8@acuvFKTCFFnQCsu0w3bU3OngIHogzekgRlZZqUoRdtjhTNID/d0wTW0JFszRxFCNpMSlADVrdgxMSa9Su1HSisihk9mRNlpaKR8lTiXwJB7nnmHl@b6BGUps1jCN30dlPHIpfpBQum@c3qUqku6@0Z7VaZKkecOUPRePtkYMWKpCC0DuCzbrO810URAuSh2WBdbgC3Gi89IcWGSxc4qwhdw0rWT6ERacTwdeiCnDPtxP@ka3T3v6Cw "Charcoal – Try It Online") Link is to verbose version of code. Too slow for TIO with 2000 words so link uses the 106 "words" in the question at time of writing. Takes input as a list of newline-terminated words. Explanation: ``` ⊞υω ``` Start with the empty string. ``` WSF⁼⁵Lι ``` Loop over the input words of length `5`. ``` ≔⁺υ⁺Φυ⬤ι¬№λνιυ ``` Get all of the existing strings that have no overlap with this word, append the current word to all of those strings, and append the resulting strings to the list. ``` EΦυ⁼²⁵Lι⪪ι⁵ ``` Find all of the strings of length `25` and split them back into words. [Answer] # [JavaScript (V8)](https://v8.dev/), 88 bytes Prints the sets as space-separated strings. ``` f=([w,...a],o='')=>o[29]?new Set(o).size-26||print(o):w&&f(a,o,w.length-5||f(a,o+w+' ')) ``` [Try it online!](https://tio.run/##HctBDoMgEIXhqxgXIhFZmLRpm9geokvjAhUURcYoSmu8uy2s5sv/Mj3b2FLPcjLpdjtPkceFJZRSVhLIEcL5E4rsXr40t8GbmxgwXeTO0@x6HNMstSsPG0UiZgSIpYrr1nTp5Th8SWyCAoTxKeIirKHhIQnCFpRwt@NKgYOFWTUOoofZY5MV//iJKbM76O84df57rYfF41886m7VgweMldTMSNBLWOLzBw "JavaScript (V8) – Try It Online") ### Commented ``` f = ( // f is a recursive function taking: [w, // w = next word from the input array ...a], // a[] = array of remaining words o = '' // o = output set, as a string ) => // o[29] ? // if we have 5 x 6 characters in o: new Set(o) // turn o into a set .size - 26 // if its size is 26 (space included), || print(o) // print the output set : // else: w && // if w is defined, f( // do a 1st recursive call: a, // pass a[] unchanged o, // pass o unchanged w.length - 5 // if the word has 5 characters, || f( // do a 2nd recursive call: a, // pass a[] unchanged o + w + ' ' // append w and a space to o ) // end of recursive call ) // end of recursive call ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` f{IsT.cfq5lTQ5 ``` [Try it online!](https://tio.run/##K6gsyfj/P63aszhELzmt0DQnJND0//9opbSs/KIUJR0FpbLMpNQKEKM8MaekCsTIq8wtyAAx0kuTs4vBDKAImJGcUZqXDWLA6ES4aKFSLAA "Pyth – Try It Online") ### Explanation ``` # implicitly assign Q = eval(input()) f Q # filter Q on lambda T q5lT # length(T) == 5 .c 5 # all 5 element combinations of the filtered list f # filter on lambda T {IsT # T, concatenated to a single string is invariant under deduplicaiton ``` [Answer] # [Python](https://www.python.org), 104 bytes ``` lambda W:[w for w in combinations(W,5)if len({*chain(*w)})<<max(map(len,w))==800] from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TdFLbsIwEAZgdcspLFYJohKbSqiCc7CgLCaxkwz4hWPnQdWTdMOmVc_TXXuaZhTZahZf9MvOzDh-_7Sjb4y-f3GDnu3Zy0fw1eP2p5GgCg7s8HzsWWUc6xlqVhpVoAaPRrfZYf2UY8Wk0NnrqmwAdbbq87d8t1MwZApsNi2t-zzf77ebzWlROaMYeuG8MbJlqKxxfjX3-334tg61z2iM7Lhg07Oszsbx5XoOHRZiiKEH6W8x1KOybQxlE_QlhtYGkQrUMLWOwWEnfAxBG5m2tR60SNXMACkoQJ76SPQurRSidGMKwQuI4RpgTN844GhSn9KBTaWFxH9HQJ5KX_vpf6XaAY2FtJFXdXNOh5W3oeyKmKYJplGIkuCEICqiJhoCiTNxISShCE0YwhJXwhEt4YlAdERPDMRI0NWc8ny-2vt9fv8B) The direct port of the JS solution is shorter though :-( ``` def f(w=0,*R,g=""):len({*g})-26or print(g)if len(g)>29else w and(f(*R,g=g),len(w)-5or f(*R,g=g+w+" ")) ``` ]
[Question] [ Part of [**Advent of Code Golf 2021**](https://codegolf.meta.stackexchange.com/q/24068/78410) event. See the linked meta post for details. Related to [AoC2020 Day 13](https://adventofcode.com/2020/day/13), Part 2. [Why Bubbler isn't posting this](https://chat.stackexchange.com/transcript/message/59962414#59962414); [Why Riker isn't posting this](https://chat.stackexchange.com/transcript/message/59970481#59970481) --- A shuttle bus service runs between the sea port (where you are) to the airport (where you need to go). Each bus has an ID number that also indicates how often the bus leaves for the airport - more precisely, the number of minutes between the departure of two consecutive buses of that ID. Every bus departed at the same time some time in the past at the timestamp of zero. The shuttle company is running a contest: one gold coin for anyone that can find the earliest timestamp such that the first bus ID departs at that time and each subsequent listed bus ID departs at that subsequent minute. The list of bus IDs looks like this: ``` 7,13,x,x,59,x,31,19 ``` where `x` means "don't care". So the objective here is to find the timestamp `t` where: * Bus 7 departs at `t`. * Bus 13 departs at `t+1`. * Bus 59 departs at `t+4`. * Bus 31 departs at `t+6`. * Bus 19 departs at `t+7`. The earliest timestamp `t` for this list is 1068781. However, you suspect that the company won't want to give out any gold coins, because sometimes the list looks like this: ``` 7,7 ``` which is obviously impossible - Bus 7 cannot depart at `t` *and* `t+1` for any `t`. Given the list of Bus IDs, determine if you can earn a gold coin or not. **Input:** The list of bus IDs, possibly with some holes. A bus ID is always positive. A hole can be represented using any value that is not a positive integer (e.g. 0, -1, `"x"`); alternatively, you may represent holes by `1`, since they have the same effect (a `1` can always go anywhere). The list is guaranteed to be non-empty. **Output:** A value representing the answer. 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 The test cases use 0 for the holes in the list. Truthy: ``` [7, 13, 0, 0, 59, 0, 31, 19] [1, 2, 3, 4, 5] [0] [999] [1, 3, 5, 7, 9, 11, 13, 15] ``` Falsey: ``` [7, 7] [3, 1, 4, 1, 5, 9, 2] [4, 0, 4] ``` [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 45 bytes ``` a->i=1;iferr(chinese([Mod(i--,b)|b<-a])',e,1) ``` [Try it online!](https://tio.run/##NUxLDsIgEL3KpBshGRa0NA3R9gaeoGFBFZTEtATdmHh3HKgm83ufedGmIG4xexizFVMY5TF4lxK73MPqno7N5@3KghC48M9yEtbwAzqUPNsYH29mQUwQU1hfdDYFNOCZ5RxhngcE2VHX6nVdXUHakExHSxhBkViJMrT@i6T0CJRRHuUvqhqJG8res9UeX31toXdCGcPzFw "Pari/GP – Try It Online") Taking holes as 1. Tries applying the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) built-in. If it throws an error, the bus company is cheating. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` P+€TọµẠƇ ``` [Try it online!](https://tio.run/##ASYA2f9qZWxsef//UCvigqxU4buNwrXhuqDGh/9bMSwyLDMsNCw1XcOH/w "Jelly – Try It Online") Outputs an empty list for falsy. ``` P Product +€ Foreach, added to T 0...input length ọ Number of times each divides each - 0 for falsy µẠƇ Filter by all truthy ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~42~~ ~~38~~ 37 bytes ``` Head@ChineseRemainder[i=0;i++&/@#,#]& ``` [Try it online!](https://tio.run/##LUw9C4MwEN39G4JDfdKeUSQUS0qXjqUdpUOqETOYQd1E/3qaK4XjHe9z1MtgRr3YVvu@9nejO3UbrDOzeQbdus5Mja1PZ5umyVHFiN@Jf0zWLU2cXXoVqDpcP/P@arXb12itQAIZ8ZWSURBIbohWQg6BAiWTjBil/DsCJSpIEHGdfpEKFb9AQymsBTtnoeDVYos2/wU "Wolfram Language (Mathematica) – Try It Online") Input holes as `1`. Returns `Integer` for truthy, and `ChineseRemainder` for falsy. Another built-in. `ChineseRemainder` returns unevaluated if impossible (an integer if possible), so checking the head collapses these into two fixed values. --- Slightly less boring (**43 bytes**): ``` Sum[Mod[j--,],{,i=0;#},{,j=i++;GCD[,#]}]<1& ``` [Try it online!](https://tio.run/##LUzLCsIwELz3NwK9dAJu0xJCrQgKngShx5BDqRZTaAWpp5D@ekxEWGZ3dh5zvz4fc7/aoQ9jG7rPrK@vu544h4GDbXcN8/GYWlsUzeV01mDGmz3l4fa2y6oZP4xHZvKtG/plc5mTIAFOaWqVUBBIeWSOUEKgQp0Ip4RK/RWBGhIKRClOP4uETCvSGIptUS7To0qtlc98@AI "Wolfram Language (Mathematica) – Try It Online") Input holes as `1` or `-1`. Same approach as Neil's Charcoal answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` ⬤θ⬤θ⬤…·²ι∨∨﹪ιν﹪λν¬﹪⁻κμν ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxJ0ejUEcBifLMS84pLc4sSw1KzEtP1TDSUcjU1FHwL9IAIt/8lNKcfI1MHYU8oBiUlwPiAbl@@SUwBb6ZeaXFGtk6CrmaYEkwsP7/PzraWEfBUEfBBEya6ihY6igYxcb@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Accepts `-1` as a hole. Outputs a Charcoal boolean, i.e. `-` for possible, nothing for impossible. Explanation: Any factor common to two of the elements must also divide the difference in their indices, otherwise the application of the Chinese Remainder Theorem would fail at that point. ``` θ Input array ⬤ All elements satisfy θ Input array ⬤ All elements satisfy …· Inclusive range ² From literal integer `2` ι To outer value ⬤ All elements satisfy ν Potential factor ﹪ Does not divide ι Outer value ∨ Logical Or ν Potential factor ﹪ Does not divide ν Inner value ∨ Logical Or ν Potential factor ¬﹪ Divides κ Outer index ⁻ Minus μ Inner index Implicitly print ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 56 bytes ``` a=>eval("for(i=1+a.join``;a.some(n=>++x%n,x=i--)*i;);i") ``` [Try it online!](https://tio.run/##dY/vCoMgFMW/7ykkGOiyyP4QIvYiY5C0GkbTUSN6e3dz35aDCxfuOefncVSrWrpZv96JsffeDdIp2fSrmnA02BlryWKVjlabthUqXeyzx0Y2cbydDd2kThJy0YIIHRHXWbPYqU8n@8ADvtYUsYKizE/F/SoYHPmNEHH6cYOQg05RCeaQIQsdOf8HA1JFEXSAhxn7VmFH8DELkTrE3PO@HfNkwOYhW@n/We6S@wA "JavaScript (Node.js) – Try It Online") Use `0` for a hole. Too slow for most testcases. Simple idea: ``` for t := (large enough number) domnto 0 do if (t is valid) then return true return false ``` Although \$\prod a\_i\$ would be large enough. Calculating the product is a bit longer than just concat them. --- # JavaScript, 62 bytes ``` a=>a.some(o=(t,i)=>(g=j=>j&&(t%j?o:o[j]??=i%j)-i%j|g(j-1))(t)) ``` Use *hole* for a *hole*. A faster version. --- # [JavaScript (Node.js)](https://nodejs.org), 65 bytes ``` a=>a.some((x,i)=>a.some(g=(y,j,_,z=x)=>z%y?g(z%y,j,a,y):(i-j)%y)) ``` [Try it online!](https://tio.run/##dY/NCsIwEITvPkUuhQ2shfSHEiX6ICISaltaaiNWpOnLx00FDzYSWMjszJdJp196LB/t/bkdzLVytXJaHXQ8mlsFMGHLv7dGgcUOLziridQ5sscGaJKm0fIdtNuOR5ZzV5phNH0V96aBGk4FMpEi8yeXfqaCFHnmfL/5sdIioT2yjLwhA8VDspT/cMTKkVEFelmITxOxRq@zFClCTJ9f@omFTNgkZMv8RzO/cW8 "JavaScript (Node.js) – Try It Online") Use *hole* for a *hole*. The fast version in polynomial time complexity. [Answer] # Haskell, ~~65~~ 52 bytes ``` f l=or[all(==0)$zipWith mod[t..]l|t<-[0..product l]] ``` [Try it Online!](https://tio.run/##LUzLCsMgEPyVPfSQgJU8DEGo39GDeJCmIdJNlNReSv/driawwzAzO7PY9@uJmNIMqPyuLWKlVFNfvi7cXVxg9ZOOnBv8xdtVN5yH3U@fRwQ0Jq3WbaAg7G6LUK02wAxajwzanlBukIX6rKRhmrgjyUBQljVByjMhe2BA/Vxqz5n8RdZIdKyKY7h8deQeWhhTpz8) Uses 1 for a hole. -13 bytes thanks to xnor [Answer] # TypeScript Types, 332 bytes ``` //@ts-ignore type a<T,N=[],U=`${T}`>=U extends`${N["length"]}`?N:a<T,[...N,0]>;type b<A,B>=A extends[...B,...infer X]?b<X,B>:A;type c<A,B>=[]extends A|B?Exclude<A|B,[]>:c<B,b<A,B>>;type M<T,X={[K in keyof T]:[a<T[K]>,a<K>]}[number],Y=X>=0 extends(X extends X?Y extends Y?b<X[1],c<X[0],Y[0]>>extends b<Y[1],c<X[0],Y[0]>>?1:0:0:0)?0:1 ``` Represents holes with `1`s. [Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF1KBVWgAwBIBvcgX3YA+Wi0LoAHuHSIAJpC7dq9AEQAbafHAALZYwEB+agC4yVegDpL1SgAZGggNy4ChAEakAgpQBCwj2MlpOQtLb0pLc1hEADN0VEIADUZ9dwSfQSMPJ3wiAGNPdIZGCSlZSEIPAB9vfQBRcVzVAFcZdE9qyiYM-LD3L19HZyIAWQpKBNpuegBpQijCAGt0HGRownJGI3pTGftKMmnBPXpEJoBbVzjmAE1aBOEbANK5AAoEp6DyhP1rj7LCa4pUgJegARmY+RBdko13odkEghKnzcpFh4MokLhNyxCP0oKMNgJBIAlPpCaDMNgcutHrRCKN6AB2SiEUEAZhZoM5LIArABObmENlc1l8+yYECEKUAPX0VJc5FBhDpDJFACYWRzCAAWXniyUyuVDdZq5X00hg-XAKWEWXyojkNlmhl811Wm1243kbXOi0irU8lnMwgC1ki9mcnnuw2U40AMVp5qZQejtqN1LjSpVFq1It1rN5LNDatTnozpuz9HzedLcqAA) ## Ungolfed / Explanation I suspect this just applies the Chinese Remainder Theorem, but I haven't looked into it. ``` // Convert a number literal or a string literal representing a number to a `Nat` type NumOrStrNumToNat<T, N=[], U=`${T}`> = U extends `${N["length"]}` ? N : NumOrStrNumToNat<T, [...N, 0]> type ModNat<A, B> = A extends [...B, ...infer X] ? ModNat<X, B> : A // Calculate the GCD of two `Nat`s using the Euclidean algorithm type GcdNat<A, B> = [] extends A | B ? Exclude<A | B, []> : GcdNat<B, ModNat<A, B>> type Main< T, // Convert an e.g. T of [1,5,3] to [Nat(1), Nat(0)] | [Nat(5), Nat(1)] | [Nat(3), Nat(1)] X = { [K in keyof T]: [NumOrStrNumToNat<T[K]>, NumOrStrNumToNat<K>] }[number], Y = X > = // Return 0 if any of the following return 0 0 extends ( // Map over X cross Y X extends X ? Y extends Y ? // Return 1 if X[1] and Y[1] are equal modulo the GCD of X[0] and Y[0] ModNat<X[1], GcdNat<X[0], Y[0]>> extends ModNat<Y[1], GcdNat<X[0], Y[0]>> ? 1 : 0 : 0 : 0 ) ? 0 : 1 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` Π'?ẏ+?ḊA ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOoCc/4bqPKz/huIpBIiwiIiwiWzEsMiwzLDQsNV0iXQ==) Outputs an empty list as falsy and a list with items as truthy, taking holes as 1. ``` Π # Absolute value of product ' # Range 1...n filtered by ?ẏ+ # Add 0...input length to that ḊA # All divisible by ? # Input ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` PLʒ∞<+IÖP ``` Port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/240110/52210), also taking `1` as holes and outputting an empty list for falsey. [Try it online](https://tio.run/##yy9OTMpM/f8/wOfUpEcd82y0PQ9PC/j/P9pQx0jHWMdExzQWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8DfPTOTXnUMc9G@9C6w9MC/tem6PyPjjaM1Yk21DHSMdYx0TEFsi0tLcEixjqmOuY6ljqGhjqGxjqGIClzMAsITYHCOsZAFlCpQrQJkGMCljYHkiAVIBFToF6j2FgA) (uses a find\_first `.Δ` instead of filter `ʒ` to speed the test suite up). **Explanation:** ``` P # Take the product of the (implicit) input-list L # Pop and push a list in the range [1,product(innput)] ʒ # Filter this list by: ∞ # Push an infinite positive list: [1,2,3,...] < # Decrease each by 1: [0,1,2,...] + # Add the current integer to it: [y,y+1,y+2,...] IÖ # Check if the first input amount of values are divisible by the input-values # at the same positions (it'll transform the list into the smallest of the # two, causing the infinite list to shrink to the input-size) P # Check if all are truthy by taking the product # (after which the filtered list is output implicitly) ``` [Answer] # [Python3](https://www.python.org), 88 bytes ``` lambda L,t=1:t>lcm(*L)or any((t-i)%b for i,b in enumerate(L))*f(L,t+1) from math import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TVDRahQxFMXXfMVlByFZp2XTbqlbWPFBH8QRCvpQWBfJzt7pBDLJktzRrn6KLwXRf6pf402mSIcJl3Puueee5Oefw5H64O9_devPv0fqTl4-3Dgz7PYGmprW-opeuXaQ80aFCMYfpaQTq57voGNs6x1YD-jHAaMhlI1S807y4AutRBfDAIOhHuxwCJHmk__fZ2bC0I2-pRBcqiEdk-BzmpAitmNMNnhnB0tSL_KnhKjgAw7BfkfgQCJEe2u9cV8YwLpQr__7nbam7VHssYMS3nrCW4xJXQmAiDRGD08Nnijynk-YSOT7OesxX7Ako731ed52hWfCRErfLPVyVs2KNcAhspOcfXz_7vr67ZuZKmQbPFk_IoOGs-JX42S2yN0KxoSgwSTog8vbEqHZQ-hg8ajf3HFYluREdzlOsy3XSKMjbvN7Z6Np88Sq6aXvH35Um8sa9HkNi_JfrEo510yutmLD9YxhDUvuMV7wWa24U-UW8xc1sAFPaT356Cxj6pJLhmVUFyGrzphdlhXL7ZThHw) Uses 1s as holes. Returns 0 (falsy) if possible, and 1 (truthy) if impossible. Some test cases cannot be completed due to memory limit with recursion. The iterative version however can finish and gives the correct results: [Attempt This Online!](https://ato.pxeger.com/run?1=TVHBahsxEKVXfcVgU9h1N8FKHFIHEnpoD6UOBNqbMUVZz2YFWslIs03cX-nFFJp_Sr-mM9pNsdhlmDdvZt6Tfj3v9tQGfzj86ak5ef_yu4mhg85QC7bbhUgzpbbYQFOsyisFQHANmmPE1LvX5LG1DkFLHcA2TLoBV3fFbOiRE5H66Mc2NSB5wuwajN8XBZ3Y8u09NCGCre7BekDfdxgNIa8ucwvBO144KP37xgwCoel9TSG4VEHaJ8X_aUKKWPcx2eCd7SwVei6nVGoKt9gF-xNFoQrRPlhv3HdO2IxAH_7PO61N3WK2n91YT_iAMWVTo6HjAUcM2fMNEynx46xHMZSV0dZ66edrEpwBEyk9WmqLyXQy3tcu8qRi8vXL57u7Tx8ng_s6eLK-R05WrBV_GFfICKlOoU_8AmAStMHJtkRothAamI_89ROLZYooehI5q83xO8oDq9fNA1oON3142a8vK9DnFczzd7HM4VwzuNyoNcczTitYcI3zOf_L5Vhh-KIC7ucmrYcxWlgMXXKQNHfqTGTWGaOLvGGxGRT8Aw) This is a bruteforce search for all numbers `t` between 1 and the LCM (least common multiple) of all bus IDs. If we find a `t` that has the correct remainders when divided by all bus IDs `b`: `(t-i) % b == 0` then the bus schedule is possible. ]
[Question] [ [Steven Gerrard](https://en.wikipedia.org/wiki/Steven_Gerrard) was born on 30th of May 1980. He is now 37 years old. Happy birthday, Steven! To celebrate his anniversary, your goal is to remind him the number of goals he has scored each year in premiere league for Liverpool. He doesn't want to remember the goals scored before or after playing for Liverpool. It is like scoring `0` goals. **Input** The starting year of football season. **Output** The number of goals scored by Steven during this season for Liverpool. **List of seasons and goals** ``` 1998–99 0 1999–2000 1 2000–01 7 2001–02 3 2002–03 5 2003–04 4 2004–05 7 2005–06 10 2006–07 7 2007–08 11 2008–09 16 2009–10 9 2010–11 4 2011–12 5 2012–13 9 2013–14 13 2014–15 9 ``` **Example** ``` Input Output 2002 5 2017 0 1990 0 2014 9 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest submission in bytes in each language wins. Explanations are encouraged. [Answer] ## JavaScript (ES6), ~~47~~ ~~43~~ ~~42~~ 39 bytes ``` y=>+'0723135148933694'[y-1999]+y%20%9|0 ``` ### How? We compute an approximation ***x*** of the number of goals for a given year ***y*** with the formula: ``` x = y % 20 % 9 ``` This is actually a very bad approximation, but it's always less than or equal to the expected value ***v*** and never less than ***v - 9***, which allows to encode the difference with a single decimal digit. ``` y | y % 20 | x = y % 20 % 9 | v | v - x -----+--------+----------------+----+------ 1999 | 19 | 1 | 1 | 0 2000 | 0 | 0 | 7 | 7 2001 | 1 | 1 | 3 | 2 2002 | 2 | 2 | 5 | 3 2003 | 3 | 3 | 4 | 1 2004 | 4 | 4 | 7 | 3 2005 | 5 | 5 | 10 | 5 2006 | 6 | 6 | 7 | 1 2007 | 7 | 7 | 11 | 4 2008 | 8 | 8 | 16 | 8 2009 | 9 | 0 | 9 | 9 2010 | 10 | 1 | 4 | 3 2011 | 11 | 2 | 5 | 3 2012 | 12 | 3 | 9 | 6 2013 | 13 | 4 | 13 | 9 2014 | 14 | 5 | 9 | 4 ``` ### Demo ``` let f = y=>+'0723135148933694'[y-1999]+y%20%9|0 for(y = 1997; y <= 2017; y++) { console.log(y, f(y)) } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ 24 bytes ``` •3ßÎó‚4Ëǝï•17в15ÝƵÊØ+Ikè ``` [Try it online!](https://tio.run/##ATgAx/8wNWFiMWX//@KAojPDn8OOw7PigJo0w4vHncOv4oCiMTfQsjE1w53GtcOKw5grSWvDqP//MjAwMA) or as a [Test suite](https://tio.run/##AUsAtP8wNWFiMWX/MTk5MCAyMDIwxbh2ef/igKIzw5/DjsOz4oCaNMOLx53Dr@KAojE30LIxNcOdxrXDisOYK3lrw6j/eSLDvzogw78iLP8) **Explanation** ``` •3ßÎó‚4Ëǝï• # push the number 69255401071877657848 17в # convert to list of base-17 digits # produces the list [1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9,0] 15Ý # push the range [0 ... 15] ƵÊØ+ # add the 303rd prime (1999) to each Ik # get the index of the input in this list # or -1 if outside the range è # get the element at that index in first list ``` [Answer] # JavaScript, 44 Bytes ``` y=>parseInt("173547a7bg9459d9"[y-1999],17)|0 ``` [Answer] # PHP, 44 Bytes ``` <?=intval(_173547a7bg9459d9[$argn-1998],17); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zNTIwsLDmsrf7b2Nvm5lXUpaYoxFvaG5samKeaJ6UbmliapliGQ1WqmtoaWkRq2Normn9/z8A "PHP – TIO Nexus") [Answer] # PowerShell, 65 Bytes ``` (($g=(1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9)["$args"-1999]),0)[!$g] ``` uses a ternary/array format to return 0 if the year isn't in the array. This is so long because powershell doesn't have any `else return 0` format, and the full array is required, if he scored 9 or less goals in each year we could shave a lot off this by indexing into a string instead. [Answer] # Bash, ~~97~~ 93 Bytes ``` a=(1 7 3 5 4 7 10 7 11 16 9 4 5 9 13 9) ((2014<$1||$1<1999))&&(echo 0)||(echo $[a[$1-1999]]) ``` [Answer] # C#, ~~79~~ 72 bytes ``` y=>new[]{0,1,7,3,5,4,7,10,7,11,16,9,4,5,9,13,9}[y>2014|y<1999?0:y-1998]; ``` [Answer] # Braingolf v0.6, 48 bytes ``` #ߎ-V173547# 792+82*945994+9&,0R!?1-[v>R]v_:0_|; ``` This is a weird one. The character `ߎ` has the ordinal 1998, making `#ߎ` the Braingolf literal for 1998, which is then subtracted from the input. ### Explanation: ``` #ߎ-V173547# 792+82*945994+9&,0R!?1-[v>R]v_:0_|; Implicit input of n #ߎ- Subtract 1998 from n V Create a new stack and switch to it 173547 Digit literals 1, 7, 3, 5, 4 and 7 #<newline> Integer literal 10 792 Digit literals 7, 9 and 2 + Sum the last 2 items (9 and 2) to make 11 82* Digit literals 8 and 2 multiplied to make 16 9459 Digit literals 9, 4, 5 and 9 94+ Digit literals 9 and 4 summed to make 13 9 Digit literal 9 &, Reverse stack 0 Digit literal 0 R Return to main stack !? If n != 0 1- Decrement n [...] Loop, repeat n+1 times v> Move to next stack and rotate to the right R Return to main stack v_ Move to next stack and output last item : Else 0_ Push zero and output | Endif ; Suppress implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~59~~ 58 bytes Inspired by [this answer](https://codegolf.stackexchange.com/a/123496/66418). ``` lambda x:1997<x<2015and int('173547a7bg9459d9'[x-1999],17) ``` [Try it online!](https://tio.run/##FYxBCsMgFAXX9RTuotCCWsX8kN6iu7YLg0kjJFaCofb09mcz8GDmpV@eP1HV6fasi1sH72jpJIDtS6@ENC56GmJmjbRXo62zwxu0AQ/No1zQg9dZWl6/c1hGet/2sSOntB3FxEJMe2ac8ypBCIJ2ewCIEjjxXSNU@wc "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~50~~ 41 bytes ``` y=>+`0x${"06243696af8348c8"[y-1999]}`+1|0 ``` --- ## Try it ``` f= y=>+`0x${"06243696af8348c8"[y-1999]}`+1|0 oninput=_=>o.innerText=f(+i.value) o.innerText=f(i.value=1998) ``` ``` <input id=i type=number><p id=o> ``` ]
[Question] [ You will take two positive integers `n` and `x` as input, and output [Euler's totient function](https://en.wikipedia.org/wiki/Euler%27s_totient_function) (number of positive integers less than `x` co-prime to `x`) applied `n` times. # Testcases ``` n x result 1 10 4 2 10 2 3 10 1 1 100 40 2 100 16 3 100 8 4 100 4 5 100 2 6 100 1 ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes Code: ``` FÕ ``` Explanation: ``` F # Do the following n times: Õ # ..Calculate the totient ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=RsOV&input=MQoxMDA). [Answer] # Python 2, ~~84~~ ~~78~~ 70 bytes ``` n,x=input();exec('k=m=1;'+'x-=(x%k<m%k)*x/k;m*=k*k;k+=1;'*x)*n;print x ``` *Thanks to @xnor for golfing off 8 bytes!* Test it on [Ideone](http://ideone.com/qVLteW). ### Background By [Euler's product formula](https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler.27s_product_formula), ![Euler's product formula](https://i.stack.imgur.com/xsXir.png) where **φ** denotes Euler's totient function and **p** varies only over prime numbers. To identify primes, we use a corollary of [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem): ![corollary of Wilson's theorem](https://i.stack.imgur.com/ordYr.png) ### How it works After reading the input, we construct and execute a certain string. The executed code is roughly equivalent to the following. ``` r = range(x) for _ in range(n): k = 1 m = 1 for _ in r: x -= (x % k < m % k) * x / k m *= k**2 k += 1 ``` The inner loop will set **x = φ(x)**, so executing it **n** times stores the desired output in **x**. At all times, the variable **m** will be equal to the square of the factorial of **k - 1**. In fact, we set **k = 1** and **m = 0!2 = 1** at the beginning of the inner loop. **k** varies from its initial value **1** to the initial value of **x** and is incremented each time the sinner loop is executed. **m** is updated accordingly by multiplying it by the "old" value of **k2**. For the actual calculation of **x**, recall that `m%k` will yield **1** if **m** is prime and **0** if not. This means that `x%k<m%k` will yield **True** if and only if both **k** is a prime number and **x** is divisible by **k**. In this case, `(x%k<m%k)*x/k` yields **x / k**, and subtracting it from **x** replaces its previous value with **x(1 - 1/k)**, as in Euler's product formula. Otherwise, `(x%k<m%k)*x/k` yields **0** and **x** remains unchanged. [Answer] ## Actually, 4 bytes ``` `▒`n ``` [Try it online!](http://actually.tryitonline.net/#code=YOKWkmBu&input=MTAwCjI) This program takes `x` as the first input, and `n` as the second input. Explanation: ``` `▒`n `▒`n call the following function n times: ▒ totient(x) ``` [Answer] ## Mathematica, 17 bytes ``` EulerPhi~Nest~##& ``` An unnamed function which takes `x` as the first argument and `n` as the second. Here `EulerPhi~Nest~##` is short for `Nest[EulerPhi, ##]` and then `##` expands to a sequence of both arguments so we get `Nest[EulerPhi, x, n]`. And `EulerPhi` is of course the totient function. [Answer] ## [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ÆṪ¡ ``` Expects `x` as the first argument and `n` as the second. [Try it online!](http://jelly.tryitonline.net/#code=w4bhuarCoQ&input=&args=MTAw+Mg) This is as straightforward as it gets: `ÆṪ` is the built-in totient function and `¡` applies this function as many times as the second argument. [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` :"_Zp ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiJfWnA&input=MgoxMDAKCg) ``` : % Take n implicitly. Generate vector [1 2 ... n] " % For each loop, that is, repeat n times _Zp % Euler's totient function. Takes x implicitly first time % End for. Display implicitly ``` --- Without using Euler's totient function: **9 bytes** ``` :"t:Zd1=s ``` [**Try it online!**](http://matl.tryitonline.net/#code=OiJ0OlpkMT1z&input=MgoxMDAKCg) ``` : % Take n implicitly. Generate range [1 2 ... n] " % For each loop, that is, repeat n times t % Duplicate. Takes x implicitly first time. Call that t : % Range [1 2 ... t] Zd % GCD of t and [1 2 ... t], elementwise 1=s % How many times the result equals 1: Euler's totient % End for. Display implicitly ``` [Answer] # J, ~~6~~ 4 bytes ``` 5&p: ``` Straight-forward approach. Nests the totient function *n* times on an initial value of *x*. ## Usage ``` f =: 5&p: 5 f 100 2 ``` ## Explanation Normally, `5&p:` is a monad that computes the totient of its argument. However, when used dyadically, it nests itself on an initial value of its LHS according to the number of times on its RHS. [Answer] # [PARI/GP](http://pari.math.u-bordeaux.fr), 33 bytes Straightforward iteration: ``` f(n,x)=for(i=1,x,n=eulerphi(n));n ``` Straightforward recursion: ``` f(n,x)=if(x,n,f(eulerphi(n),x-1)) ``` [Answer] # Haskell, ~~49~~ ~~46~~ ~~44~~ 40 bytes Thanks @xnor for another again named solution: ``` x%0=x x%n=sum[1|1<-gcd x<$>[1..x]]%(n-1) ``` Old version: The following is an unnamed pointless function that takes two arguments: (Thanks @Lynn for another two bytes!) ``` (!!).iterate(\y->sum[1|t<-[1..y],gcd y t<2]) ``` To use it, you can e.g. assign it a name (`f=(!!).(...`) and then call it via `f 10 1` (as an example for the first test case). Explanation: The lambda function `(\y->sum[1|t<-[1..y],gcd y t<2])` is the totient function. `iterate f x` produces an infinite list `[x,f(x),f(f(x)),f(f(f(x))),...]` and `!!` is just for accessing this list at a specific index. Older version: ``` x#n=(iterate(\y->sum[1|t<-[1..y],gcd y t<2])x)!!n ``` Usage e.g. for the first test case: `10#1`. [Answer] # CJam, 20 bytes ``` q~{_mf1|1-{1$\/-}/}* ``` [Try it online!](http://cjam.tryitonline.net/#code=cX57X21mMXwxLXsxJFwvLX0vfSo&input=MTAwIDM) ### How it works ``` q~ Read and evaluate all input. Pushes x and n. { }* Repeat n times: _mf Compute the prime factorization of a copy of x. 1|1- Add and remove 1 from the prime factorization. | deduplicates and - handles the edge case 1mf -> [1]. { }/ For each remaining prime p: 1$ Push a copy of x. \/ Swap with p and divide, pushing x/p. - Subtract from x, pushing x-x/p. ``` [Answer] ## [Hoon](https://github.com/urbit/urbit), 84 bytes ``` |*((pair) ?~(p q $(p (dec p), q (lent (skim (gulf 1 q) |=(@ =(1 d:(egcd +< q)))))))) ``` Ungolfed: ``` |* (pair) ?~ p q %= $ p (dec p) q (lent (skim (gulf 1 q) |=(@ =(1 d:(egcd +< q))))) == ``` [Answer] # Julia, 36 bytes ``` n\x=n>0?~-n\sum(k->gcd(k,x)<2,1:x):x ``` [Try it online!](http://julia.tryitonline.net/#code=blx4PW4-MD9-LW5cc3VtKGstPmdjZChrLHgpPDIsMTp4KTp4Cgpmb3IgKG4seCkgaW4gKCAoMSwxMCksICgyLDEwKSwgKDMsMTApLCAoMSwgMTAwKSwgKDIsIDEwMCksICgzLCAxMDApLCAoNCwgMTAwKSwgKDUsIDEwMCksICg2LCAxMDApICkKICAgIEBwcmludGYoIiUxZCAlM2QgJTJkXG4iLCBuLCB4LCBuXHgpCmVuZA&input=) [Answer] ## Javascript, 88 ~~95~~ ``` g=(a,b)=>b?g(b,a%b):a==1 t=(x,n=x,o=0)=>n?t(x,--n,o+g(x,n)):o f=(n,x)=>n?f(n-1,t(x)):x ``` The first function returns true/false if the greatest commom divisor is 1. The second function calculates the *totient*. The third function is a simple recursion to do the totient n times. I took this idea from the wikipedia link: > > It can be defined more formally as the number of integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n, k) = 1; > > > [Answer] # [Perl 6](http://perl6.org), ~~47 45 44 43 42 41~~ 39 bytes ``` ~~{($^x,{+(^$^x .grep: {$\_ gcd$x==1})}...\*)[$^n]} {($^x,{+(^$^x Xgcd $x).grep: \*==1}...\*)[$^n]} {($^x,{+grep \*==1,(^$^x Xgcd $x)}...\*)[$^n]} {($^x,{+grep \*==1,(^$^x Xgcd$x)}...\*)[$^n]} {($^x,{+grep 2>\*,(^$^x Xgcd$x)}...\*)[$^n]} {($^x,{+grep 2>\*,(^$\_ Xgcd$\_)}...\*)[$^n]}~~ {($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]} ``` ### Explanation: ``` { # parameters are $n,$x ( declared as placeholder parameters ) ( $^x, # seed sequence generator with second argument { # parameter is $_ sum 2 X[>] # crossed compared using &infix«>» ( 0 ..^ $_ # from 0 up to and excluding the parameter X[gcd] # cross apply &infix:<gcd> with: $_ # the parameter ) } ... # keep applying that block * # forever )[ $^n ] # grab the one at the index indicated by the first argument } ``` ### Test: ``` use v6.c; use Test; my @tests = ( (1, 10) => 4, (2, 10) => 2, (3, 10) => 1, (1,100) => 40, (2,100) => 16, (3,100) => 8, (4,100) => 4, (5,100) => 2, (6,100) => 1, ); plan +@tests; my &repeated-totient = {($^x,{sum 2 X>(^$_ Xgcd$_)}...*)[$^n]} for @tests -> $_ ( :key(@input), :value($expected) ) { is repeated-totient(|@input), $expected, .gist } ``` ``` 1..9 ok 1 - (1 10) => 4 ok 2 - (2 10) => 2 ok 3 - (3 10) => 1 ok 4 - (1 100) => 40 ok 5 - (2 100) => 16 ok 6 - (3 100) => 8 ok 7 - (4 100) => 4 ok 8 - (5 100) => 2 ok 9 - (6 100) => 1 ``` ]
[Question] [ Upon receiving month and year in YYYYMM format, generate output of the corresponding **calendar month** for that year. For example the input `201312` should generate the following output: ``` Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` Only trick is, NO native calendar generating functions... so Linux clones, no "cal" function... Muahahahahah! PS: The calendar must start out with Monday as the left-most day, this is to ensure that the output is like the "cal" function, but does not output like "cal", which has Sunday as its left-most day... Smallest code size wins. [Answer] # Ruby, ~~170~~ 168 characters ``` g=gets.to_i require'date' d=Date.new g/100,g%100 puts'Mo Tu We Th Fr Sa Su' l=['']*(d.jd%7)+[*1..(d>>1).jd-d.jd] 56.times{|i|$><<"#{l[i].to_s.rjust 2} #{?\n if i%7>5}"} ``` Bugfix: didn't require the neccessary library (+16) used julian date modulo 7 instead of current week day directly (-3) used /100 and %100 to parse date instead of regex (-13). Taken from LegoStormtroopr's answer. removed the parentheses around the argument to `rjust` and `Date.new`(-2) [Answer] ## Python 2.7 - 152 Unfortunately it fails for [September 1752](http://en.wikipedia.org/wiki/Calendar_%28New_Style%29_Act_1750). Granted, it imports all of the calender functions, but only *uses* 1, and that just returns the start day of the week and the number of days. ``` from calendar import* w,l=monthrange(*divmod(input(),100)) print" Mo Tu We Th Fr Sa Su\n"+" "*w+''.join(["%3d"%s+"\n"*((s+w)%7<1)for s in range(1,l+1)]) ``` Relatively standard code, but this is my favourite bit: ``` "\n"*((s+w)%7<1) ``` It prints the new line using string multiplication, if the number of the current day and start day of the week is Sunday (e.g. 7) as the boolean is cast to an integer. This saves a character on the more intuitive `x%7==0` by using `x%7<1` instead. Test output: ``` > 198210 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` [Answer] # Mathematica 203 ``` g@d_:=Module[{w={"Mo","Tu","We","Th","Fr","Sa","Su"},c}, c@n_:=" "~ Table ~{n}; Grid@Partition[Join[w,c[Position[w,StringTake[ToString@DayName@d,2]][[1,1]]-1], Range@DayCount[d,d~DatePlus~{1,"Month"}],c@6],7]] ``` **Testing** ``` g[{2013, 12}] g[{2014, 1}] g[{2014, 2}] ``` ![calendars](https://i.stack.imgur.com/ylJbB.png) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 87 bytes ``` k§2vẎṄ,4ȯI:£3<?4ẎIεD4/⌊‟₁/⌊N‟:400/⌊»∧+ż↵`»8τv‹¥Ẏt2Ṡ7%7ε¤w$ẋf»∇ė{»4τ¥Ẏt28+ɾJ7ẇƛƛS2↳;Ṅ;⁋, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%C2%A72v%E1%BA%8E%E1%B9%84%2C4%C8%AFI%3A%C2%A33%3C%3F4%E1%BA%8EI%CE%B5D4%2F%E2%8C%8A%E2%80%9F%E2%82%81%2F%E2%8C%8AN%E2%80%9F%3A400%2F%E2%8C%8A%C2%BB%E2%88%A7%2B%C5%BC%E2%86%B5%60%C2%BB8%CF%84v%E2%80%B9%C2%A5%E1%BA%8Et2%E1%B9%A07%257%CE%B5%C2%A4w%24%E1%BA%8Bf%C2%BB%E2%88%87%C4%97%7B%C2%BB4%CF%84%C2%A5%E1%BA%8Et28%2B%C9%BEJ7%E1%BA%87%C6%9B%C6%9BS2%E2%86%B3%3B%E1%B9%84%3B%E2%81%8B%2C&inputs=%27201312%27&header=&footer=) -7 thanks to lyxal. ``` === Part 1: Header === k§ # Monday to Sunday 2vẎ # Get first two letters of each Ṅ, # Join by spaces === Part 2: What day does it start? === 4ȯI # Last two (month) as integer :£ # Store a copy to register 3<?4ẎIε # Decrement the year if the month is Jan or Feb D # Calculate: 4/⌊‟ # floor(y/4) ₁/⌊N‟ # -floor(y/100) : # y 400/⌊ # And floor(y/400) »...»8τv‹ # Compressed list of the days (mod 7) at the start of each month ¥Ẏt # Get the correct item 2 # Add 2 (1 because first day of month, 1 because it ends on Sunday) Ṡ7% # Take the sum of the whole thing, mod 7. === Part 3: Get the whole month === 7ε # Difference from 7 ¤w$ẋf # Copies of the empty string »...»4τ # Compressed list of days in each month, -28 ¥Ẏt # Get the correct item 28+ # Add 28 ɾ # Make a range out of that J # Add on the empty strings === Part 4: Format nicely === 7ẇ # Divide into chunks of 7 ƛ ; # Foreach... ƛ ; # For each item... S # Stringify 2↳ # Align Ṅ # Join by spaces ⁋, # Output joined by newlines ``` [Answer] # SmileBASIC, 204 bytes ``` INPUT Y$Y$[3]=Y$[3]+"/ DTREAD Y$+"/01"OUT Y,M,,W W=W-1+!W*7?"Mo Tu We Th Fr Sa Su FOR I=1TO 30+(1AND M-(M>7))-(M==2)*2+(Y MOD 4<1&&(Y MOD 100||Y MOD 400<1))LOCATE W*3,?STR$(I,2); W=W+1 IF W>6 THEN W=0? NEXT ``` Wow, that leap year detector is VERY long... [Answer] # PHP, ~~153~~ 147 bytes ``` Mo Di We Th Fr Sa Su <?=str_pad("",3*$w=date(w,$t=strtotime(chunk_split($argv[1],4,"-")."7")));while($d++<date(t,$t))printf("%2d "." "[++$w%7],$d); ``` **breakdown** ``` echo"Mo Di We Th Fr Sa Su\n"; // header echo str_pad("",3* // 4. print leading spaces $w=date(w, // 3. get weekday $t=strtotime( // 2. convert to unix timestamp chunk_split($argv[1],4,"-")."7" // 1. import, split to year-month-, append day 7 ))); while($d++<date(t,$t)) // 5. loop $d through days of month: printf("%2d "."\n"[++$w%7],$d); // print date, plus a linebreak for sundays ``` [Answer] ## JavaScript (239) ``` h=prompt();y=h.slice(i=0,4);m=h[4]+h[5]-1;d=new Date(y,m);a='MoTuWeThFrSaSu'.match(/../g);for(p=0;p<(d.getDay()||7)-1;p++)a.push(' ');while(d.setDate(++i)&&d.getMonth()==m)a.push(9<i?i:' '+i);while(c=a.splice(0,7).join(' '))console.log(c) ``` Output: ``` (for 198210) (for 201312) Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su 1 2 3 1 4 5 6 7 8 9 10 2 3 4 5 6 7 8 11 12 13 14 15 16 17 9 10 11 12 13 14 15 18 19 20 21 22 23 24 16 17 18 19 20 21 22 25 26 27 28 29 30 31 23 24 25 26 27 28 29 30 31 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 242 bytes Not the most elegant solution, I suspect. Input in the form of an integer with the four high digits forming the year, and the low two digits the month. ``` X=100,W;f(d){int m=d%X,y=d/X,i=0,M=" >8><><>><><>"[m]/2+(m==2&(!(y%4)&&(y%X|!(y%400))));for(m+=m<3?y--,10:-2,W=(((1+(26*m-2)/10-2*y/X+5*(y%X)/4+y/X/4)%7)+6)%7,printf("Mo Tu We Th Fr Sa Su\n%*s",3*W,"");i<M;)printf("%2d%c",++i,W++%7^6?32:10);} ``` [Try it online!](https://tio.run/##dU9BboMwEDw3r3AtGa2xLWxDCYpxcuuNUyKB1LRSBKXlAIlIOKA0b6cuSm/trjSr0eyMdkvxUZbTVFglJc9NDRW9Nt0FtbYiBR9tFRS8sZJnFqN1sk5dz4Bf2tdAM2it1R48wkgi6nluFF8zkZK6MvWxh5bZNg03oxBcyZXQPLcAoBjo2G@FpoGSQvtjULAn/yeABhFzLIgoWVIWO@Sn3t1UA86OaDeg/B3tPtFzj7YHtB32HfHPmId@zjGmpkkzQ3/3ia5IiTljDc8ZI8u3eBPqlZLU3Kb5y0PTAV1cFw81aKlCpalBp@FyBrzvhBAu7y4lMvlHkpH8w3VD0zc "C (gcc) – Try It Online") [Answer] # APL(NARS), 183 chars ``` L←{(0=400∣⍵)∨(0≠25∣⍵)∧0=4∣⍵}⋄C←{Y←(30+2741⊤⍨12/2)+(¯2+L⍵[2])×2=⍳12⋄d←7∣+/Y[⍳⍵[1]-1],{1+L⍵}1900..⍵[2]-1⋄7 7⍴(,/7 2⍴'MoTuWeThFrSaSu'),(d⍴⊂''),{2 0⍕⍵}¨(⍳Y[⍵[1]]),12⍴⊂''}∘{(100∣⍵),⌊⍵÷100} ``` Input ok only from 1900. Test & how to use it: ``` C 201312 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 C 202312 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` ]
[Question] [ # Input A string of text. # Output The string of text, however, every consonant is the next consonant in the alphabet, and every vowel is the next vowel in the alphabet (z becomes b, u becomes a). The case of the new letter should be the same as the letter it is replacing (a becomes e, A becomes E). If there are two consonants in a row, they will be separated by the characters 'ei', the case of 'ei' can be whatever you please. Characters outside of the 26 character Latin alphabet should remain unchanged. This includes whitespace and punctuation. (For clarity, the vowels are aeiou. Y is not considered a vowel) Examples: The phrase "Hello World" becomes "Jimeimu Xuseimeif" The phrase "codegolf" becomes "dufihumeig" [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 27 bytes ``` k⁰kv":ɾJJƒ*‛ß+k⁰⇧1Ṁ$‡‛eijøṙ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJr4oGwa3ZcIjrJvkpKxpIq4oCbw58ra+KBsOKHpzHhuYAk4oCh4oCbZWlqw7jhuZkiLCIiLCJcIkhBZWxsbyBXb3JsZFwiIl0=) This is a bit of a mess. ``` k⁰kv" # Consonants and vowels, paired :ɾ # Duplicate and make an uppercase copy of each J # Concatenate to the original J # Concatenate to the input ƒ* # Reduce by ring translation, ring translating by each string ‛ß+ # "[bcdfghjklmnpqrstvwxyz]+" 1Ṁ # Insert at position 1... k⁰⇧ # "BCDFGHJKLMNPQRSTVWXYZ" $ # Put that under the value øṙ # Regex replace that with... ‡ # A function that... ‛eij # Joins by "ei" ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 131 bytes ``` s=>s.replace(/[a-z]/gi,c=>(s+g(i=B(c)[0]-1)?"":"ei")+(h=j=>g(i)^g(j=-~j%26)?h(j):B([j+1|i&96]))(i&31),B=Buffer,g=i=>s=1065233>>i&1) ``` [Try it online!](https://tio.run/##Xc9Ra4MwEAfw930KCVRyqLXRTWghlvk09j42EAcuJvFC2hQz91DGvrqLY0@9p@Pu9@c403/1Xkx4@czObpCL4ovntd9O8mJ7IWne9tm1yzWmgtfUJ5oib6iAdtdlDI6EHIhEAgkdueF12MK7poZnP2ZTVHAcqYFDQ1uTsG@M91UHQDEuGaQNb2al5JRqjuEgZ7vqoSjLusaYwSLc2Tsrt9Zpqih5kta66NVNdiAAUZ5Hz3iSeJqjt9nLtVV3NxERvtHOqtWHCpFhVjjOwepb@3JlRXn/L//s48c6WX4B "JavaScript (Node.js) – Try It Online") ### Commented ``` s => s.replace( // replace in the input string s ... /[a-z]/gi, c => // ... each letter c (case insensitive) ( // s + // if the previous letter was a vowel (or this // is the 1st iteration and s is still a string) g( // or the current letter i = // whose ASCII code - 1 is loaded in i B(c)[0] - 1 // ) ? // is a vowel: "" // append nothing : // else: "ei" // append "ei" ) + ( // h = j => // h is a recursive function looking for the // replacement letter g(i) ^ // if the type of the current letter g( // does not match the type of j = -~j % 26 // the next letter in the alphabet // obtained by incrementing j modulo 26 ) ? // then: h(j) // keep advancing by doing a recursive call : // else: B([ // output the letter j + 1 | // whose ASCII code is j + 1 i & 96 // with bits #5 and #6 taken from i ]) // )(i & 31), // initial call to h with j = i mod 32 B = Buffer, // define B for Buffer g = i => // g is a helper function taking an integer s = 1065233 // representing an ASCII code minus 1, >> i & 1 // returning 0 for consonant / 1 for vowel, // and also saving the result in s ) // end of replace() ``` [Answer] # [sed](https://www.gnu.org/software/sed/) `-E`, 131 bytes ``` s/[A-Z]/@\l&/g y/bcdfghjklmnpqrstvwxyzaeiou/cdfghjklmnpqrstvwxyzbeioua/ :a s/@(.)/\u\1/ s/[b-df-hj-np-tv-z]{2}/!&/i s/!(.)/\1ei/ ta ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ODVlWbSSrqtS7IKlpSVpuhY3m4v1ox11o2L1HWJy1PTTuSr1k5JT0tIzsrJzcvMKCouKS8rKKyqrElMz80v1sckkgWQS9bmsErmK9R009DT1Y0pjDPWBnOgk3ZQ03Yws3bwC3ZIy3arYaqNafUU1_UygnCJYoWFqpj5XSSLEKVAXLVjtkZqTk68Qnl-UkwIRAgA) This code expect that there won't be characters `@` and `!` input. Any two characters could be used instead of those, I think that even unprintable ones should work (at least using escape codes), but I chose to keep it as is to make it readable. Also this program could be made without this restriction, but it would be longer and less interesting. **Explanation:** ``` s/[A-Z]/@\l&/g # lowercase all characters and make note which characters were lowercased # this have to be done because transliteration (following command) is case sensitive # otherwise there would have to also be all uppercase characters y/bcdfghjklmnpqrstvwxyzaeiou/cdfghjklmnpqrstvwxyzbeioua/ # change character to next one :a # beginning of loop s/@(.)/\u\1/ # uppercase back all characters where we made note # it is inside of loop, to save 1B by not using g flag s/[b-df-hj-np-tv-z]{2}/!&/i # make note where to place string ei # this is done so that the long bracket expression doesn't need to be repeated twice # also this command is the reason for loop as sed doesn't supported overlapping replacements s/!(.)/\1ei/ # put ei after noted character ta # repeat till there is nothing to replace ``` [Answer] # [Goruby](https://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby/9289#9289) `-p`, 99 bytes ``` c="aeiou"+b="bcdfghj-np-tv-z" d="eioua"+b[1..]+?b $_.t!c+c.up,d+d.up gsub(/[#{b}]{2}/i){_1.t.j"ei"} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=pVZbb9s2FH73rzhR0lhyHDneBRiCGmk7pJeXFmiBDZjhCRRF22wlSiApN7bk_pG97GHby572c7Zfs0NSki9Niw7LQ0if--U7h_rlN1nG6z-m3mXhzf7p_fXk9tmLl1XvFJ7lhgGFZGmZsGtYal2o69FowfWyjEOaZyMj4P7FaR6PMqI0k6NFns6jRi2UcY-mRCl4Fb9lVPcAHj2yAkuiljCBattD2orJOFdsCGc_3L5-8urNLXLa6xAET1EmYXPImF7mSZRxpbhYQDaEARnCeYxsAI1Ke8anMEW-Yuk8tBHMYAZ1PYGMaLpE7cgZU34WTK9m1gKfo5Hzc3D2AKJIMZFEka-NowCqekDkQtUNGyAOYy4SNBayFUl9r5A5rWobgnWTEE1qOPuAkR0SYesFISVp6p99CIzfsw97Ri3Dugoa6taeLFWsIWi4OQrP1CGAa1BlwaQTF0mv_b9X2KbYvbamx_VQKNPvDyHD00RC4pS1TBePRM7o59NKhTqPVLhQZeyPwlFQeX44uAk8uIDXbMHuipApSgrmn50H2-3I6mbhQrLCl0GocqkjRFiSQ83bmnJn0gZlhFBdl5IZSuGfXyu-YQE8fAj8KMMmGdfuXCjdgYR-Ahx0-AXYoEOw1ojQqoOJBiISkAwDE44dLZj2dVMcwhWDlyRjt1LmcgheKbjgmpMUg086e3Ba0a03tCVm0h8HR5kssTwMTZM4lmzFiea5-ILeGAnXF_szL2VECQY0Af_mcRje_BTAZIIie5jPQgQxu_Od2jprQTcOy0LnSLZVr-pNjZaxocI222wARL-LaxOYBlW1lpjmbj4Eu9NQipThAvAP_FtBjMH86oLs9CwXBibXjtbU27H4Pbi1HCyN6ZPNxJhW7QB9NEFuq9yDoeO6urJ2WDFW3TLDEWxEEPCF5CuiOyUcxJ16Y7wRaf0sfWK6-RzbGZvLe7xQcznpuw4UpVbgnVZky9I0HyJg4m0u08QC5zDmuW8QMb66cppN5zJsmqiNmf5Tvtk8KTebXn_KJ2Iw-ObB5fjbIb8Yfz2ra7HdWUOUEgWKrK371n6SR--XPHW1uwJ7hzVn6VHtUK4UuqnsFdj7gZyVdXV8LCVZdx7zNIls0xroOqqlvM252Fd8SrCL35vrJ7VNLN0MeN7Hzl8IjRtKdgYYoUvQPGNGhQtqHi-4FWXGpMHCvuobBJpYdJojUEXKdW_nlTjEGKrf7-_NtW9TxmkzC4DusHIJ95Ae8KmxJdcIeSJUgSsb5inRmon2PMFlkhUEkdicJ4AB5hR3kDlmQWjSqmpj1A2leabAs1cT7GllWFv31pgHJM3pu3b8DTq7bMz8qTI1a5SEn1XD7Z4SynwSmr61VBxYZ2A3RG3_3V_TELscnCSOMU5Yo4XZvfP7dNA3T1xDs7hw2jjX93ho-qdzubdFrIh7TWyAZlUwFNxZYkfSLccuCnuaCm73MXHg6X5I_qfmT6-bMs5wtUyvjYn_2U3Tyc81rstqP36MrDCLrjk7XktvczwYj3UW5-0H2-5L5tCb-VCyD79kdFV3yKGrsPuoMRvXfNfcF-nePG9_L_X88ru_KZ14hPG89C7iiRfTZL5Yvr0UxaVeXW68XjLxDJMgdzoOw9nFTdw7i0J9Qi8oLsthcpHg0XOfMlOzaWfVV9sRD6poHCLUUNtrXP3aHH8-N2sZfjQr2ZH-BQ) # [Ruby](https://www.ruby-lang.org/), 110 bytes ``` c="aeiou"+b="bcdfghj-np-tv-z" d="eioua"+b[1..]+?b $_.tr!c+c.upcase,d+d.upcase gsub /#{"([#{b}])"*2}/i,'\1ei\2' ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWN_OSbZUSUzPzS5W0k2yVkpJT0tIzsnTzCnRLynSrlLhSbJVAkolA2WhDPb1YbfskLpV4vZIixWTtZL3SguTE4lSdFO0UKJMrvbg0SUFfuVpJI1q5Oqk2VlNJy6hWP1NHPcYwNTPGSB1iK9TyBSuS81NS0_Nz0iB8AA) [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 85 bytes ``` T`_o`A\EIOUA-DF-HJ-NP-TV-ZBaei\oua-df-hj-np-tv-zb i`(?![_aeiou])\w\B(?![_aeiou]) $&ei ``` [Try it online!](https://tio.run/##K0otycxL/P8/JCE@P8ExxtXTP9RR18VN18NL1y9ANyRMN8opMTUzJr80UTclTTcjSzevQLekTLcqiSszQcNeMToeKJtfGqsZUx7jhMznUlFLzfz/3yM1JydfITy/KCeFKzk/JTU9PycNAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` T`_o`A\EIOUA-DF-HJ-NP-TV-ZBaei\oua-df-hj-np-tv-zb ``` Translate each letter in the string to the next letter in the string. `E` and `o` are special so have to be quoted in the replacement string (`o` in the source string refers to a copy of the replacement string) while `-` indicates a character range (also avoids having to quote `H` and `h`). `_` in the source string is just a filler to align the strings. ``` i`(?![_aeiou])\w\B(?![_aeiou]) $&ei ``` Case-insensitively find pairs of consecutive consonants and insert `ei` after the first. [Answer] # [C (clang)](http://clang.llvm.org/), ~~152~~ 149 bytes -3 bytes thanks to ceilingcat!! ``` *i,c,u,p;z(s){i=wcschr(s,c-u);c=i?i[1]:c;}f(*s){for(p=0;c=*s++;p=i)u=c/91*32,z(L"AEIOUA"),z(L"BCDFGHJKLMNPQRSTVWXYZB"),printf("ei%c"+(!p|!i)*2,c+u);} ``` [Try it online!](https://tio.run/##VU/LbsIwELzzFYslJDsxKtBTiaIK@qKUvh/QQg50cehKIURxIipofr2pCUSoe/HszGjGi3UMpuE8zy2SKFMZOWuuxYbcFWr8irmWWE@Fgy6d0rjptdHJfG4Zh7@MeeQ2jGJp23Yil0Tq4tFJ0zpuyTUfsM7F9f1rh4li6Z6dX171@jeD27uHx6fnl7fh6P2ja8QopjDxOVNUQ2bzavRTJWG1JNqmNcuNCIsphVxUNhUwYwgLEqWTsQcu7DgzA9ZTQbCE4TIOZkyavU8LRYsURqlWW@gzeTB/4s6Eimb/pEYBMqdSvOZG4NsvkDl010qeAwS2Cy1xaC@PqAV6EqrvSGGiZm0oVoBY6TRI2mAa9xElsJuecMoQn@/VA1XmTsJJyPZ0VsnyX/SD6Vzn9dUf "C (clang) – Try It Online") [Answer] # [Python](https://www.python.org), 166 bytes ``` f=lambda s,v='UOIEA',c='BZYXWVTSRQPNMLKJHGFDC':s and[y:=(q:=[x:=(t:=s.upper())[0],[v,c][x in c]][x in v+c])[~-q.find(x)],y.lower()][y<s]+'ei'*({*t[:2]}<{*c})+f(s[1:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3l6XZ5iTmJqUkKhTrlNmqh_p7ujqq6yTbqjtFRUaEh4UEBwUG-Pn6eHt5uLu5OKtbFSsk5qVEV1rZahRa2UZXAOkSK9tivdKCgtQiDU3NaINYnegyneTY6AqFzDyF5Fgoo0w7OVYzuk63UC8tMy9Fo0IzVqdSLye_HKQpNrrSpjhWWz01U11Lo1qrJNrKKLbWploruVZTO02jONrQKlYT4todBUWZeSUaaRpKHqk5OfkK4flFOSmKSppQaZinAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes ``` ≔⪪aeiou¹θ≔⁻⪪β¹θη⊞υ⁰⭆S⁺×ei×⊟υΣ⊞Oυ№η↧ι⊟EΦ⟦ιθη↥θ↥η⟧№λι§λ⊕⌕λι ``` [Try it online!](https://tio.run/##RY7NasMwEITveQrh0xpUaM45hUKpIaEGt@QQelDtJVqQJUU/bd5eWdUO3Yt2mNG3M2oVRqdMKfsY6WJh8IYSNArJ5UaKbSvFtd1tVvdINsc18/1wpdCc6HPUkKV4rnsgm2BI/FyOykNnfU6LBI73hiEfNGOEBomvLHvvPGS2hzxDpb17DCq5UKkvLjNRS3FwvxhGFRGo/RvG8b965ZVMwgBn4lLcSYpP79dsLfmvdPv1IBopqDL2qbMT3qru7BhwRptwYqSd1swyu1Le0BgnTi6YaVOefswd "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪪aeiou¹θ ``` Get a list of the vowels in lowercase. ``` ≔⁻⪪β¹θη ``` Subtract them from the lowercase alphabet to leave the consonants.s ``` ⊞υ⁰ ``` Start off with no previous consonant. ``` ⭆S⁺ ``` Map over each input character, joining together... ``` ×ei×⊟υΣ⊞Oυ№η↧ι ``` ... "ei" repeated the number of times the previous character was a consonant times the number of times the current character is a consonant, saving the result for the next iteration, ... ``` ⊟EΦ⟦ιθη↥θ↥η⟧№λι§λ⊕⌕λι ``` ... taking any of the uppercase consonants, uppercase vowels, lowercase consonants or lowercase vowels that contain the character, or as a last resort the original character, cyclically rotating the character in that list. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~28~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žNÃü2D€S„aeý:žNžM‚Du«vyDÀ‡ ``` [Try it online.](https://tio.run/##AUwAs/9vc2FiaWX//8W@TsODw7wyROKCrFPigJ5hZcO9OsW@TsW@TeKAmkR1wqt2eUTDgOKAof//SGVsbG8gV29ybGQJY29kZWdvbGYJYmNk) `ü2D€S` could alternatively be `SãDJs`: [try it online](https://tio.run/##yy9OTMpM/f//6D6/w83Bhxe7eBU/apiXmHp4rxVQ6Og@30cNs1xKD60uq3Q53PCoYeH//x6pOTn5CuH5RTkpnMn5Kanp@TlpnEnJKQA). **Explanation:** ``` žN # Push the consonants constant à # Only keep those characters from the (implicit) input-string ü2 # Pop and push its overlapping pairs as strings D # Duplicate this list of string-pairs €S # Convert each 2-letter string to a character-pair „aeý # Join each pair with "ae" delimiter : # Replace all pairs with the 4-letter strings in the (implicit) input žN # Push the consonants constant žM # Push the vowels constant ‚ # Pair them together Du« # Merge an uppercase copy of this pair vy # Loop over all four strings: D # Duplicate the current string À # Rotate its copy once towards the left ‡ # Transliterate the characters in the input-string # (after which the result is output implicitly) S # Convert it to a list of characters ã # Create all possible character-pairs with the cartesian power of 2 D # Duplicate this list of character-pairs J # Join each inner character-pair to a 2-letter string s # Swap so the character-pair list is at the top of the stack again ``` ]
[Question] [ Given a linear equation `mx+n`, return `n` and `m`. However, the equation may be in any of the following formats: ``` 5x+2 -> 5 2 5x-2 -> 5 -2 5x -> 5 0 -2 -> 0 -2 x -> 1 0 ``` Here are the formats, where each `?` stands for a positive integer written without leading zeroes ``` ?x+? ?x-? -?x+? -?x-? x+? x-? ? -? ?x -?x x ``` All of these cases must be handled. ## Specifications: * You can assume that the equation is in one of the above formats, i.e. it matches the regex `^(-?[123456789]\d*)?x([+-][123456789]\d*)?|-?[123456789]\d*$`. ## Test Cases: ``` -2x+3 -> -2 3 44x -> 44 0 -123 -> 0 -123 x -> 1 0 -1x -> -1 0 ``` [Answer] # [Python 2](https://docs.python.org/2/), 55 bytes ``` j=1j c=eval(input().replace(*'xj')) print c.imag,c.real ``` [Try it online!](https://tio.run/nexus/python2#JYnLDoMgFAV/hd2F@ki0upHwJ25uKW0giAQf4e8RcXNmJue3BrIR7WCMVQ91RvMgz20EHovVO3MYSnX9HUUjTNr5YxcWl88Xp43PyYjOcCnUiZaWk7I2KG9RKvqCaIAx7oN2O5GtXvBfy3yjTekC "Python 2 – TIO Nexus") Uses Python's built-in code evaluation. The input is formatted like a complex number by replacing `x` with`j`, Python's complex unit. Because only literals like `2j` are recognized, but not `j` or `-j`, the variable `j` is assigned as `1j` to cover those. Unfortunately, Python doesn't seem to have a built-in to convert a complex number to a pair of reals. [Answer] ## Mathematica, 16 bytes Inspired by [xnor's Python 2 answer](https://codegolf.stackexchange.com/a/120288/66104): ``` ReIm[I#/.x->-I]& ``` Takes input as a literal expression (not a string), and returns a pair of numbers. It works by making `x` a complex number then taking the real and imaginary parts — the only non-obvious bit is multiplying by *i* to start with, to get the output in the right order. We can also use ``` ReIm[x=-I;I#]& ``` for 14 bytes (tied with Jelly!), but setting `x` to equal *-i* before taking the input, instead of just replacing `x` afterwards, feels like cheating… [Answer] ## JavaScript (ES6), ~~53~~ 48 bytes ``` s=>([a,b]=s.split(/x\+?/),1/b?[a||1,b||0]:[0,s]) ``` ### Test cases ``` let f = s=>([a,b]=s.split(/x\+?/),1/b?[a||1,b||0]:[0,s]) console.log(f("-2x+3")) // -> -2 3 console.log(f("44x")) // -> 44 0 console.log(f("-123")) // -> 0 -123 console.log(f("x")) // -> 1 0 console.log(f("-1x")) // -> -1 0 ``` [Answer] # [sed](https://www.gnu.org/software/sed/), ~~44~~ 42 bytes ``` s:+:: s:x: : t s:^:0 : : s:^ :1 : s: $: 0: ``` [Try it online!](https://tio.run/nexus/sed#Fci7DQAxCATRnCoInKGTjD/JFuMm7GC75yAZPU1cGCAXhEJe4qCnah2Fa0EbtCNi04ZsfhXJVmhT1kr5mDWcPw "sed – TIO Nexus") I/O: one per line. -2 bytes thanks to @KritixiLithos. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”x;ṣ”xVṫ-µ¬ṂW+ ``` Test suite at **[Try it online!](https://tio.run/nexus/jelly#FYs7DsJADET7OUX6yJKz2XwQEhegB3EFTuAySsMloEKiISVbrKAy4iC7F1mcYvw80puSp5tsU7yvPKT4JA26pDgf65LeLw2/z/eS50XD3i7rQ4PxbMnTtaJdZbtTKY3UDk6oBbVSe5AX6tCDBowC2ggEDZvEcGwam2fVG731jtHbOzBGXnWWPw)** ### How? ``` ”x;ṣ”xVṫ-µ¬ṂW+ - Main link: list of characters s examples: "5x-2" "x" "-123" ”x - literal 'x' ; - concatenate with s "x5x-2" "xx" "x-123" ṣ”x - split on 'x's ["","5","-2] ["","",""] ["","-123"] V - evaluate as Jelly code (vectorises) [0,5,-2] [0,0,0] [0,-123] ṫ- - tail from index -1 inclusive [5,-2] [0,0] [0,-123] µ - monadic chain separation (call that z) ¬ - not z [0,0] [1,1] [1,0] Ṃ - minimum 0 1 0 W - wrap in a list [0] [1] [0] + - add to z (vectorises) [5,-2] [1,0] [0,-123] ``` [Answer] # PHP, 73 Bytes ``` preg_match("#((.*)x)?\+?(.*)#",$argn,$t);echo$t[1]?$t[2]?:1:0," ",+$t[3]; ``` [Try it online!](https://tio.run/nexus/php#LY2xDoIwFEV3vsI8GKi0RmADkw6GwUUXN2hIQyo4SMmzQxOjv44Uupx7b85L3olPwxQoRI0tqkmjeY59/Kva6@1@OVekDB4aleyGuAYLFFjqmK11Ze6ag03yza@Z@enTMi/ZJpmXSwr5jiT2I/nME6q@fUmzfIMwjg97YglvEu5aCHQ9o5EhpeoGHZk6FXxhJniRFkcKO6DJsnNRzu4AmhHK4Dv/AQ "PHP – TIO Nexus") # PHP, 91 Bytes works also with `-x` ``` preg_match("#((-)?(\d+)?x)?\+?(-?\d+)?#",$argn,$t);echo$t[2],$t[1]?$t[3]?:1:0," ",$t[4]?:0; ``` [Try it online!](https://tio.run/nexus/php#LY0/D4IwEMV3PoU5GNpAE/44gUkHw@CiixsQQrSCg7Q5OzQx@tWxLSzvvd@9u9yBq0kFAlFij0JJ1M95JL@6P1@up2NNq@AhUQy3iTRgIAHmJPfJa@GSExP7uFq@0eaGrR1bO7Z11rvhHQ04zvSzKBRj/xq0fQUhIYxy0t5jyg3lbcwJ455CSPxBEmlaidskI93knaUm67jVouNlVqYJ7MAN9xbTanGL0M5QBd/lDw "PHP – TIO Nexus") [Answer] ## Mathematica, 23 bytes ``` Coefficient[#,x,{1,0}]& ``` [Try it online](https://sandbox.open.wolframcloud.com/app/objects/) copy and paste with ctrl-v this code ``` Coefficient[#,x,{1,0}]&[-2x+3] ``` and press shift+enter to run [Answer] # [Python 2](https://docs.python.org/2/), 71 bytes ``` lambda s:([0,]+[int(x or`1-i`)for i,x in enumerate(s.split('x'))])[-2:] ``` [Try it online!](https://tio.run/nexus/python2#VY/LCsMgEEX3/YrZqWQsiTGbQL7ECklpAkJeGAP@vVVDCt0Mc@bcu5ipe4V5WN6fAY6WqhJ1oczqqIfN9hU3PZs2CwY9mBXG9VxGO7iRHs9jn42jxBPGNFNctDqkpEObkkqRxheCoGpQaI0J@YX85kxlhqzKWyVT/Ywv6shcYJ0PUiYt5e0rUV/duPy3dfuA3cZnYKKOYRpdZ8MX "Python 2 – TIO Nexus") [Answer] # Mathematica, 33 bytes ``` #~CoefficientList~x/.{a_}:>{a,0}& ``` Pure function taking an expression in the expected format (note: not a string, but a pure expression like `-2x+3`), and returning an ordered pair of integers with the constant coefficient appearing first (for example, `-2x+3` returns `{3,-2}`). The builtin `CoefficientList` (which works for polynomials of any degree) does the heavy lifting; its default behavior is to return constants as length-1 lists, so `/.{a_}:>{a,0}` overrides that and makes the `0` coefficient of `x` appear explicitly. [Answer] # [Retina](https://github.com/m-ender/retina), 38 bytes ``` x$ x+0 ^[^+-]*$ 0x+$+ ^[^-\d] 1$+ - +- ``` Definitely can be improved. Possibly stretching how we are allowed to format output. It just outputs a complete equation, as in `n` and `m` separated by `x+` [Try it online!](https://tio.run/nexus/retina#@1@hwlWhbcAVFx2nrRurpcJlUKGtog3i6sakxHIZAtm6XNq6//9X6BoCAA "Retina – TIO Nexus") [Answer] # [Octave](https://www.gnu.org/software/octave/), 45 bytes ``` @(a)[imag(u=eval(strrep(a,'x','j'))),real(u)] ``` [Try it online!](https://tio.run/nexus/octave#TcvBCoMwDMbx@54il5EEm6K1V8X3EA891LGxwahz9O1rSx3smF/@3zpordNEjuf7y91oH/zXPWn7hODf5BRGVPhAZlbB58fOS1oJxcSmR4YryAhioL9ktDZmgorWQltQOlPCii2Us3AtT@5@6d9eMqYD "Octave – TIO Nexus") Evaluate the expression, with `x` replaced by complex `j`. Octave is very flexible when it comes to complex expressions, with `j`,`1j`,`i` and `1i` all equivalent (with the advantage that `1j` and `1i` cannot be overwritten by variables, but that's irrelevant for this challenge). Inline expression is used to build a list of `[imag(u) real(u)]` with `u` the complex number. I initially wanted to try a more idiomatic approach, using the built-in `sym2poly`. For example (already at 47 bytes to make sure `0*x` is handled): ``` @(a)sym2poly([strrep(a,'x','*x') '+x^2']))(2:3) ``` This one however failed on the case of `x` without coefficient. In the end a real/complex setup like `xnor` turned out to be optimal. [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` 120'i'ZtU&Zj ``` [Try it online!](https://tio.run/nexus/matl#@29oZKCeqR5VEqoWlfX/v3qFtqU6AA "MATL – TIO Nexus") Port of my Octave answer, but of course adapted for compactness in MATL. Explanation: ``` 120'i'Zt % Replace character 120 ('x') by 'i' in input (implicit). % (Used 120 instead of 'x' to save a separator between 'x' and 'i') U % Convert string to complex number &Zj % Split complex number in real and imaginary part. Implicit display. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/),~~145~~ ~~138~~ 112 bytes ``` f(char*s){int a,b,i=0;sscanf(s,"%dx%d",&a,&b);if(L!=0)i=(int)(L-s);printf("%d %d",s[i]=='x'?a:0,s[i]=='x'?b:a);} ``` [Try it online!](https://tio.run/nexus/c-gcc#TY7BDoIwEETvfMUKQbpaDcGEA7X6A/yB8VAolU20mhYSEuO3a/Gic9uX2ZlJyLbXUXd7P2i6b/tDlPyII3v5It0Zsh3UEFjbO@Z5NmUIEdkBbooswycYFu@KoGldFkUZowAA1w2js5CL19uwtldu5fE5PynecJK58L5V1oS8ONVTqmO@VHzZoCDD6oXMkSQLdmT1xqN4hD1DqEk1zFZ/orOUYchRVfnf1VQKQ@H7Aw "C (gcc) – TIO Nexus") ``` void f(char*s) { int a,b,i=0; sscanf(s,"%dx%d",&a,&b); if(L!=0) i=(int)(L-s); printf("%d %d",s[i]=='x'?a:0,s[i]=='x'?b:a); } ``` Can definitely be shortened, but dont see it now! ]
[Question] [ **This question already has answers here**: [Mathematical Combination](/questions/1744/mathematical-combination) (36 answers) Closed 7 years ago. Given two nonnegative integers `n,k` such that `0 <= k <= n`, return the binomial coefficient ``` c(n,k) := (n!) / (k! * (n-k)!) ``` ### Test cases Most languages will probably have a built in function. ``` c(n,0) = c(n,n) = 1 for all n c(n,1) = c(n,n-1) = n for all n c(5,3) = 10 c(13,5) = 1287 ``` ### Related challenges [Catalan Numbers](https://codegolf.stackexchange.com/questions/66127/catalan-numbers) [Compute the multinomial coefficient](https://codegolf.stackexchange.com/questions/69424/compute-the-multinomial-coefficient) [Generate Pascal's triangle](https://codegolf.stackexchange.com/questions/3815/generate-pascals-triangle) [m-nomial coefficient](https://codegolf.stackexchange.com/questions/78343/m-nomial-coefficient) [Answer] ## JavaScript (ES6), 27 bytes ``` f=(n,k)=>k?n*f(n-1,k-1)/k:1 ``` [Answer] # MATL, 2 bytes ``` Xn ``` [try it online!](http://matl.tryitonline.net/#code=WG4&input=NQoz) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` c ``` [Try it online!](https://tio.run/nexus/jelly#@5/8//9/Q@P/pgA "Jelly – TIO Nexus") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 11 bytes ``` l~S*\0e]e!, ``` [Try it online!](https://tio.run/nexus/cjam#@59TF6wVY5Aam6qo8/@/obGCKQA "CJam – TIO Nexus") ### Explanation This uses a trick that (I think) I first used [for the Catalan numbers challenge](https://codegolf.stackexchange.com/a/66130/8478). CJam doesn't have a built-in for this, and computing three factorials is too expensive. But the binomial coefficient `c(n,k)` is the number of ways we can select `k` out of `n` elements. That is, it's equal to the number of permutations of a list of `n` elements where `k` of them have one value and the remaining have another. ``` l~ e# Read and evaluate input. Dumping n and k on the stack. S* e# Get a string of k spaces. \0e] e# Pad to length n with zeros. e! e# Get the unique permutations. , e# Count the number of such permutations. ``` [Answer] # Haskell, ~~37~~ 35 bytes ``` n#0=1 0#k=1 n#k=(n-1)#(k-1)*n`div`k ``` [Answer] # Mathematica, 8 bytes ``` Binomial ``` Yup. Sample usage: `Binomial[13,5]` or `13~Binomial~5` to obtain `1287`. [Answer] # Matlab, 8 bytes There is a builtin for this calculation: ``` nchoosek ``` [Answer] ## Haskell, 34 bytes ``` n#k|k<1||k>=n=1|m<-n-1=m#(k-1)+m#k ``` Usage example: `13#5` -> `1287`. A variant with the same size for the `k<1||k>=n`test is `n*k-k*k<1`. [Answer] # J, 1 byte ``` ! ``` ### Usage: ``` 3!5 10 5!13 1287 ``` [Answer] ## [Jellyfish](https://github.com/iatorm/jellyfish), 6 bytes ``` pCi i ``` [Try it online!](https://tio.run/nexus/jellyfish#@1/gnMmlkPn/v6ExlykA "Jellyfish – TIO Nexus") `C` is the built-in for binomial coefficients, the `i`s are replaced with one input each, `p` prints the result. [Answer] # [Python 2](https://docs.python.org/2/), 33 bytes ``` f=lambda n,k:k<1or n*f(n-1,k-1)/k ``` Note that this will return *True* if **k = 0**, which [seems to be allowed by default](http://meta.codegolf.stackexchange.com/a/9067/12012). [Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnk22VbWOYX6SQp5WmkadrqJOta6ipn/2/oCgzr0QhTcNUx1iTC8YxNNYx1fwPAA "Python 2 – TIO Nexus") [Answer] # Pyth, 3 bytes ``` .cF ``` A program that takes input in the form `n,k` and prints the result. [Test](http://pyth.herokuapp.com/?code=.cF&input=13%2C5&debug=0) **How it works** This simply folds `c(n,k)` over the input. [Answer] # [Actually](https://github.com/Mego/Seriously), 1 byte Input is of the form `k<newline>n`. [Try it online!](https://tio.run/nexus/actually#@/9oWsf//8ZcpgA "Actually – TIO Nexus") ``` █ ``` [Answer] # [Perl 6](https://perl6.org), 23 bytes ``` {+combinations $^n,$^p} ``` ``` {[*] ($^n...0)Z/1..$^p} ``` ( Both are were based on code found at [examples.perl6.org](http://examples.perl6.org/categories/best-of-rosettacode/binomial-coefficient.html "Best of RosettaCode: Binomial Coefficient"), and [RosettaCode](http://rosettacode.org/wiki/Evaluate_binomial_coefficients#Perl_6 "RosettaCode: Binomial Coefficient") ) [Answer] # [MATL](http://github.com/lmendo/MATL), 10 bytes ``` :i:&G-:h/p ``` [Try it online!](http://matl.tryitonline.net/#code=Omk6JkctOmgvcA&input=MTAwCjkw) This does the computation manually, without the builtin: ``` : % Take input n implicitly. Range % STACK: [1 2 ... n] i: % Take input k. Range % STACK: [1 2 ... n], [1 2 ... k] &G- % Push n and k again. Subtract % STACK: [1 2 ... n], [1 2 ... k], n-k : % Range % STACK: [1 2 ... n], [1 2 ... k], [1 2 ... n-k] h % Concatenate the top two arrays horizontally % STACK: [1 2 ... n], [1 2 ... k 1 2 ... n-k] / % Element-wise division % STACK: [1/1 2/2 ... k/k (k+1)/1 (k+2)2 ... n/(n-k)] p % Product of array. Implicitly display % STACK: 1/1 * 2/2 * ... * k/k * (k+1)/1 * (k+2)2 * ... * n/(n-k) ``` ]
[Question] [ **This question already has answers here**: [Display number of occurrences for every character in an input string](/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string) (66 answers) Closed 7 years ago. **GOAL :** To Implement a character counting program This is how this counting system works : input of the program is a set of *printable* ASCII characters . the program counts each type of character , and outputs the number of each character , starting from first mentioned character to last mentioned character . Example : ``` input : aaaabbbbbcccc 123445b output : 4 6 4 4 1 1 1 2 1 ``` Which `4` is number of `a`s , `6` is number of `b`s , `4` is number of `c`s , `4` is number of spaces () and so on . Also you can split answers with space (like example) , EOL , or anything other than numerals . **Rules** Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available. Your program must be a full, runnable program, and not a function or snippet It's optional to mention the ungolfed version of program and/or a short explanation . **Test input :** `ThIs Is ThE iNPUT , WITH 72/2 CHARS!` **Test output :** `4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1` [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` 8#u ``` Input is a string enclosed with quotation marks (which is [allowed by default](http://meta.codegolf.stackexchange.com/q/7633/36398)) [**Try it online!**](http://matl.tryitonline.net/#code=OCN1&input=J2FhYWFiYmJiYmNjY2MgICAgMTIzNDQ1Yic) ### Explanation `u` is the `unique` function, which essentially removes duplicates. It can produce up to four outputs. The fourth output is the count of unique characters, identified in order of appearance. `8#` specifies that the fourth output of `u` should be produced. In general, `2#` means "produce two outputs", `3#` means "produce three outputs" etc. When the maximum number of function outputs is reached, larger numbers mean "take the *first* output only", or "the *second* only" etc. Thus, since `u` has four possible outputs, `4#` would produce all four outputs; `5#` produces the first, `6#` the second, etc. [Answer] ## 05AB1E, 6 bytes ``` Ùv¹y¢, ``` **Explained** ``` Ùv # for each unique char in original order ¹y¢ # count number of occurances in input string , # print on newline ``` [Try it online](http://05ab1e.tryitonline.net/#code=w5l2wrl5wqIs&input=YWFhYWJiYmJiY2NjYyAgICAxMjM0NDVi) [Answer] # Pyth, 4 bytes ``` /LQ{ ``` [Test suite.](http://pyth.herokuapp.com/?code=%2FLQ%7B&test_suite=1&test_suite_input=%22aaaabbbbbcccc++++123445b%22%0A%22ThIs+Is+ThE+iNPUT+%2C+WITH+72%2F2+CHARS%21%22&debug=0) ### Explanation ``` /LQ{ Input: Q /LQ{Q Implicitly fill arguments {Q Yield the unique elements of Q. L For each unique element: / Yield its number of occurrences Q in Q. ``` [Answer] # J, ~~18~~ 15 bytes ``` echo#/.~stdin'' ``` Following the challenge spec to write a program, the above is a one-line script in J that reads a line from stdin, computes the result, and prints it to stdout. If using an online interpreter, it would require **4 bytes** since without stdio, only function arguments could be used. ``` #/.~ ``` Straight-forward application of adverbs `/.` and `~` to the tally `#` verb. ## Usage As a script, ``` $ echo -n 'aaaabbbbbcccc 123445b' | jconsole golf.j 4 6 4 4 1 1 1 2 1 ``` As a function, ``` (#/.~) 'aaaabbbbbcccc 123445b' 4 6 4 4 1 1 1 2 1 ``` ## Explanation ``` #/.~ Input: s ~ Reflects the input /. An adverb that executes a verb on each set of identical items in s Operates in the order of first-seen distinct items in s # Get the size of each set of identical items Returns a list of the sizes of identical items ``` [Answer] ## CJam, 9 bytes ``` l__&\fe=p ``` [Test it here.](http://cjam.aditsu.net/#code=l__%26%5Cfe%3Dp&input=aaaabbbbbcccc%20%20%20%20123445b) ### Explanation ``` l e# Read input. __ e# Make two copies. & e# Set intersection - removes duplicates. \ e# Swap with input. fe= e# For each (unique) character, count its occurrences. p e# Print as array literal. ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9411/43319) # Shortest by byte count ``` +⌿t∘.=∪t←⍞ ``` `t←⍞` get character input and store as *t* `∪' unique elements of `t∘.=` table of which elements of t are equal to (the unique elements of t) `+⌿` sum the columns ### 5 character solution which unfortunately is 15 bytes: ``` ⊢∘≢⌸⍞ ``` `⍞` get character input `⌸` make a table of contents containing... `⊢∘≢` the tally (`≢`) of the indices while the entries are ignored (`⊢`) [Answer] ## Jelly, 4 bytes ``` Qċ@€ ``` [Try it online](http://jelly.tryitonline.net/#code=UcSLQOKCrA&input=&args=VGhJcyBJcyBUaEUgaU5QVVQgLCBXSVRIIDcyLzIgQ0hBUlMh) ## Explanation ``` Qċ@€ Main link. Argument: S Q Remove duplicate characters from S. Current value v contains each character of S once sorted by first appearance. @€ For each character in v. ċ count its occurrence in S. ``` [Answer] ## Mathematica, 56 bytes ``` Print@StringRiffle[Last/@Tally@Characters@InputString[]] ``` Essentially, `Tally` does exactly what the challenge asks for (although it gives pairs of `{element, count}`). The rest is just for working with strings and proper I/O for a full program. [Answer] # Retina, ~~30~~ 28 bytes 2 bytes thanks to Martin Ender. ``` +`((.).+)\2 $2$1 (.)\1* $.&¶ ``` [Try it online!](http://retina.tryitonline.net/#code=K2AoKC4pLispXDIKJDIkMQooLilcMSoKJC4mwrY&input=YWFhYWJiYmJiY2NjYyAgICAxMjM0NDVi) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 32 bytes ``` :efd:?:{tL,?he:L:{t:.m~h?}fl.}f. ``` Awfully long but there's no simple way of counting elements of something yet… [Answer] # Java 7, ~~246~~ ~~235~~ ~~231~~ 213 bytes Loads of bytes removed thanks to *cliffroot*. ``` import java.util.*;class M{public static void main(String[]a){Map<Long,Long>m=new LinkedHashMap();for(long c:a[0].toCharArray())m.put(c,m.get(c)!=null?m.get(c)+1:1);for(Long e:m.values())System.out.print(e+" ");}} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/7KUzHR) ``` import java.util.*; class Main{ public static void main(String[] a){ // Test code: a = new String[]{ "ThIs Is ThE iNPUT , WITH 72/2 CHARS!" }; Map<Long, Long> m = new LinkedHashMap(); for(long c : a[0].toCharArray()){ m.put(c, m.get(c) != null ? m.get(c) + 1 : 1); } for(Long e : m.values()){ System.out.print(e + " "); } } } ``` **Output:** ``` 4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1 ``` [Answer] # Python 3, ~~134~~ 81 bytes ``` s,r=input(),[] for c in s: k,s=s.count(c),s.replace(c,'') if k:r+=[k] print(*r) ``` **Output:** ``` 4 2 3 2 7 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1 ``` Not that short :( --- **Another approach: 109 bytes** Not shorter than the others but the counting happens in a one-liner. ``` s=input() k=[i[1]for i in sorted({i:str(s.count(i))for i in s}.items(),key=lambda v:s.index(v[0]))] print(*k) ``` --- **Edit:** Golfed 53 bytes thanks to @Dr Green Eggs and Iron Man **Edit 2:** Added one-liner method [Answer] # Java 7, ~~172~~ 168 bytes ``` class M{public static void main(String[]a){int[]m=new int[256];byte[]b=a[0].getBytes();for(int z:b)m[z]++;for(int z:b){System.out.print(m[z]>0?(m[z]+" "):"");m[z]=0;}}} ``` Stores number of occurrences in an int array, then for each char print number of occurrences and replace this value with zero so it won't be printed again. Whitespaces and comments added: ``` class M{ public static void main(String[]a){ int[]m=new int[256]; // map, ascii value to number of occurrences byte[b]=a[0].getBytes(); for(int z:b)m[z]++; // count number of occurrences for(int z:b){ System.out.print(m[z]>0?(m[z]+" "):""); // print result m[z]=0; // make it not be printed again } } } ``` See it online: <https://ideone.com/7X58F9> [Answer] **C#** ``` public static void Main(string[] args) { string str = "aaaabbbbbcccc 123445b"; Dictionary<char, int> counts = new Dictionary<char, int>(); for (int i = 0; i < str.Length; i++) if (counts.ContainsKey(str[i])) counts[str[i]]++; else counts.Add(str[i], 1); foreach (var count in counts) Console.WriteLine("{0} = {1}", count.Key, count.Value.ToString()); } ``` [Answer] # ES6, 90 bytes ``` a=prompt();b=new Map();for(c of a)b.set(c,(b.get(c)|0)+1);alert([...b.values()].join(' ')) ``` [Answer] ## Python 3, ~~76~~ 73 bytes 3 bytes shorter: ``` s,a=input(),[] for y in s:a+=(y,'')[y in a] print([s.count(x)for x in a]) ``` Old version: ``` s=input();print([s.count(x)for x in sorted(set(s),key=lambda i:s.index(i))]) ``` Iterates over a sorted set of unique characters from the input, counts the occurrences, and outputs a list of the counts. [Answer] ## Python 3, 93 bytes ``` s=input();c,o=[],"" for i in s: if i not in c:c+=i for i in c:o+=str(s.count(i))+" " print o ``` [Answer] ## Matlab, 47 chars ``` @(y)arrayfun(@(x)sum(y==x),unique(y,'stable')) ``` Reasonably straightforward, though the default behavior of Matlab's `unique` function to sort the values makes the function rather longer. [Answer] ## Pyke, 3 bytes ``` }F/ ``` [Try it here!](http://pyke.catbus.co.uk/?code=%7DF%2F&input=ThIs+Is+ThE+iNPUT+%2C+WITH+72%2F2+CHARS%21) ``` for i in uniquify(input): print input.count(i) ``` [Answer] **Python 2.7 - 103 Bytes (Ungolfed)** ``` i=list(raw_input()) print ''.join([str(e) for e in map(lambda x,y:x!=y and i.count(x)or' ',i,['']+i) ]) ``` **edit:** Thanks to [Dr Green Eggs and Iron Man](https://codegolf.stackexchange.com/users/31716/dr-green-eggs-and-iron-man) for helping to reduce 47 Bytes! ]
[Question] [ Write a program which will take for input 2 integer arrays and return a truthy value if there exists an element which is present in both of arrays, or a falsy one otherwise. The obvious solution to this problem would be to iterate through each element in the first array and compare it against each element in the second, but here's the catch: Your program must have an algorithmic complexity of at most, in the worst case, O(NlogN), where N is the length of the longer array, Test cases: ``` {1,2,3,4,-5},{5,7,6,8} -> false {},{0} -> false {},{} -> false {1,2},{3,3} -> false {3,2,1},{-4,3,5,6} -> true {2,3},{2,2} -> true ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # [Actually](http://github.com/Mego/Seriously), 1 byte ``` ∩ ``` [Try it online!](http://actually.tryitonline.net/#code=4oip&input=ezEsMn0KezMsM30) This is merely the set intersection built-in. The resultant value is the intersection of the two sets - a non-empty list (which is a truthy value) if there is an intersection, and an empty list (which is a falsey value) otherwise. ## Complexity According to the [Python Wiki](https://wiki.python.org/moin/TimeComplexity#set), set intersection has a worst-case time complexity of `O(N*M)` (where `N` and `M` are the lengths of the two sets). However, the time complexity is only that bad when the two sets contain distinct objects that all have the same hash value (for example, `{"some string"} & {hash("some string")}`). Since the set elements are only integers in this case (and no two integers hash to the same value unless they are equal), the actual worst-case complexity is `O(min(N, M))` (linear in the length of the smaller of the two sets). The construction of each set is `O(N)` (linear in the number of elements), so the overall complexity is `O(max(N, M))` (the complexity is dominated by the construction of the larger set). [Answer] # TSQL, ~~40~~ ~~37~~ 36 bytes SQL doesn't have arrays, it is using tables instead Returns -1 for true or 0 for false ``` DECLARE @ table(a INT) DECLARE @2 table(b INT) INSERT @ values(1),(2),(3),(4),(-5) INSERT @2 values(5),(6),(7),(8) SELECT~-sign(min(abs(a-b)))FROM @,@2 ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/1086537/check-if-2-arrays-contain-the-same-element)** [Answer] # Ruby, 37 bytes: ``` exit ($*.map{|x|eval x}.reduce:&)!=[] ``` As in the definition: "program which will take for input 2 integer arrays and return a truthy value if...", this is a program, accepts 2 arrays as strings in input, returns true or false. as a function - 14 bytes: ``` ->a,b{a&b!=[]} ``` ## Complexity: The ruby documentation of the itnersection (&) operator says "It compares elements using their hash and eql? methods for efficiency.", which I suppose is exactly what we are looking for. Empirically: ``` $ time ruby a.rb "[*1..1000001]" "[*1000001..2000000]" real 0m0.375s user 0m0.340s sys 0m0.034s $ time ruby a.rb "[*1..2000001]" "[*2000001..4000000]" real 0m0.806s user 0m0.772s sys 0m0.032s $ time ruby a.rb "[*1..4000001]" "[*4000001..8000000]" real 0m1.932s user 0m1.857s sys 0m0.073s $ time ruby a.rb "[*1..8000001]" "[*8000001..16000000]" real 0m4.464s user 0m4.336s sys 0m0.119s ``` Which seems to confirm it. [Answer] # Perl, 25+1 = 26 bytes in collaboration with Dada ``` print 2<($a{$_}|=$.)for@F ``` Run with `-a` (1 byte penalty). An improved version of the program below (which is kept around to see the history of the solution, and to show the solution I found by myself; it also has more explanation). The `-a` option reads space-separated arrays as the input, storing them in `@F`. We use the `%a` dictionary (accessed as `$a{$_}`) to store a bitmask of which input arrays the input is in, and print `1` every time we see an element in both arrays, i.e. a value higher than 2 inside the resulting bitmask (fortunately, a failing comparison returns the null string, so the `print` does nothing). We can't use `say` because a newline is truthy in Perl. Performance is asymptotically the same as the older version of the program (but faster in terms of constant factors). # Perl, 44+1 = 45 bytes ``` $a{"+$_"}|=$.for split}{$_={reverse%a}->{3} ``` Run with `-p` (1 byte penalty). Input one array per line, separating the elements by spaces. This works via creating a hash table `%a` that stores a bitmask of the input arrays that a value has been seen in. If it's been seen in both the array on line 1 and on line 2, the bitmask will therefore store the value 3. Reversing the hash and seeing if 3 has a corresponding key lets us know if there are any values in common. The complexity of this algorithm is O(n) if you consider hash creation to be constant time (it is, if you have bounded integers, like Perl does). If using bignum integers (which could be input into this program, as it leaves the input as a string), the complexity of the algorithm itself would nominally be O(n log n) for each hash creation, and O(n) for the hash reversal, which adds up to O(n log n). However, Perl's hashing algorithm suffers from potential O(n²) performance with maliciously selected input; the algorithm is randomized, though, to make it impossible to determine what that input is (and it's possible that it can't be triggered simply with integers), so it's debatable what complexity class it "morally" counts with. Luckily, this doesn't matter in the case where there's only finitely many possible distinct elements in the array. This code will work for input other than integers, but it won't work for more than two arrays (because the `3` is hardcoded and because input on the third line wouldn't bitmask correctly, as it isn't a power of 2). Rather annoyingly, the code naturally returns one of the duplicate elements, which is truthy in *almost* all cases, but `"0"` is falsey in Perl and a valid duplicate element in the array. As such, I had to waste three bytes prepending a `+` to the output, which is the cheapest way I found to give a truthy output in the edge case of the arrays overlapping at `0`. If I'm allowed to use notions of truthy and falsey from a language other than Perl (in which any nonempty string is truthy), you can change `"+$_"` to `$_` to save three bytes. [Answer] # Python2 - ~~41~~ 30 bytes ``` lambda a,b:bool(set(a)&set(b)) ``` Set intersection: O(min(N,M)) where N and M are the length of the sets. Conversion from a list to a set: O(max(N,M)) * Thanks to [Jakube](https://codegolf.stackexchange.com/users/29577/jakube) for saving 9 bytes! `set(a).intersection(b)` -> `set(a)&set(b)` * Thanks to [Kade](https://codegolf.stackexchange.com/users/38417/kade) for saving 2 bytes! -> removed `f=` [Answer] # Axiom, 439 bytes ``` c:=0;s(x,y)==(free c;if x.1=%i and y.2=%i then(x.2<y.1=>return true;x.2>y.1=>return false;c:=1;return false);if x.2=%i and y.1=%i then(x.1<y.2=>return true;x.1>y.2=>return false;c:=1;return false);if x.1=%i and y.1=%i then(x.2<y.2=>return true;x.2>=y.2=>return false);if x.2=%i and y.2=%i then(x.1<y.1=>return true;x.1>=y.1=>return false);false);r(a,b)==(free c;c:=0;m:=[[%i,j] for j in a];n:=[[i,%i] for i in b];r:=merge(m,n);sort(s,r);c) ``` this convert the first list in a list as [[i,1], [i,2]...] the second list in a list as [[1,i], [0,i]...] where i is the variable imaginary than merge the 2 list, and make one sort that would find if there is one element of list 1 in the list 2 so it is at last O(N log N) where N=lenght list 1 + lenght list 2 ungolfed ``` -- i get [0,0,1,2,3] and [0,4,6,7] and build [[%i,0],[%i,0],[%i,1],[%i,2] [%i,3],[0,%i],..[7,%i]] c:=0 s(x:List Complex INT,y:List Complex INT):Boolean== free c -- [%i,n]<[n,%i] if x.1=%i and y.2=%i then x.2<y.1=> return true x.2>y.1=> return false c:=1 return false if x.2=%i and y.1=%i then x.1<y.2=>return true x.1>y.2=>return false c:=1 return false if x.1=%i and y.1=%i then x.2< y.2=>return true x.2>=y.2=>return false if x.2=%i and y.2=%i then x.1< y.1=>return true x.1>=y.1=>return false false r(a,b)== free c c:=0 m:=[[%i, j] for j in a] n:=[[ i,%i] for i in b] r:=merge(m,n) sort(s, r) c ``` results ``` (12) -> r([1,2,3,4,-5], [5,7,6,8]), r([],[0]), r([],[]), r([1,2],[3,3]), r([3,2,1],[-4,3,5,6]), r([2,3],[2,2]) Compiling function r with type (List PositiveInteger,List Integer) -> NonNegativeInteger Compiled code for r has been cleared. Compiled code for s has been cleared. Compiling function r with type (List PositiveInteger,List PositiveInteger) -> NonNegativeInteger Compiled code for r has been cleared. Compiling function s with type (List Complex Integer,List Complex Integer) -> Boolean Compiled code for s has been cleared. (12) [0,0,0,0,1,1] Type: Tuple NonNegativeInteger ``` i dont understand why it "clears" code for r and s... [Answer] ## PowerShell, ~~88~~ ~~78~~ ~~77~~ 23 bytes ``` !!(diff -Inc -Ex $A $B) ``` Thanks to @briantist for shaving off a whopping 54 bytes from my original, more verbose answer by shortening `-IncludeEqual`, `-ExcludeDifferent`, and `-Not`! ``` ~~if(-Not(diff -IncludeEqual -ExcludeDifferent $A $B)){("false")}else{("true")}~~ ``` I can't find the source for `Compare-Object` (`diff` is an alias for `Compare-Object`), so I'm not certain on the time complexity. [Answer] # [PHP](https://php.net/), 15 bytes ``` array_intersect ``` [Try it online!](https://tio.run/##bZDLasMwEEX3/orBeKHC2GnsOC3k0V2/oDvVGOFIKKXYQlIWoeTb3ZHiFupaCyHuPbrzMNqM@xejTZJkXjrv4AA8AeDA11hihRvM6wZ5jU@4xecGGoTVKj@CEp9O3kGS@GN0ZmcJXOL@gVSaalZYzek5WFGPa0LzDbVa4/aXj6C3l4mjSYgqKXYpMHLNjlagDqOwVlzbc@@ldbLzI8lqsFJ0msG0IuHoBQ/wReGy0wM4b1sjTgw@3NC3su@Gk2SRQSjrcKeQ7ojOBO03UwyKogh20M4KWDDueTBFpm/24vU1/rqBpIn/2q9hCZP900b63pNwG78B "PHP – Try It Online") A PHP built-in, as a [callable](https://www.php.net/manual/en/language.types.callable.php)/lambda function. Return is a PHP `truthy`/`falsey` testable value. Also, per the other PHP submission, this implementation should meet the challenge complexity requirements ([StackExchange](https://stackoverflow.com/questions/6329211/php-array-intersect-efficiency/6329397#6329397)). [Answer] ## R, 23 bytes ``` sum(scan()%in%scan())>0 ``` If we assume that there will always be one and only one element matching and that `1` is a truthy value (which it is in **R**), then we can write : ``` sum(scan()%in%scan()) ``` which is 21 bytes. [Answer] # PHP, ~~55~~ 51 bytes ``` <?=count(array_intersect($_GET[a],$_GET[b]))<1?0:1; ``` Usage: save in a file and call from browser: `intersect.php?a[]=1&a[]=2&a[]=3&b[]=0&b[]=4&b[]=5` outputs `0` for `false`. `intersect.php?a[]=1&a[]=2&a[]=3&b[]=0&b[]=4&b[]=1` outputs `1` for `true`. About complexity, I couldn't find references but according to this [StackOverflow's post](https://stackoverflow.com/a/6329397/2096343) the script should be OK [Answer] # GolfScript, 1 byte If taking the input directly as arrays on the stack is allowed, this one-byte GolfScript solution should meet the spec: ``` & ``` If text-based I/O is required, the input needs to be evaluated first, pushing the length up to *two* bytes: ``` ~& ``` Both of these solutions use the GolfScript array intersection operator, which is implemented using [the corresponding operator in Ruby](http://ruby-doc.org/core-2.3.3/Array.html#method-i-26). They return an empty array (which is falsy) if the arrays contain no matching elements, or a non-empty array (which is truthy) containing all the matching elements otherwise. I have so far not been able to find any documentation on the internal implementation or asymptotic complexity of the Ruby array intersection operator, beyond the brief statement that "It compares elements using their hash and eql? methods for efficiency." However, a reasonable implementation using hash tables would run in O(*n*) time (assuming that hashing and comparisons are O(1)), and some quick performance testing suggests that this is indeed the case: [![Log-log plot of execution time vs. input size](https://i.stack.imgur.com/VG8aI.png)](https://i.stack.imgur.com/VG8aI.png) These tests were carried out using the GolfScript program `~2?.2*,/&`, which takes an integer *k*, generates an arithmetic sequence of 2 × 2*k* elements, split it into two arrays of 2*k* elements and computes their (obviously empty) intersection. The red stars show the measured execution time *t* in seconds (on a logarithmic scale) for various values of *k*, while the green line plots the function *t* = *c* × 2*k*, where the scaling constant *c* ≈ 2−17.075 was chosen to best fit the measured data. (Note that, on a log-log plot like this, *any* polynomial function of the form *t* = *c* × (2*k*)*a* would yield a straight line. However, the slope of the line depends on the exponent *a*, and the data is certainly consistent with *a* = 1 as shown by the green line above. FWIW, the numerical best-fit exponent for this data set was *a* ≈ 1.00789.) [Answer] ## JavaScript (ES6), 39 bytes ``` (a,b,c=new Set(b))=>a.some(e=>c.has(e)) ``` Will be worse than O(n+m) but hopefully not as bad as O(n\*m). [Answer] ## Rust, 103 bytes ``` |a:&[i32],b:&[i32]|!b.iter().collect::<std::collections::HashSet<_>>().is_disjoint(&a.iter().collect()) ``` Takes two array slices (or references to full arrays, they dereference to slices automatically), bundles them up into sets, and checks for non-disjointness. I'm not quite sure how set union is implemented in the Rust standard library, but it should be O(n + m) at worst. Without using collections, the easiest alternative I see is to sort both arrays, then step over them carefully to look for duplicates. Something like this ``` fn overlapping(a: &Vec<i32>, b: &Vec<i32>) -> bool{ let mut sa = a.clone(); sa.sort(); let mut sb = b.clone(); sb.sort(); let mut ai = 0; let mut bi = 0; while ai < a.len() && bi < b.len() { if sa[ai] < sb[bi] { ai += 1; } else if sa[ai] > sb[bi] { bi += 1; } else{ return true; } } false } ``` But that requires too much mutation to be fun to golf in Rust IMO :) [Answer] ## Python, 11 bytes ``` set.__and__ ``` Builtin that takes 2 sets and does an intersection on them [Answer] # Axiom, ~~50~~ 221 bytes ``` binSearch(x,v)==(l:=1;h:=#v;repeat(l>h=>break;m:=(l+h)quo 2;x<v.m=>(h:=m-1);x>v.m=>(l:=m+1);return m);0);g(a,b)==(if #a>#b then(v:=a;w:=b)else(v:=b;w:=a);c:=sort(v);for x in w repeat(if binSearch(x,c)~=0 then return 1);0) ``` ungolfed ``` --suppose v.1<=v.2<=....<=v.#v -- binary serch of x in v, return the index i with v.i==x -- return 0 if that index not exist --traslated in Axiom from C book --Il Linguaggio C, II Edizione --Brian W.Kerninghan, Dennis M.Ritchie binSearch(x,v)== l:=1;h:=#v --1 4 repeat l>h=>break m:=(l+h)quo 2 --m=(4+1)/2=5/2=2 --output [l,m,h] x<v.m=>(h:=m-1) --l x m h => x>v.m=>(l:=m+1) return m 0 g(a,b)== if #a>#b then (v:=a;w:=b) else (v:=b;w:=a) c:=sort(v) --output c for x in w repeat(if binSearch(x,c)~=0 then return 1) 0 ``` g(a,b) gets the more big array beetwin a and b; suppose it has N elements: sort that array, do binary search with elements that other array. This would be O(Nlog(N)). It return 0 for no element of a in b, 1 otherwise. results ``` (6) -> g([1,2,3,4,-5], [5,7,6,8]), g([],[0]), g([],[]), g([1,2],[3,3]), g([3,2,1],[-4,3,5,6]), g([2,3],[2,2]) Compiling function binSearch with type (PositiveInteger,List Integer ) -> NonNegativeInteger (6) [0,0,0,0,1,1] Type: Tuple NonNegativeInteger ``` [Answer] # [Jelly](//github.com/DennisMitchell/jelly), 2 bytes ``` œ& ``` [Try it online!](//jelly.tryitonline.net#code=xZMm&args=WzMsMiwxXQ+Wy00LDMsNSw2XQ) Explanation ``` œ& Main link. Arguments: x y ⁸ (implicit) x ⁹ (implicit) y œ& Intersection of x and y ``` ]
[Question] [ Recently there was [a question on Stack Overflow](https://stackoverflow.com/questions/31509311/return-the-first-word-with-the-greatest-number-of-repeated-letters) where the OP was trying to write a function to find the word in a string that has the most repeated letters. It is of course not hard to write one up in seconds, and [I wrote one in Javascript](http://jsfiddle.net/DerekL/d1v5tzze/) as short as I can for fun. But I'm not an expert in code golfing, so I wonder how much shorter can this simple program be! --- ## Challenge Write a program or function that takes in a string of words and return or print the word with the most repeating single letters. Rules: * Choose the word with the greatest number of repeating *single* letters (see examples below) * If no word has repeating letters, return -1. * If two words have the same maximum number of repeating letters, choose the one closer to the start of the string. * The shortest submission in bytes wins. ## Input Take as input a string consisting of one or more space-delimited words. Input can be from STDIN (or closest alternative), command line parameters, or function arguments. ## Output Print the output to STDOUT to return it. ## Examples Consider the string `aaabbb cccc`. This contains two words: `aaabbb` and `cccc`. The word `aaabbb` has 3 `a`'s and 3 `b`'s, and `cccc` has 4 `c`'s. So the maximum number of repeated letters in `aaabbb` is 3 and the maximum in `cccc` is 4. We want to choose the word with the maximum number of repeated single letters, so the output for `aaabbb cccc` should be `cccc`. Other test cases: ``` Today, is the greatest day ever! --> greatest This is a great day --> -1 aaabbb cccc --> cccc ``` [Answer] # C - GCC - ~~159~~ ~~145~~ 135 Bytes ``` x=0,w=0,i,j,c;main(int _,char**z){while(--_)for(j=i=0;_[z][i];j=++i,x=c>x?w=_,c:x)for(c=0;j--;)c+=z[_][i]==z[_][j];puts(x?z[w]:"-1");} ``` Will update when I can truncate it a bit How to compile: gcc -w cg.c How to run: ./a.out word1 word2 aass ddaaa ssdddd Output: ssdddd No-Output/No-match: -1 First off, I cheated a bit, by taking in the words as program arguments, but getting GCC to parse the words and give me a word count for free was too much reward to pass up. ### How does it work? We have 3 nested loops. The first incrementing through each word, the next two are mimicking a bubble sort to compare values. The first letter is never compared with itself, and each subsequent letter is compared to each previous letter. Whenever a word has more same letters than a previous word, the word is stored in x, and the count of how many same letters is also stored. ### GCC Abuse We use implicit global auto int delcarations for our integers. We allow argv to be an int instead of a char (currently a char, this is a TODO). We make use of default functions such as puts and getchar. We also make use of the comma operator to overload our trinary (conditional) operator. ### Want 2 less bytes? Replace "-1" with \*z and name the file -1 ### Program unobfuscated and untested: ``` int main(int argc, char * argv[]) { int word = 0 // Current most repeat letters word int count = 0; // Current most repeat letters int i, j, increment; // Counter variables while(--argc != 0) // While we have words from program parameters { for(j = i = 0; argv[argc][i] != '\0'; j = ++i) // Iterate through each letter until end of word { for(increment = 0; j > 0; j--) // Iterative backwards through each letter { if(argv[argc][i] == argv[argc][j]) { increment++; } } if(increment > count) // New greatest lettered word { word = argc; count = increment; } } } if(word == 0) { puts("-1"); } else { puts(argv[word]); } return 0; } ``` [Answer] # Pyth, 14 bytes ``` eoeS/LNN+czd_1 ``` [Demonstration.](https://pyth.herokuapp.com/?code=eoeS%2FLNN%2Bczd_1&input=Hello%20world!&debug=0) [Test harness.](https://pyth.herokuapp.com/?code=Fz%2Bz.zeoeS%2FLNN%2Bczd_1&input=Today%2C%20is%20the%20greatest%20day%20ever!%0AThis%20is%20a%20great%20day&debug=0) ``` eoeS/LNN+czd_1 Implicit: z = input(), d = ' ' czd chop z on delimeter d. + _1 Add an -1 to the end of the list. o Order the list by eS the maximum of /LN the occurence count in the word N of letters in the word. (If we are mapping over -1, this will give -1/-1 = 1) Since Python's sort is stable, this will leave -1 at the end if all words have maximum repetition count 1. e Take the final element of the resulting list and print it. ``` [Answer] # K, 35 bytes (missing -1 requirement, just noticed, but time to sleep) ``` {1#w[>{|/{#:&:x=y}[x]'x}'w:" "\:x]} ``` ### how it works: 1 take ``` 1# ``` of the words indexed by ``` w[ ``` the indices to put in ascending order ``` > ``` the maximum ``` |/ ``` count where ``` #:&: ``` string = char ``` x=y ``` for each char in word ``` 'x ``` for each word where `w` (words) are ``` 'w: ``` the string split by spaces ``` \:x ``` Obviously I sacrificed a bit of precision for expressiveness and legibility in the English explanation. I hope it was interesting. [Answer] # Haskell, 100 bytes ``` import Data.List f=g.last.sort.map((,)=<<last.sort.map length.group.sort).words g(1,_)="-1" g(_,w)=w ``` Usage example: `f "Today, is the greatest day ever!"` -> `"greatest"` How it works: ``` words -- split input at spaces into list of words map( ) -- for each word (,)=<< -- build a pair, where the second element is the word itself -- and the first element is made by sort -- sort the letters group -- group equal letters map length -- take length of each group sort -- sort the lengths last -- take the last -- now we have a list of (l,w) pairs where l is how often the most frequent letter occurs for word w sort -- sort the list last -- take last element g -- call g which checks the "-1" case ``` ## Haskell, ~~79~~ 77 bytes (untested) ``` import Data.List last.sortOn(last.sort.map length.group.sort).words.(++" -1") ``` This uses `sortOn` from `Data.List` v4.8.0.0, which I don't have installed, so I cannot test it. [Answer] # CJam, 25 bytes ``` lS/{_$e`$W=0=(\}%2/$W=~W? ``` [Try it online](http://cjam.aditsu.net/#code=lS%2F%7B_%24e%60%24W%3D0%3D(%5C%7D%252%2F%24W%3D~W%3F&input=aaabbb%20cccc) Explanation: ``` lS/ Get input and split at spaces. { Start of loop over all words. _ Copy, need to keep original word. $ Sort letters. e` RLE. $ Sort RLE result. Sort is increasing by count. W= Get last count/letter pair, which corresponds to largest count. 0= Extract count from pair. ( Decrement count, so that it has a falsy value when the count is 1. \ Swap count and word, so that we can sort the pairs by count. }% End of loop over words. 2/ Split list into pairs, which are the count/word pairs. $ Sort the pairs. W= Get last one, which is the largest count. ~ Unwrap the pair. W? Output word if count is truthy, -1 otherwise. ``` [Answer] # Python 2, ~~97~~ 77 Bytes Fairly straightforward solution, just maps the input (surrounded by quotes) to a tuple containing the word and the number of repeated characters. Gets the maximum, and prints out the word if the most repeated letter is repeated at all, otherwise it prints -1. I saved 20(!) bytes by rearranging the order of input so that I didn't need a key for finding the max. ``` j=max((max(map(x.count,x)),x)for x in input().split()) print[-1,j[1]][j[0]>1] ``` [Answer] # SWI-Prolog, ~~158~~ ~~154~~ 149 bytes ``` a(A,R):-split_string(A," ","",B),findall(X:Z,(member(Z,B),string_codes(Z,D),length(D,L),sort(D,E),length(E,M),X is M-L,X<0),S),sort(S,[_:R|_]);R= -1. ``` Example: `a("Today, is the greatest day ever!",R).` outputs `R = "greatest" .`. [Answer] # JavaScript, ~~86~~ ~~111~~ 108 bytes ``` s=>(l=(x=s.split` `,r=x.map(l=>(/(.)\1+/.exec(l)||[''])[0].length),x)[r.indexOf(k=Math.max(...r))],k<2?-1:l) ``` Definitely golf-able, the whole -1 thing added about 20 bytes. [Answer] # R, 107 bytes ``` w=scan(,"");l=sapply(w,function(x)max(table(strsplit(x,"")[[1]])));cat(ifelse(max(l)>1,w[which.max(l)],-1)) ``` This reads from STDIN and prints to STDOUT. Ungolfed + explanation: ``` # Read a string and split it into a vector on spaces w <- scan(, "") # Get the maximum number of letter repeats in each element of w l <- sapply(w, function(x) max(table(strsplit(x, "")[[1]]))) # If the largest number in l is 1, print -1, otherwise get the word cat(ifelse(max(l) > 1, w[which.max(l)], -1) ``` [Answer] # C# 166 Bytes ``` string a(string i){var z=i.Split(' ');int g=1,c=0;var m="-1";foreach(var w in z)foreach(var l in w.Distinct()){c=w.Where(x=>x==l).Count();if(c>g){g=c;m=w;}}return m;} ``` Straightforward coding. Nothing Special in here. C# sucks for code golfing :-/ [Answer] # JavaScript (*ES7?*), 99 Using array comprehension, that is implemented in Firefox but no more included in EcmaScript 6. Test using the snippet below (Firefox only) ``` f=s=>s.split(' ').map(w=>[for(c of(l=[m=0],w))(n=l[c]=-~l[c])>m?m=n:0]&&m>x&&(x=m,v=w),x=1,v=-1)&&v // TEST out=x=>O.innerHTML+=x+'\n'; test=x=>out(x+' -> '+f(x)) ;["aaabbb cccc","This is a great day","Today, is the greatest day ever a!"] .forEach(t=>test(t)); ``` ``` <pre id=O></pre> Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button> ``` **Ungolfed** And more compatible ``` function f(s) { v = -1; x = 1; s.split(' ') .forEach(function(w){ l=[]; m=0; w.split('').forEach(function(c){ n=l[c]=-~l[c]; if (n>m) m=n; }) if (m>x) x=m,v=w; }) return v; } // TEST out=function(x) { O.innerHTML+=x+'\n' } test=function(x) { out(x+' -> '+f(x)) } ;["aaabbb cccc","This is a great day","Today, is the greatest day ever a!"] .forEach(function(t) { test(t)} ); ``` ``` <pre id=O></pre> Try:<input id=I><button onclick='test(I.value),I.value=""'>-></button> ``` [Answer] # Python, 58 ``` max('-1',*input().split(),key=lambda w:len(w)-len(set(w))) ``` [Answer] ## C (167) ``` double m,k,n=k=2,*O,V[256];char*f(char*c,char*s){return*c?((*O=!((n+=!(*c*=*c!=32))>1.1/modf(*(O=V+*c),&m))*m+1/n+1)>k)?f(c+!!(k=*O),c):f(c+1,s):s?!*s?s+1:f(c,s-1):0;} ``` [TRY IT](http://rextester.com/WPSJ34507) **HOW DOES THIS WORK?** * the function is inner recursive one inside another recursive function, the insider function retrieves the beginning of a string where an inclusive character is returned by first function. * maximum number is given by hashing characters over an ascii table. [Answer] # Q (44 bytes) ``` {w l?0|/l:{max(#:)'[(=)x]}'[w:" "vs"-1 ",x]} ``` ### ungolfed ``` { words:" " vs "-1 ",x; counts:{max count each group x} each words; : words counts ? max counts; } ``` [Answer] **Haskell 96 Bytes** --- ``` r o=(last.sort.map length$(group.sort)o,o) w p=n$maximum(map(r)(words p)) n (1,_)="-1" n (_,w)=w ``` ``` --- `r` is a function that takes a word and return a tuple `(n,w)` where `n` is the number of occurrence of the most occurring char in the word `w`. For instance let `x="norep", y="dnredundant"`, then `r x=(1,norep), r y=(3,ndredundant)` `w` is a function that takes a string containing a number of space-separated words and: 1. Split the list on space `words p` 2. foreach word create a list of `(n,w)` 3. take the tuple that has the greatest `n` (occurrence counter) 4. If it has n equals to 1 simply return the string `-1`, the word itself (stored in the second component of the tuple) otherwise. For instance take `p="Today, is the greatest day ever!"` 1. produces `["Today,","is","the","greatest","day","ever!"]` 2. `[(1,"Today,"),(1,"is"),(1,"the"),(2,"greatest"),(1,"day"),(2,"ever!")]` 3. (2,"greatest") 4. 2 != 1 then `greatest` is the solution! [Answer] # Pure Bash (no external commands) 129 bytes This is quite long, but still compares favourably with some of the other longer entries. ``` m=1 w=-1 for b;{ declare -A a for((i=0;i<${#b};i++));{ c=${b:$i:1} let a[$c]++ d=${a[$c]} ((d>m))&&w=$b&&m=$d } unset a } echo $w ``` I'm not entirely happy with some of the constucts, having to use that inner for loop is annoying. Any suggestions? ]
[Question] [ Rosetta Stone Code Challenges are challenges where you must complete the task in as many languages as possible. ## The Challenge You will be given two numbers, `n` and `s`, in a list as input. The `n` will be a number you have to count up to. `n` will be any number from 2 to 10000. `s` will be the number you skip by when counting up to `n`. `s` will be from 1 to `n`/2 (half of `n`). If `n` was 600, `s` could not be greater 300. You have to output all of the numbers up to `n` skipping by `s` starting with 1. Each output number should either be on a newline, on the same line separated by spaces, or in a list. ## The Twist For this Rosetta Stone Code Challenge, each snippet you write the program in must be the same length. ie: If your Python program has 56 characters then your Java program must also be 56 characters. Spaces and comments do not count as characters. Variable/function names can't be more than 10 characters. Remember, this is also code golf, so try to keep your code short. ## Example ### Input ``` [100, 7] ``` ### Output ``` 1 8 15 22 29 36 43 50 57 64 71 78 85 92 99 ``` *Note: Output could be in single line separated by spaces or list format* ## Winning Criterion The winner will be decided by this formula: `numberOfLanguages/codeSize` `codeSize` is not the total code size but the average code size of a snippet. The user with the highest score will win. ie: An answer with 4 languages and a size of 31 bytes would win over an answer with 7 languages and a size of 80 bytes. A winner will be chosen at 2:00 UTC on March 9, 2015. ## Scoreboard All scores are rounded to the nearest thousandth [Maltysen](https://codegolf.stackexchange.com/a/47043/26936) - 14 languages / 24 characters = 0.583 ---- **Winner** [mbomb007](https://codegolf.stackexchange.com/a/47040/26936) - 15 languages / 29 characters = 0.517 [Jakube](https://codegolf.stackexchange.com/a/47047/26936) - 5 languages / 11 characters = 0.455 [Teun Pronk](https://codegolf.stackexchange.com/a/46983/26936) - 4 languages / 51 characters = 0.078 [captncraig](https://codegolf.stackexchange.com/a/46992/26936) - 1 language / 56 characters = 0.018 [Answer] # 23 languages, 15 characters = 1.5333333 ``` +---------------+----------------------+----------------+ | Language | Code | Kind | +---------------+----------------------+----------------+ | gs2 | B/4[RRRRRRRRRRR | (stack) | | Pyth | M%+Z+Z+Z+Z+ZHSG | (definition) | | GolfScript | \),000000001>%p | (stack) | | CJam | \),000000001>%p | (stack) | | zsh | seq 00000001 $2 $1 | (script) | | Bash | seq 00000001 $2 $1 | (script) | | FlogScript | \),0000001>\%Pa | (stack) | | APL | {00001+⍵×⍳⌈⍺÷⍵} | (lambda) | | Mathics | 00001~Range~##& | (lambda) | | Mathematica | 00001~Range~##& | (lambda) | | J | ({.\00001+i.)~- | (lambda) | | Matlab | @(a,b)00001:b:a | (lambda) | | Octave | @(a,b)00001:b:a | (lambda) | | Burlesque | jrojcoq-]m[m]uN | (stack) | | K | {0001+&~(!x)!y} | (lambda) | | Pip | {_%b=001FI,++a} | (lambda) | | Haskell | ff a b=[1,b+1..a] | (definition) | | Clean | ff a b=[1,b+1..a] | (definition) | | Curry | ff a b=[1,b+1..a] | (definition) | | Frege | ff a b=[1,b+1..a] | (definition) | | Julia | ff(a,b)=[1:b:a] | (definition) | | Scotch | f(a,b)=[1..a,b] | (definition) | | Perl6 | {1,$^b+1...$^a} | (lambda) | +---------------+----------------------+----------------+ ``` [Answer] # 14 Languages - 24 bytes = 0.58333333333 \*\*Facepalm\*\*. I forgot not to count the space in my Python answer. So I'm at 24 bytes now. Learned about a lot of new languages from this challenge, which I will probably using in golfs. A site that really helped me find these languages was <http://www.tutorialspoint.com/codingground.htm>. Just don't expect my programs to run in it, it requires a full program format, and I just used it to learn about the languages and used other REPLs to run them. ## 1. [Pyth](http://pyth.herokuapp.com): Pyth doesn't have a range by step function unlike python, so I used regular range and chopped (thanks @Jakube) used mod operator on it. ``` M%Hr+Z+Z+Z+Z+Z+Z+Z+Z1+1G ``` Defines a function g(until, step) ``` M Define g(G, H) %H Every H elements r1+1G Range 1->G+1 ``` ## 2. Golfscript: This is my first golfscript program. Probably not the best way to do it. ``` 000000000000000;\),1>\%p \ swap ) increment , range 1> all but first element \ swap % take every top of stack elements p print array ``` ## 3. Bash Utils: Uses the seq command which has INCREMENT param. ``` seq 00000000000000001 $2 $1 ``` ## 4,5. Python, [Sage](http://www.sagemath.org/): Self-explanatory code. ``` lambda a,b:range(1,a+1,b) ``` Sage is a language based on Python used for math stuff. ## 6. Mathematica: Again, self-explanatory. ``` r[a_,b_]:=Range[001,a,b] ``` ## 7. Matlab: Uses Matlab's range notation and defines an anonymous function. ``` @(a,b)00000000000001:b:a ``` ## 8. Livescript: Like Coffeescript it is a JS derivative. Has cool range syntax. Arrow notation again. ``` r=((((a,b)->[1 to a by b]))) ``` ## 9. Erlang: Learned erlang just for this. Pretty self explanatory, defines function r. ``` r(a,b)->lists:seq(1,a,b) ``` ## 10. F#: Kind of obvious, F#'s function definitions are like variables. ``` let r a b=seq{000001..b..a} ``` ## 11. Haskell: Haskell's range notation has you give the first two in the range for the increment, and not an explicit increment. ``` r a b=[00000000001,a+1..b] ``` ## 12. R: Very cool language, even if function definitions are a little verbose. ``` function(a,b)seq(01,a,b) ``` ## 13. Julia: *Awesome* language, will be using for golfing in the future. ``` r(a,b)=[00000000001:b:a] ``` ## 14. CJam: Like my old golfscript answer except with input parsing and padding. ``` 0000000000000;q~\),1>\%p ``` [Answer] # 5 languages 11 characters = 0.4545 Took this challenge as an opportunity to check out some new languages (CJam, Burlesque, zsh, gs2). First time I've worked with these languages. The method behind creating the output is different in nearly each language. Only the CJam and the gs2 method are identical. The 4 methods are, creating a range [1, 100] and slice it with modulo (CJam and gs2), creating the range [1, ..., 100] and filter for elements that are 1 mod 7 (Pyth), creating the range [1, ..., 100], divide it into chunks of len 7 and use the first element of each chunk (Burlesque), and creating the sequence directly (zsh). I tried to design each program in such a way, that it looks golfed to someone, who is not familiar with the language. edit 1: added Burlesque, previous 2 languages with 10 characters = 0.2 edit 2: added gs2, previous 3 languages with 11 characters = 0.2727 edit 3: added zsh, previous 4 languages with 11 characters = 0.3636 ## CJam ``` q~\1+,0-\%p ``` Test it [online](http://cjam.aditsu.net/#code=q~%5C1%2B%2C0-%5C%25p&input=100%207) with the input `100 7`. ``` q~ push the evaluated input (100 7) \ swap (7 100) 1 push 1 (7 100 1) + add last to elements (7 101) , create the range (7, [0, 1, ..., 100]) 0 push 0 (7, [0, 1, ..., 100], 0) - delete 0 from the range (7, [1, 2, ..., 100]) \ swap ([1, 2, ..., 100], 7) % use every 7th entry ([1, 8, ..., 99]) p print pretty ``` ## Burlesque ``` jrojcoq-]m[ ``` Beside zsh, this is the only golfed program. Burlesque is quite awesome, it has a very large range of different functions, like `ro`. Sadly there's nothing like the Python `[::a]` slicing operator. There is no online interpreter, but you can get Burlesque [here](http://mroman.ch/burlesque/getstarted.html). Since Burlesque doesn't support functions or IO, you have to put the values onto the stack first, like `100 7 jrojcoq-]m[` ``` j Swap (7 100) ro Range (7 {1 2 ... 100}) j Swap ({1 2 ... 100} 7) co ChunksOf ({{1 2 .. 7} {8 ... 14} ... {99 100}}) q Create Block ({{1 2 .. 7} {8 ... 14} ... {99 100}} {}) -] head (first element) ({{1 2 .. 7} {8 ... 14} ... {99 100}} {-]}) m[ map the chunks to the head-block ``` ## gs2 ``` read-nums dup head inc range tail swap reverse head mod unlines ``` Yep, this is only 11 chars. In gs2 each byte has a different meaning. But because writing in bytes is quite hard and not any fun, you can also write in mnemonics, which you can compile to the actual gs2 code. The gs2 code, which gets executed is ``` W@!'."B !4+ ``` or as hex-dump: ``` 57 40 21 27 2e 22 42 20 21 34 2b ``` Fun fact: I didn't write in mnemonics, but directly the numbers of the hex-dump. You can test it by downloading the [compiler](https://github.com/nooodl/gs2). Compile the mnemonics file with `python gs2c.py < mnemonics.txt > compiled` or simply copy `W@!'."B !4+` to a file named `compiled` and then execute it with `echo 100 7 | python gs2.py compiled`. The mnemonics is pretty self explainable, but here's what's going on in the stack. ``` 57 40 21 27 2e 22 42 20 21 34 2b 57 read-nums ([100 7]) 40 dup ([100 7] [100 7]) 21 head ([100 7] 100) 27 inc ([100 7] 101) 2e range ([100 7] [0 1 ... 100]) 22 tail ([100 7] [1 2 ... 100]) 42 swap ([1 2 ... 100] [100 7]) 20 reverse ([1 2 ... 100] [7 100]) 21 head ([1 2 ... 100] 7) 34 mod ([1 8 ... 99]) 2b unlines ('1\n8\n...\n99') everything on the stack gets printed ``` Btw, 8 bytes are possible, maybe even less. edit: I forked gs2, slightly manipulated a command and made a pull request, which is already merged. So now the task can be done with 6 bytes: `read-nums extract-array swap range1 mod unlines`, which translates to `57 0e 42 2f 34 2b`, which is even better than the optimal pyth. ## zsh ``` f() seq 1 $2 $1 ``` This defines a function `f`, that creates the a sequence. To use it on Windows, I installed the [babun](http://babun.github.io/) shell, where you can simply type these commands. Simply write `f() seq 1 $2 $1` and in the next line `f 100 7`. First I tried to write this in Bash, but there you have to write `()` around the code block, like `f() ( seq 1 $2 $1 )`. So I switched to zsh instead. ## Pyth ``` fq1%TeQUhhQ ``` This really hurts, since of course I see the obvious 7 byte golf. You can test it [online](https://pyth.herokuapp.com/) with the input `100, 7`. ``` Q = input() UhhQ the range [0, 1, ..., Q[0]] f filtered (only use those elements T, which satisfy the equation q1%TeQ 1 == T % Q[1] ``` [Answer] ## 15 languages, 29 characters = (15/29) ≈ 0.517 I've fixed all my code so far. Now I'm searching for other languages. **1. Python** (24 golfed) ``` f=lambda n,s:range(0001,n+1,s) ``` **2. ><> (Fish)** - (19 + junk chars) This program assumes that the number and the step size were are on the stack beforehand, pushed in that order. Uses `ao` to print newlines between numbers. ``` 1 v $:@+:{:}(?!;>:nao ~~~~~~~~~~ ``` Explanation (code, stack after preceding code executes, comments): ``` 1 1 s n start n0=1. stack is (top)1 s n(bottom) (skip to print code - last line of explanation, then come back) $:@ s 1 s n swap, duplicate, rotate top 3 (this all is OVER in Forth) +: n1 n1 s n add step to x and dup {:} n n1 n1 s n compare to n ( n1>n n1 s n if !(n1 > n), JUMP: dup and print (continue) ?!; n1 s n else exit :nao n1 s n dup, print n1, newline, loop around ``` **3. APL** (19 golfed) ``` fffffffff←{(⌈⍵÷⍺)↑1+⍺∘.×(⍳⍵)} ``` *Golfed*. Paste into here: <http://ngn.github.io/apl/web/> ``` f←{(⌈⍵÷⍺)↑1+⍺∘.×⍳⍵} ``` Call like this: `7 f 100`. This creates an array from 1 to n, multiplies every element by s, adds one to each element, then takes the first ceil(n/s) elements. **4-7. Haskell**, **Clean**, **Curry**, **[Frege](http://try.frege-lang.org/)** (14 golfed - spaces don't count) This program is valid in Haskell, Clean, Curry, and Frege. ``` ffffffffff nnnn s=[1,s+1..nnnn] ``` *Golfed.* Run here: <https://ideone.com/Ii0pgP> ``` f n s=[1,s+1..n] ``` **8. [Scotch](https://github.com/bendmorris/scotch/wiki/Docs)** (15 golfed) ``` fffffffff(nnnn,s)=[1..nnnn,s] ``` **9. [Jaskell](http://jaskell.codehaus.org/)** (24 golfed) - Built based on documentation. Filter the list where the remainder modulo s is 1. ``` ffffff n s=filter(.%s==1)[1..n] ``` **10. CoffeeScript** (25 golfed) Run [**here**](http://coffeescript.org/#try:f%3D(n%2Cs)-%3Ex%20for%20x%20in%5B1..n%5Dby%20s%0Aalert%20f(100%2C7)%0A%0A) ``` fffff=(n,s)->x for x in[1..n]by s ``` **11. R** (25 golfed) Run here: <http://www.r-fiddle.org/#/fiddle?id=k3vRnCOW&version=2> ``` fffff=function(n,s)seq(1,n,s) ``` **12. Cobra** (26 golfed) ``` def ffff(n,s) for i in 1:n:s print i ``` **13. S-Lang** (28 golfed) ``` define ff(n,s){return [1:n:s];} ``` **14. Boo** (29) Not sure if range function can take 3 parameters... ``` def f(n,s):return range(n)[::s] ``` **15. Funge-98** (29, any help golfing?) As close as I could get to my ><> program. Since there's no "rotate" stack instruction, I had to use "put" and "get" instead. Befunge *really* needs some stack rotation/shift instructions, or even an "over" instruction. ``` 22p1v >:.a,\:33p\33g+:22g\`!j@ ``` Explanation: ``` n s 22p s (store n at 2,2) 1 1 s (push 1) (v and > are direction changes, so the above only happens once) \: s s 1 (swap, dup) 33p s 1 (store s at 3,3) \33g s 1 s (get s) +: n1 n1 s (add, dup) 22g n n1 n1 s (get n) \`! !(n1>n) n1 s (swap, >, not) j@ n1 s (conditional exit) :.a, n1 s (print n1, newline) ``` --- --- **NOT USING AT THE MOMENT, TOO LONG** - My score is improved by not including these. **Ruby** (35) Run here: <http://ideone.com/yFZELR> ``` def f(n,s) (1..n).select{|x|x%s==1} end ``` **PowerShell** (38) ``` function f($n,$s){(1..$n|?{$_%$s-eq 1})} ``` **Perl** (39) Run here: <https://ideone.com/HGoleN> ``` sub f{join(" ",grep $_%@_[1]==1, 1..@_[0])} ``` [Answer] # 4 languages 51 characters = (4/51) = 0,0784313725490196 No idea how many numbers after comma you want so i'll just leave it like this. All snippets are 51 characters long when you remove all the whitespace. Working on more and shorter code but it's a start. # Log **Initial answer** Submitted Python(3.4), Lua(5.1) and Javascript. Score: 3/51 = 0,0588235294117647 **Update 1** Added Ruby Score: 4/51 = 0,0784313725490196. ### Python 3.4 ``` def f(NUMB,ST): CNT=1 while CNT<=NUMB: print(CNT) CNT+=ST ``` ### Lua 5.1 ``` function f(num,st) for cn=1,num,st do print(cn); end; end; ``` ### Javascript ``` function f(n,s){ for(i=1;i<=n;i+=s){ console.log(i); } } ``` ### Ruby ``` def faa(numb,st) for i in 1..numb if i%st==1 puts i end end end ``` [Answer] # 1 language - 56 characters = 0.01785714285 ## piet (2x28) - ![http://www.pietfiddle.net/img/JpdU9zE1lR.png?cs=15](https://i.stack.imgur.com/Fbb44.png) ]
[Question] [ In informatics, we often use trees in lots of different forms and representations. The three major methods of serialising binary trees are prefix, infix and postfix notation. For example, the following binary tree: ![Tree, infix: rbxabde](https://i.stack.imgur.com/j6eGN.png)   *(source: Dutch Olympiad in Informatics, finals, 2012/13)* can be represented in prefix notation as `abrxdbe`, in infix as `rbxabde` and in postfix as `rxbbeda`. In this case, you are confronted with a complete binary tree represented in **infix** notation. Your task is to **convert this tree to prefix notation**. Your **input** on stdin will be 2*n*-1 lowercase alphabet characters, a-z and no more, ended with a newline character, for any integer *n* such that 1 ≤ *n* ≤ 16. Thus, the maximum number of characters you will get is 65535. **Output** the tree to stdout in the same way, but then in prefix format. This is code golf, so the shortest code, counted in bytes, will win. Votes will act as a tie breaker, and if those tie up as well, submission date and time. [Answer] # GolfScript, 23 chars ``` .,\{;).2base{)!}do}$/n- ``` This solution uses a different approach than Howard's: basically, it sorts the input characters according to the list of branches needed to reach that character from the root of the tree. Note that the newline at the end of the input is *required* (i.e. the input length must be a power of two). The `n-` at the end of the code is required to suppress an extra newline at the beginning of the output; if such a newline is acceptable, those characters can be omitted for a score of **21** chars. As usual, you can [test this code online.](http://golfscript.apphb.com/?c=IyBDYW5uZWQgaW5wdXQ6CjsicmJ4YWJkZVxuIgoKIyBQcm9ncmFtOgouLFx7OykuMmJhc2V7KSF9ZG99JC9uLQ%3D%3D) Explanation: * `.,\` calculates the length of the input, and moves it below the input string on the stack. It will be used as the starting value of the loop counter used to construct the sort keys below. (The code relies on this being a power of two; otherwise the bit manipulation below will not produce the expected results. Any sufficiently large power of two would work, though.) * `{ }$` sorts the characters in the input string according to the sort key computed inside the block: + `;` just throws away the character given as input to the block; we don't care about the actual character values here, just about their positions within the string. + `).` increments the loop counter on the stack (which was initialized to the length of the input string) and makes a copy of it. + `2base` converts this copy to an array of bits (omitting leading zeros; that's why we need to start counting from a large enough power of two, rather than simply from zero). + `{)!}do` repeatedly chops off the lowest bit from the array until the chopped-off bit is a `1`.Since the resulting sort keys are arrays, the `$` compares them lexicographically. Thus, for example, the array `[1]` (which corresponds to the root node) sorts before `[1 0]` (which corresponds to the left child of the root node) and `[1 1]` (the right child of the root node). * At the end, `/` gets rid of the loop counter by using it as the length of chunks to split the output string into (thanks, Peter!), and `n-` strips the newline off the sorted input string. (The GolfScript interpreter will append another newline to the output after printing the contents of the stack.) [Answer] ### GolfScript, 28 characters ``` {.,1>{.,)2//([)\c]\~c+}*}:c~ ``` You may test the code [online](http://golfscript.apphb.com/?c=OyIzMjQxNjU3IgoKey4sMT57LiwpMi8vKFspXGNdXH5jK30qfTpjfg%3D%3D&run=true). *Annotated code:* ``` # define an operator c acting on the top of stack which does the conversion { # if the input string is more than a single character .,1>{ # split string into two halves (rounded up) .,)2// # take first part last character ([) # take first part rest and call c recursively \c] # get second part \~ # call c recursively on second part c # join all three together + }* }:c # call c ~ ``` [Answer] ## GolfScript (29 chars) ``` {.,1>{.,)2//~\[)](f@f++}*}:f~ ``` [Online demo](http://golfscript.apphb.com/?c=OydyYnhhYmRlCicKCnsuLDE%2Bey4sKTIvL35cWyldKGZAZisrfSp9OmZ%2B) Works with or without the trailing newline in input. [Answer] ## APL (48) (Yes, the APL charset does [fit in a byte](http://www-03.ibm.com/systems/resources/systems_i_software_globalization_pdf_cp00907z.pdf).) ``` {1=⍴⍵:⍵⋄(⊃a),⊃,/∇¨1↓a←1⌽⌽⍵⊂⍨(⍳⍴⍵)∊1,0 1+⌈.5×⍴⍵}⍞ ``` Explanation: * `{`...`}⍞`: read input, feed to function * `1=⍴⍵:⍵`: if the input length is one, we're done * `⋄`: otherwise: * `(⍳⍴⍵)∊1,0 1+⌈.5×⍴⍵`: make a bitfield of places to split the input (first character, middle character and character past the middle character) * `⍵⊂⍨`: split the input at these places * `a←1⌽⌽`: rotate the sub-arrays so that the middle character is first, the left hand is second and the right hand is third, and store in `a`. * `⊃,/∇¨1↓a`: run the function again on the last two elements of `a` and concatenate the results * `(⊃a),`: and concatenate that to the first item in `a` [Answer] # Python 3 - 76 ``` def f(x):a=len(x)//2;return x and x[a]+f(x[:a])+f(x[a+1:]) print(f(input())) ``` [Answer] # C, 108 chars My code uses a recursive function, which always prints the character in the middle of the buffer, and calls itself with the part of the string before and the part of the string after the character printed. (Divide and Conquer) ``` char b[65536];d(s,e){int c=s+(e-s)/2;putchar(b[c]);if(c^s)d(s,c-1),d(c+1,e);}main(){gets(b);d(0,strlen(b));} ``` ungolfed: ``` char b[65536]; d(s,e){ int c=s+(e-s)/2; putchar(b[c]); if(c^s)d(s,c-1),d(c+1,e); } main(){ gets(b); d(0,strlen(b)); } ``` ]
[Question] [ Write a program to produce a file containing a crossword grid that the user can print out and work the puzzle on. ## Input A filename representing a crossword grid file and optionally a second filename representing a crossword numbering file. The input should be accepted by a conventional means for your programming environment: command line arguments, the standard input, web forms, etc.. You may assume that the [crossword has been validated](https://codegolf.stackexchange.com/questions/883/crossword-grid-verification), and if using a [numbering file that is corresponds to the grid provided](https://codegolf.stackexchange.com/questions/318/crossword-numbering). **Grid file format:** The first line consists of two white-space separated integer constants M and N. Following that line are M lines each consisting of N characters (plus a new line) selected from `[#A-Z ]`. These characters are interpreted such that `'#'` indicates a blocked square, `' '` a open square in the puzzle with no known contents and any letter an open square whose containing that letter. **Numbering file format** Lines starting with '#' are ignored and may be used for comments. All other lines contain a tab separated triplet `i`, `m`, `n` where `i` represents a number to be printed on the grid, and `m` and `n` represent the row and column of the square where it should be printed. The number of both rows and columns starts at 1. ## Output The output will be a file that the user can print out and work a crossword on. ASCII, postscript, pdf, png, and any other reasonable format will be accepted, but all must abide by these rules: 1. There must be a rule around the entire puzzle and between every pair of squares. 2. Blocked squares must be filled in darkly. 3. In play square that represent the start of a numbered (across or down) clue must be provided with a number in the upper, left corner of the square, while leaving most of the square blank for the play to write in. Note that typical grid published in the papers will have many tens of clues and may have more than 100. The output will be of the grid alone, without the list of clues. Output should be sent to a conventional destination (a file whose name is derived from the input filename, produced as a web page, etc..) ## Test case Given a input of ``` 5 5 # ## # # # ## # ``` the starting corner of an acceptable ASCII output might look like this ``` +-----+-----+-----+--- |#####|1 |2 |### |#####| | |### |#####| | |### +-----+-----+-----+--- |#####|3 | |4 |#####| | | |#####| | | +-----+-----+-----+--- |6 | |#####| | | |#####| ``` Those using graphical formats should take their inspiration from the usual printed sources. ## Numbering scheme A correctly numbered grid has the following properties: 1. Numbering begins at 1. 2. No column or span of open squares is unnumbered. 3. Numbers will be encountered in counting order by scanning from top row to the bottom taking each row from left to right. ## Aside This is the third of several crossword related challenges. I plan to use a consistent set of file-formats throughout and to build up a respectable suite of crossword related utilities in the process. Previous challenges in this series: * [Crossword numbering](https://codegolf.stackexchange.com/questions/318/crossword-numbering) * [Crossword grid validation](https://codegolf.stackexchange.com/questions/883/crossword-grid-verification) [Answer] # Postscript ~~905 797 677 675 629 608 330 320~~ 308 ``` {G N}/Times-Roman .3 2 22 1 30/.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def[/R{99<a51f3e7d75>$}/G{<1fab75>$ R(uN)${0 R{1(X)$ 0 1 -1 5 4 roll 35 eq{4<1980>$}if<81>$ 1 add}(I)$(u)$ 0 -1<ad>$}<834d>$}/X{{exit}if}/N{-.9 .7<ad>${<1fab70>$ X}loop{{(>nk)$( )<31a0>$}<a3>$ X}loop}>><0d38388b369bad8e3f>$ ``` This program is written as a "protocol prolog" so you just cat it together with the grid and number files (in that order, separated by blank lines) and pipe the whole mess to ghostscript or Distiller or a PS printer. Appended to the reference version below is a NYT puzzle (From Nov. 5, 2011) with numbers and one answer I'm pretty sure of (Saturdays is hard!). The new revision uses these two procedures to execute binary-encoded system names from strings. ``` /.{ <920> % two-byte binary-encoded name template with 0x92 prefix dup 1 4 3 roll put % insert number into string cvx exec % and execute it }def /${ //. %the /. procedure body defined above 73 . %"forall" (by code number) }def ``` Indented and (somewhat) commented. ``` /Times-Roman .3 2 22 1 30 /.{<920>dup 1 4 3 roll put cvx exec}def/${//. 73 .}def [ /R{99<a51f3e7d75>$} %currentfile 99 string readline pop /G{<1fab75>$ %currentfile token pop R (uN)$ %<754e>$ %pop gsave { 0 R { 1 (X)$ %index 0 1 -1 5 4 roll 35 eq{ 4<1980>$ %copy rectfill }if <81>$ %rectstroke 1 add }(I)$ (u)$ % 73 . %forall pop 0 -1<ad>$ %translate }<834d>$ %repeat grestore } /X{{exit}if} /N{ -.9 .7<ad>$ %translate %{ currentfile token not {exit} if } loop {<1fab70>$ X %{exit}if }loop { %dup type/integertype ne{exit}if { (>nk)$ %<3e6e6b>$ %exch neg moveto ( )<31a0>$ %cvs show }<a3>$ %stopped X %{exit}if }loop } >> <0d38388b369bad8e>$ %begin dup dup scale div setlinewidth translate selectfont {G N}exec ``` Data files. ``` 15 15 # # # ## ## # # # # # # # # # # # K# # ## ## I # L N S# # #i m n figure(number), row, col 1 1 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1 7 7 1 8 8 1 9 9 1 11 10 1 12 11 1 13 12 1 14 13 1 15 14 2 1 15 2 6 16 2 10 17 3 1 18 4 1 19 4 9 20 5 3 21 5 7 22 5 8 23 5 11 24 5 14 25 5 15 26 6 1 27 6 2 28 6 6 29 6 10 30 6 12 31 7 1 32 7 5 33 7 10 34 7 11 35 8 1 36 8 4 37 8 9 38 9 1 39 9 8 40 9 13 41 10 1 42 10 6 43 10 7 44 10 12 45 11 1 46 11 5 47 11 7 48 11 11 49 12 3 50 12 6 51 12 9 52 12 10 53 12 14 54 12 15 55 13 1 56 13 2 57 13 8 58 14 1 59 15 1 60 15 7 60 15 11 ``` It should look okay from a printer, but on-screen it needs a little help. This 19-char procedure and 9 chars to invoke it on all user-space points, helps make evenly-spaced lines look more even. So 308 + 19 + 9 = 337, used to generate this image. ``` /F{<ac893e893e5f>$} % transform round exch round exch itransform ``` ![crossword output](https://i.stack.imgur.com/o68mu.png) ## Postscript 608 This earlier version (from [revision 8](https://codegolf.stackexchange.com/revisions/3877/8)) uses a completely different approach, reusing the main-line code as a "lexicon" from which longer tokens can be indexed using strings. ``` <<-1{{30 700 translate 0 0 moveto currentfile 2{(@A1*)*}repeat exch string 3 2 roll{('BO1)*{( )(@#)* 4(,.N:;<%)*<<( ){p}/#{(1:;>%)*}0{(;,'.)* 6 -26(CE%)*}>>(IJ'B)* known not{p 0}if(LG #C)*}forall(#;*1 D%)*}repeat p/Times-Roman 8 selectfont 99 string{('BO)*{(@)* length(#=)*{p}{(@#L)* 35(=)*{p}{cvx(GID ?'H*ID ?KHF%)*( )cvs(E)*}e}e}{showpage exit}e}loop exit{( @#M# FMF#M)* closepath}currentpoint stroke eq fill mul dup token copy rmoveto sub show neg exec add 1 index 9 get rlineto put readline}loop}0 1 index 0 get{1 index 1 add}forall pop/*{{32 sub load exec}forall}/e{ifelse}/p{pop}>>begin(23,?4)*<1f>* ``` It was written using this commented version which illustrates the encoding of the lexicon. The first token `30` is commented `space` therefore `( )*` is a synonym for `30`. Not very beneficial for `30`, but for longer tokens this is(was) a big win (until deeper encoding possibilities are(were) discovered). ``` <<-1{{ %space ! " # $ % & '( ) %* + , - . %/ 30 700 translate 0 0 moveto currentfile 2{(@A1*)*}repeat exch string 3 2 roll {('BO1)*{( )(@#)* 4(,.N:;<%)*<<( ){p}/#{(1:;>%)*}0{(;,'.)* 6 -26(CE%)*}>>(IJ'B)* known not{p 0}if(LG #C)*}forall(#;*1 D%)*} %0 1 2 3 4 5 6 7 repeat p /Times-Roman 8 selectfont 99 string{('BO)*{(@)* length(#=)*{p}{ (@#L)* 35(=)*{p}{cvx(GID ?'H*ID ?KHF%)*( )cvs(E)*}e}e}{showpage clear exit}e} %8 9 : %; < = > ? loop exit{( @#M# FMF#M)* closepath} currentpoint stroke eq fill mul %@ A B C D E F G H I J K L M N O dup token copy rmoveto sub show neg exec add 1 index 9 get rlineto put readline }loop}0 1 index 0 get{1 index 1 add}forall pop/*{{32 sub load exec}forall}/e{ifelse}/p{pop}>>begin(23,?4)*<1f>* ``` [Answer] ## Python, 379 characters ``` import sys A=sys.argv f=open(A[1]) V,H=map(int,f.readline().split()) M={} if A[2:]: for r in open(A[2]).readlines():n,y,x=map(int,r.split());M[y*H+y+x]=n R='+-----'*H+'+' n,v,s='\n| ' x=y=z='' p=V+1 for c in n+''.join(f): if c==n:print x+n+y+n+z+n+R;x=y=z='' elif'@'>c:x+=5*c;y+=5*c;z+=5*c else:x+=5*s;y+=s+s+c+s+s;z+=5*s if p in M:x=x[:-5]+"%-5d"%M[p] x+=v;y+=v;z+=v;p+=1 ``` [Answer] ## C (output to SVG), 553 chars I know, the code is huge, but this problem is just crying out for an SVG answer. ``` char*f,b[99];h,w;main(i){fscanf(f=fopen(gets(b),"r"),"%d%d%*[\n]",&h,&w);for( printf("<svg xmlns='http://www.w3.org/2000/svg' viewBox='.9 .9 %d.2 %d.2'><path d='M1 1", i=w,h);i--;)printf("v%dv-%dh1",h,h);for(;h--;)printf("v1h-%dh%d",w,w);for( puts("' style='fill:none;stroke:#000;stroke-width:.04'/><path d='"); fgets(b,99,f);++h)for(i=0;i<w;)b[i++]-35||printf("M%d %dh1v1h-1Z",i,h+2);puts("'/>"); for(f=fopen(gets(b),"r");fgets(b,99,f);)sscanf(b,"%d%d%d",&i,&h,&w)>2&& printf("<text x='%d.1' y='%d.3' style='font-size:.3px'>%d</text>",w,h,i);puts("</svg>");} ``` When run it gets the two filenames on two separate lines of standard input; first the grid file, then the numbers file. The logic in this one is actually quite simple. The format of the SVG allows it to create all the elements in any order (instead of going from top to bottom as with the ASCII output solution). The size is due almost entirely to SVG boilerplate. But the resulting image looks great! **Edited to add:** Here's a shorter version (517 chars) that output to a specific resolution. This allows the code to use more default settings, but at the (to my mind) prohibitive cost that the SVG no longer auto-resizes in your web browser. ``` char*f,b[99];h,w;main(i){fscanf(f=fopen(gets(b),"r"),"%d%d%*[\n]",&h,&w);for( printf("<svg xmlns='http://www.w3.org/2000/svg'><path d='M1 1",i=w,h);i--;) printf("v%d0v-%d0h50",h*5,h*5);for(;h--;)printf("v50h-%d0h%d0",w*5,w*5);for( puts("' style='fill:none;stroke:#000'/><path d='");fgets(b,99,f);++h) for(i=-1;++i<w;)b[i]-35||printf("M%d1 %d1h50v50h-50Z",i*5,h*5+5);puts("'/>"); for(f=fopen(gets(b),"r");fgets(b,99,f);)sscanf(b,"%d%d%d",&i,&h,&w)>2&& printf("<text x='%d3' y='%d5'>%d</text>",w*5-5,h*5-4,i);puts("</svg>");} ``` [Answer] # Haskell, 328 characters ``` import System main=do(g:d)<-mapM(fmap lines.readFile)=<<getArgs;mapM_ putStrLn$g% \i k->[t|x<-d,y@(c:_)<-x,c/='#',(t,q)<-lex y,w q==i,k<1] (s:g)%n=[q|(i,x)<-e g,q<-b s:[c['|':f#n[i,j]k|(j,f)<-e x]++"|"|k<-[0..2]]]++[b s] '#'#_="#####";_#n=take 5$c n++" ";b n='+':([1..w n!!1]>>"-----+") e=zip[1..];c=concat;w=map read.words ``` [Answer] ## C, 375 chars ``` char b[99];g[999],*r=g,*f,i,j,w;main(n){ for(fscanf(f=fopen(gets(b),"r"),"%*d%d%*[\n]",&w);fgets(b,99,f);) for(i=0;i<w;)*r++=-(b[i++]==35); for(f=fopen(gets(b),"r");fgets(b,99,f);) sscanf(b,"%d%d%d",&n,&j,&i)?g[j*w-w+i-1]=n:0; for(f=g;f<=r;f+=w){for(i=w;i--;)printf(" ----");puts(""); if(f<r)for(j=3;j--;puts("|")) for(i=0;i<w;printf(~n?n&&j>1?"|%-4d":"| ":"|////",n))n=f[i++];}} ``` The two input filenames are entered on standard input, each on a separate line. The grid is rendered in ASCII on standard output. Yes, it's a lousy UI, but anything better cost characters. I took to invoking it like so: ``` printf "%s\n%s" grid.txt numbering.txt | ./crosswd-render > render.txt ``` The program should correctly handle things like commented lines in the numbering file. [Answer] ### Scala 463, output-format: html ``` object H extends App{val z=readLine.split("[ ]+")map(_.toInt-1) val d="\t\t<td width='50' height='50'" println("<html><table border='1'><tr>") val b=(0 to z(0)).map{r=>readLine} var c=0 (0 to z(0)).map{ y=>(0 to z(1)).map{ x=>if(b(y)(x)==' '&&((x==0||b(y)(x-1)==35)||(y==0||b(y-1)(x)==35))){ c+=1 println(d+"valign='top'>"+c+"</td>")} else println(d+{if(b(y)(x)!=' ')"bgcolor='#0'>"else">&nbsp;"}+"</td>")} println("\t</tr>\n\t<tr>")} println("</table></html>") } ``` [Sample output](http://home.arcor.de/hirnstrom/kram/crossword.html) [Answer] **PostScript ~~(435)~~ (434)** ``` [/r{currentfile 999 string readline pop}/p{pop}/x{exch}/T{translate}/S{scale}/G{gsave}/R{grestore}/_( )>>begin/Courier 1 selectfont 20 20 S .05 setlinewidth{r token p x p dup 3 x 3 add T G G{R 0 -1 T G _ 0 r{0 0 1 1 4 index 35 eq{rectfill p}{rectstroke put .3 .1 moveto _ show}ifelse 1 0 T _ 0}forall}repeat R R 1 -1 S -.9 -.7 T{{r dup 0 get 35 ne{( )search p 3 2 roll cvx exec G x T .4 -.4 S 0 0 moveto show p R}if}loop}stopped}exec ``` Un-golfed with data: ``` %! << /r{currentfile 999 string readline pop} /p{pop} /x{exch} /T{translate} /S{scale} /G{gsave} /R{grestore} /_( ) >>begin /Courier 1 selectfont % In theory, 20 20 scale isn't needed, % but it would make the whole thing very tiny when printed % (on screen it doesn't matter too much, it can be zoomed) 20 20 S .05 setlinewidth { % exec % Read number of lines r token % restString numberOfLines true % Discard rest of line (Contains number of columns. % It becomes clear implicitly from number of letters in a line of grid definition) p x p % numberOfLines % Move to where the top line starts dup 3 x 3 add % numberOfLines x y T % numberOfLines G G { %repeat R % Move to next line 0 -1 T G _ 0 r % ( ) 0 line { %forall % ( ) 0 char 0 0 1 1 % ( ) 0 char 0 0 x y % Check whether char is a hash 4 index 35 eq{ %ifelse 4 copy rectfill }if rectstroke % ( ) 0 char put % -/- .3 .1 moveto _ show 1 0 T _ 0 % ( ) 0 }forall % }repeat R R % Now, render the numbers according to the numbering definitions 1 -1 S -.9 -.7 T {{ r %Check whether this is a comment dup 0 get 35 ne{ % line % Split at the first tab %TODO: Ust tab instead of space ( )search % (y x) tab number true p 3 2 roll % tab number (y x) cvx exec % tab number y x G x % tab number x y T % tab number .4 -.4 S 0 0 moveto show % tab % This pop can be eliminated in theory to save two characters, % but the operand stack will continue to grow p R }if }loop}stopped }exec 15 15 # # # ## ## # # # # # # # # # # # K# # ## ## I # L N S# # #i m n figure(number), row, col 1 1 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1 7 7 1 8 8 1 9 9 1 11 10 1 12 11 1 13 12 1 14 13 1 15 14 2 1 15 2 6 16 2 10 17 3 1 18 4 1 19 4 9 20 5 3 21 5 7 22 5 8 23 5 11 24 5 14 25 5 15 26 6 1 27 6 2 28 6 6 29 6 10 30 6 12 31 7 1 32 7 5 33 7 10 34 7 11 35 8 1 36 8 4 37 8 9 38 9 1 39 9 8 40 9 13 41 10 1 42 10 6 43 10 7 44 10 12 45 11 1 46 11 5 47 11 7 48 11 11 49 12 3 50 12 6 51 12 9 52 12 10 53 12 14 54 12 15 55 13 1 56 13 2 57 13 8 58 14 1 59 15 1 60 15 7 60 15 11 ``` [Answer] **Postscript, non-combatant.** Inspired (yet again) by your [related question on SO](https://stackoverflow.com/questions/5136164/is-there-a-file-io-in-postscript-for-dummies/5846955#5846955), I've made a reference version in Postscript using file-IO. It also creates a derived fixed-width font so the grid data is simply passed to `show`. is an empty box and `#` is a filled box. Any other ascii character is drawn as a small Times-Roman glyph surrounded by a box. This program makes use of a ghostscript feature which may not be present in all Postscript interpreters. If ghostscript is invoked with the `--` option, it passes command-line arguments to the postscript program in an array of strings named /ARGUMENTS. So you need to invoke the program like this `gs -- xw-io.ps grid-file number-file`. ``` %! ARGUMENTS{}forall /numfile exch (r) file def /gridfile exch (r) file def /q{0 0 moveto 1 0 lineto 1 1 lineto 0 1 lineto closepath}def /X<</FontType 3/FontBBox[0 0 1 1]/FontMatrix[1 0 0 1 0 0] /Encoding StandardEncoding /BuildChar{ 1 0 0 0 1 1 setcachedevice .001 setlinewidth q stroke dup 35 eq { pop q fill }{ .3 .1 moveto .1 .1 scale /Times-Roman 8 selectfont (?)dup 0 4 3 roll put show }ifelse pop} >>definefont pop /X 30 selectfont 40 700 moveto { gridfile 2{dup token pop exch}repeat pop pop { gridfile =string readline{ dup length 0 ne{ show currentpoint exch pop 30 sub 40 exch moveto }{clear exit}ifelse }{clear exit}ifelse }loop /Times-Roman 8 selectfont { 40 700 moveto numfile =string readline{ dup length 0 ne{ dup 0 get 35 ne{ cvx exec 1 sub 30 mul 2 add exch 1 sub -30 mul 22 add rmoveto ( )cvs show }{clear}ifelse }{clear}ifelse }{clear exit}ifelse }loop showpage }exec ``` ]
[Question] [ "Buzzing" Bill is a well respected beaver. He is the hardest working in his home dam. He was a strong beaver and was able to lift more logs than anyone at the dam. Unfortunately Buzzing Bill's career came to an end in a tragic accident. Being such a prominent figure in his town, the Beaver newspaper wanted to write a frontpage story remembering Buzzing Bill. However Beavers have much smaller newspapers than we do and can only fit 4 letters on each line. The newspaper is assigning you to the task of writing some code to output the four letter lines. **The objective:** We need some code written that takes in a string as an input, ex: *"Big Beaver Buzzing Bill Bite the Bullet"* and splits it into four letter segments that can fit on the Beaver newspaper, and outputs the split segments in an array/list/structure The answer to this question will have an output to the sentence above that looks much like this: **[Big,Bea,ver,Buz,zing,Bill,Bite,the,Bul,let]** The output will complete the all of these criterion for beaver readability: 1. Keeps **4 letter words or less together, and completely separate from other words**, two words cannot occupy the same line— note that the first two indexes is not [BigB,eav] 2. It **splits words more than four letters and an even number of letters cleanly in two** — i.e. do not have [Beav,er] 3. **Words with an 7 letters should split at the point between the *first* two identical adjacent consonants, where one consonant occupies the middle spot, if possible.** “y” is not a consonant — Buzzing:[Buz,zing] instead of [Buzz,ing], additionally in very rare cases where the there is a triple consonant in the center, ex: “Wallled” would become [Wal,lled] as the split occurs at the first middle pair 4. **Words with an odd number of letters that do not satisfy rule #3 should be split so that the front of the word contains the extra letter** — "Beavers" should be split as [Beav, ers] rather than [Bea,vers] 5. Beavers are not very good at reading, so the **newspaper will not use any words over 8 letters, and all words will be entirely lowercase letters(only the 26 used in English)** Make the Best of it Busy Beavers! [Answer] # JavaScript (ES10), 100 bytes Returns an array of strings. ``` s=>s.split` `.flatMap(s=>s[4]?[s.slice(0,q=s.length+!/^..([^aeiouy])\1../.test(s)>>1),s.slice(q)]:s) ``` [Try it online!](https://tio.run/##NYtBDoIwEEWvUl21EQdJXJmAJ/AECKHgADUTCsxAIpfHunDzkv9@3tuulpvZjXIe/Av3Nt05zRh4JCeVqqAlKw876p/Nr8U9Dx@5BvUlmlIGwqGT/nSISwCdlxadXz6FeSYAMQiyaDZZlpjon02muLHZGz@wJwTynW71sXadqtGuOKt62TY3hOmIAgSV9BgsEcrRmP0L "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 96 bytes Returns a string with additional spaces. ``` s=>s.replace(/\S{5,}/g,s=>s.slice(0,q=s.length+!/^..([^aeiouy])\1../.test(s)>>1)+' '+s.slice(q)) ``` [Try it online!](https://tio.run/##NctBDoIwEIXhq6Ab2oBTWbiES7gUSQoOpWbSAlNIxHh2bEzcvOR9yf/Uq@ZutmM4Of/AvS93LiuGGUfSHQpVX9@X/KNM/mMmG/GcTyUDoTNhyA6qARC3RqP1y@su6wJAQUAOgmVVFTJLkzT7p5OUe@cde0Igb0Qvjq01SYt6xTlpl22zLl5LFCdgEgaMSoThGMsv "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 261,265 232 bytes gotta love the walrus. +4 bytes to fix rule 4. ``` import re def f(s,q=[]): for w in s.split(): if len(w)<5:q+=[w] elif(k:=len(w))%2<1:q+=[w[:k//2],w[k//2:]] elif b:=re.search(r'(?=[^aeiou])([a-z])\1',w):q+=[w[:(i:=b.end()-1)],w[i:]] else:l=k//2+1;q+=[w[:l],w[l:]] return q ``` [Try it online!](https://tio.run/##NYxRasMwEET/c4olUCIRx8EphaJGFHwNVQWnWdVLVNleyTX15V27qX922JnHa39S3YTH55anib7ahhMwbq7owImYddpYqTbgGoYBKEDMY@spiaUEcuAxiEGen1S312awc4menLgpfV/kw@lc3EejbsfjyWaDWVLZFYaL0ox5xIo/asE78arNe4XU9FYKUx1GK9@KXTbIVSNI6UuO4SrkoZCLkFZbROX1ot8XL/@0XwD/BzCmngN0U8sUknBiW9InlFh9I0co@3GkMP/k/XwSQqpxbr3HtJVy@gU "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python](https://www.python.org), ~~142~~ ~~139~~ ~~134~~ ~~131~~ 130 bytes ``` import re for w in input().split():c=re.match(r'..([^aeiouy])\1...$',w)and 3or(w>w[:4])*len(w[::2]);c>0!=print(w[:c]);print(w[c:]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5NasNADIX3PYUKhXhKO_Qni-KSXCR1YWwrsWA8YzRyzGTZZa_QjTftnXKbyqQFIek98cT39TNk6WKY5-9R9vcv5w_qh8gCjFf7yDABBa1hlMLYNHjSWTYbRts7abqCV9YWu3eHFMdcmbdHa-3N6m4yLrTwHLmYttOuXFfm1mModC2fKvPabB-uNwNTkMVq1PkXTVmZC8kf0Hz-rOkANbojcoJ6PJ0oqCbvtQmCdKiu9yhwYMIjtlBncDA5r6YKl5KngNBGjTFiiwwLXYo9Qojiao-QRC_iMySXM7VJf2kuXwYtiZRQLki_) *-3 thanks to xnor one-lining it, with some comparison chaining on top to shave one byte off an `and`* *-1 thanks to spooky\_simon actually knowing how `re.match` works* Basically just a bunch of incremental golfs to [spooky\_simon's solution](https://codegolf.stackexchange.com/a/263838/85334) (inspired by [xnor's comment](https://codegolf.stackexchange.com/questions/263797/buzzing-bills-newspaper-four-letter-splits/263838#comment577248_263838), and with fixes to rule 3), but it's barely even recognizable anymore so I figured I may as well post it for myself. [Answer] # [Scala](https://www.scala-lang.org/), ~~200~~ 147 bytes Port of [@Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/263800/110802) in Scala. ---     Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=ZY8xT8MwEIXFmp39lMkWraHAgIpSqSNDFyqmUpCTXNJDjpPaTkNb9VcwspQB_hP8GtyETix-eqfvvTu_f9lEKnm1_zk5paIqjYN2IGpHShTSJQvSubjHHF-DoIxfMHEwkaRhGwCkmEHhDZMmt0MYGyPXs6kzPjLnQ3jQ5CBqSYCVVGC9C2PKIUa5QgNxvdl49qCqVVLKPw7BLdBPlUIHjVReU4gNYupDVq7XlFooyFoqtQWvNYbtksqvdkozWylyY51OpKaqVtIhs5x7ZBcEf6f8I4bd4dFoisvjJyD6rF3Wv_l-exZtgoUQcpF5fiIr1kQjylgjLG1wdM23h-Jl1PmzQd_IJhSCzZ4kUlmv5_xxIEQojMhIp2Ol7jRreAvf-p2HHkUJsove8vyS947Wm15XyfkOlUVoYc670z52ne73nf4C) Saved so many bytes thanks to the comments. ``` _.split(" ").flatMap(w=>if(w.size>4){val q=w.size+1-raw"..([^aeiouy])\1..".r.findAllIn(w).size;Seq(w.slice(0,q/2),w.slice(q/2,w.size))}else Seq(w)) ``` Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=bVJdS8MwFAUf-ysufWpwBocIUlhhDwqCe1F8kKmQtmkXSdMuuZ1u0l_iy170R_lrTNOttOBLSE7Ouffcj68fkzDJLvb77xqzs6vfkydRVKVGcDitUUhaMExWQuX0nuf8w_PK-I0nCAsmFHx6ACnPoLCPgOnchDDXmm2XD6it5IWE8KgEwswxATZMgrEvPxY5xJxtuIa43u0sF2IhpT2QA664RaXk6DtVZWOhVIGppMC5ShdMiaqWDHlgCLGUxjv4-I8RQmfGerkTBo_Wek-GOlXgg08oli2HZla6YFXwXuoUZtGBCSAycBiVXOW4gmgGl6T_7erTbZtCcN1qS_V9SoPlK-OirLcv5HlKaYvpkWhtmW1wJ6aZUOmN0AZvlUtHqDDXRYXbYS4YWzmFKYEogmlPaIBLw0eKkfcRt7-19XeBjRQJD84nsCYTGCDryTCOG8AgXa_v8KabT-N1G3ZYtOPC_QE) ``` import scala.util.matching.Regex object Main { def main(args: Array[String]): Unit = { val s = "big beaver buzzing bill bite the bullet" println(splitAndManipulate(s)) } def splitAndManipulate(s: String): List[String] = { s.split(" ").toList.flatMap(word => { if (word.length >= 5) { val regex: Regex = """..([^aeiouy])\1..""".r val q = if (regex.findFirstIn(word).isEmpty) { (word.length + 1) >> 1 } else { word.length >> 1 } List(word.slice(0, q), word.slice(q, word.length)) } else List(word) }) } } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ 26 bytes ``` Ḳµ3.ịfƒØYL×7=LạLH>2×ƊĊṬk)Ẏ ``` [Try it online!](https://tio.run/##DYsxDsIwEAS/ci0NBRRUUFP4Aylt@QiGI5HiI8j5AFKQKGhCS0@FhAShwyj/8EuMm5V2ZneDRC7G8Hp8n9Nx@JxWw8VfM@G72VyE/iaWi4nvhvbXhvd9Owr9OfpjFqMyOSiUNVag9k1jilQNUQpG4DUmSoQMeWWwRg3KgYSDpAQ16DKtK0Sd3rLQYMsdQlGyVIRgORkmB1Y6Z7QFaS3yHw "Jelly – Try It Online") This... can probably still be better... ``` Ḳµ ) For each word: ƒ Reduce 3.ị the third and fourth letters in the word f by intersection ØY starting with the list of all consonants. L Is the length of that result ×7 times 7 =L equal to the length of the word? ạL Decrement the length if so. H Halve, >2×Ɗ zero if =< 2, Ċ ceil, Ṭk split after that index. Ẏ Flatten the splits together. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes ``` S` (..(..(?=....)|([^aeiouy])(?=\3...)|.(.(?=...))?))(..+) $1¶$+ ``` [Try it online!](https://tio.run/##K0otycxL/P8/OEGBS0NPD4TsbfWAQLNGIzouMTUzv7QyVhMoFmMMFgSqgCjQ1LTX1AQq19bkUjE8tE1F@///pMx0haTUxLLUIoWk0qqqzDwgNzMnB0iUpCqUZKQCRXNyUksA "Retina 0.8.2 – Try It Online") Link includes test case. Explanation: ``` S` ``` Split on spaces. ``` (..(..(?=....)|([^aeiouy])(?=\3...)|.(.(?=...))?))(..+) $1¶$+ ``` Split words of at least five letters in one of four ways: * eight letter words are split after four letters * seven letter words whose third letter is not a vowel and is doubled after three letters * other seven letter words after four letters * other words after three letters `$+` just saves me counting to find the group number of the last capture group. [Answer] # [Python 3](https://www.python.org/), 379 bytes I got kinda lazy at the end after banging my head against this problem for a couple hours. Since I wasn't sure if I could use built-in modules like `itertools` I decided not to test my luck and just make a function (which came out kinda bulky) Here's my solution ``` def f(l): if type(l) in [list,tuple]: for s in l: yield from f(s) else:yield l b=lambda s:list(f([[w[p:p+(len(w)//2)]for p in range(0,len(w),len(w)//2)]if(len(w)>4 and len(w)%2==0)else(([(w[:a],w[a:])for a in[{1:4,**{1:a for a in[i+1 for i,(a,b)in enumerate(zip(w,w[1:]))if a==b and a not in"aeiouy"]}}[1]]])if len(w)==7 else w) for w in s.split()])) ``` Was I a bit smarter and managed to remove the function I could've saved about 100 bytes, but oh well... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes ``` F⪪S ¿∧⁼Lι⁷›⁼§ι²§ι³№aeiouy§ι²⟦…ι³✂ι³⟧⪪ι⁻⁴⊘&²⊕Lι ``` [Try it online!](https://tio.run/##VZBNS8RADIbv/orQUwbGSxU87GktogUFoUfxMJ1m20Cc1mmmuvvn6yxV0UACb56EfPjBRT86WdfDGAGbSVixDlPSRiOHHo2FAgpjgA@A@9Dh3XtyMuMjhV4H5Mxvst9Hckrxh@61Dh19IlsoM/0jr0zW1ZiCYuGIx3Qs/vHSnA2e83DFl@rohaphnLZWC42wp028mh2QzPRdu62eyROHNOO1hQcnC3V4y/rBM513Ly3UwUd6o6CZ/N6w2W5dW@6hJbdQhDadTvkB0LJIDkqgA@WsCOnFernIFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` F⪪S ``` Split the input on spaces and loop over the words. ``` ¿∧⁼Lι⁷›⁼§ι²§ι³№aeiouy§ι² ``` Check to see whether this is a seven-letter word with third and fourth letters both the same consonant. ``` ⟦…ι³✂ι³⟧ ``` If so then split it after three letters. ``` ⪪ι⁻⁴⊘&²⊕Lι ``` Otherwise split it after a number of letters given by a formula which results in splits of `3, 3, 4, 4, 3, 3, 4, 4` for words of length `1` to `8`, which is the desired result. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` #εDg©4›i2ä®7Qi¬γθžPÃg2@iJ34S£]˜ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9f@dxWl/RDK00eNezKNDq85NA688DMQ2vObT634@i@gMPN6UYOmV7GJsGHFseenvP/f1JmukJSamJZapFCUmlVVWYekJuZkwMkSlIVSjJSgaI5OaklCuWJOUA6RSGpKDU1Bai4OLGyMjOlWCE3s7g4Mz@vWCEJCBKTkhUSi4tTSwA) **Explanation:** ``` # # Split the (implicit) input-string by spaces ε # Map over each word: Dg # Duplicate the current word, then pop and push its length © # Store this length in variable `®` (without popping) 4›i # If the length is larger than 4: 2ä # Split the string into two 'equal-sized' parts, where the # first part is one character longer for odd-sized strings ®7Qi # If length `®` equals 7: ¬ # Push the first part with four characters (without popping # the pair) γ # Group adjacent similar characters together θ # Pop and keep the last character-group žPà # Only keep the consonants of this group g2@i # If the length of what remains is >=2: J # Join the pair back together to the original word 34S£ # And split it into parts of sizes [3,4] (instead of the # [4,3] done by the `2ä`) ] # Close all three if-statements and the map ˜ # Flatten the list # (after which the result is output implicitly) ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-an`, 87 bytes `-an` enables autosplitting on the implicit input, which is stored in `$F`. The main strategy here is to abuse `String#slice!`, which removes the substring that matches the parameter from the original string and returns it, which means what remains can be returned as the second half. It can take as a parameter, among other things, a regex or a range, which means the 7-length case can be handled with a regex and everything else can be handled with a range. ``` puts$F.map{|f|s=f.size s>4?[f.slice!(s==7?/..(([^aeiouy])(?=\2)|..)/:0...s/2+s%2),f]:f} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TZLBjtNADIYFxzyFWYHUCjZFFRJopdIbr8ChFMlJPMloJ-NqPEOUUp6Eyx5APBM8zXomRdpLJol_f_9vJz9_hdTMfw43t-hvjg-_UzS3H_5-PqUoLz_VI56-X8xFdqYWe6ZKPr7bH_Te2ZZerGS3e7_f1PVqdfiKZDnNx_Vqv_uyXV_qer25e1vXtWy2r-XVdv3GHO_MjwV_dXn49_xZk85n63torHNgBRAG2w9uBpJINFIHDeE3CtVAuRz1GDB0WoWJw31utV57BAYeCTocs3LCTJIYOKMLANB3y_vGEUQGZ02EkQOB4z6T0atmZk-AsRhlmGCnYTK_xUCKaXEs7aomJao5QgzY2xawbW1HPlYN5VyS2mGRcRg5CRjbJ7W75o08-WJzzXfCk14n9FGHVoMp2KhRwOgQUas96UAc5lwLupmxUfnT9VUDT5RJC1A3ogeMOYWM6Nx_j-uskw7IZSutPrHXMY2NYDgFcBRjFrKmR-131lOVsy4hUcT2XmDmlNPkQkS5BzYldRk-f42Wu7IrTlH_p6J7gi9UWX6FRw) [Answer] # [Perl 5](https://www.perl.org/), 99 bytes ``` $_=join$",map/(..([^aeiouy]))(\2...$)|(.{3,4})(.{3,4})|(...)(..)/i?($1||$4||$6,$3||$5||$7):$_,split ``` [Try it online!](https://tio.run/##dYpLC8IwEITv/ooiOSRQt2h9gCBCbx48e/BRAgZdWdNgUkGtf924HhQRPMwMM984c6JBjKKcHCq0op0etcskgFxutMGqvqyVkqseAAjVSLjlaf@u3skDADdQGU6l6DaN6LOGqcg5BqyRGosy9Y4wxFjgLimMPptTUtTXK1quSMQWTBL2hlciE1r/fgtNzLc/nD5c22TmfW2@D3P0HivrH5ULr4wdR08 "Perl 5 – Try It Online") ]
[Question] [ ## Introduction Ah, INTERCAL... As much as I'd like encourage everyone to [Try it Online](https://tio.run/#Intercal), text output is just painful. According to the [docs](http://www.muppetlabs.com/%7Ebreadbox/intercal-man/home.html) it uses the "Turing Text Model". While an... *interesting* concept, using it is about as much fun as shooting yourself in the foot. And what do we do with a task like this? Automate it. ## The Turing Text Model The characters INTERCAL knows are printed on a circular tape that can only be moved in the positive direction. Printing is done by passing tape head movement commands in an array to the `READ OUT` statement. Every ASCII character is written on the *inside* of that tape (The outside has the characters for the input on it, duh). This results in the characters' bytes being on the tape in reverse. Also the tape head moves backwards along the character list, because its positioning is based on the outside of the tape. The head starts at position 0. Now the magic starts. I'll be using [Truttle1's explanation on how to achieve output](https://www.youtube.com/watch?v=OrgpSe7Y-08&t=6m54s). 1. Set up an array with the output length. 2. Fill the entries in the array with tape head movement values. 1. Find the current character's ASCII value in binary 2. Reverse it and convert back a number `n`. 3. Subtract `n` from the current head postion and modulo by 256 if needed, resulting in a value `r` 4. `r` is the value you need to store in the array 5. The head is now at position `n`. 3. `DO READ OUT` the array. ## PLEASE NOTE * Array is pre-initialized with `0`, first index is `1` * INTERCAL uses extended 8-bit ASCII characters, hence the tape length of 256. * Between 1/3rd and 1/5th of all lines have to start with `PLEASE`. Note that in that case you drop the `DO` for `GIVE UP` and `READ OUT`, but not for anything else, as seen in the examples. ## Challenge Given an input string, output a valid INTERCAL program that prints that string and terminates. ## Examples Prints "BUZZ" ``` DO ,1 <- #4 DO ,1 SUB #1 <- #190 DO ,1 SUB #2 <- #152 PLEASE DO ,1 SUB #3 <- #336 DO READ OUT ,1 PLEASE GIVE UP ``` Whitespace is optional. The following prints "FIZZ" ``` DO,1<-#4DO,1SUB#1<-#158DO,1SUB#2<-#208DO,1SUB#3<-#312PLEASEREADOUT,1PLEASEGIVEUP ``` (Examples shamelessly stolen from Truttle1's FizzBuzz program from the video.) You can find an ungolfed reference implementation in python 3 [here](https://tio.run/##jVFNa4NAFLz7K4YNhV2iRdOPg8RDSqQUCglN7SX0YK2pC3aVzbZQQn57@nZXirnVw5MZ38zOjv2PaTp1dTpJ1SMDzS/DRRC0BNpacSIIVcoQToK@29M7DoJeS2U4W64QJphHmDBMsTeat4LWd52GJC/oUn3UPAnR0udEpAHosWZT6@ZA40/dSkRIXh33XdrTWWw9yeqzNLzT77xqRAj2xsRoieY2TaNBqJyX4cSGmFEQS2oibe4IymE35I74OWKfyK9RptnNrRf5i54LbO4LXCPLxrqhifVjvtjk8IVsijtMDkdXzOHILodLyBBaCO9Xt/s6/XMfGf3LYdT/U75YYlU8k4qaOU9z//CSo1gzYX@vqXVVtr8 "Python 3 – Try It Online") ## Rules * No standard loopholes * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code wins. * You can expect input >= 1, ASCII characters only. * The program may not throw any errors apart from `ICL774I RANDOM COMPILER BUG` and `ICL666I COMPILER HAS INDIGESTION`. First one happens at random, second one is C-Intercal running out of memory and circumventing that isn't part of the challenge [Answer] # [Python 3](https://docs.python.org/3/), 157 bytes ``` t=i=0 p=o='PLEASE' for c in input():i+=1;k=int(f'{ord(c):08b}'[::-1],2);o+=i%4//3*p+f'DO,1SUB#{i}<-#{t-k&255}';t=k print(f'DO,1<-#{i}{o}DOREADOUT,1DOGIVEUP') ``` [Try it online!](https://tio.run/##NYxBC4IwAEbv/gpBai4VNRNC20GZhRBMMjssumRIQ3BD1iHGfrslEXzwDu/xibd88iGaJokYCgyBOALVscjqAhgdH83WZMN34iVtmDAHhWmP2CDtDig@PuwWJsH2rsE1Sbzw5q5hyh3EFhvfj1bC6QAmblg3uaWY3nmWkl6/XMexBqlEvSHG39MczZZpxTUmpyLDpDm7ISaH8lI0FYDTtC8pzRtK//wA "Python 3 – Try It Online") This prints \$n+3\$ instructions, of which \$\left\lfloor \frac{n+5}{4} \right\rfloor\$ are polite. That ratio just barely fits in the \$[1/5, 1/3]\$ politeness interval for all \$n \geq 1\$. -1 byte thanks to Neil. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~156~~ 148 bytes ``` s=>`DO,1<-#${Buffer(s).map(c=>o+=`${i++&&~i&3?'':'PLEASE'}DO,1SUB#${i}<-#`+(p-(g=k=>p=k--&&c>>k&1|g(k)*2)(8)&255),i=p=o=""),i+o}DOREADOUT,1DOGIVEUP` ``` [Try it online!](https://tio.run/##Fcxdi4JAFIDhv7K5MR@NI1gEEZ2JQqmFwNiyvVVMZXLWM@huN9b@dXPv3pvnvaX3tM0abX9kjde8L6BvQSVB5Por@T7utr9FkTes5d53alkGCgUk404LQcifJrM1pUt6PISbU0if/@oUbwemn4NOBLOSlVCBslBJSUimVEX8R8kqPplytuBkOp9zV4MFBMcZSuBw@Qw3QRSfXT@Idh@XMD4mfYZ1iyb3DJasYHSfG4Pu2xc25jqinPcv "JavaScript (Node.js) – Try It Online") [Try the output in INTERCAL!](https://tio.run/##XY7LCsIwEEU/ptsKmWScpuCmJUEEIcUa9yIuBOlC/P@YCUykXZ7Lfb2W7/PzuL9TcqGFw64BM539MHvGOY4Na9pYQc0WZdcewyJoQcyoBPYZCIWInT2u410WsS5YHiShnglrHhQX0GYfysm/qZysFVDuUb538YML8dqCC8fTzccppR8) ## How? ### Bit reversal We use a recursive function to reverse the bits of the character **c**. ``` ( g = k => // k = bit position counter k-- && // decrement k; if it was not 0: c >> k & 1 // bring the k-th bit of c at position 0 and isolate it | g(k) // bitwise OR with a recursive call, * 2 // whose result is doubled )(8) // initial call with k = 8 ``` ### Politeness Starting with `i = 0`, we insert a polite statement whenever the following expression is falsy: ``` i++ && ~i & 3 ``` This means that we insert a `PLEASE` for the first processed character, and then every 4 characters starting with the 3rd one. Neither the leading instruction nor on the two trailing instructions are polite. They are marked as `L` and `TT` respectively in the following table. ``` length | output structure | politeness ratio --------+--------------------+------------------ 1 | LPTT | 1/ 4 = 0.250 2 | LP-TT | 1/ 5 = 0.200 <-- lower bound 3 | LP-PTT | 2/ 6 ≈ 0.333 <-- upper bound 4 | LP-P-TT | 2/ 7 ≈ 0.286 5 | LP-P--TT | 2/ 8 = 0.250 6 | LP-P---TT | 2/ 9 ≈ 0.222 7 | LP-P---PTT | 3/10 = 0.300 8 | LP-P---P-TT | 3/11 ≈ 0.273 9 | LP-P---P--TT | 3/12 = 0.250 10 | LP-P---P---TT | 3/13 ≈ 0.231 11 | LP-P---P---PTT | 4/14 ≈ 0.286 12 | LP-P---P---P-TT | 4/15 ≈ 0.267 13 | LP-P---P---P--TT | 4/16 = 0.250 14 | LP-P---P---P---TT | 4/17 ≈ 0.235 15 | LP-P---P---P---PTT | 5/18 ≈ 0.278 .. | ... | 1/5 < r < 1/3 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~77~~ ~~74~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ç₁+₁šb퀨C¥(₁%€‘‚µ,1<-#1€·,1—¨#1<-#ÿ€·‚Ø€Ä,1‘J‘ÿ€·†¿€¾ ``` -20 bytes by porting [@UnrelatedString's Jelly answer](https://codegolf.stackexchange.com/a/211976/52210), so make sure to upvote him!! Outputs with spaces at `#1 DO,1 SUB#`, `DO READ OUT`, and `DO GIVE UP`. [Try it online](https://tio.run/##yy9OTMpM/f//cPujpkZtID66MOnw2kdNaw6tcD60VAMooArkPGqY8ahh1qGtOoY2usqGINntOoaPGqYcWqEMEjm8HywEVHJ4BpB1uAUkOcMLiOEyCw6BWfv@//dIzcnJ11Eozy/KSVEEAA) or [verify a few more test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaCkU6nDpeRfWgLj/T/c/qipURuIjy5MOrz2UdOaQyucDy3VAAqoAjmPGmY8aph1aKuOoY2usiFIdruO4aOGKYdWKINEDu8HCwGVHJ4BZB1uAUnO8AJiuMyCQ2DWvv9AwUMrdA5ts/8freSRmpOTr6NQnl@Uk6KopKOg5BQaFQWi3TyBdCwA). [Try the output in INTERCAL.](https://tio.run/##y8wrSS1KTsz5/z/Ax9Ux2FXH0EZX2VDBxV/HUCE41EkZxDUytgAKKAS5Oroo@IeG6BjiVmpoQLxSQyNilRoQq9DMhGjbLYlWakK0l4yI9pER8YYamhFvP/HeNyNeJZqnQDx3zzBXhdAArv//AQ) **Explanation:** ``` Ç # Convert the (implicit) input-string to a list of codepoint integers ₁+ # Add 256 to each value ₁š # Prepend 256 at the front of the list b # Convert each value to a binary string í # Reverse each €¨ # Remove the last digit of each C # Convert each from binary back to a base-10 integer ¥ # Take the forward differences (deltas) of this list ( # Negate each difference ₁% # Take modulo-256 on each € # Map over each integer: ‘‚µ,1<-#1€·,1—¨#1<-#ÿ€·‚Ø€Ä,1‘ # Push dictionary string "PLEASE,1<-#1 DO,1 SUB#1<-#ÿ DO READ OUT", # where the `ÿ` is automatically filled with the integer J # Join this list of strings together ‘ÿ€·†¿€¾ # Push string "ÿ DO GIVE UP", where the `y` is filled with the string # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `‘‚µ,1<-#1€·,1—¨#1<-#ÿ€·‚Ø€Ä,1‘` is `"PLEASE,1<-#1 DO,1 SUB#1<-#ÿ DO READ OUT"` and `‘ÿ€·†¿€¾` is `"ÿ DO GIVE UP"`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~90~~ ~~89~~ 85 bytes ``` DO,1<-#ILθ⊞υ⁰⭆θ⪫⟦×PLEASE⊖﹪κ³DO,1SUB#⊕κ<-#﹪⁻⊟υΣ⊞Oυ⍘⮌◧⍘℅ι !⁸ !²⁵⁶⟧ω”Z1∨?AE₂-πK↷Y:γüD0←✂ ``` [Try it online!](https://tio.run/##TZBNT8MwDIbv@xVZd3GlTGIgEBJcNlrBUKtW6woHxCFqzVotTbp8jJ9fknUDTrb8vrYfu2qYqiTjw5CrVhgIoowuHuezIHyYjJUnpg0kKHamgUMY@rrVDVhKrn49hXFhl7IeDpS8ylbAx7btUEOQJ/GyiANKIqwUdigM1pDK2nIJe0pu3EBKTkuLcjVzvrX48@295mEoObekrbAactmDdVphO/AwWY@KGak81IppHHFgg0dUGiFndYJfBv5JmapbwTi0fgOZBi7ch5f8xHR9exd@UvI9Xnz5zSZeRlm5pYvxruf1W1zm7lfD8IKcS0repeL1dDLMj/wH "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` DO,1<-#ILθ ``` Print the instruction to set the length of the output. ``` ⊞υ⁰ ``` Start with the head at position 0. The value is actually stored in the predefined empty list as we can modify the list's value later using the Pop and PushOperator functions rather than having to resort to a command. ``` ⭆θ⪫⟦...⟧ω ``` Loop over the characters and print the concatenation of 5 expressions for each character. (This is slightly golfier as the concatenation automatically stringifies the two numeric values in the list). ``` ×PLEASE⊖﹪κ³ ``` Be polite every third character. There is also a `PLEASE` at the end, so that the politeness ratio is ¹⁄₄, ¹⁄₅, ²⁄₆, ²⁄₇, ²⁄₈, ³⁄₉, ³⁄₁₀, ³⁄₁₁ ... after which the politeness ratio tends towards ¹⁄₃. ``` DO,1SUB#⊕κ<-# ``` Print the 1-indexed index at the start of the instruction to output the character. ``` ﹪⁻⊟υΣ⊞Oυ⍘⮌◧⍘℅ι !⁸ !²⁵⁶ ``` Calculate the reversed binary of the current character, output the difference from the head, and update the head with the new reversed binary, all in one expression. The binary is encoded using space for `0` so that it can easily be padded to 8 bits, plus the use of strings avoids separators that would otherwise be necessary. ``` ”Z1∨?AE₂-πK↷Y:γüD0←✂ ``` Print the compressed trailing instructions to output the string and exit. The string compression means that I don't have to worry about optimising the number of times I output `PLEASE` any further. [Answer] # [Python 3](https://docs.python.org/3/), 128 bytes ``` t=0 for c in input():n=int(f'{ord(c):08b}'[::-1],2);print(f'PLEASE,1<-#1DO,1SUB#1<-#{t-n&255}DOREADOUT,1');t=n print('DOGIVEUP') ``` [Try it online!](https://tio.run/##JY5BC4IwGIbv/opB0BxMcIYQsx2MjQiCSWaX6JJlemgT@zyI@NtXIryXh4cH3naA2pqNcyBCr7IdKlFj/mt78Ak3ojHgV3i03dMvCQ@3jwnfOA/YnUYkabtFZyeV5oqyXbBiUlOWF/vVDCMEZh3F8ST1WaVSFxfKMElAGG9JsdSH41UVGSbO5RZ9@rJG8wvohsa8EVjUf1@Iix8 "Python 3 – Try It Online") Produces [similar output](https://tio.run/##rZUxC8IwEIV3f0Wha4XcNU1TcKkkiCCkWOsu4iCIg/j/I44OwjdkDHzc5b28u9yf79vrennkPB3iOMdGNutaQmpkXrb191CJmCqkYxxDWk6NrP6DVhmoCkHrYWeloHUQ9PSKlIONB1dYMsS0tfTxICdUiSiVDIOotnBnD03sqYcCwc5RxdTDjk7KACuawl53sGCLw2CKClEDHaQDRbMgrnAKZTCFs0CXF7ZGYUEHC3qouNfCWxh/jTQNeMfRG6r59Sak3f4clynnDw) to my Jelly solution, but is just as much a modification of Lynn's Python solution. Originally [used Python 3.8's "walrus" operator](https://tio.run/##LYzRSsMwFEDf9xUXBqaBFJbJYESL1DXIYNixrb6ID1m8o9EtCektRcRvrw6E83LgcOIXtcHfLmMaRypmk1NIYMH5P2JPGVcxOU8Z2250uddC3udTWdVC7pvH6VWYoDzzqrhGJ/Yd0ntmuZotjz/sValcvok55zfzxUKwqt7psqqbg5CM31HhJ//vqn5av@hmy/g4royHAYHMJ4KBS7igJ6AAJsaE1hlC@Og7gjYMcHZEZ4T180HvVuUGrEnYgTmGnmBoHWEXjcWHXw), but it turned out shorter not to by 2 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~62~~ 59 bytes ``` OŻ+⁹BUṖ€Ḅ_Ɲ%⁹“!![ẓ,ȮFẈẋ⁹⁾V!ĖÐĊnß6ṛ»;;“Œ°þ[ṪȦṄ»Ʋ€;“©⁴Œ½OлŒu ``` [Try it online!](https://tio.run/##y0rNyan8/9//6G7tR407nUIf7pz2qGnNwx0t8cfmqgJFHjXMUVSMfrhrss6JdW4Pd3U83NUNEm3cF6Z4ZNrhCUe68g7PN3u4c/ah3dbWQLVHJx3acHhf9MOdq04se7iz5dDuY5uAxoFkDq181LgFKL3X//CEQ7uPTir9//9/SEZmsUJaampOsUJKaW6SQlJpiUJmmkJmiUJ5flF2MZwBAA "Jelly – Try It Online") Uses an array length of 1 and prints repeatedly to save on indexing, and sets the length to one repeatedly to save on politeness logic: length-element-print forms a very convenient unit of 3. Without string compression: ``` OŻ+⁹BUṖ€Ḅ_Ɲ%⁹“please,1<-#1do,1sub#1<-#”;;“doreadout,1”Ʋ€;“dogiveup”Œu ``` [Try a result online!](https://tio.run/##vZbNisJAEIQfxmsWpnvGdgJ7URJEECJqvMuyB0E8iO8fwbvwCYXHQNEpeuqnL7fH//3vfJ2m3bZfHvrGfn9m1g2NHcbV7PVhqRv2/bIbxmNjb1HFAcqtEJQTlFU0qyD2XgEqI1pzMspasi4ddSuEe3bZKPdA5BEqo0VUxD4q0mnI1uWEPCGldBgCJcScUF@47H@eqkx@hVkVqW/uMrN@@6HNmHMIKlz2hlFkfmYmbEMWf8wVKJOTrOWYwZD62FGAArIm2dZtESpdsQawEGZDCOu@LaLzgt08LLFyVWnGWfWmIss1Zdx@OUGcRbLLjlsW7/nzpuiG9ebUj7tpegI "INTERCAL – Try It Online") ``` O Codepoints of input. Ż Prepend zero, +⁹ add 256 to each, B convert each to binary. U Reverse each, Ṗ€ remove last element from each, Ḅ convert from binary. _Ɲ Subtract all adjacent pairs, %⁹ and modulo 256. Ʋ€ Map: ; prepend to the number “...» "please,1<-#1do,1sub#1<-#", ; append to that “...» "doreadout,1". ;“...» Append "dogiveup" to the whole result Œu and uppercase. ``` ]
[Question] [ *The New York Times* periodically runs a puzzle they call the "Spelling Bee" in which they list six "allowed" letters plus one "mandatory" letter and challenge the reader to form as many five-letter-or-longer dictionary words as possible out of those letters. Each "allowed" letter can appear 0 or more times. The mandatory letter must appear at least once in each word. No other letters are allowed. Proper nouns are **not** acceptable answers. For example, in [last week's puzzle](https://www.nytimes.com/2017/02/18/crosswords/a-little-variety-spelling-bee.html), the allowed letters were `{"A", "C", "D", "H", "I", and "R"}`, while the mandatory letter was `"N"`. Allowed answers for this set of letters range from 5-letter words "ranch", "naiad", and "nadir", up to 9-letter words "cnidarian" and "circadian". The more words you find, the higher the *Times* rates your intelligence. Your challenge: write a solver in the language of your choice. Additional rules and tips: 1. If your programming environment or operating system provides a list of words, you may use it. If not, you must include code for loading a word list from disk or the internet; you can not assume it has been magically loaded into a variable outside your code. 2. The word list should be generic, not limited to only those words that contain the mandatory letter, and not limited to words that meet the length or other requirements here. In other words, all dictionary searches should be done by your code, not some pre-processor. 3. If a word is capitalized in the dictionary, treat it as a proper noun. If your dictionary does not distinguish proper nouns, find a different dictionary. 4. Different dictionaries will deliver different sets of answers, but given the test case above, you must return at least 20 qualifying answers, and the words "harridan", "niacin", and "circadian" must be on it. The words "Diana", "Adrian", and "India", as proper nouns, must not be. 5. Your code should take the form of a function or program that accepts two variables: a string or list of characters representing the allowed letters, and a character representing the required letter. It should return a list of allowed answers in any order. 6. Except to the extent my rules here dictate otherwise, [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. 7. In the event my rule summary here deviates from the rules at the *New York Times*, follow the rules here. 8. Shortest byte count wins, though I plan to call out excellent solutions using novel algorithms or that are otherwise interesting to me, assuming any such are submitted. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~50~~ ~~44~~ ~~41~~ ~~39~~ 43 bytes ``` param($a,$m)gc z|sls $m|sls "^[$a$m]{5,9}$" ``` ## Notes * Using a ~~scriptblock (unnamed function) because there's still a requirement for a function~~ full program. * Takes the "allowed" letters as a single string. * Using [The English Open Word List](http://dreamsteep.com/projects/the-english-open-word-list.html) which is provided as a series of lists (one for each letter). I've combined them all into a single file named `z`, ~~but I only included words that are between 5 and 9 letters, inclusive~~ due to the new rule, the wordlist and my gist have been updated to not exclude any of the original words (of any size). [Here's the list, for anyone else to use](https://gist.github.com/briantist/b1fbc8365f4224c4e7d91ffcf1656434). ## Explanation Reads the wordlist file `z` as lines and does two regular expression matches (by way of `Select-String` with the `sls` alias). The first `sls` matches the mandatory letter, so the result is all the words that contain the letter, then that gets piped into the second `sls` which uses an expression that, in the case of the example input, looks like this: `^[acdhirn]{5,9}$` (so it matches only words that consist of those letters and no others, between 5 and 9 characters in length, inclusive). ## Invocation and Output ``` &{param($a,$m)gc z|sls $m|sls ^[$a$m]+$} 'acdhir' 'n' ``` Output (57 words): ``` acarian acaridan acini ahind anana anarch anarchic arachnid arcana arnica cairn canard cancan candid candida canid canna cannach caranna carina chain characin chicana china chinar chinch cinch circadian # cnida cnidarian cranch crania dharna diarian dinar dinic drain handcar harridan # inarch indican indicia indri iridian nadir naiad naira nanna niacin # nicad rachidian radian ranarian ranch rancid randan ricin ``` [Answer] # **Mathematica, ~~143~~ 130 bytes** ``` Join@@StringCases[Join@@StringCases[WordList[],RegularExpression["^["<>#2<>#<>"]{5,9}$"]],RegularExpression["\w+(?="<>#<>")\w+"]]& ``` ## Invocation (with input) ``` Join@@StringCases[Join@@StringCases[WordList[],RegularExpression["^["<>#2<>#<>"]{5,9}$"]],RegularExpression["\w+(?="<>#<>")\w+"]]&["n","acdhir"] ``` ## Output (20 words) ``` {"anarchic", "arachnid", "cairn", "canard", "cancan", "candid", "candida", "chain", "china", "cinch", "circadian", "cnidarian", "dinar", "drain", "handcar", "harridan", "niacin", "radian", "ranch", "rancid"} ``` ### Explanation ``` Join@@ // Shortened version of Flatten; removes {} from StringCases lists StringCases[ // Find substrings in a string/list that match a regex pattern. Join@@ StringCases[ WordList[], // Built-in function; returns a list of English words. RegularExpression[ "^["<>#2<>#<>"]{5,9}$" // Take the WordList, and find 5-9 letter // words with any character in the // the first or second arguments. // In this case, "x" would be "achdir", // and "y" is the letter "n". // <> is for string concatenation. ] ], RegularExpression[ "\w+(?="<>#<>")\w+" // Take the result from the previous // StringCases function, and find words // that actually have the character(s) in // the second argument in them. // In this case, find words that actually // have the letter "n" in them. ] ] & // Define an anonymous function. ["n","acdhir"] // Pass arguments to the function; "#" is "n", and "#2" is "acdhir". ``` [Answer] # bash/dash/ash with grep and egrep, ~~31 30~~ 29 bytes ``` egrep ^[$1$2]\{5,}$ z|grep $2 ``` This assumes you have a a word list in a file named `z`. The [word list](https://gist.github.com/briantist/b1fbc8365f4224c4e7d91ffcf1656434) I used was kindly provided by [briantist](https://codegolf.stackexchange.com/users/30402). Example: ``` $ echo 'egrep ^[$1$2]\{5,}$ z|grep $2' > program; chmod +x program $ ./program acdhir n | tr '\n' ' ' acarian acaridan acini ahind anana anarch anarchic arachnid arachnidan arcana arnica cairn canard cancan candid candida canid canna cannach caranna carina chain characin chicana china chinar chinch cinch circadian cnida cnidarian cranch crania dharna diarian dinar dinic drain handcar harridan inarch indican indicia indri iridian nadir naiad naira nanna niacin nicad rachidian radian ranarian ranch rancid randan ricin ``` [Answer] # [Python 3.6](https://docs.python.org/3.6/) ~~84~~ 78 bytes -6 bytes thanks to WuTheFWasThat (`splitlines` -> `split` and `{c}and 4<len(w)<10` -> `{c*(4<len(w)<10)}`) ``` lambda s,c:[w for w in open('z').read().split()if{*w}-{*s}=={c*(4<len(w)<10)}] ``` An unnamed function that takes a string and a character. Returns a list created by keeping those entries (`w`s) from a file where the set of remaining letters after removing any that are in the "can use" set (`{*s}`) is the set of the single "must use" character. The `*`s in `{*x}` unpack the strings to save bytes over `set(x)`. The word-length check is `4<len(w)<10` and string multiplication saves a byte (since `{*w}-{*s}` can never result in a set containing an empty string). Requires a file in the current directory named simply **z** containing the list of words separated by newlines (or carriage returns or both). Taking a list of words would be preferable at **58** bytes. With `s='acdhri'` and `c='n'` and using a file containing all entries and suffixed entries from the [Chambers Scrabble™ Words](https://www.collinsdictionary.com/scrabble/scrabble-tools/) (CSW) dictionary A.K.A. SOWPODS (which explicitly excludes proper nouns) we get the following resulting list of **85** words: ``` ['acarian', 'acaridan', 'acaridian', 'acinar', 'acini', 'acinic', 'acridin', 'adhan', 'ahind', 'anana', 'anarch', 'anarchic', 'anicca', 'aniridia', 'aniridic', 'arachnid', 'arcadian', 'arcan', 'arcana', 'arnica', 'cairn', 'canada', 'canard', 'cancan', 'cancha', 'candid', 'candida', 'canid', 'canna', 'cannach', 'caranna', 'cardan', 'carina', 'chain', 'chana', 'characin', 'chicana', 'china', 'chinar', 'chinch', 'cinch', 'circadian', 'cnida', 'cnidarian', 'cranachan', 'cranch', 'crani', 'crania', 'darrain', 'dharna', 'diarian', 'dinar', 'dinic', 'dinna', 'drain', 'hainch', 'hanch', 'handcar', 'hariana', 'harridan', 'hinahina', 'inarch', 'india', 'indican', 'indicia', 'indri', 'iridian', 'nadir', 'naiad', 'naira', 'nandin', 'nandina', 'nanna', 'naric', 'niacin', 'nicad', 'rachidian', 'radian', 'radicand', 'ranarian', 'ranch', 'rancid', 'randan', 'ranid', 'ricin'] ``` The word "india", is listed by this dictionary even though, due to the rules of Scrabble™, it explicitly excludes proper nouns, as: "(In international radio communication) a code word for the letter i [-S]" ('-S' indicating "inidas" is also acceptable), of course we could use any other file listing the words, but do note that "india" is also listed in TWL, the equivalent dictionary used in official Scrabble™ tournaments in the U.S. and Canada. [Answer] # [Perl 6](https://perl6.org), ~~48~~ 41 bytes ``` {grep /^@_*[$^a@_*]+$/,grep *.comb>4,1.IO.words} ``` ``` {grep /^@_**5..*$/&/$(@_[0])/,1.IO.words} ``` Expects a whitespace-separated wordlist as a file called `1` in the current directory. Expects the required character as the first argument, and a list of the additional allowed characters as the second argument (or as multiple arguments, it doesn't matter), all in lowercase. ### How it works ``` { } # A lambda. (@_ is the flattened argument list.) 1.IO.words # Read words from file as a lazy sequence. grep / /&/ / # Filter words which match *both* these regexes: ^@_**5..*$ # 1) Consists of 5+ allowed chars. $(@_[0]) # 2) Contains the required char. ``` [Answer] **Perl, 43 + 1 (`-n` switch)** ``` /^[^\p{Lu}](?i)(?=.*n)[acdhirn]{5,9}$/&&say ``` **Run** on linux: ``` perl -nE '/^[^\p{Lu}](?i)(?=.*n)[acdhirn]{5,9}$/&&say' < /usr/share/dict/american-english ``` **Output:** 33 words without proper nouns ``` anarchic arachnid banana bandana bandanna branch canard cancan candid circadian crania enrich errand farina grandad granddad handcar harridan maharani mandarin maniac marina niacin ocarina ordain picnic piranha rancid saccharin tannin unhand urchin zinnia ``` [Answer] # Powershell, 41 bytes *Inspired by briantist's [answer](https://codegolf.stackexchange.com/a/111293/80745).* briantist uses 3 cmdlets to make a solution. I would like to keep within one cmdlet. ``` param($a,$m)sls "^(?=.*$m)[$a$m]{5,9}$" z ``` As with the briantist's answer, I used [The English Open Word List](http://diginoodles.com/The_English_Open_Word_List_%28EOWL%29) files combined into a single file named `z`. As in other answers, the regex subpattern `^[$a$m]{5,9}$` asserts when a line contains allowed and required chars only. The basic difference: `(?=.*$m)` asserts that the required character can be matched somewhere in a line, without consuming characters. See [docs](https://docs.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-language-quick-reference#grouping-constructs). Unfortunately, `sls` provides additional information, not matches only. The rules don't forbid it `:-)`. To display only words, you need to get the value of the `Line` property (47 bytes) or call the cmdlet `gc` (43 or 44 bytes). Test script: ``` $f = { # the output contains words and extra info param($a,$m)sls "^(?=.*$m)[$a$m]{5,9}$" z # 41 bytes, 1 command #param($a,$m)sls $m z|sls "^[$a$m]{5,9}$" # 40 bytes, 2 commands # only words solutions: #param($a,$m)sls "^(?=.*$m)[$a$m]{5,9}$" z|% l*e # 47 bytes, 1 command + 1 property #param($a,$m)gc z|sls "^(?=.*$m)[$a$m]{5,9}$" # 44 bytes, 2 commands #param($a,$m)gc z|sls $m|sls "^[$a$m]{5,9}$" # 43 bytes, 3 commands, briantist's https://codegolf.stackexchange.com/a/111293/80745 } &$f 'acdhir' 'n' ``` Output: ``` z:542:acarian z:547:acaridan z:854:acini z:2134:ahind z:3624:anana z:3644:anarch z:3647:anarchic z:5042:arachnid z:5117:arcana z:5466:arnica z:14834:cairn z:15334:canard z:15341:cancan z:15363:candid z:15364:candida z:15414:canid z:15435:canna z:15440:cannach z:15866:caranna z:16065:carina z:17442:chain z:17721:characin z:18241:chicana z:18408:china z:18411:chinar z:18418:chinch z:19142:cinch z:19213:circadian z:20286:cnida z:20288:cnidarian z:23975:cranch z:23983:crania z:28928:dharna z:29121:diarian z:29648:dinar z:29687:dinic z:32006:drain z:48944:handcar z:49311:harridan z:54033:inarch z:54380:indican z:54393:indicia z:54473:indri z:56194:iridian z:70546:nadir z:70575:naiad z:70595:naira z:70655:nanna z:71643:niacin z:71659:nicad z:87803:rachidian z:87884:radian z:88295:ranarian z:88304:ranch z:88321:rancid z:88329:randan z:92641:ricin ``` ]
[Question] [ ## Input A dictionary with string keys and string values. ## Output The 'inversedict' of this dictionary. ## How to make an inversedict An inversedict is a dictionary with string keys and **string array** values. The keys are the values from the original dictionary, and the values are the keys from the original dictionary with that value from the original dictionary. ## An example ``` Input ["Clyde": "blue", "Sarah": "blue", "Fred": "green"] Output ["blue": ["Clyde", "Sarah"], "green": ["Fred"]] ``` ## This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # Mathematica, 28 bytes ``` Merge[Reverse/@Normal@#,#&]& ``` The input is an `Association`, the output is an `Association` too. **Explanation** ``` Normal@# ``` Convert the input `Association` to a `List` of `Rule`s. ``` Reverse/@ ... ``` Reverse the `Rule`s. ``` Merge[ ... ,#&] ``` `Merge` all `Rule`s, grouping duplicates with a `List` and then with the identity operation. Creates an `Association`. **Usage** ``` Merge[Reverse/@Normal@#,#&]&[ <|"Clyde" -> "blue", "Sarah" -> "blue", "Fred" -> "green"|> ] ``` > > `<|"blue" -> {"Clyde", "Sarah"}, "green" -> {"Fred"}|>` > > > [Answer] ## Python 2, 54 bytes ``` lambda i:{i[k]:[a for a in i if i[a]==i[k]]for k in i} ``` **Usage:** ``` f=lambda i:{i[k]:[a for a in i if i[a]==i[k]]for k in i} print f({"Clyde": "blue", "Sarah": "blue", "Fred": "green"}) ``` Gives ``` {'blue': ['Sarah', 'Clyde'], 'green': ['Fred']} ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` tᵍ⟨ttʰhᵐ⟩ᵐ ``` [Try it online!](https://tio.run/##dY0xCsJAEEWvMkytjQdQRPACChZLitEMbnCT6O6qBLGxECwEb2CrnY2NR/AWyUVi1g2IoOW8/@b/saaJzFQ6bZWbNUKzDbjuFPtbsdvlj8M2v59Km9@Pxfli7fMmq7s4Xx0tBQiBPZWFjA3AsVoyBg0QOCBN8hv1NYeOTDVzgoFjArtKOWYlg6GYYUXeFxjT/E9i01@B7xtKzlxKul4lP7BMosXHsjIyEJm3CLPqw6tJCFTXvQe8VP@MGDRXbRkkzCHEqfYWGwsTMuxECF4 "Brachylog – Try It Online") Takes input as a list of `[key, value]` pairs through the input variable, and outputs a list of `[value, [keys]]` pairs through the output variable. ``` ᵍ Group the elements of the input t by their last elements. ᵐ For each group, t its last element ⟨ ⟩ paired with hᵐ the first element of every element ʰ with the first element of the pair being replaced by t its last element ᵐ is the corresponding element of the output. ``` ...such an eloquent explanation... [Answer] # [Rust](https://www.rust-lang.org/), 127 bytes ``` use std::collections::HashMap as H;|m:H<String,String>|{let mut n=H::new();for(k,v)in m{n.entry(v).or_insert(vec![]).push(k)}n} ``` [Try it online!](https://tio.run/##lY49T8MwEIZ3fsXVky1F@QEOgQGpysLUEVWVSS5NVOcS@SNV5fq3BwfKABUD01l3fp73Nd66pSUYVE9cQHgA0OighRLC4i2CdY2U9ag11q4fyUpZKdu9qgmUhaq4DrJ63DnT0zH7Gk/XsBoG74DKSkrCMxdFOxp@ymbRp6hAOZIzFz6LfDSHniwax2esN297kU/edvwkIsUlFrc6q2xIkeXfdb6DEpF@5jcpe9GXBlnuxoP9bMdFBuxd@5@7O2ynjOr@j20NNr@po0Gke2xKb6dpw1mQz5Fl0PJkWm9x@QA "Rust – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` uXeHG]hHQH ``` [Try it online!](https://tio.run/##K6gsyfj/vzQi1cM9NsMj0OP//@hoJeecypRUJR0FpaSc0lSlWB2FaKXgxKLEDFQht6LUFJBIelFqap5SbCwA "Pyth – Try It Online") ``` uXeHG]hHQH Implicit: Q=eval(input()), H={} (empty dictionary) u Q Reduce elements of Q... H ... starting with an empty dictionary... ... current value is G, next value is H: X G Add to G... eH ... with key as last element of H (i.e. value from original input dictionary)... ]hH ... value as first element of H, wrapped in a list This adds a new single-element list if the key is not alrady present, or concatenates values if it is ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~9~~ 7 bytes Input is as a 2D-array: `[[key,value],[key,value],...]`. Output is as a 3D-array: `[[value,[key,key,...]],[value,[key,key,...]],...]`. If we can ouput the pairs in reverse order then the `Ô` can be removed, an the `v` replaced with `o` to save a byte. ``` üÌ®ÕÔvÎ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/Myu1dR2zg&input=W1siQ2x5ZGUiLCJibHVlIl0sWyJTYXJhaCIsImJsdWUiXSxbIkZyZWQiLCJncmVlbiJdXQotUQ) ``` üÌ®ÕÔvÎ :Implicit input of array ü :Group and sort by Ì : Last element of each ® :Map Õ : Transpose Ô : Reverse v : Modify first element Î : Get first element ``` If output *must* be a 2D-array then: ## ~~10~~ 8 bytes ``` üÌc_ÕÔvÎ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=/MxjX9XUds4&input=W1siQ2x5ZGUiLCJibHVlIl0sWyJTYXJhaCIsImJsdWUiXSxbIkZyZWQiLCJncmVlbiJdXQotUQ) The `_`, essentially, serves the same purpose as the `®` above and the `c` flattens the array by one level afterwards. [Answer] # Lua, 82 Bytes ``` function(t)g={}for k,v in pairs(t)do g[v]=g[v]or{}g[v][#g[v]+1]=k end return g end ``` An anonymous function which takes a table as an input and outputs the inverse dict. ## Commented and Ungolfed. ``` function(t) #Anonymous Function. g={} #Define the output array. for k,v in pairs(t) do #For each value in the input by key value pairs. g[v]= g[v] or {} #Set the value of the output dictionary with the key v, to either itself, or a new table if it's null. g[v] [#g[v]+1] = k #Set a new value (#g[v]+1 is the key that is +1 the count, lua is 1 indexed) to the key. end #This loop will append values with the same 'key', instead of set. However, makes all output in table form. return g #Output g end #End ``` [Answer] # JavaScript (ES6), 57 bytes ``` d=>eval("r={};for(i in d)(r[j=d[i]]=r[j]||[]).push(i);r") ``` Input and output are as Objects, e.g. `{"Clyde": "blue", "Sarah": "blue", "Fred": "green"}` [Answer] ## C#6, 136 bytes ``` using System.Collections.Generic;using System.Linq;ILookup<string,string>F(Dictionary<string,string>d)=>d.ToLookup(x=>x.Value,x=>x.Key); ``` [repl.it demo](https://repl.it/E2QB/0) Seriously, do I really need to ungolf this? Just [create](https://msdn.microsoft.com/en-us/library/bb549346(v=vs.110).aspx) an [`ILookup`](https://msdn.microsoft.com/en-us/library/bb534291(v=vs.110).aspx) with input value as output key and input key as output value. [Answer] # C++17, 158 bytes ``` #import<string> #import<map> #import<vector> [](auto m){std::map<std::string,std::vector<std::string>>n;for(auto x:m)n[x.second].push_back(x.first);return n;} ``` Ungolfed and usage: ``` #include<iostream> #include<string> #include<map> #include<vector> auto f= [](auto m){ std::map<std::string,std::vector<std::string>>n; //using namespace is equally long for(auto x:m) n[x.second].push_back(x.first); return n; } ; using namespace std; int main(){ map<string,string> m={ {"a","x"},{"b","x"},{"c","y"} }; auto n = f(m); for (auto x:n){ cout << x.first << ": "; for (auto y:x.second) cout << y << ", "; cout << "\n"; } cout << "\n"; } ``` [Answer] # [Factor](https://factorcode.org/), 27 bytes ``` [ [ last ] collect-key-by ] ``` [![running the above code in the listener](https://i.stack.imgur.com/nxWKk.gif)](https://i.stack.imgur.com/nxWKk.gif) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 (or 9) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .¡θ}εø`н‚R ``` Input as `[[key,value],[key,value],...]`; output as `[[value,[keys]],[value,[keys]],...]`. [Try it online.](https://tio.run/##yy9OTMpM/f9f79DCcztqz209vCPhwt5HDbOC/v@PjlZyzqlMSVXSUUrKKU1VitWJVnIrSk0B8tOLUlPzwALBiUWJGXAVsQA) If it's allowed to output as `[[[keys],value],[[keys],value],...]` instead, it can be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) less by removing the trailing `R`: [Try it online.](https://tio.run/##yy9OTMpM/f9f79DCcztqz209vCPhwt5HDbP@/4@OVnLOqUxJVdJRSsopTVWK1YlWcitKTQHy04tSU/PAAsGJRYkZcBWxAA) **Explanation:** ``` .¡ } # Group the pairs of the (implicit) input-list by: θ # Their last item ε # Then map over each group of pairs: ø # Zip/transpose; swapping rows/columns ` # Pop and push the list of keys and list of values separately to the stack н # Pop and leave just the first item of the values-list ‚ # Pair it with the keys-list R # (optional: Reverse the [[keys],value] pair to [value,[keys]]) # (after which the result is output implicitly) ``` [Answer] # JavaScript, 47 bytes Input as a 2D array, output as an object. ``` a=>a.map(([k,v])=>i[v]=[...i[v]||[],k],i={})&&i ``` [Try it online!](https://tio.run/##TcixDsIgFEDRf2FoIEFmF7qYODjo0PHlDc@WIhahgUrSWL8ddXO7596pUO6Tm5dd2ddRV9ItqQfNnMMkCwrdOiioQSn1i20DlBNKp19v0TSu9jHk6I3y0fJTdzmrvCQXrBtXPnIAdvDrYJhkV/80DCWwjhLd/scxmeFrm4wJDFEIUT8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ZQż¹ƙɗ@/ ``` [Try it online!](https://tio.run/##y0rNyan8/z8q8OieQzuPzTw53UH//@F270dNayL//69Wcs6pTElVslJQSsopTVXSUVAKTixKzEAWcCtKTQHx04tSU/OUavUyS1JzizU0AQ "Jelly – Try It Online") Input as a list of `[key, value]` pairs, output as a list of `[value, keys]` pairs. ``` Z ɗ@/ With the keys on the right and the values on the left: ż Zip Q the unique values with ¹ƙ the keys grouped by value, in order of the value's first appearance. ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 6 bytes ``` .=~$@~/.$@$. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWa_Rs61Qc6vT1VBxU9CBCUJmbk6OVojVilPLzUmOUdBRilErzMktilDR1FICCJeX5EMGCoszcVLhoRlFqKhbxtPzSIohwcn5uQX5xZglCKrMMm47izApMDbFKsVC3AQA) Takes and outputs a list of pairs. ``` . Map =~ group by $ [input] @ [second element] ~ pair / fold . map $ [the group] @ [second element] $ [value] . map [the group] [first element] ``` **5 bytes** if we allow the output to be in the format `[(values, key)]` rather than `[(key, values)]`: ``` .=~$@~`'$/ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWq_Rs61Qc6hLUVfQhAlDxm5OjlaI1YpTy81JjlHQUYpRK8zJLYpQ0dRSAgiXl-RDBgqLM3FS4aEZRaioW8bT80iKIcHJ-bkF-cWYJQiqzDJuO4swKTA2xSrFQtwEA) [Answer] # [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` ∵⊂⊝:⊕□⊛,⍘⊟⍉ ``` [Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAg4oi14oqC4oqdOuKKleKWoeKKmyzijZjiip_ijYkKCmZbeyJDbHlkZSIgImJsdWUifQogIHsiU2FyYWgiICJibHVlIn0KICB7IkZyZWQiICJncmVlbiJ9XQoKZlt7IlN1emFuIiAiYSJ9CiAgeyJKb2UiICJiIn0KICB7Ik1hdHQiICJiIn0KICB7IlplZCIgImMifQogIHsiWmVsZGEiICJhIn1dCg==) ``` ∵⊂⊝:⊕□⊛,⍘⊟⍉ ⍉ # transpose ⍘⊟ # uncouple , # over ⊛ # classify ⊕□ # group by box : # flip ⊝ # deduplicate ∵⊂ # zip ``` [Answer] # Perl, 36 bytes This is an anonymous function which takes a hash (not hash reference) as an argument, and returns a hash (not a hash reference) as its result. (A "hash" is Perl's name for a dictionary.) Although the language has dictionaries, it doesn't have sets; thus, for the values of the inverse dictionary (which are logically sets), I used the common Perl representation of a set as a hash, in which the keys are the set elements and the values are irrelevant. Here's the program itself: ``` sub{my%t;$t{+pop}{+pop}++while@_;%t} ``` Here's how I tested it: ``` use Data::Dumper; $f = sub{my%t;$t{+pop}{+pop}++while@_;%t}; my %test = qw/sky blue sea blue grass green/; print Dumper({&$f(%test)}); ``` The dump of the resulting hash is: ``` $VAR1 = { 'blue' => { 'sky' => 1, 'sea' => 1 }, 'green' => { 'grass' => 1 } }; ``` which is the expected value. [Answer] ## Haskell, 55 bytes ``` foldl(\l(k,v)->maybe(v,[k])((,)v.(k:))(lookup v l):l)[] ``` This uses the good old association list as the data structure, which means that the output list may contain multiple elements with the same key, where only the first one is valid. However, I exploit the fact that the keys in the input list are all distinct. Usage example: ``` *Main> foldl(\l(k,v)->maybe(v,[k])((,)v.(k:))(lookup v l):l)[] [("Clyde","blue"),("Sarah","blue"),("Fred","green")] [("green",["Fred"]),("blue",["Sarah","Clyde"]),("blue",["Clyde"])] ``` How it works: ``` foldl( )[] -- starting with the empty list, reduce the -- input list \l (k,v)-> -- with via a lambda function that takes a list l -- (the output list so far) and a key-value-pair -- (k,v) from the input list and returns the next -- version of the output list, which is made by: :l -- prepend to the existing list maybe (lookup v l) -- if v is already a key in the output (,)v.(k:) -- prepend k to the list for v -- (this leaves the current pair in places and -- adds the updated version to the front) (v,[k]) -- else a new pair with v and k flipped -- and k put into a singleton list ``` [Answer] ## Racket 208 bytes ``` (let p((l2(remove-duplicates(map(λ(x)(list-ref x 1))ll)))(ol'()))(cond[(empty? l2)(reverse ol)][ (p(rest l2)(cons(cons(first l2)(for/list((i ll)#:when(equal?(first l2)(list-ref i 1)))(list-ref i 0)))ol))])) ``` Ungolfed: ``` (define (f ll) (define l2 (remove-duplicates (map (λ (x) (list-ref x 1)) ll))) (let loop ((l2 l2) (ol '())) (cond [(empty? l2) (reverse ol)] [else (define tl (for/list ((i ll) #:when (equal? (first l2) (list-ref i 1))) (list-ref i 0))) (loop (rest l2) (cons (cons (first l2) tl) ol)) ]))) ``` Testing: ``` (f '[("Clyde" "blue") ("Sarah" "blue") ("Fred" "green")]) ``` Output: ``` '(("blue" "Clyde" "Sarah") ("green" "Fred")) ``` [Answer] # Groovy, ~~56~~ 53 bytes ``` {m=[:];it.each{k,v->if(!m."$v"){x=m."$v"=[]};x<<k};m} ``` ## Testing ``` ({m=[:];it.each{k,v->if(!m."$v"){x=m."$v"=[]};x<<k};m})(["Clyde": "blue", "Sarah": "blue", "Fred": "green"]) ``` **Output** ``` [blue:[Clyde, Sarah], green:[Fred]] ``` [Answer] # Java 7, ~~211~~ 205 bytes golfed: ``` Map<String,List<String>>i(Map<String,String>m){Map<String,List<String>>r=new HashMap<>();for(String k:m.keySet()){String s=m.get(k);if(r.get(s)==null)r.put(s, new ArrayList<>());r.get(s).add(k);}return r;} ``` ungolfed: ``` public static Map<String, List<String>> i(Map<String, String> m) { Map<String, List<String>> r = new HashMap<>(); for (String k : m.keySet()) { String s = m.get(k); if (r.get(s) == null) r.put(s, new ArrayList<>()); r.get(s).add(k); } return r; } ``` [Test it online!](https://ideone.com/AZO9Uk) Java ... the worst golfing language. [Answer] ## R, 79 69 bytes ``` function(l)setNames(lapply(u,function(x)names(l)[l==x]),u<-unique(l)) ``` R does not have a dictionary by default but the closest approximation to a dictionary is an object of class `list`. It's basically a generic vector allowing for multiple data types where each value (can basically be any R-object) is allowed to have a name/key. **Example** A list with keys/names can be created as e.g.: ``` l <- list(Clyde="blue", Sarah="blue", Fred="green") ``` Which if printed returns: ``` $Clyde [1] "blue" $Sarah [1] "blue" $Fred [1] "green" ``` Calling the function now returns: ``` $blue [1] "Clyde" "Sarah" $green [1] "Fred" ``` [Answer] # [Go](https://go.dev), 107 bytes ``` type S=string func f(m map[S]S)map[S][]S{O:=make(map[S][]S) for k,v:=range m{O[v]=append(O[v],k)} return O} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5BCsIwEEX3OUXIKoHqWgpdCW4rZFm6iHZSS5o0jKkgpSdxUwQP4VG8jY0VcfVnPn_m_du97qanV0ejaqBWNY401ncY1kzbwB590KvNy4SrByqzc8DG1UT37kg1t3PeF7KUYtGilEOeZlYZ4D9HEN0hNcklzVC5yBjy4lJmyntwFY9zYsRIEEKPjubjFwkfSCzEBR2IjX99sRQoFxnYtr1WwFLKDm0PLKFMKlSnf2OHUMW9RgDHRrKfD0Pr-NxeCPKFTdOibw) [Answer] # [Raku](https://raku.org/), 28 bytes ``` {push my Array%: .antipairs} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/uqC0OEMByHMsKkqsVLVS0EvMK8ksSMwsKq4FKVLNSATK2yo451SmpCrY2imoJ@WUpqrrKAQnFiVmIAu4FaWmgPnpRampeerWXMWJlQppGmADNK3/AwA "Perl 6 – Try It Online") Raku hashes have an `antipairs` method that returns a list of the value-key pairs, and a `push` method that adds any number of key-value pairs, accumulating values associated with duplicated keys into arrays. So this answer could *almost* be just: ``` {push {}: .antipairs} ``` ...but unfortunately the `push` method *doesn't* create an array value unless there actually is a duplicated key. In the provided example, it would associate the key `"green"` with the string `"Fred"`, not the array `["Fred"]`. So I address that by declaring that the anonymous returned hash has values of type `Array`. [Answer] # [Scala 3](https://www.scala-lang.org/), 47 bytes ``` _.groupBy(_._2).map{case(k,v)=>k->v.keys.toSeq} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=VY-7asMwFIb3PMVBkwS2Cu1SAjb0QrdMGYMxJ9Kp61qVVUl2YkKfpEuWZukT5W3qYg_J9B8-OP_l-xQUGrz73bDUtjv0lhXnst2-k4qwwtoC7SNZHeDBucMCoEcDte3JB3quVVwCX6HbrKOvbZXApAVkOVxh-pzvohCQ_XTxNb0_35Sy8m3nHgdeyvJWyA90B4WBeJP0IsubNO9lQ0OQsR0dvuY3NbfQkP2HcPZkBk0M0hzY1nTEEmBr9Ph2jV486YlUnsgyMdq4sVI0ll8M4lqIxRx1PE76Bw) ]
[Question] [ ## Challenge You must write an encoder (and a separate decoder) which takes a string as input and outputs the string encoded in the *style* of a strand of DNA. ## DNA DNA is made up of four types of nucleotide: * Adenine (A) * Thymine (T) * Cytosine (C) * Guanine (G) Adenine and thymine pair up together to make `AT` or `TA`. Similarly, cytosine and guanine pair up together to make `CG` or `GC`. Let's call these pairs *units*. This means that your encoded string is only allowed to contain the four units AT, TA, CG and GC. This means that: ``` ATTAGACG ``` Would be invalid because it contains the unit GA, which is impossible. Similarly, ``` TAGCGCCGATA ``` Is invalid because the final A does not have a thymine to pair up with. ## Example You must encode the following example text and use its encoded length as part of your score: > > I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower. At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts. > > > ## Bounty If you answer this challenge in the language [DNA#](https://esolangs.org/wiki/DNA-Sharp), I will offer a 100 to 200 rep bounty. ## Rules Your encoder and decoder programs *must* work for any string supplied. Therefore, your encoder must produce a genuine encoding and your decoder should not simply hardcode the example text. You must support all printable ASCII characters: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` If you can support more characters, that is acceptable. ## Scoring Your score is how long in characters (not units) the encoded version of the above text plus the length in bytes of your decoder and your encoder. ## Winning The program with the lowest score wins. [Answer] ## Pyth, 5152 + 21 + 23 = 5196 bytes ### Encoder ``` sm@c4s_B"ATCG"djC.ZQ4 ``` [Try it here](http://pyth.herokuapp.com/?code=sm%40c4s_B%22ATCG%22djC.ZQ4&input=%22%22%22I+have+a+friend+who%27s+an+artist+and+has+sometimes+taken+a+view+which+I+don%27t+agree+with+very+well.+He%27ll+hold+up+a+flower+and+say+%22look+how+beautiful+it+is%2C%22+and+I%27ll+agree.+Then+he+says+%22I+as+an+artist+can+see+how+beautiful+this+is+but+you+as+a+scientist+take+this+all+apart+and+it+becomes+a+dull+thing%2C%22+and+I+think+that+he%27s+kind+of+nutty.+First+of+all%2C+the+beauty+that+he+sees+is+available+to+other+people+and+to+me+too%2C+I+believe.+Although+I+may+not+be+quite+as+refined+aesthetically+as+he+is+...+I+can+appreciate+the+beauty+of+a+flower.+At+the+same+time%2C+I+see+much+more+about+the+flower+than+he+sees.+I+could+imagine+the+cells+in+there%2C+the+complicated+actions+inside%2C+which+also+have+a+beauty.+I+mean+it%27s+not+just+beauty+at+this+dimension%2C+at+one+centimeter%3B+there%27s+also+beauty+at+smaller+dimensions%2C+the+inner+structure%2C+also+the+processes.+The+fact+that+the+colors+in+the+flower+evolved+in+order+to+attract+insects+to+pollinate+it+is+interesting%3B+it+means+that+insects+can+see+the+color.+It+adds+a+question%3A+does+this+aesthetic+sense+also+exist+in+the+lower+forms%3F+Why+is+it+aesthetic%3F+All+kinds+of+interesting+questions+which+the+science+knowledge+only+adds+to+the+excitement%2C+the+mystery+and+the+awe+of+a+flower.+It+only+adds.+I+don%27t+understand+how+it+subtracts.%22%22%22&debug=0) ### Decoder ``` .ZCimxc4s_B"ATCG"dcQ2 4 ``` [Try it here](http://pyth.herokuapp.com/?code=.ZCimxc4s_B%22ATCG%22dcQ2+4&debug=0) (Input too long to link, put output of first in quotes in the input box) Compresses the input and converts it from base 256 into an integer. Then converts into a sequence of base 4 numbers and chooses from `['AT', 'CG', 'GC', 'TA']` [Answer] [**DNA#**](https://esolangs.org/wiki/DNA-Sharp) **: 10216 + 852 + 384 = 11452 bytes** This is not exactly tested, as I haven't gotten a hold of a working interpreter... There are probably mistakes I use a simple brute force approach so far where each character is read in, then broken up into 2 bit blocks with `AT = 00; TA = 01; CG = 10; GC = 11`. The sample text is 1277 ASCII characters, and it takes 4 codes (2 bits) to encode each 8 bit char: 1277 \* 4 \* 2 = **10216 bytes** # Encoder **852 bytes - line form** ``` GCGCGCTAATATATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATATTAATATGCATGCCGCGGCTACGATATGCCGCGATATATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATTAATTAATGCATGCGCTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATATATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATGCATGCATCGGCCGGCTAATATATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATGCATGCATCGGCCGGCTAATATATTAATTAATTAATTAATATATCGATCGATCGATCGATGCATGCATCGGCCGATATGCATATATGCATATGCATGCATGCATCGGCTAATTAATATTAATATGCATGCCGCGCGATATGCCGCGTACGATGCCGCGATGCATGCTATAATATATATCGCGATATATATGCTAATCGGCCGATTAATTAATTAATTAATGCCGATATATCGCGATATTAATATGCATGCCGCGATATGCTAATCGGCCGATATGCTAATCGGCCGGCCGATGCATGCGCCGATGCATGCGCGCGCCG ``` **224 bytes - symbol form:** ``` ,[>++++++++*=X>:=<<X[/=<X>++++++++*=X+>+++++++++*=X+++<<[>+++++++++++++++++++>-------------------<<-][>----------------->+++++++++++++++++<<-][>++++>----<<-]>.>.<<<-[+>:=<<X/=<X*=<X<<-=>>X>>[-]++++</=>X>:=<<X>[-]>[-]]<<]<<,] ``` and with variable names and some messy comments... ``` DNA# dna encoder a = input //get first char [ //for each char b = 64 //divisor to get first 2 bits c = a //initialize as a [ //while c != 0 c /= b d = 65 //first print char e = 84 //second print char c //select c [ //if c > 0 (3,2,1) d + 19 e - 19 c - 1 ] [ //if c > 1 (3,2) d - 17 e + 17 c - 1 ] [ //if c > 2 (3) d + 4 e - 4 c - 1 ] //c is now 0 (hopefully) print d print e b - 1 [ //if b is not 1 (last 2 bits) b + 1 //reset b c = a //trash top 2 bits (modulus algorithm) c /= b c *= b a -= c c = 0 //reset c c + 4 b /= c //b >> 2 c = a //copy a again for next 2 bits d = 0 //get a 0 value so we don't loop ] c //select c (0 if done with char: exit loop and get next char) ] a = input //get next char ] ``` # Decoder **384 bytes - line form** ``` GCGCGCGCGCTAATATATATATTAATTAATTAATTAGCTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATTAATTAATGCATGCATGCTATAATATATATATATCGCGGCTAATATATTAATGCATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAGCCGGCTAATATATTAATGCATCGATCGATCGATCGATCGATCGGCCGGCTAATATATTAATGCATTAATTAATTAATTAGCCGATTAATTAATTAATTAATATTACGATGCCGCGATGCGCGCGCGCATATATATATCGGCCGATGCGCATATGCGCCG ``` **99 bytes - symbol form** ``` ,,[>>++++[>+++++++++*=X+++<<<-=>>>X[>+<+++++++++++++++++++][>+<------][>+<++++]++++>*=<X<,,>>-]<.<] ``` var names... ``` DNA# dna decoder , , /* read second char into a*/ [ /* for each set of 4 pairs */ c = 4 /* loop iterator */ [ a - 84 /* if pair was AT (65,84): don't increment b */ [ b + 1 a + 19 /* if pair was TA (84,65): increment b once */ ] [ b + 1 a - 6 /* if pair was CG (67,71): increment b twice */ ] [ b + 1 a + 4 /* if pair was GC (71,67): increment b three times */ ] a = 4 b *= a /* shift b up 2 bits */ a,, /* get next char (skip one) */ c - 1 /* decrement loop iterator: exit loop on 0 */ ] b print /* output b in ASCII */ a /* select a (next char) */ ] /* end if next char is 0 (null terminated string) */ ``` If anyone finds a mistake or is able to run the web interpreter feel free to tell me how wrong I am :P [Answer] ## Python 2, ~~10216~~ 5152 + ~~72~~ 98 + ~~122~~ ~~110~~ 139 = ~~10410~~ ~~10398~~ 5389 ### Encoder: ``` import zlib lambda s:''.join('ACGTTGCA'[ord(c)>>b&3::4]for c in zlib.compress(s)for b in(0,2,4,6)) ``` ### Decoder: ``` import zlib lambda s:zlib.decompress(''.join(chr(int(''.join([str('ACGT'.index(s[i+j]))for j in(6,4,2,0)]),4))for i in xrange(0,len(s),8))) ``` [Answer] ## Javascript (ES6), ~~6138~~ 6038 bytes These functions will encode and decode any printable ASCII characters as required by the challenge rules. They are however using a static Huffman code which is optimized for the example text. They should work pretty well on any other English text, as long as there aren't too many capital letters, digits or miscellaneous symbols. But they will perform poorly on a random input. *Edit: saved 94 bytes by rethinking the decoder logic and including all hints provided by Neil* ### Encoder (~~305~~ 281 bytes) ``` s=>(n=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>C[c]=('00'+(n++).toString(2)).slice(-i-3)),n*=2)),s=s.replace(/./g,c=>C[c]||(524160|c.charCodeAt()).toString(2)),s.length&1&&(s+=0),s.replace(/../g,c=>'ATCG'[c=+`0b${c}`]+'TAGC'[c])) ``` ### Decoder (~~391~~ 315 bytes) ``` s=>(n=N=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>(C[j=i+3]=(C[j]||{}))[n++]=c),n*=2)),s=s.replace(/../g,c=>''+((x='ATCG'.search(c[0]))>>1)+(x&1)),eval(`for(r='';N<s.length-1;){for(i=j=0;!(f=C[j]&&C[j][i])&&j++<19;i+=+s[N++]+i);r+=f||String.fromCharCode(i&127)}`)) ``` ### DNA sequence (5442 bytes) Below is the DNA sequence which is generated for the example text. ``` GCTATAATATCGCGCGTAGCGCATATCGATTAATATTACGGCGCCGTATACGATCGGCGCTAGCATTAGCTAATCGGCATTAGCCGATCGTAATATCGATGCCGATTAATGCATGCTAATGCTAATGCTAATATTAATTAGCCGGCCGATTATATAATCGTAATTAATGCATTAGCATATTACGCGTACGGCCGATATGCATCGATCGCGTAATGCGCCGGCATCGGCCGATTAATATTAGCGCATTACGATGCGCTAATATGCCGCGTATATACGCGGCATCGCGATGCTATAATTATAGCCGATTAGCGCGCATTATAATATTAATGCGCTATACGTAATCGTAATTAGCTAATGCTATAATCGCGATGCGCCGATTAGCATGCGCTACGATGCCGCGATGCCGATGCATTACGCGATATGCGCGCGCTAATGCGCCGATGCATTACGATATATCGGCATTACGATCGGCCGATGCCGTAGCGCTACGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAATATCGATGCGCTAGCATTAATCGCGTAGCTACGATGCGCCGCGGCATTAATTAATTAGCGCTACGATTATACGATGCCGCGATTACGGCATTATAATGCCGTACGCGTACGGCTAGCGCCGTAGCATATATTACGCGCGATATGCTAATGCGCCGTAGCGCCGCGATATCGATGCGCTAGCATTACGCGGCGCCGATGCATTACGATATATCGTAGCCGCGGCATCGTAATGCCGCGATATGCGCGCTACGCGCGTATAGCATATCGCGTAATTAATCGCGTAGCTAGCATCGATGCGCCGCGGCTATAATATCGTAATCGATTAATTAGCATATCGTACGTACGCGTACGCGTACGCGATTATACGTAATTAGCATTAATCGTAATCGATTATACGATGCCGCGATTACGGCATTATAATGCCGTACGCGTACGGCTAGCGCCGTAGCATATATCGCGTATATACGCGTAATATGCTAATCGATGCTACGGCCGTACGCGATTAGCTAGCATTAGCATCGATTAATCGTAATATCGATATCGTACGGCATGCATTATAGCCGCGTACGCGTACGCGATTATAATCGTAGCGCTACGTAATTATAATCGCGGCTAATCGATTAATGCATTACGATATATCGTAGCCGGCTAATGCATGCTAATATTAATTAGCCGGCCGATTACGCGCGATTACGGCATTACGGCTAATTAGCATATTACGTAATATCGATATCGGCGCGCATGCCGATGCATATATCGCGTATATACGTAGCGCGCTATAGCCGTAGCGCCGCGATATCGATGCGCTAGCATTACGCGCGATCGCGTATATACGTAGCGCGCCGGCATTATAATCGCGCGTATAATATTATAATGCGCCGATCGTAATTAGCGCTACGGCATGCGCTAGCATTAATTACGGCCGATTAGCGCCGTACGCGCGCGGCCGGCGCTAATATTAGCGCGCCGATGCTACGTACGTACGCGATTAATTACGGCCGATTAATGCATTACGATGCGCATCGATCGCGTATAATCGATGCTACGATCGCGTAGCATGCTATAGCTACGATCGCGTATATAATCGCGATATCGCGTAATTAATCGTAATGCATCGATTACGCGTAATATCGTAGCGCATTAATTACGGCATATCGTACGGCTACGATATCGATCGCGCGATATTAATTATAATCGCGTAGCATCGATGCGCTACGTACGATGCGCTAGCCGATATCGATTAATTAGCCGGCCGATCGCGCGATATTAGCATATTAATTATATAATTAATTAGCCGTAATTACGCGCGATGCTACGATGCCGATTACGATGCGCGCATATGCCGCGATATGCGCGCTATACGATCGCGTATACGATGCCGTAGCGCTAATCGCGATGCTATAATTAGCATATCGTAGCTACGATTAGCCGATCGCGATTACGGCATTAATTAGCGCGCATGCCGTATACGCGCGATCGATTAATCGTAATTACGTAATGCCGGCCGGCATGCCGTACGGCCGATTAATATGCATGCTAATCGCGTACGCGTACGCGGCATCGTACGATGCATTAGCTACGATTAATCGTAATATCGCGTAATATGCTAATCGATGCTAATGCTAATGCTAATATTACGCGCGATCGGCATCGATGCCGATTAATGCGCTAGCGCCGGCGCATCGTACGGCATGCATCGTATAATTAATTATAATCGCGTAATTACGGCATTATAATGCCGTACGCGGCCGGCATTAATTACGGCCGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAGCTAATATTAGCGCCGCGCGCGATTATAATCGCGTAATTAATCGCGTAGCATATTAATTATAATGCTAGCATATTAGCGCATCGATGCTATAATTAATCGTAATCGATGCCGATGCCGTACGGCATCGCGATGCCGATCGATGCATCGTAATATCGTACGGCTAATTAGCATGCTAATATCGCGTATAATCGATGCTAGCGCATTAATTAGCTAATTAGCATCGATCGCGTATATAATTAGCATATCGCGTAATTAATCGTAATGCATGCCGCGATATGCTATAATTATACGCGATGCCGTAGCATTATAGCATATGCTAGCATATCGTAGCCGCGTACGTAGCATCGATCGCGTATAATCGATCGGCATTAGCATTACGATCGTAATATGCATGCCGATCGCGTATAATGCCGTAATGCGCCGTAATTATAATCGCGTAATTATACGCGATGCCGATGCGCTAGCCGATTACGCGGCATCGTATAATTACGGCCGATTAATCGGCTATAATGCTAATATGCGCATCGATTACGTAGCCGTATACGCGGCCGTAGCGCATCGATGCCGCGTATATACGCGGCATCGCGATTAATGCATTAATGCATATATTATATAATGCGCCGATTAATATCGATATGCTACGATCGCGTAGCATGCTATAGCTAGCCGCGATATGCTATAATTAGCATATTATAATTAGCATATGCTATATAGCCGATCGTAATATGCGCATTATAATATGCGCGCGCGCTAGCATGCATGCTAATATGCTACGATCGCGTAGCATGCTATAGCTACGATTAATCGCGATTATAATCGCGGCTAATCGATCGGCCGGCTAGCATATTATAGCCGTATACGCGATTAGCGCGCATCGATTAATCGCGATTAATATGCCGTAATTATACGATCGGCGCTAATGCTAGCATATTACGCGATGCCGTAGCGCGCATATATCGCGTATAATGCCGTAATGCGCCGATCGTAATATCGTACGATCGTACGATATTACGGCATTATAATGCCGTACGCGGCCGGCATATCGTATAATATCGTAGCCGATTAATGCATTACGATATGCCGTAATTATAGCTACGGCCGATATCGGCGCATCGGCTAATATGCGCATGCGCCGTAATTATAATCGCGTAATATGCATGCCGGCCGTAGCATCGATCGTACGCGGCATGCGCATGCTACGCGCGGCCGTAGCATCGTAGCGCATCGATTAATGCATTAATGCATATATCGCGTATAATCGATGCGCTAGCCGTACGATCGGCATTACGTACGTAATGCATGCCGCGATATGCGCGCTACGCGCGTAATTACGGCCGCGTATACGCGCGATTATAATCGCGCGTATAATATCGCGTATAATCGATCGGCTAATTACGATCGATGCATGCATCGATTACGTAGCATTATAATCGCGTAATTACGGCGCCGATCGATGCCGCGATGCCGTAATATTAGCGCCGTAATTACGATGCGCCGATTACGGCCGATTACGTAGCATTAATTACGTACGGCCGTAGCATCGATCGCGCGATATATCGTATATATATACGTATAATCGGCTATAATATTACGTAGCCGTAATGCTACGCGCGCGTAATTATATAATATATGCGCTAGCATTACGATGCATATGCATGCCGCGTATAATTAATATGCTATAATATTACGCGTAATATGCATGCGCTAATTAGCATCGTACGTACGCGTACGTAGCGCGCTATAGCGCCGATATATGCTATAATATGCCGATATCGCGATGCGCATCGATCGCGTATATAATCGCGATATGCATGCGCATCGTACGGCTATATAATCGATCGGCATCGATGCCGATCGTAATCGTAATTATAATCGCGTAATTATACGCGATGCATTAATTACGTAGCTAATATTACGCGGCTAATATTAATCGGCGCTAGCCGTAATATCGATATGCGCGCCGTAGCATCGTACGTACGCGTACGCGATTAGCGCGCGCGCGCCGATTATAGCCGATATGCATCGATCGCGTATATACGCGTAATATCGATTACGTACGCGTATAATGCTAATGCTATACGATTAATCGTATAGCCGTAATCGATTAATGCATTAATGCATATATATGCGCGCGCTATACGCGTACGCGATATGCATGCCGATCGCGTATAATCGATGCATTAATTAGCTAATTAGCATCGATGCTAGCCGATGCATGCGCATTAATGCGCGCCGTAATTAGCGCGCGCATCGGCGCTACGATTACGCGTAATATGCTATAATATTAATATGCATGCTAATCGCGTACGCGTACGCGGCTAGCGCCGTAATTAGCGCCGCGGCATTACGATATTAGCGCTACGGCATGCGCTAGCCGTAATTAATTACGGCCGATTACGTAGCCGCGATGCCGTAATGCATGCTAATGCATGCGCGCCGCGATTAGCGCGCATGCCGTAATGCATGCTAATGCTAATATGCGCATCGATGCCGCGTATATACGCGGCATCGCGATCGCGTATAATCGATCGTACGGCATGCATTATAGCCGGCATTAATTAGCGCTACGGCGCATTAGCTATACGATATGCTAGCGCGCTAATTAATTAATATGCGCCGATGCCGGCATATCGTATAGCCGGCGCATCGATCGCGCGATATTATAATCGCGTAATATTAGCGCGCCGGCTACGTACGCGCGATGCGCATATTATAGCCGCGGCGCATCGATCGCGTATAATCGATGCCGATGCCGGCCGTACGCGATGCCGTAGCCGGCATATCGATGCGCTAGCATTATAATCGCGTAATATCGTAGCTAATTAATTAATTACGGCCGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAGCTAATATTACGCGGCTAATATCGATTAGCGCATTAGCTACGATTAATCGGCGCTAGCCGTAGCTAATATTACGCGCGATCGGCGCATATGCGCGCCGATCGCGATTAGCATCGGCGCTAGCATGCCGTACGTACGCGTAATTAGCCGGCCGATTATACGATGCCGCGATATGCTATAATATCGTAGCCGTAGCTACGCGCGGCATCGCGTATACGCGCGCGTAGCTAAT ``` ### Demo The snippet below includes some demonstration code. ``` let e = s=>(n=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>C[c]=('00'+(n++).toString(2)).slice(-i-3)),n*=2)),s=s.replace(/./g,c=>C[c]||(524160|c.charCodeAt()).toString(2)),s.length&1&&(s+=0),s.replace(/../g,c=>'ATCG'[c=+`0b${c}`]+'TAGC'[c])) let d = s=>(n=N=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>(C[j=i+3]=(C[j]||{}))[n++]=c),n*=2)),s=s.replace(/../g,c=>''+((x='ATCG'.search(c[0]))>>1)+(x&1)),eval(`for(r='';N<s.length-1;){for(i=j=0;!(f=C[j]&&C[j][i])&&j++<19;i+=+s[N++]+i);r+=f||String.fromCharCode(i&127)}`)) function encode() { var txt, dna; if(txt = document.getElementsByTagName('textarea')[0].value) { dna = e(txt); document.getElementsByTagName('textarea')[0].value = ''; document.getElementsByTagName('textarea')[1].value = dna; document.getElementsByTagName('div')[0].innerHTML = 'DNA length: ' + dna.length + ' (' + (dna.length / txt.length).toFixed(2) + ' nucleotides per character)'; } } function decode() { var txt, dna; if(dna = document.getElementsByTagName('textarea')[1].value) { txt = d(dna); document.getElementsByTagName('textarea')[0].value = txt; document.getElementsByTagName('textarea')[1].value = ''; document.getElementsByTagName('div')[0].innerHTML = 'Text length: ' + txt.length; } } ``` ``` textarea {font-size:10px;font-family:Arial;width:400px;height:70px} ``` ``` <textarea>I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower. At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts.</textarea><br> <button onclick="encode()">Text -> DNA</button><button onclick="decode()">DNA -> Text</button><br><textarea></textarea><div></div> ``` [Answer] ## JavaScript (ES6), ~~10216~~ 8520 + ~~85~~ 129 + ~~97~~ 147 = ~~10398~~ 8796 ### Encoder: ``` s=>s.replace(/..?.?/g,b=>"9876543210".replace(/./g,b=>'ACGT'[b=r>>b*2&3]+'TGCA'[b],r=0,[...b].map(c=>r=r*96+127-c.charCodeAt()))) ``` ### Decoder: ``` s=>s.replace(/../g,c=>'ACGT'.search(c[0])).replace(/.{10}/g,b=>String.fromCharCode(...[9216,96,1].map(n=>parseInt(b,4)/n%96^127).filter(n=>n^127))) ``` Works by packing up to three printable ASCII characters into 20 nucleotides, thus saving 16.6% on average. The characters are mapped from 95 to 1 to shorten the decoder, as it can then use `^127` to floor the division and restore the character code. Excess nucleotides get decoded into 127 which needs to be skipped. The encoder could be 1 byte shorter and the decoder 7 bytes shorter in Firefox 30-57 (note that these are incompatible with the above): ``` s=>s.replace(/..?.?/g,b=>"9876543210".replace(/./g,b=>'ACGT'[b=r>>b*2&3]+'TGCA'[b],r=0,[...b].map(c=>r=r*96+c.charCodeAt()-31))) s=>s.replace(/../g,c=>'ACGT'.search(c[0])).replace(/.{10}/g,b=>String.fromCharCode(...(for(n of[9216,96,1])if(n=parseInt(b,4)/n%96|0)n+31))) ``` [Answer] # Python 3, 15324 + 122 + 211 = 15657 bytes This is a very wasteful method which converts each character to a three digit number and, for each of those three digits, assigns it a two unit code. ## Encoder, 122 bytes ``` u='AAAATTTCCGTTTTAAAGGCATCGTCGCGGTAGCAGCGCC' o='' for i in o.join("%03d"%ord(i)for i in input()):o+=u[int(i)::10] print(o) ``` *See the encoded version of the example text [**here**](http://pastebin.com/raw/6czXxnLN)* ## Decoder, 211 bytes ``` u=['ATAT','ATTA','ATCG','ATGC','TATA','TACG','TAGC','CGCG','CGGC','GCGC'] l=input() I=u.index s='' for j in[l[i:i+12]for i in range(0,len(l),12)]:s+=chr(int(str(I(j[:4]))+str(I(j[4:8]))+str(I(j[-4:])))) print(s) ``` [Answer] # Ruby, 97 + 96 + 5152 = 5345 bytes Encoder program requires the flags `-nrzlib`. ``` Zlib::Deflate.deflate($_).bytes{|b|('%04s'%b.to_s(4)).chars{|c|$><<"ATTACGGC"[2*c.to_i,2]}} ``` Decoder program requires the flags `-przlib`. ``` gsub(/../){"ATTACGGC".index($&)/2} gsub(/..../){$&.to_i(4).chr} $_=Zlib::Inflate.inflate$_ ``` [Answer] # Python 2, 12770 + 204 + 271 = 13245 **Encoder:** ``` from itertools import* D=[''.join(p)for p in permutations('AT TA CG GC'.split())] e=lambda x:''.join('AT'+D[c-32]if c<56else'TA'+D[c-56]if c<80else'CG'+D[c-80]if c<104else'GC'+D[c-104]for c in map(ord,x)) ``` **Decoder:** ``` from itertools import* D=[''.join(p)for p in permutations('AT TA CG GC'.split())] n=D.index d=lambda x:''.join(chr(n(c[2:])+32)if'AT'==c[:2]else chr(n(c[2:])+56)if'TA'==c[:2]else chr(n(c[2:])+80)if'CG'==c[:2]else chr(n(c[2:])+104)for c in map(''.join,zip(*[iter(x)]*10))) ``` Every character is encoded to a 10-character (5 unit) string, with the first unit indicating what quarter of the printable character string it belongs to, and the last four indicating what character in that quarter is represented. [Try it here.](https://repl.it/DCmw/3) [Answer] # PHP, 5106 + 297 + 161 = 5564 encoder ``` $t=str_replace("=","",base64_encode((gzdeflate($_GET["e"]))));$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";$e=["AT","TA","CG","GC"];$n="";foreach(str_split($t)as$b){$p=str_pad(base_convert(strpos($c,$b),10,4),3,"0",STR_PAD_LEFT);$n.=$e[$p[0]].$e[$p[1]].$e[$p[2]];}echo $n; ``` decoder ``` $e=["AT"=>0,"TA"=>1,"CG"=>2,"GC"=>3];$a=str_split(strtr($_GET["d"],$e),3);$o="";foreach($a as $v)$o.=$c[base_convert($v,4,10)];echo gzinflate(base64_decode($o)); ``` [Answer] # Node.js (5.6.0), 5104 + 125 + 122 = 5351 I was originally working in JavaScript, but Node.js provides compression much more easily. Thanks Neil for helping trim out 5 bytes on the encoder! **Encoder (125 bytes):** ``` s=>[...require('zlib').deflateRawSync(s)].map(a=>('000'+a.toString(4)).slice(-4).replace(/./g,b=>'ATCG'[b]+'TAGC'[b])).join`` ``` **Decoder (122 bytes):** ``` s=>require('zlib').inflateRawSync(Buffer(s.replace(/../g,a=>'ATCG'.search(a[0])).match(/..../g).map(a=>parseInt(a,4))))+'' ``` **DNA Sequence (5104 bytes):** ``` TATATATATATATAATGCATCGTACGATGCCGGCTACGGCATGCATATATATGCATGCGCGCTAATTATATATACGATCGATCGGCCGTAGCATGCATATCGTAGCGCATCGATATATTACGTAGCTAGCATATGCCGCGATATCGTATAGCCGCGATCGCGGCCGTAATATGCGCGCTAATATCGGCATGCTACGATCGATGCATGCCGGCATTAATTACGCGTATACGTATAGCTAATTAATTATAATCGCGCGATTAGCCGGCGCGCGCTAGCGCTAATTAGCGCCGCGTATATAGCCGATCGTATACGTAATCGGCATTAATATCGATCGTAGCATCGGCTATACGGCTAATCGATGCGCCGTATAATTAATTATAATGCCGGCCGATATGCATGCATATTATACGGCCGCGCGTATAATGCATCGATTAGCCGTACGCGTAATTAGCTATACGTAATCGTACGTAGCCGCGTATACGTAATATATCGCGTAATTATAATCGATCGGCTACGCGCGGCGCCGATATGCTAGCATCGATCGTAATATGCTAATCGTATACGTATATACGTACGCGATCGGCATGCATGCATCGCGGCTATACGTACGGCCGATATGCATTAGCATATCGTAGCTAATCGATGCGCCGGCGCATATCGATCGATGCGCTAATATGCCGATTAATGCCGTAGCTATACGCGATCGTATAATGCGCGCATCGATGCATGCCGTAATTACGCGGCTACGATTACGCGTACGATGCTATAGCTACGCGTAATTAATTAGCTAGCATCGGCCGATTACGGCCGCGGCTACGTAGCATGCTAATCGCGTAATTATAGCGCCGGCGCATGCTAGCATGCTAATCGCGATGCTAATTAATCGTAATTACGCGCGCGCGTAATCGGCCGCGATGCCGCGTATAATTACGTAATGCCGTATAGCTAATCGATGCCGCGTACGCGGCGCTACGATGCCGCGATATCGCGTACGATCGTAGCTAGCATATTAATATTATAGCCGGCCGCGTAGCATGCATCGCGATTATATACGCGCGGCGCATGCTATAATTAATTAATGCTAATTAATCGCGATGCCGCGCGGCCGATTACGCGCGTAGCCGTATACGTAGCATCGGCGCATCGGCCGCGTAGCTATAATGCGCCGGCTAATCGGCTACGGCATATTAATGCCGCGATCGATCGTACGGCGCTATAATGCCGGCCGCGTAGCCGCGTATAATTAATGCCGATTAATCGCGGCGCTATATAATATATTATAGCGCGCATTATATAGCGCCGATGCTAGCGCTATACGGCGCTACGTAATTATAATATTATATAGCATGCTAGCCGCGATTATAGCATCGATGCTAATGCTACGCGCGCGTACGCGGCTACGATTAATTAGCTAATCGATATATGCTACGATTATATACGGCCGTAATTACGCGCGTAGCCGCGTAATGCCGTAGCATATCGTACGATATATTATACGGCGCTAATTACGCGATCGCGCGATTACGATCGTAGCATTAGCCGTAATTAATATATTATAGCATTAGCATTACGCGATCGCGGCATCGCGCGTAATGCTATAGCATCGCGGCTATAGCCGTAGCTATATAATGCATGCCGGCGCTAGCTAGCGCATATATTACGGCATATGCATTAGCGCATGCCGATATGCTACGATATCGGCTAGCCGATCGTATACGCGATCGGCCGCGTATAATCGCGCGGCGCTACGTATAGCTACGCGCGTAATTATAGCGCCGGCATTACGCGATATATGCCGTAGCATGCCGGCCGCGATTAGCCGCGTAATATATATTACGCGTAGCTAGCTAATTACGGCTACGGCTATAGCCGGCCGATTATAATTAATATTACGGCCGCGGCTATAGCATATATATGCGCATGCATTACGATTATATAGCATGCATATATCGATATCGTAATCGATTATAATATTATACGATCGCGCGATTACGATTATATACGTATAGCATATTAGCTACGTATAGCATTATAGCATATATGCTAGCTAGCCGGCTAATTAATATATGCCGCGATATATATGCGCATTAGCATGCCGATCGCGTAGCGCATCGATTAGCATATCGGCATGCGCGCCGTAATGCTAATGCTATATAATCGCGCGGCGCGCCGGCCGGCGCCGGCATATGCATATATATGCCGGCATGCATGCCGATTATATAGCGCGCCGCGTATATAGCCGCGATGCCGGCATTAGCATCGGCATCGCGGCTAGCGCATCGATCGTACGTACGTATAATTAGCATATCGCGCGCGGCATGCCGCGATTACGTAGCTAGCATTAATATATATCGATTAGCGCATGCTAATATATGCCGATATATATATTATAGCCGATCGGCGCATTATAGCCGATTAATTAATCGCGATTACGTACGGCATTATATACGTATACGCGCGTATAGCGCATATATTAATATCGATATGCGCGCATTATATATAGCCGATTACGTAATGCCGGCGCCGCGATGCATTAATCGATGCTAATATATTATACGTAATATCGGCTACGCGTATAGCATATATTACGCGATTACGATCGGCGCGCGCGCATGCTAGCATATCGATGCGCGCCGTAGCCGATCGCGCGGCATTAGCATGCGCTATAATCGATATATATTAGCCGATCGTATACGGCTACGCGCGTAATGCATTAGCCGTAGCATGCCGATTATAGCATATCGCGGCGCATATCGCGGCTACGGCATTAATCGATTATAATCGATGCATTAGCGCCGTAATGCCGATCGATTAGCATCGCGGCTATACGATCGGCTATAGCATTAATATATATTATACGCGGCATATATTAGCGCATTAGCTACGTAATATGCGCCGATTATACGGCCGGCATGCGCTACGGCATATTAGCCGCGTAATCGTACGCGATATTACGCGCGTAATGCCGTAGCGCATCGGCATATATCGCGATGCTACGTAATGCATGCATGCTAATCGATGCCGCGATCGATGCGCTAGCATCGTATAATATCGGCTAATCGTATACGTATATATAGCGCGCTATACGTAATGCCGGCTATATACGGCCGGCGCATGCGCATATGCATCGGCTAATTACGCGATCGTACGATCGATATATGCTACGGCGCGCATATCGGCTAGCCGCGCGCGGCCGGCTAATGCCGCGCGATATCGGCGCTATACGGCCGTACGATGCCGCGCGATATCGATGCTATAATTACGCGTAATCGATATGCGCTAGCGCCGATCGTATAGCTACGTAGCGCATTACGGCATGCTACGCGGCATGCATTAATCGGCCGATCGGCGCCGTAGCTACGATATCGTACGGCGCCGGCGCATTAGCTAGCGCGCGCGCCGCGGCATGCTATAATATTACGTACGCGTACGTAATATTAGCATGCATTAATTAGCCGGCATTATAGCTACGCGTACGCGATGCATTATACGTAGCGCTAGCATCGCGCGCGCGTATATAATGCCGCGTATACGATTAGCTATAGCCGGCCGCGCGGCTAGCATGCCGATCGATGCTAATCGGCCGTAATTACGATATTATATATATATATAGCTAGCGCATGCCGTACGGCCGTACGGCATATATTAATTAATTATAGCGCTAGCTACGATTATAGCTATATAGCTACGTAATCGCGGCATCGTAATCGGCGCTAGCCGCGATGCTAGCCGATCGCGGCCGGCCGCGTAATATGCCGGCGCCGTAATGCCGATCGTATATACGGCATCGCGGCCGCGATGCATGCCGATATCGTACGCGATATCGCGGCTATAGCCGATATCGTATACGCGTAATGCGCATGCTACGATATGCCGCGCGTATATAGCCGATCGGCCGCGTAATATTATAATCGGCATGCATATGCGCCGCGCGTACGGCGCTAATATCGCGCGATTAATTAATATATATTAGCATCGCGATGCGCATTATAATGCTACGCGGCGCCGGCGCCGATCGTATATAATGCCGGCCGCGATATATTAGCTATACGCGCGCGCGGCGCGCTACGCGTATAGCGCGCATATCGATATTAGCATGCTAATCGTAGCATGCATATCGTATACGCGCGATGCGCCGCGATGCATCGGCGCGCGCATGCCGGCGCGCGCCGCGCGGCATTATACGTAATCGTAGCGCGCGCCGATATGCTAATTAGCGCCGCGTAGCATGCTACGGCCGCGGCCGGCCGGCGCGCCGCGGCGCATATCGCGGCATCGCGGCTAATATCGCGATGCCGCGCGGCGCCGATCGTAGCTAGCTAGCGCGCATCGATATATATGCGCGCATGCCGCGTAGCTAGCGCATCGTAATTATAGCATCGCGCGCGGCATCGCGGCGCGCGCTAATTACGTAGCGCTACGCGATTACGCGATTAATGCGCGCCGGCATCGGCATTAGCGCATGCATTATATATATACGCGCGTACGGCGCTACGATATCGCGGCTATAATATGCTAGCGCCGCGATATATCGGCGCATCGTAATATGCGCTAATATATTAGCGCTAATATGCATCGGCATCGATCGGCTACGTATAATATGCGCGCGCATATATCGATATTAGCCGCGTACGTATACGTACGTATATAATGCTAATGCGCATTATAGCCGATTACGTACGATATGCGCGCATTAATCGTATATAGCTATACGATCGCGGCTATACGATATGCTAGCCGTATAGCGCTAGCATATATTAATATCGGCATATGCTAGCGCCGGCCGCGGCTATATACGGCATGCGCGCTACGGCGCTACGCGCGGCGCGCCGTATAATTATACGCGTAGCCGGCGCATATATCGGCCGTAGCCGGCATATGCGCATCGGCGCTAGCTATAGCTAATGCGCTAGCTACGTATACGTAGCCGTAATGCGCCGATGCGCATTAGCATGCTAGCCGCGCGTATACGTACGTATACGATCGCGCGGCGCTATACGCGGCGCCGTACGATGCGCGCCGATATGCATATCGATATATCGGCATGCGCTATACGTAGCATGCATGCATGCTATACGTACGATGCGCGCGCGCGCATATATTA ``` ]
[Question] [ ## Challenge Write the shortest program P such that * P takes any positive integer n as input, and outputs a program string P1 * executing P1 (with no input) outputs a program string P2, * executing P2 (with no input) outputs a program string P3, * ... * executing Pn (with no input) outputs exactly "Hello!" (without the quotes). Schematically:                 **P(n) → P1 → P2 → ... → Pn → Hello!** ## Criteria * I/O is via stdin/stdout. * Program length is measured in bytes. * Programs consist only of ASCII printable characters. * There must be no duplicates among the programs P, P1,...,Pn. EDIT: Programs P, P1,...,Pn are meant to be source code, and "executing the program" refers to whatever processing produces the output (i.e., interpretation, compilation & execution, etc.). [Answer] ### Golfscript ~~39~~ 14 ``` ~'Hello!'{`}@* ``` **Example:** Assuming that **n=4** and our program is **P**, these are the steps: 1. [Run **P** with parameter **4**.](http://golfscript.apphb.com/?c=Oyc0JwoKfidIZWxsbyEne2B9QCo%3D&run=true) The output is `"\"\\\"\\\\\\\"Hello!\\\\\\\"\\\"\""` (**P1**) 2. [Running **P1**](http://golfscript.apphb.com/?c=IlwiXFxcIlxcXFxcXFwiSGVsbG8hXFxcXFxcXCJcXFwiXCIi&run=true) outputs `"\"\\\"Hello!\\\"\""` (**P2**) 3. [Running **P2**](http://golfscript.apphb.com/?c=IlwiXFxcIkhlbGxvIVxcXCJcIiI%3D&run=true) outputs `"\"Hello!\""` (**P3**) 4. [Running **P3**](http://golfscript.apphb.com/?c=IlwiSGVsbG8hXCIi&run=true) outputs `"Hello!"`(**P4**) 5. Running **P4** outputs `Hello!`. If you don't trust me, follow [this link](http://golfscript.apphb.com/?c=IkhlbGxvISI%3D&run=true) ☺. [Answer] ## JavaScript, 58 chars ``` function $(_){alert(_?$+'$('+--_+')':'Hello!')}$(prompt()) ``` [Answer] ## Perl (~~45~~ 36) ``` say"say q("x($m=<>),"Hello!",")"x$m ``` Run with `perl -M5.010` to use `say`. For `n=1`, outputs `say q(Hello!)` For `n=2`, outputs `say q(say q(Hello!))` For `n=3`, outputs `say q(say q(say q(Hello!)))` and so on. [Answer] ### Python3, 66 ``` r="print(%r)";e=eval;n=e(input())+1;e(e("(r%"*n+"'Hello!'"+")"*n)) ``` [Answer] ### Common Lisp, 68 characters ``` (do((n(read)(1- n))(s'(princ"Hello!")`(print',s)))((= 0 n)(eval s))) ``` ``` (do ((n (read) (1- n)) (s '(princ "Hello!") `(print ',s))) ((= 0 n) (eval s))) ``` The only non-straightforward thing: it generates one more level of program than needed and evaluates it, because `eval` is one character shorter than `print`. [Answer] # Common Lisp: 65 ``` #1=(SETF N(READ)(CADDR'#1#)(1- N)W(PRINT(IF(= N 0)"Hello!"'#1#))) ``` This version is smaller than the existing CL-answer. In case your Lisp croaks with a stackoverflow, then you have to use this, 81 bytes: ``` #1=(SETF N(READ)*PRINT-CIRCLE* T(CADDR'#1#)(1- N)W(PRINT(IF(= N 0)"Hello!"'#1#))) ``` I know I'm late to the party, and I'm sure this could still be optimized. Demonstration (careful, some online REPLs don't work correctly): ``` * #1=(SETF N(READ)*PRINT-CIRCLE* T(CADDR'#1#)(1- N)W(PRINT(IF(= N 0)"Hello!"'#1#))) 2 #1=(SETF N 1 *PRINT-CIRCLE* T (CADDR '#1#) (1- N) W (PRINT (IF (= N 0) "Hello!" '#1#))) #1=(SETF N 1 *PRINT-CIRCLE* T (CADDR '#1#) (1- N) W (PRINT (IF (= N 0) "Hello!" '#1#))) * (eval *) #1=(SETF N 0 *PRINT-CIRCLE* T (CADDR '#1#) (1- N) W (PRINT (IF (= N 0) "Hello!" '#1#))) #1=(SETF N 0 *PRINT-CIRCLE* T (CADDR '#1#) (1- N) W (PRINT (IF (= N 0) "Hello!" '#1#))) * (eval *) "Hello!" "Hello!" * ``` Note that: * Tested using SBCL 1.2.11.debian * There are lots of warnings because I'm doing things that are seriously not supposed to be done. Thankfully, all warnings are printed with a semi-colon, so they would be treated as comments anyway. * Duplication is because one is the return value and one actual output. If the return value would also count, then it simplifies to 58 bytes: `#1=(SETF N(READ)(CADDR'#1#)(1- N)W(IF(= N 0)"Hello!"'#1#))` * I still know I'm late to the party [Answer] ### Python 2.7, 57 ``` print reduce(lambda x,y:y+`x`,input()*["print"],"Hello!") ``` [Answer] ## Haskell, 62 ``` main=interact$(iterate(("main=putStr"++).show)"Hello!"!!).read ``` [Answer] Bash, 47 or 12 (if I use golfbash) Code: ``` read x;for((;x>=0;x--)){ O+=" echo";};$O Hello! ``` golfbash code: ``` R;n e Hello! ``` Previous code (49): ``` read x;E=echo;eval \"\${E[0]\"{0..$x}\"}\" Hello! ``` Use: Make program P ``` $ echo '<paste code here>' > P $ chmod +x P ``` Example Make P1: ``` $> echo 4 | ./P > echo echo echo echo Hello! ``` Make P2: ``` $> echo 4 | ./P | bash echo echo echo Hello! ``` Make P3: ``` $ echo 4 | ./P | bash | bash echo echo Hello! ``` Make P4: ``` $ echo 4 | ./P | bash | bash | bash echo Hello! ``` Run P4: ``` $ echo 4 |./P | bash | bash | bash | bash Hello! ``` Say that I make a new general purpose language called golfbash - at bit like golfscript - that has some useful commands like these: ``` R which reads stdin and places result into variable $REPLY. n $1 $2 which echo's $1 $REPLY times followed by $2. e which echo's all parameters to stdout. ``` Then I could write this: ``` R;n e Hello! ``` This would be legal, would't it? [Answer] **F#, 182** ``` let say msg = sprintf "%s" msg let gen num = let rec g n a = match n with | i when i > 0 -> g (i-1) ("say \"" + a + "\"") | _ -> say a g num "Hello!" ``` [Answer] # J - 31 char Keep in mind that J uses Pascal-style strings: `'It''s too easy!'` ``` 'Hello!'(],,)''''#~<:2^".1!:1]1 ``` Explained: * `".1!:1]1` - Read in a line from stdin and convert it to a number. * `<:2^` - Take 2 to the power of this number, and decrement. * `''''#~` - Make a string with that many copies of the single quote character. * `'Hello!'(],,)` - Append these quotes to the front and back of `Hello!`. Usage: ``` 'Hello!'(],,)''''#~<:2^".1!:1]1 NB. let's try 3 3 '''''''Hello!''''''' '''''''Hello!''''''' NB. P1 '''Hello!''' '''Hello!''' NB. P2 'Hello!' 'Hello!' NB. and P3 prints Hello! Hello! ``` [Answer] ## Python 2.7: 75 ``` def h(n): return "Hello"if n<1 else'print %s' % `h(n-1)` print h(input()) ``` First time golfing, not sure if I'm doing it right ;p [Answer] # Clojure, 36 bytes ``` (str(apply str(repeat 5\'))"Hello!") ``` Symbol ``` 'something ``` evaluates to ``` something ``` Build up a symbol with 5 single quotes and run the result until no quotes left. ]
[Question] [ The Lost Numbers are 4, 8, 15, 16, 23, 42. Your goal is to create an expression to output them all. Your allowed characters are 0123456789, ^+-\*/, (), % for modulo and n as the single variable allowed. Modified PEMDAS `()^*/%+-` is the precedence and / is normal division (3/2 = 1.5). 0^0 = 1 although division by 0 is undefined. Create the shortest expression (in characters) such that for n = 0..5 (or 1..6 for 1-indexing) the nth Lost Number will be the result of the expression. Shortest expression wins. [Answer] # 20 characters Assuming that the precedence of the operators is similar to JS. The input is expected to be 1-indexed. ``` n*4+16%n*3+6*0^(6-n) ``` [Try it online!](https://tio.run/##DcxBCsMgEEDRvaeYTYmj0VRa3LS5SQkRa0OKjEFLNiFnt64@b/O/bnfF53X7KUrvUAuMMFcSd2nshcRNWnGduFWEddYlrj5w04MyqHPYomscXtOw9NAJ0SFjn5Q5tYd5AMFzBNsqJcLBAHyikmLQMS087C7ygsjO@gc "JavaScript (Node.js) – Try It Online") (interpreted in JS ES7) ### Breakdown ``` n | 1 | 2 | 3 | 4 | 5 | 6 | (x4) 16 % n | 0 | 0 | 1 | 0 | 1 | 4 | (x3) 0 ^ (6 - n) | 0 | 0 | 0 | 0 | 0 | 1 | (x6) -------------+----+----+----+----+----+----+------ | 4 | 8 | 15 | 16 | 23 | 42 | ``` [Answer] # ~~16~~ 15 characters `6704196%(n*8+3)` One-indexed. A simple application of a generalisation of the Chinese Remainder Theorem, with the formula n\*8+3 chosen to make it work (that is, where moduli have a common factor, the corresponding values' difference is also divisible by that factor), as well as to get a shorter number on the left. Previously: `485559068%(n+41)`, zero-indexed [Answer] # 15 bytes ``` n*4+703%n^3%7*3 ``` [Try it online!](https://tio.run/##yyrNyUz8n5ZfpJBna2hlxlVQlJlXkpOn8T9Py0Tb3MBYNS/OWNVcy/i/JldqXsp/AA "Julia 0.4 – Try It Online") Based off @Arnauld's answer. The idea was to look for a magic formula `A%n^B%C` that maps (1, 2, 3, 4, 5, 6) to (0, 0, 1, 0, 1, 6) to combine the last two terms in Arnauld's formula into one: ``` n | 1 | 2 | 3 | 4 | 5 | 6 | (x4) 703%n^3%7 | 0 | 0 | 1 | 0 | 1 | 6 | (x3) -------------+----+----+----+----+----+----+------ | 4 | 8 | 15 | 16 | 23 | 42 | ``` ]
[Question] [ ## Background In C, there is a function to help parse command-line arguments: `getopt`. Getopt takes the argument count (`argc`), the argument list (`argv`), and a string representing the options the program should take (**`optstring`**). The option string (`optstring`) is a series of option characters each followed by one colon (for an option requiring an argument), two colons (for an option with an optional argument), or zero colons (for an option without an argument). For example: one might use the following option string for their company's new widget. ``` "v::x:hy:S:G::dns:f::" ``` But that looks horrible! The options are all mixed together! This option string would look much better if it were sorted: ``` "f::G::v::S:s:x:y:dhn" ``` ## Specifications * The input will be a string matching the regular expression `([A-Za-z]:{0,2})+` * You should take input as a string or list of characters. * You should output the string sorted by the method detailed below. * You do not need to handle empty input. * You do not need to handle input with repeated options of the same type (`"aa"` is not valid, but `"aa:a::"` is valid). ### Sorting Method In the sorted option string: * The characters followed by two colons come first, sorted alphabetically, with uppercase letters before their respective lowercase letters (i.e. "aBb", not "Bab"). * Then are the characters with one colon, sorted alphabetically, with uppercase letters before their respective lowercase letters. * Last are the characters with no colon, sorted alphabetically, with uppercase letters before their respective lowercase letters. ## Rules * [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes in each language wins. ## Examples ``` # "input" => "output" "v::x:hy:S:G::dns:f::" => "f::G::v::S:s:x:y:dhn" "aa:a::" => "a::a:a" "B:" => "B:" "Confusio:n::" => "n::o:Cfinosu" "Confusio:n:" => "n:o:Cfinosu" "m:qW:X:xc:vViI" => "c:m:W:X:IiqVvx" "V:omo:V" => "o:V:moV" "agg:ra:va::ting::" => "a::g::a:g:aginrtv" "input" => "inptu" ``` [Long test case](https://pastebin.com/yuq8F2bh) (312 characters) Invaid Inputs (you don't have to handle): ``` "gg" (duplicated option) "" (empty string) ":w:" (first colon isn't after a character) "x:y:0:fhn" ('0' is not alphabetic) "A:::" (3 colons is invalid) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ΣÖom_↔Oġλ¬√ ``` [Try it online!](https://tio.run/##yygtzv6vkPuoqfHQtv/nFh@elp8b/6htiv@Rhed2H1rzqGPW////y6ysKqwyKq2CrdytrFLyiq3SrKy4EhOtEoGUkxWXc35eWmlxZr5VnhUKhyvXqjDcKsKqItmqLCzTkyvMKj833yqMKzE93aoo0aoMqL0kMy8dqCkzr6C0BAA "Husk – Try It Online") ## Explanation ``` ΣÖom_↔Oġλ¬√ Implicit input, say "kH::r:R:Hk:" ġ Split between characters for which this gives a falsy result: λ Take two arguments, ignore the first. √ Is the second argument a letter? ¬ Negate. Now we have the options: ["k","H::","r:","R:","H","k:"] O Sort: ["H","H::","R:","k","k:","r:"] Ö Sort by ↔ reversing and om_ converting everything to lowercase: ["H::","k:","R:","r:","H","k"] Σ Concatenate: H::k:R:r:Hk ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 47 bytes ``` . $&$& T01`L`l`.. O^`\w.:* .(.) $1 O$^`\w:* $.& ``` [Try it online!](https://tio.run/##VY49C8IwFEX39ztiqA4Pu95RhyIIHZToIJKgNgZsov2I9dfHODpdzoEDt7sNzps0KyqdmIQUkvbLUm/1QzNTfdanN2NBXPCcREm1@JksBMuUIjDh/sEOFXD1PRqAjIHJswKtg2/G3gV4/AG1eB1wxHRBVG5DCqENUGSsRWcQc55P2Rw5/xyHLw "Retina – Try It Online") The trickiest part was actually sorting the letters, because Retina's "sort-by" feature doesn't have a case-insensitive sort (so by default it sorts the upper case letters in front of *all* lower case letters). To work around this, I had to insert a lower-case copy of each character to do the sorting and then get rid of it again. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~17~~ 16 bytes ``` f".:*" ñ_iZw vÃq ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=ZiIuOioiIPFfaVp3IHbDcQ==&input=Im06cVc6WDp4Yzp2VmlJIg==) ### How it works Say the input string is `v:vg::G:G::o:`. The first part of the code, `f".:*"`, finds all matches of the regex `/.:*/g`, which matches a character followed by any number of colons. This splits the input into `[v:, v, g::, G:, G::, o:].` The `ñ` method on an array sorts each the array as if certain changes were applied, without actually applying them (like `sorted(array, key=<whatever>)` in Python). So we need to sort: * double-colons before everything else; * single-colons after double-colons, but before no-colons; * letters in their alphabetical order; and finally * uppercase letters before lowercase. `Z{ZiZéJ v}` is the shortest way I could find to do this: ``` Zw Reverse Z. v Convert to lowercase. Zi Insert this at the beginning of Z. ``` This is easiest to understand with some examples: ``` v: v g:: G: G:: o: Zw :v v ::g :G ::G :o v :v v ::g :g ::g :o Zi :vv: vv ::gg:: :gG: ::gG:: :oo: ``` The original values are then sorted lexicographically by these keys. The result is that `::gG::` is sorted to the front, then `::gg::`, and so on, giving us `[G::, g::, G:, o:, v:, v]`, which is then joined with `q` and outputted. [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ 90 bytes ``` lambda s:''.join(sorted(re.findall('.:*',s),key=lambda s:(-len(s),s.lower(),s))) import re ``` [Try it online!](https://tio.run/##VYy9DsIgGEX3PgUbYCqD4006OfgAri4YforSjwaw2qfHujRxuznn5M5rHROdmhtuLerpbjQr4Fw9UiBRUq7WiGyVC2R0jIIrHHhfZP@067D34hjtVsu@qJjeNottSSm7MM3bA8u2zTlQZU7wBfhgXHHFBTBU4AAuu92fE7lXCQn0z7X3yBqLBmog/5PtCw "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` n”:œṗ⁸ṢŒuÞṚLÞṚ ``` [Try it online!](https://tio.run/##y0rNyan8/z/vUcNcq6OTH@6c/qhxx8Odi45OKj087@HOWT5g8v///0q5VoXhVhFWFclWZWGZnkoA "Jelly – Try It Online") Full program. [Answer] ## JavaScript (ES6), 93 bytes ``` f= s=>s.match(/\w:*/g).sort((a,b)=>b.length-a.length||parseInt(a,36)-parseInt(b,36)||a>b).join`` ``` ``` <input oninput=o.textContent=this.value&&f(this.value)><pre id=o> ``` [Answer] # [Perl 5](https://www.perl.org/), 69 + 1 (`-n`) = 70 bytes ``` say sort{$b=~y///c<=>length$a||($"=lc$a)cmp lc$b||1-2*($"ne$a)}/.:*/g ``` [Try it online!](https://tio.run/##VYuxCsIwFEX3fIVIBhVqrNDlYh10EAcnobrG2sZA@1KbWCxWP92Y1emee@A0RVsl3lvZj6xp3Ytf0k8vhMhX6boqSLkbl8Mw4eO0yrmc5nUzCnAZhjhazoKmIti3mGMmlPcd8MStxxE74EoWJcCkhAyzAdsaKh9WGxD@DqtxP@GMZ44u03uWwdQGGZNKoZXoQu40qRBpah7uaxqnDVkfHZL5Il74iH4 "Perl 5 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 124 bytes ``` import Data.List import Data.Char s(c:x)|(l,r)<-span(==':')x=(-length l,toLower c,c:l):s r;s _=[] t(_,_,x)=x f=(t=<<).sort.s ``` [Try it online!](https://tio.run/##bZBbS8MwFMff@ykORTDBbh/guAg6UQbzaVAFkRFqL8E2mTlpzcDvPk872XwwD@fyz@9ckkbTR9m2h4Ppds4HuNdBz9eGQvJXWDbaJyQKjPJbtJmXixnttBVKXeKljErM2tLWoYE2C27tvkoPRVZgK5HAXxNs1etbEsQ222ZRqphUSgS1WMg58Yg5HUJJgdRrAnxEOiBGbPa4wUfEd0tYIaYZpOxY4NsNEhN7fG9sKrPfKq1RHzl2HJ9v7iaV7UlZOlv1ZBzaYwU7h8vKWEf9v9QR@ofp8PMZXzAWOORmNWIFdjhKK/OZD/FM5ug6h/mIsMPO5X92r2v0GgfePBhbn55Rjy@pUdfG@jCceWN3fRgZDgJvM8lvSTL@I0TQlkABI5vg1xYugBr3xfrVFaQwgxu2HE6iqCBKzqYOpgJOQampQ2hKy6RwHzKFsqVyTB5uV2uZTnTSaWN5Tqd3T1sQvS167/cw7iAnS4cf "Haskell – Try It Online") [Answer] # Bash, ~~232~~ 213 bytes ``` s(){ s=${1#?} c=${1%$s} o=${s%%[^:]*} s=${s#$o} o=$c$o;}; p()(s $1;l= g= p=$o d=$c;[[ $o ]]&&(while s $s;[[ $o ]];do (((x=${#o}-${#p},y=36#$d-36#$c,x?x:y?y:62#$c-62#$d)>0))&&g+=$o||l+=$o;done;echo `p $g`$p`p $l`)) ``` [try it online](https://tio.run/##VZBhb9MwEIa/51ecXLeyYdXYkPbhMq@CAVPFBNImBaRS1JCkjqXWzuI2JOry28u5pWh88T333qu7V/6V@nK/90LuwCu@uxhMesgCDLnvwRH54XD2E@ev@oPBD7g76Bl3cR9HlZDCA7@IVwq0gkpxBzlN49kMCOfz0Uj8Ls2qAHL5f2qcu0gI0dLGgevH9Fb9WafeXg14Pg5vdtZOWuwmHV5dUjcOby5v3kg5GunXdOX5eRUKLbJFXGSlg0UFXC94FepqIeX@QYmvn@HTu@m9jI4Z6iLNwUALRQgAYOi@OT//wXooCIsDkl4rLmiLkcQhcg0KeEG5qT/cYtwElTS@e5jxybxnUUgC19cfv3yAiDWILZYdPuIdYm49LhEZqBtgBCTR/BE9eTrMS8silqaYniwE1JH4/q9ANWK3zi633ji0Jx@Bw9ulsc5v/zec5i/Ha3z6ht@xzbBJzPToyHCNQZyap6RpyZSgWztMjlMCXLskpNMa6xQbSrYxVr8IqkNWjak2tt40ZDW22m6OY8INXaYf2f8B) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 152 bytes ``` s=>{var o="";for(var d=":::";d!="";){d=d.Substring(1);for(var c='@';c!=90;o+=s.IndexOf(c+d)>=0?c+d:"",s=s.Replace(c+d,""),c^=' ')if(c<97)c++;}return o;} ``` [Try it online!](https://tio.run/##XVBda8IwFH3Pr7j2xYY6cU/DW@PGBhvCxsYE3dMgJqkGauKStFPE396lVgYbeTjce764Ef5KWKcaUXLv4e1IdtWq1AJ84CFCbbWEF65NSuFI5gcf1Hb4WBkx8cFpsx5Ah1MoWOPZ9FhzB5YlSV5Yl7aDZAkiJrnstVt6lEwO59Wqs6XX9FcoWP@un4seG49ymzE/nBmp9q9FKjJJp2x0GxGTZOAj9a52JReqpQZJQgfik/WhT3UUT8Y3VGRZfnIqVM6AzU9NTr43ulSQBlep9hCAtlGbXRWAweWsB2u8LVUM5/JZG5XSPAp1AelFyCB2QZfbUv98S6eDOhuLzkFjwKl9TY24x80B5/iEKI3HApFwjjzCPZKYUFReWzT4ZyBb/FriB@4F1gs9Iwu0W4sLwtdrdBzraA/xF6Pp3Ed@AA "C# (.NET Core) – Try It Online") Ungolfed: ``` s => { var o = ""; for (var d = ":::"; d != "";) { d = d.Substring(1); for ( var c = '@'; c != 90; o += s.IndexOf(c + d) >= 0 ? c + d : "", s = s.Replace(c + d, ""), c ^= ' ' ) if (c < 97) c++; } return o; } ``` The basic idea is to iterate over all 156 possible options and check for their existence. If found, append to the output, and remove from the input. ]
[Question] [ ## The Challenge Write a program that takes an integer *N* as input, and outputs the stage of life or death that a tree is currently in. *N* will always be between 0 and 10. **The Stages of Life and Death** * **Life:** To draw a stage of life, simply draw a base of size *N*, consisting of `^` characters, then move up and substract 2 from *N*, if the result is greater than 0, and draw a line of `^` characters again, again with the size of the new *N*. Repeat while *N* is larger than 0. To finish off, place either a single `|` character if the startoff value of *N* is odd, or two `||` characters if it was even. Example: `N = 5` ``` ^ ^^^ ^^^^^ | ``` Note that if *N* = 0, only the stem will be drawn, without the leaves (`^`) on them. * **Death:** This is roughly the same as *Life*, except that the base is *10 - N*, you use `M` instead of `^` and you add 2 to *N* and redraw the lines with the same procedure as above, but this time you add 2 to *N* while it is smaller or equal to 10. Example: `N = 3` ``` M MMM MMMMM MMMMMMM | ``` ## The Goal Your program has to run in 2 different languages both have to take a input *N*. The first language has to output the **life** stage of a tree according to *N*, the second language has to output the **death** stage. ## Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes that meets all the requirements wins. * The code has to run in 2 different languages. Yes, Python 2 and Python 3 *are different languages*. * Standard loopholes are forbidden. * Trailing newlines or spaces are allowed. ## Test Cases Input: `N = 1` **First language (life):** ``` ^ | ``` **Second language (death):** ``` M MMM MMMMM MMMMMMM MMMMMMMMM | ``` --- Input: `N = 10` **First language (life):** ``` ^^ ^^^^ ^^^^^^ ^^^^^^^^ ^^^^^^^^^^ || ``` **Second language (death):** ``` || ``` --- **Good luck coding!** [Answer] # Dyalog APL / SOGL, ~~70~~ ~~65~~ ~~63~~ 62 bytes ``` 0000000: 7b0d 04eb c0fd 5832 5c49 e32a 2e4c ac20 {.....X2\I.*.L. 0000010: 4d2a 5b3a 836b 6b7d 01ea 500d 9b31 a90f M*[:.kk}..P..1.. 0000020: 7b0f c285 c8c7 b932 c00e f8b1 c70f 7db0 {......2......}. 0000030: 32c2 8531 9c85 80b2 b50f aa32 f97d 2..1.......2.} ``` ### Interpreted in [the classic Dyalog APL encoding](https://codegolf.meta.stackexchange.com/a/9429/59183): - life: (contains unprintables), expects `⎕IO←1` ``` {' ^|⎕X2I┤z.L?pMzÅÏÏ}ûP'[1+⍵{⍵,⍨⌽⍉(2|⍺)↓⍉⍵}↑2,⍨1/⍨¨⍳⌈⍵÷2]} ``` [TryAPL here!](http://tryapl.org/?a=f%20%u2190%20%7B%27%20%5E%7C%u2395X2%05I%u2524z.L%3FpMz%04%03%C5%CF%CF%FBP%27%5B1+%u2375%7B%u2375%2C%u2368%u233D%u2349%282%7C%u237A%29%u2193%u2349%u2375%7D%u21912%2C%u23681/%u2368%A8%u2373%u2308%u2375%F72%5D%7D%20%u22C4%20f%203&run) ``` {' ^|..'[1+⍵{⍵,⍨⌽⍉(2|⍺)↓⍉⍵}↑2,⍨1/⍨¨⍳⌈⍵÷2]} 1+ add 1 to every value ' ^|..'[ ....] index the array getten below into " ^|.." with SOGLs code never being indexed in ⍵{..}↑2,⍨1/⍨¨⍳⌈⍵÷2 1/⍨¨ replace each with that many 1s ⍳ the first ... numbers ⌈ ceiling of ⍵÷2 the right argument divided by 2 2,⍨ append 2 ↑ mix; convert to a 2D array, padding with zeroes ⍵{..} execute that function with the arguments ⍵ - my right argument and the result of above {⍵,⍨⌽⍉(2|⍺)↓⍉⍵} helper function ⍵,⍨ append the right arg to ⍉⍵ the right arg transposed ↓ without the first ... rows (2|⍺) remainder of left arg ÷ 2 ⌽⍉ transposed and reversed ``` ### Interpreted in [SOGLs encoding](https://github.com/dzaima/SOGL/blob/master/chartable.md) - death: ``` {∑⁴╝υ”X2\I┐*.Lκ M*[:≥kk}¹╚P∑Β1Ι»{»φ√ωΩΡ2υ«⌠ΝΩ»}μ2φ√1β√↓νΟ»ι2⌡} ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTdCJXUyMjExJXUyMDc0JXUyNTVEJXUwM0M1JXUyMDFEWDIlNUNJJXUyNTEwKi5MJXUwM0JBJTIwTSolNUIlM0EldTIyNjVrayU3RCVCOSV1MjU1QVAldTIyMTEldTAzOTIxJXUwMzk5JUJCJTdCJUJCJXUwM0M2JXUyMjFBJXUwM0M5JXUwM0E5JXUwM0ExMiV1MDNDNSVBQiV1MjMyMCV1MDM5RCV1MDNBOSVCQiU3RCV1MDNCQzIldTAzQzYldTIyMUExJXUwM0IyJXUyMjFBJXUyMTkzJXUwM0JEJXUwMzlGJUJCJXUwM0I5MiV1MjMyMSU3RA__,inputs=Mw__) Explanation: ``` {∑⁴╝υ”X push "{∑⁴╝υ" and pop it - noop 2\ push input divides by 2 I┐* get that many + 1 vertical bars .Lκ push 10-input M* get that many "M"s as a string [ } while ToS isn't falsy (here: isn't "") : duplicate the string ≥ put the duplicate at the stacks bottom kk remove the last 2 letters (does nothing when the string is empty) ¹ wrap everything in an array ╚ center horizontally P print that ... execute a bunch of random nonsense which luckily does nothing ``` This took way too long.. Golfing tips for the APL part are welcome, everything mostly should be applicable as long as it doesn't change anything before `ûP'` You can load the file (after reversing `xxd`) in [SOGL](https://dzaima.github.io/SOGLOnline/) by selecting the file in the `Browse...` dialog and then clicking `load SOGL codepage encoded file`. [Answer] # [Python 2](https://docs.python.org/2/) and [Python 3](https://docs.python.org/3/), ~~119~~ ~~110~~ 109 bytes ``` r=p='';n=1/2>0;b=(-1)**n*int(input())+10*n while b>0:r=p+'^M'[n]*b+'\n'+r;b-=2;p+=' ' print(r+p[1:]+'||'[b:]) ``` [Try it online!](https://tio.run/##Lc69CsIwFAXgPU8Rutz8UEwqOiSkb@DmVuuQGmhAbkNoUaHvHlt0PMN3zkmfeZywKcP0CC5XVVWySw7AotOHplXWO1ZrLgSKiDOLmJaZcS61EkheY3wG6ltlNiThfoEOe@El3BBktr52jU3SAQWS8s6zTJ02vYR1hc6bnpdt8V9zzUswhNLwDgPb7/At/BgAL1qRMzmR4xc "Python 2 – Try It Online") (Python 2, life) [Try it online!](https://tio.run/##Lc69CoMwFAXgPU8RXG5@kCZKOyTEN@jWzdohNqAg1xCUtuC7p0o7nuE758TPMsxY535@BpeKosjJRQdg0elT1SjrHSs1FwLFiAsbMa4L41xqJZC8hnEK1DfK7EjC4wotdsJLuCPIZH3pKhulAwokpoMnGVttOgnbBq03Hc/74r/mltZgCKXhHXp23OF7@DEAnrUiF3Im9Rc "Python 3 – Try It Online") (Python 3, death) [Answer] # [Python 2](https://docs.python.org/2/) / [Python 3](https://docs.python.org/3/), 121 bytes ``` def f(n): m=-1;n,c=(n,10-n,'^','M')[1/2>0::2];s='' while n>0:s=' '*m+c*n+'\n'+s;m+=1;n-=2 return s+' '*m+'|'*(n%2or 2) ``` [Try it online!](https://tio.run/##JY1LCsMgFEXnWcWblKdRqTo0mB10Bf1MUkMC9SWooRS6dyt0eA@Hc/dPWTaytT7DDDMj7jqIXpmB5OQZSaMVSXygxAvyqznbUTtn70P2iB28l/UVgBprG7CPYupJ4I1Q5CEK3zLK2w5SKEciyOIv4Rd7Rie7JbC87mml0r5X2o/COK9G/wA "Python 2 – Try It Online") (Python 2) [Try it online!](https://tio.run/##JYxNCsMgFIT3OcXblKfR0Gh3irlBT9CfTRqJ0LyIMZRC724tncXAN3xMfOd5pVMpj8mDZ8RNA4vrlCU5OkZS9R1JvKPEM/KLOuqhN0bf7OYQG3jN4TkB1a0yYLuIsSWBV0Kx2UW4etM53UCa8p4INvGX8IMto4NeE2heYgqUmWe/DhT3zHhNUf0X "Python 3 – Try It Online") (Python 3) [Answer] # [Python 3](https://docs.python.org/3/)/[Python 2](https://docs.python.org/2/), 128 bytes ``` def f(n,a=1/2>0): m=[n,10-n][a];k=-~m%2+1 for j in range(k,m+1,2):print(" "*((m-j)//2)+"^M"[a]*j) print(" "*((m-k)//2)+"|"*k) ``` [Try it online!](https://tio.run/##VctLCsIwEADQfU4xBIRMPqSJu0q8gScoFQI22oRMS@lGEK8eXbhx/9763B8LHVu7TQmSIB2Ds/7cYc@ghoG06wyNQxxPJZh3PXjlGKRlgwwzwRbpPomiq3LaY79uM@2CA5dCVJPRWo@KXy/8@2VGBv@g/MCLy4ItCYftAw "Python 3 – Try It Online") (Python 3) [Try it online!](https://tio.run/##VctLCsIwEADQfU4xBIRMPqTJsiXewBOUCgEbbUOmJXQjiFePLty4f29/Ho@NfGu3OUESpGNw1p877BmUMJJ2naFpjNOQg3mXk1eOQdoqrLAQ1Ej3WWRdlNMe@70udAgOXApRzIrWelT8euHfL1dk8A/yD7y4zNiScNg@ "Python 2 – Try It Online") (Python 2) [Answer] # [C (gcc)](https://gcc.gnu.org/) / [Python 2](https://docs.python.org/2/), 308 bytes ``` #define _\ """ main(N,n,j,k){scanf("%d",&N);j=-~!(N%2);for(n=j;n<=N;n+=2){printf("%*c",(N-n)/2+1,94);for(k=n-1;k;k--)printf("^");puts("");}printf("%*c",++N/2,124);N%2?puts("|"):0;} #define _""" #define/* N=10-input();j=[1,0][N%2] for n in range(1,-~N,2):print(N-n)/2*" "+"M"*(n+j) print~-N/2*" "+"|"*-~j #*/_ ``` [Try it online!](https://tio.run/##VY7LbsIwEEX3/gp3EJWfSmyxKa7VL6h/gFIUmQTFUaco0BWQX08dHpW6m9E9d@ZEvYtxHGfbummxppsPAgDkq2qRBYUqqY6fDrHChsF8C@o5cJe8Hp5YmFvumu@eoU8OX31wKL3lp33f4nGiRQTFgkZeWGnUy@JGdx61cZ3rtOYP9BO42/8cDwzycPl3QMpQWGVsbueHbzfqDHxZugv5k56U70shSPCm1C1mlk2yK6PK9Sq31yQLUKQt0r7CXc2M0kNQli@vL@@uAihIeAfBUCZOrtGgwyM4g9BDIjNRbMbR/AI "C (gcc) – Try It Online") # [Python 2](https://docs.python.org/2/) / [C (gcc)](https://gcc.gnu.org/), 308 bytes ``` #define _\ """ main(N,n,j,k){scanf("%d",&N);j=-~!(N%2);for(n=j;n<=N;n+=2){printf("%*c",(N-n)/2+1,94);for(k=n-1;k;k--)printf("^");puts("");}printf("%*c",++N/2,124);N%2?puts("|"):0;} #define _""" #define/* N=10-input();j=[1,0][N%2] for n in range(1,-~N,2):print(N-n)/2*" "+"M"*(n+j) print~-N/2*" "+"|"*-~j #*/_ ``` [Try it online!](https://tio.run/##VY7LTsMwEEX3/oowVZGfSmyxocbiC/APlFJFbQJ2xDRKwwK1za8Hpw@k7mZ0z5057W//tUMzjrNtVQessvU7AQDyXQakXqKMsmGH/abEmsJ8C/LRMxudGh6onxtm611H0UWLL85bFM6wQ9sF7Ceab0BSr5DlRmj5/HShG4dK28Y2SrEb@gHMtj/9nkIaTncHhPC5kdqkdnr4eqGOwBaFPZF/6Un5uuSceKcLFTCxdJJdalmslqm9Ikkgwyxg1pX4WVEt1eClYYvzy6srhwwEvAGnKCIj52hQ/hYcgashkhnP1@Oo/wA "Python 2 – Try It Online") ]
[Question] [ The Rugby World Cup starts in a few hours! Write a program or function which, given a rugby team score as input, outputs all possible ways the score could have been attained in a Rugby game. ### Ways to score in Rugby * **Penalty kick/Drop kick:** Both penalty kicks and a drop kicks are worth **3** points (We regroup them in this challenge to reduce the number of possibilities). * **Try:** A try is worth **5** points. * **Conversion:** A conversion is worth **2** points. **It can only occur if a try occurs too** (i.e. there can never be more conversions than trys in a game). ### Input Input is a positive integer, which corresponds to the total score of one team at the end of the game. You may assume that the score is valid, i.e. it can be attained using at least one combination of ways to score described above. ### Ouput The output for one possible way of attaining the score must look like this: ``` 2K,1T,1C ``` (*the numbers can obviously change*). the number before `K` is the number of penalty kicks and/or drop kicks, the number before `T` is the number of Trys, and the number before `C` is the number of conversions. Since you have to output all possible ways the score could have been attained, you may output them either inside a list, or separate them with line breaks (which is what I'll use in the examples below). ### Test cases * Input: `9` Output: ``` 3K,0T,0C ``` There are no other possibilites (For example, `0K,1T,2C` would give 9 points but a conversion cannot happen without a corresponding try). * Input: `12` Output: ``` 4K,0T,0C 0K,2T,1C ``` * Input: `19` Output: ``` 0K,3T,2C 4K,1T,1C 3K,2T,0C ``` * Input: `42` Output: ``` 14K,0T,0C 10K,2T,1C 9K,3T,0C 7K,3T,3C 6K,4T,2C 5K,5T,1C 4K,6T,0C 3K,5T,4C 2K,6T,3C 1K,7T,2C 0K,8T,1C 0K,6T,6C ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] ## Python 3, 113 104 bytes ``` a=int(input());print(['%sK,%sT,%sC'%(i%a,i/a%a+i%a,i%a)for i in range(a**3)if i%a*3+i/a%a*5+i/a/a*7==a]) ``` First attempt at code golf. Brute force list comprehension. I'm assuming the list output is acceptable? Counting tries + conversion as 7 points removes the if statement. Inspired by xor's python 2 answer. [Try it here](https://repl.it/BJGq/1) [Answer] # Pyth, 42 bytes ``` V^Q3I&g@K.[Z3jNQ1eKqQs*VKj352Ts.iKc2"K,T,C ``` Try it out [here](https://pyth.herokuapp.com/?code=V%5EQ3I%26g%40K.%5BZ3jNQ1eKqQs%2AVKj352Ts.iKc2%22K%2CT%2CC&input=10&debug=0). This uses the same heuristic as Andrea Biondo's answer, in that it generates every possible combination of kicks, tries and conversions from 0 to `(n-1)`. It prints the formatted output only if `(number of tries) >= (number of conversions)` and the total score is correct. ``` Implicit: Q=eval(input()), T=10, Z=0 V^Q3 For N in [0 - ((Q^3)-1)]: jNQ Convert N to base Q to get 3-tuple .[Z3 Left-pad the above with 0 to length 3 K Store in K @K 1 K[1] eK Last element of K (i.e. K[2]) g Rule 1: is K[1] >= K[2]? j352T [3,5,2] *VK By-element multiplication of K with the above s Take the sum qQ Rule 2: is that sum equal to the input? I& If rules 1 & 2 are true: c2"K,T,C ['K,', 'T,' 'C'] .iK Interleave K with the above s Concatenate into string and output ``` [Answer] # R, ~~135~~ ~~126~~ 124 bytes ``` n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n")) ``` Quick explanation: ``` n=scan() # Takes input from stdin a=expand.grid(k=0:n,t=0:n,c=0:n) # Creates matrix of all possible combinations of 3 integers from 0 to n with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,], # Only keeps the one that produced a correct score cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n")) # Prints ``` Usage: ``` > n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n")) 1: 9 2: Read 1 item 3K,0T,0C > n=scan();a=expand.grid(k=0:n,t=0:n,c=0:n);with(a[a$c<=a$t&3*a$k+5*a$t+2*a$c==n,],cat(sprintf("%iK,%iT,%iC",k,t,c),sep="\n")) 1: 42 2: Read 1 item 14K,0T,0C 9K,3T,0C 4K,6T,0C 10K,2T,1C 5K,5T,1C 0K,8T,1C 6K,4T,2C 1K,7T,2C 7K,3T,3C 2K,6T,3C 3K,5T,4C 0K,6T,6C ``` [Answer] # CJam, 48 bytes Quite slow, just generates all possible combination of values from `0` to `score - 1` for K, T and C. Then filters out the ones where the sum isn't right or `C > T`. ``` qi:X,3m*{_)\1=)<\[Z5Y].*:+X=&},::s"KTC"f.+',f*N* ``` [Try it online](http://cjam.aditsu.net/#code=qi%3AX%2C3m*%7B_)%5C1%3D)%3C%5C%5BZ5Y%5D.*%3A%2BX%3D%26%7D%2C%3A%3As%22KTC%22f.%2B'%2Cf*N*&input=42). # Explanation ``` qi:X e# Take input as integer, assign to X ,3m* e# Cartesian power [0 ... input-1]^3 { }, e# Keep values if: _)\1=)< e# Conversions <= Tries & e# AND \[Z5Y].*:+X= e# Sum([k t c]*[3 5 2]) == X ::s e# [k t c] -> ["k" "t" "c"] "KTC"f.+ e# Vector append -> ["kK" "tT" "cC"] ',f* e# Join with comma N* e# Join outer list with newline ``` [Answer] # R, ~~113~~ 101 bytes Not quite as elegant as @plannapus's answer. Go the All Blacks :) ``` n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='') ``` Test run ``` > n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='') 1: 9 2: Read 1 item 3K,0T,0C > n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='') 1: 12 2: Read 1 item 4K,0T,0C 0K,2T,1C > n=scan();for(C in 0:n)for(T in 0:n)for(P in 0:n)if(C*7+T*5+P*3==n)cat(P,'K,',C+T,'T,',C,'C\n',sep='') 1: 42 2: Read 1 item 14K,0T,0C 9K,3T,0C 4K,6T,0C 10K,2T,1C 5K,5T,1C 0K,8T,1C 6K,4T,2C 1K,7T,2C 7K,3T,3C 2K,6T,3C 3K,5T,4C 0K,6T,6C ``` [Answer] ## Python 2, 93 ``` lambda n:["%dK,%dT,%dC"%(k/n/n,k%n+k/n%n,k%n)for k in range(n**3)if k%n*7+k/n%n*5+k/n/n*3==n] ``` An anonymous function. Generates all possible triples of values by converting a value `k` from `0` to `n^3-1` to base `n`. Filters for those with the right sum. Try+conversion is considered a separate 7-point play, and the number of tries includes those too. [Answer] # Haskell, ~~102~~ 88 bytes ``` a#b=show a++b f n=[k#"K,"++t#"T,"++c#"C"|q<-[[0..n]],k<-q,t<-q,c<-q,3*k+5*t+2*c==n,t>=c] ``` Usage example: `f 19` -> `["0K,3T,2C","3K,2T,0C","4K,1T,1C"]`. Edit: output in list format seems to be ok ... [Answer] # Ruby, 89 ``` ->s{(s*s).times{|i|c=s-3*(k=i%s)-5*t=i/s c%2>0||c<0||c/2>t||puts("#{k}K,#{t}T,#{c/2}C")}} ``` call like this: ``` g=->s{(s*s).times{|i|c=s-3*(k=i%s)-5*t=i/s c%2>0||c<0||c/2>t||puts("#{k}K,#{t}T,#{c/2}C")}} g.call(gets.to_i) ``` Loops through all possible K and T and calculates the score from conversions that is required. If the score for conversions is not invalid, print the K,T,C combination that has been found. ]
[Question] [ # **Prelude:** This task is taken from [Five Problems Every Software Engineer Should Be Able to Solve in Less Than an Hour](https://gist.github.com/agrison/1a27a50c22a7f46df17c), which I really recommend. # **The task:** > > Write a program that outputs all possibilities to put + or - or > nothing between the numbers 1, 2, ..., 9 (in this order) such that the result is always 100. > > > # **Winning Criteria:** Shortest code in bytes wins. [Answer] # Perl 5.10.0 - ~~50~~ ~~46~~ 45B ``` say for grep{eval==100}glob join'{,+,-}',1..9 ``` Usage: `perl -M5.10.0 scratch.pl` (I think I get the version for free) [Answer] # CJam, ~~43~~ 40 bytes ``` "-"SL]8m*{A,2>.+1\+s}%{~]:+100=},N*S/'+* ``` Here is how it works: ``` "-"SL] e# This is an array containing -, space and empty character e# This represents -, + and joints correspondingly 8m* e# Get all cartesian products of these 3 strings of length 8 e# For instance, all cartesian products of length 2 are: e# [["-" " "] ["-" "-"] ["-" ""] [" " " "] [" " "-"] [" " ""] e# ["" " "] ["" "-"] ["" ""]] { }% e# Map these cartesian products over this loop A,2> e# Get array [2, 3, 4, 5, 6, 7, 8, 9] .+ e# In-order concatenation of the above two arrays 1\+s e# Prepend 1 to the result from above and convert it to string { }, e# Now we have all possible strings of 1 to 9 with all possible e# operators as well as joins (things like 567). Its time to e# filter out what add up to 100 ~ e# Evaluate the string. This leaves some numbers on stack. ]:+ e# Wrap those numbers in an array and take their sum 100= e# Check if the sum is equal to 100 N* e# Join all filtered strings by newline S/'+* e# We used space instead of +. So now we replace space with + ``` [Try it online here](http://cjam.aditsu.net/#code=%22-%22SL%5D8m*%7BA%2C2%3E.%2B1%5C%2Bs%7D%25%7B%7E%5D%3A%2B100%3D%7D%2CN*S%2F%27%2B*) [Answer] My shot at this: # Python 2, 93 bytes ``` def a(e,i): if i<=9:[a(e+x+`i`,i+1)for x in("+","-","")] elif eval(e)==100:print e a("1",2) ``` [Answer] # Mathematica, ~~93~~ 92 bytes ``` Print/@Select[""<>ToString/@Range@9~Riffle~#&/@{"+","-",""}~Tuples~{8},ToExpression@#==100&] ``` Fairly straightforward: generates all possible strings using `Tuples` and then filters them. For reference, I get: ``` 1+2+3-4+5+6+78+9 1+2+34-5+67-8+9 1+23-4+5+6+78-9 1+23-4+56+7+8+9 12+3+4+5-6-7+89 12+3-4+5+67+8+9 12-3-4+5-6+7+89 123+4-5+67-89 123+45-67+8-9 123-4-5-6-7+8-9 123-45-67+89 ``` [Answer] # Pyth, 26 bytes ``` fqvT100m+ssC,r1Td9^c3"+-"8 ``` First, we generate all 8 element combinations of ["+", "-", ""]. `c3"+-"` chops `"+-"` into 3 rougly equal sied pieces, giving the appropriate list. `^c3"+-"8` gives the 8 element combinations. Then, we greate the arithmetic sequences. `C,r1Td` zips together the operators with the numbers 1 through 8, which are then summed twice to give the string, and `+ ... 9` puts a 9 at the end. Finally, `fqvT100` filters for those expressions which evaluate to 100. --- The update to the interpreter which allowed this code to work was [this one](https://github.com/isaacg1/pyth/commit/3457185a1b1f7a85b23cd9135f8401e98edacdc9), which was made about a day before this question was asked, so this code would have only worked on the command line compiler, not the online one, when the question was asked. [Demonstration.](https://pyth.herokuapp.com/?code=fqvT100m%2BssC%2Cr1Td9%5Ec3%22%2B-%228&debug=0) [Answer] # K, ~~61~~ 50 bytes ``` t@&100=.:'t:{:[x>9;,y;,/_f[x+1]'(y,"+";y,"-";y),\:$x]}[2;"1"] ``` Tested with Kona. The general approach is to recursively generate all the expressions and then filter out those which eval (`.`) to 100. This is reasonably competitive as written, but I think there's still room for improvement. ## edit: ``` t@&100=.:'t:(,"1"){,/x,/:\:("+";"-";""),\:$y}/2+!8 ``` Altering my approach a bit to be iterative rather than recursive, which removes the need for explicit base cases as well as saving me some brackets. [Answer] # JavaScript, 86 ~~92~~ Head to head with the best. That must be an anomalous problem. **Edit** -6 thx @nderscore ``` for(i=6562;k=--i;eval(o)-100||alert(o))for(j=o=1;j++<9;k=k/3|0)o+=k%3?' +-'[k%3]+j:[j] ``` Test in any browser console, it pops up just 11 times. Or this snippet: ``` function out(x) { OUT.innerHTML = OUT.innerHTML + '\n' + x; } // 6562 is 3 powered to 8 +1 for(i=6562;k=--i;eval(o)-100||out(o)) for(j=o=1;j++<9;k=k/3|0) o+=k%3?' +-'[k%3]+j:[j] ``` ``` <pre id=OUT></pre> ``` [Answer] # Python (176) 39 minutes and counting (for all problems that is) ``` from itertools import* for i in product(('+','-',''),repeat=8): s=''.join(''.join(j)for j in chain(izip_longest(map(str,range(1,10)),i,fillvalue=''))) if eval(s)==100:print s ``` This could probably be shorter, but this was my actual solution for this problem, just golfed down a bit. [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~54 50~~ 48 bytes [SBCS](https://github.com/abrudz/SBCS) ``` ↑b/⍨100=⍎¨b←{' '~⍨,(1↓⎕D),⍪⍵,' '}¨(,∘.,)⍣7⍨'-+ ' ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9Q2MUn/Ue8KQwMD20e9fYdWJD1qm1CtrqBeBxTU0TB81Db5Ud9UF02dR72rHvVu1QHK1B5aoaHzqGOGno7mo97F5kB16rraCuoA&f=AwA&i=AwA&r=tryAPL&l=apl-dyalog&m=tradfn&n=f) A tradfn submission which uses strict right to left evaluation. ]
[Question] [ When you run your program first, it should print an integer sequence. The second run should print the 'Mary had a little lamb' song. The third run should produce an ASCII image file. ## Scoring Your score will be the sum of your bytes of code and any file content at the start of each of the 3 runs. Lowest score wins. For example, `myprog` is 1500 bytes and does not change its size, but writes a 4 bytes file each run so it knows what to do on the next run. The score would be 1500 + (1500+4) + (1500+4) = 4508. ## Output The first output is this sequence of 133 integers, separated by single spaces: ``` 0 89 98 179 188 197 269 278 287 296 359 368 377 386 395 449 458 467 476 485 494 539 548 557 566 575 584 593 629 638 647 656 665 674 683 692 719 728 737 746 755 764 773 782 791 809 818 827 836 845 854 863 872 881 890 908 917 926 935 944 953 962 971 980 1079 1088 1097 1169 1178 1187 1196 1259 1268 1277 1286 1295 1349 1358 1367 1376 1385 1394 1439 1448 1457 1466 1475 1484 1493 1529 1538 1547 1556 1565 1574 1583 1592 1619 1628 1637 1646 1655 1664 1673 1682 1691 1709 1718 1727 1736 1745 1754 1763 1772 1781 1790 1808 1817 1826 1835 1844 1853 1862 1871 1880 1907 1916 1925 1934 1943 1952 1961 1970 ``` The second output is this text exactly (including capitals, punctuation, and white space - the inconsistent punctuation is intentional): ``` Mary had a little lamb, Little lamb, little lamb, Mary had a little lamb, Its fleece was white as snow And everywhere that Mary went, Mary went, Mary went, Everywhere that Mary went The lamb was sure to go It followed her to school one day School one day, school one day It followed her to school one day Which was against the rules. It made the children laugh and play, Laugh and play, laugh and play, It made the children laugh and play To see a lamb at school ``` The third output is this image in PPM ASCII(P3) format left in a file called `blue.ppm`. This is the image in PNG format: ![target image](https://i.stack.imgur.com/sHCba.png) The PPM file should look something like this: ``` P3 50 50 255 255 255 255 255 255 255 255 255 255 255 255 255 ... ... 255 255 255 ``` There is a copy of the [full PPM file here](http://pastebin.com/8PxXi4Xb). ## Example run (on Linux) ``` # ls myprog # interpreter myprog 0 89 98 179 188 197 269 278 287 296 359 ... # interpreter myprog Mary had a little lamb, Little ... # interpreter myprog # ls blue.ppm myprog # cat blue.ppm P3 50 50 255 255 255 255 255 255 ... ``` ## Rules * Your code may modify itself. * Running the program a fourth time is undefined behaviour. * You may write to a file in the current directory, but the size of this file will add to your score at the start of each run. The final PPM file is excluded from this. * The first two outputs are to stdout (or similar). The last output is written to a file, with nothing sent to stdout. * The first two outputs may optionally have a trailing white space character (e.g. space or line feed). * You may not use compression or image libraries. You may use your own compression or image functions but this code must be included in your program. * The standard loopholes are prohibited. [Answer] # Ruby, ~~1356~~ 1268 \* 3 = 3804 bytes ``` if File.file?(?b) s='P3 50 50 255 ' d=e=0 [153,44,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,6,1,42,1,4,40,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,1,36,1,5,1,4,1,1,34,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,34,1,3,1,5,1,4,1,8,31,5,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,1,25,1,9,1,4,1,8,37,4,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,1,34,1,14,36,63].map{|n|n.times{s+=[" 255 255 255"," 0 0 255"][d];s+=$/if (e+=1)%50==0};d=1-d} File.write 'blue.ppm',s elsif File.file?(?a) puts [["","Mary had a ","little lamb",?,,?,,"Its fleece was white as snow"],["And ","everywhere that ","Mary went",?,,'',"The lamb was sure to go"],["","It followed her to ","school one day",'','',"Which was against the rules."],["","It made the children ","laugh and play",?,,'',"To see a lamb at school"]].map{|a,b,c,d,e,f|[a+b+c+d,c.capitalize+', '+c+d,b.capitalize+c+e,f]*$/}*" " `touch b` else 1971.times{|i|$><<"#{i} "if i.to_s.chars.map(&:to_i).reduce(:+)%17<1} `touch a` end ``` To keep track of the invocation, I'm creating an empty file `a` on the first run and an empty file `b` on the second run. * The first program uses a certain property of the numbers. * The second program uses a bunch of reusable parts of the verses, but that currently only saves 100 bytes over naively printing the entire thing. * The third program currently uses just a simple run-length encoding. I'll look into actually encoding the path of the line later. [Answer] # Python (897 + 814 + 386 = 2097) Simple self-modifying answer. I'll have to refine the second run later. ``` def p(x):print x, map(p,[0]+filter(lambda x:sum(map(int,`x`))==17,range(1971))) #l="ittle lamb,";M="Mary ";w=M+"went";e="verywhere that "+w;s="chool one day";I="It followed her to s"+s+"\n";j="augh and play";i="It made the children l"+j;print M+"had a l"+l+"\nL"+l+" l"+l+"\n"+M+"had a l"+l+"\nIts fleece was white as snow\n\n"+"And e"+e+",\n"+w+", "+w+",\nE"+e+"\nThe lamb was sure to go\n\n"+I+"S"+s+", s"+s+"\n"+I+"Which was against the rules.\n\n"+i+",\nL"+j+", l"+j+",\n"+i+"\nTo see a lamb at school" #print>>file("blue.ppm","w"),"P3 50 50 255"+' '.join(" %i"%(255-255*any(a<y<b and x==c or y==d and e<x<f for a,b,c,d,e,f in[(2,48,2,47,2,37),(9,48,36,9,27,37),(9,41,28,40,9,29),(0,41,10,1,9,49),(0,37,48,36,14,49),(2,37,15,3,2,16)]))*2+" 255"for x in range(50)for y in range(50)) import sys;x=file(sys.argv[0],"r+");y='#'.join(x.read().split('#')[1:]);x.seek(0);x.truncate();x.write(y) ``` Additionally, if run for the fourth time, it safely degrades to a NOP: ``` '.join(x.read().split('#')[1:]);x.seek(0);x.truncate();x.write(y) ``` [Answer] # Python 3, 1027 + 1028 + 1029 = 3084 ``` 0 or print('0 '+' '.join(str(i)for i in range(1971)if sum(map(int,str(i)))==17)) 1 or print("""+$, L$, l$, +$, Its fleece was white as snow And e(@, @, @, E(@ The!was sure to go #& S&, s& #& Which was against the rules. %l/, L/, l/, %l/ To see a!at school""".translate({43:'Mary had a l',36:'ittle lamb',40:'verywhere that ',64:'Mary went',35:'It followed her to s',38:'chool one day',47:'augh and play',37:'It made the children ',33:' lamb '})) q=[153,44]+[e-63for e in b'E@i@E@i@E@i@E@i@E@i@E@i@CgD@C@@@c@D@C@@@c@D@C@@@c@D@C@@@c@D@C@@aB@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@a@B@D@C@G^D@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@G@X@H@C@GdC@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@M@a@Mc~?'] 1 or open("blue.ppm","w").write("P3\n50 50\n255\n"+' '.join(q[r*2]*'255 255 255 '+q[r*2+1]*'0 0 255 'for r in range(140)).strip()) f=open(__file__);l=f.read();f.close();open(__file__,"w").write(l.replace("0 or","0 and",1).replace("1 or","0 or",1)) ``` Uses [OEIS A166370](https://oeis.org/A166370) for the numbers, some hand-written compression for Mary's Lamb and ASCII bytes to store the amounts of numbers in the PPM. (Ab)uses Python's feature to only evaluate the second value for logical operators if the result is not known yet (short-circuiting): `1 or code` and `0 and code` do not evaluate `code`. Then uses some replacements to change the `0 or` enabling code execution to a `0 and` and the next `1 or` to `0 or`. The 3rd execution kills the second replace, as there are no more `1 or`'s. The 4th execution kills the first replace, after which the code does basically nothing. [Answer] # C++, 1204 \* 3 = 3612 bytes Compiler used - **GCC 4.9.2** with `-std=c++14` flag ``` #include<bits/stdc++.h> int i,j,c; using namespace std;int main(){fstream f("F"),g("G");if(!f){while(i<=1970){j=i,c=0;while(j)c+=j%10,j/=10;if(c==17||i==0)cout<<i<<" ";i++;}ofstream f("F");}else if(f&&!g){cout<<R"(Mary had a little lamb, Little lamb, little lamb, Mary had a little lamb, Its fleece was white as snow And everywhere that Mary went, Mary went, Mary went, Everywhere that Mary went The lamb was sure to go It followed her to school one day School one day, school one day It followed her to school one day Which was against the rules. It made the children laugh and play, Laugh and play, laugh and play, It made the children laugh and play To see a lamb at school)";ofstream g("G");}else{ofstream F("blue.ppm");F<<"P3 50 50 ";vector<int> L={1,2,4,10,13,16,19,25,28,43,76,103,109,127,190,460};vector<string> R={"1","?","43","10","6","161=","1","14","39","10","4","1514121<","1","151412","33","10","12","1315141;","1","13151417","30","10","1","1514171","7",":1814171","36","01","1","41","11",";191","35","01","1",">"},C={"255","0"};string r;i=j=0;while(i<R.size()){stringstream S(R[i]);S>>c;while(c--)r+=R[i+1];i+=2;}i=0;while(i<r.size()){c=L[r[i]-48];while(c--){F<<C[j]<<" ";}j=1-j;i++;}}} ``` ***Explanation -:*** ``` #include<bits/stdc++.h> using namespace std; int main() { fstream f( "F" ), g( "G" ); // Creating empty files so that the program can decide when to run which task /**************************** TASK 1 ****************************/ if ( !f ) // Print all the numbers within the range whose sum of digits is 17 { for ( int i = 0; i <= 1970; i++ ) { int j = i, c = 0; while ( j ) { c += j % 10, j /= 10; } if ( c == 17 || i == 0 ) { cout << i << " "; } } ofstream f( "F" ); } /**************************** TASK 2 ****************************/ else if ( f && !g ) // Print the second task as it is using raw literals { cout << R"(Mary had a little lamb, Little lamb, little lamb, Mary had a little lamb, Its fleece was white as snow And everywhere that Mary went, Mary went, Mary went, Everywhere that Mary went The lamb was sure to go It followed her to school one day School one day, school one day It followed her to school one day Which was against the rules. It made the children laugh and play, Laugh and play, laugh and play, It made the children laugh and play To see a lamb at school)"; ofstream g( "G" ); } /**************************** TASK 3 ****************************/ else // Third task using Run-Length encoding { ofstream F( "blue.ppm" ); F << "P3 50 50 "; /* L = set of all the lengths found during run-length encoding. R = vector containing the run-length encoding of "255" and "0" alternatingly. {1,"?") means 1 times print '255'/'0' "x" number of times where x = L[ASCII(?)-48] = L[15] = 469 C = vector containing the two strings to be printed alternatingly. */ vector<int> L = {1, 2, 4, 10, 13, 16, 19, 25, 28, 43, 76, 103, 109, 127, 190, 460}; vector<string> R = {"1", "?", "43", "10", "6", "161=", "1", "14", "39", "10", "4", "1514121<", "1", "151412", "33", "10", "12", "1315141;", "1", "13151417", "30", "10", "1", "1514171", "7", ":1814171", "36", "01", "1", "41", "11", ";191", "35", "01", "1", ">"}; vector<string> C = {"255", "0"}; string r; // Contains the normal/expanded version of R i = j = 0; while ( i < R.size() ) // Expanding "R" into normal form and putting it into "r" { stringstream S( R[i] ); S >> c; // Convert R[i] to its integer representation and put it in "c" with the help of stringstream. while ( c-- ) { r += R[i + 1]; } i += 2; } i = 0; while ( i < r.size() ) { c = L[r[i] - 48]; // "c" is the number of times the current character has to be printed consecutively. while ( c-- ) { F << C[j] << " "; } j = 1 - j; // Alternate "255" and "0" i++; } } } ``` [Answer] # PHP [(1552\*3)+2 = 4658](https://www.google.com/search?q=(1552*3)%2B2) There is A LOT of golfing that can be made. The code writes 1 byte into another file called `z`, to check the status. Here is the code: ``` <?$Y=base64_decode;$Z=gzdecode;$r=file_put_contents;switch(include z){case 2:$M=Mary;$l=lamb;$L=ittle;$H="$M had a l$L $l,";echo"$H L$L $l, l$L $l, $H Its fleece was white as snow ";$W="$M went";$H="verywhere that $W";echo" And e$H, $W, $W, E$H The $l was sure to go ";$S=chool;$O="$S one day";$I=" It followed her to s$O";echo"$I S$O, s$O$I Which was against the rules.";$L="augh and play";$I=" It made the children l$L";echo"$I, L$L, l$L,$I To see a $l at s$S";$r(z,3);break;case 3:$r($Z($Y("H4sIAAAAAAAAA+3ay63CMBSE4X2qSAkRKH3QfzXAmkf8mBOfiX9dRXcBfIJ47Ewwj/uyb+u+Lbd9fx+r4gACAgICApoO2l5/Jf+X0icCfT4gG7ka0DSQQMdPOopB9bv5BpqeG6D2F8tjQK6AImJAroAiYkCugCJiQK6AemKQ51bWF+oaxe6Rk2DhAQUKjIIEIU9Xg8gTkBIiT0BKKG+e8nXMcVBRDFr3oyQIq4ADVLW1JNnfbEYkafYcJR+oatZLtrebEfluPVAAVDNKkn3yZoQfazhAvXkaW4WNTvQkEIUcSAlRyIGUEIUcSApRyIGUEIUcSAlRyIGUEIUcSAlRyH+/w/H7qudDXUHMf+nhpq4NGlM28196KOFtx5iy6XPpyTdiyaEhZdPg3p0S3gaN+baOAnVViAKV6bz4QxSoTOflAhAF6v95yfdVTT7otOEPCSNQ+Sgl/1jc9RhAhrOfux8HyG/2Gy6xE0J+v+AyXGInhAxnv98SOyFkOPspWA6Q3+w3XGInhChYQBGQ4ez3W2InhAxnPwXLAfKb/RfYvQqH8o0aENBJ0BPXPoC/PXEAAA==")),'blue.ppm');$r(z,1);break;default:echo$Z($Y("H4sIAAAAAAAAAxXSuQHAMAwCwFUYIehF+y8WXCWWaDj7gw4ncA+Uv7eIOcQKIf/fIPuQI+QuUj5fo+pQLdQsagclz67QeegSuhc9g95Gy/NLTBwmhanF9GCmMVsYeXeB5WFD2FxsDbYbO4XdxMr7I/QdREGxUA5UDXVBk9AGJGfuw33CcXExuGxcFa4TN4FbuvIHfq/091p/rk26N+nipN7R1RnuznB5htsz9GbuzzQA0wJMEzBtwNRbWIFlBpYdWIZgWYJlCpbe1hhsa7DNwbYH2yBsi7BNwtaLGIVjFY5ZOHbhGIZjGY5pOLbh6OWswzUPl+8+DcS1ENdEXBtxjcS1kku+sJ0oQ1GWokxF2YoyFmUtylzG4HsbDt/n3NG5C+cunbty7tq5G7738/3WJLxlVAIAAA=="));$r(z,2);} ``` I know that this is a VERY horrible code and I can try to golf the list. But hey, I can't find a pattern on those :/ [Answer] # Ruby, 691+612+225 = 1528 bytes Another self modifying answer, this time in ruby. I just bumped into this yesterday and the compressing of the poem caught my eye. I was only able to save 92 bytes off the raw text thought. ``` puts (0..1970).select{|i|eval(i.to_s.gsub /\B/,'+')%17<1}*' ' File.write $0,%@ m='lamb:little 0,:Mary :2had a 1:2went:laugh and play:It made the children 5:It followed her to 10: was : that :11 one day:school:everywhere:3 1 1 3 Its fleece8white as snow And 1294, 4, 4, 1294 The 08sure to go 7 10, 10 7 Which8against the rules. 6, 5, 5, 6 To see a 0 at 11' 12.downto(0){|i|m.gsub! i.to_s,m.split(':')[i]} puts m.split(':')[13].gsub /^./,&:upcase File.write $0,%!a=[1] s=[16,13] File.write 'blue.ppm',(' P3 50 50 '+[460,a*43,[19,127]*6,13,a*39,[s,4,109]*4,s,4,a*33,10,s,[103,10,s]*12,25,a*30,s,25,[76,28,13,25]*7,a*36,13,[103,43]*11,a*35,190].flatten.map{|i|('255 '*i)+'0 0 '}*' ')[1..-6]!@ ``` Each run of the program rewrites the program for the next run. I didn't figure out the special property of the numbers until looking over the other answers. And did take same inspiration Martin's answer but I didn't use the suggestion from blutorange because I couldn't figure out why it worked. There is probably a few more bytes to scavenge from the poem but not much. It is basically just subbing in common sequences and is using the order of the sequence as the part to replace. For the final part I length encoded all of the 255 bytes into an array and glued them together with the zeros. And then I encoded the repeating sequences in that array. [Answer] # JavaScript + HTML, 3909 bytes This is a HTML/JavaScript application that uses page reload to rerun files. I goofed on parsing the PPM. If you know how to read PPM files, please let me know. Stack Exchange doesn't allow local-storage. So you will have to run the JSFiddle. Again, I know I bombed the ppm file. But in the end: **JavaScript**: 1,232 bytes \* 3 = 3696 **HTML**: 71 bytes \* 3 = 213 **Total**: 3909 [JSFiddle](http://jsfiddle.net/neoaptt/103b4z9q/) ``` var mary = '</br>\ Mary had a little lamb,</br>\ Little lamb, little lamb,</br>\ Mary had a little lamb,</br>\ Its fleece was white as snow</br>\ </br>\ And everywhere that Mary went,</br>\ Mary went, Mary went,</br>\ Everywhere that Mary went</br>\ The lamb was sure to go</br>\ </br>\ It followed her to school one day</br>\ School one day, school one day</br>\ It followed her to school one day</br>\ Which was against the rules.</br>\ </br></br>\ It made the children laugh and play,</br>\ Laugh and play, laugh and play,</br>\ It made the children laugh and play</br>\ To see a lamb at school\ '; var img = '<img src="https://i.stack.imgur.com/sHCba.png"/>' function run() { var step = localStorage.getItem("step"); step++; localStorage.setItem("step", step); $('#step').text(step); var r = $('#results') switch (step) { case 1: for (var i = 0; i < 133; i++) { r.append(i + 1 + ' '); } break; case 2: r.html(mary); break; case 3: r.html(img); localStorage.setItem("step", 0); break; default: localStorage.setItem("step", 0); break; } } run(); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Step: <span id='step'></span> </label> <div id='results'></div> ``` ]
[Question] [ *This challenge was originally [posted on codidact](https://codegolf.codidact.com/posts/289152).* --- At my job we have to sometimes lay out materials. Materials come in large long rolls and are cut into smaller pieces when being laid out. When we order the rolls we draw up a layout document which describes how we are going to cut them and layout the pieces. This tells the manufacturer how we are going to use the rolls so they can make all the right adjustments. We then use the document when actually laying the materials out. In reality these documents are very complex and include a lot of information, however for this challenge I will simplify them. We will say pieces are placed in a 1-dimensional list with no gaps. The document indicates which pieces come from which rolls and the order in which they are cut.The document uses color to indicate which roll each piece comes from and numbers them in order. However sometimes things don't get printed in color, or colors get smudged. But usually you can still figure out which pieces come from which rolls based on the numbers alone, since there are some constraints on how things can be placed. Here are the two constraints: 1. We lay out pieces from the same roll in order, so 1 is the first piece to be laid out, then 2 etc. 2. If the piece number is greater than 1 it must be placed adjacent to another piece from the same roll. So if we look at the following layout: ``` 1,2,1,3 ``` We can see that there are two rolls, since there are two 1s. We can also see that one of the rolls has 3 pieces since there is a piece labeled 3. The 3 is next to a 1, so they must come from the same roll, thus the pieces come from the following rolls: ``` [1,2,1,3] [0,1,1,1] ``` In this challenge you are going to write a program which determines the color information based on a colorless layout. # Task Take as input a list of positive integers representing a layout. Each integer is a piece number. Output a lists of integers representing the possible colorings of the layout. Each coloring should be a list of integers with the same length as the input such that iff the pieces at two indices are from the same roll the same integer is at those indices in the coloring. If there is no way to color the layout, output an empty list, if it is ambiguous output all the possible colorings. If there is no layout just output an empty list. This is code-golf, so the goal is to minimize the size of your source code as measured in bytes. # Test cases The output does not have to exactly match the ones given here, the possibilities can be given in any order, and the rolls can be assigned different numbers, so long as each roll is assigned a different number. ``` [1,2,1] -> [[0,0,1], [0,1,1]] [2,1,3,2,1] -> [[0,0,0,1,1], [0,0,1,1,1]] [1,2,1,2,1] -> [[0,0,1,1,2], [0,0,1,2,2], [0,1,1,2,2]] [1,6] -> [] [4,2,3,1] -> [] [1] -> [[0]] [1,2,3,4] -> [[0,0,0,0]] [4,3,1,2] -> [[0,0,0,0]] [3,1,2,4] -> [[0,0,0,0]] [1,2,1,3] -> [[0,1,1,1]] [1,2,3,1] -> [[0,0,0,1]] [1,2,2,1] -> [[0,0,1,1]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṖtL$ƬL>LƲƇƑƇJxẈƊ€ ``` A monadic Link that accepts a layout as a list of positive integers and yields all possible colourings using a prefix of the positive integers. **[Try it online!](https://tio.run/##y0rNyan8///opIc7p5X4qBxb42Pnc2zTsfZjE4@1e1U83NVxrOtR05r/OofbQUpmANlZjxrmKNjaKTxqmKsZ@f9/dLShjpGOYawOl0I0kNYxhvPA4kg8MzBtAhQxhonB1RnrmEBljUF6wGwwCyoOMcsYST1CL8SGWAA "Jelly – Try It Online")** ### How? ``` ŒṖtL$ƬL>LƲƇƑƇJxẈƊ€ - Link: list of positive integers, Layout ŒṖ - all partitions of {Layout} Ƈ - keep those {patitions} for which: Ƒ - {partition} is invariant under?: Ƈ - keep those {parts} for which: Ʋ - last four links as a monad: Ƭ - collect while distinct under: $ - last two links as a monad: L - length t - trim all occurrences of {that} from both ends L - length of {that list of collected, trimmed parts} L - length {part} > - {collected count} greater than? {part length} € - for each {valid partition}: Ɗ - last three links as a monad: J - indices {partition} Ẉ - length of each {partition} x - {indices} times {lengths} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 107 bytes ``` f=([v,...a],L=[],k=0,G,h)=>v?1&(h<v^G/2|G>>v)?'':f(a,L=[...L,k],k,G|=1<<v,v)+f(a,L,1+k,G&G+2&&1):G?'':L+` ` ``` [Try it online!](https://tio.run/##dZFNboMwEIX3nMIrwGIKGFAX/GVVWZW4gUUVi4bSJoIoSb1penZqGxxE2rIav/c9z3j44IKfm9P78fLQD6@7cWwLlwnwfZ/XUBWshn0RAoUOF6XYENvtcvFCg@hKy1LgjeOkrcsVKBMV7CUO9FqQPBcgsKc9IJ4UbepFtk1wSlWo8rbWdsyYhRAjEAGpAekvCBBjIYRakQWRRa0oyUBsyBs1AZrUpaH1nb9oBUQLHZkDmQ9z9NEMM0W1mkggNmPeVLKQps3SP4ZkwedpZztRd@nuf9ra/D89PS5e2XdvX41qNrXYajF369Z2bfntcHriTedyVJToCzVDfx4OO/8wvLnOc3/8vKQOII6zlSP/M5bSN87GHw "JavaScript (Node.js) – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 31 bytes ``` ms.e.ekbdf.Am&SI._M.+dqSldSdT./ ``` [Try it online!](https://tio.run/##K6gsyfj/P7dYL1UvNTspJU3PMVct2FMv3ldPO6UwOCclOCVET////2gjHUMdYx0gGQsA "Pyth – Try It Online") ### Explanation ``` ms.e.ekbdf.Am&SI._M.+dqSldSdT./Q # implicitly add Q # implicitly assign Q=eval(input()) ./Q # list all partitions of Q f # filter these partitions on lambda T .A # check if all are truthy m T # T mapped over lambda d .+d # the deltas of d ._M # mapped to their signs SI # is invariant under sorting & # and Sd # sorted(d) q # equals Sld # range(1,len(d)+1) m # map the remaining valid partitions over lambda d s # flatten .e.ekbd # convert each element of each partition part to its index in the partition ``` [Answer] # JavaScript (ES6), 168 bytes Returns a string, using commas and linefeeds as separators. ``` f=([v,...a],p=[],c=p,b=[...p,c])=>v?f(a,p,[...c,v])+(c+c&&f(a,b,[v])):b.some(c=>c.some(d=m=p=v=>m==(m|=1<<v)|d^p<(d^=v<2,p=v))|m+1&m+2)?"":b.map((c,i)=>c.map(_=>i))+` ` ``` [Try it online!](https://tio.run/##dZLPUsIwEMbvPEWGAyTTtZCW8QDdcvLgM2SKhhQUh9IMYC7is9ckbeiA2tPu9/32T3b6IY08qeNOnx8Odblpmi1SYSCOY1mARlGAQg1rFFbRoAqGuVluqQQNTlJgChZRFanRyKlrEFZg83V8qqsNVZirNiqxQo0G8wqRVhfkWWbYpVzpjJYrNFlihxnGLlXER1WUsOVwaJtUUlOqYMdcH5e8YL5jLHodvDYLMSBEcEiAF0D8N5kQIaYw9YoNuA0KR1kG0kBeqRbwpA8D7Xv@oh2Q9HQSEt4lXeljWKYt9erMAmlY86ryngxj@vkpzHq827azZ66Xn/6n7c3/q9vHpTf23dtvVg2X6m13mLtze7sYxNv6@CTVO5UEc/JFVH041ftNvK/f6Pj5oD/P8zEQyRY3jv1vmJW@2aL5AQ "JavaScript (Node.js) – Try It Online") ## Commented ### Recursive part We build all partitions of the input array `a[]`. ``` f = ( // f is a recursive function taking: [ v, // v = next piece number ...a ], // a[] = array of remaining values p = [], // p[] = current partition c = p, // c[] = current piece cluster b = [...p, c] // b[] = copy of p[] with c[] added ) => // v ? // if v is defined: f(a, p, [...c, v]) + // do a recursive call with v added to c[] ( // c + c && // if c[] is not empty, f(a, b, [v]) // do another recursive call with p[] = b[] ) // and c[] = [ v ] : // else: ... // final test (see below) ``` ### Final test We test whether the partition `b[]` is valid. ``` b.some(c => // for each cluster c[] in b[]: c.some(d = m = p = // initialize d, m and p to NaN'ish values v => // for each value v in c[]: m == (m |= 1 << v) // set the bit at index v in m and make sure // that m is modified by doing so | d ^ p < ( // make sure that p and v are in the expected d ^= v < 2, // order, update p to v p = v // and update the direction if v = 1 ) // ) // end of inner some() | m + 1 & m + 2 // make sure that m consists of a sequence of // consecutive bits set to 1, followed by a // trailing 0 ) // end of outer some() ? // if it failed: "" // append nothing : // else: b.map((c, i) => // turn each value in each cluster c[] in b[] c.map(_ => i) // into a roll number ) + // implicit coercion to a string `\n` // append a linefeed ``` [Answer] # Python3, 772 bytes: ``` E=enumerate def f(l,I=[],r=[]): if len(I)==len(l):yield r;return for i,a in E(l): if a==1 and i not in I: j,k,Q,W=i,i,[],[] while(j:=j-1)>=0 and j not in I and l[j]!=1 and(Q==[]or Q[-1][0]<l[j]):Q+=[(l[j],j)] while(k:=k+1)<len(l)and k not in I and l[k]!=1 and(W==[]or W[-1][0]<l[k]):W+=[(l[k],k)] R=range(max(len(Q),len(W))) for x in R: for y in R: u=[Q[:x+1],W[:y+1]] for o,V in E(u): if V and V[0][0]==2: M=V+u[not o] if len(S:=[X for X,_ in M])==len({*S}): yield from f(l,I+[j for _,j in M]+[i],r+[M+[(a,i)]]) yield from f(l,I+[i],r+[[(1,i)]]) def F(l): R=[] B={str(sorted(j))for j in f(l)} for i in map(eval,B): v=[-1]*len(l) for P,j in E(i): for _,I in j:v[I]=P R+=[v] return{*map(tuple,R)} ``` [Try it online!](https://tio.run/##bVLBauMwEL3nK7Q3KZ5CHYdl8Xb2UEghh0CTQlwQohiibGU7dlDtbELot2c1kpttk4UQed68efOkme2hfW3q5MfWnk4T1HW30TZv9WCl12zNK5iiVGDdn0gHzKxZpWs@FYh0ViI9GF2tmP1pddvZesDWjWUGcmZqNqH8gFFRjhizvF4xw@qmpeSUMqyAEuaQoQEDro1UBP55NZXmRYrFTSx@4a0vLM6FPqxkob4FTT5H5861ncubWMlbdUdJkc4jlJw@oRCfdMsUyygWd8E/aZWX0uVZOuuls3/SpZPOgnSpoAzSC7R5/VvzTb7nJDwXQEcmhKA0PcqeOiz8rX18@BSzDuVcpvsoVpDJ9OBOFRLEbGAZnrMTPZ2edOnNLp0p90McfaTYDJdRJ@lKjfrA@rk9pSifveYzvJDmTPWTPA6f3s/qjIWprm2zCTsQycKXvUARyiJp3FZEchZJnoMRSvmLXtcFmuRxT6K1egiLsUCa9z0e31rL3xrb6hUvhKA@votTEO/9RlG8ybdc7/IK7r3THdJQhmGOg/BUj8HfhJtwmeB5SliR7uRU4aODF258O9c67OxxSMJtt600LMT7aWtN3fIHLmMYQazcBM@IiyG5Qj3vP@j3L/HYMZJLzpVOAuOLqoS0v2AeueAFD8kVdu2KjYCNgRH19Bc) [Answer] # [Python 3.8](https://docs.python.org/3.8/), 230 bytes ``` r=range p=lambda l:[[l]]+[q+[l[n:]]for n in r(1,len(l))for q in p(l[:n])] f=lambda Q:[[k for k,g in enumerate(q)for h in g]for q in p(Q)if all(sorted(d:=[0<s[i+1]-s[i]for i in r(len(s)-1)])==d and{*s}=={*r(1,len(s)+1)}for s in q)] ``` [Try it online!](https://tio.run/##bY5BbsMgEEX3PgVLJiZSKVZVWeEQWaNZUIEdFIJtcBdVlLO7xlGqxs5qNE/vf/3@Zzx1QXz2cZqijDq0tuil15cvo4mvlfKIpRpK5VWoEZsukkBcIJFy5m2gHiCzIbOeelUHBCyaR8NxbjiTbJxZmx0bvi826tHSYQmeMmzxX8cRXEO09zR1cbSGmlqqt0NSruS4n8/iuvuGvCDBngOClIboYK67dJPyunvsS1ByuOVIypEBcOqjCyNtqOLsnXEEKP7I/DOxoYv3gn48/dVsiLWz6RGsWqVE7n5iC1l59w1iw15trRZv@gU "Python 3.8 (pre-release) – Try It Online") Essentially a port of my [Pyth answer](https://codegolf.stackexchange.com/a/263846/73054). [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 66 bytes thanks @doug for drawing my attention to this interesting challenge ``` {(,^x)(,/{@[y;z;:;]'(((x=1+/y=)')#y@-1 1+z;,1+|/y)1=x@:z}[x]')/<x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxdjuFOwyAUhf/3Ka6ZsZDSUNbFH8UlfY+mZnUB21iHUqawuT270HZukYTcez/OOVxZHBF5thgReiwrxw+84HWMELJrllC3xjFeuDJlwJIDJyz5oQ6ztS2Lw6mydYzpkz1FkSxSlsgS6FZpLbamUzuQSoOSMn1xqdoJ0GLY92YAZFoB27bpe7F7FeCr+h7AtI3BUWSK433lzrqQYPlGvUUQzgM9L2KkucOBATVaNCY4Qbx/mE4M0AwgPvfdV+NDzWRCG9l0PbfccY1rv6OpGCyBcZRB5ou/wHDtsYeQX5/GBz7XWTI6b9xhmCXLsWNTN4sf+V0WupVnuTdNE2GckOwSl8OKk+m/WZuPqbdsJP900yp5YON+1zx20f2x5YUF3S9whHoI) The results are off by one compared to the examples (this is allowed). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 77 bytes ``` ⊞υ⟦…θ¹⟧FΦθκ«≔⟦⟧ηFυ«⊞η⁺κ⟦⟦ι⟧⟧≔⊟κζ¿⁼№ζ¹›ι↨ζ⁰⊞η⁺κ⟦⁺ζ⟦ι⟧⟧»≔ηυ»EΦυ⬤ι⬤λ№λ⊕ξ⭆¹ΣEιEνξ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVC9TsMwEBZj8hSnTrZ0lSgsSJ1KBAgkpEiMlgcTnMaKm7R2jKCoT8LSAQQLL8TTcHYoCx5857vv586vn1WjXNUru9-_h6Genn0f3ZTBNywgiOK5srpo-jXbIMy45PO87h2wS2MH7WKx5Rxe8mzhvVl2TEiEhkBZQoXUypJag1Da4FlLqsJIySPqQCvJoOUI21Q0NbCLTVDWs6IP3cC20RvhymkVXQ3CufI6lo85HfhnkBJqkxEfnXZ_IxIuUGWXl86Q9q1aH7ahhRfWRvkYLMLoTsl1Vzm90t2gH9hTtKRp7gbiLyN9Ro-wSkrEjaFDGGHzN39f-d-P_RCT6aOdyC8hTnCGp0i3lGPvBw) Link is to verbose version of code. Explanation: ``` ⊞υ⟦…θ¹⟧ ``` Start with a partition of just the first piece in a roll. ``` FΦθκ« ``` Loop over the remaining pieces. ``` ≔⟦⟧η ``` Collect new potential partitions. ``` Fυ« ``` Loop over the current partitions. ``` ⊞η⁺κ⟦⟦ι⟧⟧ ``` Maybe this piece starts a new roll. ``` ≔⊟κζ ``` Remove the last roll. ``` ¿⁼№ζ¹›ι↨ζ⁰ ``` If this piece could be part of the last roll... ``` ⊞η⁺κ⟦⁺ζ⟦ι⟧⟧ ``` ... add that as an alternative. ``` »≔ηυ ``` Save the potential partitions for the next pass. ``` »EΦυ⬤ι⬤λ№λ⊕ξ⭆¹ΣEιEνξ ``` Output only those partitions whose rolls all contain all of the values from `1` up to their length, mapping each value to the roll index and flattening. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .œʒε1š1¡`R‚εD{Q}`y{āQP}P}εĀƶ˜ ``` Port of [*@CursorCoercer*'s Pyth answer](https://codegolf.stackexchange.com/a/263846/52210). 1-based output. [Try it online](https://tio.run/##AT0Awv9vc2FiaWX//y7Fk8qSzrUxxaExwqFgUuKAms61RHtRfWB5e8SBUVB9UH3OtcSAxrbLnP//WzEsMiwxLDNd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vaOTT006t9Xw6ELDQwsTgh41zDq31aU6sDahsvpIY2BAbUDtua1HGo5tOz3nf63O/@hoQx0jHcNYnWggqWMMZYPF4GwzIGkC5BlD@FB5Yx0TsLgxSCWQBabBYhDdxnB1MB0g82IB). **Explanation:** ``` .œ # Get all partitions of the (implicit) input-list ʒ # Filter it by: ε # Map over each part of the current partition: 1š # Prepend a 1 to the part 1¡ # Then split the part on 1s ` # Pop and push all split-parts separated to the stack R # Reverse the top/last split-part ‚ # Pair it back together with the list before it) ε # Map over this pair of lists: D{Q # Check if the list is sorted from lowest to highest: D # Duplicate the list { # Sort the copy Q # Pop both lists, and check if they're equal }` # After the map: pop and push the two checks to the stack again y # Push the current part-list again { # Sort it from lowest to highest ā # Push a list in the range [1,length] (without popping the list) Q # Check if the two lists are the same P # Get the product of all values on the stack to see if this part is # truthy }P # After the inner map: check if all parts of this partition were truthy }ε # After the filter: map over the remaining partitions: Ā # Convert each character to a 1 (with an !=0 check) ƶ # Convert each inner value by its 1-based list-index ˜ # Flatten this partition of indices to a single list # (after which the list of lists of (1-based) indices is output # implicitly as result) ``` [Answer] # [Perl 5](https://www.perl.org/), 183 bytes ``` sub f{my@a;(join'',map chr,@_)=~m~^((.+)(?(?{$_=$2;$i=s/\x1/\0/;1while$c=chr++$i,s/\x00\Q$c\E|\Q$c\E\0/\0/;/[^\0]/||!(local@b=(@b,(1+$b[-1])x--$i))})(*F)))+\z(?{push@a,\@b})(*F)~s;@a} ``` [Try it online!](https://tio.run/##bU9Lc4IwEL7zK7ZOHJISChHtQUQ5tL33nCADKCMdUAZ0auvjr9MA0o7aHJJv93tsNl8W6aiqyl0I8SH7cgMbf2yStarSLMghWhXU9Ylzzs5zjJ80gmd4dkC@gwY2SpzSEHtmCNOw2ecqSZcocqRD01BCa8o0xTuKxOuxfaSulhp8LkzPOB4fcLqJgtQNHeyGFDMNhVxnHtnrOkoIORH8@EYI0cS3nJnvypUbUOGGbf9c2m5wqnblEl6CbTAev@yyHNSFvFVbyYtkvY2h19dHoxIcx5lCvxTrHgUF5EH@BdRyiKFe9QBlniZbUKlKpQBOYMwFx1wsqKcR4RlKvCkuml4TNZmA6sthnNEBZR7oU@DcpKbEFCRgEngKlxy1bhQt2aga2CqbnNusuvOnHHQFuxSN7bk1SDyUTasLqLkuqsu36PDqHw0xrD0y7I5o2v852q9av8TVDtbtrh1xt1pNeIqvKNUP "Perl 5 – Try It Online") With newlines for readability: ``` sub f{ my@a; (join'',map chr,@_)=~ m~^((.+)(?(?{ $_=$2; $i=s/\x1/\0/; 1while$c=chr++$i,s/\x00\Q$c\E|\Q$c\E\0/\0/; /[^\0]/||!(local@b=(@b,(1+$b[-1])x--$i)) })(*F)))+\z(?{ push@a,\@b })(*F)~s; @a } ``` Regexen as solution to any problem, but this one turned out somewhat long, therefore just for sake of completeness. Kind of seed-fill problem in 1-D. Last minute improvement was to number rolls from 1, per recent comment to OP. Otherwise (to number from 0) it was plus a few bytes. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 184136 bytes ``` (),&'*+(?,/{$[#*y:,/-1 1,/:'&'&/'(x:(x;y))=/:{|'y}\(0,/:-1_')'1|:'\(x+1;~y) {(@[;+/y;+;1]'x)_\:*|y}[x]'y &/*|x;,x;()]}.')/,1(1=)\(), ``` [Try it online!](https://ngn.codeberg.page/k#eJxFjkEOgzAMBO+8IlIrbIdQ1w3qIRFq/wGIG29IROjbG6CUk3d215Ynh2RK0BW+DM/X7qKjM1yLEsMOSigZMDgMPhK17OYEcenxnsNaRiCQ5KDHUIn/RCqUmvHd+Yqjr7wMEGjsnU5x6cIAMccl6xS8CR5pWG5AbASlpT4/URQToKiHktxbh7IHbO4Jz3U0me3POTpWNXtkV1zlJnZ3P2LP7n8t+/QFQ+w0LQ==) A beast! First, turn input into a single list of a list of singletons. This forms the initial list of partitions. Recursively search all such lists for indices which contain a singleton with value > 1 and whose neighbor to the right or left has a maximum value 1 less than the value of the singleton and either have length > 1 or have length 1 and a value equal to 1. Merge each such singleton with each such neighbor to form the next set of partitions. [EDIT: same idea but only keep the length and the highest value of each sequence. These are always the same except for singletons with value > 1. I.e. those values waiting to be merged.] ]
[Question] [ **Input:** Ten unique integer coordinates, between `(0,0)` and `(100,100)`. **Output:** The coordinates arranged in the order/an order such that a path drawn between the coordinates in that order is the shortest path possible. This is code golf so the shortest code wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes ``` MinimalBy[ArcLength@*Line]@*Permutations ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczLzM3McepMtqxKNknNS@9JMNByyczLzXWQSsgtSi3tASoND@v@H9AUWZeib5DmoNrcka@g5@DslpdcHJiXl1QYl5Kfq5nXklqempRdLWBjqGBQa1OtamOuY5Rbex/AA "Wolfram Language (Mathematica) – Try It Online") (7 points) Times out for longer inputs. Accepts a list of points with *approximate-number* coordinates. To accept exact (`Integer`) input, **+3 bytes**: ``` MinimalBy[N@*ArcLength@*Line]@*Permutations ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczLzM3McepMtrPQcuxKNknNS@9JMNByyczLzXWQSsgtSi3tASoOj@v@H9AUWZeib5DmoNrcka@g7JaXXByYl5dUGJeSn6uZ15JanpqUXS1gY6hgUGtTrWpjrmOUW3sfwA "Wolfram Language (Mathematica) – Try It Online") This is because `MinimalBy` uses Mathematica's canonical ordering, which compares objects structurally, rather than numerical ordering. Thus, for example, `3` is "less than" `1+Sqrt[2]`. This is only an issue when using exact numbers, where the length can include `Sqrt`s. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes *Edit: -1 byte thanks to a [tip](https://codegolf.stackexchange.com/a/218055/95126) from Leo* ``` ◄oṁ√Ẋδṁo□-P ``` [Try it online](https://tio.run/##yygtzv7//9H0lvyHOxsfdcx6uKvr3BYgM//RtIW6Af///4@ONtYxjNUBkkZA0lDHAEgagUkDsIgBWNZIxxgsaxwbCwA "Husk – Try It Online") (with only 8 points to avoid timing-out...) **How?** ``` P # from all permutations of the input ◄o # get the one that minimizes the result of ṁ√ # sum of all the square roots of Ẋ # applying to all adjacent sets of coordinates δṁo # sum of all the □- # squares of the differences ``` [Answer] # [Haskell](https://www.haskell.org/), ~~107~~ 100 bytes ``` import Data.List f=head.sortOn(sum.(zipWith(\(x,y)(m,n)->sqrt$(x-m)^2+(y-n)^2)<*>tail)).permutations ``` [Try it online!](https://tio.run/##HYo7C8IwFEZ3f4VDh3s1DX2stpOj4OjgAwK29GKSxuQWWv98DFnOd/g4kwqfQesYybjZ8/6sWMkLBd6N3TSotwzpvVoIi5HwI3cjnuABq9gQjLBY9uHruYC1NPhqjrCVNi2eDj0r0ojSDd4srJhmG6JRZDvnyXIx3qESNQpoRZPYiDazSqyz19nb3FSpecY/ "Haskell – Try It Online") *-7 by @xnor and @benrg* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` œΣü-nOtO}н ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6ORziw/v0c3zL/GvvbD3///oaAMdBYNYHQUQbQiiDRF8IxBtBOUbIviGUNooNhYA "05AB1E – Try It Online") Times out on TIO with 10 coordinates. **Commented**: ``` œ # all permutations of the coordinates Σ } # sort on ... ü # for each pair of adjacent coordinates ... - # take the element-wise difference nOt # Euclidean norm for each difference (square, sum, square root) O # sum all distances н # take the first element ``` [Answer] # JavaScript (ES6), 124 bytes Processing 10 points on TIO takes about 35 seconds. ``` f=(a,X,Y,d=m=1/0,p=[])=>a.map(([x,y],i)=>f(a.filter(_=>i--),x,y,1/d&&d+Math.hypot(x-X,y-Y),[...p,[x,y]]))+a?o:d>m||(m=d,o=p) ``` [Try it online!](https://tio.run/##dY3BasMwEETv/Yo9BW2zUqxry7r4A3pPMCIskd04WJZQTIjB/@64PhZ6nDfDm5s85H7JXRr1EH2zLC0roSOdyHNgeygoce2QSzFBklL1kyZH3QpaJabt@rHJ6sxlpzXS2pE9@N3O779lvJrrlOKonvpIkz4h1caYRJvBIe7lK374MsyzCuwpcsKlAobfVZWzTMoW6LbXM3AJNWzOLIOPQSG8gy0szFDQfwU4/Hy7xOEe@8b08UdVf3K7Elxe "JavaScript (Node.js) – Try It Online") ### Commented A recursive function that tries all permutations of the input points, computing the length of the path for each of them and keeping track of the shortest one. ``` f = ( // f is a recursive function taking: a, // a[] = input X, Y, // (X, Y) = coordinates of the previous point d = m = 1 / 0, // d = total distance, m = minimum distance // (both initialized to +Infinity) p = [] // p[] = current path ) => // a.map(([x, y], i) => // for each point (x, y) at position i in a[]: f( // do a recursive call: a.filter(_ => i--), // with the i-th entry removed from a[] x, y, // using (x, y) as the previous point 1 / d // set the distance d to 0 if this is the 1st point && // otherwise: d + // update d by adding Math.hypot( // the Euclidean distance between x - X, y - Y // the points (X, Y) and (x, y) ), // [...p, [x, y]] // append the point (x, y) to the path ) // end of recursive call ) // end of map() + a ? // if a[] is not empty: o // just return o[] : // else (complete path): d > m // unless the new distance is greater than m, || (m = d, o = p) // update m to d and set the output o[] to p[] ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 213 bytes ``` l->{double d=1e9,e;var r=l.clone();for(int i=0,z,x[]=new int[10];i<10;)if(x[i]<i){var t=l[z=i%2*x[i]++];l[z]=l[i];l[i]=t;for(e=z=i=0;z<9;)e+=l[z].distance(l[++z]);if(e<d){d=e;r=l.clone();}}else x[i++]=0;return r;} ``` [Try it online!](https://tio.run/##jVJLj5swEL7nV8ylkllYC/a2axypUrVqD5Wq5og4eMFknRobGZMHEb89HRMSrdoeesL@5nvMDN6JvXjc1b8uqu2s87DDOx280vSBrf7CmsFUXlnzZ1EcPN1K2wa80qLv4btQBs4rgG5406qC3guPn71VNbRYIxvvlNkWJQi37aOZCvC6@Oc/rDL@6UtRJvfTGhp@0Y/rc23RUkLNM/mcSLYXDhzXtNLWSBKxxjqCElA8TcbkWJTcyAMgUmRpyVSepSxSDTkWqsxVdA5yz3UxcvXp6SGgcVwyvJcIqnBSJfezq@RI4ikb82cWyTiISlorHM1UkugijscyYugt8zo611yyj31Nk9S9BEzAAHRx0g/OgGPThc3Dz4MIU9sWOISef84XlN7LXVhGv5S/iv59I/1tV@sb8fCucD3kyqW9GjEdcsjS25Zh8aGirklwWhzoq7bCk2sP1Mij/2Y8ydIsSuAfYLTkTff2hHPihN0t9t5@DgC5/8KXF0xbVJtT72VL7eBphy/Ba0NmdpBd3waZ7aIP4zvZD9pjQENF1@nTwvhvw6v@6jitpstv "Java (JDK) – Try It Online") It takes roughly 1 second to process. ## Explanations This is basically the [iterative heap's algorithm](https://www.baeldung.com/java-array-permutations#2-iterative-algorithm) with the distance computation and comparison integrated, because there are no native way to get permutations and because recursion in Java is expensive, byte-wise. I'm using `java.awt.geom.Point2D` which has a `distance(Point2D)` method but it's not reflected in the code since I try by all means to avoid writing such a long class name to spare bytes. This is why I use `l.clone()` twice and `var t`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` Œ!ÆịạƝSƊÞḢ ``` [Try it online!](https://tio.run/##y0rNyan8///oJMXDbQ93dz/ctfDY3OBjXYfnPdyx6P///9HRBjqGsTrRxjpGQNJIxxhMGgBJQzDbEMw2BqsxAKqJBQA "Jelly – Try It Online") Test case is 8 points arranged into a pseudo-regular octagon. TIO times out on 10 points, but the program should work in theory. ## Explanation ``` Œ!ÆịạƝSƊÞḢ Main monadic link Œ! Permutations Þ Sort by Ɗ ( Æị Convert to complex numbers ạ Absolute difference Ɲ of each neighboring pair S Sum Ɗ ) Ḣ First element ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~, 135 bytes Saved **3 Bytes** due to a suggestion from Noodle9 to use `lambda` instead of `print`! ``` lambda a:min(permutations(a),key=lambda p:sum([sum([(p[i][j]-p[i+1][j])**2for j in 0,1])**.5for i in range(9)])) from itertools import* ``` Essentially, this program loops through all possible `permutations` of the path and prints the path with the minimum length. The `key` argument of the `min` function is a `lambda` function that calculates the sum of the "distance" between consecutive points in `p`. [Try it online!](https://tio.run/##nY1NbsIwEIX3OcXssNMB2SapHKT0ImkWrkiKAf/IHhacPrURJ@jme6NPT2/iky7Bq20dv7e7cT9nA@bkrGdxSe5BhmzwmRmOt@U5vgvxlB@OTS@wONl5us77kh@yXrxt1RoSXMF6ECirOPTV2GqS8b8LG/jMebOm4MDSkiiEewbrYkjUbgQjTEyg4MgUdoUSVWGHn4U96kKNQ@GA6lUSqGpNC9THmhJ1x@cml6GVEW9isp6AEHaw/4IdQt7e@xLFof/vhz8 "Python 2 – Try It Online") ]
[Question] [ ~~Write a program that outputs the number 0.~~ That's a bit trivial, isn't it? Let the length of your program be \$S\$. Write a program that outputs the number 0. When your program is cyclically shifted \$i < S\$ bytes left, it should output \$i\$. To cyclically shift a string \$i\$ bytes left means to move the last \$i\$ bytes (including newlines) to the front, without changing the order. For example, if your code is `ABCD`, then `ABCD` should output 0; `DABC` should output 1; `CDAB` should output 2; `BCDA` should output 3. ## Rules * Your program must be at least **3** bytes long. * "Output" represents any acceptable output: on the stack, to STDOUT, as a return value, as an exit code, etc. * Your program is to not take any form of input. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 3 bytes ``` .++ ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fT1v7/38A "brainfuck – Try It Online") **how it works**: it's really simple, actually. The internal memory is initialized at 0 so we output (with `.`) the original cell and we get 0. By shifting the program, we are shifting memory increments (done with `+`) to before the output, so each byte shifted corresponds to one more increment, and hence we increase the counter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ‘n¬ ``` The implicit input of a Jelly program is `0`: **[Try `‘n¬` online!](https://tio.run/##y0rNyan8//9Rw4y8Q2v@/wcA "Jelly – Try It Online")** `0` incremented \$\neq\$ not(`0`) \$\implies0+1 \neq 1 \implies 1\neq 1 \implies 0\$ **[Try `¬‘n` online!](https://tio.run/##y0rNyan8///QmkcNM/L@/wcA "Jelly – Try It Online")** not(`0`) incremented \$\neq\$ `0` \$\implies1+1\neq 0 \implies 2\neq 0 \implies 1\$ **[Try `n¬‘` online!](https://tio.run/##y0rNyan8/z/v0JpHDTP@/wcA "Jelly – Try It Online")** (`0` \$\neq\$ not(`0`)) incremented \$\implies(0\neq 1)+1 \implies 1+1 \implies 2\$ [Answer] # [Keg](https://github.com/JonoCode9374/Keg) `-hd`, 3 bytes ``` 210 ``` [Try it online!](https://tio.run/##y05N///fyNDg////uhkpAA "Keg – Try It Online") # How? Keg only outputs the top item of the stack. These individual digits push themselves onto the stack. So for every cyclic shift, it outputs the character code of the top of the stack. ``` Program -> Stack -> Output last item 210 -> [2, 1, 0] -> [0] 021 -> [0, 2, 1] -> [1] 102 -> [1, 0, 2] -> [2] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes Right-shifts instead of left-shifts. ``` >>g ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fzi79/38A "05AB1E – Try It Online") ## Explanation ``` >>g : >> Increment empty string twice g Find the length of the empty string (0) >g> : > Increment empty string g Find the length (0) > Increment that (1) g>> : g Find length of empty string (0) >> Increment twice (2) ``` ]
[Question] [ The [Dihedral group \$D\_3\$](https://en.wikipedia.org/wiki/Dihedral_group_of_order_6) represents the symmetries of an equilateral triangle, using the identity (represented by `id`), rotations (represented by `r1` and `r2`), and reflections (represented by `s0`, `s1`, and `s2`). Your task is to compute the composition \$yx\$ of the elements \$x, y \in D\_3 \$. They are given by the Cayley table below: ``` x id r1 r2 s0 s1 s2 y +----------------------- id | id r1 r2 s0 s1 s2 r1 | r1 r2 id s1 s2 s0 r2 | r2 id r1 s2 s0 s1 s0 | s0 s2 s1 id r2 r1 s1 | s1 s0 s2 r1 id r2 s2 | s2 s1 s0 r2 r1 id ``` ### Input Any reasonable input of `x` and `y`. Order does not matter. ### Output `y` composed with `x`, or looking up values in the table based on `x` and `y`. ### Test Cases These are given in the form `x y -> yx`. ``` id id -> id s1 s2 -> r1 r1 r1 -> r2 r2 r1 -> id s0 id -> s0 id s0 -> s0 ``` ### Notes on I/O You may use any reasonable replacement of `id, r1, r2, s0, s1, s2`, for example `1, 2, 3, 4, 5, 6`, `0, 1, 2, 3, 4, 5`, or even `[0,0], [0,1], [0,2], [1,0], [1,1], [1,2]` (here the first number represents rotation/reflection and the second is the index). [Answer] # [Python 2](https://docs.python.org/2/), 27 bytes ``` lambda o,O:[o[_]for _ in O] ``` [Try it online!](https://tio.run/##VZDdioMwEIWvzVMcvKqQguZScF@hD5AGsZiwQquS2KKUPrudidtuezPMfJwzf@My/Q69Wl11XM/N5dQ2GOSh1IOujRs8anQ9Dmbtm4sNqKDTrk0lUl/EqDiGPMZIgkqNYPHUnM6WDHeRsKWEziUKCWUkEbIT4VIi34hiwiXJIqG2myZ/uULx10e9NS8Xy4x4CNFaB29v1gdb8x67MStFwqdwxdfEU4glncN7U82ZQVVhLMk/Xf0mFIKt86ePwfLVaPRdP2GWWOgD@x/6w9cGbvc/ZjbyY@hismx9Ag "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ị ``` A dyadic link taking y on the left and x on the right. Uses the representations of the fist three natural numbers transformed as their actions describe: ``` name: id r1 r2 s0 s1 s2 value: [1,2,3] [2,3,1] [3,1,2] [2,1,3] [1,3,2] [3,2,1] (action: identity rot-Left rot-Right swap-Left swap-Right swap-Outer) ``` A port of [Jonathan Frech's Python answer](https://codegolf.stackexchange.com/a/171966/53748) `ị` is Jelly's "index into" atom, and it vectorises; note that Jelly is 1-indexed. **[Try it online!](https://tio.run/##y0rNyan8///h7u7///9HG@sY6hjF/o820gGyYgE "Jelly – Try It Online")** Or see [a table using the question-names](https://tio.run/##y0rNyan8///h7u7/h5c7HN6XkOnwqGkNCDXuAAq6//8fHW2oY6RjHKujEA2kdAxBDCClYwQRMYRIASmICJACqon9H62UmaKkowAESkWGMIYRlFFsAGPApIqNlIBULAA "Jelly – Try It Online"). --- To take x on the left and y on the right, these values may be used instead: ``` id r1 r2 s0 s1 s2 [1,2,3] [3,1,2] [2,3,1] [1,3,2] [3,2,1] [2,1,3] ``` ...[see here](https://tio.run/##y0rNyan8///h7u7/h5cf3peQ6fCoaQ0INe4Airn//x8dbahjpGMcq6MQbawDZIIYQL6OIYhhCGQYQaSMICJACqg49n@0UmaKko4CECgVGcIYRlBGsQGMAZMqNlICUrEA "Jelly – Try It Online"). [Answer] # JavaScript (ES6), 39 bytes Uses the following mapping: ``` id | r1 | r2 | s0 | s1 | s2 ----+----+----+----+----+---- 2 | 0 | 4 | 1 | 3 | 5 ``` Takes input as `(x)(y)`. ``` x=>y=>'450123234523012323'[(x*51^y)%18] ``` [Try it online!](https://tio.run/##JcrdCoMgHAXw@z3F/2aow0VqwmAY1GuIg@hjFC1Dx9Cnd2Q3hx/nnKX7db538/69b3YY06RSUHVUNapkybjgopJcnEIah5tkr0iu7GFSAwo0cAolhYoCoyAoSDDPS5sX5BiigHx55Dxk58bxbI6Ob283b9exWO0bN8Wn23EEVcPJcLDVEw4ER2IIIekP "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 20 bytes Using [Jonathan Frech's I/O format](https://codegolf.stackexchange.com/a/171966/58563): ``` x=>y=>y.map(n=>x[n]) ``` [Try it online!](https://tio.run/##JcrdCoMgHAXw@z3F/2aow0VqwmAY1GuIg@hjFC1Dx9Cnd2Q3hx/nnKX7db538/69b3YY06RSUHVUNapkybjgopJcnEIah5tkr0iu7GFSAwo0cAolhYoCoyAoSDDPS5sX5BiigHx55Dxk58bxbI6Ob283b9exWO0bN8Wn23EEVcPJcLDVEw4ER2IIIekP "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~27~~ ~~26~~ 23 bytes ``` lambda x,y:(y+x*5**y)%6 ``` [Try it online!](https://tio.run/##Rc2xCoMwFIXhuXmKQ6Cg6R00rR0EnyTNkGJDBY0SbUmePsU4dPk5wwdnidt7djLZ7pFGMz17g0CxLeIliEaIWJ7vyZnptaKD4kPPCXyt9vo671wv85Zcs68ZP4euCJJwI9SEK6HRjNnZI2JwOFTLTosf3AaVL5QtAiGWGrsLf6fTDw "Python 2 – Try It Online") Edit: Saved 3 bytes thanks to @NieDzejkob. Uses the following mapping: ``` id | r1 | r2 | s0 | s1 | s2 ----+----+----+----+----+---- 0 | 2 | 4 | 1 | 3 | 5 ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 3 bytes ``` +.× ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Cktt7h6f//Z6YAmY86ZujZPupd8ah3s7HCo@4WhSJDoKjho569mSkQvhGQb4TgFxuAdCG4MOXFBhA@THmxAZc7kAlUVmQINASoD6gWKM2lnpmirqBeZAgijIBEsQGIAHGLjdSj3YEOedTbCXJWGtBZ7rEA "APL (Dyalog Classic) – Try It Online") `+.×` is matrix multiplication we represent the group as ``` id r1 r2 s0 s1 s2 1 0 0 0 0 1 0 1 0 0 0 1 0 1 0 1 0 0 0 1 0 1 0 0 0 0 1 0 1 0 1 0 0 0 0 1 0 0 1 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0 ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 1 byte ``` @ ``` [Try it online!](https://tio.run/##y9bNS8/7n2aloeCgoPk/ITMlocgwocgoodggodgwodjIoVpLLb0uxqqiVl1dO10hTd8qxirdSsNAwVDByBqIFQysgVjBEEgaAtlADBQHYgVDzf//AQ "K (ngn/k) – Try It Online") `x@y` is list indexing, which is the same as composition of permutations; we represent the group as ``` id:0 1 2; r1:1 2 0; r2:2 0 1; s0:2 1 0; s1:1 0 2; s2:0 2 1 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes Uses [Jonathan's I/O format](https://codegolf.stackexchange.com/a/171966/58974). ``` gV ``` [Try it online](https://tio.run/##y0osKPkfYhsdYqhjpAPEIUZAliGQBPOArNjDm4w10zUCbJUyU4oMi4yKDYoNi42UDm/STArlCkkPSAr7nx72PyA9JCk1/L9SkaESlxJQGgA) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~24~~ 19 bytes ``` (x,y)=>(y+x*5**y)%6 ``` [Try it online!](https://tio.run/##Jc1LCoMwGATgfU8xm5LE/hVNazclgl5DXAQfRbFGklLM6VNMN8MHMzCz/mrX2Wn7XFfTD2FUge/khSq5v@xJkSRenB@hgkKDjCAJd0JOuBEKtM9THRs29YzAXHakzaNjWhkt2bHtzOrMMqSLefEqfeuNe6gSf@4H62aM960QIvwA "JavaScript (Node.js) – Try It Online") Edit: Saved 2 bytes by switching to `**` and 3 bytes thanks to @NieDzejkob. Uses the following mapping: ``` id | r1 | r2 | s0 | s1 | s2 ----+----+----+----+----+---- 0 | 2 | 4 | 1 | 3 | 5 ``` The old 24 byte version also works in old versions of JavaScript: ``` (x,y)=>(y%2?y+6-x:y+x)%6 ``` [Answer] # [Racket](https://racket-lang.org/), 42 bytes ``` (lambda(x y)(modulo(+ y(* x(expt 5 y)))6)) ``` [Try it online!](https://tio.run/##HYvNCoAgEAbvPcUHXXbrFFTvs6WGtP1gBvr0Jh1nhgmy7jaWVuXcEH5oyFjnTwtXSOVYjFBCZjou8@pFPTJ1SGTTHTHVwDwzF27q559bJYMcRgxVfg "Racket – Try It Online") A boring port of Neil's Python answer. Uses the same I/O format, so: ``` id | r1 | r2 | s0 | s1 | s2 ----+----+----+----+----+---- 0 | 2 | 4 | 1 | 3 | 5 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes ``` Mod[#+#2*5^#,6]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d83PyVaWVvZSMs0TlnHLFbtf7ShjoJJbOx/AA "Wolfram Language (Mathematica) – Try It Online") Another boring port of Neil's answer, this time in Mathematica. It is an anonymous function that takes arguments in the order `[y, x]`. Here’s the input representation: ``` id | r1 | r2 | s0 | s1 | s2 ----+----+----+----+----+---- 0 | 2 | 4 | 1 | 3 | 5 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` è ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/171972/52210), but with 0-based indices, so the representations are: ``` id r1 r2 s0 s1 s2 # Original values [0,1,2] [1,2,0] [2,0,1] [1,0,2] [0,2,1] [2,1,0] # Values instead ``` [Try it online](https://tio.run/##yy9OTMpM/f//8Ir//6ONdAx0DGO5og11gKxYAA) or [verify all possible combinations](https://tio.run/##yy9OTMpM/W90eO7RyYdWllWGHlpXplRhq2Qf4WKvZK1QCWRVAlkKj9omKSjZ/z@84r/OfwA) or [verify all mapped back to ids](https://tio.run/##yy9OTMpM/a/0qGFOZkqxYbFBkWGRUbERkGt0eEvxoXVexV7Zh1cohXEZHZ57dPKhlWWVoYfWlSlV2CrZR7hE6oXZK1krVAI5lRCOwqO2SQpK9v8Pr/gP5Ov8BwA). **Explanation:** ``` è # Index the second (implicit) input-list vectorized into the first (implicit) input-list # And output the result implicitly ``` ]
[Question] [ According to [this question](https://codegolf.stackexchange.com/questions/166999/execute-a-superb-shuffle) a Superb Shuffle™️ is defined as a full deck of cards (including jokers) which follows this set of rules: * 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 cards are expressed as a value(A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K), followed by a suit (C, D, H, S). For example 'AS' is the Ace of Spades. The Jokers are represented by a single letter J. * Write some code to indicate if an array of cards is a Superb Shuffle™️ or not. * Use any language you like. * Attempt to do so in the smallest number of bytes. Test cases: 1: This is Superb™️ ``` [ "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" ] # true ``` 2: This is all sorted ``` [ "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" ] # false ``` 3: Aces together ``` [ "AC", "AS", "AD", "AH", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "9S", "KD", "4C", "6S", "10D", "3S", "7D", "JH", "J", "4D", "8H", "QC", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C", "5S", "3H", "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H", "8C", "10S", "5C", "7S", "JD", "2C", "4S", "8D", "7C", "QH" ] # false ``` 4: Crazy 8's ``` [ "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S", "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "4D", "AH", "QC", "AD", "5H", "9C", "JS", "2H", "6C", "QD", "3C", "5S", "10S", "9D", "KH", "2S", "6D", "10H", "J", "3D", "7H", "JC", "KS", "4H", "5C", "7S", "JD", "2C", "4S","QH", "8D", "8S", "8C", "8H" ] # false ``` 5: Also superb ``` [ "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", "J", "5H", "8S", "KH", "3D", "8C", "JD" ] # true ``` 6: Ace by 2 ``` [ "AS", "2S", "6H", "9S", "AC", "4D", "9C", "QD", "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", "J", "5H", "8S", "KH", "3D", "8C", "JD" ] # false ``` 7: Ace by King ``` [ "AS", "KH", "2S", "6H", "9S", "AC", "4D", "9C", "QD", "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", "J", "5H", "8S", "3D", "8C", "JD" ] # false ``` 8: Jokers together ``` [ "AS", "5D", "9H", "KC", "2D", "6H", "10C", "QS", "3H", "7C", "9S", "KD", "4C", "6S", "10D", "AC", "3S", "7D", "JH", "J", "J", "4D", "8H", "QC", "AD", "5H", "9C", "JS", "2H", "6C", "8S", "QD", "3C", "5S", "9D", "KH", "2S", "6D", "10H", "3D", "7H", "JC", "KS", "4H", "8C", "10S", "AH", "5C", "7S", "JD", "2C", "4S", "8D", "QH" ] # true ``` 9: Adjacent suit/value separated by Jokers ``` [ "AS", "6H", "9S", "AC", "4D", "J", "4H", "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", "QD", "7S", "QH", "2D", "7C", "10D", "8C", "5H", "8S", "KH", "3D", "9C", "JD" ] # true ``` [Answer] # JavaScript (ES7), 88 bytes Returns **true** for Superb™️ or **false** for Ugly™️. ``` a=>a.every(r=s=([a,b,c])=>!s|!b|!((r-(r='34567891JQKA'.search(a)))**2%13<2|s==(s=c||b))) ``` [Try it online!](https://tio.run/##xZTLauMwAEX3@QonMNQuadr4LRgXTLIQ9sp4WbpwPM60Q2gGuy0U/O9pfG9UCfogHaZ048WNpEjnXOlP9Vh1dXv79/7sbvur2a2TXZVcVrPmsWmf7DbpEvuqmq6m9bWTXI67frzqx7bdnu1/OvH8IIxiMc@KPD2ZdU3V1jd25TjO6an7Y@79dPsuSewuqft@tU939fau226a2Wb7217bVyPLmqTlZGpNguXwFXL45ovh6yIJkcwvEBUY6iGKkIghGVbJMdpHGJacgyhF5CGKkGSYn2E8glgeFikwNkUYYJRAkmG2iyREEiMpMNJDEqidCIQ5BrsYFi65H/2/HpKIAabnGOmrncQLTkGaYlyAKEKSYb6LxEcSIynkZHTtONb5uXXfPjSj0bu8uTNi4QpBqdnxX3hIURpbIQl6yNWJCYy@eDJypVOenui5S7E0/PAoJAmJWFFq4NTtSy2FnSC9WOreKMLygEJpwIoLTYzC2BVSpVRWiujFwugdFbEdKOewYkabive62nTvAGerSt2tg9BjK49WlS@A3mr5Z/r9T82mhq/p9zHNphuj3x/w/vYHZfD7uffkNW@y@W/AP2J8uCsETf/0Ex@Pm1jZUhIiCmEcj5uPpKHeVbcpWBpacqPTvOAkRj48PU/Jm@S/oJLaKtXREEUQuMIrNSXCidXrw7qwFVRPwxRJYZSS6aeJaAvF2zVaq146XQNCplKqI/C9GfP93j0D "JavaScript (Node.js) – Try It Online") ### How? Each card is split into 3 characters **a**, **b** and **c**, some of which might be *undefined*. The rank is given by the position of **a** in the string **"34567891JQKA"** (**'2'** gives **-1**). The suit is given by **b** for all cards but 10's, for which we need to test **c** instead, and *Jokers* that have an *undefined* suit. We keep track of the previous rank in **r** and the previous suit in **s**. We use the expression \$(r - new\\_rank)^2 \bmod 13\$ to detect invalid consecutive ranks. This gives: * \$0\$ if both ranks are equal * \$1\$ if the absolute difference between the ranks is \$1\$ * \$1\$ if we have an *Ace* followed by a *Two* or a *Two* followed by an *Ace*, because the squared difference is \$144\$ and we have \$144 \equiv 1 \pmod{13}\$. * an integer greater than \$1\$ in all other cases We simply compare the new suit with **s** to detect identical consecutive suits. We use the expression **!s | !b** to detect that either the previous or the current card is a *Joker*, in which case the results of the other tests are discarded. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 68 bytes ``` .*,(.*) $1,$& J\b -- 10 T \b\w $&$& T`Ao`2-9TJQKA`\b. (\w).{2,4}\1.* ``` [Try it online!](https://tio.run/##zZTNauMwGEX3eo60pOHGNI4dW0sjQYW8MsrSi0ygi25aKIUuSp89PVZnCs10ZvoDQ1cBxfruOVeWby/vrq5/HE7mF7tDsdC8WJyZ2UqzUxPHvVkuzercbM24H@/N7JTV7a672ZVLu41D3@3GfWHm4/1Z8VCqehxXxeJw6JJqLxvUO5Vem6DVudOQtA5qnGxS71U5bRJ/eHVO66TGKwZFVV5t0ODUedVB1ikmlUEbpzZp8Fo71UnWqw8qkzaeIdPGtVfDr1OfVAW1jvWkLqh2apKiV@lUJbVeQzAwsplcVhgHCs8QYFPeRia8TIICBWbDhRRpgDLC@szOVJDQIQdIBIkGG2dgELHhGQ@lMBEjCwYO@AOGFY3Aal0uCXzU6S0qGp7tMsEk8Wahx1W@1eNfSgT3vT3@XiLczz1@6ay7P5z1C@MU/k/IIzqqBhBT4NvMCBcopBNp83SmNSFPZ0/tM3afG6Q2MEgnjQQIGYkhUojADjCQmS1MAKQTRwE444kaPjiAHSe6JhOVubL80kyy0OGEB4zRHzPmff8LkTaOEVv3itH@Yvz8WX/6Zn/4XvfuJ@Z3/vbkw7D5Xn/HO/ME "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `0` if superb, `1` if not. Explanation: ``` .*,(.*) $1,$& ``` Copy the last card to the beginning to simulate wrap-around. ``` J\b -- ``` Replace the jokers with two-character placeholders, which is enough to ensure that the surrounding cards aren't matched with each other. ``` 10 T ``` And replace the `10`s with tens. ``` \b\w $&$& ``` Duplicate the rank of each card. ``` T`Ao`2-9TJQKA`\b. ``` Calculate the adjacent rank. ``` (\w).{2,4}\1.* ``` Look for adjacent cards of the same suit or same or adjacent rank. [Answer] # Java 10, ~~246~~ ~~210~~ ~~205~~ ~~178~~ 170 bytes ``` d->{var r=1>0;int p=-1,P=p,q,u;for(var c:d)r&=p<0|(u=(p-(p=(q=c.length())<2?-1:"A234567891JQK".indexOf(c.charAt(0))))%12)<-1|u>1&P!=(P=q<2?p:c.charAt(q>2?2:1));return r;} ``` [Try it online.](https://tio.run/##7Zddb6JAGIXv@ytmTbaBBKkgfqDFhmg2BLLdGvZus4kUaGtrERGbbdr@dhffY2SK2jWu3exFvSDhzDDOnOfMO3DrPXjl2@Bu7o@86ZR99YbR0xFjwygNkyvPD9n54paxy/F4FHoR8wU3TYbR9Y@fLBDbWdPLUXaZpl469Nk5i5jB5kG58/TgJSwxlE6lnQ3FYqOsSBdGLE2kWftqnAiLZr8ViMmxEZ9WnoWZIcRlITaEieHLozC6Tm8EUTxVz8pKq2SqVa1WbzR1xe47JXkYBeGvb1eCL/s3XmKmQkXMfp8VVTwtK8@zjnJ88ckQLoxJ9njcWvWadNQztaWIYjsJ01kSsaT9Mm8vZh/PLkfZ7JeLeBgPA3af@ZCv1BNhwskJ@57M0pvH1uo2nKbM96YhU6ClmSCUTLcksVKtt7jq1uLqdBdXlZQ6KUqFpD51rZLUIEVfKDQY/UoOPaRRW93FoySZJFVJapBi0zA29Sehab0eq0@PmNRWo846KTYNopJSJ6VJSp96VkmpFealU5tDz6jUu97D7PJZVElpQKBRHOqpFebV7OJJajSpe42kBik2DaOSopHSJKVvlSiEBRa1dRbwXHdz32AQlo9lYhENi5sK/SU3z1qPQwcw8L9p5TbCLpiBRWNFWtFAKw8A8IIiIAFGzeUshXcwhgzgU9LNc4SUIAxgDaYgZq8ALN3tF2AgpY0uFzU7DwyCAezAC3gZI45FMvTvHolGiw20nmRLmjVgXhSwgb646/cGOzPiJrwF0SEJHRLQ/nyQyJzP23hAYBsf/U98bMkeHLJ6/XXxWlUwvkRYufX7FDA@I27u9tb69VbpOmTlch@naXgvj2epHGfnTTqKBJGOJQL1xRtNw03njbpe47AIWIr/wkLhO@YDV3SXmzSsA0mnUKJgNMDDEGxJhAN@gR6Wpff4otHLCTiFcgWnwAvxwQYHU2QM3oO7bvFHi7UqW@DHD9zNDcc2R/gABdFAUkFO73JxBmdkzCmU/mUwN5031VcskFA3z@kyFbvuJ74AuXkV27CH9jj69zr0QehfHP27bB3Q23L0a//la5j5umbsXsTWUcCod2Lxlv3L/QYGCArQNXkSZnCbfTVkr/wmHfZqdrqYrqRuOO2Bgofz8Xb8jm/HBTAOwDjddTDAADw6V7o@9sth9wv/5UwfnQQBH52yLLMg9O@WH54b3hEi2Reox3Ksl/lv) **Explanation:** ``` d->{ // Method with String-array parameter and boolean return-type var r=1>0; // Result-boolean, starting at true int p=-1, // Previous value, starting at -1 P=p, // Previous suit, starting at -1 q,u; // Temp integers for(var c:d) // Loop over the cards of the input-deck: r&=p<0 // Validate whether the previous value is -1 |(u=(p- // Or if the difference between the previous and current value, (p= // where the current value is: // (and replace the previous with the current value for the next // iteration at the same time) (q=c.length())<2? // Is it a Joker: -1 // Use -1 : // Else: "A234567891JQK".indexOf(c.charAt(0)) // Use 0-12 depending on the order ))%12) // (Modulo-12 for 'A' and 'K') <-1|u>1 // is more than 2 &P!= // And the previous and current suits are not equal, (P= // where the current suit is: // (and replace the previous with the current suit for the next // iteration at the same time) q<2? // Is it a Joker: p // Use -1 : // Else: c.charAt(q>2?2:1)); // Use the suit-character // where the `q>2?2:1` is for cards of value 10 return r;} // Return if all validations inside the loop have succeeded ``` [Answer] # [Python 2](https://docs.python.org/2/), 108 bytes ``` lambda l:all('J'in(a,b)or(q(a[0])-q(b[0])+1)%13>2<a[-1]!=b[-1]for a,b in zip(l,l[1:])) q='234567891JQK'.find ``` [Try it online!](https://tio.run/##7ZZLb9pAFIX3@RXuorKtkiq2MfagUgnBwrJXiCVlYZSiWHLNQ1RV@@dpOB@ESaoQ@oxUZTOWju4w937nzIjl183Nogm3896HbV1@ml2XTt0t69pzc7dqvLI18xdrb@WVk6upf7nyZrvvm8B/HUTvw3fl5DKYvurNdp/5Yu3cljtV43yrll7dqidBd@r7F6ueG0btuJOkJshHhft2XjXX2y83Vf3RCbrLddVsnLlXNcvPG8/3txO3P3ZbjhsPd6vJdmsx2K2hlI6U4ErSSKWRpESKkVKotC2lM2aDpL6kSFIiJdfmXPUSUgkjFfalxFKMlFxbQykdKamUkSojKbEUI6VQZSilM6ST44mRlARBewtVtqWkA@ol9SXFkhIpuTaHUtpSUimjzJ1eHDByMgNTRHdQ4YeYwIyt0xgTvLQECjygbXDhE6NBlC7M0MJOqzDCG8aBI/4xM6wxGS74YTKbXbaf8w4wvsICEzAfXhhFQIBqBlaKII/jRC1nEUaCYDHYO3F@Pp/I5Nlp/LUcQvcPp/GcHML7Xhqf7VL3f/JS/4hxP/jvczyNjlADEEfhntoYwQUVhmdKY/VOc0lm9c458dBiXVgJJGqwYHJGYwQI0iQG4hN@gB2@cDxQy47zMzmz4T4mYyaeYQ4mwDo/okssRKGVscMrc/QVdNiEHWC8Bf7wbTwH5gvGExjvXYYXmE/AfBTjM7yN//5fz9//w/NYAi3L/q@ncX@pTscwHZy61OYujd8B "Python 2 – Try It Online") --- # [Python 3](https://docs.python.org/3/), 109 bytes ``` lambda l:all([(q(a[0])-q(b[0])+1)%13*(A!=B)>2for(*a,A),(*b,B)in zip(l,l[1:])if a>[]<b]) q='234567891JQK'.find ``` [Try it online!](https://tio.run/##7ZZNb9pAFEX3@RV0UXlMaRXbGNuoRHJgYdkrxJKyMEpQLLkEItqq/fM03ANhkiqEfkaqwmKQrt4w7517Z8Ti6@rqeh6sZ70P67r8OL0oG3W3rGszNktTjk8n7tulmW6@33juay9omvRV79w982fXN6ZZtlK3ZZrT1rlbzRvfqoWpW/XY607catYoz8aT99OJe7LsOX7QDjtRnHj5sHDezar5xfrLVVVfNrzu4qaar8zMXH4ua1PNF59Wxr39rMdOOnJaDSccbNYk26xFf7P6UjpSvFNJQ5UGkiIpiZRCpW0pnREbJKWSAkmRlFybc9VLiCUMVZhKCaUkUnJt9aV0pMRShqoMpIRSEimFKn0pnQGd7E8MpEQI2luosi0l7lMvKZUUSoqk5NrsS2lLiaUMM2dyssPIyQxMEd1BhR9igmRkncaY4KUlUOABbYMLnxgNonSRDCzstAojvGEcOOIfM8Mak@GCH0lms8u2c94BxldYYALmwwujCAhQk76VIsjjOFHLWYSRIFgMtk4cn88nMnl0Gn8th9D9w2k8JofwvpfGZ7vU6U9e6h8xbgf/fY6H0RFqAOIo3GMbI7igwvBMmVi901yUWb1zTjiwWBdWAokaLJic0RgBgjSJgfiEH2CHLxx31LL9/EzObLiPyZiJZ5iDCbDO9@giC5FvZWz3yux9BR02YQcYb4E/fBuPgfmC8QDGe5fhBeYTMB/F@Axv47//1/P3//A8lkDLsv/radxeqsMxjPuHLnVyl8bv "Python 3 – Try It Online") Python 3 wins bytes with iterable unpacking but loses bytes by refusing to chain together comparisons of differently-typed items. The unpacking needs to handle both `'J'` and `'10S'`, which means it can either extract the first value or the last value, but not both. [Answer] # [Ruby](https://www.ruby-lang.org/), 123 bytes ``` ->a{a.each_cons(2).all?{|a,b|a==?J||b==?J||(s="A234567891JQK".chars).zip(s.rotate).all?{|f|((a.chars|b.chars)-[?0]-f)[2]}}} ``` [Try it online!](https://tio.run/##xZRPT8JAFMTvfArSU0mkwe3fPSBp4LBpT02PhJiFSDQhagAPSvnsaGe6boNo0Gi8lGTy3vLeb2Z3/TR/PiyHh/6V3mnvRi9urxcP9xtX9Dy9Wo12lb6YV3o4HGVVNeePuxk6qfCDMIoTeZkVueMtbvV60/Ne7h7djbd@2OrtjelfVq6rWVDNm8L@dDSY9Ze9qZjt9/vDY3c5nXa6XSctnYuuE07qr1T1Nx/XXwElgnI5gFSg1IcUQ5G1Up@SozqAGJXsgZRC8iHFUDL0Z6iHkKjmkAK1KcQQVRJKhm4BJYKSQClQ6UMJzSQSYo5igbJownns//pQYgpoz1EZmEmSMVugpqgLIcVQMvQLKAGUBEqhnM5s1ukcweUYZMDysLSgeCQ3kmXrf7k2oedmPdKhOVyDEGkgVyVnjiQnLTM4N7HBMZyoLF16GyjrAANAVImyITE4VbO3YY4TxxYP3WEwiJAOMj/kLMetkNEPRgFJrE/MaN0RXMaltKFpnDo3y4hL@Q7jVHy/E9wfRZbI/ya450SWPnwS3P98FWovv/cofGRLDr8G9yuezR0gVHpNL5LTaImQ6SMNri1bq3DQWLUsFeZGhJOWBXkrq7ykpEMW3JQb8YYE71iUdZA20Q1CJ1yDUlkiBJGYF4TRYAJoM92kaTSHBmT2eSHGwrAVrTSa18paTqC0jzYR7psLb3APrw "Ruby – Try It Online") ### Explanation: Without going too much into detail: * split every pair into single characters * remove '0' if any * remove duplicate characters * try to remove pairs of adjacent values If after the treatment, 3 characters are left, the pair is good. [Answer] # Python 3, 130 125 bytes *5 bytes saved thanks to Chas Brown* ``` v="A234567891JQK".find;s=lambda d:len(d)<2or("J"in d[:2]or 1<abs(v(d[0][0])-v(d[1][0]))<12and d[0][-1]!=d[1][-1])and s(d[1:]) ``` My first post here, so this could probably be golfed down a little more. ### Explanation Recursive lambda; checks if the first two cards of the current list are of different suits, are different ranks, and their ranks differ by more than 1 (but less than 12, to account for Ace-King), or if one of the two cards is a Joker, in which case it's fine, then consumes the first element of the list and recurses. [Answer] # [Ruby](https://www.ruby-lang.org/), 119 bytes ``` f=->s,c=20,d=?Z{a,*b=s;a ?(x=a[-1];x==?J||(e=((i="A234567891JQK".index(a[0]))-c)%13;e>1&&e<12)&&x!=d)&&f[b,i||20,x]:!p} ``` [Try it online!](https://tio.run/##7ZbPj5pAHMXv/hUsSY02uJFfArWsMXiYwIlwK@GgqyYe2piaJjTL/u1W3hOHjStR1qaXXjB5@c4w83mPF3/@Wvze79f@4GmnPfvGUFv6k28vc@3zwt@N58qkl/vzdKBn49z3J2FR9FZ@r7fx1alhWvbIcT09jCP1cfNjucp783SY9fuD5/4n3RyvnvRud/VVN/rdbv7gLw8/63ShbYri8JY8@/Kwfd2naUdR1Gmiaopqz8qnJ8pnFJRPA8oIij6EFGPUhORA8Uql3CXCtAVxlHANpCkkE5IDJcT6EPMQXHHcJMbsFKKNKQ9KiNUGlBEUF0qMSROKXZ3Egxhh2MDYaMbzyPeaUBwKWB5h0qpO4gZcAnWKORuSAyXEegOKBcWFEgu1k2mdGleegNfnpJ1IRtyNl/GS2it5Y/KOqpsRDH3hDciP3vGWRMzTeLOaDzwyicEs7CgkWNpqCQmf3pOSK2Q@KpLieOUKN3YMJBkaw0yQHs1jdIjYC2r5ohVMAUJY7hjSNcmVIUlkVI7@XJtghCQ5cXgvtLfEtVVQSfvvxPWaoNKC87j@yxoobbytBc6xEsHduDahPCafPGkzbXDPqJIeM0cQvLFXuwXP6IiakUb1CdizGv2ollB@lQRDDLwkL8PvwjoREdI8OkQjyJtcK4pCwiADt6oMpoLm02EaSb/oC9mHsk9IMK6wGrUMVvUk3SZLOkeHyPVgwLvlegXd/2BvA/vms7kVLw4SyDZph7fchY31Ebxsx5msszZ8UUpClmEz32ayHyjY9v16KlnQEBJem79a@G4SSetixTa1613/Y11KaM3HC@16lw64SwW0aABaIhvgQgG4QVMDeDKn2eP3@fal2BXKVlmnu@x1/wc "Ruby – Try It Online") Recursive version. It walks through the array and compares the current card to the last card. The rank is searched in the string "A234567891JQK" and jokers are skipped. It starts with a dummy previous card "20Z" which will accept any neighbour. [Answer] # [Python 2](https://docs.python.org/2/), 122 bytes ``` lambda a:all((12>abs(R(c[0])-R(d[0]))>1and c[-1]!=d[-1])or'J'in c[-1]+d[-1]for c,d in zip(a,a[1:])) R='A234567891JQK'.find ``` [Try it online!](https://tio.run/##pZPNaoNAFEb3PoV1o9KkxH8NGBCliK5MurNZTGKlgjXBpIv25W3muxpTSAtNNyMc7h3vnG9m/3F83TV6V/rPXc3eNgUT2ZzVtaJo@oJtDspS2eaztTpdKgX/qguNNYW4zafa@s4v@EfdtXIiVw3Be7By14rbSSGe6Ge1V9iE5dr81C0sfTnQDdOyHdfTkiyVH8qqKbp9WzVHsVRyQRSlYCVNRMmK@OrFfE1DvuogNog2A8pQagA5IB4nfJcU1SagvaIeoADIAHJAEvQnqAdw436TDLUBoIUqDyRBtw5ig7ggGSoNEGuYxANMUayjzI5onvG/BohDAO0pKs1hEjekFtAAdRaQA5KgXwcxQVyQLJaEter7T@37iyBc0dwPFJ/d9X5IBJ0Wpxqm60fAr/g2VnSRB0knt248miIjdGw6Hh3BPDuKxzgpM4qGAiDR1urCGukhBTgqMg/H60CZU7QUIAVFaSRnub3AbBBNt8wJL25MMsZPMVOWlBkFc/IPz4@sPlwX/S3/v@rGYOH4LG7TzXehy/Ef3XQdo/Fd3uIbjyseX/Xvvn803XVf "Python 2 – Try It Online") ]
[Question] [ The day of the week and month of the year seem to get a lot of attention but no one seems to care about the week of the year. I believe it's time to change that, so your job is to write a program or function that when given a date outputs an integer between 1 and 53 corresponding to the current week of the year. For the purposes of this challenge we will say that the first Sunday of the year marks the beginning of the year so the *only* case when January 1st is considered week 1 is when it falls on a Sunday. * Input can be any date format which does not explicitly include the week number (just specify the format in your answer) for dates between `1JAN1900` and `31DEC2100`. * Output is an integer between 1 and 53 * You may use any [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of providing input/output. ### Test Cases ``` 17MAY2017 -> 20 3JAN2013 -> 53 1JAN2017 -> 1 17MAY1901 -> 19 31DEC2100 -> 52 7JUL2015 -> 27 ``` * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all standard golfing rules apply, and the shortest code (in bytes) wins. [Answer] # [MATL](https://github.com/lmendo/MATL), 50 bytes *Thanks to @Neil and @NickClifford for pointing out a mistake, now corrected* ``` ZO1)TThXJYOXIGYO&:8XO!s310=sJ4B-YOIq&:8XO!s310=sX\ ``` [Try it online!](https://tio.run/nexus/matl#@x/lb6gZEpIR4RXpH@HpHumvZmUR4a9YbGxoYFvsZeKkG@nvWYgsFhHz/7@6obmvY6SRgaG5OgA) Or [verify all test cases](https://tio.run/nexus/matl#S4jw/h/lb6gZEpIR4RXpH@HpHemvZmUR4a9YbGxoYFvsZeKkG@nvWYgsFhHz3yXkv7qhua9jpJGBobk6l7qxl6MfkGkMZBpCmCBRsApDSwNDkApDF1dnI0MDAyDb3CvUB6jEVB0A). ### Explanation This uses the three date/time conversion functions that there are in MATL: * `XO`: convert date and time to string format; * `YO`: convert date and time to serial date number; * `ZO`: convert date and time to vector of components. Determining if week "0" should become 52 or 53 was costly, because MATL cannot define callable functions to reuse the `8XO!s310=s` part. Reusing by means of loop with a branch [only saves one byte](https://tio.run/nexus/matl#@29kpeSQbx/lb6gZEpIR4RXpH@HpHumvZlXrZeKkG@nvWahmFWsR4a9YbGxoYFscGxHz/7@6gaGXo5@RgaGlOgA), and complicates the explanation, so probably not worth it. Also, something could be gained inputting the date as a [year, month, day] array; but the I would not use all three date functions :-) Consider input `'17MAY2017'` as an example. ``` % Implicit input % STACK: '17MAY2017' ZO % Convert to date vector % STACK: [2017 5 17] 1) % Get first entry: year % STACK: 2017 TTh % Append [1 1] % STACK: [2017 1 1] XJ % Copy to clipboard J YO % Convert to date number % STACK: 736696 XI % Copy to clipboard I GYO % Push input again. Convert to date number % STACK: [736696 736832] &: % Binary range % STACK: [736696 736697 736698 ... 736832] 8XO % Convert to date string with format 'ddd': day of week % STACK: ['Sun'; 'Mon'; 'Tue'; ... ; 'Wed'] !s % Sum of each row (chars are interpreted as code points) % STACK: [310 298 302 ... 288] 310= % Compare with 310 (sum of 'Sun') % STACK: [1 0 0 ... 0] s % Sum of array. If is 0, it needs to be transformed into 52 or 53, % depending on the number of Sundays the previous year contains. % STACK: 20 J % Paste from clipboard J % STACK: 20, [2017 1 1] 4B- % Push [1 0 0] and subtract element-wise % STACK: 20, [2016 1 1] YO % COnvert to date number % STACK: 20, 736330 I % Paste from clipboard I % STACK: 20, 736330, 736696 q % Subtract 1 % STACK: 20, 736330, 736695 &: % Binary range % STACK: 20, [736330 736331 736332 ... 736695] 8XO % Convert to date string with format 'ddd': day of week % STACK: 20, ['Fri'; 'Sat'; 'Sun'; ... ; 'Sat'] !s % Sum of each row (chars are interpreted as code points) % STACK: 20, [289 296 310 ... 296] 310= % Compare with 310 (sum of 'Sun') % STACK: 20, [0 0 1 ... 0] s % Sum of array % STACK: 20, 52 X\ % 1-based modulo % STACK: 20 % Implicit display ``` [Answer] ## JavaScript (ES6), ~~82~~ 80 bytes Takes input as `(year,month,day)`. ``` let f = (y,m,d)=>-~((((x=new Date(y,m-1,d))-new Date(y,0,1))/864e5+372-x.getDay())/7%53) console.log(f(2017, 5,17)) // 20 console.log(f(2013, 1, 3)) // 53 console.log(f(2017, 1, 1)) // 1 console.log(f(1901, 5,17)) // 19 console.log(f(2100,12,31)) // 52 console.log(f(2015, 7, 7)) // 27 ``` [Answer] ## JavaScript (Firefox 34+), 70 bytes ``` with(new Date())y.value=getFullYear(),m.value=getMonth()+1,d.value=getDate()+1 f= (y,m,d)=>new Date(y,--m,d-new Date(y,m,d).getDay()).toLocaleFormat`%U` ``` ``` <div oninput=w.value=f(y.value,m.value,d.value)><input id=y type=number><input id=m type=number min=1 max=12><input id=d type=number min=1 max=31><input id=w readonly placeholder=Output> ``` Works by finding the first day of the week containing the given date, then finding that day's week number (which is never zero). [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm), ~~12~~ 33 bytes **EDIT**: Fixed the edge cases for "%U". ``` IΩDÖ?┼╓y≤s"-12-31"C"%F"╓₧Ω "%U"╓& ``` Assumes input can be a timestamp. Explanation to come. [Try it online!](https://tio.run/nexus/ohm#@@95bqXL4Wn2j6bseTR1cuWjziXFSrqGRrrGhkrOSqpuSkDBR03Lz63kUlINBXHU/v83NDQzNzM2NDIw@K@bAgA "Ohm – TIO Nexus") [Answer] # Python 2, ~~70~~ 64 bytes Input => `(year,month,day)` ``` from datetime import*;lambda*v:int(date(*v).strftime('%U'))or 53 print(f(2017, 5,17)) #20 print(f(2013, 1, 3)) #53 print(f(2017, 1, 1)) #1 print(f(1901, 5,17)) #19 print(f(2100,12,31)) #52 print(f(2015, 7, 7)) #27 ``` -6 bytes, thanks to @ovs [Answer] # JavaScript (Firefox Only), 77 bytes Takes date as string: i.e. `Jan 1, 2017` ``` s=>+new Date(s)[k='toLocaleFormat']`%U`||new Date(s.slice(-4)-1,11,31)[k]`%U` ``` [Answer] # PHP, 125 Bytes ``` for($w=53,$a=0;($c=date_create)($argn)>=$n=date_modify($c("07JAN1900"),"+$a week");$a++)$w=date_format($n,z)<7?1:$w+1;echo$w; ``` [Try it online!](https://tio.run/nexus/php#NY3BSsNAFEX3/Qp5vMUMyWJeQxl0mpZSs7Bo3ehCtIQhnTZFOhPGQFDRX48vDa7u4XK4d75s6mbiYgyxjK4JsT35o/gtyu3j0926kGZyCNHZqhavQPph9TJVpCGFbLPaMmaMNOLQXgy6VjQYdFusp6QUs94837MyY1SDzoqCnf1AG49efvf8IbDLZ1mKNldGYJXvbevKiq9bJ8XoLXL0Y38O@9PhkzUBSv/vyRQStFedc@8gDdokkbx58Xn/bFuBPv2Sc72kG@wSMq6qA3amHxLePJif/g8 "PHP – TIO Nexus") # PHP, 28 Bytes Version for Monday instead Sunday ``` <?=date(W,strtotime($argn)); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVTI093WMNDIwNFey5rK3@29jb5uSWJKqEa5TXFJUkl@SmZuqAVapqWn9/z8A "PHP – TIO Nexus") [Answer] # C#, ~~138~~ ~~123~~ 121 bytes ``` namespace System.Globalization{d=>CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d,(CalendarWeekRule)1,(DayOfWeek)0);} ``` Turns out there's a built in for that, although it is rather large... ``` namespace System.Globalization { Func<DateTime, int> f = d => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, (CalendarWeekRule)1, (DayOfWeek)0); } ``` [Answer] # Powershell, 260 + 8 = 268 bytes +8 bytes because of the `-DateTime` flag --- Accepts argument as `"day month year"` format. ``` function W([datetime]$DateTime = (Get-Date)) { $cultureInfo = [System.Globalization.CultureInfo]::CurrentCulture $cultureInfo.Calendar.GetWeekOfYear($DateTime,$cultureInfo.DateTimeFormat.CalendarWeekRule,$cultureInfo.DateTimeFormat.FirstDayOfWeek) } ``` *Not Powershell expert, can't golf* --- # Test case ``` >W -DateTime "11 March 2015" 11 ``` ]