text
stringlengths
180
608k
[Question] [ Invert the Format method. The `Format` method of the String class (or equivallent, such as `sprintf`) is available in most languages. It basically takes a "Format" string which may contain placeholders with some extra formatting, and zero or more values to be inserted instead of those placeholders. Your task is to implement the inverse function in your language of choice. # API Method name should be either `format1` or `deformat`. **Input**: 1st parameter will be the "Format" string, just like in the original format method. 2nd parameter will be the parsed string (see examples below). No other parameters are needed nor allowed. **Output**: an array (or your language-of-choice's equivalent) of values that were extracted correspondingly with the placeholders in the format. The placeholders are `{0}`, `{1}`, `{2}`, etc. In case of bad format you may throw an error, or return whatever you like. In case of invalid input, you may throw an error, or return whatever you like. Invalid input is such that cannot be generated by String.Format using same format string, for example: `'{0}{0}', 'AAB'`. # Examples ``` deformat('{0} {1}', 'hello world') => ['hello', 'world'] deformat('http{0}://', 'https://') => ['s'] deformat('http{0}://', 'http://') => [''] // array of one item which is an empty string deformat('{0}{1}{0}', 'ABBA') => ['A', 'BB'] ``` # Ambiguity In case of ambiguity you may return any suitable answer. For example: ``` deformat('{0} {1}', 'Edsger W. Dijkstra') // both ['Edsger', 'W. Dijkstra'] and ['Edsger W.', 'Dijkstra'] are applicable. ``` # Some More Rules * To make it easier, there's no need to actually support formatting. You can forget all about leading zeros, decimal point or rounding issues. Just generate the values as strings. * To make it non-trivial, **Regular Expressions are not allowed**. * You don't need to take care of curly braces in input (i.e. 2nd input parameter will not contain any `{`s or `}`s). # Winning This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")! (should be read as "This is Sparta!") the correct function having shortest length wins. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are forbidden. [Answer] # Haskell, 220 characters ``` import Data.Map;f""""=[empty] f('{':b)d=[insert k m b|(k,('}':a))<-lex b,(m,c)<-[splitAt n d|n<-[0..length d]],b<-f a c,notMember k b||b!k==m] f(x:b)(y:d)|x==y=f b d;f _ _=[];format1 x y=elems$mapKeys((0+).read)$f x y!!0 ``` Breaks if you use multiple representations for the same pattern (`{1}` vs `{01}`) - doesn't enforce their equality, discarding matches for all but one representation instead. 19 characters can be saved by omiting `mapKeys((0+).read)$` if proper ordering of matches above 10 patterns doesn't matter, or if padding to the same length may be required, or if string ordering of patterns is acceptable. In any case, if a pattern is omitted from the first argument, it is omitted from the result as well. Removing `!!0` from the end makes `format1` return the list of all solutions, rather than just the first one. before golfing: ``` import Data.Map import Control.Monad cuts :: [a] -> [([a],[a])] cuts a=[splitAt n a | n <- [0..length a]] f :: String -> String -> [Map String String] -- empty format + empty parsed = one interpretation with no binding f "" "" = [empty] -- template-start format + some matched = branch search f ('{':xs) ys = do let [(key, '}':xr)] = lex xs (match, yr) <- cuts ys b <- f xr yr guard $ notMember key b || b!key == match return $ insert key match b -- non-empty format + matching parsed = exact match f (x:xs) (y:ys) | x == y = f xs ys -- anything else = no interpretation f _ _ = [] deformat :: String -> String -> [String] deformat x y = elems $ mapKeys ((0+).read) $ head $ f x y ``` [Answer] # Ruby, 312 characters ``` class String def-@ self[0,1].tap{self[0,1]=''}end end def format1 f,s,r=[] loop{if'{'==c=-f n,f=f.split('}',2) [*1..s.length,0].each{|i|next if'{'!=f[0]&&s[i]!=f[0] if u=format1((g=f.gsub("{#{n}}",q=s[0,i])).dup,s[i..-1],r.dup) r,s,f=u,s[i..-1],g r[n.to_i]=q break end}else c!=-s&&return end ""==c&&break} r end ``` 5 characters could be saved by preferring zero-length matches, making the `ABBA` solution `['', 'ABBA']`, rather than the question's preferred solution. I chose to interpret the examples as an implied part of the specification. [Answer] # Python, 208 chars, albeit incomplete. ``` def format1(i,o): i+=" ";o+=" ";x=y=0;s=[] while x<len(i): if i[x]=="{": try:y+=len(s[int(i[x+1])]) except: s+=[""] while o[y]!=i[x+3]:s[int(i[x+1])]+=o[y];y+=1 x+=3 x+=1;y+=1 return s ``` The function sweeps both strings simultaneously, until it finds a opening brace in the input string, signifying a placeholder. Then, it assumes the placeholder has already been expanded, and tries to advance the index of the output string past it by looking in the list of values found so far. If it hasn't been expanded, it adds a new entry to the list of values, and starts adding in characters from the output string until it reaches the character after the placeholder in the input string. When it gets to the end of the input string, it returns the values found so far. --- It works well for simple inputs, but it has a number of issues: * It requires a known delimiter after each placeholder in the input, so it doesn't work with placeholders right next to each other i.e. "{0}{1}". This is why I needed to append a space char to both strings. * It assumes the first instances of each placeholder are in order e.g. "{**0**}{**1**}{1}{0}{**2**}". * It only works for the first 10 placeholders as it assumes they are all 3 chars long. * It doesn't handle ambiguous cases at all :( [Answer] # C++11 code, 386 characters ``` #include <string> #include <map> using namespace std;using _=map<int,string>;using X=const char;_ format1(X*p,X*s,_ k=_()){_ r;while(*p!='{'){if(!*p||!*s){return*p==*s?k:r;}if(*p++!=*s++)return r;}int v=0;while(*++p!='}'){v=v*10+(*p-48);}p++;if(k.find(v)!=k.end()){return format1((k[v]+p).c_str(),s,k);}while((r=format1(p,s,k)).empty()){k[v]+=*s++;if(!*s){return*p==*s?k:r;}}return r;} ``` The format1 function have 2 strings as input (const char\*) and returns an hashmap with keys integer (the pattern) and value is the identified string. If nothing is found or any error, an empty hashmap is returned. Usage: ``` for (auto v : format1("{1} {2}", "one two")){ cout << v.first << "=" << v.second << endl; } ``` Output: ``` 1=one 2=two ``` Example 2: ``` auto v = format1("{1} {2}", "one two"); cout << v[1] << " and " << v[2] << endl; ``` Output: ``` one and two ``` The patterns are in decimal representation, inputs bigger than `MAXINT` will overflow but it still works. Even though there are smaller solutions in other programming languages, this is the smallest C++ - yet! :) This is the code before golfing: ``` #include <string> #include <map> using namespace std; using res = map<int,string>; res format1(const char* p, const char* s, res k=res()){ res r; // intermediate result, empty until the end // match until first '{' while (*p != '{'){ if (!*p || !*s){ // exit case return ((*p == *s) ? k : r); // == 0 } if (*p++ != *s++) return r; } // *p == '{' int v = 0; while(*++p != '}'){ v = v*10 + (*p - '0'); } p++; // advance past '}' // match back-references if (k.find(v) != k.end()){ return format1((k[v]+p).c_str(), s, k); } // recursive search while ( (r=format1(p, s, k)).empty() ){ k[v] += *s++; if (!*s){ return *p == *s ? k : r; } } return r; } ``` ]
[Question] [ At <http://shakespeare.mit.edu/> you can find the full text of each of Shakespeare's plays on one page (e.g. [Hamlet](http://shakespeare.mit.edu/hamlet/full.html)). Write a script that takes in the url of a play from stdin, such as <http://shakespeare.mit.edu/hamlet/full.html>, and outputs the number of text characters each play character spoke to stdout, sorted according to who spoke the most. The play/scene/act titles obviously do not count as dialogue, nor do the character names. *Italicized text* and [square bracketed text] are not actual dialogue, they should not be counted. Spaces and other punctuation within dialogue should be counted. (The format for the plays looks very consistent though I have not looked at them all. Tell me if I've overlooked anything. Your script does not have to work for the poems.) # Example Here is a simulated section from [Much Ado About Nothing](http://shakespeare.mit.edu/much_ado/full.html) to show what I expect for output: > > # More Ado About Nothing > > > ## Scene 0. > > > **Messenger** > > > I will. > > > **BEATRICE** > > > Do. > > > **LEONATO** > > > You will never. > > > **BEATRICE** > > > No. > > > Expected output: ``` LEONATO 15 Messenger 7 BEATRICE 6 ``` # Scoring This is code golf. The smallest program in bytes will win. [Answer] # PHP (240 characters) Divides the html into strings (using as a delimeter), then runs a couple of regular expressions to extract name and words spoken. Saves length of words spoken into array. Golfed: ``` <?@$p=preg_match_all;foreach(explode('/bl',implode(file(trim(fgets(STDIN)))))as$c)if($p('/=s.*?b>(.*?):?</',$c,$m)){$p('/=\d.*?>(.*?)</',$c,$o);foreach($m[1]as$n)@$q[$n]+=strlen(implode($o[1]));}arsort($q);foreach($q as$n=>$c)echo"$n $c\n"; ``` Ungolfed: ``` <?php $html = implode(file(trim(fgets(STDIN)))); $arr = explode('/bl',$html); foreach($arr as $chunk){ if(preg_match_all('/=s.*?b>(.*?):?</',$chunk,$matches)){ $name = $matches[1]; preg_match_all('/=\d.*?>(.*?)</',$chunk,$matches); foreach($name as $n) @$names[$n] += strlen(implode($matches[1])); } } arsort($names); foreach($names as $name=>$count) echo "$name $count\n"; ``` Note: This considers 'All' to be a separate character. Example: ``` $php shakespeare.php <<< "http://shakespeare.mit.edu/hamlet/full.html" HAMLET 60063 KING CLAUDIUS 21461 LORD POLONIUS 13877 HORATIO 10605 LAERTES 7519 OPHELIA 5916 QUEEN GERTRUDE 5554 First Clown 3701 ROSENCRANTZ 3635 Ghost 3619 MARCELLUS 2350 First Player 1980 OSRIC 1943 Player King 1849 GUILDENSTERN 1747 Player Queen 1220 BERNARDO 1153 Gentleman 978 PRINCE FORTINBRAS 971 VOLTIMAND 896 Second Clown 511 First Priest 499 Captain 400 Lord 338 REYNALDO 330 FRANCISCO 287 LUCIANUS 272 First Ambassador 230 First Sailor 187 Messenger 185 Prologue 94 All 94 Danes 75 Servant 49 CORNELIUS 45 ``` [Answer] # Rebol - ~~556~~ 527 ``` t: complement charset"<"d: charset"0123456789."m: map[]parse to-string read to-url input[any[(s: 0 a: copy[])some["<A NAME=speech"some d"><b>"copy n some t</b></a>(append a trim/with n":")some newline]<blockquote>newline any["<A NAME="some d">"copy q some t</a><br>newline(while[f: find q"["][q: remove/part f next find f"]"]s: s + length? trim head q)|<p><i>some t</i></p>newline][</blockquote>|</body>](foreach n a[m/:n: either none? m/:n[s][s + m/:n]])| skip]]foreach[x y]sort/reverse/skip/compare to-block m 2 2[print[x y]] ``` This could probably be golfed further however its unlikely to get below the answer(s) already provided :( ### Ungolfed: ``` t: complement charset "<" d: charset "0123456789." m: map [] parse to-string read to-url input [ any [ (s: 0 a: copy []) some [ "<A NAME=speech" some d "><b>" copy n some t </b></a> (append a trim/with n ":") some newline ] <blockquote> newline any [ "<A NAME=" some d ">" copy q some t </a><br> newline ( while [f: find q "["] [ q: remove/part f next find f "]" ] s: s + length? trim head q ) | <p><i> some t </i></p> newline ] [</blockquote> | </body>] (foreach n a [m/:n: either none? m/:n [s] [s + m/:n]]) | skip ] ] foreach [x y] sort/reverse/skip/compare to-block m 2 2 [print [x y]] ``` This program removes [square bracketed text] and also trims surrounding whitespace from the dialogue. Without this the output is identical to *es1024* answer. ### Example: ``` $ rebol -q shakespeare.reb <<< "http://shakespeare.mit.edu/hamlet/full.html" HAMLET 59796 KING CLAUDIUS 21343 LORD POLONIUS 13685 HORATIO 10495 LAERTES 7402 OPHELIA 5856 QUEEN GERTRUDE 5464 First Clown 3687 ROSENCRANTZ 3585 Ghost 3556 MARCELLUS 2259 First Player 1980 OSRIC 1925 Player King 1843 GUILDENSTERN 1719 Player Queen 1211 BERNARDO 1135 Gentleman 978 PRINCE FORTINBRAS 953 VOLTIMAND 896 Second Clown 511 First Priest 499 Captain 400 Lord 338 REYNALDO 312 FRANCISCO 287 LUCIANUS 269 First Ambassador 230 First Sailor 187 Messenger 185 Prologue 89 All 76 Danes 51 Servant 49 CORNELIUS 45 ``` [Answer] # Common Lisp - 528 ``` (use-package :plump)(lambda c(u &aux(h (make-hash-table))n r p)(traverse(parse(drakma:http-request u))(lambda(x &aux y)(case p(0(when(and n(not(ppcre:scan"speech"(attribute x"NAME"))))(setf r t y(#1=ppcre:regex-replace-all"aside: "(#1#"^(\\[[^]]*\\] |\\s*)"(text x)"")""))(dolist(w n)(incf(gethash w h 0)(length y)))))(1(if r(setf n()r()))(push(intern(text(aref(children x)0)))n)))):test(lambda(x)(and(element-p x)(setf p(position(tag-name x)'("A""b"):test #'string=)))))(format t"~{~a ~a~^~%~}"(alexandria:hash-table-plist h))) ``` # Explanation This is a slightly modifed version which adds printing informations (see paste). ``` (defun c (u &aux (h (make-hash-table)) ;; hash-table n ;; last seen character name r p ) (traverse ;; traverse the DOM generated by ... (parse ;; ... parsing the text string (drakma:http-request u) ;; ... resulting from http-request to link U ) ;; call the function held in variable f for each traversed element (lambda (x &aux y) (case p (0 ;a (when(and n(not(alexandria:starts-with-subseq"speech"(attribute x "NAME")))) (setf r t) (setf y(#1=ppcre:regex-replace-all"aside: "(#1#"^(\\[[^]]*\\] |\\s*)"(text x)"")"")) (format t "~A ~S~%" n y) ;; debugging (dolist(w n) (incf (gethash w h 0) ;; get values in hash, with default value 0 (length y)))) ;; length of text ) (1 ;b (if r(setf n()r())) (push (intern (text (aref (children x)0)))n)))) ;; but only for elements that satisfy the test predicate :test (lambda(x) (and (element-p x) ;; must be an element node (setf p(position(tag-name x)'("A""b"):test #'string=)) ;; either <a> or <b>; save result of "position" in p ))) ;; finally, iterate over the elements of the hash table, as a ;; plist, i.e. a list of alternating key values (k1 v1 k2 v2 ...), ;; and print them as requested. ~{ ~} is an iteration control format. (format t "~&~%~%TOTAL:~%~%~{~a ~a~^~%~}" (alexandria:hash-table-plist h))) ``` # Notes * I remove bracketed text as well as the "aside: " occurence that is not present in brackets (I also trim whitespace characters). [Here is a trace of execution](http://pastebin.com/raw.php?i=cTQQpC9D) with the text being matched and the total for each character, for [Hamlet](http://shakespeare.mit.edu/hamlet/full.html). * As other answers, **All** is assumed to be a character. It could be tempting to add the value of all to all other characters, but this would be incorrect since "All" refers to the characters actually present on stage, which requires to keep a context of who is present (tracking "exit" "exeunt" and "enter" indications). This is not done. ]
[Question] [ Given a list of chords label them as either 'Major' or ' Minor'. ## Input Input will be a list of chords, one per line, made up of 3 notes separated by a space. Each note will consist of the note name in uppercase (`A`-`G`) and an optional accidental (`#` or `b`). Chords may be in any inversion (i.e. the notes may be in any order). ## Output If the chord is major, output 'Major'. If the chord is minor, output 'Minor'. If the chord is neither major nor minor, output a blank line. ## Example **Input** ``` C E G F Ab C C Eb Gb E G B Db F Ab Bb G D D A Gb ``` **Output** ``` Major Minor Minor Major Minor Major ``` ## Test scripts As in some of my past questions, I've once again butchered some test scripts originally created by [Joey](https://codegolf.stackexchange.com/users/15/joey) and [Ventero](https://codegolf.stackexchange.com/users/84/ventero) to provide some test cases for this question: * [bash](http://www.garethrogers.net/tests/majorminor/test) * [Powershell](http://www.garethrogers.net/tests/majorminor/test.ps1) Usage: `./test [your program and its arguments]` ## Rewards Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 13/10/2012 will be accepted as the winner. ## A little theory For those of you with no musical theory knowledge here's enough information for you to be able to compete. A major or minor chord is made up of three notes which are separated by a specific pattern of semitones. If we consider the root (bottom note) of the chord to be 0, then a major chord is the pattern 0-4-7 and a minor chord is the pattern 0-3-7. Things are made more awkward by the fact that some notes are a semitone apart and some are a tone apart. The spread of semitones from `Ab`-`G#` is as follows: ``` G#/Ab A A#/Bb B/Cb B#/C C#/Db D D#/Eb E/Fb E#/F F#/Gb G G#/Ab 0 1 2 3 4 5 6 7 8 9 10 11 12 ``` `G#/Ab` means that that `G#` is the same note as `Ab`. From this we can see that the chord `Ab C Eb` is a major chord, and that `Ab Cb Eb` is minor. To complicate matters further, the chord `Eb Cb Ab` is considered to be the same as `Ab Cb Eb`, `Cb Eb Ab` and `Cb Ab Eb` and so on. Every one of these variations is still a minor chord. [Answer] ## Python, 160 ``` f='A#BC D EF G3453543'.find try: while 1:x,y,z=sorted(map(lambda x:f(x[0])+f(x[1:])+1,raw_input().split()));print'MMianjoorrr'[f(`y-x`+`z-y`)/14:-1:2] except:0 ``` [Answer] ## GolfScript, 83 chars ``` n%{' '%{1\{'A#BC D EF G'?+}/.}%$(+2/{~- 12%}%.(+.(+]$0=.$]10,7>?'MMaijnoorr '>2%}% ``` This is a quick first solution; I'm sure this can be golfed further. Passes the bash test suite, after fixing the bug pointed out by flodel in the comments. **Edit 1:** Saved 5 chars with a shorter way to recognize the canonicalized major and minor chord patterns. **Edit 2:** Saved 2 more chars with more compact output encoding inspired by grc's solution. (Thanks!) As a side effect, the code now prints an extra blank line after the output, but the test harness seems to accept that, so I guess it's OK. :) Here's how it works: * The outer loop `n%{ }%n*` just splits the input into lines, runs the code inside the braces for each line and joins the results with newlines. * `' '%` splits each line into an array of notes. For each of those notes, `1\{'A#BC D EF G'?+}/` then converts that note into a semitone number by searching for each of its characters in the string `'A#BC D EF G'` and adding up the positions (which will be -1 for any character not found in the string, notably including `b`). (I'm *sure* I've seen this trick used before.) Finally, the `.` duplicates each number, so that, at the end of the loop, e.g. the input `F Ab C` has been turned into `[9 9 0 0 4 4]`. * We then sort the notes with `$`, move the first note to the end with `(+`, and split the array into pairs with `2/`, so that it now looks e.g. like `[[9 0] [0 4] [4 9]]`. Then `{~- 12%}%` maps each pair of notes into its difference modulo 12, turning our example array into `[9 8 7]`. * Next, `.(+` makes a copy of the array and rotates its elements left by one position. We do this twice and collect the copies into an array with `]`, so that our example now looks like `[[9 8 7] [8 7 9] [7 9 8]]`. * We then sort this array of arrays with `$` and take the first element — in this case `[7 9 8]` — with `0=`. We then make a copy of this array (`.`), sort it (`$`), collect both the unsorted and the unsorted array into another array of arrays (`]`), and search for the first occurrence of the array `[7 8 9]` (which is written as `10,7>` to save two chars) in it. * This gives us either `0` (if the unsorted array was `[7 8 9]`, and thus the chord is major), `1` (if the unsorted array was a permutation of `[7 8 9]`, which, given that its first element must be smallest, can only be `[7 9 8]`, making the chord minor) or `-1` (if even the sorted array does not equal `[7 8 9]`). * This number is then used as a starting index into the string `"MMaijnoorr\n\n"` (where the `\n`s are given as actual linefeeds in the code), from which we take that character and every second subsequent one as the output. If the index is -1, we start from the last character of the string, which is just a line feed. ]
[Question] [ ["Y.M.C.A."](https://www.youtube.com/watch?v=CS9OO0S5w2k) is a popular disco song by the Village People that has a [well-known dance](https://en.wikipedia.org/wiki/Y.M.C.A._%28song%29#Origin_of_hand_movement_and_dance). Write the shortest program to output the capital letters "Y", "M", "C", and "A" synchronized to the song's chorus. Generally, one letter goes on each line sent to standard output. This primarily is to simplify programs subject to the output buffering of the C standard library (printing a newline flushes the output buffer), so you may omit any or all of these newlines if such omission would make your program shorter. Your program, which is started at the same time as the music, must output the letter "Y" within 0.125 s of each of these times after starting (in seconds; I determined these from the music video posted on YouTube). ``` 45.766 49.611 60.889 64.661 109.816 113.591 124.810 128.687 173.830 177.620 188.950 192.724 204.013 207.739 219.057 ``` The letters "M", "C", and "A" respectively come 0.930 s, 1.395 s, and 1.628 s after each "Y". For testing purposes, these relative times are converted into absolute times by adding them to the time of the preceding "Y". I have written a [test program and corresponding example program](https://github.com/plstand/ymcagolf) in C that assume a newline follows each letter (although this is not a rule of competition). It is written for Linux and will not work on Windows without using Cygwin. If you cannot test your submission using the test program, at least check your submission against the [YouTube video](https://www.youtube.com/watch?v=CS9OO0S5w2k). If your submission requires a special command-line option to behave properly, that command-line option counts when calculating your score. However, any interpreter startup time does not count against you, and the test program can be modified to accommodate that if necessary. Although I doubt one exists, I must say that using a programming language function or library designed specifically for this task is prohibited. [Answer] ## Ruby ~~180 135 124 118 108~~ 104 ``` [458,k=22,*[97,k,435,k]*2,*[98,k]*2,98].flat_map{|e|[e,9,5,2]}.zip(%w(Y M C A)*15){|a,b|sleep a/1e1;p b} ``` [Answer] ## C, 161 154 chars ``` #define P(d,x)w(d);puts(#x); w(n){usleep(n<<16);} y(d){P(d,Y)P(14,M)P(7,C)P(3,A)} b(){y(664);y(35);y(147);y(35);} main(){b(b(b(w(34))));y(148);y(33);y(148);} ``` The tester passes, but only if `fflush(stdout);` is added after each `puts`. Since the question clearly states that `fflush` is not required, I take it as a problem in the tester. Logic: `w` sleeps, the time is given in units of 16.384 65.536 ms. This resolution allows accurate enough timing and small constants (I should perhaps try 100ms). `P` waits a while and prints a character. `y` prints a YMCA sequence, after an initial delay. `b` prints 4 YMCA sequences - this 4\*YMCA happens 3 times, with similar enough timing. `main` prints the 3\*4\*YMCA sequences, plus the remaining 3. [Answer] ## Python2.6 (~~82~~)(~~214~~)(~~219~~)(~~196~~)(~~185~~)(152) Fixed. Ran against the video & seems accurate. Saved quiet a few characters by reducing the precision from 3 to 2 in most of the cases(thanks for the tip @JPvdMerwe). The only problem is that the tester shows a huge discrepancy in the timings. It starts out of sync & tries to come back into sync. In the two test cases it was more than 175 seconds out of sync at the beginning and came back to within 0.342 and 0.451 seconds of being back in sync. ``` import time;s=time.sleep for t in[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6]*15: i=0;s(t) while i<4:s([.1,.9,.5,.2][i]);print'YMCA'[i];i+=1 ``` [Answer] ### Mathematica, 157 ``` p=Print[Pause@#;#2]& (#~p~"Y";.93~p~"M";.465~p~"C";.233~p~"A")&/@{45.766,2.217,9.65,2.144,43.527,2.147,9.591,2.249,43.515,2.162,9.702,2.146,9.661,2.098,9.69} ``` I watched the entire video to confirm the timing. Y M C A.... Y M C A... It could be shorter with less precision, but then I'd have to watch the video again to confirm that it was not off by more than .125 at the end. lol [Answer] # [JavaScript (Node.js)](https://nodejs.org), 206 bytes ``` s=async t=>await new Promise(r=>setTimeout(r,t*1e3));(async _=>{for(t of[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6])for(i=0,await s(t);i<4;)await s([.1,.9,.5,.2][i])||console.log('YMCA'[i++])})() ``` [Try it online!](https://tio.run/##PY1dC4IwGIX/infuzTXyo0hsQnQddNFNyIhhMxbqYltJZL/dNLGrc54DD@fGn9zkWt7tvFYX0XWGcvOqc8fSlDdcWqcWjXPQqpJGIE1TI@xRVkI9LNLYznwRAiRodM40fRdKI@uoIouWZI0D4uOYLHGAo5BEffygH/@4msahMxh0SRd4/DbIQiI3UQITZ71LYtwLJGCZZNC2uaqNKgUp1RW5p/1u62bS8xh8AEHXfQE "JavaScript (Node.js) – Try It Online") i tried out the tester program and it was within about half a second for each cue but not 0.125. i think the startup time just needs to be factored in and some of the deltas may need to be adjusted to account for accumulated rounding errors. i'm curious if there may be a shorter solution without using >ES5 `await`, and a shorter way to print to `STDOUT`. ]
[Question] [ There's a payment machine for laundry in my building which does a few frustrating things. The ones relevant to this challenge are: * It doesn't make change. So if you pay over the amount then you are not getting that over-payment back. * It doesn't accept coins smaller than 20c. Meaning the only coins it accepts are 20c, 50c, 1€ and 2€ (1€=100c). * The price of running one machine is 2.30€ The third item doesn't seem immediately frustrating, however if we take a look at all the ways to make 2.30€ we can see an issue: | 2€ | 1€ | 50c | 20c | | --- | --- | --- | --- | | 0 | 1 | 1 | 4 | | 0 | 0 | 3 | 4 | | 0 | 0 | 1 | 9 | You may notice that in order to pay 2.30€ you *must* have at least a 50c coin and four 20c coins. There's no way to substitute other coins in, if you show up and you don't have that combination of coins (plus extra coins to cover the remainder) you are going to have to overpay. I'm very suspicious that the designers of the machine set the price this way just to make it look reasonable but force over-payment. I think most people end up paying 2.50€ because it's simpler or because their pocket change doesn't meet the stringent requirements to pay exactly 2.30€ To illustrate this hypothesis I have created a strictness index. To measure it you take all the ways you can make a particular price using the available coin set and for each coin type find the option that uses the least of that coin, record the number of that coin used and sum them all up. If we use the example above, the strictness index is 0 + 0 + 1 + 4 = 5. In fact there is no possible price with a worse strictness index for this set of coins. 5 is the limit. Not all prices have a strictness index, for example 1.97€ can't be made with the coins above so this procedure doesn't make sense. We just ignore these values, we only care about prices that are possible to make with the given coins. ## Task In this challenge you will take a set of positive integers representing coin values and calculate the maximum strictness index a price can have in this coin system. The input set will always contain at least 2 values, there will never be duplicates and you may assume it is in strictly ascending or descending order. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize the size of your source code as measured in bytes. ## Test cases ``` 2 5 10 20 -> 5 2 3 -> 3 2 3 5 -> 2 1 8 -> 7 2 4 -> 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` Œṗf³$ƑƇœ&/¹¡L P!Ç€Ṁ ``` [Try it online!](https://tio.run/##ATEAzv9qZWxsef//xZLhuZdmwrMkxpHGh8WTJi/CucKhTApQIcOH4oKs4bmA////WzEsIDNd "Jelly – Try It Online") -1 thanks to Jonathan Allan. [Unlike Vyxal](https://github.com/Vyxal/Vyxal/issues/1201), Jelly's multiset intersection appears to work properly. This is roughly \$O\left(2^{\left(\prod{s}\right)!}\right)\$. I'm pretty sure using [caird's fork](https://github.com/cairdcoinheringaahing/jellylanguage/) would save a few bytes but I can't be bothered for now. ``` P!Ç€Ṁ Main link (takes a list of numbers) P! Factorial of product € Map over 1...n Ç Helper (see below) Ṁ Take maximum Œṗf³$ƑƇœ&/¹¡L Helper link (takes argument n) Œṗ Integer partitions Ƈ Filtered by... $Ƒ Same under f³ Remove all but input / Reduce by œ& Multiset union ¹¡ N times L Get final length ``` [Answer] # Python3, 551 bytes: ``` from itertools import* def f(v): j,m=[],{} for I,n in enumerate(v): c=0 while(c:=c+1): F,O=0,[] for j in permutations(Y:=[*(set(v)-{n})],len(Y)): s=c*n for i in j:s-=i*(s//i) if s>0:O+=[c];F=1 else:O+=[0];F=0;break m[n]=max(O)if 0 not in O else(m[n]if n in m else 0) if F==0:break U,V=[],[i for i in m if m[i]] for i in range(1,len(V)+1): for j in combinations(V,i): n=sum(k*m[k]for k in j) if 0==any(any(0==(n-(t*(n//t)))%l and t*(n//t)for l in j)for t in {*v}-{*V}):U+=[sum(m[l]for l in j)] return max(U) ``` [Try it online!](https://tio.run/##XZBBb@MgEIXv/hVzWQlcouBWlSpX7DHSnnJKpApxcF28JTGDhUl3qyi/PcuQdNvdg63hm3kD703v6TXg3cMUz@chBg8u2ZhCGGdwfgox1dWLHWBgb7ytYCe80kYcTxUMIcIPgeAQLB68jV2ylyHolcz/X69utKxvVX/TFAwrsVZSaEM1yXcknmz0h9QlF3BmT63SNZttypsWRzxxI0aL7IlfFsCs@hpLRXpH@l07L5TLouXS8dJyA8zfZbu@Ubo3jyvVFGrH2RYmicnH52i7PXW8RqN895uteVZKwJBo77ooGHUzLj59QSDLNRmulJLtdc9GbCkZ7T5f5mnGa2dM9Qljhz8ta4qtLb8m8zeMPvhnh9cwtsJdbKOaD57ta6/3hkb3xffHK6RSHb4z@nLJcMFSzXC5TJzzbyN0@AIfgMTjRUxl8Xms306LY7098XaT06GbvB7Nl9H8/GjTIWZHOaUNP0/RYWID07cC7gU0UsCtNJxXXxp3/5/F/T@kEQ90Pv8B) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 143 bytes ``` with(Math)f=(a,i=0,t)=>!t&&(g=n=>n>0?min(...a.map(m=>(m==t)+g(n-m))):n&&1/0,g(i,s=0)||a.map(v=>s+=g(i,t=v)),max(s,f(a,i+1,a.map(v=>i/=v*v)|i))) ``` [Try it online!](https://tio.run/##XY07DsIwEAV7bkFj7ZKN40CDkNacgBMgCivkYxQ7EbYMRe4eEiFRULxmNJr3MMmE6mnHmPvhXs/zy8YOLiZ22DAYsqwoIuttFAJa9qy9VmdnPUgpjXRmBMd6GUfMWvC5Q8STF6IsFLVgKbDCafqaiXXIeKWREyI584ZAzXqTlfRzbMFpl3CyS2quBh@Gvpb90EID15KON8TNH93TYaHzBw "JavaScript (Node.js) – Try It Online") I hope the answer is correct although I cannot verify it by any larger testcases due to its terrible time complexity. ]
[Question] [ ## Task Given a winning Wordle play results (clues), the target ("secret") word and a list of words, output a possible sequence of words leading to such results. The words in the list will be distinct and so should be the output. You may assume that for given inputs a solution exists. If there is more than one, you may output any or all of them. Take your input in any convenient manner: including string of coloured rectangles, string of 3 distinct characters of your choice, array of 3 distinct values, etc. You may output list of words first-to-last or reversed. You can omit the last row of clues as it will be all "green" or take the target word as the last row if you like. The target word is also optional in the output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. ## Example ``` input => clues: 00100 00000 11100 01210 22222 or ⬜⬜🟨⬜⬜ ⬜⬜⬜⬜⬜ 🟨🟨🟨⬜⬜ ⬜🟨🟩🟨⬜ 🟩🟩🟩🟩🟩 target: CGOLF words: ABCDE,CGOLF,EDCBA,LOGOS,VLOGS,WORDS,XYZAB output => ABCDE,XYZAB,LOGOS,VLOGS,CGOLF ``` ## How does Wordle exactly work? *Taken from [@pxeger's related challenge](https://codegolf.stackexchange.com/questions/241723/highlight-a-wordle-guess).* In [Wordle](https://powerlanguage.co.uk/wordle/), you try to guess a secret 5-letter word, and some letters in your guess are highlighted to give you hints. If you guess a letter which matches the letter in the same position in the secret word, the letter will be highlighted green. For example, if the secret word is `LEMON` and you guess `BEACH`, then the `E` will be highlighted green. If you guess a letter which is present in the secret word, but not in the correct corresponding position, it will be highlighted yellow. If a letter appears more times in the guess than it does in the secret word, only upto as many occur in the secret may be highlighted. If any of the occurrences are in the same place, they should be preferentially highlighted green, leaving earlier letters unhighlighted if necessary. For example, with the secret `LEMON` and the guess `SCOOP`, the second `O` will be green, because it is in the right place, but the first `O` will be unhighlighted, because there is only one `O` in the secret, and one `O` has already been highlighted. Any of the remaining letters in the secret may be highlighted yellow if they match, as long as the right number are highlighted in total. For example, with the secret `LEMON` and the guess `GOOSE`, only one of the `O`s should be highlighted; it does not matter which. ## Test cases Use `ABCDE` as target and `ABCDE,DECAB,EDCBA,QWERT` as words: ``` clues: 22222 output: ABCDE clues: 11211 11211 22222 output: DECAB,EDCBA,ABCDE or EDCBA,DECAB,ABCDE clues: 00100 22222 output: QWERT,ABCDE ``` Use `GOOSE` as target and `GOOSE,LEMON,SCOOP` as words: ``` clues: 01010 10210 22222 output: LEMON,SCOOP,GOOSE ``` [Answer] # [Python 3](https://docs.python.org/3/), 155 bytes Based on my submission for the related challenge, uses the same color encoding: `-1` for *Green*, `0` for *Yellow* and `1` for not highlighted. ``` def f(g,s,w): for l in g:k=[k for k in w if(c:='')or[-(a==b)or(c:=c+b).count(b)>sum(y!=x==b for x,y in zip(s,k))for a,b in zip(s,k)]==l][0];yield k;w-={k} ``` [Try it online!](https://tio.run/##jVDBbuIwFLznK7yn2O0D2dlLReWVQrAWJLOmULXVpjmEENgobBIlKZRW/Xbql4LaY21pNG88M3pydWj/lcXPq6o@HlfpmqzpBhrYs4FD1mVNtiQryGaQyzDv5hznPcnWNBlI12VlHfZoLOXSMpSSyyXrJ@VT0dIl@9U8/aeHH/LZvnfpZzhg/iWraAM5Y6jFsPyqRVJuo5BH14cs3a5Ifr3vydf87YjWNm1a9JZVWlDO@nUaryjrN9U2a6n7WDwWLu5NLmIgDZCEyC5yMjD7srFSGIpeZvfbsW6nHTbWEdIaaRxZ3976mrSlybkcXIb5qsbkxfmTPiV29PA4/jAYqQ@EkQr8IahRMPTh5l7Nbx1HCE@IE34rwLng/JtWYa8juCfOgd/GLNQHglZT8wcWgTEzbLXHQb/ouEXPQxSd3iH3ED2OusDBOq3pVD1WWhtnEcz9GaiZCcYQTO4mGoZKW/7XmOkCtPanPig1nygY@9rXVtEPD4haQ9fwDg "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 164 bytes ``` f=lambda a,b,c:a and[[w]+f(a[1:],b,c-{w})for w in c for t in[[*b]]if[not a or a in t and t.remove(a)for a in[a[a==b:]or t.remove(a)for a,b in[*zip(w,t)]]]==a[0]][0] ``` [Try it online!](https://tio.run/##tVE9b4MwEN3zK7xh0msE6YbEkABJBxq3IWraWh5MYlSkBBBxitqqv53ahCGfVZecZfn87u69O7v4lO95dlfXibvi63jJEYcYFo46syWlFbtJMKe2wzR6@139mEleogqlGVog7UrlUtqNGUsTmuUScaRQrhOk5kCyV4p1/iEwb0p1hHLKXTd2mK4/CkOsE7pfaYErkCZjzHU5tRhTu16KBFW46dB0OkiRuYhSOuKrjYBJngmYlVvBaCrFmmk67ehWyrxiTbvK0XfOVHUp5LbMUNIQboTEC9PsdIoyzSSuMKUWWGCrbTFQ2a01qHWC2mCfzbWhr/EDtA/tYvuw4Y1JODL2EGwMhp4fQBOAwPeGAwjJmETwrI4I5mTqR/Dy@jYYGr1NsUolNsAwle0NcUGsYT4n5gfeYNiKPc2D6ewytd1OZ5@8xCl6xTbOf9NVBe2d5NHc1v//ekxIdNRGA0EYPJAJRB4hj39PrEn/JXUfhCE5lAq1wS5wKFL/Ag "Python 3 – Try It Online") Based on my answer to [Highlight a Wordle guess](https://codegolf.stackexchange.com/a/246179/87681) [Answer] # Python3, 195 bytes: ``` S=set f=lambda b,t,w,p=[]:f(b[1:],t,w,p+[i for i in S(w)-S(p)if sum(j==k for j,k in zip(i,t))==(J:=(F:=b[0].count)(2))and(sum(l in t for l in i)-J==F(1)or len(S(i)&S(t))-J==F(1))][:1])if b else p ``` [Try it online!](https://tio.run/##rZFRb9owEMff8yksHpZzuaI48DBF8gOEgFSxua2rsS7LQzISzW0IVnCFti9PY0PL1sfSe/H/7nL@/3zRf8zvTTP8rNv9XvJtabyK1/m6WOWkQIM71DzNogqKlEXZodBPFak2LVFENUTCjl5K0FRVZPu0hgfOH133AR9t/6/SoNBQyjlcRRxmES/SIBv82jw1hkJIad6swE7W9nPjZp1U9PKK8xkwaitlAxIU/SShu@ulQbM0Ypm1LkhZb0ui92qtN60hbekVvNfrBQELAo/YCGwcJGOnKgvZUYY2uhlPt6oxUEGaXqzzDr8xqGj2@uS2HFSqWeV1Df7PVd9HUtAMiR/PxWLWZf54Ek8TdCkm03gyxoWYC4nfukPiUtxOJX6//zGe@IOtrpUBH31KqVcwi@ydwcEciPM/gUyTeDw5gtwsk9u7t7ahtWXdIthhEXZB/yRn8ITv4hm@@XNnIQzfhTByCCxgrwgsCNlH8Iwcz1wI6XicwEXyRXxFGQtx/T/J/hk) ]
[Question] [ # Challenge Given a matrix of positive integers, determine if there are any "rings" of mountains. The formal definition for this challenge is: given a matrix of positive integers, is there any positive integer `n` for which there is a closed ring of cells in the matrix that are strictly greater than `n` such that all cells enclosed in the ring are less than or equal to `n`. Let's take a truthy example: ``` 3 4 5 3 3 1 2 3 4 2 1 3 4 3 6 5 ``` If we set `n` to `2`: ``` 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 ``` As we can clearly see, the `1`s along the edge form a ring. We define a ring as an ordered collection of cells where adjacent cells in the collection are also adjacent (edge or corner) on the grid. Additionally, the ring must contain at least 1 cell inside of it; that is, attempting to edge-only BFS-floodfill the entire matrix excluding the cells in the collection and never traversing a cell in the collection must miss at least one cell. # Truthy Test Cases ``` 4 7 6 5 8 -> 1 1 1 1 1 6 2 3 1 5 -> 1 0 0 0 1 (n = 3) 6 3 2 1 5 -> 1 0 0 0 1 7 5 7 8 6 -> 1 1 1 1 1 1 3 2 3 2 1 6 5 7 2 1 7 3 7 4 1 6 8 4 6 1 3 1 3 1 3 1 3 1 7 5 8 7 5 7 8 -> if you have n = 4, you get an interesting ridge shape around the top and right of the grid 8 4 4 2 4 2 7 6 1 8 8 7 2 7 5 4 7 2 5 3 5 5 6 5 1 6 4 5 3 2 3 2 7 4 8 4 4 6 7 7 2 5 3 2 8 2 2 2 8 2 4 8 8 6 8 8 5 7 6 8 6 8 7 -> there is an island in the outer ring (n = 4), but the island is a ring 5 3 2 4 2 4 7 6 3 7 8 5 1 5 8 2 5 2 8 2 7 8 3 8 8 8 4 7 6 1 4 1 1 2 8 5 5 5 5 7 8 7 150 170 150 170 160 170 150 170 150 ``` # Falsy Test Cases ``` 1 2 3 2 1 -> this is just a single mountain if you picture it graphcially 2 3 4 3 2 3 4 5 4 3 2 3 4 3 2 1 2 3 2 1 4 5 4 3 2 -> this is an off-centered mountain 5 6 5 4 3 4 5 4 3 2 3 4 3 2 1 1 1 1 1 1 -> this is four mountains, but they don't join together to form a ring 1 2 1 2 1 1 1 1 1 1 1 2 1 2 1 1 1 1 1 1 3 3 3 3 3 -> there is a ring formed by the `3`s, but the `4` in the middle is taller so it doesn't qualify as a mountain ring 3 1 1 1 3 3 1 4 1 3 3 1 1 1 3 3 3 3 3 3 3 4 4 4 3 4 4 3 4 4 3 3 3 3 4 4 4 3 4 4 3 4 4 4 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 ``` # Rules * Standard Loopholes Apply * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes in each language is declared the winner of its language. No answers will be accepted. * The input may be taken as any reasonable form for a matrix of positive integers * The output may be given as any two reasonable, consistent, distinct values indicating [true] or [false]. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 38 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` Ẇ€Z$⁺Ẏµ,ZẈ>2ẠµƇµḊṖZƊ⁺FṀ<,Z.ịḊṖ$€Ɗ€ƊȦ)Ṁ ``` [Try it online!](https://tio.run/##lVO9TsMwEN77FB66IFmoju06SIiRh0iUkQX1BdiAgVZFYmRmYmKtRMNWpIrXcF8knO8nTls6IFmn@PPn777zXW5vZrO7rovt0@7xoxrvHtrYvmxWuort4qqI7dtmtZ1vVvFzGdev1XYJhOu4vr/U1Xn8eiZ4DFfhJIWf9zM47b7nsOu6eqRUXTutglZTrbxWZaNVDZ@FVlYrAxgDFjEBApIhlnCxaTTqGGGlmFhGVEMGAh5DdJkBIu5Ix6Rz8mCZiiiTyEGJUmwlsUjKoQ2KgQswyKYLAnskEeBR3zNMvsmeYzgXRwVwSso3RYylMrvESAvZ5IucUOmllOSlD/2RmLSDelwuyUoLfO5MKcX0yQPDVtKWeyIGdwaXmPSo4AdNDn1z/ASoIQU/wb7g95RQBPYYuaf92xl@B4uZZVhoRx2xfzL2NVg432FW3zzROWJk1YGOkTcwbNDIwBcZ@BeDhS2m4pVn2uTJtoMmnGQMNLKwk2XzIDJ8eM2dYgw0Dnvl8u9PU3ABlqjHyVwqO1lNzpFn0jgB0wDVALdAbpGmP712mt80mPCjj5pf "Jelly – Try It Online") Outputs **1** if the matrix contains mountain ranges, **0** otherwise. ## How it works (slightly outdated) I may be able to shorten the code a bit, so this section will probably undergo heavy editing. **The helper link** ``` ,Z.ịḊṖ$€Ɗ€ – Helper link. Let S be the input matrix. ,Z – Pair S with its transpose. Ɗ€ – For each matrix (S and Sᵀ), Apply the previous 3 links as a monad. .ị – Element at index 0.5; In Jelly, the ị atom returns the elements at indices floor(x) and ceil(x) for non-integer x, and therefore this returns the 0th and 1st elements. As Jelly is 1-indexed, this is the same as retrieving the first and last elements in a list. ḊṖ$€ – And for each list, remove the first and last elements. ``` For example, given a matrix in the form: ``` A(1,1) A(1,2) A(1,3) ... A(1,n) A(2,1) A(2,2) A(2,3) ... A(2,n) A(3,1) A(3,2) A(3,3) ... A(3,n) ... A(m,1) A(m,2) A(m,3) ... A(m,n) ``` This returns the arrays (the order doesn't matter): ``` A(1,2), A(1,3), ..., A(1,n-1) A(m,2), A(m,3), ..., A(m,n-1) A(2,1), A(3,1), ..., A(m-1,1) A(2,n), A(3,n), ..., A(m-1,n) ``` Long story short, this generates the outermost rows and columns, with the corners removed. **The main link** ``` Ẇ€Z$⁺Ẏµ,ZẈ>2ẠµƇµḊṖZƊ⁺FṀ<ÇȦ)Ṁ – Main link. Let M be the input matrix. Ẇ€ – For each row of M, get all its sublists. Z$ – Transpose and group into a single link with the above. ⁺ – Do twice. So far, we have all contiguous sub-matrices. Ẏ – Flatten by 1 level. µ µƇ – Filter-keep those that are at least 3 by 3: ,Z – Pair each sub-matrix S with Sᵀ. Ẉ – Get the length of each (no. rows, no. columns). >2 – Element-wise, check if it's greater than 2. Ạ – All. µ ) – Map over each sub-matrix S that's at least 3 by 3 ḊṖ – Remove the first and last elements. ZƊ – Zip and group the last 3 atoms as a single monad. ⁺ – Do twice (generates the inner cells). FṀ – Flatten, and get the maximum. <Ç – Element-wise, check if the results of the helper link are greater than those in this list. Ȧ – Any and all. 0 if it is empty, or contains a falsey value when flattened, else 1. Ṁ – Maximum. ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~224~~ ... 161 bytes ``` import StdEnv,StdLib p=prod ~ =map ^ =reverse o$ @ =transpose o~(^o^) $l=:[h:t]|h>1=l=[1: $t] $e=e ?m=p[p(~p(limit(iterate(@o@)(~(~(\a|a>b=2=0))m))))\\n<-m,b<-n] ``` [Try it online!](https://tio.run/##RZBNi8IwEIbv@RWB7aGFFKzaD8Soh93DgjePtYVY4xpoPohRdkH60zc7aRfMMJN5eJPJS7qeM@WlPt97jiUTygtptHX44M4f6kFg24sTMtRYfUYDppIZ1GJq@YPbG8c6QjtMnWXqZnTgIW51m6Cop6v6unLN87rJaE/rbIUj16CIU462kpraxIOJeyGFi4Xjljke7/QuiQeII3uyzYnO6SxJZALreFTrVJLTOlWNPzhmHXoDu86Kb0xxXZckJxUJtSRVQ@qKLCHmY5bABclADycmzkEJfU4WJB@5gD6Duhx5AVrIEjjMC9MKoPHOv15Bhgh6eCnML0JtGjB3uavOCa3A3hbRF06m/W936dnXzaefe//@o5gU3QTTh/v06vPZTP4B "Clean – Try It Online") Defines the function `? :: [[Int]] -> Int`, returning `0` if there is an ring, and `1` otherwise. Works by turning the matrix into `2`s for mountains and `0`s for valleys, then floods in with `1`s until the result stops changing. If any `0`s still exist for any mountain height, the product will be `0`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 302 bytes ``` a=>a.some((b,i)=>b.some((n,j)=>(Q=(W=(i,j,f)=>[a.map((b,I)=>b.map((t,J)=>I==i&J==j)),...a+0].reduce(A=>A.map((b,I)=>b.map((t,J)=>f(I)(J)&&(A[I-1]||b)[J]|(A[I+1]||b)[J]|b[J-1]|b[J+1]|t))))(i,j,I=>J=>a[I][J]<=n)).some((b,i)=>b.some((d,j)=>d&&!i|!j|!Q[i+1]|b[j+1]==b.b))<!/0/.test(W(0,0,I=>J=>!Q[I][J])))) ``` [Try it online!](https://tio.run/##fVJNb@IwEL37V5gL2CKkMbFJKtWRuCAll6qnHrJIJJCuElGCSHbVA/@dnZkYCtLuxnLGM/P85stN8bvotqf62M8O7a66rOylsEnhd@1nJUTp1dImpdMOXgOaeLPi3Yraa7wPUPPC/yyOCE0JSkrvZaCk1tbjzNpGSs/3/WIarP1Ttfu1rcTSJst/3vsQqRSZHI/FMk9nan0@lzLP1mdUp99qmWfoBIHGXsJHWaU2yaCEPF0D6sUepPxrNTuqZjcej@rzqDmP3vJ6SnQNCGtLv5TyZfQUPPl91fXiXQRe4LgBS@QY8rJ6fbVfNtm2h67dV/6@/SlW4svvjvu6F5Mfh4mk2nqb9Fcjd7Zjceqq1b4tKHkGTGITcs0ND1nIFZ@D1PBXJEO@4GbjYJpHqPKYLRAGEAOnkMCGReCJeMwXV7giF2ym6FpEpwgsEddkiyHuA1xRCiGj89WBxDF39AzvYH64IwivwIde1AzXdIJaICFDUTEOVMdcLhgbWJBjAWdCky@GjStmyI2cmF98TcJQ7YMRA4UuBU1JhFS5oT7ElMBAGIEWElnskAqkojbHwDIsvBvd2mACriLYJmAkF6SzOztA7yc/meE3ubVxqFMxlJr6P8wXzne2G@57usa5hsZpegDmjuIBrrhbxESb/de2uT02t2jWiuYdur482tza3L1S7dLSVIe@gfSDzeE2Dy3R9Fqx189cQT8hCuQH8SCwYQpGE3EVc/XM5wGbw1OAcmHCMEp8opc/ "JavaScript (Node.js) – Try It Online") Checks if flowing from a point can't reach the border, while border can walk to every point ]
[Question] [ In this challenge, you need to find a specific pixel within an photograph (taken with a real camera). You are passed an (R, G, B) tuple and an image, and **you need to return a point (x,y) within the image that matches the RGB color given**. The image may have multiple points that match the color; you only need to find 1. The *challenge* is that you need to do it **while reading as few pixels as possible**. Your score will be total number of pixels read across all test cases. If you wish, you can read the entire image into an array of RGB values, as long as you don't do any processing on the pixels. I allow this purely for efficiency purposes. For example, in Python, `list(Image.open("image_name+".jpg").convert("RGB").getdata())` is ok. Hardcoding locations is not allowed. Your algorithm should work well for more than just the test cases listed below. You are not allowed to save data between test cases. I've chosen RGB values that appear infrequently (`<10`) in the image (in case that makes a difference for your algorithm). If you are using randomness in your algorithm, please set a seed, so that your score is constant. Images can be found on [Github](https://github.com/nathanmerrill/images) **Test cases:** ``` image_name: (r, g, b) [all possible answers] barn: (143,91,33) [(887,1096),(2226,1397),(2007,1402),(2161,1508),(1187,1702)] (53,35,59) [(1999,1260)] (20,24,27) [(1328,1087),(154,1271)] (167,148,176) [(1748,1204)] (137,50,7) [(596,1498)] (116,95,94) [(1340,1123)] (72,49,59) [(1344,857),(1345,858),(1380,926),(1405,974),(1480,1117)] (211,163,175) [(1963,745)] (30,20,0) [(1609,1462),(1133,1477),(1908,1632)] (88,36,23) [(543,1494),(431,1575)] daisy: (21,57,91) [(1440,1935),(2832,2090),(2232,2130),(1877,2131),(1890,2132)] (201,175,140) [(1537,1749),(2319,1757)] (169,160,0) [(2124,759)] (113,123,114) [(1012,994),(2134,1060),(1803,1183),(1119,1335)] (225,226,231) [(3207,829),(3256,889),(3257,889),(1434,981),(2599,1118),(2656,1348),(2656,1351)] (17,62,117) [(2514,3874),(2336,3885)] (226,225,204) [(3209,812)] (119,124,146) [(2151,974),(2194,1021),(2194,1022),(2202,1034),(2812,1500)] (2,63,120) [(2165,3881),(2326,3882),(2330,3882),(2228,3887)] (200,167,113) [(1453,1759)] dandelion: (55,2,46) [(667,825),(668,825)] (95,37,33) [(1637,1721),(1625,1724),(1405,1753),(2026,2276),(2016,2298)] (27,41,50) [(1267,126),(424,519),(2703,1323),(1804,3466)] (58,92,129) [(2213,3274)] (136,159,105) [(1300,2363),(2123,2645),(1429,3428),(1430,3432),(1417,3467),(1393,3490),(1958,3493)] (152,174,63) [(2256,2556)] (78,49,19) [(2128,2836)] (217,178,205) [(2736,3531)] (69,95,130) [(870,305),(493,460),(2777,1085),(2791,1292),(2634,3100)] (150,171,174) [(2816,1201),(2724,2669),(1180,2706),(1470,3215),(1471,3215)] gerbera: (218,186,171) [(4282,1342)] (180,153,40) [(4596,1634),(4369,1682),(4390,1708),(4367,1750)] (201,179,119) [(4282,1876),(4479,1928)] (116,112,149) [(5884,252),(4168,371),(4169,372),(4164,384),(5742,576)] (222,176,65) [(4232,1548)] (108,129,156) [(5341,3574),(5339,3595),(5302,3734)] (125,99,48) [(4548,1825),(4136,1932),(5054,2013),(5058,2023),(5058,2035),(5055,2050),(5031,2073)] (170,149,32) [(4461,1630),(4520,1640)] (156,185,203) [(3809,108)] (103,67,17) [(4844,1790)] hot-air: (48,21,36) [(1992,1029),(2005,1030),(2015,1034),(2018,1036)] (104,65,36) [(3173,1890),(3163,1893)] (169,89,62) [(4181,931),(4210,938),(4330,1046),(4171,1056),(3117,1814)] (68,59,60) [(1872,220),(1874,220),(1878,220),(1696,225),(3785,429)] (198,96,74) [(4352,1057)] (136,43,53) [(1700,931)] (82,42,32) [(4556,961),(4559,973),(4563,989),(4563,990),(4441,1004),(4387,1126),(4378,1128)] (192,132,72) [(1399,900),(3105,1822),(3104,1824),(3105,1824),(3107,1826),(3107,1827),(3104,1839),(3119,1852)] (146,21,63) [(1716,993)] (125,64,36) [(4332,937)] in-input: (204,90,1) [(1526,1997),(1385,2145),(4780,2807),(4788,3414)] (227,163,53) [(1467,1739),(2414,1925),(2441,2198),(134,2446)] (196,179,135) [(3770,2740),(1110,3012),(3909,3216),(1409,3263),(571,3405)] (208,59,27) [(1134,1980),(4518,2108),(4515,2142)] (149,70,1) [(4499,1790),(2416,2042),(1338,2150),(3731,2408),(3722,2409),(4400,3618)] (168,3,7) [(987,402),(951,432),(1790,1213),(1790,1214),(1848,1217),(4218,1840),(4344,1870),(1511,1898)] (218,118,4) [(3857,1701),(1442,1980),(1411,2156),(25,2606)] (127,153,4) [(3710,2813)] (224,230,246) [(2086,160),(2761,222),(4482,1442)] (213,127,66) [(4601,1860),(4515,2527),(4757,2863)] klatschmohn: (170,133,19) [(1202,2274),(1202,2275),(957,2493),(1034,2633),(3740,3389),(3740,3391),(3683,3439)] (162,92,4) [(489,2854)] (159,175,104) [(3095,2475),(3098,2481)] (199,139,43) [(1956,3055)] (171,169,170) [(3669,1487),(3674,1490),(3701,1507)] (184,115,58) [(1958,2404)] (228,169,5) [(1316,2336),(1317,2336)] (179,165,43) [(3879,2380),(1842,2497),(1842,2498)] (67,21,6) [(1959,2197),(2157,2317),(2158,2317),(2158,2318),(2116,2373)] (213,100,106) [(1303,1816)] tajinaste-rojo: (243,56,99) [(1811,2876),(1668,4141),(2089,4518),(1981,4732),(1659,4778),(2221,5373),(1779,5598),(2210,5673),(2373,5860)] (147,157,210) [(1835,1028),(1431,3358)] (114,37,19) [(1792,3572),(1818,3592)] (108,117,116) [(2772,4722),(1269,5672),(2512,5811),(2509,5830),(2186,5842),(2186,5846),(2190,5851),(2211,5884)] (214,197,93) [(1653,4386)] (163,102,101) [(2226,2832),(2213,3683),(1894,4091),(1875,4117)] (192,192,164) [(2175,2962),(2206,3667),(2315,3858),(1561,3977),(3039,5037),(3201,5641)] (92,118,45) [(1881,1704),(1983,1877),(2254,2126),(3753,5862),(3766,5883)] (145,180,173) [(1826,1585)] (181,124,105) [(1969,3892)] turret-arch: (116,70,36) [(384,648),(516,669)] (121,115,119) [(2419,958)] (183,222,237) [(172,601),(183,601),(110,611),(111,617)] (237,136,82) [(2020,282),(676,383),(748,406),(854,482),(638,497),(647,661),(1069,838),(1809,895),(1823,911)] (193,199,215) [(1567,919),(1793,1047)] (33,30,25) [(1307,861),(309,885),(1995,895),(504,1232),(2417,1494)] (17,23,39) [(1745,1033),(788,1090),(967,1250)] (192,139,95) [(1445,1337)] (176,125,98) [(1197,1030)] (178,83,0) [(2378,1136)] water-lilies: (86,140,80) [(2322,2855),(4542,3005),(4540,3006),(4577,3019)] (218,124,174) [(1910,2457)] (191,77,50) [(2076,1588)] (197,211,186) [(4402,1894)] (236,199,181) [(2154,1836)] (253,242,162) [(1653,1430)] (114,111,92) [(1936,2499)] (111,93,27) [(2301,2423),(2127,2592),(2137,2717),(2147,2717)] (139,92,102) [(1284,2243),(1297,2258)] (199,157,117) [(3096,993)] ``` [Answer] ## Python, score: 14,035,624 First thing's first, here's the code: ``` from heapq import heappush, heappop from PIL import Image import random random.seed(1) def dist(x, y): return sum([(x[i] - y[i]) ** 2 for i in range(3)]) def gradient_descent(image_name, c): im = Image.open(image_name + '.jpg').convert('RGB') L = im.load() sx, sy = im.size heap = [] visited = set() count = 0 points = [] for i in range(0, sx, sx / 98): for j in range(0, sy, sy / 98): points.append((i, j)) for x in points: heappush(heap, [dist(c, L[x[0], x[1]]), [x[0], x[1]]]) visited.add((x[0], x[1])) while heap: if count % 10 == 0: x = random.random() if x < 0.5: n = heap.pop(random.randint(10, 100)) else: n = heappop(heap) else: n = heappop(heap) x, y = n[1] c_color = L[x, y] count += 1 if c_color == c: p = float(len(visited)) / (sx * sy) * 100 print('count: {}, percent: {}, position: {}'.format(len(visited), p, (x, y))) return len(visited) newpoints = [] newpoints.append((x + 1, y)) newpoints.append((x - 1, y)) newpoints.append((x, y + 1)) newpoints.append((x, y - 1)) newpoints.append((x + 1, y + 1)) newpoints.append((x + 1, y - 1)) newpoints.append((x - 1, y + 1)) newpoints.append((x - 1, y - 1)) for p in newpoints: if p not in visited: try: d = dist(c, L[p[0], p[1]]) heappush(heap, [d, [p[0], p[1]]]) visited.add(p) except IndexError: pass ``` and here's a gif showing how the algorithm examines pixels: ![](https://github.com/Eppie/image-hide-and-seek/blob/master/gifs/water-lilies_197_211_186.gif?raw=true) So, here's what this code is doing: The variable `heap` is a [priority queue](https://en.wikipedia.org/wiki/Priority_queue) of `(x, y)` coordinates in the image, sorted by the Euclidean distance of the color at that coordinate to the target color. It gets initialized with 10,200 points which are evenly distributed across the entire image. With the heap initialized, we then pop off the point with the minimum distance to the target color. If the color at that point has a distance > 0, that is to say, if the color at that point is NOT the target color, we add the 8 surrounding points from it to `heap`. To ensure that a given point isn't considered more than once, we maintain the variable `visited`, which is a set of all the points that have been examined so far. Occasionally, instead of directly taking the point with the minimum color distance, we'll randomly choose some other point from *near* the top of the queue. This isn't strictly necessary, but in my testing, it shaves off approximately 1,000,000 pixels from the total score. Once the target color is found, we simply return the length of the `visited` set. Like @Karl Napf, I ignored the test cases where the specified color was not present in the image. You can find a driver program to run through all the test cases at the [GitHub repository](https://github.com/Eppie/image-hide-and-seek) I created for this answer. Here are the results from each specific test case: ``` barn color: (143, 91, 33), count: 20388 / 0.452483465755%, position: (612, 1131) color: (53, 35, 59), count: 99606 / 2.21061742643%, position: (1999, 1260) color: (72, 49, 59), count: 705215 / 15.6512716943%, position: (1405, 974) daisy color: (21, 57, 91), count: 37393 / 0.154770711039%, position: (1877, 2131) color: (169, 160, 0), count: 10659 / 0.0441179100089%, position: (2124, 759) color: (113, 123, 114), count: 674859 / 2.79326096545%, position: (1119, 1335) color: (225, 226, 231), count: 15905 / 0.0658312560927%, position: (3256, 889) color: (17, 62, 117), count: 15043 / 0.0622634131029%, position: (2514, 3874) color: (226, 225, 204), count: 138610 / 0.573710808362%, position: (1978, 1179) color: (119, 124, 146), count: 390486 / 1.61623287435%, position: (2357, 917) color: (2, 63, 120), count: 10063 / 0.0416510487306%, position: (2324, 3882) color: (200, 167, 113), count: 16393 / 0.06785110224%, position: (1453, 1759) dandelion color: (95, 37, 33), count: 10081 / 0.0686342592593%, position: (1625, 1724) color: (27, 41, 50), count: 2014910 / 13.7180691721%, position: (1267, 126) color: (58, 92, 129), count: 48181 / 0.328029684096%, position: (1905, 756) color: (136, 159, 105), count: 10521 / 0.0716299019608%, position: (1416, 3467) color: (152, 174, 63), count: 10027 / 0.0682666122004%, position: (2256, 2558) color: (69, 95, 130), count: 201919 / 1.37472086057%, position: (2708, 2943) color: (150, 171, 174), count: 29714 / 0.202301198257%, position: (1180, 2706) gerbera color: (180, 153, 40), count: 21904 / 0.0906612910062%, position: (4459, 1644) color: (116, 112, 149), count: 14896 / 0.0616549758413%, position: (5884, 252) color: (222, 176, 65), count: 76205 / 0.315414704215%, position: (4313, 2097) color: (108, 129, 156), count: 12273 / 0.0507983027994%, position: (5302, 3734) color: (125, 99, 48), count: 26968 / 0.111621333814%, position: (5054, 2013) color: (170, 149, 32), count: 89591 / 0.370819746281%, position: (4478, 1647) color: (156, 185, 203), count: 177373 / 0.734151989118%, position: (4096, 368) color: (103, 67, 17), count: 11035 / 0.0456741849093%, position: (4844, 1790) hot-air color: (48, 21, 36), count: 49711 / 0.24902994992%, position: (1990, 1095) color: (104, 65, 36), count: 9927 / 0.0497298447599%, position: (3191, 1846) color: (68, 59, 60), count: 195418 / 0.978957066918%, position: (3948, 470) color: (82, 42, 32), count: 12216 / 0.0611967143737%, position: (4559, 984) color: (192, 132, 72), count: 116511 / 0.583668171938%, position: (3103, 1844) in-input color: (204, 90, 1), count: 44058 / 0.248299807393%, position: (4695, 2559) color: (227, 163, 53), count: 12654 / 0.0713147615132%, position: (221, 2384) color: (196, 179, 135), count: 181534 / 1.02307996812%, position: (1030, 3486) color: (208, 59, 27), count: 9956 / 0.0561095120614%, position: (4518, 2108) color: (149, 70, 1), count: 13698 / 0.0771984829467%, position: (3731, 2408) color: (168, 3, 7), count: 19381 / 0.10922644167%, position: (942, 398) color: (218, 118, 4), count: 36648 / 0.206538911011%, position: (25, 2606) color: (224, 230, 246), count: 1076427 / 6.06647185011%, position: (4482, 1442) color: (213, 127, 66), count: 62673 / 0.353209265712%, position: (4701, 2579) klatschmohn color: (170, 133, 19), count: 11535 / 0.0724321530189%, position: (1034, 2633) color: (162, 92, 4), count: 103795 / 0.651763790429%, position: (489, 2854) color: (159, 175, 104), count: 10239 / 0.0642941321856%, position: (3098, 2481) color: (171, 169, 170), count: 10119 / 0.063540611738%, position: (3674, 1490) color: (184, 115, 58), count: 22425 / 0.140814133632%, position: (1958, 2404) color: (228, 169, 5), count: 10449 / 0.0656127929688%, position: (1316, 2336) color: (179, 165, 43), count: 10285 / 0.0645829816905%, position: (1842, 2498) color: (67, 21, 6), count: 10206 / 0.0640869140625%, position: (2116, 2373) color: (213, 100, 106), count: 11712 / 0.073543595679%, position: (1303, 1816) tajinaste-rojo color: (243, 56, 99), count: 126561 / 0.5273375%, position: (2241, 5424) color: (114, 37, 19), count: 11285 / 0.0470208333333%, position: (1818, 3583) color: (108, 117, 116), count: 33855 / 0.1410625%, position: (1269, 5672) color: (163, 102, 101), count: 1058090 / 4.40870833333%, position: (1546, 4867) color: (192, 192, 164), count: 10118 / 0.0421583333333%, position: (1919, 3171) color: (92, 118, 45), count: 13431 / 0.0559625%, position: (3766, 5883) color: (145, 180, 173), count: 1207713 / 5.0321375%, position: (1863, 955) turret-arch color: (116, 70, 36), count: 145610 / 3.23161258822%, position: (96, 671) color: (183, 222, 237), count: 11704 / 0.259754094722%, position: (140, 604) color: (237, 136, 82), count: 60477 / 1.34220338231%, position: (1063, 993) color: (193, 199, 215), count: 359671 / 7.98240046163%, position: (2259, 953) color: (33, 30, 25), count: 148195 / 3.28898308846%, position: (1307, 861) color: (17, 23, 39), count: 10601 / 0.235274535044%, position: (2080, 1097) color: (192, 139, 95), count: 219732 / 4.87664787607%, position: (1127, 970) color: (176, 125, 98), count: 2471787 / 54.8578942696%, position: (147, 734) water-lilies color: (86, 140, 80), count: 10371 / 0.0717376936238%, position: (4542, 3005) color: (218, 124, 174), count: 25655 / 0.177459312498%, position: (1910, 2457) color: (197, 211, 186), count: 1144341 / 7.91557073177%, position: (4402, 1894) color: (253, 242, 162), count: 14174 / 0.0980435897622%, position: (1672, 1379) color: (111, 93, 27), count: 10405 / 0.0719728764975%, position: (2147, 2717) color: (199, 157, 117), count: 10053 / 0.0695380420403%, position: (3096, 993) Total: 14035624 ``` [Answer] ## Python, score: 396,250,646 * While there are no PNGs to parse and there are still problems with the testcases, I decided to program anyway. * Those testcases where the value is not present in the image were ignored (checked against a traditional linear search, which had a score of **544,017,431**) ``` from PIL import Image def dist(x,y): d = 0 for i in range(3): d += (x[i]-y[i])**2 return d def mid(x,y): return (x+y)/2 class Finder: def __init__(self, image_name, c): self.image_name = image_name, self.c = c self.found = False self.position = None self.im = Image.open(image_name+".jpg").convert("RGB") self.L = self.im.load() self.visited = set() def quadsearch(self,x0,x1,y0,y1): if x0==x1 and y0==y1: return xm=mid(x0,x1) ym=mid(y0,y1) R = [ (x0,xm,y0,ym), (xm,x1,y0,ym), (x0,xm,ym,y1), (xm,x1,ym,y1), ] P = [(mid(t[0],t[1]), mid(t[2],t[3])) for t in R] DR = [] for i in range(len(P)): p = P[i] if p in self.visited: continue self.visited.add(p) u = self.L[p[0], p[1]] d = dist(u, self.c) if d == 0: self.found = True self.position = (p[0], p[1]) return DR.append((d,R[i])) S = sorted(range(len(DR)), key=lambda k: DR[k][0]) for i in S: if self.found == True: return r = DR[i][1] self.quadsearch(r[0], r[1], r[2], r[3]) def start(self): sx,sy = self.im.size self.quadsearch(0,sx,0,sy) def result(self): if self.found: count = len(self.visited) sx,sy = self.im.size ratio = float(count)/(sx*sy) print len(self.visited), ratio, self.position, self.L[self.position[0], self.position[1]], "=", self.c else: print self.c, "not found" if __name__ == "__main__": image_name="turret-arch" c=(116,70,36) F = Finder(image_name, c) F.start() F.result() ``` It is a recursive quad-section search. Sometimes it finds the correct value in a few percent, sometimes over 75%. Here are the results for all testcases: `pixels_visited, percentage, (position) (RGB at position) = (RGB searched)` ``` tajinaste-rojo 1500765 0.062531875 (2329, 5146) (243, 56, 99) = (243, 56, 99) (147, 157, 210) not found 335106 0.01396275 (2116, 5791) (114, 37, 19) = (114, 37, 19) 1770396 0.0737665 (1269, 5672) (108, 117, 116) = (108, 117, 116) (214, 197, 93) not found 8086276 0.336928166667 (1546, 4867) (163, 102, 101) = (163, 102, 101) 12859 0.000535791666667 (1476, 4803) (192, 192, 164) = (192, 192, 164) 7505961 0.312748375 (3766, 5883) (92, 118, 45) = (92, 118, 45) 15057489 0.627395375 (1871, 1139) (145, 180, 173) = (145, 180, 173) (181, 124, 105) not found in-input 35754 0.00201500551852 (4695, 2559) (204, 90, 1) = (204, 90, 1) 5029615 0.283456451895 (10, 2680) (227, 163, 53) = (227, 163, 53) 6986547 0.393744217722 (1383, 3446) (196, 179, 135) = (196, 179, 135) 1608341 0.090642053775 (4518, 2108) (208, 59, 27) = (208, 59, 27) 581774 0.0327873194757 (3750, 2798) (149, 70, 1) = (149, 70, 1) 1302581 0.0734101891628 (4374, 1941) (168, 3, 7) = (168, 3, 7) 6134761 0.345739701008 (25, 2606) (218, 118, 4) = (218, 118, 4) (127, 153, 4) not found 9760033 0.550050913352 (4482, 1442) (224, 230, 246) = (224, 230, 246) 212816 0.0119937745268 (4701, 2579) (213, 127, 66) = (213, 127, 66) water-lilies 5649260 0.390767412093 (4577, 3019) (86, 140, 80) = (86, 140, 80) 12600699 0.871608412215 (1910, 2457) (218, 124, 174) = (218, 124, 174) (191, 77, 50) not found 3390653 0.234536328318 (4402, 1894) (197, 211, 186) = (197, 211, 186) (236, 199, 181) not found 7060220 0.488365537823 (1672, 1379) (253, 242, 162) = (253, 242, 162) (114, 111, 92) not found 6852380 0.473988947097 (2147, 2717) (111, 93, 27) = (111, 93, 27) (139, 92, 102) not found 14105709 0.975712111261 (3096, 993) (199, 157, 117) = (199, 157, 117) dandelion (55, 2, 46) not found 9094264 0.619162854031 (1637, 1721) (95, 37, 33) = (95, 37, 33) 2358912 0.16060130719 (1526, 3129) (27, 41, 50) = (27, 41, 50) 11729837 0.798600013617 (1905, 756) (58, 92, 129) = (58, 92, 129) 6697060 0.455954520697 (2246, 2685) (136, 159, 105) = (136, 159, 105) 6429635 0.437747480937 (2148, 2722) (152, 174, 63) = (152, 174, 63) (78, 49, 19) not found (217, 178, 205) not found 80727 0.00549611928105 (2481, 3133) (69, 95, 130) = (69, 95, 130) 239962 0.0163372821351 (2660, 917) (150, 171, 174) = (150, 171, 174) turret-arch 210562 0.0467313240712 (725, 655) (116, 70, 36) = (116, 70, 36) (121, 115, 119) not found 2548703 0.565649385237 (140, 604) (183, 222, 237) = (183, 222, 237) 150733 0.033453104887 (2165, 601) (237, 136, 82) = (237, 136, 82) 3458188 0.767497003862 (2259, 953) (193, 199, 215) = (193, 199, 215) 2430256 0.539361711572 (265, 1222) (33, 30, 25) = (33, 30, 25) 638995 0.141816103689 (1778, 1062) (17, 23, 39) = (17, 23, 39) 2506522 0.556287895601 (1127, 970) (192, 139, 95) = (192, 139, 95) 1344400 0.298370988504 (147, 734) (176, 125, 98) = (176, 125, 98) (178, 83, 0) not found hot-air 17474837 0.875411434688 (1992, 1029) (48, 21, 36) = (48, 21, 36) 1170064 0.0586149905099 (3191, 1846) (104, 65, 36) = (104, 65, 36) (169, 89, 62) not found 11891624 0.595717352134 (3948, 470) (68, 59, 60) = (68, 59, 60) (198, 96, 74) not found (136, 43, 53) not found 12476811 0.625032612198 (4387, 1126) (82, 42, 32) = (82, 42, 32) 4757856 0.238347376116 (3105, 1822) (192, 132, 72) = (192, 132, 72) (146, 21, 63) not found (125, 64, 36) not found daisy 5322196 0.220287235367 (2171, 2128) (21, 57, 91) = (21, 57, 91) (201, 175, 140) not found 22414990 0.9277629343 (2124, 759) (169, 160, 0) = (169, 160, 0) 20887184 0.864526601043 (1119, 1335) (113, 123, 114) = (113, 123, 114) 595712 0.0246566923794 (2656, 1349) (225, 226, 231) = (225, 226, 231) 3397561 0.140626034757 (2514, 3874) (17, 62, 117) = (17, 62, 117) 201068 0.00832226281046 (1978, 1179) (226, 225, 204) = (226, 225, 204) 18693250 0.773719036752 (2357, 917) (119, 124, 146) = (119, 124, 146) 3091040 0.127939041706 (2165, 3881) (2, 63, 120) = (2, 63, 120) 3567932 0.147677739839 (1453, 1759) (200, 167, 113) = (200, 167, 113) barn 314215 0.0697356740202 (784, 1065) (143, 91, 33) = (143, 91, 33) 2448863 0.543491277908 (1999, 1260) (53, 35, 59) = (53, 35, 59) (20, 24, 27) not found (167, 148, 176) not found (137, 50, 7) not found (116, 95, 94) not found 2042891 0.453391406631 (1345, 858) (72, 49, 59) = (72, 49, 59) (211, 163, 175) not found (30, 20, 0) not found (88, 36, 23) not found klatschmohn 3048249 0.191409829222 (3683, 3439) (170, 133, 19) = (170, 133, 19) 1057649 0.0664133456509 (489, 2854) (162, 92, 4) = (162, 92, 4) 2058022 0.129230138206 (3095, 2475) (159, 175, 104) = (159, 175, 104) (199, 139, 43) not found 2060805 0.129404892156 (3674, 1490) (171, 169, 170) = (171, 169, 170) 7725501 0.485110247577 (1958, 2404) (184, 115, 58) = (184, 115, 58) 2986734 0.187547095028 (1316, 2336) (228, 169, 5) = (228, 169, 5) 497709 0.0312528257017 (3879, 2379) (179, 165, 43) = (179, 165, 43) 3996978 0.250983720944 (2157, 2318) (67, 21, 6) = (67, 21, 6) 3332106 0.209234167028 (1303, 1816) (213, 100, 106) = (213, 100, 106) gerbera (218, 186, 171) not found 9445576 0.390955128952 (4377, 1750) (180, 153, 40) = (180, 153, 40) (201, 179, 119) not found 6140398 0.254152853347 (5742, 576) (116, 112, 149) = (116, 112, 149) 6500717 0.269066561215 (4233, 1541) (222, 176, 65) = (222, 176, 65) 13307056 0.550782905612 (5302, 3734) (108, 129, 156) = (108, 129, 156) 13808847 0.571552180573 (5058, 2023) (125, 99, 48) = (125, 99, 48) 9454870 0.391339810307 (4478, 1647) (170, 149, 32) = (170, 149, 32) 2733978 0.113160142012 (4096, 368) (156, 185, 203) = (156, 185, 203) 11848606 0.490417237301 (4844, 1790) (103, 67, 17) = (103, 67, 17) ``` ]
[Question] [ Automatic house building nanobots have been fabricated, and it's your job to code them. Here is the house created by input `7 4 2` ``` /-----/| / / | |-----| | | | | | | / |_____|/ ``` The input is a string containing the house's dimensions. `7` is the width. ``` |_____| ---7--- ``` `4` is the height. ``` | | | | ``` `2` is the depth ``` / / ``` Given this input, can you create the house? Your code must be as small as possible so that it can fit in the robots. ## Notes The smallest dimensions you will be given as input are `3 2 2`. Your program can do anything with dimensions that are smaller than `3 2 2`. ## Testcases ``` 3 2 10 /-/| / / | / / / / / / / / / / / / / / / / / / / / / / / / |-| / |_|/ ``` [Answer] ## Python 2, 128 bytes ``` w,h,d=input();i=d while-i<h:c='|/'[i>0];print' '*i+c+'- _'[(d>i!=0)+(h+i<2)]*(w-2)+c+' '*min(d-i,h-1,w+1,h-1+i)+'/|'[d-i<h];i-=1 ``` Prints row by row. The row indices `i` count down from `d` to `-h+1`. [Answer] # Ruby, 145 bytes Returns a list of strings. Each element in the list corresponds to a line. If a multiline string must be returned, add 3 bytes to add `*$/` right before the last bracket. ``` ->w,h,d{s=' ';(0..m=d+h-1).map{|i|(i<d ?s*(d-i)+?/:?|)+(i<1||i==d ??-:i==m ??_ :s)*(w-2)+(i<d ? ?/:?|)+(i<h ?s*[i,d].min+?|:s*[m-i,h-1].min+?/)}} ``` [Answer] ## JavaScript (ES6), 169 bytes ``` (w,h,d)=>[...Array(d+h--)].map((_,i)=>` `[r=`repeat`](i<d&&d-i)+(c=`|/`[+(i<d)])+` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+c+` `[r]((i<d?i:d)-(i>h&&i-h))+`|/`[+(i>h)]).join`\n` ``` Where `\n` represents a literal newline character. Explanation: ``` (w,h,d,)=> Parameters [...Array(d+h--)].map((_,i)=> Loop over total height = d + h ` `[r=`repeat`](i<d&&d-i)+ Space before roof (if applicable) (c=`|/`[+(i<d)])+ Left wall/roof edge ` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+ Space, floor or eaves between walls c+ Right wall/roof edge (same as left) ` `[r]((i<d?i:d)-(i>h&&i-h))+ Right wall `|/`[+(i>h)] Back wall/floor edge ).join` Join everything together ` ``` Edit: Saved 2 bytes thanks to @jrich. [Answer] # Python 224 301 297 Bytes (Now Works for all boxes including 1x1x1) ``` l,w,h=input() s,r,d,v,R,x=" "," - ","/","|",range,(l*3-1) print s*(w+1)+r*l for n in R(w): if n<h:e,c=v,n else:e,c=d,h print s*(w-n)+d+s*x+d+s*c+e if h-w>=1:e,c=v,w elif w>h:e,c=d,h else:e,c=d,w print s+r*l+s*c+e for n in R(h): if h>w+n:e,c=v,w else:e,c=d,h-n-1 print v+s*x+v+s*c+e print r*l ``` Explanation: Takes in three constants: l (length), h(height), w(width). If we look at a couple sample boxes we can find patterns in the spacing. For a 3 x 4 x 3 box, we will use numbers to represent spacing between sections. ``` 1234 - - - 123/12345678/| 12/12345678/1| 1/12345678/12| 1 - - - 123| |12345678|123/ | 8|12/ | 8|1/ | 8|/ - - - ``` The top row has 4 spaces or which is w + 1. The Next three lines have w - (1 \* x). X being the line. These are patterns that continue throughout all lines in all boxes. Therefore, we can easily program this line by line, multiplying the number of spaces to fit the pattern. Here is a sample for a 5 x 5 x2 box. ``` 123 - - - - - 12/12345678912345/| 1/ /1| 1 - - - - - 12| | |12| | |12| | |12| | |1/ |12345678912345|/ - - - - - ``` [Answer] # Python 3.5, 328 326 313 305 295 248 bytes (*Thanks to [Kevin Lau](https://codegolf.stackexchange.com/users/52194/kevin-lau-not-kenny) for the tip about reducing the size of the ternary statements!*) ``` def s(w,h,d):R,M=range,max;S,V,L=' |/';O=w-2;D=d-M(0,d-h);Q=h-M(0,h-d);print('\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)])) ``` Takes input as 3 integers in the order of `width, height, depth`. Will golf more over time wherever I can. [Try it online! (Ideone)](http://ideone.com/EDXTBd) ## Explanation: For the purposes of this explanation, assume the function was executed with the arguments `(3,2,3)` where 3 is the width (`w`), 2 is the height (`h`), and 3 is the depth (`d`). That being said, let me begin by showing the main part of the entire function: ``` '\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]) ``` Here, the two lists that make up the entire "house" are created and then joined together by literal new lines (`\n`). Let's call them list `a` and list `b` respectively, and analyze each one of them: * Here is where list `a` is created: ``` [S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))] ``` This list contains the first `d` lines of the house. Here, `i` is each number in the range `0=>(d-(d-h))+d-h` where `d-h=0` if negative or zero. To start, `d-i` spaces are added to the list, followed by a `/` and then whatever is returned by a compressed conditional statement. In this conditional statement, `w-2` number of spaces are returned if `i>1`. Otherwise the same number of `-` are returned. Then, these are followed up by another `/`, and then spaces, where the number of spaces now depends on whether or not `i<=d-(d-h)-1`. If it is, then `i` spaces are added. Otherwise, `h-1` spaces are added. Finally, this is all topped off by either a `/` or a `|`, where `|` is added if `i<=d-(d-h)-1`, otherwise a `/` is added. In this case of a `3x2x3` prism, this would be returned by list `a`: ``` /-/| / / | / / / ``` * Here is where list `b` is created: ``` [V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]` ``` This lists contains the rest of the lines of the prism. In this list, `i` is each integer in the range `(h-(h-d))+h-d=>0` where `h-d=0` if negative or zero. To start this list off, firstly a `|` is added since these lines always start with a `|`. Then, either a space, `-`, or `_` is added depending on whether or not `i=h` or `i<2`. If `i<2`, then a `_` is added. Otherwise, a `-` is added if `i=h`, or a space is added if `i>h` or `i<h` or `i>2`. After this decision has been made, then `w-2` number of the chosen character is added. After this, another `|` is added, and then either `i-1` or `d` number of spaces are added. If `i>h-(h-d)`, then a `d` number of spaces are added. Otherwise, `i-1` number of spaces are added. Finally, this is all topped off with either a `|` or a `/`, in which a `|` is added if `i>h-(h-d)`, or a `/` is added if `i<=h-(h-d)`. In the case of a `3x2x3` prism, list `b` returns: ``` |-| / |_|/ ``` After the 2 lists have been created, they are finally joined with literal new lines (`\n`) using `'\n'.join()`. This is your completed prism, and in this case, would come to look like this: ``` /-/| / / | / / / |-| / |_|/ ``` ]
[Question] [ **Task** The task is to golf a real-time exact string matching algorithm of your choice. **Input** Two lines of text supplied on standard input, separated by a new line. The first line contains the "pattern" and will simply be an ASCII string drawn from the letters `a-z`. The second line contains the longer "text" and will also simply be an ASCII string drawn from the letters `a-z`. **Output** A list of indices of where the exact matches occur. You should output the position of the start of each match that occurs. **Specification** Your algorithm can spend linear time preprocessing the pattern. It must then read the text from left to right and take *constant time* for every single character in the text and output any new match as soon as it occurs. Matches can of course overlap each other. **Algorithm** There are many real-time exact matching algorithms. One is mentioned on the [wiki for KMP](http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm#Variants) for example. You can use any one you like but you must always output the right answer. I will keep a per language leader table so that those who prefer popular languages can also win in their own way. Please explain which algorithm you have implemented. **Real-time** It seems there has been a lot of confusion over what real-time means. It doesn't simply mean linear time. So standard KMP is *not* real-time. The link in the question explicitly points to a part of the wiki page for KMP about a real-time variant of KMP. Neither is Boyer-Moore-Galil real-time. This [cstheory](https://cstheory.stackexchange.com/questions/7392/how-is-real-time-computing-defined) question/answer discusses the issue or one can just google "real-time exact matching" or similar terms. [Answer] # Python 2, 495 bytes This one is a real-time KMP, which is a lot shorter and only slightly slower than the BMG algorithm (which is usually sublinear). Call with `K(pattern, text)`; output is identical to the BMG algorithm. ``` L,R,o=len,range,lambda x:ord(x)-97 def K(P,T): M,N=L(P),L(T);Z=[0]*M;Z[0]=M;r=l=0 for k in R(1,l): if k>r: n=0 while n+k<l<P[n]==P[n+k]:n+=1 Z[k]=n if n>0:l,r=k,k+n-1 else: p,_=k-l,r-k+1 if Z[p]<_:Z[k]=Z[p] else: i=r+1 while i<M<P[i]==P[i-k]:i+=1 Z[k],l,r=i-k,k,i-1 F=[[0]*26]*M for j in R(M-1,0,-1):z=Z[j];i,x=j+z-1,P[z+1];F[i][o(x)]=z s=m=0 while s+m<N: c=T[s+m] if c==P[m]: m+=1 if m==M:print s,;s+=1;m-=1 else: if m==0:s+=1 else:f=F[m][o(c)];s+=m-f;m=f ``` [Answer] # Python 2, 937 bytes This ain't short, by any means, but it (a) works, (b) satisfies all the requirements, and (c) is golfed as much as I can possibly make it. ``` L,r,t,o,e,w=len,range,26,lambda x:ord(x)-97,enumerate,max def m(s,M,i,j,c=0): while i<M-c>j<s[i+c]==s[j+c]:c+=1 return[c,M-i][i==j] def Z(s): M=L(s) if M<2:return[[],[1]][M] z=[0]*M;z[0:2]=M,m(s,M,0,1) for i in r(2,1+z[1]):z[i]=z[1]-i+1 l=h=0 for i in r(2+z[1],M): if i<=h:k=i-l;b,a=z[k],h-i+1;exec["z[i]=b+m(s,M,a,h+1);l,h=i,i+z[i]-1","z[i]=b","z[i]=min(b,M-i);l,h=i,i+z[i]-1"][cmp(a,b)] else: z[i]=m(s,M,0,i) if z[i]>0:l,h=i,i+z[i]-1 return z def S(P,T): M,N=L(P),L(T) if not 0<M<N:return R,a=[[-1]]*t,[-1]*t for i,c in e(P): a[o(c)]=i for j in r(t):R[j]+=a[j], if M<=0:R=[[]]*t n,F,z,l=Z(P[::-1])[::-1],[0]*M,Z(P),0;G=[[-1,M-n[j]][n[j]>0]for j in r(M-1)] for i,v in e(z[::-1]):l=[l,w(v,l)][v==i+1];F[~i]=l k,p=M-1,-1 while k<N: i,h=M-1,k while 0<=i<[]>h>p<P[i]==T[h]:i-=1;h-=1 if i<0 or h==p:print-~k-M,;k+=[1,M-F[1]][M>1] else:c,q=i-R[o(T[h])][i],i+1;s=w(c,q==M or M-[G,F][G[q]<0][q]);p=[p,k][s>=q];k+=s ``` This is an implementation of the Boyer-Moore-Galil algorithm. Pretty straightforward - call with `S(pattern,text)`; the other two functions are used in preprocessing. Indeed, everything but the last 5 lines is preprocessing. An example run, which took about a second: ``` >>> a = 'a'*1000 >>> b = 'a'*1999 + 'b' >>> S(a,b) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ``` [Answer] ## KMP, Python 2(213 bytes) ``` R=raw_input E=enumerate p=R() t=R() f=[-1]*((len(p)+1)) j=-1 for i,c in E(p): while j+1 and p[j]!=c:j=f[j] f[i+1]=j=j+1 j=-1 for i,c in E(t): while j+1 and p[j]!=c:j=f[j] j+=1 if j==len(p):print i+1-j;j=f[j] ``` Ungolfed version. The first loop is to build up the KMP automata. The second loop is walking on the automata. They share nearly the same pattern but abstracting them out will cost more bytes so for a code golf I'd rather duplicate this logic. Similar implementation is actually widely used in programing contests. ``` pattern = raw_input() text = raw_input() fail = [-1] * (len(pattern) + 1) j = -1 for i, c in enumerate(pattern): while j >= 0 and pattern[j] != c: j = fail[j] j += 1 fail[i + 1] = j j = -1 for i, c in enumerate(text): while j >= 0 and pattern[j] != c: j = fail[j] j += 1 if j == len(pattern): print i + 1 - j j = fail[j] ``` [Answer] ## Realtime KMP, Python 2(167 bytes) ``` R=raw_input E=enumerate P=R() T=R() F=[{}] for i,c in E(P):j=F[i].get(c,0);F+=[dict(F[j])];F[i][c]=i+1 j=0 for i,c in E(T): j=F[j].get(c,0) if j==len(P):print i+1-j ``` In normal KMP, we simulate the automaton behavior by using a fail function. In this realtime KMP, the full automaton is constructed so that in the matching phrase it can process each character in realtime(constant time). The preprocessing time and space complexity is O(n m), where m is the alphabet size and n is the length of pattern string. However, in my tests, the actual size of transition table is always less than 2n so maybe we can prove that the time and space complexity is O(n). Ungolfed version ``` pattern = raw_input() text = raw_input() # transitions[i][c] points to the next state walking from state i by c. # Transition that point to staet 0 are not stored. # So use transitions[i].get(c, 0) instead of transitions[i][c] transitions = [{}] for i, c in enumerate(pattern): j = transitions[i].get(c, 0) transitions.append(transitions[j].copy()) # Before this assignment, transitions[i] served as the fail function transitions[i][c] = i + 1 j = 0 for i, c in enumerate(text): j = transitions[j].get(c, 0) if j == len(pattern): print i + 1 - j ``` [Answer] ## Q, 146 Bytes ``` W:S:u:"";n:0;p:{$[n<#x;0;x~(#x)#W;#x;0]};f:{{|/p'x}'((1_)\x#W),\:/:u};F:{S::x 1;W::*x;n::#W;u::?W;T:(f'!1+n),\:0;(&n=T\[0;u?S])-n-1} ``` **Test** ``` F" ABCDABD ABCdABCDABgABCDABCDABDEABCDABzABCDABCDABDE" ``` generates 15 and 34 **Notes** Not restricted to alphabet (support any ascii char, and is case-sensitive). Not uses any of the specific operations defined by Q over strings -> works on strings as sequences (ops match, length, etc.) Minimizes transition table joining all characters not in pattern as one unique character-class. I can squeeze code a little. It's a first attempt to validate solution strategy Visit any character of text exactly once, and for each input character there is a unique jump. So I assume that search fits as 'real time' Table construction al state i and char c search for longest substring that ends at i and after appending c is a prefix of S. Construction is not optimized, so i don't know if its valid Input format doesn't fit well with language. Passing two string arguments will save 16 Bytes **Explanation** global W represents pattern and S corresponds to text to search `x:1_"\n "\:x` weird code to cope with input requirements (Q requires thtat multiline strings has non-first lines indented, so it must discard added space in front of every non-first line) `n::#W` calculates W lenght and save as global n `u::?W` calculates unique chars in W, and save as global u `u?S` generates the characted-class for each char of S Construct a transition table T with one row per unique character in W (plus one extra), and a column for each index in W (plus one extra). Extra row correspond to initial state, and extra column collects any char in S but not in W. This strategy minimizes table size `p:{$[n<#x;0;x~(#x)#W;#x;0]}` is the function that search longest prefix `f:{{|/p'x}'((1_)\x#W),\:/:u}` is the function that calculates a row x of T ``` T:(f'!1+n),\:0 applies f repeteadly to calculate each row, and adds value 0 to each row ``` Search text using transition table. `T\[0;u?S]` iterates over 0 (initial state) and each of the character class of S, using as a new value the value at transitition table T[state][charClass]. Final states has value n, so we look for that value in the sequence of states and returns it adjusted (to indicate initial instead of final position of each match) [Answer] ## Boyer-Moore, Perl (50) Perl attempts to use Boyer-Moore naturally: ``` $s=<>;$g=<>;chomp$g;print"$-[0] "while$s=~m/($g)/g ``` ]
[Question] [ *Idea thanks to @MartinBüttner from a discussion in chat* [Mahjong](https://en.wikipedia.org/wiki/Mahjong) is a tile game that is immensely popular in Asia. It is typically played with four players, and the goal of the game is to be the first person to complete a valid hand using the tiles. For this challenge, we will consider a simplified version of the game — PPCG mahjong. In PPCG mahjong, there are three suits – `m`, `p` and `s` – and the tiles are numbered from `1` to `9`. There are exactly four copies of each tile, and the tiles are denoted by its number followed by its suit (e.g. `3m`, `9s`). A completed PPCG mahjong hand consists of four sets of three and a pair, for a total of 14 tiles. A set of three can be either: * Three of the same tile (e.g. `4s 4s 4s`, but not `4m 4p 4s`), or * A sequence of three consecutive tiles in the same suit (e.g. `1s 2s 3s` or `6p 7p 8p` but not `3s 4m 5m` or `3p 5p 7p`). Sequences do not wrap (so `9m 1m 2m` is invalid). A pair is simply two identical tiles (e.g. `5s 5s`). ## The challenge Your program will receive a space-separated hand of 13 tiles, with each tile appearing no more than four times. You may write either a full program or a function which takes in a string. Your task is to find all possible 14th tiles ("waits") which, when added to the hand, would form a completed PPCG mahjong hand. The outputted tiles should be space-separated, but can be in any order. Leading or trailing whitespace is allowed. Your program should run in a reasonable amount of time, no longer than a minute. ## Examples ``` Input: 1m 1m 1m 4s 4s 4s 7p 7p 7p 3m 3m 3m 9s Output: 9s Input: 1m 1m 1m 3m 3m 3m 5m 5m 5m 2s 3s 7p 8p Output: Input: 1m 2m 2m 3m 3m 3m 3m 4m 1s 1s 9s 9s 9s Output: 1s Input: 1m 1m 1m 2m 3m 4m 5m 6m 7m 8m 9m 9m 9m Output: 1m 2m 3m 4m 5m 6m 7m 8m 9m Input: 1m 1m 1m 5p 2m 3m 5p 7s 8s 5p 9s 9s 9s Output: 1m 4m 6s 9s ``` In the first example, the `1m 4s 7p 3m` all form existing triplets, leaving the lone `9s` to form a pair. In the second example, the `2s 3s` and `7p 8p` can only form sequences, and the remaining tiles can only form triplets. Hence no pair can be formed, and there is no output. In the third example, the hand splits into `1m2m3m 2m3m4m 3m3m 1s1s 9s9s9s`. Normally this would be a wait for `3m 1s`, but as all four `3m` have been used, the only available wait is `1s`. In the fourth example, all of the `m` tiles complete the hand. For example, for `1m`, one could have `1m1m1m 1m2m3m 4m5m6m 7m8m9m 9m9m` which is a completed hand. Try to work out the rest of the fourth example and the fifth example :) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution in the fewest bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny/) apply. [Answer] ## Python, ~~312~~ 281 bytes ``` def W(S):H=lambda C,n=0,t=1:sum([m<C[0]and H([c-s for c in C][:l]+C[l:],n+1,u)for m,s,l,u in(2,3,1,t),(t,2,1,4),(4-5*all(C[:3]),1,3,t)])|H(C[1:],n,t)if C[2:]and max(C)<5else n>4;T=[i+s for s in"mps"for i in"12345678900"];return" ".join(t for t in T if("1"<t)*H(map((S+t).count,T))) ``` `W` takes a string as input and returns a string as output. The small number of tiles (27) makes it fast enough to test if each of them completes the hand. The problem becomes to check if a hand is valid. The function uses a simple backtracking algorithm that considers all possible choices of sets and checks if any of them adds up to a complete hand. Hands are represented as tile histograms, i.e. a list of tile counts (for all the tiles, not only the ones present in the hand.) This makes it easy to both check if we have a certain number of a certain tile, and if we have a sequence of adjacent tiles (padding between tiles of different suits prevent multi-suit sequences.) [Answer] # JavaScript (E6) 306 ``` F=h=>( R=(a,p,n=1)=>(a=[...a]).splice(p,n)&&a, K=(t,d=3)=> !t[0] |t.some( (v,p)=> v==t[p+1]&v==t[p+d-1]&& K(R(t,p,d)) || ~((r=t.indexOf((x=-~v[0])+v[1]))|(s=t.indexOf(-~x+v[1])))&& K(R(R(R(t,s),r),p)) ), o=[], [for(s of'mps')for(i of'123456789')h.replace(t=i+s,s,'g')[34] &&K([t,...h.split(' ')].sort(),2)&&o.push(t) ],o ) ``` **Explained** ``` F=hand=>( Remove=(a,p,n=1)=> // function to remove 1 or more element from an array, returning a new shorter array ((a=[...a]).splice(p,n), a), // using array.splice on a new created array Check=(ckHand, dim)=> // recursive function to check hand. // removing pairs (at iteration 0) or sequence of three, if at last the hand remain empty then success // parameter dim is 2 or 3 indicating how many equal elements are to be removed !ckHand[0] // check if empty (element 0 does not exist) |ckHand.some( // else traverse all array checking what can be removed (value, position)=> value == ckHand[position + 1] & value == ckHand[position + dim-1] && // look for 3 (or 2) equal elements Check(Remove(ckHand, position, dim), 3) // if found, then remove elements and check again || ~((r = ckHand.indexOf((x=-~value[0]) + value[1])) // value[0] is number, value[1] is suit |(s = ckHand.indexOf(-~x + value[1]))) && // look for an ascending sequence in following elements (the array is sorted) Check(Remove(Remove(Remove(ckHand, s), r), position),3) // if sequence found, remove elements and check again ), output=[], // start with an empty solution list [ // using array comprehension to implement a double loop for(s of'mps') // loop for all suits for(i of'123456789') // loop for all numbers ( tile=i+s, // current tile (hand.replace(tile,' ','g').length > 34) // if tile is present 4 times in hand, the replaced length is 38-4 == 34 && ( // else proceed with check ckHand = hand.split(' '), ckHand.push(tile), // in ckHand (as an array) the hand to be checked, that is base hand + current tile ckHand.sort(), // sorting the array simplfy the checks Check(ckHand, 2) // start checks looking for a pair ) && output.push(tile) // if check ok, add tile to the solution list ) ], output // last expression in list is the function return value ) ``` **Test** in FireFox/FireBug console ``` ;["1m 1m 1m 4s 4s 4s 7p 7p 7p 3m 3m 3m 9s", "1m 1m 1m 3m 3m 3m 5m 5m 5m 2s 3s 7p 8p", "1m 2m 2m 3m 3m 3m 3m 4m 1s 1s 9s 9s 9s", "1m 1m 1m 2m 3m 4m 5m 6m 7m 8m 9m 9m 9m", "1m 1m 1m 5p 2m 3m 5p 7s 8s 5p 9s 9s 9s"].forEach(s=>console.log(s+' => '+F(s))) ``` *Output* ``` 1m 1m 1m 4s 4s 4s 7p 7p 7p 3m 3m 3m 9s => 9s 1m 1m 1m 3m 3m 3m 5m 5m 5m 2s 3s 7p 8p => 1m 2m 2m 3m 3m 3m 3m 4m 1s 1s 9s 9s 9s => 1s 1m 1m 1m 2m 3m 4m 5m 6m 7m 8m 9m 9m 9m => 1m,2m,3m,4m,5m,6m,7m,8m,9m 1m 1m 1m 5p 2m 3m 5p 7s 8s 5p 9s 9s 9s => 1m,4m,6s,9s ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 241 bytes ``` s=>[...Array(i=27)].flatMap(_=>A([...s,k=--i%9+1+'mps'[i/9|0]])>/^(..)(.*\1){4}/.test(k+s)?k:[]) A=s=>s.some(t=>R(s,t,t,t)|t[1]<'z'&R(s,t,t[0]-1+t[1],t[0]-2+t[1]))|s[0]==s[1]&!s[2] R=(s,p,q,r,z=0,k=s.filter(y=>y!=p||z++))=>p?z&&R(k,q,r):A(s) ``` [Try it online!](https://tio.run/##TZDBctowEIbvfgrlUKytjIwNKZBUznDprZf06CiMB@TUxcbCKzIDMc9OJWNCRt9odlf//pL2X/ae4aoptBlu67U65@KMIkk554umyQ60EPEUJM/LzPzONF2KZEHdKQYbMRwW3@YsYn6l0U@LcN6OpIQkfKWcA@XfXyL4mJxCbhQaumEIT5uHVIK3EPYK5FhXihqRPFMMjFvQmjSSP/2jP@hr6UgOI@aqlzjuYoAWbSYE2mRwh2ksvWdhO3SwC5rgKEb2ccjzojSqoQeRHO6EbtsjYwAi0U/HgfXfOC08LCjC@dFr1G5fNIr6OfrAG5WtfxWl@nPYrugo8Pcmn3VlXWYrRUPOwrfA/uHDI@Q9a4ghgqTy0WZ4E9GXNbNTACsldOneBpcOQtwAteTVZaCG6z3@pUu2A3Aep25f1VusS8XL@s3@LKfGHZ7gHFXkwgR7prpnXPXM0fuUfRbvr8RIxl3XTDtZ3DH@wsQ2omPec3OLrwLr86Mi04rM7HU9N9m97pU2mCKZoQuubv8B "JavaScript (Node.js) – Try It Online") Came from [the more complex checker](https://codegolf.stackexchange.com/q/242582/) and made small changes ]
[Question] [ Given a non-empty list **L** of integers greater than **1**, we define **d(L)** as the smallest positive integer such that **n + d(L)** is [composite](https://en.wikipedia.org/wiki/Composite_number) for each **n** in **L**. We define the sequence **an** as: * **a0 = 2** * **ai+1** is the smallest integer greater than **ai** such that **d(a0, ..., ai, ai+1) > d(a0, ..., ai)** ## Your task You may either: * Take an integer **N** and return the **N-th** term of the sequence (0-indexed or 1-indexed) * Take an integer **N** and return the first **N** terms of the sequence * Take no input and print the sequence forever This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! It's OK if your code is getting slow as **N** gets larger, but it should at least find the 20 first terms in less than 2 minutes. ## First terms * **a0 = 2** and **d(2) = 2** (we need to add 2 so that 2+2 is composite) * **a1 = 3** because **d(2, 3) = 6** (we need to add 6 so that 2+6 and 3+6 are composite) * **a2 = 5** because **d(2, 3, 5) = 7** (we need to add 7 so that 2+7, 3+7 and 5+7 are all composite), whereas **d(2, 3, 4)** is still equal to **6** * etc. Below are the 100 first terms of the sequence (unknown on OEIS at the time of posting). ``` 2, 3, 5, 6, 10, 15, 17, 19, 22, 24, 30, 34, 35, 39, 41, 47, 51, 54, 56, 57, 70, 79, 80, 82, 92, 98, 100, 103, 106, 111, 113, 116, 135, 151, 158, 162, 165, 179, 183, 186, 191, 192, 200, 210, 217, 223, 226, 228, 235, 240, 243, 260, 266, 274, 277, 284, 285, 289, 298, 307, 309, 317, 318, 329, 341, 349, 356, 361, 374, 377, 378, 382, 386, 394, 397, 405, 409, 414, 417, 425, 443, 454, 473, 492, 494, 502, 512, 514, 519, 527, 528, 560, 572, 577, 579, 598, 605, 621, 632, 642 ``` [Answer] # Pyth, 24 bytes ``` Pu+GfP_+Tf!fP_+ZYG)eGQ]2 ``` [Demonstration](https://pyth.herokuapp.com/?code=Pu%2BGfP_%2BTf%21fP_%2BZYG%29eGQ%5D2&input=10&debug=0) Basically, we start with `[2]`, then add elements 1 at a time by alternately finding `d`, then adding an element, and so forth. Outputs the first `n` elements of the sequence. Contains a filter inside a first integer filter inside a first integer filter inside an apply repeatedly loop. **Explanation:** ``` Pu+GfP_+Tf!fP_+ZYG)eGQ]2 u Q]2 Starting with `[2]`, do the following as many times as the input f ) Starting from 1 and counting upward, find d where !f G None of the elements in the current list P_+ZY plus d give a prime. f eG Starting from the end of the current list and counting upward, find the first number which P_+T plus d gives a prime. +G Append the new number to the current list P Trim the last element of the list ``` There's obvious repeated effort between the two "Add and check if prime" calls, but I'm not sure how to eliminate it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes ``` ṛ,;1+ÆPẸṆʋ1#ⱮẎ</ Ḷ߀‘Ṫç1#ƊḢƲ2⁸? ``` [Try it online!](https://tio.run/##AUYAuf9qZWxsef//4bmbLDsxK8OGUOG6uOG5hsqLMSPisa7huo48LwrhuLbDn@KCrOKAmOG5qsOnMSPGiuG4osayMuKBuD////85 "Jelly – Try It Online") Jelly sucks at recurrence sequences. :/ [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 74 bytes ``` K`__; "$+"{/;(?!(__+)\1+\b)/+`; ;_ .+$ $&¶$& )/;(__+)\1+$/+`.+$ _$&_ %`\G_ ``` [Try it online!](https://tio.run/##K0otycxLNPz/3zshPt6aS0lFW6la31rDXlEjPl5bM8ZQOyZJU187wZrLOp5LT1uFS0Xt0DYVNS5NoBqoAhWgNEgmXkUtnks1IcY9/v9/Q0sA "Retina – Try It Online") 0-indexed. Explanation: ``` K`__; ``` Each line `i` in the workarea contains two unary values, `aᵢ;d+aᵢ`. We start with `a₀=2` and `d+a₀=0` (because it's golfier). ``` "$+"{ ... ) ``` Repeat the loop `N` times. ``` /;(?!(__+)\1+\b)/+` ``` Repeat while there is at least one non-composite number. ``` ; ;_ ``` Increment `d`. ``` .+$ $&¶$& ``` Duplicate the last line, copying `aᵢ₋₁` to `aᵢ`. ``` /;(__+)\1+$/+` ``` Repeat while `d+aᵢ` is composite. ``` .+$ _$&_ ``` Increment `aᵢ`. ``` %`\G_ ``` Convert the results to decimal. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~138~~ ~~130~~ 128 bytes ``` import StdEnv $l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1 ``` # ``` map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2]) ``` [Try it online!](https://tio.run/##HcyxCsMgFIXhvU/hkEEpEdKxxE7tUOiWMTpc1CbC9SYkJhDos9dKp/Nzhs@iB8pxcht6FiFQDnGelsS65B60nypUG6WAXO8KsAwpoIPzVjQTG6zjdN6F6C9SlqgbI1AEsqzJXYKiqGLObHQ8JL9A8lyjGl3f0xWN1tTW/egYSmk@rPqfN1ahKZ4R@WvfCMOa6@cr3w@CGOz6Aw "Clean – Try It Online") ***Expanded:*** ``` $l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1 $l=until( )inc 1 // first value from 1 upwards where _ \v=all( )l // _ is true for everything in l \n=any( )[2..n+v-1] // any of [2,3..n+v-1] match _ gcd(n+v) // the gcd of (n+v) and ^ o // (composed) ^ is _ (<)1 // greater than 1 ``` # ``` map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2]) map hd( ) // the first element of each list in _ iterate( )[2] // infinite repeated application of _ to [2] \l=hd[ ] // the head of _ [n:l] // n prepended to l \\n<-[hd l..] // for every integer n greater than the head of l | $[n:l]> $l // where d(n0..ni+1) > d(n0..ni) ``` [Answer] # [Julia 0.6](http://julialang.org/), ~~145~~ 130 bytes ``` ~L=(x=1;while any(map(m->all(m%i>0 for i=2:m-1),L+x));x+=1;end;x) !n=n<1?[2]:(P=!(n-1);t=P[end]+1;while ~[P;t]<=~P;t+=1;end;[P;t]) ``` [Try it online!](https://tio.run/##NYyxCoMwFEX3fkUcCi@kgsnQwfjsDzhkDw6BWpqSPEUsTRd/PQ0Fpwv3nnNf7@DdNed9QEgo9efpw8QcfSG6BWLduxAgnn3fsMe8Mo@qjbXkl0EkznUSRZnorhM/VYTUyZtVYwsGK6CC6Q2NLfsojufdGr2NHe4lDvlf8bysnrZAUKmG5x8 "Julia 0.6 – Try It Online") *(-15 bytes using my new and improved golfing skills - operator overloads, replacing conditional by ternary and hence removing `return` keyword.)* **Expanded**: ``` function primecheck(m) all(m%i>0 for i∈2:m-1) end function d(L) x = 1 while any(map(primecheck, L+x)) x += 1 end return x end function a(n) n > 0 || return [2] Prev = a(n-1) term = Prev[end] + 1 while d([Prev;term]) ≤ d(Prev) term += 1 end return [Prev;term] end ``` ]
[Question] [ > > This post is loosely inspired by [this mathoverflow post](https://mathoverflow.net/q/289810/119216). > > > A Vanisher is any pattern in Conway's Game of life that completely disappears after one step. For example the following pattern is a size 9 Vanisher. [![Size 9 Vanisher](https://i.stack.imgur.com/NTqvF.png)](https://i.stack.imgur.com/NTqvF.png) An interesting property of Vanishers is that *any pattern* can be made into a vanishing one by simply adding more live cells. For example the following pattern can be completely enclosed into a vanishing pattern like so [![Non-Vanishing](https://i.stack.imgur.com/TVqOb.png)](https://i.stack.imgur.com/TVqOb.png)[![Enclosed](https://i.stack.imgur.com/M35gJ.png)](https://i.stack.imgur.com/M35gJ.png) However we can make that pattern into a Vanisher by adding even fewer live cells. [![Smaller Enclosure](https://i.stack.imgur.com/hwVAy.png)](https://i.stack.imgur.com/hwVAy.png) [![Even Smaller Enclosure](https://i.stack.imgur.com/qCo5P.png)](https://i.stack.imgur.com/qCo5P.png) Your task is to write a program that does this task for us. That is given a pattern as input find and output a vanishing pattern containing the input. You do not necessarily have to find the optimal pattern just a pattern that works. ## Scoring To score your program you will have to run it on all of the size 6 polyplets (not double counting symmetrically equivalent cases). [Here](https://pastebin.com/raw/JjfwPNi9) is a pastebin containing each polyplet on its own line. There should be 524 of them total. They are represented as a list of six coordinates (`(x,y)` tuples) each being the location of a live cell. Your score will be the total number of new cells added to make all of these polyplets into Vanishers. ### Ties In the case of ties I will provide a list of the size 7 polyplets for the programs to be run on. ## IO I would like IO to be pretty flexible you can take input and output in reasonable formats however you are probably going to want to take input in the same format as the raw input data I provided. Your format should be consistent across multiple runs. ## Timing Your program should run in a reasonable amount of time (approx <1 day) on a reasonable machine. I'm not going to really be enforcing this too much but I'd prefer if we would all play nice. [Answer] # Python + [Z3](https://github.com/Z3Prover/z3), score = 3647 Runs in 14 seconds on my eight core system. ``` from __future__ import print_function import ast import multiprocessing import sys import z3 def solve(line): line = ast.literal_eval(line) x0, x1 = min(x for x, y in line) - 2, max(x for x, y in line) + 3 y0, y1 = min(y for x, y in line) - 2, max(y for x, y in line) + 3 a = {(x, y): z3.Bool('a_{}_{}'.format(x, y)) for x in range(x0, x1) for y in range(y0, y1)} o = z3.Optimize() for x in range(x0 - 1, x1 + 1): for y in range(y0 - 1, y1 + 1): s = z3.Sum([ z3.If(a[i, j], 1 + ((i, j) != (x, y)), 0) for i in (x - 1, x, x + 1) for j in (y - 1, y, y + 1) if (i, j) in a ]) o.add(z3.Or(s < 5, s > 7)) o.add(*(a[i, j] for i, j in line)) o.minimize(z3.Sum([z3.If(b, 1, 0) for b in a.values()])) assert o.check() == z3.sat m = o.model() return line, {k for k in a if z3.is_true(m[a[k]])} total = 0 for line, cells in multiprocessing.Pool().map(solve, sys.stdin): added = len(cells) - len(line) print(line, added) x0, x1 = min(x for x, y in cells), max(x for x, y in cells) + 1 y0, y1 = min(y for x, y in cells), max(y for x, y in cells) + 1 for y in range(y0, y1): print(''.join('#' if (x, y) in line else '+' if (x, y) in cells else ' ' for x in range(x0, x1))) total += added print('Total:', total) ``` [Full output](https://glot.io/snippets/ex2cce6wcq/raw/vanishers.out) ]
[Question] [ note: the string art might look horrible here because of SE font weirdness :P :( Given a list of four-tuples representing the corners of rectangles, draw translucent rectangles over each other in that order. For this challenge, you are required to have the smallest coordinate in the top-left corner and the x-axis increasing to the right and the y-axis increasing downwards. A four-tuple `(x0, y0, x1, y1)` or `(x0, x1, y0, y1)` represents the `(x, y)` coordinate pairs of the top-left and bottom-right corners of a rectangle (you may choose either of the two formats for rectangles but it must be consistent) What do I mean by "translucent rectangle"? Well, for this challenge, you will be using the space character and most of the [box-drawing](https://en.wikipedia.org/wiki/Box-drawing_character) characters; specifically, all of the ones used to draw rectangles, including "bold" characters. When a translucent rectangle is drawn, first all thin lines in the space being occupied disappear and all bold lines become thin, and then the rectangle itself is drawn over in bold lines. For example, if you draw a rectangle in the top-left and then in the bottom-right, it might look something like this: ``` ┏━━━━┓ ┃ ┃ ┃ ┃ ┃ ┏━━╇━━┓ ┃ ┃ │ ┃ ┗━╉──┘ ┃ ┃ ┃ ┃ ┃ ┗━━━━━┛ ``` To be clear, lines are lightened (bold -> thin -> none) for all lines strictly within the rectangle (for example, downwards facing lines are affected for the top edge but not the bottom edge). # Test Cases Some number of lines of input will be given, followed by unicode-art, for each test case. ``` 0 0 5 5 5 5 10 10 3 3 7 7 2 2 8 8 ┏━━━━┓ ┃ ┃ ┃ ┏━━╇━━┓ ┃ ┃┌─┴─┐┃ ┃ ┃│ │┃ ┗━╉┤ ├╊━┓ ┃│ │┃ ┃ ┃└─┬─┘┃ ┃ ┗━━╈━━┛ ┃ ┃ ┃ ┗━━━━┛ 14 5 15 9 13 2 15 16 6 4 15 11 ┏━┓ ┃ ┃ ┏━━━━━━╇━┫ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┗━━━━━━╈━┫ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┗━┛ 6 8 10 11 15 12 16 16 14 10 16 16 9 1 15 15 ┏━━━━━┓ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┏━━╉┐ ┃ ┃ ┃│ ┃ ┃ ┃│ ┌╊┓ ┗━━╉┘ │┃┃ ┃ │┠┨ ┃ │┃┃ ┃ │┃┃ ┗━━━━╈┩┃ ┗┷┛ ``` [Generate more test cases!](https://tio.run/##dVbJbuNGED1bX1GAD5IcWtASx44Q5xJfDPgQGDFgg9GBFltSj6kmQbYicU6Zyb5v1dn3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lVel0nCuE2IZKZrfKqtlMq6m31W@b7P7VH@erAwh7Z7nBcuuF50msNcuxTTPsG4aevHvAAzi3RhbZNe9m1YcUDux8IstctUQZGvBRTNnaRS6Vq12rgWS8Uxk1rZt57F17miihwncaptVmHMhLiYtkT@XjGnvGhVrMtUwMYpgA13q9XhAWg21tc42IyN5pQ2sP3E3ces5Ver9i@qZqXq4KIqL1X2Kwibm7APxXzz00GXiVPcURPB6iLbRsD0qrBmHbLhvgcHtuCSk0fVHCtVcAcP7CkKxodhALNucco0szWre3DSBexkvmWOj5v8J2EN1ip8QavJv0qHW38d1itt/o@wARv/Aw) # Rules * Input can be in any reasonable format for a list of four-tuples. Input can be one-indexed or zero-indexed along either axis (i.e. the top-left corner can be any of `(0, 0)`, `(0, 1)`, `(1, 0)`, `(1, 1)`. * Output must be as unicode-art as described. Output may not have leading newlines and can have at most one trailing newline (after the last line). Trailing whitespace will be ignored for the purposes of this challenge. # Code-points The bold and light horizontal and vertical pipes are in the range `[U+2500, U+2503]`. The various corner pipes are in the range `[U+250C, U+251C)`. The three-armed pipes are in the range `[U+251C, U+253C)`. The four-armed pipes are in the range `[U+253C, U+254C)`. The remaining pipes that can be found in my program are never actually used. [Answer] # [Python 3](https://docs.python.org/3/), ~~289~~ 286 bytes ``` l,u=eval(input()) *_,w,h=map(max,zip(*l)) r=[*map(list,[' '*-~w]*-~h)] R=range for x,y,X,Y in l: for i in R(x,X+1): for j in R(y,Y+1):Q=i<X,y<j,x<i,j<Y;r[j][i]=u[sum(3**o*max(Q[o]*[j in(y,Y),i in(x,X)][o%2]*2,u.index(r[j][i])//3**o%3-Q[o])for o in R(4))] for l in r:print(''.join(l)) ``` [Try it online!](https://tio.run/##LY/pTttAFIX/5yksJBTbvUBIikA0fgj4lciyqkhNG0eOHZmkOP1RFehC9@3c7vu@76W0dHmX8yLpTKk0ujr305xzZvqjQSdLa@NxIsOgfbiVuHHaHw5czyv5@2VVOkGv1Xd7rUKOxH3XTwzPg9C3MIlXBhKWnbI/dXQ1MqPjRaXlIG@lh9qlg1nuFDKShjSdOHWSxZJjUWyXZbeQxp5Zz7B/sLsLR9K0cCmI6w0Z1btS1GPp1pv78rAbhXEUDMOVYc@t@X5m@gt3KcwiP7Rma/XEZttkLwqzyWrkV2U4HacH2oX7P8CbmbHmydqUtXq2Otut3uuZp9s9sXu@2M/jdOCWy9PdzGSaT4/HoVuRiszJnCeumTJbMcfomtRkXuaNqkpVFmTBi2TCoW5Rf1C/EiCU@p24RlynfiGOUX8SNwijt4hbxDZhLm9TfxNrxE3CGL8Rtwlj3KEafY44T6wTd4i71D/EPeIhcYl4Q7wjnhAm1iQ8o5qK48Rl4i3xnnhK/CKM5SV1g3qKukNcIC5SDb9PPCI2iAfEY@IK8YH4RDynrlFPEi@o69QzxFXiI/GZeEU9Qd0kXlNPU89O/AU "Python 3 – Try It Online") Takes input as a list of 4-tuples: `(x0, y0, x1, y1)`, along with the pipedrawing characters as follows: `" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"` Supports boxes of zero width or height (uses all box drawing chars). Based on [my answer](https://codegolf.stackexchange.com/a/141294/38592) to [this question](https://codegolf.stackexchange.com/questions/140905/unicode-rectangles/), but modified to alter existing boxes when drawing. **'Ungolfed':** ``` u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋" #Create array of spaces: l=eval(input()) w,h=list(map(max,zip(*l)))[2:] r=[[' ']*w for _ in' '*h] for x,y,X,Y in l: n,m=X-1,Y-1 for i in range(x,X): for j in range(y,Y): A,B=j in(y,m),i in(x,n) P=(i<n*A,y<j*B,x<i*A,j<m*B) # Pipe sides of the new box Q=(i<n,y<j,x<i,j<m) # Pipe sides that are inside the new box, and should be thinned. # Get new pipe (sides of new box, on top of thinned pipes of existing boxes. (u.index... is existing pipe)) l=sum(3**o*max(P[o]*2,(u.index(r[j][i])//3**o%3)-Q[o])for o in range(4)) #Add to 'canvas' r[j][i]=u[l] print('\n'.join(''.join(l)for l in r)) ``` [Answer] ## JavaScript (ES6), ~~298~~ 261 bytes ``` (a,u,m=n=>[...Array(1+Math.max(...a.map(t=>t[n])))])=>m(3).map((_,j)=>m(2).map((_,i)=>u[a.reduce((c,[x,y,v,w])=>i<x|j<y|i>v|j>w?c:(g=n=>c-=c/n%3|0&&n,h=n=>c+=n*(2-(c/n%3|0)),[i>x&&9,i<v].map(j>y&j<w?g:h),[j>y&&3,j<w&&27].map(i>x&i<v?g:h),c),0)]).join``).join`\n` ``` Where `\n` represents the literal newline character. Based on my answer to [Unicode rectangles](https://codegolf.stackexchange.com/questions/140905). Explanation: An array of strings of spaces is created to draw in. Each spaces is then processed by looping over all the boxes in the input. Characters that lie outside of the box are then ignored but those on the edge or inside are processed further. For each of the four line segments making up a character (each represented by a power of 3) there are then three possibilities; a) the segment lies just outside the box and should be ignored (achieved by passing a parameter of 0 instead of the power of 3) b) the segment lies on the edge of the box and should be bold (achieved by calling the `h` function) c) the segment lies inside the box and should be lightened (achieved be calling the `g` function). The character is then indexed into the Unicode string. Once all the boxes have been processed the array is then joined on newlines. ``` f= (a,u,m=n=>[...Array(1+Math.max(...a.map(t=>t[n])))])=>m(3).map((_,j)=>m(2).map((_,i)=>u[a.reduce((c,[x,y,v,w])=>i<x|j<y|i>v|j>w?c:(g=n=>c-=c/n%3|0&&n,h=n=>c+=n*(2-(c/n%3|0)),[i>x&&9,i<v].map(j>y&j<w?g:h),[j>y&&3,j<w&&27].map(i>x&i<v?g:h),c),0)]).join``).join` ` ;u=" ╶╺╵└┕╹┖┗╴─╼┘┴┶┚┸┺╸╾━┙┵┷┛┹┻╷┌┍│├┝╿┞┡┐┬┮┤┼┾┦╀╄┑┭┯┥┽┿┩╃╇╻┎┏╽┟┢┃┠┣┒┰┲┧╁╆┨╂╊┓┱┳┪╅╈┫╉╋"; [[ [0, 0, 5, 5], [5, 5, 10, 10], [3, 3, 7, 7], [2, 2, 8, 8], ],[ [14, 5, 15, 9], [13, 2, 15, 16], [6, 4, 15, 11], ],[ [6, 8, 10, 11], [15, 12, 16, 16], [14, 10, 16, 16], [9, 1, 15, 15], ]].map(a=>document.write(`<pre style="font-family:Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,sans-serif">${f(a,u)}</pre>`)); ``` ]
[Question] [ You are given 6 numbers: 5 digits [0-9] and a target number. Your goal is to intersperse operators between the digits to get as close as you can to the target. You have to use each digit **exactly** once, and can use the following operators **as many** times as you want: `+ - * / () ^ sqrt sin cos tan`. For example, if I'm given `8 2 4 7 2 65` I can output `82-(2*7)-4`. This evaluates to 64, thus giving me a score of 1 since I was 1 away from the target. **Note:** You can not put a decimal point between digits. I am using the code from this [StackOverflow answer](https://stackoverflow.com/a/26227947/5311008) to evaluate the mathematical expressions. At the bottom of this question there are programs you can use to test it out. ## Chaining Functions (Update!) @mdahmoune has revealed a new level of complexity to this challenge. As such, I'm adding a new feature: chaining unary functions. This works on sin, cos, tan, and sqrt. Now instead of writing `sin(sin(sin(sin(10))))`, you can write `sin_4(10)`. Try it out in the evaluator! ## Input 200 line-separated test cases of 5 digits and a target number that are space-separated. You can use the program at the bottom of the question to make sample test cases, but I will have my own test cases for official scoring. The test cases are broken up into 5 sections of 40 tests with the following ranges for the target number: * Section 1: [0,1] (to 5 decimal points) * Section 2: [0,10] (to 4 decimal points) * Section 3: [0,1000] (to 3 decimal points) * Section 4: [0,106] (to 1 decimal point) * Section 5: [0,109] (to 0 decimal points) ## Output 200 line separated mathematical expressions. For example, if the test case is `5 6 7 8 9 25.807`, a possible output could be `78-59+6` ## Scoring The goal each round is to get closer to the target number than the other competing programs. I'm going to use [Mario Kart 8 scoring](http://mariokart.wikia.com/wiki/Driver%27s_Points), which is: `1st: **15** 2nd: **12** 3rd: **10** 4th: **9** 5th: **8** 6th: **7** 7th: **6** 8th: **5** 9th: **4** 10th: **3** 11th: **2** 12th: **1** 13th+: **0**`. If multiple answers get the same exact score, the points are split evenly, rounded to the nearest int. For example, if the programs in 5th-8th place are tied, they each get (8+7+6+5)/4 = 6.5 => **7** points that round. At the end of 200 rounds, the program that got the most points wins. If two programs have the same number of points at the end, the tie-breaker is the program that finished running faster. ## Rules 1. You can only use one of the languages commonly pre-installed on Mac like C, C++, Java, PhP, Perl, Python (2 or 3), Ruby, and Swift. If you have a language you want to use with a compiler/interpreter that is a relatively small download I may add it. You can also use a language with an online interpreter, but that will not run as fast. 2. Specify in your answer if you want trig functions to be calculated in **degrees** or **radians**. 3. Your program must output its solutions to all 200 test cases (to a file or STDOUT) within **60 seconds** on my Mac. 4. Randomness must be seeded. 5. Your total output for all test cases can't be more than **1 MB**. 6. If you have improved your solution and would like to be re-scored, add **Re-Score** at the top of your answer in bold. ## Programs (change the "deg" argument to "rad" if you want radians) 1. **[Test out evaluator](https://tio.run/##rVfdb9s2EH@2/goiDzUVx7LdtRsaNSuGtdvL2g1N91Q0NSPTFlOZUkgqcZf4b8/uKErWl5MgqAAn4pH3u0/enS7YFRunGZcXi293Yp2lypALoAW5EUlwGjEpuQq9LD9PRESihGlN3jMhyc2dNswA7TxNE84kWfCV4lyTE7JkieYVjzu2SGHJCb9iCV0KyRJyapSQK9hXPrnxCDyKm1xJIvk1@fv8gkeGljv4CGlIlqKA8eyIRHHoVVtXqVgA28b8HjPVYMInioGHjkbI/BrlBQmXKxNT3ydv7DoCtt8MhQM@OQb4sOLf7oSUhnJmKOqCTJ/Sd8y05V3HAiylKPaEDMnQr6kWNk6KZXlsLxg@@9hrPjMq583NrddzzIWmxzoXn4wpzT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0npT6AEqCEYLiVeSw8hxOSXpdDbIksJfAZv4OcWXpaE0zHFr1OqSB1jU6eIS4f5APgIC3qORdOY1cxExqnKRWoBZPBGf5Mlf2MIkrRTtvQKRT4sq1yTdHuukyIO0dlVxjuXTIJ@VeBBGgTAeJhGRLvhHYUrGGyGS2LPtsQiPfQGuCQPZOl1xTWe6tp4eZ3qupPBUeW7@/seWSMvyDrZIK/8jeYa2SSvySuA9db89aZZvITNdX/1/sX6Sm@tDUib3dfdV9215sv2RhvfNu@hrf0D)** 3. Generate test cases: ``` document.getElementById("but").onclick = gen; var checks = document.getElementById("checks"); for(var i = 1;i<=6;i++) { var val = i<6 ? i : "All"; var l = document.createElement("label"); l.for = "check" + val; l.innerText = " "+val+" "; checks.appendChild(l); var check = document.createElement("input"); check.type = "checkBox"; check.id = "check"+val; if(val == "All") { check.onchange = function() { if(this.checked == true) { for(var i = 0;i<5;i++) { this.parentNode.elements[i].checked = true; } } }; } else { check.onchange = function() { document.getElementById("checkAll").checked = false; } } checks.appendChild(check); } function gen() { var tests = []; var boxes = checks.elements; if(boxes[0].checked)genTests(tests,1,5,40); if(boxes[1].checked)genTests(tests,10,4,40); if(boxes[2].checked)genTests(tests,1000,3,40); if(boxes[3].checked)genTests(tests,1e6,1,40); if(boxes[4].checked)genTests(tests,1e9,0,40); document.getElementById("box").value = tests.join("\n"); } function genTests(testArray,tMax,tDec,n) { for(var i = 0;i<n;i++) { testArray.push(genNums(tMax,tDec).join(" ")); } } function genNums(tMax,tDec) { var nums = genDigits(); nums.push(genTarget(tMax,tDec)); return nums; } function genTarget(tMax,tDec) { return genRand(tMax,tDec); } function genRand(limit,decimals) { var r = Math.random()*limit; return r.toFixed(decimals); } function genDigits() { var digits = []; for(var i = 0;i<5;i++) { digits.push(Math.floor(Math.random()*10)); } return digits; } ``` ``` textarea { font-size: 14pt; font-family: "Courier New", "Lucida Console", monospace; } div { text-align: center; } ``` ``` <div> <label for="checks">Sections: </label><form id="checks"></form> <input type="button" id="but" value="Generate Test Cases" /><br/><textarea id="box" cols=20 rows=15></textarea> </div> ``` ## Leaderboard 1. user202729 ([C++](https://codegolf.stackexchange.com/a/140473/46313)): 2856, *152 wins* 2. mdahmoune ([Python 2](https://codegolf.stackexchange.com/a/140415/46313)) [v2]: 2544, *48 wins* ### Section scores (# of wins): 1. [0-1] **user202729**: 40, mdahmoune: 0 2. [0-10] **user202729**: 40, mdahmoune: 0 3. [0-1000] **user202729**: 39, mdahmoune: 1 4. [0-106] **user202729**: 33, mdahmoune: 7 5. [0-109] user202729:0, **mdahmoune**: 40 Related: [Generate a valid equation using user-specified numbers](https://codegolf.stackexchange.com/questions/6417/generate-a-valid-equation-using-user-specified-numbers) [Answer] # C++ ``` // This program use radian mode //#define DEBUG #ifdef DEBUG #define _GLIBCXX_DEBUG #include <cassert> #else #define assert(x) void(0) #endif namespace std { /// Used for un-debug. struct not_cerr_t { } not_cerr; } template <typename T> std::not_cerr_t& operator<<(std::not_cerr_t& not_cerr, T) {return not_cerr;} #include <iostream> #include <iomanip> #include <cmath> #include <limits> #include <array> #include <bitset> #include <string> #include <sstream> #ifndef DEBUG #define cerr not_cerr #endif // DEBUG // String conversion functions, because of some issues with MinGW template <typename T> T from_string(std::string st) { std::stringstream sst (st); T result; sst >> result; return result; } template <typename T> std::string to_string(T x) { std::stringstream sst; sst << x; return sst.str(); } template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } const int N_ITER = 1000, N_DIGIT = 5, NSOL = 4; std::array<int, N_DIGIT> digits; double target; typedef std::bitset<N_ITER> stfunc; // sin-tan expression // where sin = 0, tan = 1 double eval(const stfunc& fn, int length, double value) { while (length --> 0) { value = fn[length] ? std::tan(value) : std::sin(value); } return value; } struct stexpr { // just a stfunc with some information double x = 0, val = 0; // fn<length>(x) == val int length = 0; stfunc fn {}; // bool operator[] (const int x) {return fn[x];} double eval() {return val = ::eval(fn, length, x);} }; struct expr { // general form of stexpr // note that expr must be *always* atomic. double val = 0; std::string expr {}; void clear() { val = 0; expr.clear(); } // cos(cos(x)) is in approx 0.5 - 1, // so we can expect that sin(x) and tan(x) behaves reasonably nice private: void wrapcos2() { expr = "(cos_2 " + expr + ")"; // we assume that all expr is atomic val = std::cos(std::cos(val)); } public: void wrap1() { if (val == 0) { expr = "(cos " + expr + ")"; // we assume that all expr is atomic val = std::cos(val); } if (val == 1) return; wrapcos2(); // range 0.54 - 1 int cnt_sqrt = 0; for (int i = 0; i < 100; ++i) { ++cnt_sqrt; val = std::sqrt(val); if (val == 1) break; } expr = "(sqrt_" + to_string(cnt_sqrt) + " " + expr + ")"; // expr must be atomic } }; stexpr nearest(double initial, double target) { stexpr result; // built on the fn of that result.x = initial; double value [N_ITER + 1]; value[0] = initial; for (result.length = 1; result.length <= N_ITER; ++result.length) { double x = value[result.length-1]; if (x < target) { result.fn[result.length-1] = 1; } else if (x > target) { result.fn[result.length-1] = 0; } else { // unlikely --result.length; // result.val = x; result.eval(); assert(result.val == x); return result; } value[result.length] = result.eval(); // this line takes most of the time if (value[result.length] == value[result.length-1]) break; } // for (int i = 0; i < N_ITER; ++i) { // std::cerr << i << '\t' << value[i] << '\t' << (value[i] - target) << '\n'; // } double mindiff = std::numeric_limits<double>::max(); int resultlength = -1; result.length = std::min(N_ITER, result.length); for (int l = 0; l <= result.length; ++l) { if (std::abs(value[l] - target) < mindiff) { mindiff = std::abs(value[l] - target); resultlength = l; } } result.length = resultlength; double val = value[resultlength]; assert(std::abs(val - target) == mindiff); if (val != target) { // second-order optimization for (int i = 1; i < result.length; ++i) { // consider pair (i-1, i) if (result.fn[i-1] == result.fn[i]) continue; // look for (sin tan) or (tan sin) if (val < target && result.fn[i-1] == 0) { // we need to increase val : sin tan -> tan sin result.fn[i-1] = 1; result.fn[i] = 0; double newvalue = result.eval(); // if (!(newvalue >= val)) std::cerr << "Floating point sin-tan error 1\n"; if (std::abs(newvalue - target) < std::abs(val - target)) { // std::cerr << "diff improved from " << std::abs(val - target) << " to " << std::abs(newvalue - target) << '\n'; val = newvalue; } else { result.fn[i-1] = 0; result.fn[i] = 1; // restore #ifdef DEBUG result.eval(); assert(val == result.val); #endif // DEBUG } } else if (val > target && result.fn[i-1] == 1) { result.fn[i-1] = 0; result.fn[i] = 1; double newvalue = result.eval(); // if (!(newvalue <= val)) std::cerr << "Floating point sin-tan error 2\n"; if (std::abs(newvalue - target) < std::abs(val - target)) { // std::cerr << "diff improved from " << std::abs(val - target) << " to " << std::abs(newvalue - target) << '\n'; val = newvalue; } else { result.fn[i-1] = 1; result.fn[i] = 0; // restore #ifdef DEBUG result.eval(); assert(val == result.val); #endif // DEBUG } } } } double newdiff = std::abs(val - target); if (newdiff < mindiff) { mindiff = std::abs(val - target); std::cerr << "ok\n"; } else if (newdiff > mindiff) { std::cerr << "Program error : error value = " << (newdiff - mindiff) << " (should be <= 0 if correct) \n"; std::cerr << "mindiff = " << mindiff << ", newdiff = " << newdiff << '\n'; } result.eval(); // set result.result assert(val == result.val); return result; } expr nearest(const expr& in, double target) { stexpr tmp = nearest(in.val, target); expr result; for (int i = 0; i < tmp.length; ++i) result.expr.append(tmp.fn[i] ? "tan " : "sin "); result.expr = "(" + result.expr + in.expr + ")"; result.val = tmp.val; return result; } int main() { double totalscore = 0; assert (std::numeric_limits<double>::is_iec559); std::cerr << std::setprecision(23); // double initial = 0.61575952241185627; // target = 0.6157595200093855; // stexpr a = nearest(initial, target); // std::cerr << a.val << ' ' << a.length << '\n'; // return 0; while (std::cin >> digits[0]) { for (unsigned i = 1; i < digits.size(); ++i) std::cin >> digits[i]; std::cin >> target; /* std::string e; // int sum = 0; // for (int i : digits) { // sum += i; // e.append(to_string(i)).push_back('+'); // } // e.pop_back(); // remove the last '+' // e = "cos cos (" + e + ")"; // double val = std::cos(std::cos((double)sum)); // // stexpr result = nearest(val, target); // cos(cos(x)) is in approx 0.5 - 1, // // so we can expect that sin(x) and tan(x) behaves reasonably nice // std::string fns; // for (int i = 0; i < result.length; ++i) fns.append(result.fn[i] ? "tan" : "sin").push_back(' '); // // std::cout << (fns + e) << '\n'; // continue;*/ std::array<expr, NSOL> sols; expr a, b, c, d; // temporary for solutions /* ---------------------------------------- solution 1 : nearest cos cos sum(digits) */ a.clear(); for (int i : digits) { a.val += i; // no floating-point error here a.expr.append(to_string(i)).push_back('+'); } a.expr.pop_back(); // remove the last '+' a.expr = "(" + a.expr + ")"; a.wrap1(); sols[0] = nearest(a, target); /* ----------------------------------------- solution 2 : a * tan(b) + c (also important) */ // find b first, then a, then finally c a.clear(); b.clear(); c.clear(); // e = a, b = e1, c = e2 a.expr = to_string(digits[0]); a.val = digits[0]; a.wrap1(); b.expr = "(" + to_string(digits[1]) + "+" + to_string(digits[2]) + ")"; b.val = digits[1] + digits[2]; b.wrap1(); c.expr = to_string(digits[3]); c.val = digits[3]; c.wrap1(); d.expr = to_string(digits[4]); d.val = digits[4]; d.wrap1(); b = nearest(b, std::atan(target)); double targetA = target / std::tan(b.val); int cnt = 0; while (targetA < 1 && targetA > 0.9) { ++cnt; targetA = targetA * targetA; } a = nearest(a, targetA); while (cnt --> 0) { a.val = std::sqrt(a.val); a.expr = "sqrt " + a.expr; } a.expr = "(" + a.expr + ")"; // handle number of the form 0.9999999999 /// partition of any number to easy-to-calculate sum of 2 numbers {{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}} double targetC, targetD; // near 1, not in [0.9, 1), >= 0.1 // that is, [0.1, 0.9), [1, inf) double target1 = target - (a.val * std::tan(b.val)); double ac = std::abs(target1), sc = sgn(target1); if (ac < .1) targetC = 1 + ac, targetD = -1; else if (ac < 1) targetC = 1 + ac/2, targetD = ac/2 - 1; else if (ac < 1.8 || ac > 2) targetC = targetD = ac/2; else targetC = .8, targetD = ac - .8; targetC *= sc; targetD *= sc; c = nearest(c, std::abs(targetC)); if (targetC < 0) c.val = -c.val, c.expr = "(-" + c.expr + ")"; d = nearest(d, std::abs(targetD)); if (targetD < 0) d.val = -d.val, d.expr = "(-" + d.expr + ")"; sols[1].expr = a.expr + "*tan " + b.expr + "+" + c.expr + "+" + d.expr; sols[1].val = a.val * std::tan(b.val) + c.val + d.val; std::cerr << "\n---Method 2---" << "\na = " << a.val << "\ntarget a = " << targetA << "\nb = " << b.val << "\ntan b = " << std::tan(b.val) << "\nc = " << c.val << "\ntarget c = " << targetC << "\nd = " << d.val << "\ntarget d = " << targetD << "\n"; /* ----------------------------------------- solution 3 : (b + c) */ target1 = target / 2; b.clear(); c.clear(); for (int i = 0; i < N_DIGIT; ++i) { expr &ex = (i < 2 ? b : c); ex.val += digits[i]; ex.expr.append(to_string(digits[i])).push_back('+'); } b.expr.pop_back(); b.expr = "(" + b.expr + ")"; b.wrap1(); c.expr.pop_back(); c.expr = "(" + c.expr + ")"; c.wrap1(); b = nearest(b, target1); c = nearest(c, target - target1); // approx. target / 2 sols[2].expr = "(" + b.expr + "+" + c.expr + ")"; sols[2].val = b.val + c.val; /* ----------------------------------------- solution 4 : a (*|/) (b - c) (important) */ a.clear(); b.clear(); c.clear(); // a = a, b = e1, c = e2 a.expr = to_string(digits[0]); a.val = digits[0]; a.wrap1(); b.expr = "(" + to_string(digits[1]) + "+" + to_string(digits[2]) + ")"; b.val = digits[1] + digits[2]; b.wrap1(); c.expr = "(" + to_string(digits[3]) + "+" + to_string(digits[4]) + ")"; c.val = digits[3] + digits[4]; c.wrap1(); // (b-c) should be minimized bool multiply = target < a.val; double factor = multiply ? target / a.val : a.val / target; target1 = 1 + 2 * factor; // 1 + 2 * factor and 1 + factor std::cerr << "* Method 4 :\n"; std::cerr << "b initial = " << b.val << ", target = " << target1 << ", "; b = nearest(b, target1); std::cerr << " get " << b.val << '\n'; std::cerr << "c initial = " << c.val << ", target = " << b.val - factor << ", "; c = nearest(c, b.val - factor); // factor ~= e1.val - e2.val std::cerr << " get " << c.val << '\n'; sols[3].expr = "(" + a.expr + (multiply ? "*(" : "/(") + ( b.expr + "-" + c.expr ) + "))"; factor = b.val - c.val; sols[3].val = multiply ? a.val * factor : a.val / factor; std::cerr << "a.val = " << a.val << '\n'; /* ---------------------------------- Final result */ int minindex = 0; assert(NSOL != 0); for (int i = 0; i < NSOL; ++i) { if (std::abs(target - sols[i].val) < std::abs(target - sols[minindex].val)) minindex = i; std::cerr << "Sol " << i << ", diff = " << std::abs(target - sols[i].val) << "\n"; } std::cerr << "Choose " << minindex << "; target = " << target << '\n'; totalscore += std::abs(target - sols[minindex].val); std::cout << sols[minindex].expr << '\n'; } // #undef cerr // in case no-debug std::cerr << "total score = " << totalscore << '\n'; } ``` Input from standard input, output to standard output. [Answer] # [Python 2](https://docs.python.org/2/), radians, score 0.0032 on official test This is the second draft solution gives an average score of 0.0032 points. As it uses a composition of a lot of `sin` I used the following compact notation for the output formula: * `sin_1 x=sin(x)` * `sin_2 x=sin(sin(x))` * `...` * `sin_7 x=sin(sin(sin(sin(sin(sin(sin(x)))))))` * `...` ``` import math import bisect s1=[[float(t) for t in e.split()] for e in s0.split('\n')] maxi=int(1e7) A=[] B=[] C=[] D=[] a=1 for i in range(maxi): A.append(a) C.append(1/a) b=math.sin(a) c=a-b B.append(1/c) D.append(c) a=b B.sort() C.sort() A.sort() D.sort() d15={0:'sqrt_100 tan_4 cos_2 sin 0',1:'sqrt_100 tan_4 cos_2 sin 1',2:'sqrt_100 tan_2 cos_2 sin 2',3:'sqrt_100 tan_4 cos_2 sin 3',4:'sqrt_100 tan_4 cos_2 sin 4',5:'sqrt_100 tan_4 cos_2 sin 5',6:'sqrt_100 tan_4 cos_2 sin 6',7:'sqrt_100 tan_2 cos_2 sin 7',8:'sqrt_100 tan_2 cos_2 sin 8',9:'sqrt_100 tan_4 cos_2 sin 9'} def d16(d):return '('+d15[d]+')' def S0(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(B, r)-1 w1=abs(r-B[i1]) i2=bisect.bisect(C, w1)-1 w2=abs(w1-C[i2]) s='('+d16(a1)+'/(sin_'+str(i1)+' '+d16(a2)+'-'+'sin_'+str(i1+1)+' '+d16(a3)+')'+'+'+d16(a4)+'/sin_'+str(i2)+' '+d16(a5)+')' return (w2,s) def S1(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(C, r)-1 w1=abs(r-C[i1]) i2=bisect.bisect(A, w1)-1 w2=abs(w1-A[i2]) s='('+d16(a1)+'/sin_'+str(i1)+' '+d16(a2)+'+sin_'+str(maxi-i2-1)+' ('+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')' return (w2,s) def S2(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(A, r)-1 w1=abs(r-A[i1]) i2=bisect.bisect(D, w1)-1 w2=abs(w1-D[i2]) s='('+'(sin_'+str(maxi-i2-1)+' '+d16(a1)+'-'+'sin_'+str(maxi-i2)+' '+d16(a2)+')'+'+sin_'+str(maxi-i1-1)+' ('+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+'))' return (w2,s) def S3(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(A, r)-1 w2=abs(r-A[i1]) s='('+'sin_'+str(maxi-i1-1)+' ('+d16(a1)+'*'+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+'))' return (w2,s) def S4(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(B, r)-1 w2=abs(r-B[i1]) s='('+d16(a1)+'/(sin_'+str(i1)+' '+d16(a2)+'-'+'sin_'+str(i1+1)+' '+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')'+')' return (w2,s) def S5(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(C, r)-1 w2=abs(r-C[i1]) s='('+d16(a1)+'/sin_'+str(i1)+' '+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')' return (w2,s) def S6(l): cpt=0 d=l[:-1] r=l[-1] a1,a2,a3,a4,a5=[int(t) for t in d] i1=bisect.bisect(D, r)-1 w2=abs(r-D[i1]) s='(sin_'+str(maxi-i1-1)+' '+d16(a1)+'-'+'sin_'+str(maxi-i1)+' '+d16(a2)+'*'+d16(a3)+'*'+d16(a4)+'*'+d16(a5)+')' return (w2,s) def all4(s1): s=0 for l in s1: f=min(S0(l),S1(l),S2(l),S3(l),S4(l),S5(l),S6(l)) print f[1] s+=f[0] s/=len(s1) print 'average unofficial score:',s all4(s1) ``` [Try it online!](https://tio.run/##tVddc1u3EX0WfsWd9IFkRMHA4tszfJClf9BHReOh9ZFwRpZUkqnb6fS3u2cPoJiRI6Vp4@FY5sVdALtnz55dPv5z/9PDvXzeudV3332XpoaPm2RyNtUas3FTndIU8XHWV5Fo0pSxJlPAiiQJ3uj7AitdqRJLMgGnBJ4Em@Akm4xdAR/PXb4ErOg9iSfHElww/anoPlurEzF6qsdtRf1p4gtscCbOqepPqt7hHPXa46@zrjYfTcRTw0kahdQSdFfAe@FKCbU2o75k2uGc7KWZ7l/iOSFLFsZe1WNdaSXpSsEZXLPR56BReOwqHR/E1Yx6k4kHbMS7alxHlDbZSUy8PY64XEgpm0QLwU4iHyqiyDiJ8dpcKmw8vQsd@VZCMpUe1458Fue5C9jwdinNOSIvuE1tSqmhYVdmFOpPial4o5lSbxRVF0NsjLTyg9hxuRiN0g/EpAUwQb1rPAmRuhLUw4ibe@ylSAxkiwwb58Q32GTio/7ElKOeU8kOZjmFUhBF@5Iv34LyJ/L@zsMQPfOluVfEGtAQ4uOHzz45n5gdZnRKuKsV05OuZtHG5hWvyj3wyKbY9BBP55BEmxwW1FvHCMRGENX0clAiFNCL/E9kMjCzJEUguErAar3L3tAnItps9vAjE3DdFGwKtUdDt3BLSqBjLyimzpYsjYf2aMS6nJrR8/0oO@9cAY5PGRLNkDfCwCo9rdULUZTOEIssB6Nlov8UIBSlZscNPHAGqskoGo7lXEF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nx7PD18aFBWGjMx/rhc9TTDqzlwDbRFhB02OafZLlbDLj8N4Hr7Cu4zl6C6/Q34Dp9Ca5X0Dr@8k6r/2QjJzSZHwD2/QFY3/8X4Mg3Aef0K3BOXwLn/DfAOf81OLP5C4Ef4PZrJg2rZ/iRTM@N/B/A8CUQwzcGUZ6BOGD5nVD8gfty8P1/CjF@Y82RZ5rzp6rIy0XxcmGkb6wa8kw1/oAOfP9/1Hv@JmGdfxXW@UFYL/D0d6r3T4x6fXcX5zuvge80bA3mjpOYx9LR7eojJiS21SW7xZKyuGRdL0n9JfmwJHyI6uhxC1ym2wtF7Gh3vLq9cPi2e7O6u7nXm8ywmK3/frNd/3gz/Xz/cHu7udqs76bd1cP25u1suTNPfn3@/B8 "Python 2 – Try It Online") ]
[Question] [ Let's imagine we have a finite set of positive integers. This set can be represented as a line of dots where each integer present in the set is filled in like a scantron or [punch card](https://en.wikipedia.org/wiki/Punched_card). For example the set `{1,3,4,6}` could be represented as: ``` *.**.* ``` `*` represents a member of our set and `.` represents an integer that is not a member oft he set. These sets have "factors". Loosely x is a factor of y if y can be built out of copies of x. More rigorously our definition of factor is as follows: * x is a factor of y if and only if y is the union of a number of *disjoint* sets, all of which are x with an offset. We would call `*.*` a **factor** of `*.**.*` because it is quite clearly made up of two copies of `*.*` put end to end. ``` *.**.* ------ *.*... ...*.* ``` Factors don't have to be end to end, we would also say that `*.*` is a factor of `*.*.*.*` ``` *.*.*.* ------- *.*.... ....*.* ``` Factors can also overlap. This means `*.*` is also a factor of `****` ``` **** ---- *.*. .*.* ``` However a number cannot be covered by a factor more than once. For example `*.*` is *not* a factor of `*.*.*`. --- Here is a more complicated example: ``` *..*.**..***.*.* ``` This has `*..*.*` as a factor. You can see that below where I have lined up the three instances of `*..*.*`. ``` *..*.**..***.*.* ---------------- *..*.*.......... ......*..*.*.... ..........*..*.* ``` # Task Given a set by any reasonable representation output all the sets that are factors of the input. You may index by any value, (that is you may select a smallest number that can be present in the input). You may also assume that the input set will always contain that smallest value. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so you should aim to do this in as few bytes as possible. # Test Cases *These test cases were done by hand, there may be a mistake or two on the larger ones* ``` * -> * *.*.* -> *, *.*.* *.*.*.* -> *, *.*, *...*, *.*.*.* ****** -> *, **, *..*, ***, *.*.*, ****** *..*.**..***.*.* -> *, *..*.*, *.....*...*, *..*.**..***.*.* *...*****.**.** -> *, *...**.**, *.....*, *...*****.**.** ``` [Answer] ## Mathematica, ~~71~~ 68 bytes ``` #&@@@Cases[(s=Subsets)@s@#,x_/;Sort[Join@@x]==#&&Equal@@(#&@@@x-x)]& ``` Input as `{1,3,5,7}` (sorted) and output as `{{1, 3, 5, 7}, {1, 3}, {1, 5}, {1}}`. The function will throw a bunch of messages. This is **O(22Nope)** (where **N** is the length of the input and **o=p=e=1**...). It generates all subsets of subsets, then selects those that result in the input send when joined together (ensuring we're only considering partitions) and where all elements are the same if we subtract the smallest value of each subset). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ;÷@DỊȦ ÆDçÐf ``` Input and output use `1` and `0` instead of `*` and `.`. [Try it online!](https://tio.run/##y0rNyan8/9/68HYHl4e7u04s4zrc5nJ4@eEJaf8Ptz9qWuP@/7@hjoKhARBCKTADDEACID6INIQrAXMMwcKGhgA "Jelly – Try It Online") ### How it works ``` ÆDçÐf Main link. Argument: n (integer with decimal digits 1 and 0) ÆD Compute all divisors of n. çÐf Filter; call the helper link with left argument d and right argument n for all divisors d of n. Return the array of d's for which the helper link returns a truthy value. ;÷@DỊȦ Helper link. Left argument: d. Right argument: n ÷@ Divide n by d. ; Concatenate, yielding [d, n÷d]. D Decimal; convert both integers in the pair to base 10. Ị Insignificant; map 1 and 0 to 1, all other positive integers to 0. Ȧ All; return 1 iff the result contains no zeroes. ``` ]
[Question] [ I think it's easiest to explain this challenge in a sequential manner. Start with an input number \$N\$ and: 1. Find its highest prime factor 2. Check numbers above and below \$N\$ and see if the highest prime factor is higher (i.e. the highest prime factor of \$N-1\$ and/or \$N+1\$ is higher than the factor of \$N\$. 3. Continue to check higher **and/or** lower numbers neighboring \$N\$ in the directions where the highest factors are increasing (\$(N-2, N-3 ...)\$ and/or \$(N+2, N+3 ...)\$ and so on) 4. Once there aren't any prime factors in either direction that are higher than the ones we've already found we stop and output the highest prime factor we have encountered. Let's look at an example: `245` has the prime factors `5, 7, 7`. Its neighbors are: ``` 244 -> 2, 2, 61 245 -> 5, 7, 7 246 -> 2, 3, 41 ``` The highest prime factor is increasing in both direction, so we must look at the next neighbor: ``` 243 -> 3, 3, 3, 3, 3 244 -> 2, 2, 2, 61 245 -> 5, 7, 7 246 -> 2, 3, 41 247 -> 13, 19 ``` The highest prime factors are now decreasing in both direction, so the highest prime factor we've encountered is `61`, and should therefore be returned. Another example: Let's look at `1024`. Its prime factors are `2, 2, 2, 2, 2, 2, 2, 2, 2, 2`. The prime factors of its nearest neighbors are: ``` 1023 -> 3, 11, 31 1024 -> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 1025 -> 5, 5, 41 ``` The highest prime factor are increasing in both direction, from `2` to `31` or `41`. Let's look at the neighbors: ``` 1022 -> 2, 7, 73 1023 -> 3, 11, 31 1024 -> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 1025 -> 5, 5, 41 1026 -> 2, 3, 3, 19 ``` The highest prime factor for `1022` is `73`, and the highest prime factor for `1026` is `19`. Since `19` is lower than `41` we're not interested in it. **It's still increasing for numbers smaller than \$N\$, so we'll check the next one in that direction**: ``` 1021 -> 1021 1022 -> 2, 7, 73 1023 -> 3, 11, 31 1024 -> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 1025 -> 5, 5, 41 1026 -> 2, 3, 3, 19 ``` `1021` is a prime, and the highest prime we've encountered, so it should be returned. **Rules:** * You will only get positive \$N\$ larger than \$1\$ and smaller than \$2^{31}-2\$. * Input and output formats are optional, but the numbers must be in base 10. * You should continue searching for higher primes as long as the highest value is increasing in that direction. The directions are independent of each other. **Test cases:** Format: `N, highest_factor` ``` 2, 3 3, 3 6, 7 8, 11 24, 23 1000, 997 736709, 5417 8469038, 9431 ``` [Answer] # Mathematica, ~~82~~ 74 bytes *Thanks to Martin Ender for saving 8 bytes!* ``` Max@@(±n_:=#//.x_/;l[t=x+n]>l@x:>t;l=FactorInteger[#][[-1,1]]&)/@{±-1,±1}& ``` Unnamed function taking an integer input and returning an integer. `±n_:=#//.x_/;l[t=x+n]>l@x:>t` defines a unary function `±` which keeps increasing the global function's integer input by `n` as long as the largest prime factor is increasing. (The largest-prime-factor function is defined with `l=FactorInteger[#][[-1,1]]&`.) `{±-1,±1}` therefore applies that function twice to the input integer, with increment `-1` and again with increment `1`. Then, `Max@@(...l...)/@...` takes the larger of the two largest-prime-factors thus found. Previous submission: ``` Max@@(l=FactorInteger[#][[-1,1]]&)/@(#//.x_/;l[t=x+#2]>l[x]:>t&@@@{{#,-1},{#,1}})& ``` [Answer] ## Perl, 137 bytes 122 bytes of code + 15 bytes for `-p` and `-Mntheory=:all`. ``` sub f{$t=(factor$_+pop)[-1]}$i=$j=1;while($i|$j){f++$c;($i&=$t>$h)&&($h=$t);f-$c;($j&=$t>$l)&&($l=$t)}$_=$h>$l?$h:$l?$l:$_ ``` To run it: ``` perl -pMntheory=:all -e 'sub f{$t=(factor$_+pop)[-1]}$i=$j=1;while($i|$j){f++$c;($i&=$t>$h)&&($h=$t);f-$c;($j&=$t>$l)&&($l=$t)}$_=$h>$l?$h:$l?$l:$_' <<< 736709 ``` If you don't have `ntheory` installed, you can install it by typing `(echo y;echo) | perl -MCPAN -e 'install ntheory'` in your terminal. [Answer] ## Ruby, 99 bytes ``` ->n{f=->n{i=2;n%i<1?n/=i:i+=1while i<n;n};g=->s,z{s+=z while f[s+z]>b=f[s];b};[g[n,1],g[n,-1]].max} ``` Explanation: * f() is the highest prime factor * g() is the function searching neighbors in one direction * apply g to (n,-1) and to (n,+1) to search in both directions [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` ;‘ÆfṀ€>/ ÇÐḟṖ‘,Ç1#Ṫ€ÆfFṀ ``` [Try it online!](https://tio.run/##y0rNyan8/9/6UcOMw21pD3c2PGpaY6fPdbj98ISHO@Y/3DkNKKFzuN1Q@eHOVUApoBo3oKL/D3dserhjUdjh9qOTHu6cwfVw95bD7UDpyP//jRSMuYyB2EzBnMtCwdCQy8hEwchYAUiZKpgZchkaGBgoWFqaAxlACSBhCAA "Jelly – Try It Online") Bleh ## How it works ``` ;‘ÆfṀ€>/ - Helper link. Takes n on the left ‘ - Yield n+1 ; - Pair; [n, n+1] Æf - Prime factors of each Ṁ€ - Maximum of each >/ - Is max(pf(n)) > max(pf(n+1))? ÇÐḟṖ‘,Ç1#Ṫ€ÆfFṀ - Main link. Takes N on the left ÇÐḟ - Remove all integers 1 ≤ k ≤ N which return true under the helper link Ṗ - Remove the last one (N) ‘ - Increment all Ç1# - Find the first integer ≥ N which the helper link returns true , - Pair Ṫ€ - Get the last element of each This returns [x, y] where x is the lower neighbour with the highest prime factor, y is the upper neighbour with the highest prime factor Æf - Prime factors of each FṀ - Flatten and get the maximum ``` ]
[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 last year. [Improve this question](/posts/41595/edit) Let's say you have a list of words and you want to be able to use letter cards to spell each word. For example, to spell *cat*, you would use three cards labelled C, A, T. Assuming each card is *double-sided*, submit a program to define a minimum number of cards that can be used to spell the entire list of words. Input is the word list, it can be file-based, hard-coded, command line, whatever. Output is the list of cards, formatted and ordered as you see fit, provided it is clear how the cards are labelled. Case is not significant: Golf, golf and GOLF are equivalent. Some hints: * the number of cards can be no less than the length of the longest word * it makes no sense for a card to have the same letter on both sides * while case is not significant, recommend lower case to take advantage of *certain symmetries* Examples, these take advantage of *certain symmetries*: Input: *ben, bog, bug, den, do, doe, dog, due, dug, Ed, end, gob, God, Ned, ode, pen, Poe, pug* Output: *b/d, e/g, o/n* Input: *an, and, ape, are, be, bed, bud, bur, Dan, Deb, dub, ear, Ed, era, nap, pan, pea, pub, Rae, ran, rub* Output: *a/b, d/r, e/n* Making it a popularity contest, so elegance of code, run-time performance, and cleverness (including rule-bending & loopholes) are important! **Addition**: Some have asked about "allowed" symmetries, whether special fonts can be used, and whether the cards can be folded. Allowed symmetries are any letters which look similar to each other after 0, 90, 180 or 270 degrees rotation. This includes b/q, d/p and n/u. I would also say M/W, Z/N, and of course I/l (capital i, lowercase L). I'm probably scratching the surface, so if there are any others you're unsure about, just ask. To keep it simple, please restrict to a standard sans-serif font, say that used in SE. As far as folding, while you can do some amazing substitutions, e.g. B can be D, E, F, I, P, or R, and maybe C or L if you fold really creatively, I think that's bending, literally, too much! I came up with this problem while playing with some similar cards with my kids. I noted how easy it was to come up with single-sided cards vs. how difficult it was to come up with double-sided cards. **Addition**: Have provided a bounty to be awarded to the most popular answer. If there's a tie, will award to the one who submitted first. Another hint: * solving the single-sided problem will give you an idea of the minimum number of cards needed (e.g. 20 single-sided cards translates to at least 10 double sided-cards needed) **Addition**: Oh bother, I was busy and forgot about the bounty expiring. It ended up going to no one because the only answer was submitted before the bounty started! Sorry about that. [Answer] # C# - CardChooser ## Summary This application uses a brute force method to attempt to solve each list. First I create a list of potential cards to select from, then I determine which is a best fit(removes the most chars + shortens long words most), add this to a result list and continue with this process until I have selected enough potential cards to remove every word in the list, then I rematch those cards to each word and print the output. If you would like to see a more limited version of this code without downloading and building the provided windows forms application you can use the link provided to run my program on smaller sets of data, please note that this is the console application version so the resulting cards are NOT rotated: <http://ideone.com/fork/VD1gJF> ## Revision History Current - Added better result optimization suggested by @Zgarb Update 3 - More code cleanup, more bugs fixed, better results Update 2 - Windows Forms, More verbose output Update 1 - New/Better support for character symmetries Original - Console Application ## Examples acr, aft, ain, sll, win, say, said, fast, epic ![Output 0](https://i.stack.imgur.com/mLyjC.png) hes, will, with, wont, would, wouldve, wouldnt, yet, you, youd, youll ![Output 1](https://i.stack.imgur.com/eVwgB.png) aaaa, bbbb, cccc ![Output 2](https://i.stack.imgur.com/L1bWU.png) ## Code I still need to combine this into one larger project with the ConsoleApp and WindowsForms code all sharing the same classes and methods, then split out the different regions in the RunButton\_Click method so I can write units around them, anyway whenever I find time to do that I will, for now this is what I have: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace CardChooserForms { public partial class CardChooser : Form { private class Solution : IEquatable<Solution> { public List<string> Cards { get; set; } public List<string> Remaining { get; set; } public int RemainingScore { get { return this.Remaining.Sum(b => b.ToCharArray().Count()); } } public bool Equals(Solution other) { return new string(Cards.OrderBy(a => a).SelectMany(a => a).ToArray()) == new string(other.Cards.OrderBy(a => a).SelectMany(a => a).ToArray()); } public override int GetHashCode() { return (new string(Cards.OrderBy(a => a).SelectMany(a => a).ToArray())).GetHashCode(); } } private class Symmetry { public char Value { get; set; } public Int16 RotationDifference { get; set; } } /// <summary> /// This is where Symmetries are stored, right now it only has support for pairs(two values per array) /// </summary> private static Symmetry[][] _rotatableCharacters = new Symmetry[][] { new Symmetry[] { new Symmetry {Value = 'Z'}, new Symmetry {Value = 'N', RotationDifference = 90}}, new Symmetry[] { new Symmetry {Value = 'd'}, new Symmetry {Value = 'p', RotationDifference = 180 }}, new Symmetry[] { new Symmetry {Value = 'u'}, new Symmetry {Value = 'n', RotationDifference = 180 }}, new Symmetry[] { new Symmetry {Value = 'm'}, new Symmetry {Value = 'w', RotationDifference = 180 }}, new Symmetry[] { new Symmetry {Value = 'b'}, new Symmetry {Value = 'q', RotationDifference = 180 }}, new Symmetry[] { new Symmetry {Value = 'l'}, new Symmetry {Value = 'I', RotationDifference = 0}}, }; //These all control the output settings private readonly static int _defualtSpacing = 25; private readonly static int _defualtFontSize = 8; private readonly static Font _defualtFont = new Font("Microsoft Sans Serif", _defualtFontSize); private readonly static Brush _defualtBackgroundColor = Brushes.Beige; private readonly static Brush _defualtForegroundColor = Brushes.Black; public CardChooser() { InitializeComponent(); } private void RunButton_Click(object sender, EventArgs e) { #region Input Parsing //Get input string input = InputRichTextBox.Text; if (!input.Contains(",")) throw new ArgumentException("Input must contain more than one value and must be seprated by commas."); //Parse input var inputLowercasedTrimedTransformed = input.Split(',').Select(a => a.ToLowerInvariant().Trim()).ToArray(); var inputSplitTrimIndex = input.Split(',').Select(a => a.Trim()).ToArray().Select((a, index) => new { value = a, index }).ToArray(); #endregion Input Parsing #region Card Formation var inputCharParsed = inputLowercasedTrimedTransformed.Select(a => a.ToCharArray()).ToArray(); var possibleCards = GetAllCasesTwoLengthArrayElements( UniqueBiDirection( //Get unique characters inputCharParsed .SelectMany(a => a) .Distinct() .Select(a => new { Character = a, PossibleCharacters = inputCharParsed.SelectMany(b => b).Where(b => b != a).ToList() }) //Now get distinct cards(ie NB == BN, NB != NE) .SelectMany(a => a.PossibleCharacters.Select(b => new string(new char[] { a.Character, b })).ToArray()).ToArray() ).ToArray() ).ToArray(); //Now get every possible character each card can eliminate var possibleCharsFromCards = GetAllPossibleCharsFromACards(possibleCards).ToArray(); //Now set up some possibilities that contain only one card var possibleCardCombinations = possibleCards.Select((a, index) => new Solution { Cards = new List<string> { a }, //Use the index of each card to reference the possible characters it can remove, then remove them per card to form a initial list of cards Remaining = inputLowercasedTrimedTransformed.Select(b => b.RemoveFirstInCharArr(possibleCharsFromCards[index].ToLowerInvariant().ToCharArray())).ToList() }) //Take the best scoring card, discard the rest .OrderBy(a => a.RemainingScore) .ThenBy(a => a.Remaining.Max(b => b.Length)) .Take(1).ToList(); #endregion Card Formation #region Card Selection //Find best combination by iteratively trying every combination + 1 more card, and choose the lowest scoring one while (!possibleCardCombinations.Any(a => a.Remaining.Sum(b => b.ToCharArray().Count()) == 0) && possibleCardCombinations.First().Cards.Count() < possibleCards.Count()) { //Clear the list each iteration(as you can assume the last generations didn't work var newPossibilites = new List<Solution>(); var currentRoundCardCombinations = possibleCardCombinations.ToArray(); possibleCardCombinations.Clear(); foreach (var trySolution in currentRoundCardCombinations) foreach (var card in possibleCards.Select((a, index) => new { value = a, index }).Where(a => !trySolution.Cards.Contains(a.value)).ToArray()) { var newSolution = new Solution(); newSolution.Cards = trySolution.Cards.ToList(); newSolution.Cards.Add(card.value); newSolution.Remaining = trySolution.Remaining.ToList().Select(a => a.RemoveFirstInCharArr(possibleCharsFromCards[card.index].ToLowerInvariant().ToCharArray())).ToList(); newPossibilites.Add(newSolution); } //Choose the highest scoring card possibleCardCombinations = newPossibilites .OrderBy(a => a.RemainingScore) .ThenBy(a => a.Remaining.Max(b => b.Length)) .Distinct().Take(1).ToList(); } var finalCardSet = possibleCardCombinations.First().Cards.ToArray(); #endregion Card Selection #region Output using (var image = new Bitmap(500, inputSplitTrimIndex.Count() * _defualtSpacing + finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing)) using (Graphics graphic = Graphics.FromImage(image)) { //Background graphic.FillRectangle(_defualtBackgroundColor, 0, 0, image.Width, image.Height); //Header graphic.DrawString("Total Number of Cards Required: " + finalCardSet.Count(), _defualtFont, _defualtForegroundColor, new PointF(0, 0)); graphic.DrawString( "Cards: " + String.Join(", ", finalCardSet.Select(a => a[0] + "/" + a[1])), _defualtFont, _defualtForegroundColor, new RectangleF(0, _defualtSpacing, image.Width - _defualtSpacing, finalCardSet.Count() * 5)); //Results foreach (var element in inputSplitTrimIndex) { //Paint the word graphic.DrawString(element.value + " -> ", _defualtFont, _defualtForegroundColor, new PointF(0, element.index * _defualtSpacing + finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing)); //Now go through each character, determining the matching card, and wether that card has to be flipped foreach (var card in GetOrderedCardsRequired(inputLowercasedTrimedTransformed[element.index].ToLowerInvariant(), finalCardSet.ToArray()).ToArray().Select((a, index) => new { value = a, index })) using (var tempGraphic = Graphics.FromImage(image)) { //For cards that need to flip if (Char.ToUpperInvariant(element.value[card.index]) != Char.ToUpperInvariant(card.value[0]) && Char.ToUpperInvariant(element.value[card.index]) != Char.ToUpperInvariant(card.value[1])) { //TODO this is hacky and needs to be rethought var rotateAmount = _rotatableCharacters .OrderByDescending(a => a.Any(b => b.Value == Char.ToLowerInvariant(element.value[card.index]))) .First(a => a.Any(b => Char.ToUpperInvariant(b.Value) == Char.ToUpperInvariant(element.value[card.index]))) [1].RotationDifference; //Rotate tempGraphic.TranslateTransform( _defualtSpacing * (_defualtFontSize / 2) + card.index * _defualtSpacing + (rotateAmount == 90 ? 0 : _defualtSpacing / 2) + (rotateAmount == 180 ? -(_defualtSpacing / 4) : 0), finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing + element.index * _defualtSpacing + (rotateAmount == 180 ? 0 : _defualtSpacing / 2)); tempGraphic.RotateTransform(rotateAmount); //Print string tempGraphic.DrawString( String.Join("/", card.value.ToCharArray().Select(a => new string(new char[] { a })).ToArray()), _defualtFont, Brushes.Black, new RectangleF(-(_defualtSpacing / 2), -(_defualtSpacing / 2), _defualtSpacing, _defualtSpacing)); } else tempGraphic.DrawString( String.Join("/", card.value.ToCharArray().Select(a => new string(new char[] { a })).ToArray()), _defualtFont, _defualtForegroundColor, new RectangleF( _defualtSpacing * (_defualtFontSize / 2) + card.index * _defualtSpacing, finalCardSet.Count() * (_defualtFontSize / 2) + _defualtSpacing + element.index * _defualtSpacing, _defualtSpacing, _defualtSpacing)); } } OutputPictureBox.Image = new Bitmap(image); } #endregion Output } private IEnumerable<string> GetAllPossibleCharsFromACards(string[] cards) { return cards.Select(a => new string(a.ToCharArray().Concat(_rotatableCharacters .Where(b => b.Select(c => c.Value).Intersect(a.ToCharArray()).Count() > 0) .SelectMany(b => b.Select(c => c.Value)) .Distinct().ToArray()).Distinct().ToArray())); } private IEnumerable<string> GetOrderedCardsRequired(string word, string[] cards) { var solution = new List<string>(); var tempCards = GetAllPossibleCharsFromACards(cards).Select((a, index) => new { value = a, index }).ToList(); foreach (var letter in word.ToCharArray()) { //TODO this still could theoretically fail I think var card = tempCards //Order by the least number of characters match .OrderBy(a => word.ToLowerInvariant().Intersect(a.value.ToLowerInvariant()).Count()) .ThenByDescending(a => tempCards.Sum(b => b.value.ToLowerInvariant().Intersect(a.value.ToLowerInvariant()).Count())) //Then take the least useful card for the other parts of the word .First(a => a.value.ToLowerInvariant().Contains(Char.ToLowerInvariant(letter))); solution.Add(cards[card.index]); tempCards.Remove(card); } return solution; } private static IEnumerable<string> UniqueBiDirection(string[] input) { var results = new List<string>(); foreach (var element in input) if (!results.Any(a => a == new string(element.ToCharArray().Reverse().ToArray()) || a == element)) results.Add(element); return results; } private static IEnumerable<string> GetAllCasesTwoLengthArrayElements(string[] input) { if (input.Any(a => a.Length != 2)) throw new ArgumentException("This method is only for arrays with two characters"); List<string> output = input.ToList(); foreach (var element in input) { output.Add(new string(new char[] { Char.ToUpperInvariant(element[0]), Char.ToUpperInvariant(element[1]) })); output.Add(new string(new char[] { element[0], Char.ToUpperInvariant(element[1]) })); output.Add(new string(new char[] { Char.ToUpperInvariant(element[0]), element[1] })); } return output; } private void SaveButton_Click(object sender, EventArgs e) { using (var image = new Bitmap(OutputPictureBox.Image)) image.Save(Directory.GetCurrentDirectory() + "Output.png", ImageFormat.Png); } } public static class StringExtensions { public static string RemoveFirstInCharArr(this string source, char[] values) { var tempSource = source.ToUpperInvariant(); foreach (var value in values) { int index = tempSource.IndexOf(Char.ToUpperInvariant(value)); if (index >= 0) return source.Remove(index, 1); } return source; } } } using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace CardChooserForms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new CardChooser()); } } } namespace CardChooserForms { partial class CardChooser { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.InputRichTextBox = new System.Windows.Forms.RichTextBox(); this.EnterInputLabel = new System.Windows.Forms.Label(); this.RunButton = new System.Windows.Forms.Button(); this.OutputPictureBox = new System.Windows.Forms.PictureBox(); this.OutputPanel = new System.Windows.Forms.Panel(); this.SaveButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.OutputPictureBox)).BeginInit(); this.OutputPanel.SuspendLayout(); this.SuspendLayout(); // // InputRichTextBox // this.InputRichTextBox.Location = new System.Drawing.Point(60, 40); this.InputRichTextBox.Name = "InputRichTextBox"; this.InputRichTextBox.Size = new System.Drawing.Size(400, 100); this.InputRichTextBox.TabIndex = 0; this.InputRichTextBox.Text = ""; // // EnterInputLabel // this.EnterInputLabel.AutoSize = true; this.EnterInputLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.EnterInputLabel.Location = new System.Drawing.Point(57, 20); this.EnterInputLabel.Name = "EnterInputLabel"; this.EnterInputLabel.Size = new System.Drawing.Size(81, 17); this.EnterInputLabel.TabIndex = 1; this.EnterInputLabel.Text = "Enter Input:"; // // RunButton // this.RunButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.RunButton.Location = new System.Drawing.Point(60, 147); this.RunButton.Name = "RunButton"; this.RunButton.Size = new System.Drawing.Size(180, 52); this.RunButton.TabIndex = 2; this.RunButton.Text = "Run"; this.RunButton.UseVisualStyleBackColor = true; this.RunButton.Click += new System.EventHandler(this.RunButton_Click); // // OutputPictureBox // this.OutputPictureBox.Location = new System.Drawing.Point(3, 3); this.OutputPictureBox.Name = "OutputPictureBox"; this.OutputPictureBox.Size = new System.Drawing.Size(500, 500); this.OutputPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.OutputPictureBox.TabIndex = 3; this.OutputPictureBox.TabStop = false; // // OutputPanel // this.OutputPanel.AutoScroll = true; this.OutputPanel.Controls.Add(this.OutputPictureBox); this.OutputPanel.Location = new System.Drawing.Point(4, 205); this.OutputPanel.Name = "OutputPanel"; this.OutputPanel.Size = new System.Drawing.Size(520, 520); this.OutputPanel.TabIndex = 4; // // SaveButton // this.SaveButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SaveButton.Location = new System.Drawing.Point(280, 147); this.SaveButton.Name = "SaveButton"; this.SaveButton.Size = new System.Drawing.Size(180, 52); this.SaveButton.TabIndex = 5; this.SaveButton.Text = "Save"; this.SaveButton.UseVisualStyleBackColor = true; this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click); // // CardChooser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(534, 737); this.Controls.Add(this.SaveButton); this.Controls.Add(this.RunButton); this.Controls.Add(this.EnterInputLabel); this.Controls.Add(this.InputRichTextBox); this.Controls.Add(this.OutputPanel); this.Name = "CardChooser"; this.Text = "Card Chooser"; ((System.ComponentModel.ISupportInitialize)(this.OutputPictureBox)).EndInit(); this.OutputPanel.ResumeLayout(false); this.OutputPanel.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.RichTextBox InputRichTextBox; private System.Windows.Forms.Label EnterInputLabel; private System.Windows.Forms.Button RunButton; private System.Windows.Forms.PictureBox OutputPictureBox; private System.Windows.Forms.Panel OutputPanel; private System.Windows.Forms.Button SaveButton; } } ``` ]
[Question] [ Create a deterministic program to play nd tic-tac-toe with the other contestants. Your program should work when `n` (width) and `d` (dimension number) are in these ranges: ``` n∈[3,∞)∩ℕ ie a natural number greater than 2 d∈[2,∞)∩ℕ ie a natural number greater than 1 ``` `n = 3; d = 2` (32 ie 3 by 3): ``` [][][] [][][] [][][] ``` `n = 3; d = 3` (33 ie 3 by 3 by 3): ``` [][][] [][][] [][][] [][][] [][][] [][][] [][][] [][][] [][][] ``` `n = 6; d = 2` (62 ie 6 by 6): ``` [][][][][][] [][][][][][] [][][][][][] [][][][][][] [][][][][][] [][][][][][] ``` And so on. **Input:** Input will be to STDIN. The first line of input will be two numbers, `n` and `d` in the form `n,d`. After this will be a line consisting of coordinates specifying the moves that have been done. Coordinates will be listed in the form: `1,1;2,2;3,3`. The upper left corner is the origin ( 0,0 for 2D). In the general case, this list will be like `1,2,...,1,4;4,0,...,6,0;...` where the first number represents left-right-ness, the second up-down-ness, the third through the 3rd dimension, etc. Note that the first coordinate is `X`s first turn, the second is `O`s first turn, .... Should this be the first move, the input will a number followed by 1 blank line. For consistency, the input will always end with a newline. Sample Input (\n is newline): ``` 10,10\n0,0,0,0,0,0,0,0,0,0;0,2,3,4,5,6,7,8,9,0;0,1,2,3,4,5,6,7,8,9\n ``` For first move: ``` 10,10\n\n ``` where `\n` is the newline character. **Output:** Output the move you wish to make in the same format as the input (a comma-separated list). An invalid move (ie one that has already been taken) will result in a loss for the game. Note: You can use a random number generator, as long as you seed it with a value such that each run would be identical given the same conditions. In other words, the program must be deterministic. Note: only valid moves are allowed. **Winning Games** (If you've played enough multi-dimensional tic tac toe, this is the same.) In order for there to be a win, one player must have all the adjacent squares along a line. That is, that player must have `n` moves on a line to be a winner. Adjacent: * each tile is a point; for example (0,0,0,0,0) is a point in `d=5` * adjacent tiles are tiles such they are both points on the same unit d-cube. In other words, the [Chebyshev distance](http://en.wikipedia.org/wiki/Chebyshev_distance) between the tiles is 1. * in other words, if a point `p` is adjacent to a point `q`, then every coordinate in `p`s corresponding coordinate in `q` differs from it by no more than one. Additionally, at least on coordinate pair differs by exactly one. Lines: * Lines are defined by vectors and a tile. A line is each tile hit by the equation: `p0 + t`<`some vector with the same number of coordinates as p0`>`` **Simulation and Winning Conditions:** * State in your answer if it is ready for grading. That is, clearly indicate whether or not your answer is done. * If your answer is marked as done, it will not be graded until at least 24 hours after the last edit to the code. * Programs must work offline. If a program is found to be cheating, it will automatically receive a score of `-1`, and will not be scored further. (How would anyone end up with their programs cheating?) * If your program produces invalid output, it is immediately counted as a loss for the game * If you program fails to produce output after 1 minute it is immediately counted as a loss for the game. If necessary, optimize for speed. I don't want to have to wait an hour to test a program off of another. * Each program will be run against the other programs twice for each `n` in the range `[3,6]` and each `d` in the range `[2,5]`, once as `X` and once as `O`. This is one round. * For each game a program wins, it gets `+3` to its score. If the program tied (1 win and 1 loss in a single round or ties for both games), then it gets `+1`. If the program lost, then it gets `+0` (ie no change). * The program with the highest score wins. Should there be a tie, then the program with the least number of lost games (out of the tied contestants) wins. Note: Depending on the number of answers, I may need help running the tests. *Good luck! And may the simulations run ever in your favor!* [Answer] # Python 3 ``` import random as rand import re def generateMoves(width, dim): l = [0] * dim while existsNotX(l, width - 1): yield l[:] for i in range(dim): if l[i] < width - 1: l[i] += 1 break else: l[i] = 0 yield l def existsNotX(l, x): for i in l: if i != x: return True return False input_s = input() dims, moves = None, None #this is to allow input as a single paste, instead of ENTER inputting. try: dims, moves = input_s.splitlines() except ValueError: dims = input_s moves = input() rand.seed(moves + dims) dims = eval(dims) #change into tuple moves = moves.split(';') if len(moves[0]): moves = [eval(m) for m in moves] #change into tuples output =[x for x in generateMoves(dims[0], dims[1]) if x not in moves] print(re.sub('[^\\d,]', '', str(output[rand.randint(0, len(output))]))) ``` This is simply a random ai. It randomly selects a move out of the moves that are still available. [Answer] # Python 2.7 This is a work-in-progress submission which I'm providing to give a skeleton/inspiration to other answerers. It works by listing every possible winning line, then applying some heuristic to score that line according to how valuable it is. Currently, the heuristic is blank (super-secret workings). I have also added win and clash error handling. ### Notes on the problem How many winning lines are there? Consider the 1-dimensional case; there are 2 vertices, 1 edge, and 1 line. In 2 dimensions, we have 4 vertices joined by 2 lines, and 4 edges joined by 2\*n lines. In 3 dimensions, we have 8 vertices joined by 4 lines, 12 edges joined by 6\*n lines, and 6 faces joined by `3*n^2` lines. In general, let us call a vertex a 0-facet, an edge a 1-facet, etc. Then let `N(i)` denote the number of i-facets, `d` the number of dimensions, and `n` the side length. Then the number of winning lines is `0.5*sum(N(i)*n^i,i=0..d-1)`. Per wikipedia, `N(i)=2^(d-i)*d!/(i!*(n-1)!)`, so the final formula is: `sum(2^(d-i-1) n^i d! / (i! * (n-i)!),i=0..d-1)` which wolfram|alpha doesn't like very much. This gets very large pretty quickly, so I don't expect my program to have manageable runtime for d>8. Some results (sorry about the formatting: ``` d\n 0 1 2 3 4 5 6 7 8 9 0 1 1 1 1 1 1 1 1 1 1 1 2 4 6 8 10 12 14 16 18 20 2 4 11 26 47 74 107 146 191 242 299 3 8 40 120 272 520 888 1400 2080 2952 4040 4 16 117 492 1437 3372 6837 12492 21117 33612 50997 5 32 364 2016 7448 21280 51012 107744 206896 368928 620060 6 64 1093 8128 37969 131776 372709 908608 1979713 3951424 7352101 7 128 3280 32640 192032 807040 2687088 7548800 18640960 41611392 85656080 8 256 9834 130809 966714 4907769 19200234 62070009 173533434 432891129 985263594 ``` ### I/O At the moment, the input needs to be input as: `tictactoe.py <ret> n,d <ret> move;move <ret>` - note the multiple lines and no final `;`. The output looks like `(x_1,x_2,x_3...)`, for instance: `tictactoe.py <ret> 6,5 <ret> <ret>` => `0, 0, 0, 0, 0` `tictactoe.py <ret> 6,5 <ret> 0,0,0,0,0;0,0,0,0,5 <ret>` => `0, 0, 0, 5, 0` ``` # Notes on terminology: # # - A hypercube is the region [0,n]^d # - An i-facet is an i-dimensional facet of a hypercube, # which is to say, a 0-facet is a vertex, a 1-facet an # edge, a 2-facet a face, and so on. # - Any tuple {0,n}^i is a vertex of an i-hypercube # which is why I've used vertex to describe such # tuples # - A winning line is a set of n coordinates which joins # two opposite i-facets # - i-facets are opposite if they differ in every co- # ordinate which defines them # # Test Data: # import numpy import itertools def removeDuplicates(seq): noDupes = [] [noDupes.append(i) for i in seq if not noDupes.count(i)] return noDupes def listPairedVertices (i,n): """ listPairedVertices returns a list L of elements of {0,n}^i which has the property that for every l in L, there does not exist l' such that l+l' = {n}^i. """ vertices = numpy.array([[b*(n-1) for b in a] for a in [ list(map(int,list(numpy.binary_repr(x,i)))) for x in range(2**i) ]]) result = [] while len(vertices)>1: for j in range(len(vertices)): if numpy.all(vertices[j] + vertices[0] == [n-1]*i): result.append(vertices[0]) vertices=numpy.delete(vertices,[0,j],axis=0) break return result def listSequences (d,l): """ listSequences returns the subset of {0,1}^d having precisely n 1s. """ return numpy.array([ r for r in itertools.product([0,1],repeat=d) if sum(r)==l ]) def listPaddedConstants (s,n): """ listPaddedConstants takes a sequence in {0,1}^d and returns a number in {0..n}^sum(s) padded by s """ result = numpy.zeros([n**sum(s),len(s)],dtype=numpy.int) for i,x in enumerate([list(z) for z in itertools.product(range(n),repeat=sum(s))]): for j in range(len(s)): if s[j]: result[i][j] = x.pop() return result def listWinningVectorsForDimension(d,i,n): """ List the winning lines joining opposite i-facets of the hypercube. An i-facet is defined by taking a vertex v and a sequence s, then forming a co-ordinate C by padding v with zeroes in the positions indicated by s. If we consider s = s_0.e_0 + s_1+e_1... where the e_j are the canonical basis for R^d, then the formula of the i-facet is C+x_0.s_0.e_0+x_1.s_1.e_1... for all vectors x = (x_0,x_1...) in R^n We know that winning lines only start at integral positions, and that the value of a will only be needed when s_j is nonempty, so the start point S of a winning line is in fact determined by: + vertex v in {0,n}^(d-i), padded by s + a in R^i, padded by the complement of s, s' Having performed the following operations, the co-ordinates of the winning lines are abs(S-k*s') for k in [0..n-1] """ vertices = listPairedVertices(d-i,n) sequences = listSequences(d,i) result = [] for s in sequences: for v in vertices: C = [0]*d j = 0 for index in range(d): if s[index]: C[index] = 0 else: C[index] = v[j] j+=1 result += [ [numpy.absolute(S-k*(numpy.absolute(s-1))) for k in range(n)] for S in [C+a for a in listPaddedConstants(s,n)] ] return result def AllWinningLines (d,n): """ has the structure [[x_1,x_2,x_3],[y_1,y_2,y_3]] where each l_k is a length-d co-ordinate """ result = [] for i in range(d): result += listWinningVectorsForDimension(d,i,n) return result def movesAlreadyMade (): """ Returns a list of co-ordinates of moves already made read from STDIN """ parameters = raw_input() moves = raw_input() parameters = list(map(int,parameters.split(','))) moves = [map(int,a.split(',')) for a in moves.split(';')] \ if moves != '' else [] return {'n':parameters[0], 'd':parameters[1], 'moves':moves} def scoreLine (moves, line, scores, n): """ Gives each line a score based on whatever logic I choose """ myMoves = moves[0::2] theirMoves = moves[1::2] if len(moves)%2: myMoves, theirMoves = theirMoves, myMoves lineHasMyMove = 0 lineHasTheirMove = 0 score = 0 for coord in line: if coord.tolist() in myMoves: lineHasMyMove += 1 if coord.tolist() in theirMoves: raise Exception('Move clash') elif coord.tolist() in theirMoves: lineHasTheirMove += 1 if lineHasMyMove == len(line): raise Exception('I have won') elif lineHasTheirMove == len(line): raise Exception('They have won') elif lineHasMyMove and lineHasTheirMove: pass elif lineHasTheirMove == len(line)-1: score = n**lineHasTheirMove else: score = n**lineHasMyMove for coord in line: if coord.tolist() not in moves: scores[tuple(coord)]+=score def main(): """ Throw it all together """ data = movesAlreadyMade() dimension = data['d'] length = data['n'] lines = AllWinningLines(dimension, length) scores = numpy.zeros([length]*dimension, dtype=numpy.int) try: [scoreLine(data['moves'], line, scores, length) for line in lines] except Exception as E: print 'ERROR: ' + E.args[0] return print ','.join(map( str,numpy.unravel_index(numpy.argmax(scores),scores.shape) )) if __name__ == "__main__": main() ``` Edit: for I/O, added logic. I believe this is now ready to mark Note that this comment was initially a placeholder which I deleted and undeleted. [Answer] # Python 2 ``` import re import itertools input_s = raw_input() dims, moves = None, None #this is to allow input as a single paste, instead of ENTER inputting. try: dims, moves = input_s.splitlines() except ValueError: dims = input_s moves = raw_input() dims = eval(dims) #change into tuple moves = moves.split(';') if len(moves[0]): moves = [eval(m) for m in moves] #change into tuples allSpaces = [x for x in itertools.product(range(dims[0]), repeat=dims[1])] move = None for space in allSpaces: if space not in moves: move = space break print(re.sub('[^\\d,]', '', str(move))) ``` Most of the code is exactly the same as [Quincunx's random AI](https://codegolf.stackexchange.com/a/25361/3787). Instead of randomly selecting a move, it picks the first available move lexicographically (i.e. (0,0,...0), then (0,0,...1), then (0,0,...2), etc.). This is a pretty rubbish strategy, but it almost always beats playing at random. ]
[Question] [ Remove one stick and output the stack updated. # Description You can remove only sticks on top( completely drawn). You can assume: * there are 5 sticks on the table. * there's one and only one stick you can remove. * sticks are recognizable : there aren't overlapping sticks on the same orientation and there aren't sticks joined which form a longer line. * input should be not ambiguous, there should be only one valid solution as pointed out by @Arnauld comment, for example [this input is not valid](https://tio.run/##y0osSyxOLsosKNHNy09J/a9Q86hhCgTVcCnUKCjUICiETA0XV3B@TmlJZn6egiEXkh6IWhiJZBRCvRGyejQtCgoKyLqA3P///wMA "JavaScript (Node.js) – Try It Online") * Trailing /leading spaces doesn't matter. Sticks are 4 chars long and are placed vertically or horizontally. ``` | ———— | | | ``` **Test cases** [Before, after] ``` [" ||| —|—— ||| |||— ", " | | ———— | | |—|— "], [" ||| —|—— ||| |||—— ", " | | ———— | | |—|—— "], [" ||| —|—— ||| |||——— ", " | | ———— | | | |——— "], [" | ———| |——— | | |———— ", " | ———| |——— | | | "], [" | | | ———— | | | | |——— | ", " | | | || | | | | |——— | "], [" | ———— ——|— |——— | ", " | | | ——|— |——— | "], [" | | ————| | |——— | | | | ", " | | | | | | |——— | | | | "], [" ———| ——|— —|—— |——— ", " ———— ———— ———— ———— "], [" | —||— || ———— | | | | ", " | —||— || ||| | | | | "], [" |——— | | | | | | | ———| | ", " |——— | | | | ———| "] ``` **Input specifications** You can add trailing and leading whitespaces / lines as your wish, , I hope this can help focusing on the task by avoiding data bounds checking. [here is a small program](https://tio.run/##xVbJjtNAEL3XV5R8SeweIgbBcMqNOweOSYTswcMYJU5kG5GIjsRH8IX8SOglvXdnGYFiJXK7uuvV63rVS/e92h36oWvarx/qZbNqhrqbYjbPMii7Tps@L5FZZ56x48ZFBo/PpbEiN85HGTTtl7od@BeyIevVquTtuwza@seyaWsxrs0OQ90P/XQGswzFA0gp5a8/v35T9mc/Y2Mv@S2e7A7AeKHy0j9jpUcw7blgrjqkwneDWlYZ1vLXb4uCipYgYbGIAjFGmo8O7TGy7ZqTjWYaNjFNwafm9FA8DeinjD1uxnWmrQQielYbnHF8IdyJ1Ek7PdP00sBN1MDaTX8YetH9XF8Wn1rNl8flklgzhwiFcK6875jhY1rRS7MKBgnk2KwTsXXt/6OY7ozhTIHTSF1TtSfoijuzdMIQGuJ6aMaffaZEs4lb0lFHOOokLbZmr5QrshaSJePEji7qi4QLCpRac6Q0yUJLYC@l8zM9G4ma1kURvM3alIjhS9V@5TQshek1pefv2epEQf/EoRivuwUc2PbND/CPT5/Egd@zE1gcvpNVuflJBwo4yOaO4m7Sb5bNMB7BKN/DHmDDXAZ2kiNDKHe4fkJ5begZYRd2UpePzxJPOsmbQPGOoHunAKymr3lQ6bBlDq7HQ1Gh78QM3n0FmYlsJ9/WTTsO@gjKqwdBde0gCv19DCqP43v3HoISthhX0/tXVW7gi4qvb9yruQeOws@wASu385bdh0hWZMX9GyK/uGRh5kWj5y1@9RIKOHl7G8saJExGN10G/kBdGEKisBe3qm54wbnXQSKKUJUTjkaYS6mcYUQ4SqWcjhxJiMkh90fBE8oQLbeltss8D3SFNGqyih7CXAvOHgKkkD22erHEYQNe3gROllJYSLconxvWSqoy8psJHwP@H9LD4S8 "Ruby – Try It Online") to get input data in some formatting. In the header section you can change some characters like array bounds and others. Data is in the form of a square matrix and the image is surrounded by whitespaces. # Rules * Input/output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963). * You can print it to STDOUT, return it as a function result or error message/s. * Either a full program or a function are acceptable. * [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins. [Sandbox](https://codegolf.meta.stackexchange.com/a/24336/84844) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 102 bytes ``` WS⊞υιυ≔ΦLυ№§υι×-⁴η≔Σηζ¿η‖T↗«≔Eθ⭆υ§λκυ≔ΣΦLυ№§υι×|⁴ζ»Jζ⌕§υζ×§-|¬η⁴F⁴↓§ -⊙EErlKDχ✳κ…κ⌕Eκ›μ ⁰∧›⁵Lκ№κ-¿η‖T↗ ``` [Try it online!](https://tio.run/##lVFda8IwFH22v@LSpwRScOBe9KkoDsc2RN0PKDW2oWnSpemczv327qYfVgZjLJBycnpO7rk3cRqZWEeyro@pkBzIShWV3VojVEIohXVVpqRiIOjMWyNpSYUoLEuRKLIU0nJDnrhKLKoog7muUBLaldrzj9bHYCdyXhI/8BlMKEUiHa7YVjlJkTojJQ6AGDb8IHlsdyZS5UGbnExfi41IUosSLksOn96ocz9HBXlj0MZ1B6zYF5cMsqaaCzy6Kfe/1Jdrahfxy3us8mKnyZnBUqj9rel8NfWkHzj3i7bYFm2vmXnYEpAJTraZ5nShj2oI7YObUqhOTWtu@0Yis@Y8WwiDYxFakbsxg@HUdjk/xZLPU12QrIvm3IgfDI9cvzkDH3wnHbtPiIr@1z2DbhoZvY4DrfhklDah/36augaACzTL@w0GuDp46egfcBD0Pq8O3uU3 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of strings containing spaces, minus signs or pipes. Explanation: ``` WS⊞υι ``` Input the game. ``` υ ``` Output the game to the canvas. ``` ≔ΦLυ№§υι×-⁴η≔Σηζ ``` Try to locate a horizontal stick. ``` ¿η ``` If one was found, then... ``` ‖T↗ ``` ... reflect the canvas transforming between minus signs and pipes, ... ``` « ``` Otherwise, ... ``` ≔Eθ⭆υ§λκυ ``` ... transpose the game array (sadly without transforming), ... ``` ≔ΣΦLυ№§υι×|⁴ζ ``` ... and find a vertical stick. ``` »Jζ⌕§υζ×§-|¬η⁴ ``` Jump to the stick's current location on the canvas. ``` F⁴↓§ -⊙EErlKDχ✳κ…κ⌕Eκ›μ ⁰∧›⁵Lκ№κ- ``` Overwrite the pipes of the (possibly transformed) stick with spaces, unless there are at most four consecutive non-blank characters (including the pipe itself) including at least one minus sign on at least one side of the pipe, in which case overwrite with a minus sign instead. ``` ¿η‖T↗ ``` Transform the canvas back if necessary before it's implicitly printed. ]
[Question] [ Your task is to program a mathematical function \$s\$, that takes a nonempty finite set \$A\$ of points in the 2D plane, and outputs an uncircularity score \$s(A)\$ that satisfies following properties: 1. *Positive Definiteness*: If there is a circle or a straight line that contains all points of \$A\$, then \$s(A) = 0\$. Otherwise \$s(A) > 0\$ 2. *Surjectivity:* It is surjective to the nonnegative real numbers, that means for every nonnegative real number \$r\$ there is a finite subset \$A\$ of the plane such that \$s(A) = r\$. 3. *Translation Invariance:* \$s\$ is translation invariant if \$s(A) = s(A + v)\$ for every vector \$v\$ and for all \$A\$. 4. *Scale Invariance:* \$s\$ is scale invariant, if \$s(A) = s(tA)\$ for every \$t≠0\$ and for all \$A\$. 5. *Continuity.* \$s\$ is said to be *continuous* if the function \$f(p) := s(A ∪ \{p\})\$ (mapping the a point `p` to a real number) is continuous using the standard absolute value on the real numbers, and the standard euclidean norm on the points of the plane. Intuitively speaking this *uncircularness score* can be thought of as something similar to the correlation coefficient in linear regression. ### Details Your function in theory has to work in the reals, but for the purpose of this challenge you can use floating point numbers as substitute. Please provide an explanation of your submission and an argument why those five properties hold. You can take two lists of coordinates or a list of tuples or similar formats as input. You can assume that no point in the input is repeated i.e. all points are unique. [Answer] # Python 2 with numpy, 116 bytes ``` from numpy import* def f(x,y):a=linalg.lstsq(hstack((x,y,ones_like(x))),(x*x+y*y)/2);return a[1]/sum((x-a[0][0])**4) ``` Takes x and y as 2d column vectors and returns an array containing the answer. Note that this will give an empty array for a perfectly straight line or with 3 or fewer points. I think lstsq gives no residuals if there's a perfect fit. ### Explanation Essentially, this finds the circle of best fit and gets the squared residuals. We want to minimize `(x - x_center)^2 + (y - y_center)^2 - R^2`. It looks nasty and nonlinear, but we can rewrite that as `x_center(-2x) + y_center(-2y) + stuff = x^2 + y^2`, where the `stuff` is still nasty and nonlinear in terms of `x_center`, `y_center`, and `R`, but we don't need to care about it. So we can just solve `[-2x -2y 1][x_center, y_center, stuff]^T = [x^2 + y^2]`. We could then back out R if we really wanted, but that doesn't help us much here. Thankfully, the lstsq function can give us the residuals, which satisfies most of the conditions. Subtracting the center and scaling by `(R^2)^2 = R^4 ~ x^4` gives us translational and scale invariance. 1. This is positive definite because the squared residuals are nonnegative, and we're dividing by a square. It tends toward 0 for circles and lines because we're fitting a circle. 2. I'm fairly sure it's not surjective, but I can't get a good bound. If there is an upper bound, we can map [0, bound) to the nonnegative reals (for example, with 1 / (bound - answer) - 1 / bound) for a few more bytes. 3. We subtract out the center, so it's translationally invariant. 4. We divide by x\*\*4, which removes the scale dependence. 5. It's composed of continuous functions, so it's continuous. [Answer] # Python, 124 bytes ``` lambda A:sum(r.imag**2/2**abs(r)for a in A for b in A for c in A for d in A if a!=d!=b!=c for r in[(a-c)*(b-d)/(a-d)/(b-c)]) ``` Takes *A* as a sequence of complex numbers (`x + 1j*y`), and sums Im(*r*)2/2|*r*| for all complex cross-ratios *r* of four points in *A*. ### Properties 1. *Positive Definiteness.* All terms are nonnegative, and they’re all zero exactly when all the cross-ratios are real, which happens when the points are collinear or concyclic. 2. *Surjectivity.* Since the sum can be made arbitrarily large by adding many points, surjectivity will follow from continuity. 3. *Translation Invariance.* The cross-ratio is translation-invariant. 4. *Scale Invariance.* The cross-ratio is scale-invariant. (In fact, it’s invariant under all Möbius transformations.) 5. *Continuity.* The cross-ratio is a continuous map to the extended complex plane, and *r* ↦ Im(*r*)2/2|*r*| (with ∞ ↦ 0) is a continuous map from the extended complex plane to the reals. (Note: A theoretically prettier map with the same properties is *r* ↦ (Im(*r*)/(*C* + |*r*|2))2, whose contour lines w.r.t. all four points of the cross-ratio are circular. If you actually need an uncircularness measure, you probably want that one.) ]
[Question] [ It's the election! The area which we are in implements the system of voting called **instant runoff** (sometimes called **alternative vote** or **preferential voting**). Each voter orders each candidate from most preferred to least preferred, marking a "1" for their most preferred candidate, a "2" for their second candidate, and so forth until each candidate is numbered. I'll let this friendly koala explain the rest: [![preferential voting](https://i.stack.imgur.com/OwMDK.png)](http://chickennation.com/website_stuff/cant-waste-vote/web-700-cant-waste-vote-SINGLE-IMAGE.png) (Image modified from [original](http://chickennation.com/website_stuff/cant-waste-vote/web-700-cant-waste-vote-SINGLE-IMAGE.png) by [Patrick Alexander](http://www.chickennation.com/), used under the [CC BY-NC-SA 3.0 AU licence](http://creativecommons.org/licenses/by-nc-sa/3.0/au/deed.en_GB)). If you prefer your instant runoff explanation in text form, there's also the [Wikipedia article](https://en.wikipedia.org/wiki/Instant-runoff_voting). (Note: It's also possible, although unlikely, for there to be two or more candidates with the least votes. In these situations, choose one of them randomly at equal probabilities and eliminate them.) In this challenge, the first line of input is a list of strings, which are the names of the candidates for the election. In these examples I've used pipe delimited values, although feel free to adjust the input format to suit your language. ``` The Omitted Anti-neutrino|Placazoa|Alexander the Awesome|Tau Not Two|Semolina Sorcerer ``` Following that are `n` lines of input which are also lists of strings, each which represents a single vote. The first entry represents that votes #1 preference, the next the #2 preference, etc. For example: ``` Alexander the Awesome|Semolina Sorcerer|Tau Not Two|Placazoa|The Omitted Anti-neutrino ``` would mean that that particular vote has Alexander as their first preference, Semolina Sorcerer as their second, Tau Not Two as their third, etc. You can assume that every vote will contain every candidate, and that there will be no blank or incomplete votes. Given the votes as input, your program or function should then output the winner of the election. You can find an ungolfed reference implementation in Python 3 [here](https://gist.github.com/auburnsummer/2a826e562da2694da378d32b94a3c52e). **Example Inputs and Outputs** **Input** ``` Dionysius|Portal Butter|Alexander the Awesome|Red Trainmen Portal Butter|Alexander the Awesome|Dionysius|Red Trainmen Dionysius|Portal Butter|Alexander the Awesome|Red Trainmen Portal Butter|Red Trainmen|Alexander the Awesome|Dionysius Dionysius|Portal Butter|Alexander the Awesome|Red Trainmen Alexander the Awesome|Red Trainmen|Portal Butter|Dionysius Red Trainmen|Alexander the Awesome|Dionysius|Portal Butter Dionysius|Portal Butter|Alexander the Awesome|Red Trainmen Red Trainmen|Dionysius|Portal Butter|Alexander the Awesome Alexander the Awesome|Dionysius|Red Trainmen|Portal Butter Dionysius|Portal Butter|Alexander the Awesome|Red Trainmen Alexander the Awesome|Red Trainmen|Dionysius|Portal Butter ``` **Output** ``` Alexander the Awesome ``` **Input** ``` Depressed Billy|Sighted Citrus|Frosty Fox|Electronic Accident Frosty Fox|Sighted Citrus|Electronic Accident|Depressed Billy Frosty Fox|Depressed Billy|Sighted Citrus|Electronic Accident Depressed Billy|Electronic Accident|Sighted Citrus|Frosty Fox Depressed Billy|Sighted Citrus|Electronic Accident|Frosty Fox Depressed Billy|Electronic Accident|Sighted Citrus|Frosty Fox Electronic Accident|Frosty Fox|Depressed Billy|Sighted Citrus Sighted Citrus|Frosty Fox|Electronic Accident|Depressed Billy Frosty Fox|Depressed Billy|Sighted Citrus|Electronic Accident Sighted Citrus|Electronic Accident|Frosty Fox|Depressed Billy Frosty Fox|Electronic Accident|Depressed Billy|Sighted Citrus Sighted Citrus|Frosty Fox|Depressed Billy|Electronic Accident ``` **Output** `Sighted Citrus` or `Frosty Fox` (randomly) **Input** You can get the last input set [here](https://gist.githubusercontent.com/auburnsummer/dd7409ebd9e81a3bb5600bc9dedfbf8b/raw/c3f008f14dd6fd87e01eab8212d29e2029e9b853/votes3). It is one of the voting areas of a recent Australian election, and consists of 63 428 votes. **Output** ``` Ross HART ``` [Answer] # Pyth - 30 bytes Will refactor it. Infers first line from rest of input. ``` WgclQ2leKlD.gkhMQ=Q-RhhJKQ;hhJ ``` [Test Suite](http://pyth.herokuapp.com/?code=WgclQ2leKlD.gkhMQ%3DQ-RhhJKQ%3BhhJ&test_suite=1&test_suite_input=%5B%5B%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Dionysius%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Portal+Butter%27%2C+%27Red+Trainmen%27%2C+%27Alexander+the+Awesome%27%2C+%27Dionysius%27%5D%2C+%5B%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%2C+%27Portal+Butter%27%2C+%27Dionysius%27%5D%2C+%5B%27Red+Trainmen%27%2C+%27Alexander+the+Awesome%27%2C+%27Dionysius%27%2C+%27Portal+Butter%27%5D%2C+%5B%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Red+Trainmen%27%2C+%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%5D%2C+%5B%27Alexander+the+Awesome%27%2C+%27Dionysius%27%2C+%27Red+Trainmen%27%2C+%27Portal+Butter%27%5D%2C+%5B%27Dionysius%27%2C+%27Portal+Butter%27%2C+%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%5D%2C+%5B%27Alexander+the+Awesome%27%2C+%27Red+Trainmen%27%2C+%27Dionysius%27%2C+%27Portal+Butter%27%5D%5D%0A%5B%5B%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%2C+%27Frosty+Fox%27%2C+%27Electronic+Accident%27%5D%2C+%5B%27Frosty+Fox%27%2C+%27Sighted+Citrus%27%2C+%27Electronic+Accident%27%2C+%27Depressed+Billy%27%5D%2C+%5B%27Frosty+Fox%27%2C+%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%2C+%27Electronic+Accident%27%5D%2C+%5B%27Depressed+Billy%27%2C+%27Electronic+Accident%27%2C+%27Sighted+Citrus%27%2C+%27Frosty+Fox%27%5D%2C+%5B%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%2C+%27Electronic+Accident%27%2C+%27Frosty+Fox%27%5D%2C+%5B%27Depressed+Billy%27%2C+%27Electronic+Accident%27%2C+%27Sighted+Citrus%27%2C+%27Frosty+Fox%27%5D%2C+%5B%27Electronic+Accident%27%2C+%27Frosty+Fox%27%2C+%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%5D%2C+%5B%27Sighted+Citrus%27%2C+%27Frosty+Fox%27%2C+%27Electronic+Accident%27%2C+%27Depressed+Billy%27%5D%2C+%5B%27Frosty+Fox%27%2C+%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%2C+%27Electronic+Accident%27%5D%2C+%5B%27Sighted+Citrus%27%2C+%27Electronic+Accident%27%2C+%27Frosty+Fox%27%2C+%27Depressed+Billy%27%5D%2C+%5B%27Frosty+Fox%27%2C+%27Electronic+Accident%27%2C+%27Depressed+Billy%27%2C+%27Sighted+Citrus%27%5D%2C+%5B%27Sighted+Citrus%27%2C+%27Frosty+Fox%27%2C+%27Depressed+Billy%27%2C+%27Electronic+Accident%27%5D%5D&debug=0). [Answer] # [R](https://www.r-project.org/), ~~101~~ 99 bytes ``` f=function(m)`if`(n<-dim(m)-1,f(matrix(m[m!=names(t<-sample(table(m[1,])))[which.min(t)]],n)),m[1]) ``` [Try it online!](https://tio.run/##vZIxa8MwEIV3/QrXkwRKIdAxHpKmmUvbLRiiyudaYElBumAH/N9dTU1sEscmJYtAOr3vPZ3OtW2e5AcjUVlDNdupfEfNYpYpHXazOc@pFuhUTfVWPyVGaPAUFzMv9L4EiuI7rHo75yljbFsVShbPWhmKLE25YYyHWsraP4qXIhShxiR@tw5FGa0OiOCaZQm1MBm4CAuIlhV4q6FZh1RHrw6@@YAs@nJCGQ2GnI7HQDrSruC8dCvCPa63r/SYJ9cpEbuQewJ3XCdxyJSf/L/AIzp8hR7zqhBhHmPuYZ/ETcy4cbZKXhgj5NLgbpz1eIw2tm4@1U@BweNVoQvctxIkOmuUjJZSqgwMNmvYO/A@XFqpsjySM3WvNIJG@pJLjj3MyZBMNxxST/Meht/oBbnKfUDPJ3VpyHtE1PHvHvEbA5Pd/gI "R – Try It Online") Takes input as a matrix, with each column representing the choices of one voter. Works by recursion: find a candidate with minimal number of votes, delete all corresponding entries in the matrix, reformat the matrix, and recurse until the matrix has only 1 row. The votes at each iteration are computed by counting with `table` the values in the top row, which are the current top choices of each voter. This is shuffled with `sample` to break ties at random. `n<-dim(m)-1` gives a vector of length 2, but only the first value is used (so it is equivalent, but 1 byte shorter than, `n<-nrow(m)-1`). This value is used twice: first it is compared to 0 to check whether the last iteration has been reached; second, if we recurse, it is the number of rows of the new matrix. [Answer] # [Python 2](https://docs.python.org/2/), 209 bytes ``` def f(s): d={} for v in s: k=v[0];d[k]=d.get(k,[])+[v] if len(d[k])>len(s)/2:return k D=d.values() for v in choice([g for g in D if len(g)==len(min(D,key=len))]):v.pop(0) return f(s) from random import* ``` [Try it online!](https://tio.run/##rZJPc4IwEMXP5lPsDdI61nqkQ2e01nOn7Y1ycGDBDJAwSaQypZ/dBtuO6PgHRk@BJO/33m42L/VC8NF6HWIEka2oQyB0v74JREJCAYyDckgvcQtv6D@EXuK74SBGbSd9z6e3XuGTHosgRW7Xh/Sx/lL0buRI1EvJISEwNZJini5R2bTBDRaCBWh78WYrrrem8MeKqevWa8a4Pe0nWNZ/lPrUKQa5yO2hAf0Z1KFJJEUGcs5Ds7AsF1LfbCqabSrqKdcrBipPmbatyqKN2v53P7hFTSlbpnfv@JSQXDKuDcayrCkTvFRsqaoXw5@nMFlqjbIap7gyzihBLxDGn6hEhtUrhvAu54xnyEkbwRa/I72aa/PoXIRLXM9f2WNuXbtE3IVcEnjHtROHdHnJ6wVu0eEjdDPF9Hekdycbc4lKGcCEpWlZvbF4oc3fE9PSIGZSKF3CTKyq5xQDLQVnAYyDgIVoSI3jPeGB29WeV1N9JsYh733JIcej1ZDuhqfU3bxPw8/0gnR6oSv3vFOXTnm3iNq@7havsZl@sv4B "Python 2 – Try It Online") Takes input as a list of lists of voter prefernces (the header row is not included). The randomization in case of a tie is vexing! [Answer] # [Perl 5](https://www.perl.org/) `-plF\|`, 155 bytes ``` %r?push@v,[@F]:map$r{$_}=1,@F}{while(@v/2>=$c{$\=pop@t}){map{shift@$_ while!$r{$$\_[0]}}@v;%c=();map$c{$$_[0]}++,@v;$r{(@t=sort{$c{$a}-$c{$b}}keys%c)[0]}=0} ``` [Try it online!](https://tio.run/##rVFdT4MwFH3nV2BSEshAmcleXKr1izeffNwWMrsqjZU2bYeS0r8uwhKThSCDxKfm9pxzz73nCiLZoq49eSP2KkNFuELJ5upjK4A0ILVwHqLEms@MMuKj4uLyGgJswBoKLpC2gWmYRmX0VSOQugfaWasE6SreWIuKpYehHyzbhvj3ezYLG6Ch@UhDxaU2Lba1Ufu8WPtOSuXhoKXC2Nb1AxGSKEV27h1lrKye6Vumm@qearlXVSK50qWb8K/qkRGsJc8pdm8xpjuSa@cI7gh72FXH61h9Yow@766kz/HPbZzphkPqad7DzU9k4Uy60D9nPimlIe8Ro47fe8Q1vrnQlOeqjp4W5/E8riPBknX1Aw "Perl 5 – Try It Online") [Answer] **[Python 2](https://docs.python.org/2/), 200 bytes** ``` def f(s): d={} for v in s: k=v[0];d[k]=d.get(k,[])+[v] if len(d[k])>len(s)/2:return k D=d.values() x=[g for g in D if len(g)==len(min(D,key=len))] for v in x[id(x)%len(x)]:v.pop(0) return f(s) ``` [Try it online!](https://tio.run/##rZJLb4JAFIXXzq@4mwYmNda6pKGJlrpu2u4oCyNXnIAzZGagkNLfbgfbRjQ@ILqCeZzvnHvnpqVeCj5ar0NcwMJW1CEQul/fBBZCQg6Mg3JIL3Zzfxg8hH4cuOEgQm3HfT@gt34ekB5bQILcrg/pY/2n6N3IkagzySEm4BlJPksyVDYlULh@tIFHNdyDP3VEXbf@rhi3vX6MZb2iNGgEKXwW2gW9qa8VNHDyQSpSe2iYf151/k0h000hPeX6@UClCdO2VVm0UdL/7ge3jEVvq/fvnYASkkrGtcFYluUxwUvFMlW9CKlnCUwyrVFW4wSLGQ9Rgl4ijD9RiRVWrxjCu5wxvkJO2gi2@B3p1VybR@ciXOJ6/soec@vaJeIu5JLAO66dOKTLS14vcIsOH6GbKaa/I7072ZhKVMoAJixJyuqNRUttVk9MS4OYSqF0CVNRVM8JzrUUnM1hPJ@zEA2pcbwnPHC72vNqqs/EOOS9LznkeLQa0t3wlLqb92n4mV6QTi905Z536tIp7xZR29fd4jU200/WPw) Utilises the object ID of the array as a source of 'randomness'. Based off [Chas Brown's Answer](https://codegolf.stackexchange.com/a/188261/52045) - I don't have enough rep to comment! ]
[Question] [ Write a program or function which, given an input string and a standard deviation `σ`, outputs that string along the normal distribution curve with mean `0` and standard deviation `σ`. ### Normal distribution curve The `y` coordinate of each character `c` is: [![enter image description here](https://i.stack.imgur.com/ly0EB.png)](https://i.stack.imgur.com/ly0EB.png) where `σ` is given as input, and where `x` is the `x` axis coordinate of `c`. * The character in the center of the string has `x = 0`. If the string's length is even, either of the two middle characters can be chosen as the center. * Characters are separated by steps of `0.1` (e.g. the character to the left of the center one has `x = -0.1`, the one to the right of the middle one has `x = 0.1`, etc.). ### Printing the string * Lines, like characters, are separated by steps of `0.1`. * Each character is printed on the line with the `y` value that is closest to its own `y` value (if the value is precisely in between the values of two lines, choose the one with the biggest value (just like how `round` usually returns `1.0` for `0.5`)). * For example, if the `y` coordinate of the center value (i.e. the maximum value) is `0.78` and the `y` coordinate of the first character is `0.2`, then there will 9 lines: the center character being printed on line `0` and the first character being printed on line `8`. ### Inputs and outputs * You may take both inputs (the string and `σ`) as program arguments, through `STDIN`, function arguments or anything similar in your language. * The string will only contain printable `ASCII` characters. The string can be empty. * `σ > 0`. * You may print the output to `STDOUT`, in a file, or return it from a function (**as long as** it is a string and not say a list of strings for each line). * A trailing new line is acceptable. * Trailing spaces are acceptable as long as they don't make the line exceed the last line in length (so no trailing space is acceptable on the last line). ### Test cases ``` σ String 0.5 Hello, World! , W lo or l l e d H ! 0.5 This is a perfectly normal sentence tly ec n f o r r e m p a a l s se This i ntence 1.5 Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers. d answer site for p uestion an rogramming Code Golf is a q puzzle enthusia Programming Puzzles & sts and code golfers. 0.3 ..................... . . . . . . . . . . . . . . . ... ... ``` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), ``` nsw a er t s i e n t or by sh te so the s wins. ``` [Answer] # Python 3 with [SciPy](https://www.scipy.org/scipylib/index.html), ~~239~~ 233 bytes ``` from scipy import stats,around,arange def f(s,t): l=len(t);p=[];y=around(stats.norm.pdf((arange(l)-l//2)*.1,scale=s),1)*10 for i in range(l):p+=[[' ']*(max(y)-y[i])];p[i]+=[t[i]]+[' ']*(y[i]-y[0]) for j in zip(*p):print(*j,sep='') ``` A function that takes input via argument of standard deviation `s` and string `t`, and prints the result to STDOUT. **How it works** ``` from scipy import stats,around,arange Import the statistics, rounding and range functions from SciPy def f(s,t): Function with input standard deviation s and string t l=len(t);p=[] Define the much-used length of t as l and initialise the print values list p arange(l) Generate a list of integer x values in [0,l)... ...-l//2*.1 ...and scale such that 0 is at the middle character and the x-step is 0.1 stats.norm.pdf(...,scale=s) Generate a list containing the y values for each x value by calling the normal probability density function scaled with s... y=around(...,1) ...round all values to 1 decimal place... ...*10 ...and multiply by 10 to give the vertical index of each character for i in range(l):... For all characters in t... p+=[[' ']*(max(y)-y[i])] ..add the number of lines below the character as spaces... p[i]+=[t[i]]+[' ']*(y[i]-y[0]) ...add the character and the number of lines above the character as spaces This leaves p containing a list for each desired output line, but transposed. for j in zip(*p):... For every output line in the transpose of p... print(*j,sep='') ...print the output line ``` [Try it on Ideone](https://ideone.com/LzrOpE) [Answer] ## Ruby: ~~273~~ 254 Bytes ``` ->n,s{j,o,g,r,l=-(n.size/2),[],0,{} n.gsub(/./){(r[((2*Math::PI)**-0.5*10*Math.exp(-(j/1e1)**2/2/s/s)/s).round]||="")<<$& j+=1} r.sort.map{|y, c|o<<(l ?$/*(y-l-1):"")+(" "*g)+(c[0,(h=c.size)/2])+(" "*(n.size-g*2-h))+(c[h/2,h]) g+=h/2 l=y} puts o.reverse} ``` A huge thanks to [Kevin Lau](https://codegolf.stackexchange.com/users/52194/kevin-lau-not-kenny) for saving 18 bytes! ]
[Question] [ ## Specification This challenge is simple to state: your input is a non-empty array of nonnegative integers, and your task is to partition it into as few increasing subsequences as possible. More formally, if the input array is `A`, then the output is an array of arrays `B` such that: * Each arrays in `B` form a partition of `A` into disjoint (not necessarily contiguous) subsequences. Inductively, this means that either `B` is the singleton array containing `A`, or the first element of `B` is a subsequence of `A` and the rest form a partition of `A` with that subsequence removed. * Every array in `B` is (not necessarily strictly) increasing. * The number of arrays in `B` is minimal. Both the input and output can be taken in the native array format of your language. Note that there may be several correct outputs. ## Example Consider the input array `A = [1,2,1,2,5,4,7,1]`. One possible output is `B = [[1],[1,2,4,7],[1,2,5]]`. The partition condition is evident from this diagram: ``` A 1 2 1 2 5 4 7 1 B[0] 1 B[1] 1 2 4 7 B[2] 1 2 5 ``` Also, each array in `B` is increasing. Finally, `A` can't be split into two increasing subsequences, so the length of `B` is also minimal. Thus it's a valid output. ## Rules and scoring You can write a function or a full program. The lowest byte count wins, and standard loopholes are disallowed. There is no time bound, but you should evauate your solution on all test cases before submitting it. ## Test cases Only one possible output is shown, but there may be several valid options. In particular, the order of the arrays in the result doesn't matter (but each individual array should be in increasing order). ``` [0] -> [[0]] [3,5,8] -> [[3,5,8]] [2,2,2,2] -> [[2,2,2,2]] [1154,1012,976,845] -> [[845],[976],[1012],[1154]] [6,32,1,2,34,8] -> [[1,2,8],[6,32,34]] [1,12,1,12,1,13] -> [[1,1,1,13],[12,12]] [6,4,6,13,18,0,3] -> [[0,3],[4,6,13,18],[6]] [1,2,3,2,3,4,7,1] -> [[1,1],[2,2,3,4,7],[3]] [0,9,2,7,4,5,6,3,8] -> [[0,2,3,8],[4,5,6],[7],[9]] [7,1,17,15,17,2,15,1,6] -> [[1,1,6],[2,15],[7,15,17],[17]] [4,12,2,10,15,2,2,19,16,12] -> [[2,2,2,12],[4,10,15,16],[12,19]] [10,13,9,2,11,1,10,17,19,1] -> [[1,1],[2,10,17,19],[9,11],[10,13]] [3,7,3,8,14,16,19,15,16,2] -> [[2],[3,3,8,14,15,16],[7,16,19]] [15,5,13,13,15,9,4,2,2,17] -> [[2,2,17],[4],[5,9],[13,13,15],[15]] ``` [Answer] ## Haskell, 54 bytes ``` n#[]=[[n]] n#(l:c)|[n]<=l=(n:l):c|1<2=l:n#c foldr(#)[] ``` Usage example: `foldr(#)[] [4,12,2,10,15,2,2,19,16,12]`-> `[[2,2,2,12],[4,10,15,16],[12,19]]` How it works: go through the input list starting at the right end. Build the output list (of lists) by prepending the current element `n` to first sublist `l` where `n` is less or equal to the head of `l`. If there's none, make a new singleton list of `n` at the end of the output list. [Answer] # Pyth, 20 bytes ``` fTu&ahfSI+THGHGQm[)Q ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=fTu%26ahfSI%2BTHGHGQm%5B%29Q&test_suite=0&input=%5B1%2C2%2C1%2C2%2C5%2C4%2C7%2C1%5D&test_suite_input=%5B0%5D%0A%5B3%2C5%2C8%5D%0A%5B2%2C2%2C2%2C2%5D%0A%5B1154%2C1012%2C976%2C845%5D%0A%5B6%2C32%2C1%2C2%2C34%2C8%5D%0A%5B1%2C12%2C1%2C12%2C1%2C13%5D%0A%5B6%2C4%2C6%2C13%2C18%2C0%2C3%5D%0A%5B1%2C2%2C3%2C2%2C3%2C4%2C7%2C1%5D%0A%5B0%2C9%2C2%2C7%2C4%2C5%2C6%2C3%2C8%5D%0A%5B7%2C1%2C17%2C15%2C17%2C2%2C15%2C1%2C6%5D%0A%5B4%2C12%2C2%2C10%2C15%2C2%2C2%2C19%2C16%2C12%5D%0A%5B10%2C13%2C9%2C2%2C11%2C1%2C10%2C17%2C19%2C1%5D%0A%5B3%2C7%2C3%2C8%2C14%2C16%2C19%2C15%2C16%2C2%5D%0A%5B15%2C5%2C13%2C13%2C15%2C9%2C4%2C2%2C2%2C17%5D) or [Test Suite](http://pyth.herokuapp.com/?code=fTu%26ahfSI%2BTHGHGQm%5B%29Q&test_suite=1&input=%5B1%2C2%2C1%2C2%2C5%2C4%2C7%2C1%5D&test_suite_input=%5B0%5D%0A%5B3%2C5%2C8%5D%0A%5B2%2C2%2C2%2C2%5D%0A%5B1154%2C1012%2C976%2C845%5D%0A%5B6%2C32%2C1%2C2%2C34%2C8%5D%0A%5B1%2C12%2C1%2C12%2C1%2C13%5D%0A%5B6%2C4%2C6%2C13%2C18%2C0%2C3%5D%0A%5B1%2C2%2C3%2C2%2C3%2C4%2C7%2C1%5D%0A%5B0%2C9%2C2%2C7%2C4%2C5%2C6%2C3%2C8%5D%0A%5B7%2C1%2C17%2C15%2C17%2C2%2C15%2C1%2C6%5D%0A%5B4%2C12%2C2%2C10%2C15%2C2%2C2%2C19%2C16%2C12%5D%0A%5B10%2C13%2C9%2C2%2C11%2C1%2C10%2C17%2C19%2C1%5D%0A%5B3%2C7%2C3%2C8%2C14%2C16%2C19%2C15%2C16%2C2%5D%0A%5B15%2C5%2C13%2C13%2C15%2C9%2C4%2C2%2C2%2C17%5D) Greedy approach. I create `len(input)` empty lists. Then I iterate over each number in the `input` an choose the first list, which is still sorted after appending the number. ### Explanation: ``` fTu&ahfSI+THGHGQm[)Q implicit: Q = input list m[)Q create a list of empty lists and assign to G u Q iterate over all numbers H in input: f G filter for lists T in G, which satisfy: +TH create a new list out of T and H SI and check if it is sorted h take the first such list T a H and append H & G logical and with G (so that u doesn't overwrite G) fT remove all empty lists ``` ]
[Question] [ This challenge is based off a riddle I read in some book a while ago, which I found again [here](http://brainden.com/forum/topic/17429-random-bullets/). It is about bullets fired from a gun once per second at varying speeds that travel in a straight line forever. When one bullet hits another, both are destroyed completely. (Feel free to replace all instances of "bullet" with "missile".) ## The Task Given a list of bullet speeds in the order they're fired in, determine whether all bullets are destroyed. ## The Rules * Input is a list of non-negative integers, separated by any delimiter and with one optional character before and after. These are valid inputs: `1 2 3 4 5 6` and `[1,2,3,4,5,6]`. The programmer makes the choice. * Output a truthy value if at least one bullet survives forever and a falsy value otherwise. * Bullet speeds are given in units per second. * Bullets move simultaneously and continuously. * Bullets may collide at fractional offsets. * Multiple bullets which simultaneously reach the exact same position, whether at an integral or fractional offset from the origin, all collide with each other. ## Examples In these diagrams, `G` represents the gun, `>` the bullets, and `*` are times when bullets collide and explode. ### Truthy Input: `0` ``` 0123456789 Time 0 G> 1 G> 2 G> ... ``` Output: `1` --- Input: `0 0 0` ``` 0123456789 Time 0 G> 1 G* 2 G> 3 G> 4 G> ... ``` Output: `1` --- Input: `1` ``` 0123456789 Time 0 G> 1 G > 2 G > 3 G > ... ``` Output: `1` --- Input: `2 1` ``` 0123456789 Time 0 G> 1 G> > 2 G > > 3 G > > 4 G > > ... ``` Output: `1` --- Input: `2 3 1` ``` 0123456789 Time 0 G> 1 G> > 2 G> >> 3 G > * 4 G > 5 G > ... ``` Output: `1` --- ### Falsy Input: `1 2 3 4 5 6` ``` Unit 1111111111 01234567890123456789 Time 0 G> 1 G>> 2 G> * 3 G> > 4 G> > > 5 G> > >> 6 G > > * 7 G > > 8 G > > 9 G >> 10 G * 111111111122222222223 0123456789012345678901234567890 ``` Output: `0` --- Input: `1 0 0 3` ``` Unit 0123456789 Time 0 G> 1 G>> 2 G* > 3 G> > 4 G >> 5 G * ``` (The second collision is at time 4.5) Output: `0` --- Input: `2 1 2 3 6 5` ``` Unit 1111111111 01234567890123456789 Time 0 G> 1 G> > 2 G>> > 3 G> * > 4 G> > > 5 G> * > 6 G > > 7 G > > 8 G >> 9 G * 1111111111 01234567890123456789 ``` Output: `0` --- Input: `2 3 6` ``` Unit 0123456789 Time 0 G> 1 G> > 2 G> >> 3 G * ``` Output: `0` [Answer] ## Python 2, ~~388~~ ~~392~~ ~~388~~ ~~346~~ ~~342~~ ~~336~~ 331 bytes ``` z=k=input();l=len(k);v=range;u=v(l) while l<z: r="";o=[r]*l;z=l for h in v(l): if r:o[h-1]=o[m]=r;m=h;r="" for j in v(h+1,l): p=k[h];q=k[j];t=u[j];n=(1.0*q*t-p*u[h])/(q-p)if q-p else""if p>0 else t if t<=n<r<()>o[j]>=n<=o[h]:r=n;m=j i=0;s=o and min(o) while i<l: if o[i]==s!="":del k[i],o[i],u[i];l-=1 else:i+=1 print l ``` My god this thing is huge, but I believe it actually does work. Once you see all the intricacies of it, this challenge is ridiculously hard. I'm not sure if I can explain how it works in detail without typing for hours, so I'll just give an executive summary. The big main while loop is looping until the input list does not shrink. The nested for loop (can you believe a nested for loop is actually the shortest here?) loops over each bullet speed and ~~uses `numpy.roots` to calculate~~ calculates at which time that bullet will collide with each bullet that comes after. Here, `""` is being used to mean infinity (no intersection). An extra conditional has to be included to ensure that stopped bullets are marked as colliding the moment they appear rather than at time zero. For each number we keep track of which bullet it will hit soonest, if any, and then `o` is updated with the minimum collision times for the involved bullets. After this double loop terminates, we iterate over the input list and delete any bullet that will collide at the minimum of all collision times, if any. This allows us to simultaneously delete large numbers of bullets if they all happen to collide at the same moment. Then we repeat the entire process on the remaining bullets, since they may be able to get by now that the bullets that they would have collided with have been destroyed. As soon as no bullets are deleted (indicated by the list not shrinking), we escape the while loop and print the length of the remaining list. Thus, this program not only prints truthy if bullets survive, it actually prints exactly the number of bullets that survive. EDIT: Special thanks to feersum for generating test cases to help me find bugs. EDIT 2: Saved 42 bytes by solving the linear equation by hand instead of using numpy, and splitting out the starting times into a separate list and restructuring a conditional. EDIT 3: Saved 4 bytes by renaming range EDIT 4: Saved 6 more bytes by replacing double spaces with tabs. Also, feersum was kind enough to provide his implementation using fractions and sets for comparison. I've golfed it a bit and it comes out to 331 bytes, tying my solution. EDIT 5: saved 5 bytes by removing an unnecessary initialization and rewriting a conditional ]
[Question] [ In this challenge, you must display ASCII art of a water balloon given the amount of water that the balloon is filled with: ``` | __||__ | | / # #\ | | |######| | | |######| | | |######| | | |######| | | |######| | | \######/ | | | | | +----------+ ``` ## How to draw the balloon To display a balloon of size `n`, follow the following steps (note: whenever the division symbol (`/`) is used, it represents integer division, rounding down): 1. Draw a container consisting of ten vertical bars (`|`) on the left and right, ten dashes (`-`) on the bottom, and a plus sign (`+`) in the bottom left and bottom right corner. This makes the whole thing 12x11, and the "inside" 10x10. ``` | | | | | | | | | | | | | | | | | | | | +----------+ ``` 2. Draw two vertical bars (the opening of the balloon) centered in the middle of the top row, with `n/2` underscores (`_`) on either side (for this example, `n` will be 5): ``` | __||__ | | | | | | | | | | | | | | | | | | | +----------+ ``` 3. Draw one slash (`/`) and one backslash (`\`) surrounding this top row, one row below: ``` | __||__ | | / \ | | | | | | | | | | | | | | | | | +----------+ ``` 4. Draw `n` rows of identically-spaced vertical bars, and then one row of a pair of (still identically-spaced) backslash and slash: ``` | __||__ | | / \ | | | | | | | | | | | | | | | | | | | | | | \ / | | | | | +----------+ ``` 5. "Fill" the balloon with water, represented by a hash sign (`#`). Start at the lowest row, and work upwards. If a row is not entirely filled, you may place the hash marks wherever you want (in the below example, they are placed randomly, but you could put them, say, all on the left side if you want). ``` | __||__ | | / # #\ | | |######| | | |######| | | |######| | | |######| | | |######| | | \######/ | | | | | +----------+ ``` The maximum `n` is 7, and the minimum is 0. ## Input The input will be an integer `i`, which is the amount of hash marks (water) that must be drawn. It will never be less than 2, or greater than 100. ## Output The output should be a balloon of size `n` containing `i` hash marks (units of water), where `n` is the lowest possible size that can hold `i` units of water. Since `i` will always be 2 or greater, `n` will always be 0 or greater. The maximum possible size a balloon can be drawn at is `n` = 7. If a size 7 balloon cannot fit the amount of water specified, the balloon pops: ``` | | | | |## # ###| |##########| |##########| |##########| |##########| |##########| |##########| |##########| +----------+ ``` (The above should be the output for input `i` = 76. Just like the unpopped balloon, the six extra units of water on the top row may be arranged however you please.) ## Test cases Why have *one* test case, when you can have *all* of them? Here's an animated GIF of all inputs `i` from 2 to 100: ![animation of all i from 2 to 100](https://i.stack.imgur.com/HhSh7.gif) ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # Octave, 523 bytes 23 of those bytes are just for the n=100 case. Maybe someone can suggest a more efficient way... ``` n=input(0);x=zeros(11,6)+32;x(:,1)=124;x(11,:)=45;x(11,1)=43; if n<5 w=3;h=2;a=2; elseif n<7 w=3;h=3;a=2; elseif n<17 w=4;h=4;a=4; elseif n<37 w=5;h=6;a=6; else w=6;h=9;a=8; end if n<73 x(1,6)=124;x(1,9-w:5)=95;x(2,8-w)=47;x(3:1+h,8-w)=124;x(1+h,8-w)=92;x(2:1+h,9-w:6)=35;x=[x,fliplr(x)];x(2,5+w)=92;x(1+h,5+w)=47;x(2:1+floor((a*h-n)/a),9-w:4+w)=32;x(2+floor((a*h-n)/a),9-w+a-mod(a-n,a):4+w)=32; else x=[x,fliplr(x)];x(max(1,ceil((100-n)/10)):10,2:11)=35; if (n<100) x(ceil((100-n)/10),(2+mod(n,10)):11)=32; end end char(x) ``` ### Test **Input:** 21 **Output:** ``` | __||__ | | / \ | | | | | | |### | | | |######| | | |######| | | \######/ | | | | | | | +----------+ ``` [Answer] # Python 2, 591 bytes Took me some time and it probably could be golfed much more. Hope there aren't any major errors. ``` r=[list(x)for x in ("| |!"*10+"+----------+").split('!')] s,t=[0]*4+[1]*2+[2]*10+[3]*4+[4]*16+[5]*6+[6]*22+[7]*8+[8]*29,[(4,2,2),(4,3,2),(3,4,4),(3,5,4),(2,6,6),(2,7,6),(1,8,8),(1,9,8),(0,9,10)] a,b,c,d,e='|','/','\\','_','#' def p(x,y,w):r[y][x]=w def q(l): h,j,u=l p(5,0,a);p(6,0,a) for o in range(4-h):p(h+o+1,0,d);p(h+u-o,0,d) p(h,1,b);p(h+u+1,1,c) for o in range(j-2):p(h,o+2,a);p(h+u+1,o+2,a) p(h,j,c);p(h+u+1,j,b) def w(i,l): h,j,u=l for o in range(i):x,y=o%u,o/u;p(h+x+1,j-y,e) def f(i): n=s[i] l=t[n] if n<8:q(l) w(i,l) print "\n".join(["".join(x)for x in r]) ``` Example run: ``` f(34) ``` gives: ``` | __||__ | | /#### \ | | |######| | | |######| | | |######| | | |######| | | \######/ | | | | | | | +----------+ ``` ]
[Question] [ Your mission, should you choose to accept it, is to **add** the **minimum** number of parentheses, braces, and brackets to make a given string (containing only parentheses, braces, and brackets) have correct brace matching. **Ties of symbols added** must be broken by having the **maximum** distance between paired braces. You must return only one correct answer that matches these two rules; Further ties, should they exist, may be broken any way you see fit. Examples: ``` input output // Empty String is a legal input [ [] // Boring example [()] [()] // Do nothing if there's nothing to be done ({{ ({{}}) // NOT (){}{} (0 + 0 + 0). Maximum distance is 4 + 2 + 0, ({{}}) [([{])]} {[([{}])]} // NOT [([])]{[([])]} or similar ``` You may write a [program or function](http://meta.codegolf.stackexchange.com/a/2422/17249), receives the input via STDIN as a string argument to your function, which [returns the output as a string or prints it to STDOUT (or closest alternative).](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) You may optionally include a single trailing newline in the output. You may assume the input string consists only of the following 6 characters (or lack thereof): `[](){}` (You do not need to support `<>`) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest program wins. [Standard loopholes are banned, of course](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). [Answer] # Python 3, 211 207 198 bytes After some work on [this variation of this question](https://codegolf.stackexchange.com/q/245315/111305) (matching the brackets given exactly 1 unclosed opening bracket, with no possible unopened closing brackets), I realized that [my answer](https://codegolf.stackexchange.com/a/245353/111305) to that could be adapted to this problem (which was linked as a possible duplicate). ``` f=lambda s:s[::-1].translate(" ] [)(} {"*14) def m(a): *u,b="", for x in a: if x in"([{":u+=x elif u and x!=f(y:=u.pop()):b+=f(y);*u,_=u b+=x return b+f("".join(u)) M=lambda a:f(m(f(m(a)))) ``` Edit -4 bytes: inspired by some golfs on my answer on the other post by @ovs Edit -9 bytes: We have tied the old python2 answer here!! I knew there had to be some way to golf the closing of any trailing unclosed brackets onto the return statement, and after trying a lot of nonsense involving `map()` I realized that if I just `.join(u)` with the empty string, I can reverse it with `f()` at the same time as flipping the brackets [Try it online!](https://tio.run/##ZVHBitswEL37K6aCwGiTGkJ7WFR06KG97aXsTRVFiSXq4tjGksCL8LenGiUOZlfYMu/NzJvnmfEt/B36L8/jdA3WBw8SUgX5MGSCIWeHG1KoM1bI9cokhWlBjkqptGituU5KL0vO@hBZQ6uWUrqo0XejpzQqRM5TqcutlvwUvY8RTaF7JaZEXlNalodf/s69SnoVQ9IgUC1XJztzOTUGvPBKiM9HXYfJ9L4zwSIDDYrjAok9Hb/yqrEOLmi4qOApHk6SkbwbJpih7cFkGlpXAMs9mIh7OWfOdpmNYPoG5k/S4ZuQsR6HMf@POO2J4N@y3h8Zc/Kp1Ew2xKnPwCFj9b@h7TFyXr2sbo1weEF6Dc/n2spj5eP5bD0t8HWKtiJftFGyVjYryihm@YIEeUHj1PYB2Svl7VoBj7Pzv/sf82jPwTbZjY9dEIX8fg7RdPDrTlEmgx22BxItl1d068PMbz3afTb3vtndbM3KxKTcFOZ5eQu3NGfazjY1uys5GuAmVaw68qfJRdWmg3/UUlk/PFpu5D2Mxvuif/0P) ### Explanation and ungolfed code: This answer takes my answer to the other problem, which loops through a string and adds a missing closing bracket to properly match an unclosed opening bracket, adapts it slightly to ensure it works for multiple unclosed brackets, and then applies it to the string twice, flipping the string in-between. ``` f=lambda s:s[::-1].translate(" ] [)(} {"*14) ## lambda that flips a string, and reverses all the brackets in it def m(a): ## function that takes a string and matches every unclosed opening bracket (ignores unopened closing brackets) u=[] ## list holding all currently unclosed brackets b="" ## string that the result is build in for x in a: ## loop through the input if x in"([{": ## if its an opening bracket u+=[x] ## add it to the unclosed list elif u and x!=f(y:=u.pop()): ## if there are unclosed brackets and this bracket doesnt close the last opened one b+=f(y); ## add the necessary closing bracket u.pop() ## pop the extra opening bracket that x closes b+=x ## no matter what, add this character to the result return b+f("".join(u)) ## join the remaining unclosed brackets into a single string, flip it with f(), and add it to the result M=lambda a:f( ## Flip the final string back to the correct order m(f( ## Flip the string and apply m again to match the unopened closing brackets m(a)))) ## Apply the above function to the result to match all unclosed opening brackets ``` [Answer] # Python 2 - 198 I was hoping to get some of the comprehensions down a bit more but don't have a lot of time right now to really test different ways of doing things. ``` s="()[]{}";f=s.find def F(S): r=m="" for c in S: i=f(c)^1 if i%2:m=c+m;r+=c else: for d in m: if d==s[i]:break r+=s[f(d)^1] else:r=s[i]+r+c m=m[1:] for c in m:r+=s[f(c)^1] return r ``` The OP did not include an example like `{[([{}])]}{[` (with adjacent groups), but whether or not this functionality is required this outputs the correct `{[([{}])]}{[]}` [Answer] # Haskell, 513 The function `h`. Previous version did not give correct answers for `"({{)["` and `"({{)}}"` ``` import Control.Monad m '('=')' m '['=']' m '{'='}' m ')'='(' m ']'='[' m '}'='{' data B=B Char[B]|N[B]|Z B Char[B] instance Eq B where(==)a b=q a==q b instance Ord B where(<=)a b=q a<=q b w(B o s)=o:(s>>=w)++[m o] v(N k)=k>>=w n(B _ k)=(sum$n<$>k)+1 q(N k)=sum$n<$>k u(Z(Z g pc pk) c k)=Z g pc(pk++[B c k]) u(Z(N pk) c k)=N(pk++[B c k]) t(N k)=N k t z=t$u z f z c|elem c "([{"=[Z z c[]] f z@(Z p o k) c|m c==o=[u z]|2>1=(u$Z(Z p o [])(m c)k):f(u z)c f (N k)c=[Z(N[])(m c)k] h s=v.minimum$t<$>foldM f(N [])s ``` ]
[Question] [ You have an input array of size m\*n. Each cell in the array is populated with either P or T. The only operation you can do on the array is flip columns. When you flip a column, the letters in all the cells of that column switch (P becomes T and viceversa). If you have 'x' number of rows with same letter (e.g. PPPP) then you get a point. Design an algorithm that takes in the array and returns a solution (which columns to flip) such that the resulting array has maximum number of points possible. Note: In case there are multiple solutions that yield the highest score, choose the one with lowest number of flips. Example: Input Array: ``` PPTPP PPTPP PPTTP PPPTT PPPTT ``` Output: ``` 3 ``` Explanation: A solution that yields the highest points: Flip column no. 3 Then the original array would be: ``` PPPPP // 1 point PPPPP // 1 point PPPTP PPTTT PPTTT //Total: 2 points ``` Note that one could also flip columns 4 and 5 to get a score of two, but that needs an additional flip. You may use any convenient input format to represent the two dimensional array, and you may also any two distinct, but fixed, values to represent `P` and `T`. This is code golf, so the shortest answer (in bytes) wins. [Answer] # APL, 37 ``` {x/1+⍳⍴x←y[↑⍋(+/∘.≠⍨2⊥⍉y),¨+/y←⍵⍪~⍵]} ``` Example: ``` {x/1+⍳⍴x←y[↑⍋(+/∘.≠⍨2⊥⍉y),¨+/y←⍵⍪~⍵]} 5 5⍴0 0 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 1 1 ``` [Tested here.](http://ngn.github.io/apl/web/#code=%7Bx/1+%u2373%u2374x%u2190y%5B%u2191%u234B%28+/%u2218.%u2260%u23682%u22A5%u2349y%29%2C%A8+/y%u2190%u2375%u236A%7E%u2375%5D%7D%205%205%u23740%200%201%200%200%200%200%201%200%200%200%200%201%201%200%200%200%200%201%201%200%200%200%201%201) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 ``` f@eo+/QN/Qm!dN_osZ^U2lhQTUhQ ``` Takes input in the form of a nested list, e.g. ``` [[0,0,1,0,0],[0,0,1,0,0],[0,0,1,1,0],[0,0,0,1,1],[0,0,0,1,1]] ``` Gives output 0-indexed, e.g. ``` [2] ``` `^U2lhQ`: Generates all possible lists of 0s and 1s of the right length. `_osZ`: Orders these lists from most 1s to least. `+/QN/Qm!dN`: Counts how many times each list (`N`) and its inverse, 0s and 1s swapped (`m!dN`) occur in the input. The former corresponds to a series of flips leaving all zeros, the latter to leaving all ones. `eo`: Orders the list by the above key, and takes its last element, which will be the result with the most matching columns, and among them the one with the least ones. `f@ ... TUhQ`: Converts this list of 1s and 0s to a list of indices to be flipped. For 1-indexing, change the `d` to a `k`, then put `mhd` at the beginning. [Answer] # CJam, ~~53~~ 51 bytes ``` l~z:X,,La\{1$f++}/{,}${X\{_X=:!t}/z{_&,(},,}$0=:)S* ``` This reads a two-dimensional array of 0s and 1s from STDIN. E.g. the example in the question would be ``` [[0 0 1 0 0] [0 0 1 0 0] [0 0 1 1 0] [0 0 0 1 1] [0 0 0 1 1]] ``` [Test it here.](http://cjam.aditsu.net/) This first gets all possible subsets of columns, in order of increasing length, then performs the flips for each subsets and sorts them by how many rows still have both 0s and 1s in them. Finally, we just return the first such subset. This relies on the sorting being stable, such that the initial order of increasing length takes care of the tie-breaker. [Answer] # Haskell, 98 ``` g s=snd$maximum[((sum[1|o<-s,o==r||o==map(1-)r],-sum r),[i|(i,1)<-zip[1..]r])|r<-s++map(map(1-))s] ``` input format is a list of list of ints. you can use a string version for testing: ``` gg = g . map (map (\c -> case c of 'T' -> 0 ; _ -> 1) ) . lines ``` oh no the spaces! it hurts! this works by iterating over the rows and calculating the number of points we will get if we flipped the columns in a way that this row gains us a point. first thing to notice is that flipping the row to either all `True` or all `False` doesn't matter, because the grids will be exactly the inverse of each other and thus will have the exact same score. the way we calculate the count when a given row gains a point is so: we iterate over the rows again, and sum the points each row gives us, using the fact that they do exactly when the rows are either identical or the exact inverse. for example, if the row we are flipping is `TPPTP` and the current row we are iterating over is `PTTPT` or `TPPTP` then the row gains us a point, but when it's any other row, it doesn't gain us any points. [Answer] # CJam, 37 ``` q~_{:!}%+:T{T1$a-,\0-+}$0={U):U*}%0-` ``` Input format: ``` [[0 0 1 0 0] [0 0 1 0 0] [0 0 1 1 0] [0 0 0 1 1] [0 0 0 1 1]] ``` [Answer] # Mathematica - 76 ``` { {P, P, T, P, P}, {P, P, T, P, P}, {P, P, T, T, P}, {P, P, P, T, T}, {P, P, P, T, T} }/.{P -> 1, T -> 0}; First@MaximalBy[ Subsets@Range@Length[%], MapAt[1-#&,%,{All,#}]~Count~{1..}& ] ``` [Answer] ## Python 2, 234 ``` from itertools import * A=input() n=len(A[0]) R=range(n) S=(0,) for p in[q for i in R[:-1] for q in combinations(R,i)]: s=[sum([(l[q]+(q in p))%2 for q in R])for l in A] m=s.count(n)+s.count(0) if m>S[0]:S=(m,p) print S[1] ``` Input is a list of lists: ``` [[0,0,1,0,0],[0,0,1,0,0],[0,0,1,1,0],[0,0,0,1,1],[0,0,0,1,1]] ``` Output is a tuple of flips using python indexing from 0: ``` (2,) ``` If the output must be indexed from 1, then the code is 272 characters with 0 denoting no flips: ``` print 0 if len(S[1])==0 else [p+1 for p in S[1]] ``` ]
[Question] [ **This question already has answers here**: [Fix the Braces, etc](/questions/50873/fix-the-braces-etc) (3 answers) Closed 7 years ago. Consider the alphabet **A** =`"()[]{}<>"`. Think of the characters in the alphabet as opening and closing brackets of 4 different types. Let's say that a string over the alphabet **A** is balanced if * it is empty *-or-* * it is not empty *-and-* the number of opening and closing brackets of each type match *-and-* each opening bracket has a corresponding closing bracket of the same type to the right of it *-and-* the substring between each pair of corresponding brackets is balanced. For example, the strings `""`, `"()"`, `"<[]>"`, `"{}{}[[]]"` are balanced, but the strings `"("`, `"{>"`, `")("`, `"<>>"`, `"[(])"` are not balanced. *Task:* Given a (possibly unbalanced) input string **S** over the alphabet **A**, find all possible ways to insert minimal number of brackets to make the string balanced. More precisely, *Input:* any string **S** over the alphabet **A**. *Output:* all possible balanced strings of the shortest length over the same alphabet containing **S** as a [subsequence](http://en.wikipedia.org/wiki/Subsequence). Some examples (a string to the left of an arrow denotes an input, the list of strings to the right of the arrow denotes the corresponding output): * `""` → `""` * `"()[]"` → `"()[]"` * `"["` → `"[]"` * `">"` → `"<>"` * `"{}]"` → `"[{}]", "{}[]"` * `"<<"` → `"<><>", "<<>>"` Note that: * The output always contains at least one string. * The output contains only those types of brackets that occur in the input string. * All strings in the output are of the same length. * If an input string is balanced, then the output consists of the same single string. *Implementation requirements:* * Your implementation may be in any programming language and should be as short as possible (in terms of character count or byte count - which one is less). You may represent the source in ASCII, Unicode or any other alphabet normally used in your language. If a program in your language has a shorter standard encoding as a sequence of bytes (like x86 assembly), you may choose to claim its length based on byte count, although you may submit the program in a hexadecimal form (e.g. `7E-FF-02-...`) and/or a textual form using standard mnemonics. If browsers cannot represent characters that you used in the program, you may submit a graphical image of the source and/or a sequence of keystrokes that can be used to type it, but still may claim its length based on character count. * Any required whitespace or newline characters are included in the character count. If you want, you may submit both an "official", shortest version that is used to claim the length and a "non-official", human-readable version with additional spaces, newlines, formatting, comments, parentheses, meaningful identifier names, etc. * The implementation may be a complete program/script, a function (along with any helper functions or definitions, if needed), a functional expression (e.g. lambda, anonymous function, code block, several built-in functions combined with a function composition operator, etc) or any similar construct available in your language. * You may use any standard library functions that normally available in your language, but any required `import`, `using`, `open` or other similar constructs or fully qualified names must be included in the source unless your language imports them by default. * The program may **not** communicate with any Internet services to obtain the result, intermediate data, or to download some parts of the algorithm. * If your language supports some form of compressed expressions (like [`Uncompress["..."]`](http://reference.wolfram.com/mathematica/ref/Uncompress.html) in *Mathematica*) you may use them to make the program shorter. * If your language does not support strings or you do not want to use them, you may use character or integer arrays (or other collections) instead. If your language does not support integers (e.g. lambda-calculus), you may use a suitable encoding for them (like [Church numerals](http://en.wikipedia.org/wiki/Church_encoding#Church_numerals)). * For input and output you may use whatever mechanism you prefer: standard input/output streams, user prompt, console output, function parameters and return value, Turing machine tape, reading/writing memory blocks, etc. * You may assume that an input is well-formed (e.g. that it does not include any characters except `()[]{}<>`) and do not need to validate it. The program behavior may be undefined if the input is not well-formed. * The output strings may be printed delimited by commas, semicolons, spaces, newlines or other delimiters normally used in your language, with or without surrounding quotation marks, or returned as an array, list, sequence, a single delimited string or any other suitable collection. * The output strings may be returned in any order, but must not contain duplicates. * The program execution time must be polynomial with respect to the length of its **output**. [Answer] # Tcl, 212 characters. ``` eval [zlib i [encoding convertt unicode 兕櫭ッﰌꞟ膸줙ꎠ?곚ၻ菇몐䞝Ӫ᷇ꌃ齷靤녂閉璓陷ョ䎅汚组䕿䎢犄ﲕⷑ稑䞙⠧赧용㽫硣ꖠᓋ蘊湏뢈鱰蒺䡎ྚ嬣᪢꼍ⴚ벎艚㶼큔㱅麓傧ᶘ쳖岠ꇻ퇇䯺蛼෪ᾜ❂᠗移ﺶ䱔엻똆诖ꙧꈦ屪蘦㝖ᝎﴝ䏐駺鞜䓲䣎娯෺顡瑼曾⛁⩤暪鬙쩘覥喼\ud88eႂ嬲꫺\udfdf쒚쾟⒆鱔壌杗殰킞茶嵊䴪ꥁ⽠濶켖덼㘕拘⛇끓ᛱ㐼\ud927碀꣟禝悕衫瀇辸幇鬫瞽\udf90䵸㿕]] ``` You count characters, so I use 1 character for 2 bytes. (Except the invalid characters, that I replaced now) The zlib is pretty self explanatory. `i` is just the the abbreviation of `inflate`. `eval`. Well. I don't have to explain that? After decoding it becomes ``` proc v i {set ::m {};t $i set r [list [split $i {}]] lmap c [split $::m {}] {set c [dict get {\{ \} \} \{ {[} \] \] {[} ( ) ) ( < > > <} $c] lmap a $r[set r {}] {for {set i 0} \$i<=[llength $a] incr\ i {lappend r [linsert $a $i $c]}}} lsort -u [lmap a [lmap a $r {join $a {}}] {if {![t $a]} continue set\ a}] } proc t i {if {{}ne$i} {lmap r {{^(.*){(.*?)}(.*)$} {^(.*)\((.*?)\)(.*)$} {^(.*)<(.*?)>(.*)$} {^(.*)\[(.*?)\](.*)$}} {if {[regexp $r $i - 1 2 3]} {return [expr {[t $1$3]&[t $2]}]}};append ::m $i} {return 1};list 0} ``` Which will be passed to `eval`. It defines 2 commands: `v`, the main program, and `t` which checks the input and place unmatched braces in the global variable `m`. `v` calls `t` with the input, insert the corresponding brace at all possible positions and use `t` again to filter the valid ones out. **Input**: 1. Parameter for `v` **Output**: A Tcl list with each possible valid permutation. They have all the same length. Example: ``` % v << <<>> <><> ``` ]
[Question] [ As an exercise, I've created a simple solution for [this](https://codegolf.stackexchange.com/questions/15882/generate-alphabet-with-4-copies-of-each-letter) challenge, in x86 Assembly Language. I'm running this with FASM on Windows. Here's my source code: ``` format PE console entry start include 'WIN32A.inc' section '.text' code executable start: push char ; Start at 'A' call [printf] ; Print the current letter 4 times call [printf] call [printf] call [printf] inc [char] ; Increment the letter cmp [char], 'Z' ; Compare to 'Z' jle start ; char <= 'Z' --> goto start section 'r.data' data readable writeable char db 'A', 10, 0 ; Stores the current letter section '.idata' data readable import library msvcrt, 'msvcrt.dll' import msvcrt, printf, 'printf' ``` When I compile this, I get an executable larger than I expected. Here's a hexdump: <https://pastebin.com/W5sUTvTe> I notice there's a lot of empty space between the code section and the data and library import sections, as well as a message saying "This program cannot be run in DOS mode" embedded in the code. How can I assemble my source code to a small file, suitable for Code Golf? As a side note, suggestions for better ways to print to `stdout` without importing `msvcrt` and calling `printf` are welcome. [Answer] Quite a bit general tip, but # Use COM file format instead of PE EXE. PE EXE has a few flaws making the format pretty much useless in code-golf. First one is the image aligning (Windows won't run the EXE file if it's not aligned properly), and the second one is the header size. There are a few factors that aren't this important (dividing the executable into sections). Advantages of using COM file format (that is pretty much equivalent to flat binary) are: * Zero header code, file isn't divided into sections * No image aligning (so the image size might not be divisible by a strictly defined power of two, but it has to be smaller than 65K. It doesn't change much though, because if your submission is larger than 65K, you're doing something wrong). * You can't use external libraries - this is actually a plus, because you without doubt have other way to perform I/O. That's where [BIOS interrupts](http://www.ctyme.com/rbrown.htm) come handy. * You have direct control over the memory and devices linked up to the system, therefore there is no paging, no access violations, no memory protection, no concurrency, so on and so forth. These *features* make it easier to golf really creative programs. I've revised your code to work as flat binary. It's dead simple: ``` ORG 100H MOV DX, P MOV AH, 9 L: INT 21H INT 21H INT 21H INT 21H INC BYTE [P] CMP BYTE [P], 'Z' JLE L MOV AX, 4C00h INT 21h P DB "A", 10, "$" ``` The output binary is just 32 bytes big. I believe, it's possible to reduce the size even further, but this is just a starting point. Assemble with `nasm -fbin file.asm -o file.com`. Note, this example has been made for NASM, but you can translate it freely to FASM, and it will work flawlessly. ]
[Question] [ You are the best and most famous hero of the area. Lately there have been rumors that a [Hydra](https://en.wikipedia.org/wiki/Lernaean_Hydra) has been hanging out in a nearby ravine. Being the brave and virtuous hero that you are you figure you'll go check it out sometime later today. The problem with hydrae is that every time you try to cut off their heads some new ones grow back. Luckily for you you have swords that can cut off multiple heads at once. But there's a catch, if the hydra has less heads than your sword cuts, you wont be able to attack the hydra. When the hydra has exactly zero heads, you have killed it. There is also a special sword called ***The Bisector*** that will cut off half of the Hydra's heads, but only if the number of heads is even. The Bisector *cannot be used at all* when the number of heads is odd. This is different from cutting off zero heads. So you have decided you will write a computer program to figure out the best way to slay the hydra. ## Task You will be given as input * the number of heads the Hydra starts with * the number of heads the Hydra regrows each turn * a list of swords available for use each (each either is a bisector or cuts a fixed number of heads each turn) You should output a list of moves that will kill the hydra in the least number of turns possible. If there is no way to kill the hydra you must output some other value indicating so (and empty list is fine if your language is strongly typed). If there are multiple optimal ways to kill the hydra you may output any one of them or all of them. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better. ## Test Cases *More available upon request* ``` 5 heads, 9 each turn, [-1,-2,-5] -> [-5] 12 heads, 1 each turn, [/2,-1] -> No solution 8 heads, 2 each turn, [-9, -1] -> [-1,-9] 3 heads, 23 each turn, [/2,-1,-26] -> [-1,-1,-26,-26,-26,-26,-26,-26,-26,-26] 16 heads, 1 each turn, [/2, 4, 2] -> [/2,-4,/2,-4] ``` > > This question is a simplified version of the main mechanic of [HydraSlayer](http://www.roguetemple.com/z/hydra/). If you like this type of puzzle I recommend checking it out, its pretty fun. I do not have any affiliation with the game. > > > [Answer] # JavaScript, ~~230~~ 223 bytes ``` f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]} ``` ``` _=_=>f=(h,t,s)=>{m=h-Math.min(...s),d=1,q=[],s.map(a=>q.push([],h));while(q.length){p=q.shift(),h=q.shift(),s.map(w=>!(a=w?h+w:h/2)?d=w:!(a%1)&a>0&a<m&!f[a+=t]?f[q.push([...p,w],a),a]=1:0);d<1?(q=[],p).push(d):0}return d<1?p:[]} console.log(`[${_()(5, 9, [-1,-2,-5])}]`); console.log(`[${_()(12, 1, [0,-1])}]`); console.log(`[${_()(8, 2, [-9,-1])}]`); console.log(`[${_()(1, 2, [0,-4])}]`); console.log(`[${_()(3, 2, [0,-4,-1])}]`); console.log(`[${_()(3, 4, [0,-4,-1])}]`); console.log(`[${_()(3, 23, [0,-1,-26])}]`); console.log(`[${_()(16, 1, [0,-4,-2])}]`); ``` **Ungolfed version:** ``` f=(heads,turn,swords)=>{ max=heads-Math.min(...swords); found=1; flags=[]; queue=[]; swords.map(a=>queue.push([],heads)); while(queue.length){ path=queue.shift(); heads=queue.shift(); swords.map(sword=>{ after=sword?heads+sword:heads/2; if(!after){ found=sword; }else if(!(after%1)&after>0&after<max&!flags[after+=turn]){ flags[after]=1; queue.push([...path,sword],after); } }); if(found<1){ path.push(found); break; } } return found<1?path:[]; } ``` The bisector is represented as `0`. [Answer] # Python3, 197 bytes: ``` def f(h,H,s): q=[(h,[])] while q: h,m=q.pop(0) if 0==h:return m if m:h+=H for S in s: if((S==0.5 and 0==h%2)or(S!=0.5 and h>=abs(S)))and(h,S)not in m:q+=[([h/2,h+S][S!=0.5],m+[(h,S)])] ``` [Try it online!](https://tio.run/##VY5La8MwEITv/hXbQ0HCq9SPOiQG9Zy7jkKHlFjIUD0su4T8eneT0LQ5CHbm0wyTLouLod2lvK6nwYJlDg84876ASWoS2nBTwNmNXwNM5IJDL6dNiolVnORooZLS9XlYvnMAf7d870p5oNvGDArGAPM1S4gxJWW16eAYTrfka8NjZurlYboPefycmeKck6QJioe4XDt8P5U0Sru3Bl2pjL6nDPpS3/7R1jXlMSzMsg73qEWNokHRGc6LX1A3CDWCpiSK@j/ZIRDTYo/wDFoC7SNCldunwu1fIYh3eg3h9Qc) ]
[Question] [ Draw a simple ASCII art image containing a straight line. It's similar to [this](https://codegolf.stackexchange.com/questions/1262/ascii-art-bresenham-line-drawing) and [this](https://codegolf.stackexchange.com/questions/114980/straight-line-to-text) but with different specifications. **Input** You can modify this input format to suit your code. * integer `width` * integer `height` * integer `x0` * integer `y0` * integer `x1` * integer `y1` **Output** A filled ASCII art image of the specified width and height containing a line from pixel `(x0, y0)` to pixel `(x1, y1)`. Any standard form of text output is acceptable, but don't use built in line drawing functions. **Details** The line must be drawn using a single printable character (such as `#`), while the background is filled with a different character (such as `.`). You must print the necessary trailing characters so that the image size is correct. Pixel coordinates can be 0-indexed or 1-indexed and can start in any corner of the image. The line should be drawn by imagining a 0-width sub-pixel line connecting the centers of the start and end pixels. Every pixel that the line enters should be filled in. **Winning** Usual code-golf rules. Shortest code wins. **Examples** ``` IN: width, height, x0, y0, x1, y1 IN: 7, 6, 0, 0, 6, 5 OUT: .....## ....##. ...##.. ..##... .##.... ##..... IN: 3, 3, 1, 1, 1, 1 OUT: ... .#. ... IN: 3, 3, 0, 2, 2, 0 OUT: #.. .#. ..# IN: 6, 3, 0, 0, 5, 2 OUT: ....## .####. ##.... IN: 4, 4, -1, -1, 0, 3 OUT: #... #... #... .... ``` [Answer] ## Mathematica, ~~166~~ 137 bytes ``` l:={i,j};s=Sign;f[p_,q_,h_,w_]:=Grid@Table[(1-Max[s[p-l]s[q-l],0])Boole[Abs@Mean[s@Det@{p-l+#,p-q}&/@Tuples[.5{1,-1},2]]<.6],{i,h},{j,w}] ``` More readable version: ``` l := {i, j}; s = Sign; f[p_, q_, h_, w_] := Grid@Table[(1 - Max[s[p - l] s[q - l], 0]) Boole[ Abs@Mean[ s@Det@{p - l + #, p - q} & /@ Tuples[.5 {1, -1}, 2]] < .6], {i, h}, {j, w}] ``` This defines a function called `f`. I interpreted the input and output specifications fairly liberally. The function `f` takes input in the format `f[{x0, y0}, {x1, y1}, height, width]`, and the grid is 1-indexed, starting in the top left. Outputs look like [![A sample output](https://i.stack.imgur.com/L1zcW.jpg)](https://i.stack.imgur.com/L1zcW.jpg) with the line displayed as `1`s and the background as `0`s (shown here for `f[{2, 6}, {4, 2}, 5, 7]`). The task of turning a Mathematica matrix of `1`s and `0`s into a string of `#`s and `.`s has been golfed in many other challenges before, so I could just use a standard method, but I don't think that adds anything interesting. ### Explanation: The general idea is that if the line passes through some pixel, then at least one of the four corners of the pixel is above the line, and at least one is below. We check if a corner is above or below the line by examining the angle between the vectors (`{x0,y0}` to corner) and (`{x0,y0}` to `{x1,y1}`): if this angle is positive, the corner is above, and if the angle is negative, the corner is below. If we have two vectors `{a1,b1}` and `{a2,b2}`, we can check if the angle between them is positive or negative by finding the sign of the determinant of the matrix `{{a1,b1},{a2,b2}}`. (My old method of doing this used arithmetic of complex numbers, which was way too…well, complex.) The way this works in the code is as follows: * `{p-l+#,p-q}&/@Tuples[.5{1,-1},2]` gets the four vectors from `{x0,y0}` and the four corners of the pixel (with `l:={i,j}`, the coordinates of the pixel, defined earlier), and also the vector between `{x0,y0}` and `{x1,y1}`. * `s@Det@...` finds the signs of the angles between the line and the four corners (using `s=Sign`). These will equal -1, 0 or 1. * `Abs@Mean[...]<.6` checks that some of the angles are positive and some negative. The 4-tuples of signs that have this property all have means between -0.5 and 0.5 (inclusive), so we compare to 0.6 to save a byte by using `<` instead of `<=`. There's still a problem: this code assumes that the line extends forever in both directions. We therefore need to crop the line by multiplying by `1-Max[s[p-l]s[q-l],0]` (found by trial and error), which is `1` inside the rectangle defined by the endpoints of the line, and `0` outside it. [![Cropping a line by a rectangle](https://i.stack.imgur.com/mHlaW.png)](https://i.stack.imgur.com/mHlaW.png) The rest of the code makes a grid of these pixels. (As a bonus, here's an earlier attempt with a completely different method, for 181 bytes:) ``` Quiet@Grid@Table[(1-Max[Sign[{i,j}-#3]Sign[{i,j}-#4],0])Boole[#3==#4=={i,j}||2Abs@Tr[Cross@@Thread@{{i,j},#3,#4}]/Norm[d=#3-#4]<2^.5Cos@Abs[Pi/4-Mod[ArcTan@@d,Pi/2]]],{i,#},{j,#2}]& ``` [Answer] # CJam, 122 bytes ``` {),V>{[I\]E.*A.+}/}:F;l~]2/~@:S~'.*f*\@:A.-_:g:E;:z:D[0=:B{D~I2*)*+:U(2/B/FU2/B/:V;}fID~\:I;F]{_Wf>\S.<+:*},{~_3$=@0tt}/N* ``` [Try it online](http://cjam.aditsu.net/#code=%7B)%2CV%3E%7B%5BI%5C%5DE.*A.%2B%7D%2F%7D%3AF%3Bl~%5D2%2F~%40%3AS~'.*f*%5C%40%3AA.-_%3Ag%3AE%3B%3Az%3AD%5B0%3D%3AB%7BD~I2*)*%2B%3AU(2%2FB%2FFU2%2FB%2F%3AV%3B%7DfID~%5C%3AI%3BF%5D%7B_Wf%3E%5CS.%3C%2B%3A*%7D%2C%7B~_3%24%3D%400tt%7D%2FN*&input=6%203%200%200%205%202) This basically combines [two](https://codegolf.stackexchange.com/a/60627/7416) [answers](https://codegolf.stackexchange.com/a/80354/7416) I previously wrote for other challenges (mainly the calculations from the 2nd one - function `l`). (0, 0) is naturally the top left corner, not bottom left like the examples in the statement. **Overview:** `{),V>{[I\]E.*A.+}/}:F;` defines function F which helps generate all the pixels (coordinate pairs) for a given x coordinate `l~]2/~@:S~'.*f*\@:A.-_:g:E;:z:D` reads and processes the input, and creates a matrix of dots `0=:B{D~I2*)*+:U(2/B/FU2/B/:V;}fI` iterates over all x coordinates except the last one, and generates all the corresponding pixels `D~\:I;F` does the same for the last x coordinate `{_Wf>\S.<+:*},` keeps only the pixels that should appear inside the image `{~_3$=@0tt}/` puts a 0 in the matrix for each pixel `N*` joins the matrix with newline characters for display ]
[Question] [ > > ~~This challenge carries a [bounty of 200 points](https://codegolf.meta.stackexchange.com/a/12124/8927) for the first to answer and remain unbeaten for at least 3 days.~~ Claimed by [user3080953](https://codegolf.stackexchange.com/a/117124/8927). > > > There's a lot of talk lately about end-to-end encryption, and pressure on companies to remove it from their products. I'm not interested in the rights-and-wrongs of that, but I wondered: how short can code be that would get a company pressured into not using it? The challenge here is to implement a [Diffie Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange) between two networked systems, then allow the users to communicate back-and-forth using the generated symmetric key. For the purpose of this task, no other protections are required (e.g. no need to cycle the key, verify identities, protect against DoS, etc.) and you can assume an open internet (any ports you listen on are available to everyone). Use of builtins is allowed *and encouraged!* You may choose one of two models: * A server and a client: the client connects to the server, then server or client can send messages to the other. Third-parties in between the two must be unable to read the messages. An example flow could be: 1. User A launches server 2. User B launches client and directs it to user A's server (e.g. via IP/port), the program opens a connection 3. User A's program acknowledges the connection (optionally asking the user for consent first) 4. User B's program begins generation of a DH secret, and sends the required data (public key, prime, generator, anything else your implementation needs) to User A 5. User A's program uses the sent data to complete generation of the shared secret and sends back the required data (public key) to User B. From this point, User A can enter messages (e.g. via stdin) which will be encrypted and sent to User B (e.g. to stdout). 6. User B's program completes generation of the shared secret. From this point, User B can send messages to User A. * Or: A server with two clients connected to it: each client talks to the server, which forwards their message to the other client. The server itself (and any third-parties in between) must be unable to read the messages. Other than the initial connection, the process is the same as that described in the first option. ### Detailed rules: * You can provide a single program, or multiple programs (e.g. server & client). Your score is the total code size across all programs. * Your program must be theoretically capable of communicating over a network (but for testing, localhost is fine). If your language of choice doesn't support networking, you can combine it with something that does (e.g. a shell script); in this case your score is the total code size across all languages used. * The Diffie Hellman key generation can use hard-coded "p" and "g" values. * The generated shared key must be at least 1024 bits. * Once the key is shared, the choice of symmetric-key encryption is up to you, but you must not pick a method which is currently known to have a practical attack against it (e.g. a caesar shift is trivial to reverse without knowledge of the key). Example permitted algorithms: + AES (any key size) + RC4 (theoretically broken, but no practical attacks that I can find mention of, so it's allowable here) * Users A and B must both be able to send messages to each other (two-way communication) interactively (e.g. reading lines from stdin, continually prompting, or events such as pressing a button). If it makes it easier, you may assume an alternating conversation (i.e. after a user sends a message, they must wait for a response before sending their next message) * Language builtins **are** permitted (no need to write your own cryptographic or networking methods if they're already supported). * The underlying communication format is up to you. * The communication steps given above are an example, but you are not required to follow them (as long as the necessary information is shared, and no middle-men are able to calculate the shared key or messages) * If the details needed to connect to your server are not known in advance (e.g. if it listens on a random port), these details must be printed. You can assume that the IP address of the machine is known. * Error handling (e.g. invalid addresses, lost connections, etc.) is not required. * The challenge is code golf, so the shortest code in bytes wins. [Answer] # Node.js (372 423+94=517 513 bytes) ## Golfed Linebreaks added for "readability". ### chat.js (423 419 bytes) No line breaks ``` [n,c,p]=["net","crypto","process"].map(require);r="rc4",a="create",h="DiffieHellman",z="pipe",w="write",o=128,g=p.argv;s=e=d=0,y=c[a+h](8*o),k=y.generateKeys();v=n.connect(9,g[2],_=>{g[3]&&(v[w](y.getPrime()),v[w](k));v.on("data",b=>{s||(g[3]||(y=c[a+h](b.slice(0,o)),k=y.generateKeys(),v[w](k),b=b.slice(o)),s=y.computeSecret(b),e=c[a+"Cipher"](r,s),p.stdin[z](e)[z](v),d=c[a+"Decipher"](r,s),v[z](d)[z](p.stdout))})}) ``` Line breaks ``` [n,c,p]=["net","crypto","process"].map(require); r="rc4",a="create",h="DiffieHellman",z="pipe",w="write",o=128,g=p.argv; s=e=d=0,y=c[a+h](8*o),k=y.generateKeys(); v=n.connect(9,g[2],_=>{g[3]&&(v[w](y.getPrime()),v[w](k)); v.on("data",b=>{s||(g[3]||(y=c[a+h](b.slice(0,o)),k=y.generateKeys(), v[w](k),b=b.slice(o)),s=y.computeSecret(b),e=c[a+"Cipher"](r,s),p.stdin[z](e)[z](v) ,d=c[a+"Decipher"](r,s),v[z](d)[z](p.stdout))})}) ``` ### echo\_server.js (94 bytes) ``` c=[],require("net").createServer(a=>{c.forEach(b=>{a.pipe(b),b.pipe(a)});c.push(a)}).listen(9); ``` ## Ungolfed Node has built-in networking and crypto capabilities. This uses TCP for networking (because it's simpler than Node's interface for HTTP, and it plays nicely with streams). I use a stream cipher (RC4) instead of AES to avoid having to deal with block sizes. Wikipedia seems to think it can be vulnerable, so if anyone has any insights into which ciphers are preferred, that would be great. Run the echo server `node echo_server.js` which will listen on port 9. Run two instances of this program with `node chat.js <server IP>` and `node chat.js <server IP> 1` (the last argument just sets which one sends a prime). Each instance connects to the echo server. The first message handles the key generation, and subsequent messages use the stream cipher. The echo server just sends everything back to all the connected clients except the original. ### Client ``` var net = require('net'); var crypto = require('crypto'); var process = require('process'); let [serverIP, first] = process.argv.slice(2); var keys = crypto.createDiffieHellman(1024); // DH key exchange var prime = keys.getPrime(); var k = keys.generateKeys(); var secret; var cipher; // symmetric cipher var decipher; // broadcast prime server = net.connect(9, serverIP, () => { console.log('connect') if(first) { server.write(prime); console.log('prime length', prime.length) server.write(k); } server.on('data', x => { if(!secret) { // if we still need to get the ciphers if(!first) { // generate a key with the received prime keys = crypto.createDiffieHellman(x.slice(0,128)); // separate prime and key k = keys.generateKeys(); server.write(k); x = x.slice(128) } // generate the secret console.log('length x', x.length); secret = keys.computeSecret(x); console.log('secret', secret, secret.length) // verify that secret key is the same cipher = crypto.createCipher('rc4', secret); process.stdin.pipe(cipher).pipe(server); decipher = crypto.createDecipher('rc4', secret); server.pipe(decipher).pipe(process.stdout); } else { console.log('sent text ', x.toString()) // verify that text is sent encrypted } }); }) ``` ### Echo server ``` var net = require('net'); clients = []; net.createServer(socket => { clients.forEach(c=>{socket.pipe(c); c.pipe(socket)}); clients.push(socket); }).listen(9) ``` Thanks Dave for all the tips + feedback! [Answer] # Node.js, ~~638~~ 607 bytes Now that it's been well and truly beaten (and in the same language), here's my test answer: ``` R=require,P=process,s=R('net'),y=R('crypto'),w=0,C='create',W='write',D='data',B='hex',G=_=>a.generateKeys(B),Y=(t,m,g,f)=>g((c=y[C+t+'ipher']('aes192',w,k='')).on('readable',_=>k+=(c.read()||'').toString(m)).on('end',_=>f(k)))+c.end(),F=C+'DiffieHellman',X=s=>s.on(D,x=>(x+'').split(B).map(p=>p&&(w?Y('Dec','utf8',c=>c[W](p,B),console.log):P.stdin.on(D,m=>Y('C',B,c=>c[W](m),r=>s[W](r+B)),([p,q,r]=p.split(D),r&&s[W](G(a=y[F](q,B,r,B))),w=a.computeSecret(p,B))))));(R=P.argv)[3]?X(s.Socket()).connect(R[3],R[2]):s[C+'Server'](s=>X(s,a=y[F](2<<9))[W](G()+D+a.getPrime(B)+D+a.getGenerator(B)+B)).listen(R[2]) ``` Or with wrapping: ``` R=require,P=process,s=R('net'),y=R('crypto'),w=0,C='create',W='write',D='data',B ='hex',G=_=>a.generateKeys(B),Y=(t,m,g,f)=>g((c=y[C+t+'ipher']('aes192',w,k='')) .on('readable',_=>k+=(c.read()||'').toString(m)).on('end',_=>f(k)))+c.end(),F=C+ 'DiffieHellman',X=s=>s.on(D,x=>(x+'').split(B).map(p=>p&&(w?Y('Dec','utf8',c=>c[ W](p,B),console.log):P.stdin.on(D,m=>Y('C',B,c=>c[W](m),r=>s[W](r+B)),([p,q,r]=p .split(D),r&&s[W](G(a=y[F](q,B,r,B))),w=a.computeSecret(p,B))))));(R=P.argv)[3]? X(s.Socket()).connect(R[3],R[2]):s[C+'Server'](s=>X(s,a=y[F](2<<9))[W](G()+D+a. getPrime(B)+D+a.getGenerator(B)+B)).listen(R[2]) ``` ### Usage This is a server/client implementation; one instantiation will be the server, and the other the client. The server is launched with a specific port, then the client is pointed to the server's port. DH can take a few seconds to set-up if your machine is low on entropy, so the first messages may be delayed a little. ``` MACHINE 1 MACHINE 2 $ node e2e.js <port> : : $ node e2e.js <address> <port> $ hello : : : hello : $ hi : hi : ``` ### Breakdown ``` s=require('net'), y=require('crypto'), w=0, // Shared secret starts unknown Y=(t,m,g,f)=>g( // Helper for encryption & decryption (c=y['create'+t+'ipher']('aes192',w,k='')) .on('readable',_=>k+=(c.read()||'').toString(m)) .on('end',_=>f(k)))+c.end(); X=s=>s.on('data',x=>(x+'').split('TOKEN2').map(p=> p&&(w // Have we completed handshake? ?Y('Dec','utf8',c=>c.write(p,'hex'),console.log) // Decrypt + print messages : // Haven't completed handshake: process.stdin.on('data',m=> // Prepare to encrypt + send input Y('C','hex',c=>c.write(m),r=>s.write(r+'TOKEN2')),( [p,q,r]=p.split('TOKEN1'), // Split up DH data sent to us r&& // Given DH details? (client) s.write( (a=y.createDiffieHellman( // Compute key pair... q,'hex',r,'hex') // ...using the received params ).generateKeys('hex')), // And send the public key w=a.computeSecret(p,'hex') // Compute shared secret //,console.log(w.toString('hex')) // Print if you want to verify no MITM ))))), (R=process.argv)[3] // Are we running as a client? ?X(s.Socket()).connect(R[3],R[2]) // Connect & start chat :s.createServer(s=> // Start server. On connection: X(s, // Start chat, a=y.createDiffieHellman(1024)) // Calc DiffieHellman, .write( // Send public key & public DH details a.generateKeys('hex')+'TOKEN1'+ a.getPrime('hex')+'TOKEN1'+ a.getGenerator('hex')+'TOKEN2') ).listen(R[2]) // Listen on requested port ``` The only requirement for the tokens is that they contain at least one non-hex character, so in the minified code other string constants are used (`data` and `hex`). ]
[Question] [ Your goal is to write some code that will output the shortest unique decimal sequence for the input fraction. No two fractions with the same denominator may have the same output, although it's possible for fractions with different denominators to have the same representation. Take **2 integers** as input, the first is the numerator, the second is the denominator. E.g.: ``` n d output ----- ------ 0 13: 0.00 1 13: 0.07 2 13: 0.1 3 13: 0.2 4 13: 0.30 5 13: 0.38 ``` etc. `3/13` is the only fraction with a denominator of 13 that starts with `0.2`, so no further digits are required. `4/13` and `5/13` both start with `0.3`, so another digit is required to distinguish between them. You may output numbers greater than -1 and less than 1 either with or without a zero before the decimal point, as long as the output is consistent, i.e. `0.5` and `.5` are the same number and are both valid. No other leading zeros are allowed. Trailing zeros must be shown if they are necessary to distinguish the output from another value. You may not round any numbers away from zero; they must be truncated. There must be no leading or trailing spaces. There may optionally be a single trailing newline. More test values: ``` n d output ---------- ------ 0 1: 0 (this 0 may not be removed because there's no decimal point) 5 1: 5 0 3: 0.0 (or .0) 4 3: 1.3 5 3: 1.6 10 8: 1.2 11 8: 1.3 12 8: 1.5 -496 -38: 13.05 458 -73: -6.27 70 106: 0.660 (or .660) 255 123: 2.07 256 -123: -2.081 -257 -123: 2.089 -258 123: -2.09 258 -152: -1.697 -259 152: -1.70 260 152: 1.710 272 195: 1.39 380 247: 1.538 455 -455: -1.000 -44 891: -0.049 (or -.049) 123 1234: 0.099 (or .099) ``` In each case, the output and the denominator are sufficient to uniquely work out the numerator. [Answer] # Perl, 77 bytes ``` #!perl -p $%++while/ /<grep{!index$_/$',$\=$`/$'.($`%$'?0:n).0 x$%&'?'x$%}$`-2..$`+2}{ ``` Counting the shebang as one, input is taken from stdin. **Sample Usage** ``` $ echo 0 3 | perl golf-decimals.pl 0.0 $ echo 4 3 | perl golf-decimals.pl 1.3 $ echo 11 8 | perl golf-decimals.pl 1.3 $ echo -496 -38 | perl golf-decimals.pl 13.05 $ echo 458 -73 | perl golf-decimals.pl -6.27 $ echo -44 891 | perl golf-decimals.pl -0.049 ``` [Answer] # Pyth, 37 bytes ``` AQJ+`cGHK*20\0<Jf!}<JTm<+`dKTcRH,tGhG ``` A program that takes input in the form `numerator,denominator` and prints the result. [Test suite](http://pyth.herokuapp.com/?code=p%22Input%3A+%22Qp%22Output%3A+%22+AQJ%2B%60cGHK%2a20%5C0%3CJf%21%7D%3CJTm%3C%2B%60dKTcRH%2CtGhG&test_suite=1&test_suite_input=0%2C1%0A5%2C1%0A0%2C3%0A4%2C3%0A5%2C3%0A10%2C8%0A11%2C8%0A12%2C8%0A-496%2C-38%0A458%2C-73%0A70%2C106%0A255%2C123%0A256%2C-123%0A-257%2C-123%0A-258%2C123%0A258%2C-152%0A-259%2C152%0A260%2C152%0A272%2C195%0A380%2C247%0A455%2C-455%0A-44%2C891%0A123%2C1234&debug=0) *[Explanation coming later]* [Answer] # JavaScript (ES7), ~~118~~ ~~93~~ 90 bytes ``` f=(a,b,i=0)=>(v=(p=n=>((n/b*10**i|0)/10**i).toFixed(i))(a))==p(a+1)|v==p(a-1)?f(a,b,i+1):v ``` I saved 25 bytes, thanks to @Neil. Saved additional 3 bytes by using recursion. ]
[Question] [ I don't know about you all but I'm *not* preparing for Halloween––never did never will––but, my neighbor is, so we'll help her out. She needs help figuring out which brand of candy she has, but she has so much candy she would not be able to finish before Halloween. She has: * Snickers * KitKat * Starburst * GummyBears * Twix **Input** A multiline string (or any other reasonable form) containing only letters and spaces. **Output** A falsy value if it is not a valid candy, or which candy it is if it is a candy. **How to decide which candy it is** A candy is valid if it says one of the above brands on it. However, it's not that simple, because this is a valid candy: ``` K i t K a t ``` A valid candy is one where: * the letters are in order from left to right * the letters are capitalized correctly * the letters, going from left to right, do not *both* ascend and descend * the letters with whitespace removed form one of the above brands **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in byte wins!** **Examples** Truthys: ``` 1. kers c i n S 2. Kit K a t 3. St a r b u r st 4. Bear s G ummy 5. T w i x ``` Falsys: ``` 1. SNICKERS 2. C n a d y 3. xiwT 4. S C I ss o r s 5. Kit Kat ``` [Answer] # JavaScript (ES6), ~~221~~ ~~218~~ ~~216~~ ~~212~~ ~~208~~ ~~205~~ 201 bytes ``` f=a=>(c=d=L=0,e=1,s=[],[...a].map(a=>a=='\n'?c=L=0:c++-(a!=' '&&(s[c]?e=0:(!L&&(d?d-1?e&=c>Q>d-3:d=c>Q>2:d=1),L=s[Q=c]=a)))),e&&'Snickers0KitKat0Starburst0GummyBears0Twix'.split(0).indexOf(s.join``)+1) ``` # [Try it here.](https://jsfiddle.net/Lf0xhtpx/7/) [Answer] ## Racket 446 bytes ``` (let((lr list-ref)(ls list-set)(sl string-length)(ss substring)(l(string-split s "\n")))(let loop((changed #f))(for((i(sub1(length l)))) (let*((s(lr l i))(r(lr l(add1 i)))(n(sl s))(m(sl r)))(when(> n m)(set! l(ls l i(ss s 0 m)))(set! l(ls l(add1 i) (string-append r(ss s m n))))(set! changed #t))))(if changed(loop #f)(begin(let*((l(for/list((i l))(string-trim i)))(l(string-join l)) (l(string-replace l " " "")))(ormap(λ(x)(equal? x l))cl)))))) ``` Ungolfed: ``` (define (f s cl) (let ((lr list-ref) (ls list-set) (sl string-length) (ss substring) (l (string-split s "\n"))) (let loop ((changed #f)) (for ((i (sub1 (length l)))) (let* ((s (lr l i)) (r (lr l (add1 i))) (n (sl s)) (m (sl r))) (when (> n m) (set! l (ls l i (ss s 0 m))) (set! l (ls l (add1 i)(string-append r (ss s m n)))) (set! changed #t)))) (if changed (loop #f) (begin (let* ((l (for/list ((i l)) (string-trim i))) (l (string-join l)) (l (string-replace l " " ""))) (ormap (λ(x) (equal? x l)) cl))) )))) ``` Testing: ``` (f " kers c i n S" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f " Kit K a t" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "St a r b u r st " (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f " Bear s G ummy" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "T w i x" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "SNICKERS" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f " C n y a d" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "xiwT" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "S C I ss o r s" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) (f "Kit Kat" (list "Snickers""KitKat""Starburst""GummyBears""Twix")) ``` Output: ``` #t #t #t #t #t #f #f #f #f #t ``` [Answer] ## JavaScript (ES6), 139 bytes ``` a=>/^(Snickers|KitKat|Starburst|GummyBears|Twix)$/.test(a.reduce((s,t)=>s.replace(/./g,(c,i)=>c<'!'?t[i]:t[i]<'!'?c:'!')).replace(/ /g,'')) ``` Accepts input as an array of space-padded strings. [Answer] # Pyth - 72 bytes I hope I caught all the edge cases. Will base compress candy list. ``` &sSIM_Bmxdh-d;fnd{TK.tQd}-sKdc"Snickers KitKat Starburst GummyBears Twix ``` [Test Suite](http://pyth.herokuapp.com/?code=%26sSIM_Bmxdh-d%3Bfnd%7BTK.tQd%7D-sKdc%22Snickers+KitKat+Starburst+GummyBears+Twix&test_suite=1&test_suite_input=%5B%22K+i+t%22%2C+%22+++++++K+a%22+%2C%22+++++++++++t%22%5D%0A%5B%27++++++++++++++kers%27%2C+%27+++++++++++c%27%2C+%27++++++++i%27%2C+%27+++++++n%27%2C+%27++++S++++%27%5D%0A%5B%27++Kit+K+a+t%27%5D%0A%5B%27St+a%27%2C+%27++++r+b+u%27%2C+%27+++++++++r+st+%27%5D%0A%5B%27+++++++++Bear+s%27%2C+%27G+ummy%27%5D%0A%5B%27T+w+i%27%2C+%27++++++++++++++++++++++++++x%27%5D%0A%5B%27SNICKERS%27%5D%0A%5B%27+C+++n%27%2C+%27++++++++++y%27%2C+%27+++a+++d%27%5D%0A%5B%27xiwT%27%5D%0A%5B%27S+C+I%27%2C+%27+++++++ss+o%27%2C+%27++++++++++++++r+++++++s%27%5D%0A%5B%27Kit%27%2C+%27Kat%27%5D&debug=0). [Answer] # R, 199 chars ``` function(M){if(any(outer(z<-diff(apply(M,1,function(r)which.min(r==" ")))),z<0))return(F);C=c("Twix","KitKat","Starburst","Snickers","GummyBears");C[match(paste0(gsub(" ","",c(t(M))),collapse=""),C)} ``` Input is in the form of a character matrix. `match` takes care of *which* candy it is (it checks capitalisation too). To check that the letters are an "ascending" or "descending" sequence, we just need to check that the locations of the first non-space character (if there) in each row is increasing or decreasing. To do, this we * take the first location of a nonspace character in each row, using `apply` * take the `diff`. This might have some zero in it, otherwise should either be all positive or all negative * name the `diff` `z`, and take the outer product with itself. If the diff had mixed positive and negative entries, there will be a negative entry somewhere in its outer product. If so, return FALSE. Note that cases like ``` " i " " w x" " T " ``` will return an empty character vector (in particular not "Twix"), since `match` will be trying to match "Twxi". [Answer] # Python 2.7, 254 bytes I'm sure this can be golfed more. Input is an array of lines `s`. ``` x=len p=lambda a:x(a)-x(a.lstrip()) g=sorted a=map(p,l) j=''.join z=[i.replace(' ','')for i in l] if g(a)==a:q=j(z) elif g(a)==a[::-1]:q=j(z[::-1]) else:q='' if x(set(a))<x(a):q='' print 1if q in('Snickers','KitKat','Starburst','GummyBears','Twix')else 0 ``` [Try it here!](http://ideone.com/aNChZv "Ideone link") ]
[Question] [ You have been hired as a research assistant, and asked to create a small program that will build rat mazes. The rat box is always 62x22 and has an entrance (a) and exit (A) for the rat, like this (input 1): ``` #######a###################################################### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #################################################A############ ``` Your program must fill the box with blocks (#) leaving a path for the rat, like this (output 1): ``` #######a###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ ################################################# ############ #################################################A############ ``` This is easy you think! You start writing a small program, full of confidence. However, the Principle Scientist has had a new idea -- he wants two rats to navigate the maze at the same time. Dr Rattanshnorter explains that they have different doors and different exits (input 2): ``` #b#####a###################################################### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # B # # #################################################A############ ``` The rats have been trained to move straight through cross intersections but T-intersections leave them hopelessly confused and will invalidate the experiment. You start on your new more complex task when the good Doctor explains one final requirement: the rats are savage to each other so if they see each other at any point, a rat fight will break out and you will both be before the ethics board. You now realise your program should output a maze something like this (output 2): ``` #b#####a###################################################### # ##### ###################################################### # ##### ###################################################### # ##### ####################################### #### # ##### ####################################### ######### #### # ##### ####### #### # ############################################# # ####### #### # ############################################# # ####### #### # ############################################# # ####### #### # ############################################# # ####### #### # # ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### #### ################################################# ####### B ################################################# ############ #################################################A############ ``` By the time rat B reaches the intersection, rat A will be travelling down the corridor to exit A and the rat fight will be avoided. ### Rules: * Your program should read in (STDIN or file) an input like those above, and output (STDOUT or file) the same data except many spaces will now be hashes (#). You may substitute any single character (such as `;`) instead of `\n` in the input string but the output string still requires `\n` characters. **UPDATED** * A rat pathway must be one character width wide, except for cross intersections (every space must have zero or two orthogonally adjacent `#` characters). Each rat must have a clear single path, except for cross intersections. No T-intersections are allowed. * Rats are released simultaneously and move at a constant rate. At no time should two or more rats see each other (be in the same column or row without one of more `#` characters in between). * If no solution is possible (such as adjacent entrance points), print `Impossible\n` and exit. * Entrances and exits can be on any sides, however they will never be on the corners. * If a matched entrance and exit are adjacent (eg: `##aA##`), the rat cannot go directly from `a` to `A`. There must be a small 2 space corridor section inside the maze area. * On the turn where a rat reaches its exit point (or any time after that), it is no longer visible to other rats. * Your program may be designed to compute mazes for 1, 2, up to 26 rats. * Standard loopholes are disallowed. ### Score: With your solution, nominate how many rats per maze (N) your program can solve. Your score is your code length in bytes divided by this number N. Please include a sample output in your answer so we can see what your program produces. [Answer] # Haskell, 26 rats?, ~5000 bytes Theoretically, this code should work for any number of rats, but I offer no warranty that it will terminate before the heat death of the universe. It is based on a backtracking algorithm which tries to go the straight path first, and then switch path if the path doesn't work. The number of alternatives is exponential with respect to the length of the path and the number of rats. I haven't bothered to golf it yet, since it's so large, and since I want to make it faster first. ``` {-# LANGUAGE FlexibleContexts #-} module Main (main) where import Control.Lens import Control.Monad import Data.Char import Data.Function import Data.List import Data.Maybe type Pos = (Int,Int) type Path = [Pos] type Maze = String type Input = [(Pos,Char)] type MazeState = [(Path,Path)] type ChoiceMonad a = [a] instance (Num a, Num b) => Num (a,b) where (x,y)+(x',y')=(x+x',y+y') (x,y)-(x',y')=(x-x',y-y') fromInteger n = (fromInteger n,fromInteger n) parseMaze :: Maze -> Input parseMaze maze = maze ^@.. inner . filtered (`notElem` "# ") inner :: IndexedTraversal' Pos Maze Char inner = lined <.> traversed main :: IO () main = do maze <- readFile "Sample2.in" putStrLn $ solveAndShow maze fillMaze :: Maze -> Maze fillMaze = inner.filtered(==' ').~'#' updateMaze :: Path -> Maze -> Maze updateMaze path = inner.indices (`elem` path).filtered(=='#') .~ ' ' isDone :: MazeState -> Bool isDone = all (null . snd) showMaze :: Maze -> MazeState -> Maze showMaze maze path = updateMaze (fst =<< path) $ fillMaze maze showSolution :: Maze -> ChoiceMonad MazeState -> String showSolution _ [] = "Impossible" showSolution maze (x:_) = showMaze maze x stopCondition :: ChoiceMonad MazeState -> Bool stopCondition x = not $ null x || isDone (head x) solveAndShow :: Maze -> String solveAndShow maze = showSolution maze . solve $ mazeToState maze solve :: ChoiceMonad MazeState -> ChoiceMonad MazeState solve = fromJust . find (not.stopCondition) . iterate fullStep mazeToState :: Maze -> ChoiceMonad MazeState mazeToState maze = do let startsEnds = paths $ parseMaze maze return $ startsEnds & traverse.both %~ (:[]) fullStep :: ChoiceMonad MazeState -> ChoiceMonad MazeState fullStep = (>>= stepAll) stepAll :: MazeState -> ChoiceMonad MazeState stepAll input = do pths <- mapM goStep input guard $ iall (checkVisible pths) $ map fst pths return $ pths where goStep :: (Path,Path) -> ChoiceMonad (Path,Path) goStep (curr:rest,[]) = return (curr:curr:rest,[]) goStep (curr:these,end:ends) | distance curr end == 1 = return (end:curr:these,ends) | curr == end = goStep (curr:these,ends) goStep (path,end) = do next <- twoSteps (head end) path prev <- twoSteps next end return $ (next:path,prev:end) inMaze = inMazeWith input twoSteps :: Pos -> Path -> ChoiceMonad Pos twoSteps goal path = do next <- oneStep goal path inMaze guard $ not.null $ oneStep goal (next:path) (\x -> x==next || inMaze x) return next checkVisible :: MazeState -> Int -> Path -> Bool checkVisible _ _ [] = True checkVisible pths i xs@(x:_) = checkBack && checkNow where nBack = 1 + visibleBackwards xs --checkBack = none (any (==x).take nBack .fst) pths checkBack = hasn't (folded.indices (/=i)._1.taking nBack folded.filtered (==x)) pths checkNow = inone (\i' (x':_,_) -> (i/=i') && (==x') `any` take nBack xs ) pths -- How long have you stayed on a line visibleBackwards :: Path -> Int visibleBackwards as = length . takeWhile ((==headDiff as) .headDiff). filter ((>=2).length) $ tails as where headDiff (a:a1:_) = a-a1 headDiff x = error $ "Bug: Too short list " ++ show x inMazeWith :: [(Path, Path)] -> Pos -> Bool inMazeWith = flip elem . concatMap (\x->snd x ++ fst x) oneStep :: MonadPlus m => Pos -> Path -> (Pos -> Bool) -> m Pos oneStep end (curr:prev:_) inMaze = if distance curr end <= 1 then return end else do let distance' :: Pos -> Double distance' x = fromIntegral (distance x end) + if curr - prev == x - curr then 0 else 0.4 next <- msum . map return $ sortBy (compare`on`distance') $ neighbors curr -- Don't go back guard $ next /= prev -- Stay in bounds guard $ isInBounds next let dir = (next - curr) let lr = neighbors next \\ [curr,next+dir,end] -- If next is blocked, check that the one after that is free if inMaze next then do guard $ not . (\x->(x/=end)&&inMaze x) $ next + dir -- Both sides should be blocked as well guard $ (==2). length . filter inMaze $ lr else do -- No neighbors if empty guard $ null . filter inMaze $ lr -- All neighbors of 'curr', including 'next' let neigh' = filter (\i -> inMaze i || i == next) $ neighbors curr -- should be an even number guard $ even $ length neigh' return next oneStep _ [start] _ = return $ inBounds start oneStep _ _ _ = error "Too short path given" toBounds :: (Num a, Eq a) => (a,a) -> a -> a toBounds (low, high) x | x == low = x + 1 | x == high = x - 1 | otherwise = x distance :: Pos -> Pos -> Int distance (x1,y1) (x2,y2) = abs(x1-x2)+abs(y1-y2) -- Moves a pos to the closest one inside the bounds inBounds :: Pos -> Pos inBounds = bimap (toBounds (0,21)) (toBounds (0,61)) isInBounds :: Pos -> Bool isInBounds x = x == inBounds x neighbors :: Pos -> [Pos] neighbors pos = [ pos & l %~ p| l <- [_1,_2], p <- [succ,pred]] paths :: Input -> [(Pos,Pos)] paths pos = flip unfoldr 'a' $ \x -> do (y,_) <- find ((==x).snd) pos (z,_) <- find ((==toUpper x).snd) pos return ((y,z),succ x) ``` Sample output, 6 rats: ``` ##c###B#####b#######C#######F######################f########## ## # # ####### ########## #### ######## ############################################### ##### ############################################### ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############################################################## ############# ########################################## ############# ##### ######################################### D # # ##################################### ############## ## ##### ##################################### ######### # ############################# ######### ###### # ##### ####### ############################# #### # # # ####### ###### ####E######a##########e#d##############################A###### ``` [Answer] # Haskell, 1 rat, 681 Characters The problem can be trivially solved for all mazes with just one rat. This code also "works" for any number of rats, but doesn't follow any of the constraints on the interactions between *multiple* rats and paths. ``` module Main where import Control.Lens import Data.List(unfoldr,find) import Data.Char(toUpper) parse=(^@..lined<.>folded.filtered(`notElem`"# ")) main=interact$do i<-(naive=<<).rats.parse;(lined<.>traversed).filtered(==' ').indices (`notElem`i).~'#' naive(start,(ex,ey))=start':unfoldr go start' where start'=bnds start (ex',ey')=bnds(ex,ey) go(x,y) |(x,y)==(ex',ey')=Nothing |x== ex'=ok(x,y`t`ey') |otherwise=ok(x`t`ex',y) ok z=Just(z,z) t x y=if x>y then x-1 else x+1 bnd(l,h)x |x==l=x+1 |x==h=x-1 |True=x bnds=bimap(bnd(0,21))(bnd(0,61)) rats pos=(`unfoldr`'a')$ \x-> do (y,_)<-find((==x).snd)pos (z,_)<-find((==toUpper x).snd)pos return((y,z),succ x) ``` Sample output: ``` #######a###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ###################################################### ####### ############ #################################################A############ ``` I'm planning to support many rats, so I wrote generic code, but I haven't found a good algorithm for that yet. * `parse` extracts a list of all entrances and exits, with their coordinates * `rats` takes that list and converts it to pairs of coordinates for each rat. * `bnds` takes a coordinate on an edge and moves it to the nearest coordinate inside the maze. * `naive` takes a start and end positions and returns a simple path between them. * `main` then replaces all the white space not in a path with '#' ]
[Question] [ [According to legend](https://i.stack.imgur.com/ftMZn.jpg), almost everyone is outgolfed by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). If not, they will be. Now I'm curious if I'm one of those 'almost everyone'. You will be given a link to an answer in the format of `https://codegolf.stackexchange.com/questions/[QUESTION ID]/[QUESTION NAME]/#[ANSWER ID]`. Find the length of the code, which we will assume as the *last* number on the first line (markdown wise) of the answer in the link. Then, search for Dennis' answers, and do the same. Now compare the input's and Dennis' answers code length, and if it is out-golfed (meaning one or more answer of Dennis' is shorter than that of the input answer), output a truthy value, and if not, a falsy value. If there is no answer belonging to Dennis on the same question as the answer, output a falsy value. # Examples * [Link](https://codegolf.stackexchange.com/questions/119542/implement-the-fibonacci-quine/#119547) : `true` * [Link](https://codegolf.stackexchange.com/questions/119408/ring-me-when-our-cup-noodles-are-ready/#119412) : `false` (At least for now, tell me when it changes) # Rules * You may use any form of truthy/falsy value. * The question of the answer you're given will always be [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). * The question may not have an answer of Dennis', but the inputted answer will never belong to Dennis. * You may assume there is always a number on the first line of the answer. [Answer] ## Python 3.6 + [requests](https://pypi.python.org/pypi/requests) + [bs4](https://pypi.python.org/pypi/beautifulsoup4) - ~~363~~ 358 bytes ``` import bs4,re,requests u,n=input().split("/#");i=1;d=y=float("inf") while i: A=bs4.BeautifulSoup(requests.get(u+f"?page={i}").text,"html.parser")(class_="answer") for a in A: c=int(re.findall("\d+",(a("h1")+a("h2")+a("p"))[0].text)[-1]) if "Dennis"in a(class_="user-details")[-1].text:d=min(c,d) if a["data-answerid"]==n:y=c i=A and i+1; print(d<y) ``` Prints `True` or `False`. *Note: does not currently work on the second link because of invalid HTML produced by [this answer](https://codegolf.stackexchange.com/a/119894/30630) (the `em` and `strong` tags are terminated in the wrong order at the end of the second line, and causes the parser to miss the username block). Try it on [this link](https://codegolf.stackexchange.com/questions/119783/zooming-in-on-a-map/#119790) instead.* ## Using the API - ~~401~~ 380 bytes ``` import requests,re q,A=re.findall("\d+",input());i=1;d=y=float("inf") while i: r=requests.get(f"https://api.stackexchange.com/2.2/questions/{q}/answers?site=codegolf&filter=withbody&page={i}").json();i=r["has_more"]and i+1 for a in r["items"]: c=int(re.search("(\d+)\D+$",a["body"]).group(1)) if a["owner"]["user_id"]==12012:d=min(d,c) if a["answer_id"]==A:y=c print(d<y) ``` *Note that this also fails on the second link, but because one answer started with `This may be foul play.` instead of the header...* [Answer] # Ruby, ~~314~~ ~~315~~ 308+20 = ~~334~~ ~~335~~ 328 bytes Uses the flags `-n -rjson -ropen-uri`. +1 byte from fixing a minor bug. -7 bytes by discovering the `open-uri` Ruby default library. ``` ~/(\d+)\D+(\d+)/ u="http://api.stackexchange.com/2.2/questions/#$1/answers?site=codegolf&filter=withbody&page=%s" n=eval$2 a="answer_id" j=1 o=[] (o+=r=JSON.parse(open(u%j).read)["items"] j=r!=[]&&j+1)while j p o.select{|e|e["owner"]["user_id"]==12012||e[a]==n}.min_by{|e|e["body"][/\d+\s*bytes/].to_i}[a]!=n ``` ]
[Question] [ ## Meta-background This was set as a [question on Puzzling](https://puzzling.stackexchange.com/q/8248/34514), and the instant reaction was "well, someone will just solve that by computer". There was a debate about just how complex a program to solve this would have to be. Well, "how complex does this program have to be" is pretty much the definition of [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so maybe PPCG can settle the issue? ## Background A [matchstick equation](https://codegolf.stackexchange.com/q/50933/62131) is basically a normal mathematical equation, but where the digits and operators are constructed physically by placing matchsticks onto a table. (The main relevant feature of matchsticks here is that they're fairly rigid and have a constant length; sometimes people use other objects instead, such as cotton swabs.) For this challenge, we don't need to define specific rules for how the matchsticks are arranged (like the linked challenge does); rather, we just care about how many matchsticks we'll need to represent an expression that evaluates to a given number. ## The task Here's an alphabet of digits and mathematical operators you can use, each having a cost in matchsticks: * `0`, costing 6 matchsticks * `1`, costing 2 matchsticks * `2`, costing 5 matchsticks * `3`, costing 5 matchsticks * `4`, costing 4 matchsticks * `5`, costing 5 matchsticks * `6`, costing 6 matchsticks * `7`, costing 3 matchsticks * `8`, costing 7 matchsticks * `9`, costing 6 matchsticks * `+`, costing 2 matchsticks * `-`, costing 1 matchstick * `×`, costing 2 matchsticks (You may represent `×` as `*` in your program's output if you wish, in order to avoid needing to use non-ASCII characters. In most encodings, `×` takes up more bytes than `*`, and so I imagine that most programs will want to take advantage of this leeway.) You need to write a program that takes a nonnegative integer as input (via any [reasonable means](https://codegolf.meta.stackexchange.com/q/2447/62131)), and produces an expression that evaluates to that integer as output (again via any reasonable means). Additionally, the expression must be nontrivial: it must contain at least one operator `+`, `-`, or `×`. Finally, the expression you output must be the cheapest (or tied for the cheapest) in terms of total matchstick cost, among all outputs that otherwise comply with the specification. ## Clarifications * You can form multiple-digit numbers via outputting multiple digits in a row (e.g. `11-1` is a valid output to produce `10`). Just to be completely precise, the resulting number gets interpreted in decimal. This sort of concatenation isn't an operation that works on intermediate results; only on literal digits that appear in the original expression. * For the purpose of this challenge. `+`, `-`, and `×` are infix operators; they need an argument to their left and to their right. You aren't allowed to use them in prefix position like `+5` or `-8`. * You don't have parentheses (or any other way to control precedence) available. The expression evaluates according to the typical default precedence rules (multiplications happen first, and then the additions and subtractions are evaluated left to right). * You don't have access to any mathematical operators or constants other than the ones listed above; "lateral thinking" solutions are often accepted at Puzzling, but it doesn't make sense to require a computer to come up with them itself, and over here on PPCG, we like it to be objective whether or not a solution is correct. * The usual integer overflow rules apply: your solution must be able to work for arbitrarily large integers in a hypothetical (or perhaps real) version of your language in which all integers are unbounded by default, but if your program fails in practice due to the implementation not supporting integers that large, that doesn't invalidate the solution. * If you use the same digit or operator more than once, you have to pay its matchstick cost each time you use it (because, obviously, you can't reuse the same physical matchsticks in two different locations on the table). * There's no time limit; brute-force solutions are acceptable. (Although if you have a solution that's faster than brute force, feel free to post it even if it's longer; seeing how alternative approaches compare is always interesting.) * Although writing an explanation of your code is never *required*, it's likely to be a good idea; [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") solutions are often very hard to read (especially to people not familiar with the language they're written in), and it can be hard to evaluate (and thus vote on) a solution unless you understand how it works. ## Victory condition As a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, answers with fewer bytes are considered better. However, as usual, feel free to post answers with different approaches, or in specific languages even if they're more verbose than certain other languages; the goal of golf is really to see how far you can optimize a particular program, and doing things this way gives us lots of potential programs to optimize. So don't be discouraged if someone submits a solution using a completely different approach, or a completely different language, and gets a much shorter answer; it may well be that your answer is better-optimized and shows more skill, and voters on PPCG often appreciate that. [Answer] ## Python2, 1̶9̶8̶ ̶b̶y̶t̶e̶s̶ 182 bytes thanks to math\_junkie ``` def f(n,c=dict(zip('0123456789+-*',map(int,'6255456376212'))),e=[(0,'')]): while 1: v=(m,s)=min(e);e.remove(v) try: if eval(s)==n:return s except:0 e+=[(m+c[x],s+x)for x in c] ``` This algorithm does nothing to exclude prefix versions of `+` and `-`, but they will either be worse than, or equal to and appear later in the search, their infix counterparts. Because it uses the keyword argument `e` mutably, it will give invalid results if called multiple times per session. To fix this, use `f(n, e=[(0,'')])` instead of just `f(n)`. Note that the four-spaced indents represent tabs, so this will only work with Python 2. I also have an ungolfed and optimized version which runs quickly even for quite large numbers: ``` from heapq import heappop, heappush def f(n): digits = list('0123456789') ops =['+','-','*',''] costs = dict(zip(digits + ops, [6,2,5,5,4,5,6,3,7,6,2,1,2,0])) expressions = [(costs[d], abs(n - int(d)), int(d), d) for d in digits[1:]] seen = set() while 1: cost, d, k, expression = heappop(expressions) if d == 0: return expression for op in ops: if op in '+-' and k in seen: continue for digit in digits: if op and digit == '0': continue expression1 = expression + op + digit k1 = eval(expression1) d1 = abs(n - k1) if d1 == 0: return expression1 heappush(expressions, (cost+costs[op]+costs[digit], d1, k1, expression1)) seen.add(k) ``` [Answer] # PHP, 241 Bytes [Online Version](http://sandbox.onlinephpfunctions.com/code/452497d88958a6ea54f16911e4df4046e1babf7f) ``` function m($i){for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e;}foreach($r=range(0,2*$a=$argv[1])as$v)foreach($r as$w)$x[$v+$w]["$v+$w"]=$x[$v*$w]["$v*$w"]=1+$x[$v-$w]["$v-$w"]=m("$v")+m("$w")+1;echo array_search(min($x[$a]),$x[$a]); ``` ## Breakdown ``` function m($i){ for(;$s<strlen($i);)$e+="6255456376"[$i[$s++]];return$e; #return the count of the matchstick for an integer } foreach($r=range(0,2*$a=$argv[1])as$v) # limit to an input to 300 in the online version foreach($r as$w) $x[$v+$w]["$v+$w"]= #fill the 2D array in the form [result][expression] = count matchsticks $x[$v*$w]["$v*$w"]= 1+$x[$v-$w]["$v-$w"]= m("$v")+m("$w")+1; echo $k=array_search(min($x[$a]),$x[$a]); # Output expression with a minium of matchsticks echo"\t".$x[$a][$k]; #optional Output of the count of the matchsticks ``` Way with a little better performance ``` function m($i){ for(;$s<strlen($i);) $e+="6255456376"[$i[$s++]];return$e;} #return the count of the matchstick for an integer foreach($r=range(0,2*$a=$argv[1])as$v) foreach($r as$w){$c=m("$v")+m("$w")+1; if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input if($a==$v*$w)$x["$v*$w"]=1+$c; if($a==$v-$w)$x["$v-$w"]=$c;} echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks echo"\t".$x[$k]; #optional Output of the count of the matchsticks ``` ## Support of negative integers [Version with negative integers](http://sandbox.onlinephpfunctions.com/code/862db05770aa64b861c9576088a62692d6d497c7) ``` function m($i){ $e=$i<0?1:0; # raise count for negative integers for($s=0;$s<strlen($i);)$e+=[6,2,5,5,4,5,6,3,7,6][$i[$s++]];return$e; #return the count of the matchstick for an integer } $q=sqrt(abs($argv[1])); $l=max(177,$q); $j=range(-$l,$l); # for second loop for better performance foreach($r=range(min(0,($a=$argv[1])-177),177+$a)as$v) foreach($j as$w){$c=m("$v")+m("$w")+1; if($a==$v+$w)$x["$v+$w"]=1+$c; # fill array if value equal input if($a==$v*$w)$x["$v*$w"]=1+$c; if($a==$v-$w)$x["$v-$w"]=$c; if($a==$w-$v)$x["$w-$v"]=$c; # added for integers <0 } echo $k=array_search(min($x),$x); # Output expression with a minium of matchsticks echo"\t".$x[$k]; #optional Output of the count of the matchsticks ``` ]
[Question] [ I am shamelessly posting a request for something I would actually find useful. The task is to take an arbitrary ascii box drawing like this ``` | +----+----+ | state A +---+ +---------+ | | +----v----+ | state B | +---------+ ``` ... and turn it into something more beautiful using unicode box drawing characters, e.g. ``` │ ╭────┴────╮ │ state A ├───╮ ╰─────────╯ │ │ ╭────v────╮ │ state B │ ╰─────────╯ ``` In more detail: * convert only + - | characters - other characters should be unchanged * use + BOX DRAWINGS LIGHT VERTICAL (U+2502) │ + BOX DRAWINGS LIGHT HORIZONTAL (U+2500) ─ + BOX DRAWINGS LIGHT ARC DOWN AND RIGHT (U+256D) ╭ + BOX DRAWINGS LIGHT ARC DOWN AND LEFT (U+256E) ╮ + BOX DRAWINGS LIGHT ARC UP AND LEFT (U+256F) ╯ + BOX DRAWINGS LIGHT ARC UP AND RIGHT (U+2570) ╰ + BOX DRAWINGS LIGHT VERTICAL AND LEFT (U+2524) ┤ + BOX DRAWINGS LIGHT VERTICAL AND RIGHT (U+251C) ├ + BOX DRAWINGS LIGHT DOWN AND HORIZONTAL (U+252C) ┬ + BOX DRAWINGS LIGHT UP AND HORIZONTAL (U+2534) ┴ + BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL (U+253C) ┼ + - always replaced with U+2500 + | always replaced with U+2502 + + is replaced with a unicode character that depends on the 4 characters north, south, east and west of it (if they exist) + < and > are treated as vertical wall segments if north or south of a + (so that you can have arrows terminating in vertical walls of a box) + v and ^ are treated as horizontal wall segments if east or west of a + (so that you can have arrows terminating in horizontal walls of a box) + + is treated as a wall segment if either north, south, east or west of a + (so that lines can connect next to a box corner) Testcases ``` +-+ +---+ +---+ | | +-- |ABC| -+ | +++ +-+ ++--+ +---+ +-+ | +---> | +--+ +-v+ +---+ | | +-----+ |Hi| -> | +^-+ |world<-----+ +--+ +---+ | +-----+ | | +-- | ---+--- | ``` Becomes ``` ╭─╮ ╭───╮ ╭───╮ │ │ ├── │ABC│ ─┤ │ ╭┴╮ ╰─╯ ╰┬──╯ ╰───╯ ╰─╯ │ ╰───> │ ╭──╮ ╭─v╮ ╭───╮ │ │ ╭─────╮ │Hi│ ─> │ ╰^─╯ │world<─────╮ ╰──╯ ╰───╯ │ ╰─────╯ │ │ ╰── │ ───┼─── │ ``` Shortest code wins! [Answer] ## JavaScript (ES6), 236 bytes ``` s=>` ${s} `.split` `.map((l,i,a)=>l.replace(/[+-|]/g,(c,j)=>c>`-`?`│`:c>`+`?`─`:`┼┬├╭┤╮??┴?╰?╯`[g(a[i-1][j])+g(l[j-1],1)*2+g(l[j+1],1)*4+g(a[i+1][j])*8]),g=(c,f)=>(f?`+-^v`:`+<>|`).indexOf(c)<0).slice(1,-1).join` ` ``` ]
[Question] [ In [my previous challenge](https://codegolf.stackexchange.com/q/70017/3808), I drew the first diagram mostly by hand (with the help of vim's visual block mode). But surely there must be a better way... --- Given an input of two dimensions, a width and a height, output a hexagonal grid with those dimensions in ASCII art. Here's the diagram referenced in the intro (with minor edits), which should be your output for the input `width=7, height=3`: ``` _____ _____ _____ / \ / \ / \ _____/ -2,-1 \_____/ 0,-1 \_____/ 2,-1 \_____ / \ / \ / \ / \ / -3,-1 \_____/ -1,-1 \_____/ 1,-1 \_____/ 3,-1 \ \ / \ / \ / \ / \_____/ -2,0 \_____/ 0,0 \_____/ 2,0 \_____/ / \ / \ / \ / \ / -3,0 \_____/ -1,0 \_____/ 1,0 \_____/ 3,0 \ \ / \ / \ / \ / \_____/ -2,1 \_____/ 0,1 \_____/ 2,1 \_____/ / \ / \ / \ / \ / -3,1 \_____/ -1,1 \_____/ 1,1 \_____/ 3,1 \ \ / \ / \ / \ / \_____/ \_____/ \_____/ \_____/ ``` Notice several things: * The width and height are essentially equivalent to how many hexagons there are for a given y and x coordinate respectively. These will *always* be odd numbers. * Each hexagon is represented by the ASCII art ``` _____ / \ / \ \ / \_____/ ``` but borders are "shared" between neighboring hexagons. * The comma in the coordinates is *always* exactly two characters below the center of the top edge. The x-coordinate is then positioned directly before the comma, and the y-coordinate directly after. You may assue that the coordinates will never be too large such that they would overlap the hexagon's borders. Input may be taken as a whitespace-/comma-separated string, an array of integers, or two function/commandline arguments. Output must be a single string (to STDOUT, as a return value, etc.). Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes will win. The grid above can be used as a test case. The maximum-sized `width=199, height=199` grid is obviously impractical to include here, but the first few rows and columns should look like the following: ``` _____ ___ / \ / _____/-98,-99\_____/-96, / \ / \ /-99,-99\_____/-97,-99\___ \ / \ / \_____/-98,-98\_____/-96, / \ / \ /-99,-98\_____/-97,-98\___ \ / \ / \_____/-98,-97\_____/-96, / \ / \ /-99,-97\_____/-97,-97\___ \ / \ / ``` [Answer] # Ruby, 221 bytes ``` ->w,h{s=' ' a=(s*9+?_*5)*(w/2)+$/ (2-h*2).upto(h*2+3){|y|c=y<4-h*2 a+=[b=c ?s:?\\,s+b,s,''][y%4] (0-w/2).upto(w/2){|x|a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",s*7,?_*5,"/ \\"][(y+x*2+w)%4]%[x,y/4]} a+='// '[c ?3:y%4]+$/} a} ``` **Ungolfed in test program** ``` f=->w,h{ s=' ' #set s to space for golfing reasons a=(s*9+?_*5)*(w/2)+$/ #start building the output with a row of just _ and space (2-h*2).upto(h*2+3){|y| #iterate 4 times for each row of hexagons, plus an extra 2 at the end to finish last row c=y<4-h*2 #condition for first two rows a+=[b=c ?s:?\\,s+b,s,''][y%4] #string to be output before main set of hexagons (spaces for top row, \ for certain other rows (0-w/2).upto(w/2){|x| #iterate through hexagons on each row, 4 lines for each with the following printf type string a+=["/#{h<y/2?s*7:"%3d,%-3d"}\\",#line 1:contains ends / \ and numbers s*7, #line 2 padding spaces ?_*5, #line 3 padding ___ "/ \\"][(y+x*2+w)%4]% #line 0 top of hexagon / \; formula to select string to be printed [x,y/4] #numbers to be printed (if format for current line does not require them they are ignored) } a+='// '[c ?3:y%4]+$/ #ending alternates between / and space; / are suppressed for first two rows } a } puts g[7,3] puts g[5,5] ``` **Output** As I was finishing debugging, I noticed an ambiguity in the spec. Where `w+1` is divisible by 4, the first and last x coordinates are odd, and there is no ambiguity. But where `w-1` is divisible by 4 the first and last x coordinates are even. I assumed that the first and last columns should be offset below the next ones. But then I read the previous question and noted in that case it was the odd columns that should be offset below the even ones (note for `w-1` divisible by 4 it is not possible to do both.) That distinction was not made in this question, however. I will leave this up to OP's judgement and rework if necessary, though I'd prefer not to have to. ``` _____ _____ _____ / \ / \ / \ _____/ -2,-1 \_____/ 0,-1 \_____/ 2,-1 \_____ / \ / \ / \ / \ / -3,-1 \_____/ -1,-1 \_____/ 1,-1 \_____/ 3,-1 \ \ / \ / \ / \ / \_____/ -2,0 \_____/ 0,0 \_____/ 2,0 \_____/ / \ / \ / \ / \ / -3,0 \_____/ -1,0 \_____/ 1,0 \_____/ 3,0 \ \ / \ / \ / \ / \_____/ -2,1 \_____/ 0,1 \_____/ 2,1 \_____/ / \ / \ / \ / \ / -3,1 \_____/ -1,1 \_____/ 1,1 \_____/ 3,1 \ \ / \ / \ / \ / \_____/ \_____/ \_____/ \_____/ _____ _____ / \ / \ _____/ -1,-2 \_____/ 1,-2 \_____ / \ / \ / \ / -2,-2 \_____/ 0,-2 \_____/ 2,-2 \ \ / \ / \ / \_____/ -1,-1 \_____/ 1,-1 \_____/ / \ / \ / \ / -2,-1 \_____/ 0,-1 \_____/ 2,-1 \ \ / \ / \ / \_____/ -1,0 \_____/ 1,0 \_____/ / \ / \ / \ / -2,0 \_____/ 0,0 \_____/ 2,0 \ \ / \ / \ / \_____/ -1,1 \_____/ 1,1 \_____/ / \ / \ / \ / -2,1 \_____/ 0,1 \_____/ 2,1 \ \ / \ / \ / \_____/ -1,2 \_____/ 1,2 \_____/ / \ / \ / \ / -2,2 \_____/ 0,2 \_____/ 2,2 \ \ / \ / \ / \_____/ \_____/ \_____/ ``` ]
[Question] [ # Introduction There is an Apple tree trunk positioned between -2 to 2 on the x-axis, where some apples fall down around it: ``` | | | | <-------|---|-------> -2 2 ``` Everyday, *n* apples fall down. Each apple maintains its *x coordinate* as falls straight to the ground. But if it lands on top of another apple, it will roll according to the following rules until it reaches the ground or a supporting layer of apples: 1. If the space at *x+1* at its current height is empty the current apple goes there. 2. Else if the space at *x-1* is empty the current apple goes there. 3. Otherwise the current apple stays where it is on top of that other apple. # Challenge The input will be the *n* starting positions of each apple in order. You can take it as an array or as separated numbers or in any other valid way, just make sure you explain it in your answer. The output should be an ASCII drawing of the tree trunk and the apples around. You are *not required* to draw the x-axis to the left of the leftmost apple and to the right of the rightmost apple, but you do need to draw it anywhere it is beneath some apple. You can also extend the tree above the highest apple. You can assume all *x-coordinates* are between -100 and 100, but not between -2 and 2. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") .. The shortest answer in bytes wins! # Examples Input: `[-3, 5, 5, -4, -4, 5, -3]` Output: ``` a| | aaa| | aaa ---|---|---- ``` --- Input: `[3, 3, 3, 3, 8, 9]` Output: ``` | |a | |aaa aa |---|------- ``` --- Input: `[-5, -5, -5, -5, -5, -5, -5, -5, -5]` Output: ``` a | | aaa | | aaaaa| | -----|---| ``` [Answer] ## PHP, 230 bytes I've added the first two newlines for readibility. ``` function($l){for($y=count($l);$y>=0;$f[]="$a| |$a")$a=str_repeat($y--?$w=' ':'-',99); foreach($l as$x){for($x+=101,$s=$y=0;!$s;$b[$x]!=$w?$b[$x+1]!=$w?$b[$x-1]!=$w?$s=1:--$x :++$x:0)$b=$f[$y++];$f[$y-2][$x]=a;}echo join(' ',$f);}; ``` `[Ideone](http://ideone.com/hehx1R)` Here is the ungolfed version: ``` function drawApples(array $listStartX) { $field = []; $maximalHeight = count($listStartX); for ($y = $maximalHeight; $y >= 0; --$y) { $line = str_repeat($y > 0 ? ' ' : '-', 98); $field[] = $line .'| |'. $line; } foreach ($listStartX as $x) { $x += 100; for ($y = 0; true; ++$y) { if ($field[$y][$x] === ' ') { continue; } if ($field[$y][$x + 1] === ' ') { ++$x; continue; } if ($field[$y][$x - 1] === ' ') { --$x; continue; } $field[$y - 1][$x] = 'a'; break; } } echo implode("\n", $field); } ``` [Answer] # Python 2.7, 282 bytes ``` from collections import*;a=Counter();a[2]=-1;a[-2]=-1 for d in input(): while 0<=a[d+1]<a[d]:d+=1 while 0<=a[d-1]<a[d]:d-=1 a[d]+=1 m=max(a.values())+1 print'\n'.join(''.join(' '*(m-a[i]-1)+'a'*a[i]+'-'if i**2!=4 else'|'*m for i in range(min(a),max(a)+1))[i::m]for i in range(m)) ``` `[Ideone](http://ideone.com/lc0FvO)` Well… I tried. ]
[Question] [ *This question brought to you by a game I like to play when stuck in long phone meetings.* Given any two times from a 24 hour clock (from 00:00 to 23:59), how many valid mathematical equations can be generated with all of the times in between using only basic arithmetic operations? **Input:** two four digit strings (no colon) representing valid times in a 24 hours cycle. **Examples:** For input=0000, 1300 ``` 03:26 produces: "0+3*2=6" and "03*2=6" etc. 11:10 produces quite a few, including: "1*1=1+0" and "1=1=1^0" and "1=11^0" etc. 12:24 produces: "1/2=2/4" and "1=(2*2)/4" etc. ``` **Valid operations are:** * addition * subtraction * multiplication * division (floating point) * exponentiation * factorial **Other allowable symbols** * Parentheses * Equal signs Shortest code wins. **Notes** * The goal is to find the *number* of valid expressions between two times, not the number of times that *contain* a valid expression. * The two times given as input are included in the range of times. * You may group the digits in any way possible, so "1223" can be "12 23" or " 1 2 23" or "1 223" etc. etc. * You may use as many parentheses as needed. * You may use more than one `=` sign. For instance, the time `11:11` has the valid expression `1=1=1=1`. * If the first time occurs chronologically after the second time, the range of times should wrap as if crossing into the next day. * The numbers must remain in their original order- you may not re-order the digits. * When clustering numbers, zero's may absolutely be the front most digit, in which case, they are ignored ("0303" clustered as "03 03" is just two digits with the value of 3.) * You MAY NOT use the minus sign as unary negation. Therefore, "12:01" does NOT produce "1-2=-(01)", but DOES produce "1-2=0-1". * You MAY NOT add decimal points to digits. Therefore, "12:05" does NOT produce "1/2=0.5". * No chaining of factorials- a digit may be followed by at most one "!", no more, otherwise, many times would have infinite solutions. Ex: "5!" is valid but "5!!" is not valid. [Answer] # Python3, 363 chars Since no answer is given till today, I hand in what I got. Sadly, the try/except block is too fat, I didn't found a way to save chars there. It is really tricky with the nested loops there, not all can be done with list comprehensions I think, but maybe someone can tell me how. However, I restricted the challenge myself to only use basic math '+-\*/' and no parentheses. ``` a,b = input().split() r=0 for time in [c for c in range(int(a),int(b)) if c/10%10<6]: t,*ts='%04d'%time e=[t] for d in ts: e=[(n+o+d,n+d)[o==' '] for o in ' -+*/=' for n in e] for h in [g for g in [e.split('=') for e in e if '='in e] if len(g)>1]: for k in h: try: if eval(h[0]) != eval(k): break except: break else: r+=1 print(r) ``` My full code (hope something explanatory) on this CodeGolf can be found on my [pastebin](http://pastebin.com/dydWfcyS). ]
[Question] [ Given a list of case-insensitive ASCII letter strings ("words"), output whether the entire list can be found on some four-by-four configuration ("board") of letter squares, in which no square can be used more than once in a word, and in which words are formed by moving from any square to any adjacent square including diagonally. You do not need to worry that the combination of squares that would allow for the list actually appears in a [Boggle](/tags/boggle/info) game. The words need not be actual words in any language. You should assume that if Q appears on the board, it's on a square of its own (unlike in actual Boggle). Standard loopholes are banned, standard I/O rules apply, and you're golfing. --- In the examples below, a slash signifies a newline. ## Truthy examples * auuuuooiiaaoiee, euiaaiueeuua, ooouuueee, eueueuoaoa — All are on the board auii/euoa/ueoa/euio * swiop, byteba, ceropl, qoiz, aeis, lqoep — All are on the board abcb/rety/poiw/lqzs ## Falsy examples * swiop, byteba, ceropl, qoiz, aeis, lqoep, wybez — There are fifteen distinct letters (*abceilopqrstwyz*) and a single word has two *b*s, so that's the sixteenth square. Thus there's only one *e*. But the *e* has nine distinct letters (*abcioprtz*) adjacent to it, which is impossible. * hskcbnzvgfa, lajdnzvfhgs, kajfbmxvshd, ldgckvbsanx — There are sixteen distinct letters (*abcdfghjklmnsvxz*). Of those, *s* is adjacent to all of *abghkv*, *v* is adjacent to all of *bfgksxz*, *b* is adjacent to all of *cfmnsv*, *a* is adjacent to all of *fjklns*, and *f* is adjacent to all of *abghjv*. But on an actual board only four squares are adjacent to more than five squares apiece. [Answer] # [Python 3](https://docs.python.org/3/), 215 bytes ``` def f(w):b=product(*[set("".join(w))]*16);return any(all(any(all(x-y in[1,-1,4,-4]for x,y in zip(q,q[1:]))for q in product(*[[x for x in range(16)if k[x]==c]for c in a]))for a in w)for k in b) from itertools import* ``` [Try it online!](https://tio.run/##RU/BboMwDL33KyxOCQqV0KodOvEliIMLZvNK4xASFfbzLGGbZh/8/N6zLbstfIh92feBRhjVU19vjfMyxD6osl0oqKI4fwrbJOmurF/1m6cQvQW0m8JpUn91rTZg29amqs3FVJduFA@rySR8sVOzmdv62mmd@Tmz/3faFQ53Zj3ad1LpEI9wb9euafpjVZ9F/J3H3DwPeM/wpk@jlwdwIB9EpgX44cSHcn@KHxZoksnFoPR5cROnpwwU@uQ826DS19mj9Y4xhQgzojCRAYoJciSKEQ2ISNLpR8gpKPgN "Python 3 – Try It Online") This is never going to finish, so I can't really debug it or prove it works. I will try to find constant optimizations / test with reduced test cases, but if you spot a reason it would definitely fail, I will take it down / fix it. ]
[Question] [ In this challenge, I have a field of avocados which I'd like to juice as quickly and completely as possible. Can you write a program or function to help me work out how to juice all the avocados perfectly? As input, you'll get the avocados as an `m`x`m` square grid, where `m` is an integer between 3 and 6. Each square contains exactly one avocado. Avocados have several stages of juiciness: **Stage 1:** The avocado has not been juiced at all. **Stage 2:** The avocado has been partially juiced. **Stage 3:** The avocado has been completely juiced. **Stage 4:** The avocado has exploded due to over-juicing. When you use a juicing tool, the avocados in that juicing tool's area of effect move to the next stage. Exploding avocados have a lot of force and will destroy the entire avocado field, so make sure none of the avocados explode! Here is an example of a grid of avocados. In these examples, I've used the coordinate `0,0` for the bottom-left corner, and the coordinate `2,2` for the top-right corner, although you can adjust the coordinate system to suit your language. ``` 112 221 231 ``` The goal is to make all the avocados perfectly juiced (i.e. stage 3). To achieve this you have three different juicing tools in your possession. Each juicing tool have a different area of effect, but they all increase the juiciness of affected avocados by 1. Here are all the tools you have at your disposal. You use the juicers by specifying the first letter of the tool, then the coordinates which you want to juice. For example, to use the Slicer on square `5,2`, you would output `S 5,2`. **Slicer**: Juices the target coordinate and the avocado on either side. ``` 112 112 112 221 --> XXX --> 332 231 231 231 ``` **Grater**: Juices the target coordinate and the avocado above and below. ``` 112 1X2 122 221 --> 2X1 --> 231 --> kaboom! 231 2X1 241 ``` **Rocket Launcher**: Juices the target coordinate and all adjacent avocados. ``` 112 1X2 122 221 --> XXX --> 332 221 2X1 231 ``` ### Sample Inputs and Outputs ``` 323 212 323 G 1,1 S 1,1 3312 3121 1213 2133 R 0,0 R 1,1 R 2,2 R 3,3 22322 22222 22222 33233 33333 G 0,3 G 1,3 G 2,2 G 3,3 G 4,3 222332 333221 222332 333222 222333 333222 S 1,5 S 1,3 S 1,1 S 4,5 S 4,3 S 4,1 G 5,4 ``` [Answer] ## Mathematica — 350 bytes Not a very short solution, but better than no solution at all, right? ``` t[x_]:=Flatten@Table[x/@{G,S,R},{i,n},{j,n}];""<>Cases[StringReplace[(First@Solve[(Table[G[i,j]+G[i-1,j]+G[i+1,j]+S[i,j]+S[i,j-1]+S[i,j+1]+R[i,j]+R[i-1,j]+R[i+1,j]+R[i,j-1]+R[i,j+1],{i,n=Length@#},{j,n}]/.(G|S|R)[___,0|n+1,___]->0)==3-#&&And@@t[#[i,j]>=0&],t[#[i,j]&],Integers])/.{(x_->m_):>ToString[m x]},{"["->" ","]"->"\n",", "->","}],Except@"0"]& ``` A more readable version (with extra spaces and indents and stuff): ``` t[x_] := Flatten@Table[x /@ {G, S, R}, {i, n}, {j, n}]; "" <> Cases[ StringReplace[(First@ Solve[(Table[ G[i, j] + G[i - 1, j] + G[i + 1, j] + S[i, j] + S[i, j - 1] + S[i, j + 1] + R[i, j] + R[i - 1, j] + R[i + 1, j] + R[i, j - 1] + R[i, j + 1], {i, n = Length@#}, {j, n}] /. (G | S | R)[___, 0 | n + 1, ___] -> 0) == 3 - # && And @@ t[#[i, j] >= 0 &], t[#[i, j] &], Integers]) /. {(x_ -> m_) :> ToString[m x]}, {"[" -> " ", "]" -> "\n", ", " -> ","}], Except@"0"] & ``` Input is an array (e.g. `{{3,2,3},{2,2,2},{3,2,3}}`), output is a string (with a trailing newline — if this is unacceptable, enclose the function in `StringDrop[...,-1]` for an extra 15 bytes). I used the coordinate system that says (1,1) is the top-left corner, (n,n) is the bottom right (where n is the dimension of the matrix). Sometimes, if the solution requires doing the same operation multiple times, the output includes things like `3 G 2,2` (for "use the grater at (2,2) three times") — since you didn't say what to do in this case, I hope that's OK. Explanation: * `Table[G[i,j]+G[i-1,j]+G[i+1,j]+S[i,j]+S[i,j-1]+S[i,j+1]+R[i,j]+R[i-1,j]+R[i+1,j]+R[i,j-1]+R[i,j+1],{i,n=Length@#},{j,n}]` creates an array with the variables G[i,j] in each place that's affected by using the grater at (i,j), and similarly for S[i,j] and R[i,j]. These variables represent the number of times the tool is used at that position. * `.../.(G|S|R)[___,0|n+1,___]->0` removes the effects of using tools at positions outside the avocado field. * `...==3-#` compares this to the difference between the input and a field of perfectly juiced avocados. * `...&&And@@t[#[i,j]>=0&]` says the variables G[i,j], S[i,j], R[i,j] must be non-negative (you can't un-juice the avocados!), using the shorthand `t[x_]:=Flatten@Table[x/@{G,S,R},{i,n},{j,n}]`. * `First@Solve[...,t[#[i,j]&],Integers]` finds the first integer solution to our equations in terms of the variables G[i,j], S[i,j], R[i,j]. * `/.{(x_->m_):>ToString[m x]}` hides the variables that equal zero, while also putting the solution in a nice string form. * `StringReplace[...,{"["->" ","]"->"\n",", "->","}]` turns strings like `"2 G[1, 4]"` into strings like `"2 G 1,4"`, and adds a newline on the end. * `""<>Cases[...,Except@"0"]` removes all the leftover `"0"`s and joins all the strings together. [Answer] ## Python3, 362 bytes ``` E=enumerate M=[(0,1),(0,-1),(1,0),(-1,0)] def f(a): q=[({(x,y):u for x,r in E(a)for y,u in E(r)},[])] while q: m,j=q.pop(0) if{3}=={*m.values()}:return j for x,y in m: for G,s in[('S',M[:2]),('G',M[2:]),('R',M)]: if len(S:=[(x+X,y+Y)for X,Y in s+[(0,0)]if(C:=(x+X,y+Y))in m])==len(O:={C:m[C]+1for C in S if m[C]+1<=3}):q+=[({**m,**O},j+[(G,x,y)])] ``` [Try it online!](https://tio.run/##bVFNb9swDD3Pv0LIxZKtBrHUQyFMp6TIqSvQXFqoQuGh8urAX/HHFsPwb89IO8kwIAeTfI@PpElVfftVFvKhqk@nR@2KLnd13DrvSRu64hHjYO/QRXwF9g6d9T5dQhIaM@WRAwgHeuQ9Ux1JypoceU3SgjxCGmHPuxnWbOTGQjH585VmjhygmOR8rw/LqqzoigFMk0GOWg9BvvwdZ51rKBtV7dquLsge8hs9@FtfDSP3d7N7QTdCah7d46wcO0/EljdAGApq/mSUsLACNIBYqCl@gZjZSQ/DSeYKulOw0TF85X34Nm3wyt@waxPiRWD7NKFrpa8ShhMt0xqLn5Ue1io3axtGWLvGyh22nrnvWo5MbczWmmkWsxrB8pdr6UzgjWDSEAQ5D4Lnke8BbTkeeDretFeKbTfTb0PrjUmtOoQavcnjI8WA2RO@Ult@/Czj@pM28Fjfzqc0JsjjiqZFy0nK7LVjkmatq@mPsnCcNMumytKW@u@Fz2Cy10REk8Vi4UkhPRGJySNuxCUhkY1E5MGHGnkWyLNACCkEWHG1EppIsPIivb9KIYF5qIj@Q2JG8oJQXdWwDE3ov3UjxtgNWtym5W36HujTXw) The code above is a basic brute-force solution. However, it times out for the last test case, so below is an optimized solution (at the cost of 101 bytes) that solves all the test cases in a far more reasonable amount of time: ## Python3, 463 bytes ``` E=enumerate M=[(0,1),(0,-1),(1,0),(-1,0)] def f(a): q=[({(x,y):u for x,r in E(a)for y,u in E(r)},[])] while q: m,j=q.pop(0) if{3}=={*m.values()}:return j D={'G':{},'S':{},'R':{}} for x,y in m: for G,s in[('S',M[:2]),('G',M[2:]),('R',M)]: if len(S:=[(x+X,y+Y)for X,Y in s+[(0,0)]if(C:=(x+X,y+Y))in m])==len(O:={C:m[C]+1for C in S if m[C]+1<=3}):D[G][len(S)]=D[G].get(len(S),[])+[({**m,**O},j+[(G,x,y)])] for i in D: if D[i]:q+=D[i][max(D[i])] ``` [Try it online!](https://tio.run/##bVFNb9swDD3Pv0LIxZKtBrHUQyFMp6TIqSvQXFqoQuGh8urAX/HHFsPwb89IO8kwIAeTfI@PpElVfftVFvKhqk@nR@2KLnd13DrvSRu64hHjYO/QRXwF9g6d9T5dQhIaM@WRAwgHeuQ9Ux1JypoceU3SgjxCGmHPuxnWbOTGQjH585VmjhygmOR8rw/LqqzoigFMk0GOWg9BvvwdZ51rKBtV7dquLsge8hs9@FtfDSP3d7N7QTdCah7d46wcO0/EljdAGApq/mSUsLACNIBYqCl@gZjZSQ/DSeYKulOw0TF85X34Nm3wyt@waxPiRWD7NKFrpa8ShhMt0xqLn5Ue1io3axtGWLvGyh22nrnvWo5MbczWmmkWsxrB8pdr6UzgjWDSEAQ5D4Lnke8BbTkeeDretFeKbTfTb0PrjUmtOoQavcnjI8WA2RO@Ult@/Czj@pM28Fjfzqc0JsjjiqZFy0nK7LVjkmatq@mPsnCcNMumytKW@u@Fz2Cy10REk8Vi4UkhPRGJySNuxCUhkY1E5MGHGnkWyLNACCkEWHG1EppIsPIivb9KIYF5qIj@Q2JG8oJQXdWwDE3ov3UjxtgNWtym5W36HujTXw) Further optimizations could be added, including flood fills to check that a juicing process does not strand unjuiced avocados in a patch that can never be reached again. ]
[Question] [ King Julian needs to get through the jungle, but he's feeling lazy. He wants a computer to be able to calculate a route through the jungle for him. Using STDIN get a map of the jungle for the computer to crack. It will follow the following format: ``` 01001E 010110 000P00 1100J1 S00111 ``` The way the jungle map works is: `0` is ground that Julian can move along. `1` is dense impassable jungle. `P` is an area with predators in it, that you must avoid at all costs. `J` is relatively thick jungle. Julian's minions can break through one of these before tiring. `S` is where Julian starts. It can be anywhere on the map. `E` is where Julian wants to go; the end of the path. It also can be anywhere on the map, just like any other tile. Every character is a tile on the map. Line breaks indicate a new row of tiles. If STDIN in your language does not support line breaks, the line break must be replaced by a space to signify a new row. To move between the tiles, you must output a string using STDOUT containing the following special characters: `F` - Forward `B` - Backward `L` - Rotate Julian left (90 degrees anticlockwise) `R` - Rotate Julian right (90 degrees clockwise) `M` - Minions destroy a `J` tile 1 tile forward from Julian, if there is one (`M` just clears out the tile, you still have to move onto it) A possible output would be: ``` RFFLFRFMFLFRFLFF ``` Which solves the map above. Notes: * If your program outputs a solution which hits predators, game over. * If you hit impassable jungle, you just bounce back to where you were before you ran into dense jungle, facing the same way. (Toward the jungle) * Julian starts facing upwards. (^ That way ^) * The output doesn't have to be the fastest solution, `FFF` and `FBFBFBFBFBFFF` are the same. **However, outputting the fastest possible solution gives a -10% byte count bonus.** * If a map is invalid, STDOUT 'Invalid map.' (That includes if the map is unsolvable) * A map cannot have rows or columns of different lengths; that makes it invalid. Your answer should somewhat follow this format: ``` #Language name, *n* bytes code Explanation (optional) ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # Groovy, 656 bytes That was too long... ``` i={println"Invalid map." System.exit(1)} m=[] q=System.in.newReader() r=q.readLine() while(r!=''){m<<r r=q.readLine()} o=m[0].size() m.each{if(it.size()!=o)i()} f=[0]*4 m.eachWithIndex{l,n->s=l.indexOf('S') e=l.indexOf('E') if(s!=-1){f[0]=s;f[1]=n} if(e!=-1){f[2]=e;f[3]=n}} v=[] t={x,y,d->if(d.contains([x,y])|y>=m.size()|x>=o|x<0|y<0)return a=m[y][x] def p=d+[[x,y]] if(a=='E')v=p if(a=='J'|a=='0'|a=='S'){t(x-1,y,p) t(x+1,y,p) t(x,y+1,p) t(x,y-1,p)}} t(f[0],f[1],[]) if(!v)i() o=0 p='' v.inject{t,s-> c=m[s[1]][s[0]] k=[t[0]-s[0],t[1]-s[1]] z=[[0,1]:0,[1,0]:1,[0,-1]:2,[-1,0]:3][k] p+=((((o-z)==0)?'':(z>0?'R':'L'))+(c=='J'?'M':'')+'F') o=z s} println p ``` Output for the maze: ``` RFFLFRFMFLFRFLFF ``` Ungolfed: ``` invalid = { println "Invalid map." System.exit(1) } map = """01001E 010110 000P00 1110J1 S00111""".split('\n') //map = [""]// TODO remove this, this is type checking only //map.remove(0) //reader = System.in.newReader() //line = reader.readLine() //while (line != '') { // map << line.replace('P','1') // line = reader.readLine() //} size = map[0].size() map.each {if(it.size() != size) invalid()} startAndEnd = [0,0,0,0] map.eachWithIndex {it, idx -> s=it.indexOf('S');e=it.indexOf('E'); if(s!=-1){ startAndEnd[0]=s; startAndEnd[1]=idx} if(e!=-1){ startAndEnd[2]=e; startAndEnd[3]=idx}} def validPath = [] testMove = {x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree if (visited.contains([x,y]) || y>=map.size() || x>=size || x<0 || y<0) return; def valueAtPos = map[y][x] def newPath = visited + [[x,y]] if (valueAtPos == 'E') validPath = newPath if ((valueAtPos == 'J' || valueAtPos == '0' || valueAtPos == 'S') && !validPath) { testMove(x-1, y, newPath) testMove(x+1, y, newPath) testMove(x, y+1, newPath) testMove(x, y-1, newPath) } } if (!validPath) invalid() testMove(startAndEnd[0],startAndEnd[1], []) println validPath orintation = 0 path = '' validPath.inject {first, second -> def chr = map[second[1]][second[0]] def sub = [first[0]-second[0],first[1]-second[1]] println "acc:$first, second:$second" def newOrin = [[0,1]:0, [1,0]:1, [0,-1]:2, [-1,0]:3][sub] path += ((((orintation - newOrin)==0)?'':(newOrin>0?'R':'L')) + (chr=='J'?'M':'') + 'F') orintation = newOrin second } println "path: $path" ``` I will try this again in python soon to see if I can shorten it further. ]
[Question] [ Write an algorithm to interpret a sequence of letters as a Roman numeral. (see roman numeral rules below) Each distinct letter has a matching Arabic decimal value, no maximum. But you don't have the key beforehand, so `{A=10, I=1, X=5, ... Z=1000000}` is decided by your interpretation. # Challenge 1. Read input via `STDIN` or equivalent and write output via `STDOUT` or equivalent 2. Valid inputs are combinations of uppercase and lowercase letters i.e. matching `\[a-zA-Z]+\` 3. Input should be validated to see if the letter sequence can be interpreted as valid Roman numeral 4. If the input passes validation, valid output should be the lowest Arabic decimal interpretation and the key used i.e. `Aa` is interpreted as `4 {a=5, A=1}` **not** `6 {A=5, a=1}` **or** `9 {a=10, a=1}` **Roman Numeral Rules** 1. Only letters representing powers of ten can be repeated, maximum of three times successively and four times in total e.g. `II` `III` `XXXIX` 2. If one or more letters are placed after another letter of greater value, add that amount ``` AAaa => 22 {A=10, a=1} (20 + 2 = 22) bbAAaa => 222 {b=100, A=10, a=1} (200 + 20 + 2 = 222) ``` 3. If a letter is placed before another letter of greater value, subtract that amount ``` Aa => 4 {a=5, A=1} (5 – 1 = 4) AaA => 19 {A=10, a=1} (10 + 10 – 1 = 19) BbBaA => 194 {B=100, b=10, A=5, a=1} (100 + 100 - 10 + 5 - 1 = 194) ``` Several rules apply for subtracting amounts from Roman numerals: * Only subtract powers of ten i.e. `1, 10, 100...` **not** `5, 50, 500...` * No double subtraction therefore `18` is written as `XVIII` **not** `IIXX (10 + 10 - 1 - 1)` * Do not subtract a number from one that is more than ten times greater. You can subtract `1` from `5` **or** `10` but **not** from `50, 100, 500...` # Example **`Input:`** ``` Aa BAa CCCXLVII MMMCDVII ABADDF XVVX FAASGSH DXCCDA AaBbcDEf ``` **`Output:`** ``` 4 {a=5, A=1} 14 {B=10, a=5, A=1} 347 {C=100, L=50, X=10, V=5, I=1} 347 {M=100, D=50, C=10, V=5, I=1} 1921 {A=1000, B=100, D=10, F=1} 'XVVX' failed Roman numeral test 7191 {F=5000, A=1000, S=100, G=10, H=1} 'DXCCDA' failed Roman numeral test 4444 {a=5000, A=1000, b=500, B=100, D=50, c=10, f=5, E=1} ``` [Answer] # Python 2, ~~415~~ ~~444~~ ~~440~~ ~~419~~ 416 bytes There aren't all that many Roman numerals, after all. This script creates all of them and checks all permutations of the input, then returns the smallest match. ``` a=raw_input() g=range b=list(set(a))+[' ']*9 from itertools import* c=[] s={} u=1000 for i in g(10*u): t,f=(10*u,9*u,5*u,4*u,u,900,500,400,100,90,50,40,10,9,5,4,1),i;r="" for j in g(17):k=i/t[j];r+=('W MW Q MQ M CM D CD C XC L XL X IX V IV I').split()[j]*k;i-=t[j]*k s[r]=f for i in permutations(b[:9]): r='' for j in a:r+='IVXLCMQWE'[i.index(j)] if r in s:c+=[s[r]] print c and min(c)or'%s failed Roman numeral test'%a ``` ]
[Question] [ Your task is to play the roles of **both** characters in [this scene](https://www.youtube.com/watch?v=V3-a58Wt2tk&t=41) from Inception. In it, Cobb gives Ariadne a challenge: > > You have two minutes to design a maze that takes one minute to solve. > > > Some liberties will be taken on that description. Most importantly, this challenge is not time-based, rather scores are based on the effectiveness of your mazes and maze-solvers. *I apologize for the many edits to this challenge as we iterate towards an easy and fair format..* ### Part I: Maze format All mazes are square. A cell in the maze is represented as a zero-indexed tuple `row column`. Walls are represented by two binary strings: one for horizontal walls (which block movement between rows) and vertical walls (vice versa). On an `NxN` maze, there are `Nx(N-1)` possible walls of each type. Let's take a 3x3 example where the cells are labelled: ``` A B | C --- D | E F --- G H | I ``` all possible vertical walls are: `AB BC DE EF GH HI`. Translated into a string, the walls shown are `011001` for vertical walls and `010010` for horizontal walls. Also, by "binary string" I mean "the characters '0' and '1'". The full maze format is a string which contains, in this order: * width * start cell tuple * end cell tuple * horizontal walls * vertical walls For example, this maze: ``` 0 1 2 3 4 _________ 0 | | E| _| 1 | _|_|_ | 2 |_ _ _ | | 3 | _ _ | | 4 |____S|___| start:(4,2) end:(0,2) ``` is formatted to this: ``` 5 4 2 0 2 00001011101110001100 10100110000100010010 ``` ### Part II: The Architect The Architect program creates the maze. It must play by the rules and provide a valid maze (one where a solution exists, and the end is not on top of the start). **Input:** Two positive integers: ``` size [random seed] ``` Where `size` will be in `[15, 50]`. You are encouraged to make use of the random seed so that matches can be replayed, although it is not required. **Output:** A valid size x size (square) maze using the format described in Part I. "valid" means that a solution exists, and the start cell is not equal to the end cell. The score of an Architect on a given maze is ``` # steps taken to solve ––––––––––––––––––––––––––––– max(dist(start,end),(# walls)) ``` So architects are rewarded for complex mazes, but penalized for each wall built (this is a substitute for Ariadne's time restriction). The `dist()` function ensures that a maze with no walls does not get an infinite score. The outside borders of the maze do not contribute to the wall count. ### Part III: The Solver The Solver attempts to solve mazes generated by others' architects. There is a sort of fog-of-war: only walls adjacent to visited cells are included (all others are replaced with '?') **input:** the same maze format, but with '?' where walls are unknown, an extra line for the current location, and a comma-separated list of valid choices from this location. (This is a big edit that is meant to make it simpler to write a maze-parsing function) example (same as the above 5x5 maze after taking one step left) ``` 5 4 2 0 2 ???????????????011?? ????????????????001? 4 1 4 0,4 2 ``` Which corresponds something like this, where `?` is fog: ``` 0 1 2 3 4 _________ 0 |????E????| 1 |?????????| 2 |?????????| 3 | ?_?_????| 4 |__C_S|_?_| ``` **output:** One of the tuples from the list of valid choices Each Solver's score is the inverse of the Architect's score. ### Part IV: King of the Hill Architects and Solvers are given separate scores, so there could potentially be two winners. Each pair of architects and solvers will have many chances to outwit each other. Scores will be averaged over all tests and opponents. Contrary to code golf conventions, highest average score wins! I intend for this to be ongoing, but I can't guarantee continued testing forever! Let's say for now that a winner will be declared in one week. ### Part V: Submitting * I maintain veto power over all submissions - cleverness is encouraged, but not if it breaks the competition or my computer! (If I can't tell what your code does, I will probably veto it) * Come up with a name for your Architect/Solver pair. Post your code along with instructions on how to run it. Coming soon: an updated python test kit for the new format. Big changes happened to allow any language submissions. [Answer] # BuildFun and SolveFun Well, this took quite a while and I'm not entirely sure if the solver is cheating or not. While it has access to the entire maze all of the time, it only looks at the cell it's in, the walls surrounding it and, if there isn't a wall between them, the cells adjacent to it. If this is against the rules please let me know and I'll try to change it. Anyway, here's the code: ``` #Architect function def BuildFun(size,seed): #Initialise grid and ensure inputs are valid if size<15:size=15 if size>50:size=50 if seed<4:seed=4 if seed>size:seed=size grid=[] for x in range(size): gridbuilder=[] for y in range(size):gridbuilder.append([0,1,1]) grid.append(gridbuilder) coords=[0,0] grid[0][0][0]=1 #Generate maze while 1: #Choose a preffered direction based on location in grid and seed pref=((((coords[0]+coords[1]+2)*int(size/2))%seed)+(seed%(abs(coords[0]-coords[1])+1)))%4 #Find legal moves opt=[] if coords[0]>0:opt+=[0] if grid[coords[0]-1][coords[1]][0]==0 else [] if coords[1]<size-1:opt+=[1] if grid[coords[0]][coords[1]+1][0]==0 else [] if coords[0]<size-1:opt+=[2] if grid[coords[0]+1][coords[1]][0]==0 else [] if coords[1]>0:opt+=[3] if grid[coords[0]][coords[1]-1][0]==0 else [] #There are legal moves if len(opt)>0: moved=False while not moved: #Try to move in preffered direction if pref in opt: if pref==0: coords[0]-=1 grid[coords[0]][coords[1]][0]=1 grid[coords[0]][coords[1]][2]=0 elif pref==1: grid[coords[0]][coords[1]][1]=0 coords[1]+=1 grid[coords[0]][coords[1]][0]=1 elif pref==2: grid[coords[0]][coords[1]][2]=0 coords[0]+=1 grid[coords[0]][coords[1]][0]=1 else: coords[1]-=1 grid[coords[0]][coords[1]][0]=1 grid[coords[0]][coords[1]][1]=0 moved=True #Change preferred direction if unable to move else: pref+=1 if pref==4:pref=0 #There aren't legal moves else: moved=False #Return to a previously visited location if not moved: try: if grid[coords[0]-1][coords[1]][0]==1 and grid[coords[0]-1][coords[1]][2]==0: grid[coords[0]][coords[1]][0]=2 coords[0]-=1 moved=True except:pass if not moved: try: if grid[coords[0]][coords[1]+1][0]==1 and grid[coords[0]][coords[1]][1]==0: grid[coords[0]][coords[1]][0]=2 coords[1]+=1 moved=True except:pass if not moved: try: if grid[coords[0]+1][coords[1]][0]==1 and grid[coords[0]][coords[1]][2]==0: grid[coords[0]][coords[1]][0]=2 coords[0]+=1 moved=True except:pass if not moved: try: if grid[coords[0]][coords[1]-1][0]==1 and grid[coords[0]][coords[1]-1][1]==0: grid[coords[0]][coords[1]][0]=2 coords[1]-=1 moved=True except:pass #Check if finished fin=True for x in grid: for y in x: if y[0]==0: fin=False break if not fin:break if fin:break for x in grid: for y in x: y[0]=0 #Find positions for start and finish such that the route between them is as long as possible lsf=[[0,0],[0,0],0] for y in range(size): for x in range(size): #Check all start positions lengths=[] coords=[[y,x,4,0]] while len(coords)>0: #Spread tracers out from start to the rest of the maze for coord in coords: opt=[] if coord[0]>0:opt+=[0] if grid[coord[0]-1][coord[1]][2]==0 else [] opt+=[1] if grid[coord[0]][coord[1]][1]==0 else [] opt+=[2] if grid[coord[0]][coord[1]][2]==0 else [] if coord[1]>0:opt+=[3] if grid[coord[0]][coord[1]-1][1]==0 else [] try:opt.remove(coord[2]) except:pass #Dead end, tracer dies and possible end point is recorded along with length if len(opt)==0: lengths.append([coord[0],coord[1],coord[3]]) coords.remove(coord) else: #Create more tracers at branch points while len(opt)>1: if opt[0]==0:coords.append([coord[0]-1,coord[1],2,coord[3]+1]) elif opt[0]==1:coords.append([coord[0],coord[1]+1,3,coord[3]+1]) elif opt[0]==2:coords.append([coord[0]+1,coord[1],0,coord[3]+1]) else:coords.append([coord[0],coord[1]-1,1,coord[3]+1]) del opt[0] if opt[0]==0: coord[0]-=1 coord[2]=2 coord[3]+=1 elif opt[0]==1: coord[1]+=1 coord[2]=3 coord[3]+=1 elif opt[0]==2: coord[0]+=1 coord[2]=0 coord[3]+=1 else: coord[1]-=1 coord[2]=1 coord[3]+=1 #Find furthest distance and, if it's longer than the previous one, the start/end positions get updated lengths=sorted(lengths,key=lambda x:x[2],reverse=True) if lengths[0][2]>lsf[2]:lsf=[[y,x],[lengths[0][0],lengths[0][1]],lengths[0][2]] #Find number of walls and output maze w=draw(grid,size,lsf[0],lsf[1]) #Output maze information print('Start = '+str(lsf[0])) print('End = '+str(lsf[1])) print('Distance = '+str(lsf[2])) print('Walls = '+str(w)) print('Score = '+str(float(lsf[2])/float(w))[:5]) #Convert array grid to binary strings horizontal and vertical horizontal=vertical='' for y in range(size): for x in range(size-1):vertical+=str(grid[y][x][1]) for y in range(size-1): for x in range(size):horizontal+=str(grid[y][x][2]) #Save maze information to text file for use with SolveFun save=open('Maze.txt','w') save.write(str(size)+'\n'+str(lsf[0][0])+' '+str(lsf[0][1])+'\n'+str(lsf[1][0])+' '+str(lsf[1][1])+'\n'+horizontal+'\n'+vertical) save.close() #Solver function def SolveFun(): try: #Get maze information from text file save=open('Maze.txt','r') data=save.readlines() save.close() size=int(data[0]) s=data[1].rsplit(' ') start=[int(s[0]),int(s[1])] e=data[2].rsplit(' ') end=[int(e[0]),int(e[1])] horizontal=data[3].rstrip('\n') vertical=data[4] #Build maze from information grid=[] for y in range(size): grid.append([]) for x in range(size): grid[y].append([0,1,1]) for y in range(size): for x in range(size-1): grid[y][x][1]=int(vertical[y*(size-1)+x]) for y in range(size-1): for x in range(size): grid[y][x][2]=int(horizontal[y*size+x]) path='' cpath='' bs=0 pos=start[:] grid[pos[0]][pos[1]][0]=1 while pos!=end: #Want to move in direction of finish if end[0]<pos[0] and pos[0]-end[0]>=abs(pos[1]-end[1]):pref=0 elif end[1]>pos[1] and end[1]-pos[1]>=abs(pos[0]-end[0]):pref=1 elif end[0]>pos[0] and end[0]-pos[0]>=abs(pos[1]-end[1]):pref=2 else:pref=3 #Find legal moves opt=[] if pos[0]>0: if grid[pos[0]-1][pos[1]][2]==0:opt+=[0]if grid[pos[0]-1][pos[1]][0]==0 else[] if pos[1]>0: if grid[pos[0]][pos[1]-1][1]==0:opt+=[3]if grid[pos[0]][pos[1]-1][0]==0 else[] if grid[pos[0]][pos[1]][2]==0:opt+=[2]if grid[pos[0]+1][pos[1]][0]==0 else[] if grid[pos[0]][pos[1]][1]==0:opt+=[1]if grid[pos[0]][pos[1]+1][0]==0 else[] if len(opt)>0: moved=False while not moved: #Try to move in preferred direction if pref in opt: if pref==0: pos[0]-=1 path+='0' cpath+='0' elif pref==1: pos[1]+=1 path+='1' cpath+='1' elif pref==2: pos[0]+=1 path+='2' cpath+='2' else: pos[1]-=1 path+='3' cpath+='3' grid[pos[0]][pos[1]][0]=1 moved=True #Change preferred direction by 1 else: pref=(pref+1)%4 #No legal moves, backtrack else: bs+=1 grid[pos[0]][pos[1]][0]=2 if int(cpath[len(cpath)-1])==0: pos[0]+=1 path+='2' elif int(cpath[len(cpath)-1])==1: pos[1]-=1 path+='3' elif int(cpath[len(cpath)-1])==2: pos[0]-=1 path+='0' else: pos[1]+=1 path+='1' cpath=cpath[:len(cpath)-1] #Output maze with solution as well as total steps and wasted steps draw(grid,size,start,end) print('\nPath taken:') print(str(len(path))+' steps') print(str(bs)+' backsteps') print(str(bs*2)+' wasted steps') except:print('Could not find maze') def draw(grid,size,start,end): #Build output in string d d=' ' for x in range(size):d+=' '+str(x)[0] d+='\n ' for x in range(size):d+=' ' if len(str(x))==1 else ' '+str(x)[1] d+='\n '+'_'*(size*2-1) w=0 for y in range(size): d+='\n'+str(y)+' |' if len(str(y))==1 else '\n'+str(y)+' |' for x in range(size): if grid[y][x][2]: if start==[y,x]:d+=UL.S+'S'+UL.E elif end==[y,x]:d+=UL.S+'F'+UL.E elif grid[y][x][0]==1:d+=UL.S+'*'+UL.E else:d+='_' w+=1 else: if start==[y,x]:d+='S' elif end==[y,x]:d+='F' elif grid[y][x][0]==1:d+='*' else:d+=' ' if grid[y][x][1]: d+='|' w+=1 else:d+=' ' #Output maze and return number of walls print(d) w-=size*2 return w #Underlines text class UL: S = '\033[4m' E = '\033[0m' ``` I realise that this is ridiculously long and not particularly easy to read, but I'm lazy so this is how it's staying. # BuildFun The architect, BuildFun, is a fairly simple maze generating program that will always create a 'perfect' maze (one with no loops and where any two points will always have exactly one path between them). It bases its logic off of the seed input meaning that the mazes generated are pseudo-random with what often appear to be repeating patterns and, with the same seed and size, the same maze will be created. Once the maze is generated, the program will attempt to maximise the maze's score by searching for the start point and end point that result in the longest path between them. To do this, it runs through every start point, spreads out tracers to find the end point furthest from it, and picks the combination with the longest path. After this, it draws the maze, counts the walls and outputs the maze's information. This is the start point, end point, distance between them, number of walls and score. It also formats this information into the style described above for size, start and end, horizontal walls and vertical walls and saves this into a text file called Maze.txt for use later. # SolveFun The solver, SolveFun, uses the text file Maze.txt as the input and works in a very similar way to the architect. For every move, it will choose a direction that it wants to go based on its relative position to the end and then it will look at the walls surrounding it. If a wall is not there, it will check to see if it has been in the cell adjacent to it and, if not, it will be added as possible option. It will then move in the direction closest to its preferred direction provided it has options. If it doesn't have options, it will backtrack until it does. This continues until it reaches the end. As it moves, it records the path it is taking in the variable path which is used at the end to output the total number of steps. It also records the amount of times it had to backtrack used to calculate wasted steps at the end. When it reaches the end, it will output the maze with the shortest path from start to end marked on with `*`s. # How to Run Due to the method of outputting the maze (which includes underlining certain characters), this has to be run from a command line in the form `python -c 'import filename;filename.BuildFun(Size, Seed)'` and `python -c 'import filename;filename.SolveFun()'` where Size is an integer between 15 and 50 (inclusive) and Seed is an integer between 4 and Size (inclusive). ]
[Question] [ Key Links * [Dwarf question](https://codegolf.stackexchange.com/questions/230965/play-thud-dwarf-edition) * [Chat room](https://chat.stackexchange.com/rooms/127179/thud-challenge) * [Game](https://ajfaraday.github.io/Thud/dist/index.html) * [Controller Interface](https://github.com/AJFaraday/Thud/blob/main/docs/controller_interface.md) Troll league table ``` <script src="https://ajfaraday.github.io/Thud/dist/data/tables.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table> <thead> <tr> <th>Client</th> <th>Wins</th><th>Loses</th> <th>Score</th> </tr></thead> <tbody id="clients"> </tbody></table><script type='text/javascript'> league_table.troll.forEach( function(data_row){var row=$('<tr>'); var cell=$('<td>'); cell.html(data_row.name.substring(6)); row.append(cell); cell=$('<td>'); cell.html(data_row.win); row.append(cell); cell=$('<td>'); cell.html(data_row.lose); row.append(cell);row.append(cell);cell=$('<td>'); cell.html(data_row.score); row.append(cell); $('tbody#clients').append(row);});</script> ``` *Thud* is a game described by Terry Pratchett in his novel, *Thud!* The game simulates a battle between the Dwarfs (in blue) and the Trolls (in green) on an octagonal board with the Thudstone (an impassable space) in the centre of the board. [![Thud board in starting positions](https://i.stack.imgur.com/l2CKL.png)](https://i.stack.imgur.com/l2CKL.png) I have created an environment to play the game and create your automated player at: <https://ajfaraday.github.io/Thud/dist/index.html> The challenge is to write the most successful troll player of this game (these will be two separate challenges). # Rules Starting with the dwarf player, players take it in turns to move. ## Dwarf Movement On the dwarf player's turn, they can move one dwarf piece either as a walk or a hurl. *Walk*: Dwarfs can move as far as they like in any direction until they hit an obstacle (another dwarf, the edge of the board, or a troll). They can only kill a troll by walking if they are only one space away. *Hurl*: If two or more dwarfs are in a line (horizontal, vertical or diagonal), they can hurl the dwarf on the end of the line, by the length of the line (e.g. in a line of 3, the dwarf on the end can be hurled 3 spaces). If a dwarf is hurled into a troll, the troll is killed, reducing the troll player's score by 4 points. ## Troll Movement On the Troll player's turn they can move one troll piece, either as a walk or a shove. *Walk*: Trolls can move one space in any direction, unless a troll, dwarf or the edge of the board is in the way. Whenever a troll moves, it kills all dwarfs adjacent to its destination space. *Shove*: If two or more trolls are in a line (horizontal, vertical or diagonal) they can shove the troll at the end of the line that number of spaces away, but *only* if any of the target space's immediate neighbours contain a dwarf. When a troll is shoved, it kills all dwarfs on or adjacent to it's destination space. A troll may not land directly on a dwarf by either walk or shove moves. Each dwarf killed reduces the dwarf player's score by 1 point. ## Scores The score is calculated thus: * The dwarf player has one point for every dwarf remaining on the board. * The troll player has four points for every troll remaining on the board. * The key figure is the difference between these two. This will be used to calculate players' scores in the tournament. ## Ending the game The game ends when any of these conditions is met: * There are no dwarfs on the board. * There are no trolls on the board. * Both players have declared the game over. * The game has reached its cut-off length of 500 moves. # How to manually play a game * Go to <https://ajfaraday.github.io/Thud/dist/index.html> * Hover the mouse over a piece to see it's available moves. * Click on a piece to select it for the current move. * Click on one of the available moves to move the piece. * (You can click the relevant 'Make Peace' button to declare the game over according to that player, during their turn) # How to set up a local instance of the game You don't have to clone the repository and use it locally to make the game work, or to create an entry, but it helps. * `git clone https://github.com/AJFaraday/Thud.git` * `cd Thud` * `npm install` * You can then call `node script/get_clients.js` to get the latest entries from Stack Exchange If you prefer, you can use the github pages instance at <https://ajfaraday.github.io/Thud/dist/index.html> # How to customize a game * Open /dist/index.html in your browser * Click 'Customize' * Select troll and dwarf clients (manual allows direct control) * Select a turn time in milliseconds (only relevant to non-manual players) * Click 'Run Game' to see or play the game. * (Clicking 'Close' will not enact any changes) # Clients The game is played by clients, which represent either a troll or a dwarf player. Each is a JavaScript class which must have these three functions: * `constructor(controller)` - controller is an object which acts as your interface with the game (see below). * `turn()` - This is called whenever it is your players turn to move. * `end_turn()` - This is called after your player's turn is over. It can not move pieces, but can make decisions on whether or not to declare the game over. ## Controller The `controller` object is your client's interface with the game itself. You can find full documentation for the controller class here: <https://github.com/AJFaraday/Thud/blob/main/docs/controller_interface.md> It provides these functions to interrogate the state of the game: * `turn()` - Current turn of the game * `scores()` - The current score * `spaces()` - Every space, and what's in it * `space_info(x, y)` - Detailed information on any space on the board. * `dwarfs()` - The location of every dwarf * `trolls()` - The location of every troll * `pieces()` - All pieces belonging to the current player (equivalent of `dwarfs()` or `trolls()`) * `indexed_dwarfs()` - The location of every dwarf with a fixed index * `indexed_trolls()` - The location of every troll with a fixed index * `previous_move()` - What got moved to where last turn * `killing_moves()` - All moves which can kill one or more opponent * `current_space` - Currently selected space (not a function) * `clear_space()` - Empties currently selected space These functions are used to actually make your move: * `check_space(x, y)`- Find out what moves are available from a given space * `select_space(x, y)` - The player decides to move a piece at space. * `check_move(x, y)` - Find out what will happen if you move to a place * `move(x, y)` - The player moves the current piece to the selected space. These are concerned with ending the game: * `declare(game_over)` - Say whether or not your player thinks the game is over. * `opponent_declared()` - Has the opponent declared the game over? Your client will also have a `utils` object which will provide these helpful geometry functions: * `utils.distance_between(source, target)` - The square distance between two objects which respond to x and y * `utils.farthest_from(spaces, target)` - From an array of spaces (with x and y), choose the farthest from target (with x and y) * `utils.closest_to(spaces, target)` - From an array of spaces (with x and y), choose the closest to target (with x and y) # How to write a client Warning: There is an issue with the project on Firefox (<https://github.com/AJFaraday/Thud/issues/3>) which prevents editing the code in the browser. This has been confirmed to work in Chrome. * Open 'dist/index.html' in your browser. * Click 'Customize'. * Select 'dwarf/template' as the Dwarf player (or use another client as a starting point). * Click 'Edit' beside the Dwarf player select. * Write your client code in the text box provided. * The Validate button will change colour based on whether or not the client is passes validations (see below). * When you're happy with it, click 'Apply' (This can be done before it passes validation, but it may not actually work). * Select a worthy opponent and click 'Run Game' to see the game. ## Validations In order for a client to work, and therefore be enterable in the challenge, it has to pass these validations: * It must evaluate as Javascript code. * The code must return a class with a constructor which accepts one argument. * Instances of this class should have functions named `turn()` and `end_turn()` * The client must play a game until it is over (i.e. it must call a valid `move` during every `turn` call). The validator will run games against default opponents to determine if this happens. * Does not have any forbidden terms + `game.` - Only interact with the game via controller + `Math.random` - Please keep it deterministic + `setTimeout` or `setInterval` - Keep it sequential + `eval`, `require` or `import` - Just don't You can open the developer console (F12) to see more detailed information on your client's validation process. ## How to save a client If you have cloned the git repository, you can save your entry for future tinkering. This step is not required for entry in the challenge, but it may be helpful. * Edit a client, as above. * When you're happy with it (preferably if it's passing validation, too), click 'Copy' from the edit interface. * Create a .js file in `/src/clients/dwarf/entry` with the name of your entry e.g. `/src/clients/dwarf/entrygreat_dwarf_player.js`. (This folder will not be wiped by `get_clients.js`) * Run `node script/get_clients.js` from the Thud directory to make your entry available from the Dwarf player select. You only need to do this once to make it avilable. * `npm run build` - this will keep watching for changes in your entry and updating the package. ## How to enter your client in the competition * Decide on the name of your client, your client\_name must only have alpha characters and underscores. * Answer this question with your entry + The first line of your answer should be your client's name as a title (with = characters under it on the second line) + There should be a code block containing the class for your entry (with or without the preceeding `module.exports =`) + After that please include a brief explanation of your client's behaviour, and any other information you'd like to include. Once this is in place, anyone running `./get_answers.sh` will see your client available under your username. The GitHub Pages instance will also be updated periodically, so by making an entry, your code will be added to the repo. # Tournament rules The tournament will pit every available dwarf client (in `/src/clients/dwarf/`) against every available troll client (in `/src/clients/troll/`), and each pairing will play exactly one game. The *difference* between the two players' scores will then update a running total for each client. The winner will gain the difference, and the loser will lose the difference. There are two winners in the tournament: the most successful troll player and the most successful dwarf player. # Seeing the result of the tournament You can use the 'League Table' button to see the overall results of the clients. If you click on a client, you will see all the matches for that client. You can use the 'Matches' button to see the result of all matches. If you click on a match, the game will replay the match for you. You can change the select at the bottom of the screen to highlight specific clients. To rerun the tournament (including changes on Stack Exchange and your own entries in /src/clients/dwarf/entry) you can run `.get_answers.sh`. This will update the 'League Table' and 'Matches' screens. --- According to the rules, after playing a game, the players swap sides, so please also write an entry on the [dwarf challenge](https://codegolf.stackexchange.com/questions/230965/play-thud-dwarf-edition). ]
[Question] [ # What is a Word Signature? The signature of a word are all of it's letters put in order - the signatures of `this`, `hist` and `hits` are all `hist`. # The Challenge Write a program program should ask for an input, then print out the signature of that word. So an example program run might look like this: ``` Give me a string: this The signature signature of 'this' is hist. ``` There is no required interaction, as long as it takes an input and prints the signature, it is OK. # Scoring The program with the smallest byte count wins! # Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` var QUESTION_ID=54945;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table> ``` **Challenged Finished!** **WINNER: [jimmy23013](https://codegolf.stackexchange.com/a/54947/42003)** [Answer] # GolfScript, 1 byte ``` $ ``` Yes, only 1 byte. [Try it here.](http://golfscript.apphb.com/?c=OyJ0aGlzIiAjIE92ZXJyaWRlIHN0ZGluCgok) [Answer] # C (with x86), 61 bytes ``` s[];main(){qsort(s,read(0,s,99),1,"YXZQQQ\x8a\x00*\x02\x0f\xbe\xc0\xc3");puts(s);} ``` That string contains raw bytes, not actual `\x..` codes, and it's a *raw machine code callback* passed to `qsort`. Works on x86 only: ``` 59 pop ecx 58 pop eax 5a pop edx 51 push ecx 51 push ecx 51 push ecx 8a 00 mov al, BYTE PTR [eax] 2a 02 sub al, BYTE PTR [edx] 0f be c0 movsx eax, al c3 ret ``` Which is essentially: ``` int func(char *a, char *b) { return *a - *b; } ``` See p6-7 of this [pamphlet in Japanese by shinh](http://shinh.skr.jp/dat_dir/golf_prosym.pdf). [Answer] # Stuck, 4 bytes ``` sc$d ``` [This language](http://esolangs.org/wiki/Stuck) was documented on the wiki just yesterday! Mmm, fresh esolangs. [Answer] # Stuck, 5 Bytes I finally get to use my language, [Stuck](https://esolangs.org/wiki/Stuck)! :D ``` s$""j ``` This takes an input via stdin, sorts, joins, and implicitly prints. This did give me some ideas for changes though. **Edit:** Oh wow, someone already posted and beat me in my own language! [Answer] # GOTO++, ~~432~~ 430 bytes [GOTO++ project site](http://www.gotopp.org/). ``` niveaugourou 0 s=ENTRETONTEXTE() §2 a=LeCaracNumero()&s *(1) n=*(1) costaud i=*(2)/&i infeg NombreDeLettres(&s)/i=+*(1) b=LeCaracNumero()&s &i GOTONULPOURLESNULS %1 }&b inf &a{ a=&b n=&i §1 faiblard GOTOPRINTDUTEXTE()&a t=PrendsUnMorceau()&s *(0) &n u=PrendsUnMorceau()&s }&n+*(1){ *(0) e=BOITEAPINGOUINS()&t &u s=Marijuana()&e «» GOTONONNULPOURLESNULS %3 }NombreDeLettres(&s) eg *(1){ GOTOPASMALIN %2 §3 GOTOPRINTDUTEXTE()&s ``` Not sure why I inflicted this to myself, but I did [Answer] # gs2, 1 byte ``` / ``` Same as the GolfScript answer, but [gs2](https://github.com/nooodl/gs2) uses a different operator for sorting. [Answer] # Perl, 18 bytes ``` print sort<>=~/./g ``` Thanks to Dom Hastings for helping me save 3 bytes. [Answer] # Haskell, 35 bytes ``` import Data.List;main=interact sort ``` [Answer] # J, 3 bytes ``` /:~ ``` For example: `/:~'this'` [Answer] ## Pyth, 2 bytes ``` Sw ``` [DEMO HERE.](https://pyth.herokuapp.com/?code=Sw&input=this&debug=0) Details- ``` S - for sorting w - Python 3's input() ``` [Answer] # C#, ~~114~~ 110 characters Takes input from a command line argument. Not a very short program, but well... it's C#. :P ``` namespace System.Linq{class P{static void Main(string[]a){Console.Write(string.Concat(a[0].OrderBy(x=>x)));}}} ``` Thanks to Abbas for saving 4 bytes! [Answer] # Brainfuck, 40 bytes ``` ,[>>+>>,]<<[[<<]>>[-[<]>>[.<<->]>+>>]<<] ``` This uses the [counting sort algorithm](https://en.wikipedia.org/wiki/Counting_sort), which makes this an **O(n)** solution. The code requires a left-infinite or wrapping tape of 8 bit cells. [Try it online!](http://brainfuck.tryitonline.net/#code=LFs-Pis-PixdPDxbWzw8XT4-Wy1bPF0-PlsuPDwtPl0-Kz4-XTw8XQ&input=UHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZg) ### How it works ``` , Read a char from STDIN. [ While the byte under the pointer (last read char) is non-zero: >>+ Move the pointer two steps to the right and increment. >>, Move the pointer two steps to the right and read a char. ] << Move the pointer two steps to the left. If the input was "sort", the tape now contains the following: 0 0 115 0 1 0 111 0 1 0 114 0 1 0 116 0 1 0 0 ^ [ While the byte under the pointer is non-zero: [<<] Advance two steps to the left until a null byte is encountered. >> Advance two steps to the right. This will place the pointer on the first input character. [ While the byte under the pointer is non-zero: - Decrement. [<] Move the pointer to the left until a null byte is encountered. >> Move the pointer two steps to the right. If the decremented character is non-zero, [<] will move to the null byte before it, so >> brings the pointer to the null byte after it. If the decremented character is zero, [<] is a no-op, so >> advances two steps to the right, to a non-zero byte. [ While the byte under the pointer is non-zero: . Print the char under the pointer. <<- Move the pointer two steps to the left and decrement. > Move the pointer to the right. ] If the decremented character gave zero, this will print the value of the accumulator after it, and decrement the character once more to make it non-zero, then place the pointer to the right of the character, thus exiting the loop. >+ Move the pointer to the right and increment. This increments the accumulator each time an input character is decremented. >> Move the pointer two steps to the right. This moves the pointer to the next character. ] << Move the pointer two steps to the left. This moves the pointer to the accumulator of the last character. ] After 255, th accumulator wraps around to 0, and the loop ends. ``` [Answer] # CJam, 2 bytes ``` l$ ``` Reads a line of input (`l`) and sorts it (`$`). [Answer] ## Python 3, 31 Bytes ``` print("".join(sorted(input()))) ``` [Answer] ## Coreutils, 24 23 ``` fold -w1|sort|tr -d \\n ``` [Answer] # Ruby, 17 bytes ``` $><<$<.chars.sort ``` [Answer] # Java 8, 119 bytes This is basically only competitive with the C# answer, because, well, Java. (At least this beats GOTO++. Not really an accomplishment...) ``` class C{public static void main(String[]s){s=s[0].split("");java.util.Arrays.sort(s);System.out.print("".join("",s));}} ``` *Thanks to ProgramFOX for saving 1 byte, rink.attendant for saving 2 bytes.* [Answer] # Ostrich, 2 bytes ``` G$ ``` In [Ostrich](https://github.com/KeyboardFire/ostrich-lang) `G` reads a line of input from STDIN and `$` sorts it. [Answer] ## JavaScript (ES6), 32 bytes Demo only works in Firefox and Edge at time of writing, as Chrome/Opera does not support ES6 by default: Edit: I didn't look at the answers prior to posting but now I realize it's pretty much the exact same as [the one by NinjaBearMonkey](https://codegolf.stackexchange.com/a/54988/22867). ``` f=x=>alert([...x].sort().join``) ``` ``` <form action=# onsubmit='f(document.getElementById("I").value);return false;'> <input type=text pattern=\w+ id=I> <button type=submit>Sort letters</button> </form> ``` [Answer] # Julia, 21 bytes ``` s->join(sort([s...])) ``` And for fun, here's how you might do it without using an inbuilt sorting function, for 53 bytes: ``` f=s->s>""?(k=indmax(s);f(s[k+1:end]s[1:k-1])s[k:k]):s ``` [Answer] # SWI-Prolog, 34 bytes ``` a(X):-msort(X,Y),writef("%s",[Y]). ``` Called as such:`a(`this`).` [Answer] # Scala, 21 bytes ``` print(args(0).sorted) ``` run from command line example: ``` $ scala -e "print(args(0).sorted)" this hist ``` [Answer] # Powershell, ~~44~~ 37 Bytes ``` -join((Read-Host).ToCharArray()|sort) ``` [Answer] # JavaScript, 34 bytes ``` alert([...prompt()].sort().join``) ``` The reason this is so long is that JavaScript can only sort arrays, so the string must be split into an array, sorted, and then joined back into a string. This is ECMAScript 6; the equivalent in ES5 is: ``` alert(prompt().split('').sort().join('')) ``` [Answer] # Python 2, 33 32 bytes ``` print`sorted(raw_input())`[2::5] ``` Heavily inspired by @Kamehameha's answer. Converted to python 2. Can't golf much more. [Answer] # APL, 7 characters Doesn't work on ngn-apl for me, but should work in theory: ``` X[⍋X←⍞] ``` `⍞` reads a line from standard input, which is assigned to `X`. `⍋X` is the indices of `X` which yield an ascending order, and `X[...]` actually sorts `X` by these indices. [Answer] # JavaScript, 54 bytes call js file with node ``` console.log(process.argv[2].split('').sort().join('')) ``` [Answer] # Processing, 40 bytes ``` print(join(sort(args[0].split("")),"")); ``` [Answer] # Nim, ~~102~~ ~~101~~ ~~79~~ 73 bytes ``` let s=stdin.readAll for i in 1..'~': for j in s:(if i==j:stdout.write j) ``` Still learning Nim and working out golf tricks. Apparently it's better *not* to use the builtin `sort`, which would require a lot of imports (thanks @Mauris) [Answer] ## PowerShell, 27 bytes ``` %{([char[]]$_|sort)-join''} ``` ]
[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/22971/edit). Closed 4 years ago. [Improve this question](/posts/22971/edit) This is a really neat short challenge. Write a function or a procedure that takes two parameters, `x` and `y` and returns the result of `xy` WITHOUT using loops, or built in power functions. **The winner is the most creative solution, and will be chosen based on the highest number of votes after 3 days.** [Answer] ## APL (7) ``` {×/⍵/⍺} ``` Left argument is base, right argument is exponent, e.g.: ``` 5 {×/⍵/⍺} 6 15625 ``` Explanation: * `⍵/⍺` replicates `⍺` `⍵` times, e.g. `5 {⍵/⍺} 6` -> `5 5 5 5 5 5` * `×/` takes the product, e.g. `×/5 5 5 5 5 5` -> `5×5×5×5×5×5` -> `15625` [Answer] # C#: Floating point exponents OK, this solution is quite fragile. You can easily break it by throwing ridiculously huge numbers like 6 at it. But it works beautifully for things like `DoublePower(1.5, 3.4)`, and doesn't use recursion! ``` static double IntPower(double x, int y) { return Enumerable.Repeat(x, y).Aggregate((product, next) => product * next); } static double Factorial(int x) { return Enumerable.Range(1, x).Aggregate<int, double>(1.0, (factorial, next) => factorial * next); } static double Exp(double x) { return Enumerable.Range(1, 100). Aggregate<int, double>(1.0, (sum, next) => sum + IntPower(x, next) / Factorial(next)); } static double Log(double x) { if (x > -1.0 && x < 1.0) { return Enumerable.Range(1, 100). Aggregate<int, double>(0.0, (sum, next) => sum + ((next % 2 == 0 ? -1.0 : 1.0) / next * IntPower(x - 1.0, next))); } else { return Enumerable.Range(1, 100). Aggregate<int, double>(0.0, (sum, next) => sum + 1.0 / next * IntPower((x - 1) / x, next)); } } static double DoublePower(double x, double y) { return Exp(y * Log(x)); } ``` [Answer] # C++ How about some template meta programming? It bends what little rules there were, but it's worth a shot: ``` #include <iostream> template <int pow> class tmp_pow { public: constexpr tmp_pow(float base) : value(base * tmp_pow<pow-1>(base).value) { } const float value; }; template <> class tmp_pow<0> { public: constexpr tmp_pow(float base) : value(1) { } const float value; }; int main(void) { tmp_pow<5> power_thirst(2.0f); std::cout << power_thirst.value << std::endl; return 0; } ``` [Answer] ## Python ``` def power(x,y): return eval(((str(x)+"*")*y)[:-1]) ``` Doesn't work for noninteger powers. [Answer] # Haskell - 25 chars ``` f _ 0=1 f x y=x*f x (y-1) ``` Following Marinus' APL version: ``` f x y = product $ take y $ repeat x ``` With mniip's comment and whitespace removed, 27 chars: ``` f x y=product$replicate y x ``` [Answer] # Python If `y` is a positive integer ``` def P(x,y): return reduce(lambda a,b:a*b,[x]*y) ``` [Answer] # JavaScript (ES6), 31 ``` // Testable in Firefox 28 f=(x,y)=>eval('x*'.repeat(y)+1) ``` **Usage:** ``` > f(2, 0) 1 > f(2, 16) 65536 ``` **Explanation:** The above function builds an expression which multiply `x` `y` times then evaluates it. [Answer] I'm surprised to see that nobody wrote a solution with the Y Combinator, yet... thus: # Python2 ``` Y = lambda f: (lambda x: x(x))(lambda y: f(lambda v: y(y)(v))) pow = Y(lambda r: lambda (n,c): 1 if not c else n*r((n, c-1))) ``` No loops, No vector/list operations and No (explicit) recursion! ``` >>> pow((2,0)) 1 >>> pow((2,3)) 8 >>> pow((3,3)) 27 ``` [Answer] # C# : 45 Works for integers only: ``` int P(int x,int y){return y==1?x:x*P(x,y-1);} ``` [Answer] # bash & sed No numbers, no loops, just an embarrasingly dangerous glob abuse. Preferably run in an empty directory to be safe. Shell script: ``` #!/bin/bash rm -f xxxxx* eval touch $(printf xxxxx%$2s | sed "s/ /{1..$1}/g") ls xxxxx* | wc -l rm -f xxxxx* ``` [Answer] # Javascript ``` function f(x,y){return ("1"+Array(y+1)).match(/[\,1]/g).reduce(function(l,c){return l*x;});} ``` Uses regular expressions to create an array of size y+1 whose first element is 1. Then, reduce the array with multiplication to compute power. When y=0, the result is the first element of the array, which is 1. Admittedly, my goal was i) not use recursion, ii) make it obscure. [Answer] # Mathematica ``` f[x_, y_] := Root[x, 1/y] ``` Probably cheating to use the fact that x^(1/y) = y√x [Answer] # Golfscript, 8 characters (including I/O) ``` ~])*{*}* ``` Explanation: TLDR: another "product of repeated array" solution. The expected input is two numbers, e.g. `2 5`. The stack starts with one item, the string `"2 5"`. ``` Code - Explanation - stack - "2 5" ~ - pop "2 5" and eval into the integers 2 5 - 2 5 ] - put all elements on stack into an array - [2 5] ) - uncons from the right - [2] 5 * - repeat array - [2 2 2 2 2] {*} - create a block that multiplies two elements - [2 2 2 2 2] {*} * - fold the array using the block - 32 ``` [Answer] ## Ruby ``` class Symbol define_method(:**) {|x| eval x } end p(:****[$*[0]].*(:****$*[1]).*('*')) ``` Sample use: ``` $ ruby exp.rb 5 3 125 $ ruby exp.rb 0.5 3 0.125 ``` This ultimately is the same as several previous answers: creates a y-length array every element of which is x, then takes the product. It's just gratuitously obfuscated to make it look like it's using the forbidden `**` operator. [Answer] # JavaScript ``` function f(x,y){return y--?x*f(x,y):1;} ``` [Answer] # C, exponentiation by squaring ``` int power(int a, int b){ if (b==0) return 1; if (b==1) return a; if (b%2==0) return power (a*a,b/2); return a*power(a*a,(b-1)/2); } ``` golfed version in **46 bytes** (thanks ugoren!) ``` p(a,b){return b<2?b?a:1:p(a*a,b/2)*(b&1?a:1);} ``` should be faster than all the other recursive answers so far o.O slightly slower version in **45 bytes** ``` p(a,b){return b<2?b?a:1:p(a*a,b/2)*p(a,b&1);} ``` [Answer] ## Haskell - 55 ``` pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0 ``` There's already a shorter Haskell entry, but I thought it would be interesting to write one that takes advantage of the `fix` function, as defined in `Data.Function`. Used as follows (in the Repl for the sake of ease): ``` ghci> let pow x y=fix(\r a i->if i>=y then a else r(a*x)(i+1))1 0 ghci> pow 5 3 125 ``` [Answer] # Q 9 chars. Generates array with `y` instances of `x` and takes the product. ``` {prd y#x} ``` Can explicitly cast to float for larger range given int/long x: ``` {prd y#9h$x} ``` [Answer] Similar logic as many others, in PHP: ``` <?=array_product(array_fill(0,$argv[2],$argv[1])); ``` Run it with `php file.php 5 3` to get 5^3 [Answer] I'm not sure how many upvotes I can expect for this, but I found it somewhat peculiar that I *actually* had to write that very function today. And I'm *pretty sure* this is the first time any .SE site sees [this language](http://www.abs-models.org/) (website doesn't seem very helpful atm). # ABS ``` def Rat pow(Rat x, Int y) = if y < 0 then 1 / pow(x, -y) else case y { 0 => 1; _ => x * pow(x, y-1); }; ``` Works for negative exponents and rational bases. I highlighted it in Java syntax, because that's what I'm currently doing when I'm working with this language. Looks alright. [Answer] # Pascal The challenge did not specify the type or range of x and y, therefore I figure the following Pascal function follows all the given rules: ``` { data type for a single bit: can only be 0 or 1 } type bit = 0..1; { calculate the power of two bits, using the convention that 0^0 = 1 } function bitpower(bit x, bit y): bit; begin if y = 0 then bitpower := 1 else bitpower := x end; ``` No loop, no built-in power or exponentiation function, not even recursion or arithmetics! [Answer] ## J - 5 or 4 bytes Exactly the same as [marinus' APL answer](https://codegolf.stackexchange.com/a/22986/20356). For `x^y`: ``` */@$~ ``` For `y^x`: ``` */@$ ``` For example: ``` 5 */@$~ 6 15625 6 */@$ 5 15625 ``` `x $~ y` creates a list of `x` repeated `y` times (same as `y $ x` `*/ x` is the product function, `*/ 1 2 3` -> `1 * 2 * 3` [Answer] # Python ``` from math import sqrt def pow(x, y): if y == 0: return 1 elif y >= 1: return x * pow(x, y - 1) elif y > 0: y *= 2 if y >= 1: return sqrt(x) * sqrt(pow(x, y % 1)) else: return sqrt(pow(x, y % 1)) else: return 1.0 / pow(x, -y) ``` [Answer] # Javascript With tail recursion, works if `y` is a positive integer ``` function P(x,y,z){z=z||1;return y?P(x,y-1,x*z):z} ``` [Answer] # Bash Everyone knows `bash` can do whizzy map-reduce type stuff ;-) ``` #!/bin/bash x=$1 reduce () { ((a*=$x)) } a=1 mapfile -n$2 -c1 -Creduce < <(yes) echo $a ``` --- If thats too trolly for you then there's this: ``` #!/bin/bash echo $(( $( yes $1 | head -n$2 | paste -s -d'*' ) )) ``` [Answer] # C Yet another recursive exponentiation by squaring answer in C, but they do differ (this uses a shift instead of division, is slightly shorter and recurses one more time than the other): ``` e(x,y){return y?(y&1?x:1)*e(x*x,y>>1):1;} ``` [Answer] # Mathematica This works for integers. ``` f[x_, y_] := Times@@Table[x, {y}] ``` **Example** ``` f[5,3] ``` > > 125 > > > --- **How it works** `Table` makes a list of `y` `x`'s. `Times` takes the product of all of them.` --- **Another way to achieve the same end**: ``` #~Product~{i,1,#2}& ``` **Example** ``` #~Product~{i, 1, #2} & @@ {5, 3} ``` > > 125 > > > [Answer] ## Windows Batch Like most of the other answers here, it uses recursion. ``` @echo off set y=%2 :p if %y%==1 ( set z=%1 goto :eof ) else ( set/a"y-=1" call :p %1 set/a"z*=%1" goto :eof ) ``` x^y is stored in the environment variable `z`. [Answer] ## perl Here's a tail recursive perl entry. Usage is echo $X,$Y | foo.pl: ``` ($x,$y) = split/,/, <>; sub a{$_*=$x;--$y?a():$_} $_=1; print a ``` Or for a more functional-type approach, how about: ``` ($x,$y) = split/,/, <>; $t=1; map { $t *= $x } (1..$y); print $t ``` [Answer] # Python ``` def getRootOfY(x,y): return x**y def printAnswer(): print "answer is ",getRootOfY(5,3) printAnswer() answer =125 ``` I am not sure if this is against the requirements, but if not here is my attempt. ]
[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/22473/edit). Closed 4 years ago. [Improve this question](/posts/22473/edit) Everyone knows the phrase "Rules are made to be broken!", so here is your task: Write some code in any language that breaks a standard. This can be anything, from putting 240 volts down a USB cable, to pinging your router (**NOT** somebody else's website!) with a 10mb packet! (Don't get any ideas, both of these will probably cause all sorts of doom!) The most upvoted answer after 10 days (i.e the most serious violation) will win! Rules: 1. The code must be explained. 2. The standard that you are breaking must be linked to, and you must explain what you are doing (implies 1) to break it. Otherwise answers will not be accepted. 3. Answers that just crash the interpreter, or make it stop working will not be accepted. I would like some creative answers, not just pasting something like `𐒢` into IDLE (which crashes it) 4. Exploiting bugs are not allowed, unless they break a standard. Otherwise answers will not be accepted Begin, and have fun! [Answer] ## Python ``` print 'Hello World' ``` --- Explanation: The [standard of the Programming Puzzles & Code Golf Stack Exchange](//codegolf.stackexchange.com/help/how-to-answer) is to > > Read the question carefully. What, specifically, is the question asking for? Make sure your answer provides that > > > This code is not answering the question, so it breaks the standard. [Answer] **C** Here's a factorial program that compiles and runs succcessfully (with gcc4.6.3 on Ubuntu 12.04), but invokes as much undefined behaviour according to the [C standard](http://www.open-std.org/jtc1/sc22/wg14/www/standards) as I could cram in. Most are inspired from [here](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html). A lot of the remaining legal code is just bad. ``` int read(char** src, int into){ int _r; //leading underscores reserved, and if (!--into) sscanf(*src,"%d",&into); //_r uninitalized *(*(--src)+into)=_r>>360; //shifting more bits than we have while (into-->0) (*src)[into]='.'; //modifying const char argv printf(*src); // no return statement } main(int argc, const char** const argv){ union { int x; float y;} result; int f,minus1=0xFFFFFFFF,r,a[]={0}; r=a[3]&2; //accessing past end of array result.x=read(&argv[r],--r); //relying on order of arguments for(f=*(int*)&result.y;f;f+=minus1) //type punning/invalid union access, r*=f; //and unsigned overflow printf("%d\n",(&r+2)[-2]); //negative array indexes } ``` [Answer] # XHTML ``` <p> <div></div> </p> ``` The W3C specification (<http://www.w3.org/TR/html-markup/p.html#p>): > > # p – paragraph > > > The p element represents a paragraph. > > > ## Permitted contents > > > **Phrasing content** > > > Oh I feel dirty! **Edit:** [@xfix](https://codegolf.stackexchange.com/users/3103/xfix) pointed out that the error I was displaying was actually XHTML. The HTML error this causes is cooler and less obvious such that: `<p><div></div><p>` becomes `<p /><div></div></p>` because the `<div>` causes the `<p>` to self close. Thus resulting in an error because we are attempting to close a paragraph that doesn't exist. [Answer] [HTTP/1.1: Response - Status Code and Reason Phrase](http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1) > > The Status-Code element is a 3-digit... > > > Need I go any further? This status code isn't one of the codes defined in the standard. It doesn't even begin with one of the required category digits. It's not even 3 digits long. My browser still manages to load the page fine. In addition, this answer breaks one of this site's "standards" :) Output (status line): ``` HTTP/1.1 0 :) ``` ``` var http = require("http"); var server = http.createServer(onHttpRequest); server.listen(80); function onHttpRequest(request, response) { response.writeHead(0, ":)", { "Content-Type": "text/plain" }); response.write("Hello, World!"); response.end(); } ``` ## JavaScript (Node) [Answer] How many standards did I just break? I did some awful programming indeed here. # PHP ``` a: goto lol; begin(); b: c: echo j; goto h; d: echo u; e: echo s; f: echo t; g: h: echo k; goto o; i: echo i; goto c; j: echo l; k: echo l; l: echo e; m: echo d; n: o: echo s; p: echo t; goto u; q: echo a; goto z; r: echo n; s: echo d; t: echo a; u: echo r; goto q; v: echo D; goto i; w: echo s; x: y: z: die("!"); lol: goto v; ``` **Easter Egg:** The `echo`ed letters, if read vertically, will read `just killed standarDs!`. **Sidenote:** Running this program will output the name of a guy who really loved `goto`s. [Answer] ## C# - breaking Unicode Simple algorithm to reverse a string: ``` public string Reverse(string s) { StringBuilder builder = new StringBuilder(); for (int i = s.Length - 1; i >= 0; i--) { builder.Append(s[i]); } return builder.ToString(); } ``` This breaks the [Unicode](http://www.unicode.org/) standard, because it does not correctly keep surrogate pairs together, creating an invalid string. In .NET and many other platforms/programming languages, a `char` is not really a character, but a [UTF-16](http://en.wikipedia.org/wiki/UTF-16) code unit. NB: It also changes which letter is combined with subsequent combining marks (e.g. diacritics), which may or may not be intended. [Answer] # JavaScript Run it in the console on this page. ``` var items = [], p = 1, finish = false, intr = setInterval(function() { if (p >= 10) finish = true $.get(unescape(escape('http://api.stackexchange.com/2.2/answers?page=' + (p++) + '&pagesize=100&order=desc&sort=votes&site=codegolf&filter=!*LVwAFZ.YnaK-KS*')), function(x) { items = items.concat(x.items) if (finish) { clearInterval(intr) onFinish() } }) }, 500) function onFinish() { var item = items[Math.floor(Math.random() * items.length)] document.write(item.body) } ``` Inspired by > > The majority of answers on this site violate at least one coding standard... – [Comintern](https://codegolf.stackexchange.com/users/7464/comintern) *[1 hour ago](https://codegolf.stackexchange.com/questions/22473/break-some-standards/22485#comment46122_22473)* > > > What it does is output **a random answer out of the top 1000 voted from codegolf.SE** (i.e., solving the problem in a very meta fashion!), complete with formatting and all, on your page! --- Unfortunately, this technically doesn't satisfy the rules, since the *output* is the code with the broken standards, so I did break a standard in this code - I used `document.write` (ewwww). I also have to provide a link, so here: [Why is document.write considered a "bad practice"?](https://stackoverflow.com/q/802854/1223693) If that doesn't count as "breaking the standards," just in case, I wrapped my string in `unescape(escape())`, which is deprecated, as per [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape). Note that I'm really just doing all this to get around the rules, and the main point of this answer is its output. --- Sample run (click image to enlarge): [![screenshot](https://i.stack.imgur.com/CgwqY.png)](https://i.stack.imgur.com/CgwqY.png) [Answer] # XML Not my "invention", I actually have to work with XML's like this that we get from a very secret place: ``` <?xml version="1.0"?> <!DOCTYPE data [ <!ELEMENT data (field2)> <!ELEMENT field2 (#PCDATA)> ]> <data> <field1>Rock & Roll</field1> </data> <data> <field1>Something else</field1> </data> ``` Doesn't validate against its own embedded DTD, contains multiple roots and unescaped ampersands. (There are also other higher level errors, ambiguous content model, etc., not demonstrated here.) Very sad. [Answer] Setting the netmask to non-contigous bitmasks was allowed but highly discouraged by RFC 950, but is now forbidden as of RFC 1219. Nevertheless, BSD-likes allow you to do this. IPv4 netmasks are a combination of four bytes, just like an IP address. It is used to calculate, if two hosts with known IP addresses and netmasks are on the same network. In general an IP address consists of two parts: The network and the host part. Say your network at home is `192.168.1.1` - `192.168.1.254`. The host part are the first three bytes of the IP, namely `192.168.1.x`. This means the netmask is `255.255.255.0`, meaning the first 24 bits are the network part. In binary the mask looks like `11111111.11111111.11111111.00000000`. The 1-bits are continous. In my example, the netmask would be `00010111.00000000.00000000.00101010`. So what would happen, if the netmask is non-continous? Instead of being at the right end, the host part is scattered over the whole IP address, making it really hard to read, just like my explanation here. **DO NOT expect anything to work after this!** ``` root@Gotthold /v/root# ifconfig en0 inet 47.11.23.42 netmask 23.0.0.42 root@Gotthold /v/root# ifconfig en0 inet en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 8192 options=b<RXCSUM,TXCSUM,VLAN_HWTAGGING> inet 47.11.23.42 netmask 0x1700002a broadcast 239.255.255.255 ``` [Answer] # C How many errors can you find, which probably would cause most companies to reject your code (especially good ones). Most of these are probably style mistakes (that I hope nobody does), but some of these are undefined behavior. ``` #define BEGIN { #define END } #define print printf void main(int argv, char* argc, char **args) BEGIN print("hELLO,"); printf("WORLD"); END ``` > > 1. It defines macros that make C feel like another language (most codestyle guidelines). > > 2. The `main` function returns `void`, when it should return `int` (implementation-defined behavior). > > 3. `main` uses a form with three arguments, when it's not standard (undefined behavior). > > 4. Those arguments have incorrect names (most codestyle guidelines). > > 5. `argc` (should be `argv`) has incorrect type. It should be `char **`, but it's `char *` (undefined behavior). > > 6. Mixing C and C++ declaration styles, which differ in `*` position (most codelines guidelines want consistent code). > > 7. Strange coding style where the deeper code is deintended (most codestyle guidelines). > > 8. Using a function (`printf`) without importing correct header (undefined behavior, as it's a variadic function). > > 9. Using Caps Lock to write messages (most language guidelines). > > 10. No space after comma (most language guidelines). > > 11. Multiple statements on one line (most codestyle guidelines). > > 12. No new line printed at end, causing the prompt to be drawn on the end of program (implementation-defined behavior). > > 14. The return value is not defined (implementation-defined behavior). > > > [Answer] # Go ``` package main func main() { println(whereas "Standards are important") println("But sometimes it's fun to break them" despiteallobjections) } ``` <http://play.golang.org/p/DrDHF9EMgu> Explanation is [here](https://stackoverflow.com/a/2489837/65977). The "whereas" and "despiteallobjections" rules don't appear in the spec, but the lexer just skips over them, as kind of an easter egg. I guess the linter is more standards-compliant because if you click "Format" on that Go Playground link, you get a parse error. [Answer] # JavaScript ``` standards: while(1) break standards ``` ## Explanation: A while loop labeled "standards" is exited. ## Standards broken: ``` standards: <-- that one while(1) break standards ``` [Answer] **JavaScript** ``` var a = 1; var b = a + 2; ``` It breaks a standard [because it doesn't use enough jQuery](https://meta.stackexchange.com/a/19492) The proper way to write this code can be seen [here](http://www.doxdesk.com/img/updates/20091116-so-large.gif) [Answer] GML breaks a ton of standards. One being the beauty of not allowing for use of Ternary operators. Instead of using Ternary Operators, in GML I'd do this: ``` z = ( y * ( z > 0 ) ) + ( x * ( z <= 0 ) ); ``` Where the Ternary equivalent is: ``` z = ( z > 0 ) ? y : x; ``` The first is pretty nasty especially when you start adding in other operations. [Answer] ## Haskell My program doesn't really break any standards, but just randomly selects one to use. It tries to be fair across the different standards. Here is my code. ``` import System.Random import Control.Applicative newlines=["\n", "\r\n", "\r"] pick::[a]->IO a pick lst=fmap (lst !!) $ randomRIO (0, length lst - 1) fairUnlines::[String]->IO String fairUnlines [] = pure "" fairUnlines [str] = pure str fairUnlines (str:strs) = (\x y z->x++y++z) <$> pure str <*> pick newlines <*> fairUnlines strs ``` `fairUnlines` will take a list of Strings, and join them using random newline character standards. Also, it is the first time I have actually used the applicative style, on IO none the less. [Answer] # Bash Taking from your example: ``` ping 192.168.0.1 -c 1 -s 10000 ``` Assuming your router is at `192.168.0.1` *Note: the max ping size is 65kb, so i did 10 kb in stead of 10 mb* [Answer] # Java Oh dear, someone forgot the getter again... ``` import java.lang.reflect.*; class Main { public static void main(String[] args) throws Exception { // Brian forgot to implement the getter again. // He's on vacation, so this will have to do. // TODO: figure out what he named the fields Field field = UsefulObject.class.getDeclaredFields()[1]; Field objField = UsefulObject.class.getDeclaredFields()[0]; field.setAccessible(true); objField.setAccessible(true); Object obj = objField.get(null); String s = (String) field.get(obj); System.out.println(s); } } class UsefulObject { private static UsefulObject Useful; private String usefulField; static { Useful = new UsefulObject("useful field"); } private UsefulObject(String s) { this.usefulField = s; } public String getUsefulField() { return usefulField; } public static UsefulObject getUsefulObject() { throw new UnsupportedOperationException("TODO"); } } ``` The `Useful` field should be [lowercase](https://www.javatpoint.com/java-naming-conventions): `useful` Not sure this is a standard: useless wildcard import (should just be `java.lang.reflect.Field` since that's all that's being used). ]
[Question] [ ## Challenge The challenge is simple: **print a snake**. You will get the length of the snake as input. A snake of length 2 looks like this: ``` ==(:)- ``` A snake of length 7 looks like this: ``` =======(:)- ``` In other words, *the length of a snake is how many equal signs are before the head*. ## Usage Let's say I made a C++ implementation and compiled it to `./getsnake`. I could run it like so: ``` $ ./getsnake 10 ==========(:)- ``` ## Clarifications * [Standard loopholes are disallowed.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1070#1070) * You can get input and output in any acceptable way. * You can assume all inputs given are positive integers. * You may write a function instead of a regular program. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 33 bytes Not gonna win, but still cool. Might be able to get golfed more. [Try it online!](http://hexagony.tryitonline.net/#code=NjF9Py4kKUAkajsoMzwuLzsufWwvLjQwMDs1XGo7Lidc&input=NQ) Golfed: ``` 61}?.$)@$j;(3<./;.}l/.400;5\j;.'\ ``` Formatted: ``` 6 1 } ? . $ ) @ $ j ; ( 3 < . / ; . } l / . 4 0 0 ; 5 \ j ; . ' \ . . . . ``` Colored (Made using [Timwi's Hexagony Colorer](https://github.com/Timwi/HexagonyColorer)) [![u found da secret snek! =======(:)-](https://i.stack.imgur.com/aJf5j.png)](https://i.stack.imgur.com/aJf5j.png) Explanation: Loop, print out "=" until the counter reaches 0. ``` 6 1 } ? . $ . . $ . . ( . . . / . . } . . . . . . ; . . . . . ' . . . . . ``` Print "(" ``` . . . . . . . . . . . . . . . / ; . . . . . 4 . . . . . j . . . . . . . . ``` Print ":" ``` . . . . . . . . . . ; ( 3 < . . . . } l / . . . . . . . . . . . . . . . . ``` Print ")" ``` . . . . . . . . . j . . . . . . . . . . . . . . . ; 5 \ . . . . \ . . . . ``` The above values were generated using a simple python script. However, I kind of ran out of room for the "-". So, I had to resort to more advanced tricks. When the program prints out ")", the value of the cell isn't 41, it's 1065. Hexagony just mods the value when printing. As it turns out, (1065\*1000+4)%256=44, just one away from 45, the ascii value for "-". Then, I just increment, print, and insert a @ somewhere after printing. ``` . . . . . $ ) @ $ j . . 3 . . / . . } . . . 4 0 0 . 5 \ . ; . . \ . . . . ``` [Answer] # Cinnamon Gum, 7 bytes ``` 0000000: 7043 dc95 6d4f ce pC..mO. ``` [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNzA0MyBkYzk1IDZkNGYgY2UgICAgICAgICAgICAgICAgICAgICAgICBwQy4ubU8u&input=MTA) Would have been 6 bytes with the old `p` syntax :/ # Explanation Decompresses to `p~=~(:)-`, the `p` stage then simply reads input and repeats the `=` n times. [Answer] ## [Brian & Chuck](https://github.com/m-ender/brian-chuck), 31 bytes ``` ,{-?>}-):(=? #}<<.{?_<.<.<.<.<. ``` Input in the form of a [byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values), so e.g. input `!` gives a snake of length 33. [Try it online!](http://brian-chuck.tryitonline.net/#code=LHstPz59LSk6KD0_CiN9PDwuez9fPC48LjwuPC48Lg&input=IQ) It's been a while... ### Explanation A quick Brian & Chuck primer: * The first line of the program is Brian, the second is Chuck. * Brian and Chuck are two Brainfuck-like instances. The main catch is that Chuck's program is Brian's tape and vice versa. The tape heads/instruction pointers start on the first cell of each tape and execution starts on Brian. * As for the commands, there are a few differences. Only Brian can use `,` (input) and only Chuck can use `.` (output). In addition to `<` and `>` there are `{` and `}` which move the tape head up to the next zero cell (or in the case of `{` to the left end of the tape if there is no zero cell on the way). Instead of `[...]`, the only control flow is `?` which switches control to the other instance if the current cell is non-zero. The first executed instruction on the other cell is the one after the condition. And finally, `_` is just an alias for null-bytes, for convenience. Now the code. Brian starts with this: ``` ,{-? ``` This reads the input into Chuck's first cell, then moves the tape head to the left with `{` (does nothing right now) and decrements the input with `-` before switching control for Chuck if the value is still non-zero. This begins the main loop. Chuck then runs this bit: ``` }<<.{? ``` This moves the tape head on Brian to the very end, moves two cells left onto the `=` and prints it before the tape head all the way to the left and switching control back to Brian. This is how loops generally work in B&C. Once the input has been reduced to zero, the `?` on Brian's tape will do nothing. Then Brian executes this part: ``` >}-):(=? ``` The `):(=` are no-ops, so the actual code is just `>}-?`. We move off the zero cell with `>`, move up to `_` with `}`, decrement it to make it non-zero and switch to Chuck with `?`. Then the last bit on Chuck is run: ``` <.<.<.<.<. ``` This simply prints the five characters in front of Chuck, i.e. `=(:)-`. Note that we need to print another `=` since the main loop is only executed `N-1` times for input `N`. [Answer] # [V](https://github.com/DJMcMayhem/V), 8 bytes ``` Àé=A(:)- ``` [Try it online!](http://v.tryitonline.net/#code=w4DDqT1BKDopLQ&input=&args=NQ) V uses the "Latin1" encoding. Explanation: ``` À "Arg1 times: é= "Insert an '=' A(:)- "Append the head ``` [Answer] # [Retina](https://github.com/m-ender/retina), 10 bytes ``` .+ $*=(:)- ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCo9KDopLQ&input=MTA) This is a simple regex substitution. It matches `.+` which matches the whole input, and then substitutes it with `$*=(;)-`. The `$*` is a feature unique in Retina: it is the character-repetition special operator. For example, `5$*x` would become `xxxxx`. In the case that the previous argument is absent, the whole match is used as the default argument. [Answer] # Python, 21 bytes ``` lambda n:"="*n+"(:)-" ``` [Ideone it!](http://ideone.com/flvOaZ) [Answer] # Haskell, 25 bytes ``` f n=('='<$[1..n])++"(:)-" ``` `'='<$[1..n]` is equivalent to `replicate n '='`. [Answer] # Java 8, 52 bytes ``` n->new String(new char[n]).replace("\0","=")+"(:)-"; ``` [Test suite.](http://goo.gl/Ur0Kys) (Compile > Execute) [Credits](https://stackoverflow.com/a/4903603/6211883). ### teh traditional way, ~~61~~ ~~54~~ 53 bytes **7 bytes thanks to Kevin Cruijssen.** **1 byte thanks to Dom Hastings.** ``` n->{String s="";for(;n-->0;)s+="=";return s+"(:)-";}; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”=x;“(:)- ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCdPXg74oCcKDopLQ&input=&args=MTA) ``` ”=x;“(:)- ”= '=' x repeat (argument) that many times ; append “(:)- "(:)-" ``` [Answer] # C, 38 ``` f(n){for(;n--;printf(n?"=":"=(:)-"));} ``` [Try it on ideone.](http://ideone.com/I7HpkV) [Answer] ## 05AB1E, ~~10~~ 9 bytes ``` '=×"ÿ(:)- ``` **Explanation** ``` '= # push equal-sign × # repeat input nr of times "ÿ(:)- # interpolate snake body with head as a string # implicitly display ``` [Try it online](http://05ab1e.tryitonline.net/#code=Jz3DlyLDvyg6KS0&input=NQ) 1 byte saved thanks to Adnan. [Answer] # Javascript, 23 bytes ``` n=>"=".repeat(n)+"(:)-" ``` [Answer] ## C#, 28 bytes ``` n=>new string('=',n)+"(:)-"; ``` [Answer] # [Python](https://repl.it/repls/RewardingAncientPaddlefish), 24 bytes. ``` print"="*input()+"(:)-" ``` `input()` gets input from user `*`, when used on strings and an integer, creates a new string, which is made of joined copies of the original. For example: `"hello "*3` outputs `hello hello hello`. By multiplying `=` and `input()`, you get a string of `=` the length that the user specifies. Using `+` joins two strings, in this case, our body `"=…="` with our head, `"(:)-"` to make the snake. `print` outputs the result. [Answer] # GolfScript, ~~11~~ 10 bytes ``` ~"="*"(:)-" ``` Multiplies "=" by input, and adds head. *-1 thanks to Leaky Nun* [Answer] # Mathematica, ~~21~~ 20 bytes ``` "="~Table~#<>"(:)-"& ``` Anonymous function. Takes a number *n* as input, and returns a snake of length *n* as output. `"="~Table~#` generates a list `{"=", "=", ..., "="}` of length *n*, and `<>"(:)-"` concatenates the list's elements and appends `"(:)-"` to the resulting string. [Answer] # R, ~~32~~ 27 bytes This solution is pretty straightforward, `rep` function repeats the first element (`"="`) `scan()` times, which is in fact the user's input. ``` a=scan();cat(rep("=",a),"(:)-") ``` *EDIT*: ``` cat(rep("=",scan()),"(:)-") ``` Slighly shorter answer, using `scan()` directly. Alternatively, ``` cat(rep("=",scan()),"(:)-",sep="") ``` for a non-chopped snake (**34 bytes**) [Answer] ## Batch, 68 bytes ``` @set h=(:)- @for /l %%i in (1,1,%1)do @call set h==%%h%% @echo %h% ``` [Answer] # CJam, ~~13~~ 11 bytes ``` qi'=*"(:)-" ``` [Test it here.](http://cjam.aditsu.net/#code=qi%7B'%3D%7D*%22(%3A)-%22&input=5) *-2 bytes thanks to quartata* [Answer] # [Perl 6](http://perl6.org), ~~16 15~~ 12 bytes ``` ~~{"{'='x$\_}(:)-"} {'='x$\_~'(:)-'}~~ '='x*~'(:)-' ``` ### Explanation: ``` '=' x * # 「=」 string repeated by the only parameter 「*」 ~ # concatenated with '(:)-' # the head ``` ### Usage: ``` # store it in the lexical namespace my &snake = '='x*~'(:)-'; put snake 10; # put ^5 .map: &snake; put ^5 .map: '='x*~'(:)-'; ``` ``` ==========(:)- (:)- =(:)- ==(:)- ===(:)- ====(:)- =====(:)- ``` [Answer] # [JAISBaL](https://github.com/SocraticPhoenix/JAISBaL), 9 bytes ``` t=*Qb(:)- ``` Verbose: ``` # \# enable verbose parsing #\ push1 = \# push = onto the stack #\ mul \# multiply the top two values of the stack #\ popout \# pop the top value of a stack and print it #\ print4 (:)- \# print (:)- #\ ``` Tested with [JAISBaL-0.0.7](https://dl.bintray.com/meguy26/Main/com/gmail/socraticphoenix/JAISBaL/0.0.7/) (The compiled .jar was just pushed, but the source has been up on git for a while) [Answer] ## PowerShell v2+, 19 bytes ``` '='*$args[0]+'(:)-' ``` Full program. Takes input `$args[0]`, uses string multiplication to construct the body, then string concatenation to tack on the head. ``` PS C:\Tools\Scripts\golfing> .\snakes-all-around.ps1 7 =======(:)- PS C:\Tools\Scripts\golfing> .\snakes-all-around.ps1 77 =============================================================================(:)- ``` [Answer] # C, ~~46~~ ~~45~~ ~~43~~ bytes *saved 2 bytes thanks to owacoder!* *saved 3 bytes thanks to rici!* ``` f(n){while(4-printf("=\0(:)-"+2*!n--));} ``` [Try it on Ideone!](https://ideone.com/DXVJJh) [Answer] # Cheddar, 15 bytes (noncompeting) ``` n->'='*n+'(:)-' ``` A straightforward answer. [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 11 bytes Hexdump: ``` 0000000: aaaa5e a0f7b4 ed4cee 5d3b ..^....L.]; ``` [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluCmFkZCA2MQpmd2QgMQpnZXQKam1wLHN1YiAxLHJ3ZCAxLHB1dCxmd2QgMSxqbnoKYWRkIDQwLHB1dApyd2QgMSxzdWIgMyxwdXQKZndkIDEsYWRkIDEscHV0CmFkZCA0LHB1dA&input=MTA&debug=on) Assembler: ``` set numin add 61 fwd 1 get jmp,sub 1,rwd 1,put,fwd 1,jnz add 40,put rwd 1,sub 3,put fwd 1,add 1,put add 4,put ``` [Answer] ## K, 17 Bytes ``` {,[x#"=";"(:)-"]} ``` Example; ``` f:{,[x#"=";"(:)-"]} -1(f'!10); /print out the result of calling f where x is 0 1 2 3 4 5.... (:)- =(:)- ==(:)- ===(:)- ====(:)- =====(:)- ======(:)- =======(:)- ========(:)- =========(:)- ``` Explanation; ``` {} /function x is implicit and is an int x#"=" /take (#) x of "=" --> so 3#"=" gives "===" ,[x#"=";"(:)-"] /comma is a join that takes 2 args --> ,[x;y] gives the concatination of x and y --> "a","abc" is the same as ,["a";"abc"] and gives "aabc" ``` [Answer] # Perl, 16 + 1 (`-p` flag) = 17 bytes ``` $_="="x$_."(:)-" ``` Needs `-p` flag, so run with : ``` perl -pe '$_="="x$_."(:)-"' ``` [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 12 bytes ``` "=(:)-"nD$O. ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=%22%3D%28%3A%29-%22nD%24O%2E&input=7) ### Explanation ``` "=(:)-" Push this to the stack in reverse order - ["-",")",":","(","="] n Take number from input D Pop k and duplicate top of stack (the "=") k times $O. Output whole stack as characters and stop. ``` [Answer] # Befunge-98, 24 bytes Takes numerical input from the user, then prints the snake. ``` '=&:00pk:00gk,"-):("4k,@ ``` [Answer] # Matlab / Octave, 22 bytes ``` @(n)[~(1:n)+61 '(:)-'] ``` This is an anonymous function. [**Try it on Ideone**](http://ideone.com/sVU0ez). ### Explanation Assume `n= 5`. `1:n` produces the row vector `[1 2 3 4 5]`. `~(1:n)` negates each entry, so it gives `[0 0 0 0 0]`. `...+61` adds `61` to each entry, so it gives `[61 61 61 61 61]`. `61` is the ASCII value of character `=`. `[... '(:)-']` concatenates that with the string `'(:)-'`. This automatically converts `[61 61 61 61 61]` into the string `'====='` before the concatenation. ]
[Question] [ # RLE Brainfuck (related to [BF-RLE](https://esolangs.org/wiki/BF-RLE)) The hypothetical RLE ([Run-Length Encoding](https://en.wikipedia.org/wiki/Run-length_encoding)) dialect of Brainfuck accepts the symbols for the 8 commands and also accepts digits. The digits are used to represent the number of successive repetitions of a command, thus allowing run-length encoding of the source code. `8>` is equal to `>>>>>>>>`. The length is always on the left side of the command. Your task is to write the shortest program/function that translates the input string (RLE Brainfuck fragment) into a regular Brainfuck program. For example: Input: ``` 10+[>+>3+>7+>10+4<-]3>2+.>+.7+2.3+.2<2+.>15+.>.3+.6-.8-.2<+.<. ``` Ouptut: ``` ++++++++++[>+>+++>+++++++>++++++++++<<<<-]>>>++.>+.+++++++..+++.<<++.>+++++++++++++++.>.+++.------.--------.<<+.<. ``` The shortest code in byte count in each language will win. [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 61 bytes ``` lambda s:eval(re.sub('(\d*)(.)',r'+1*\1*1*"\2"',s)) import re ``` [Try it online!](https://tio.run/##FcjdCoIwGIDh865ieLKfTz/arIyw3UiLmDhJ8GfMWXT1S09eeF7/i@95Uqm7mzTYsWktWW7uYwcWHC5rwygzreAMOc0DBSmMFFJkRmU0Xzg/9KOfQyTBJR/6KZKOBft99ZNfI@M8ySM8NOgSdAV6w6kunqVWgBqwAoUloKp3yvOWnZcCr8U2AWv8Aw "Python 2 – Try It Online") The regex substitution expands `3<2+-` into the string: ``` +1*3*1*"<"+1*2*1*"+"+1**1*"-" ``` which is then `eval`ed. (Note how when `\1` is empty, we get `1**1 = 1`.) The first `+` is a unary operator which binds to the first number, and the other `+`s are string concatenation. This beats the more obvious ``` lambda s:re.sub('(\d+)(.)',lambda m:int(m.group(1))*m.group(2),s) import re ``` by 14 bytes. Ordinarily `"\2"` wouldn’t always work, but thankfully `\` and `"` aren’t brainfuck commands. --- **xnor** saved a byte, supplying the `1*\1*1` trick. Previously I had `\1L` in the regex, and defined `L=1` as a lambda argument, which is also pretty cool: `3L` is a long int literal and `L` is a variable. [Answer] # [Pyth](http://pyth.herokuapp.com/?code=r9&input=%2210%2B%5B%3E%2B%3E3%2B%3E7%2B%3E10%2B4%3C-%5D3%3E2%2B.%3E%2B.7%2B2.3%2B.2%3C2%2B.%3E15%2B.%3E.3%2B.6-.8-.2%3C%2B.%3C.%22&debug=0), 2 bytes ``` r9 ``` **[Try it here!](https://pyth.herokuapp.com/?code=r9&input=%2210%2B%5B%3E%2B%3E3%2B%3E7%2B%3E10%2B4%3C-%5D3%3E2%2B.%3E%2B.7%2B2.3%2B.2%3C2%2B.%3E15%2B.%3E.3%2B.6-.8-.2%3C%2B.%3C.%22&debug=0)** ## How it works ``` r9 - Full program receiving the String from STDIN. r - Pyth's set of extended string operations. 9 - The ninth command of that set (run-length decode). This supports multi-digit numbers. ``` [Answer] ## Lua, ~~65~~ ~~64~~ 63 Bytes ~~Great ! For once, Lua beats Python !~~ **Edit: Saved one byte thanks to @Jarhmander, thanks to him for the useful trick to force a single result** ``` print(((...):gsub("(%d+)(.)",function(a,b)return b:rep(a)end))) ``` [Try it online!](https://tio.run/##FchBCsIwEEDRq0hBmGGawSZqSwlzEXGR2CgFiSUm50/TzYf3v8XVuqU1ZgBgZpw//@Khg/NCCIxd/y7xlddfBNd7TCGXFE9@TmEDhyEuiFhrHS70EBJDMpI0XK16GtHEQjySZkOs7cHh1nLwrnhSbRJb3gE "Lua – Try It Online") ### Explanations ``` print)((...):gsub( -- iterate over the argument and replace the strings "(%d+)(.)", -- matching this pattern (at least one digit and a non-digit) function(a,b) -- capture the digit and non-digit parts in separate variables return b:rep(a) -- repeat the non-digit a times, a being the digit part end))) ``` [Answer] # [Scala](https://scala-lang.org), ~~73~~ 69 bytes ``` "(\\d+)(.)".r.replaceSomeIn(_:String,m=>Some("$2"*m.group(1).toInt)) ``` [Try it online!](https://scastie.scala-lang.org/WrkFSl0qSHa5imoQJIHLBg) [Answer] ## [Perl 5](https://www.perl.org/), 18 bytes **17 bytes code + 1 for `-p`.** ``` s/\d+(.)/$1x$&/ge ``` [Try it online!](https://tio.run/##Fcg7CoAwEEXRzYgoj0xM4q8IsxG1U0QQDcbC1TvG5sK5Ybn2RiTqcUZBpc7Mk@V6XURMhYHBDtyBE2qvJscWxKAOlhzI@p@mSfnZKupVmiBP7xnu7TyiqPAB "Perl 5 – Try It Online") [Answer] # RLE Brainfuck, 204 bytes ``` -3>,[[->+>+<<]>>47-3<10+<->[-<+4>->+<[>-]>[3<+<[-]4>->]5<]3>57+[-]+<<[>>-<<[3>+3<-]]3>[3<+3>-]<[>>+7<+[->11-<+[-<+]->>+[-<[->10+<]>>+]<[-4>.4<]4>[-]-3<-<+7>-7<[8>+8<-]]8>[8<+8>-]<[3<.3<[-]-6>-]7<--5>-]<,] ``` As I understand it the specs for the brainfuck environment aren't super well-defined. This program assumes that the cells in the tape allow arbitrarily large positive and negative integers, with no overflow. This code will transcribe non-command comments as well, but it will expand the run-length encoding of comments (eg "see 3b" → "see bbb"). The resulting program should run the same, so I'm not too concerned. I'm pretty sure I could still golf a few bytes off this but I'm exhausted from working with it. [Here's](https://eval.in/893142) the custom interpreter + tests I've been using to test it. If you pass it input in the Standard Input box it should run against that input instead of running the tests. My messy ungolfed workpad: ``` ->>>, [ [->+>+<<]>> clone 2 into 3 and 4 if read char is between zero and nine (num buffer | max | is_digit | original char | read | temp0 | temp1) ^ 47- <<<10+ set max <-> handle gross 0 case [ while max - max minus one <+ buffer plus one >>>>- read minus one IF STATEMENT : if read is 0 >+< [>-]>[< <<+ is_digit = 1 <[-]>>> max = 0 >->]<< back to read <<< back to max ] >>>57+[-] reset `read` (need to add first to avoid infinite negative) +<< check is_digit flag ( end marker | 0 | is_digit | original char | temp0 | temp1 | temp2 | temp3) x[ IF READ WAS DIGIT CODE 1a >>temp0 -<<x [>>>temp1 +<<<x-] ] >>>temp1 [<<<x+>>>temp1 -] <temp0 [ START CODE 2a >>temp2 + 7<y+[ IF THERE IS A NUMBER PREFIX - START CODE 1b >11- end marker is negativeone < on smallest digit +[-<+]-> find largest digit >+[ sum digits until we hit the end marker negativeone - <[->10+<]> h1 = ten * h0; h0 = 0 > + ] leave the negativeone at zero though num | 0 | 0 | 0 | original char ^ <num [->>>>.<<<<] print `original char` `num` times >>>>[-]- set `char` to negativeone <<<- last ditch guess END CODE 1b <y+ 7>temp2 - 7<y[8>temp3 +8<y-] ] 8>temp3 [8<y+8>temp3 -] <temp2 [ CODE 2b <<<. print original char <<<[-]- set num buffer to new left edge >>>>>>temp2 - ] 7<y-- END CODE 2a 5>temp0 - ] < , ] ``` [Answer] # vim, 29 25 23 22 16 bytes ``` :s/\D/a&<C-v><ESC>/g D@" ``` `<C-V>` is 0x16, `<ESC>` is 0x1b. It works by replacing each non-digit with a command that appends that character to the buffer. The counts are left alone and modify those commands. At this point, the buffer is a vimscript program that produces the desired Brainfuck program, so we pull it into a register and run it. [Try it online!](https://tio.run/##K/v/36pYP0YjxiVGUz8xxlBMWj@dKyXFQen/f0MD7Wg7bTtjbTtzbTsgx8RGN9bYzkhbz05bz1zbSM9YW8/IBsQ1NAUSIK6Zrp6FLlBQW89GDwA "V – Try It Online") Edit: Size reductions thanks to suggestions: H.PWiz: 5, TheFamilyFroot: 5, DJMcMayhem: 1 [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 24 bytes ``` ['(\d+)(.)'[\#~*]3/repl] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P1pdIyZFW1NDT1M9Oka5TivWWL8otSAn9r@DVRoXl7qhgXa0nbadsbadubYdkGNioxtrbGekrWenrWeubaRnrK1nZAPiGpoCCRDXTFfPQhcoqK1no6eukKaQX1ryHwA "Stacked – Try It Online") ## Explanation ``` ['(\d+)(.)'[\#~*]3/repl] [ ] anonymous function, taking string as argument '(\d+)(.)' for all matches of this regex: [ ]3/repl replace (stack = (whole match, digit, repetend)) \#~ convert digit to number * repeat the character by that digit ``` [Answer] # TeX, 124 bytes ``` \newcount\n\def\b{\afterassignment\r\n0}\def\r#1{\ifx;#1\else\p#1\expandafter\b\fi }\def\p#1{#1\ifnum\n>1\advance\n-1\p#1\fi} ``` (wrote in two lines to be visible, but the code can be written in one line) This defines a macro `\b` that takes the input in the form `\b<input>;`, and prints the output wanted to the document. [Answer] # [Retina](https://github.com/m-ender/retina), ~~28~~ 23 bytes *thanks to @Leo for -5 bytes* ``` \d+ $* +`1(1\D) $1$1 1 ``` [Try it online!](https://tio.run/##FcgxDoAgEAXRfs9Bof6wcUHFgmzlLcREEy1sLIz3R2gmefNe3/0cOacTZDrCLo2kpSUjRkgoZ@mxKtRDA7RgiHbz6sAKDnDswS5WylhSOVmebZngyD8 "Retina – Try It Online") [Answer] # [Pyon](https://github.com/alexander-liao/pyon), 66 bytes ``` print(re.sub("\d+.",lambda k:(int(k.group()[:-1])*k.group()[-1]),a ``` [Try it online!](https://tio.run/##K6jMz/v/v6AoM69EoyhVr7g0SUMpJkVbT0knJzE3KSVRIdtKAySXrZdelF9aoKEZbaVrGKupheCDuDqJ//8bGmhH21lo2@jG2ukBAA "Pyon – Try It Online") Pyon is pretty much just Python, but this is shorter because `re` is automatically imported when you use it, and `a` is automatically set to an argument or the input -4 bytes thanks to Mr. Xcoder [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ ~~93~~ 89 bytes -7 with thanks to Mr.Xcoder ``` n=b="" for y in input(): if"/"<y<":":n+=y elif""==n:b+=y else:b+=y*int(n);n="" print b ``` [Try it online!](https://tio.run/##LcxBCsIwEAXQfU8RZtU6dLSJWonJXETcFFoMlGmodZHTx1SE4fPfX0xM22sRnbP4wQNU07KqpIKUi5@tbmylwgRHcMmBBSvoU6XGuWzgvdjh7/f4q4cgWy3NXfZXcS1SQ87QnfDByAa5Ry44u/ZpWCMxUo@aDJJ2O7tLiZ3Xlm5tGZEcwRc "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 60 bytes ``` f(a:b)|[(c,d:e)]<-reads$a:b=(<$)d[1..c]++f e|1<2=a:f b f a=a ``` [Try it online!](https://tio.run/##FcixDoMgEIDhvU9xg4PmyqVAWxsCvIhxOBFSo3VQR9@d4vIn3//lfY7LknOq2QzN2dXhPprY9FZskce9KtfVtmrGThKFHjFBPKVVjk2C4ZaAHecfTys4mNYjbhwOSFk@sPPoNfoWfcHTil57heSRWlSkkZS9KF8lF9@CPqJMJEt/ "Haskell – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~121~~ ~~106~~ 90 bytes ``` function(s,a=strsplit)cat(rep(el(a(gsub("\\d","",s),"")),pmax(el(a(s,"\\D")),"1")),sep="") ``` [Try it online!](https://tio.run/##JYzNDoIwEITvPkZP22zZCKh4gJ58C/FQsCgJP023JPr02MbLl3wzk/H7NHbe@C/MNrzXJ8vD0OzDtvRhXBdgZRoOnt00BtmbAN46sBMYePHWgWjbp1BCKJaRUio3m8@/ZxXLW8pEnsjWNXGyDyDyI9416hJ1hTrKqc4epS6QNFKFBZVIRZ00P0ckvWR0zWKIVFP8@AE "R – Try It Online") Saved 15 bytes by realising that `rep()` will coerce to numeric. Saved another 16 thanks to Giuseppe, mainly from the use of `pmax` to replace empty strings with `1` ``` function(s) { x <- el(strsplit(s,"\\D")) # Split the string on anything that is not a digit... x <- pmax(x, "1") # ... and replace any empty strings with 1. This gets us the numbers of repeats y <- gsub("\\d","",s) # Remove all digits from the original string... y <- el(strsplit(y)) # ... and split into individual units. This gets us the symbols to repeat z <- rep(y, x) # Implement the repeats. x is coerced to numeric cat(z, sep = "") # Print without separators } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ 62 bytes ``` -join("$args"-split'\b'|%{(,$(,$_[0]*$n+$_))[!!($n=$($_-1))]}) ``` [Try it online!](https://tio.run/##FcjhCsIgFIbha9k4oXbysM1q/TBvxEQKRi3EjRn0o7p2c/DxwvPN03tY0mMIIWf5nMbIa7gu91TLNIfxxS439t18@A7KvG3cFiKCF8JWFYd4Bg5etkK4n8g5s7ZBa9AoND2agr2WTpkOySD12JFC6vTK9lCy8ijpJMuJpIn9AQ "PowerShell – Try It Online") # Breakdown What a mess! Starting from `$args`, which is a single element array containing the RLE string, I'm forcing into an actual string by wrapping it quotes. Then split it by word boundary (`\b` in regex). That will give me an array of strings, where each element is either a number or the BF token(s) that come after the number. So in the example, the first 4 elements of this split array are `10`,`+]>+>`,`3`,`+>` (all are string). Next, I pipe that into `ForEach-Object` (`%`) to deal with each *element*. The middle is a well-known PowerShell golfism, with a twist; it's essentially a DIY ternary operator, in which you create a 2 element array then index into it using the boolean expression you want to test, whereby a false result gives you element 0 and a true result gives you element 1. In this case, I actually create a single element array with the unary comma `,` operator, because I don't want output in the true case. First let's look at the indexer, even though it gets executed later. The idea of this is that `$_` (the current element) could either be a valid number, or some other string. If it's a number, I want `$n` to be the value of that number minus 1 (as a number, not a string). If it's not, I want `$n` to be false-y. PowerShell usually tries to coerce the right-hand value to the type of the left side, but it can depend on the operation. For addition, `"10"+5` would give you a new string, `"105"`, whereas `10+"5"` will give you an integer (`15`). But strings can't be subtracted so instead PowerShell can infer the numeric value automatically with a string on the left side of subtraction, therefore `"10"-5` gives `5`. SO, I start with `$_-1`, which will give me the number I want when `$_` is actually a number, but when it's not I get nothing. On the surface, "nothing" is falsey, but the problem is that is stops execution of that assignment, so `$n` will retain its previous value; not what I want! If I wrap it in a subexpression, then when it fails, I get my falsey value: `$($_-1)`. That all gets assigned to `$n` and since that assignment is itself wrapped in parentheses, the value that was assigned to `$n` also gets passed through to the pipeline. Since I'm using it in the indexer, and I want `1` if the conversion succeeded, I use two boolean-`not` expressions `!!` to convert this value to boolean. A successful number conversion ends up as true, while the falsey nothingness gives us that sweet, sweet `0` that allows for returning the only element in that fake ternary array. Getting back to that array, the element is this: ~~`$("$($_[0])"*$n*$_)`~~ `$(,$_[0]*$n+$_)` ~~`"$($_[0])"` - this is an annoyingly long way of getting the first character of the current element (let's say, getting `+` from `+[>+`), but as a string and not as a `[char]` object. I need it to be a string because I can multiply a string by a number to duplicate it, but I can't do that with a character.~~ Actually I managed to save 4 characters by using a `[char]` array instead of a string (by using another unary comma `,`), so I was able to remove the quotes and extra sub-expression. I *can* multiply an array to duplicate its elements. And since the entire result of this iteration ends up being an array anyway and needs to be `-join`ed, using an array here incurs no additional cost. Then, I multiply that ~~string~~ array by `$n`, to duplicate it `$n` times. Recall that `$n` could be `$null` or it could be the value of the preceding digits minus one. Then `+$_` adds the current element onto the end of the duplicated first character of that element. That's why `$n` is minus one. This way, `10+[>+` ends up with `$n` equal to 9, then we make 9 `+`'s and add that back to the `+[>+` string to get the requisite 10, plus the other single elements along for the ride. The element is wrapped in a subexpression `$()` because when `$n` is `$null`, the entire expression fails, so creating the array fails, so the indexer never runs, so `$n` never gets assigned. The reason I used this ternary trick is because of one of its peculiarities: unlike a real ternary operator, the expressions that define the elements *do* get evaluated whether or not they are "selected", and first for that matter. Since I need to assign and then use `$n` on separate iterations, this is helpful. The ternary array element value gets evaluated with the previous iteration's `$n` value, then the indexer re-assigns `$n` for the current iteration. So the `ForEach-Object` loops ends up outputting everything its supposed to (a bunch of errors we ignore), but as an array of new strings. So that whole thing is wrapped in parentheses and then preceded by unary `-join` to give the output string. [Answer] # [QuadR](https://github.com/abrudz/QuadRS), 17 bytes ``` \d+. ¯1((⍎↓)⍴↑)⍵M ``` [Try it online!](https://tio.run/##KyxNTCn6/z8mRVuP69B6Qw2NR719j9omaz7q3fKobSKQ2ur7/7@hgXa0nbadsbadubYdkGNioxtrbGekrWenrWeubaRnrK1nZAPiGpoCCRDXTFfPQhcoqK1nowcA "QuadR – Try It Online") Thanks to [Adám](https://judaism.stackexchange.com/users/3073/ad%C3%A1m) for providing the correct version of the code. ### How it works: ``` \d+. ⍝ Regex to match any sequence of digits followed by a character. ¯1((⍎↓)⍴↑)⍵M ⍝ Transformation line ¯1( )⍵M ⍝ Arguments: -1 and the matching expression ( ↓) ⍝ 'Drop' the last item (-1) from the match (⍵M), yielding a string which is a sequence of digits. ⍎ ⍝ Execute. In this case, it transforms a string into a number. ↑ ⍝ 'Take' the last item (-1) from the match (⍵M), yielding a character. ⍴ ⍝ Reshape it. That will take the character resulting from the 'Take' operation and repeat it n times, ⍝ where n is the result from the 'Drop' and 'Execute' operations. ``` [Answer] # [Proton](https://github.com/alexander-liao/proton), 50 bytes ``` x=>/\d+./.sub(k=>int((e=k.group())[to-1])*e[-1],x) ``` [Try it online!](https://tio.run/##KyjKL8nP@59m@7/C1k4/JkVbT1@vuDRJI9vWLjOvREMj1TZbL70ov7RAQ1MzuiRf1zBWUys1GkjpVGj@LygCqUnTUDLTjraz0LbRjbXTU9LU/A8A "Proton – Try It Online") [Answer] # Java 8, 148 bytes ``` s->{for(s=s.format(s.replaceAll("(\\d+)","%1\\$0$1d"),0);!s.matches("\\D+");s=s.replaceAll("0(\\D)","$1$1"));return s.replaceAll("((.)+)\\2","$1");} ``` ~~*Gdamn*~~ Java regexes are so useless sometimes.. Last time it was [lack of using the capture group `"$1"` for anything](https://codegolf.stackexchange.com/a/145775/52210), now this.. I want to replace `3c` with `ccc` or `000c` with `ccc` as a one-liner, but unfortunately Java has no way of doing this without a loop. Ah well. **Explanation:** [Try it here.](https://tio.run/##fU9BasMwELznFVvhgoTixXbaJuBEUMi1ufQY5aDaSuvUkY2lBErw29118aH0UBArzWpmdvZkriZuWutO5edQ1MZ7eDGVu80AKhdsdzSFhd0IAV5DV7l3KPj08CKnfj@j4oMJVQE7cLCBwcfqdmw67jce6T6bwD12tq3J7LmuOeNal1KwObtPtY6SKC2ZmCciv/NI5OLDes603kom8tHjtzQh7XaURmmUMiHyzoZL5@DPAI5CCq2zHyLZ9MOYlU57easp6RT42lQlnGnhaaf9AYyYtv3ywZ6xuQRs6SvUjjssOFupceq/lDSReyXVQqqlVAQe1vFhoTKJSuJSZriQmK1HmD5SGeFTjKuYmhLXONn3s374Bg) ``` s->{ // Method with String as both parameter and return-type for(s=s.format(s.replaceAll("(\\d+)","%1\\$0$1d"),0); // Replace every numbers of that many zeroes // (i.e. "3>2+" -> "000>00+") !s.matches("\\D+"); // Loop as long as the String contains zeroes s=s.replaceAll("0(\\D)", // Replace every 0 followed by a non-0 character, "$1$1") // with two times this captured non-0 character ); // End of loop return s.replaceAll("((.)+)\\2","$1"); // Reduce every repeated character amount by 1, // and return this as result } // End of method ``` [Answer] # [Haskell](https://www.haskell.org/), 84 bytes ``` f s@(x:r)|(n:m,x:r)<-span(`elem`['0'..'9'])s=(x<$[1..read$n:m])++f r|1<3=x:f r f e=e ``` [Try it online!](https://tio.run/##FYrRCoMgGEbv9xReBBr//Mnc1hYqe48Ikk1ZrGRYF1307s5uPs45fB@7fN00peTJ8mRbG8udhXY@H6T48rOBDW5y89DRiiLSB@3LRbNNFZ1AjM6@i3zvSwBP4i6U1Fub6eSJ0y7NdgxEkzGsLtrXSnwSFXQGjATTgMlyUbyXpgY0gA3UKAFrdai45jn0xvHOcwRU@Ac "Haskell – Try It Online") **Explanation:** `span(`elem`['0'..'9'])s` splits the given string `s` into a prefix of digits and the remainder. Matching on the result on the pattern `(n:m,x:r)` ensures that the digit prefix is non-empty and binds the character after the digits to `x` and the remainder to `r`. `x<$[1..read$n:m]` reads the string of digits `n:m` as number and repeats `x` that many times. The result is concatenated to the recursive treatment of the remaining string `r`. [Answer] # [R](https://www.r-project.org/), 151 bytes [Outgolfed by user2390246](https://codegolf.stackexchange.com/questions/146911/rle-brainfuck-dialect/146962#146962)! This is now basically a garbage approach compared to that one, but I'll continue to improve it. ``` function(s,G=substr)for(i in el(strsplit(gsub("(\\d+.)","!\\1!",s),"!")))cat("if"(is.na(g<-as.double(G(i,1,(n=nchar(i))-1))),i,rep(G(i,n,n),g)),sep='') ``` [Try it online!](https://tio.run/##HYyxbsQgEET7fIWP5nYFrIKd5FJg2vuIOAW2wYfkYAtwka93uDSjeTOaSecaxmTTL/y48tjmjC@@0bI5/RGnErYIWdz7fIy5JPRbgtCE2LgVKud9DQWWWgKDYZg5IRPsMgzqwkTGahkiTrYAC55ByBQtLFraTPN2jKuDOwShBMQ@Tg9bvxGlqhMRRHL7fxtFRLHUKLu9v17x9MDUK/8y3HTc3Lip8Kbld2daTobTjbfUcWr1E9V7lSd@SPqUNeSkieH5Bw "R – Try It Online") Also outputs a bunch of warnings. ``` function(s){ s <- gsub("(\\d+.)","!\\1!",s) # surround groups with ! X <- el(strsplit(s,"!")) # split to groups for( i in X ){ # iterate over groups n <- nchar(i) # length of group r <- substr(i,1,n-1) # potential number (first n-1 chars) d <- substr(i,n,n) # last character if( is.na(as.double(r)) ){ # if it's not a number cat(i) # print out the whole string } else { cat(rep(d,as.double(r)),sep="") # repeat d r times, and print with no separator } } } ``` Next up, seeing if using a `grep` is more efficient than `substr` [Answer] ## JavaScript (ES6), 46 bytes ``` a=>a.replace(/(\d+)(.)/g,(_,n,b)=>b.repeat(n)) ``` Pretty straightforward explanation: ``` a=>a.replace(/(\d+)(.)/g, // Match globally the following: a number N followed by a character (_,n,b)=>b.repeat(n)) // Replace each occurrence by the matched character repeated N times ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 35 bytes ``` ->s{s.gsub(/(\d+)(.)/){$2*$1.to_i}} ``` [Try it online!](https://tio.run/##FcjRCoIwGIbhW/FAcOtjn22r7GD9N2ISSBAdJc2BIV77micvPO83jb@83LKRuEa@YhpVq@5PaEXd6rV2h9py/jze25arKc2xWvrGHtELxEM6SMEpmMGLAwXs4OhBF3bac8nOi@HVlAkGNkP@Aw "Ruby – Try It Online") [Answer] ## [Untyped Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus), 452 bytes ``` (λp.λq.(λb.λg.(λi.(λp.λq.λb.p q b)(q(λq.λj.λl.j((λq.λj.qλq.λl.(λu.g i j(λp.u)(g j(λq.λg.q(b(p(λp.λq.p q))(p(λp.λq.p(p q)))q g))(λp.u)(λu.u qλq.λu.g j i q(b l(p(λp.λq.p(p(p(p q)))))q u))))λp.p(λp.λb.q p((λp.λq.l(λp.l)(λp.λq.p q)(λq.p j q)q)p b))λp.λp.p)l q))(λp.p)(λp.p(λp.λp.p)λp.λp.p)(λp.λq.p)))(b(p(λp.λp.p))(p(λp.λq.p(p q)))))(λp.λq.λb.p(q b))λp.λq.q(λp.λq.λb.p(λp.λb.b(p q))(λp.b)λp.p)p)λp.λq.λb.q(q(q(q(q(q(p q b)))))) ``` Input and output comprise of [right-fold](https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29#Folds_on_lists) lists of [church encoded](https://en.wikipedia.org/wiki/Church_encoding) character codes, for example the character code of a newline is 10 so the church encoding would be `λf.λx.f(f(f(f(f(f(f(f(f(f x)))))))))`. Converting "ABCD" to a list looks like `λf.λx.f 65 (f 66 (f 67 (f 68 x)))` but with the numbers church-encoded. Applying an encoded string to the program and reducing it all the way should give you an encoded output string with the RLE applied. [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), 42 bytes ``` s=>s::gsub("(\\d+)(.)",(_,a,b)=>b::rep(a)) ``` [Try it online!](https://tio.run/##FcxBCsIwEIXhu2Q1wySDTdRKSOYibZEGjYhQSmMXnj6mmwffW/x5Xz6/mmMtUYr3r7InUDCOD0JgVBruetYJoyTvt@cKM2Jdt/fyhQyqO9EgJI6kJ2k4BzM5scRC3JNlR2zDwe7S5uDV8M20kziwaqk/ "Funky – Try It Online") [Answer] ## C++, ~~239~~ 235 bytes -4 bytes thanks to Zacharý ``` #include<regex> using s=std::string;std::regex m("[0-9]*[<>+.,\\[\\]-]");s t(s r){s d,h;std::sregex_iterator i(r.begin(),r.end(),m),e;while(i!=e){h=(*i)[0];int g=std::strtol(h.data(),NULL,10);g+=!g;d+=s(g,h[h.size()-1]);++i;}return d;} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ▒tP☻↕╘`¼½ª√ΘBöQm>\%▒IïR} ``` [Run and debug it](https://staxlang.xyz/#p=b174500212d460acaba6fbe94294516d3e5c25b1498b527d&i=10%2B%5B%3E%2B%3E3%2B%3E7%2B%3E10%2B4%3C-%5D3%3E2%2B.%3E%2B.7%2B2.3%2B.2%3C2%2B.%3E15%2B.%3E.3%2B.6-.8-.2%3C%2B.%3C.) Regex replace and execute. [Answer] # [///](https://esolangs.org/wiki////), 114 bytes ``` /a/*l//b/l*//l/\/\///1/0a2/1a3/2a4/3a5/4a6/5a7/6a8/7a9/8a*0/9a0*/|l0l/|l/*>/>>b</<<b+/++b-/--b[/[[b]/]]b,/,,b./../ ``` [Try it online!](https://tio.run/##HY07CsMwEAX7HEWyNPLfBuOLKCp2IZBCndvc3dGahTfNm7dXlev7ue4bwVVQqoPKux30JBnoZWSQiVFmJlmYZWWRjVV2NnGJXZLjV1NtgTs5Tz04DvV4r4EQNJOzFkrRjq7TSIy0n0@XF87qRjOMJhnNM5pqNNv4DPwB "/// – Try It Online") This is fairly trivial program as far as actual algorithm, it just happens that repeating characters is a strong suit of ///. If you change the specification of the RLE, then its 106 bytes. # [///](https://esolangs.org/wiki////), 106 bytes ``` /b/l*//a/*l//l/\/\///1/0a2/1a3/2a4/3a5/4a6/5a7/6a8/7a9/8a*0/9a0l/*>/>>b</<<b+/++b-/--b[/[[b]/]]b,/,,b./../ ``` [Try it online!](https://tio.run/##FYjBCoQwDAX/p7F5tmq1EPIj3R4SWNhDb/4/XWVgYOYedv@@95xwjAAYwgAGPg9AwmoZyTZk27HZgd0KDjtR7MJpFZeFFdXWgaBQdYGIE4g8IkZvaM07evcFy@IMZsxKTUkzaSGttEnsWROxEhdizsQi9GTaH715RD7jO1l4/gE "/// – Try It Online") A 0 will never occur, and a 1 just adds a byte. 2 is the first number where anything is actually compressed, so it makes much more sense to start at that number. In other words, subtract 1 from each number. This is was the original program, just without the code to subtract one. It takes up so much space because there is an indeterminate amount of zeros at the beginning of each number, depending on the number of digits. If I just used `/0*//` to delete a zero and subtract one, it would delete one for each 0 instead. So it has to add another symbol like this `/0*/|/`, then remove that symbol `/|//`, then remove the `0`s `/0//`. [Commented version](https://tio.run/##JZDRboMwDEXf9xV@m0QgbmlLi4TyI4iHAO6KRpKJhG18PbOZFOXIju174zjb@KK47/iGiNAUkF5ThJFmShTBzjPMk6cn0RghBn4lGMLIl/XQEzzD4mxKNHLZJx3NOVg//o/hY7ncOfIJWeGMp4xVjrch@G9aUoTnEhwLDpOzM6QAq7fLpkHs2DUFHj8N7GODMbCjo5eriJs38KvraQGbIPiBcvh5TcNLZP00kBbJEs8Z44Kl4IoXwQ2vggpvgjtWggfeBTU@BNkJa@GJh3Bk0BjJNtg0QoVKscFx/ZrZXSLonxA314dZLLIfuxB4@k3iNXvn79o1Tv5DFugkx7tb6IusrO5ocNZvkCZHUWxnBRaFsMW2FXbYdcIc81yoUWvca9UaZUplKmVqdWmKrjRnpY3SldK6VLppFIfnK18S3gp9LySpG73/AQ) [Answer] ## Dart, 78 bytes (with regex), 102 bytes (without regex) With Regex: ``` (i)=>i.splitMapJoin(new RegExp(r"(\d+)(.)"),onMatch:(m)=>m[2]*int.parse(m[1])) ``` Without Regex: ``` (i,[n=0,d=0])=>i.codeUnits.map((c)=>i[d++]*((c-=48)>=0&&c<10?0*(n=n*10+c):n<1?1:(n=0*(c=n))+c)).join() ``` Both must be invoked like `(<code here>)("input string")`. Regex one is quite standard, but the regex-less one is quite special. Regex-less abuses optional parameters to allocate local variables in "single return" function, otherwise you'd need to make a block and have the return keyword. For each code unit, if the code unit is between 0 and 9 it is accumulated to `n` and an empty string is returned. Otherwise, the the character is multiplied by the value of `n` (special cased if n == 0, in that case it will always emit 1 character) and `n` is set to 0. `(n=0*(c=n))+c` sets the char code argument to the value of `n`, multiplies `n`/`c` with 0, stores 0 to `n`, then adds `c`. This resets our `n` without being in a statement context. [Answer] # Python3, 96 bytes ``` s,r=input(),"" while s: d=0 while"/"<s[d]<":":d+=1 r+=int(s[:d] or 1)*s[d];s=s[d+1:] print(r) ``` I tried another implementation in Python, but i don't beat <https://codegolf.stackexchange.com/a/146923/56846> :( ]
[Question] [ **Note: the first half of this challenge comes from Martin Ender's previous challenge, [Visualize Bit Weaving](https://codegolf.stackexchange.com/questions/83899/visualise-bit-weaving).** The esoteric programming language [evil](http://esolangs.org/wiki/Evil) has an interesting operation on byte values which it calls "weaving". It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric): * Bit 0 is moved to bit 2 * Bit 1 is moved to bit 0 * Bit 2 is moved to bit 4 * Bit 3 is moved to bit 1 * Bit 4 is moved to bit 6 * Bit 5 is moved to bit 3 * Bit 6 is moved to bit 7 * Bit 7 is moved to bit 5 For convenience, here are three other representations of the permutation. As a cycle: ``` (02467531) ``` As a mapping: ``` 57361402 -> 76543210 -> 64725031 ``` And as a list of pairs of the mapping: ``` [[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]] ``` After `8` weavings, the byte is essentially reset. For example, weaving the number `10011101` (which is `157` in base 10) will produce `01110110` (which is `118` in base 10). # Input There are only `256` valid inputs, namely all the integers between `0` and `255` inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten. You may **not** zero-pad your inputs. # Output You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten. You **may** zero-pad your outputs. --- Related: [Visualize Bit Weaving](https://codegolf.stackexchange.com/q/83899/34718) [Answer] # Python 2.7, 44 -> 36 bytes ``` lambda x:x/4&42|x*2&128|x*4&84|x/2&1 ``` [Answer] # Evil, 3 characters ``` rew ``` [Try it online!](http://evil.tryitonline.net/#code=cmV3&input=Pw) Input is in base 256, (e.g. ASCII), e.g. to enter the digit 63, enter ASCII 63 which is `?`. Explanation: ``` r #Read a character e #Weave it w #Display it ``` This *so* feels like cheating. [Answer] ## CJam, ~~15~~ 12 bytes *Thanks to FryAmTheEggman for saving 3 bytes.* ``` l8Te[m!6532= ``` Input in base 2. Output also in base 2, padded to 8 bits with zeros. [Test it here.](http://cjam.aditsu.net/#code=l8Te%5Bm!6532%3D&input=10011101) ### Explanation ``` l e# Read the input. 8Te[ e# Left-pad it to 8 elements with zeros. m! e# Generate all permutations (with duplicates, i.e. treating equal elements e# in different positions distinctly). 6532= e# Select the 6533rd, which happens to permute the elements like [1 3 0 5 2 7 4 6]. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` &8B[2K1B3D5C]) ``` Input is in decimal. Output is zero-padded binary. [**Try it online!**](http://matl.tryitonline.net/#code=JjhCWzJLMUIzRDVDXSk&input=MTU3) ### Explanation ``` &8B % Take input number implicitly. Convert to binary array with 8 digits [2K1B3D5C] % Push array [2 4 1 6 3 8 5 7] ) % Index first array with second array. Implicitly display ``` [Answer] # Jelly, 11 bytes ``` +⁹BḊŒ!6533ị ``` Translation of Martin’s CJam answer. [Try it here.](http://jelly.tryitonline.net/#code=fOKBuULhuIrFkiE2NTMz4buL&input=&args=MTU3) ``` +⁹BḊ Translate (x+256) to binary and chop off the MSB. This essentially zero-pads the list to 8 bits. Œ! Generate all permutations of this list. 6533ị Index the 6533rd one. ``` [Answer] ## JavaScript (ES6), 30 bytes ``` f=n=>n*4&84|n*2&128|n/2&1|n/4&42 ``` [Answer] # C (unsafe macro), 39 bytes ``` #define w(v)v*4&84|v*2&128|v/2&1|v/4&42 ``` # C (function), 41 bytes ``` w(v){return v*4&84|v*2&128|v/2&1|v/4&42;} ``` # C (full program), 59 bytes ``` main(v){scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;} ``` (returns via exit code, so invoke with `echo "157" | ./weave;echo $?`) # C (standards-compliant full program), 86 bytes ``` #include<stdio.h> int main(){int v;scanf("%d",&v);return v*4&84|v*2&128|v/2&1|v/4&42;} ``` # C (standards-compliant full program with no compiler warnings), 95 bytes ``` #include<stdio.h> int main(){int v;scanf("%d",&v);return (v*4&84)|(v*2&128)|(v/2&1)|(v/4&42);} ``` # C (standards-compliant full program with no compiler warnings which can read from arguments or stdin and includes error/range checking), 262 bytes ``` #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main(int v,char**p){v=v<2?isatty(0)&&puts("Value?"),scanf("%d",&v)?v:-1:strtol(p[1],p,10);exit(*p==p[1]||v&255^v?fprintf(stderr,"Invalid value\n"):!printf("%d\n",(v*4&84)|(v*2&128)|(v/2&1)|(v/4&42)));} ``` ### Breakdown Pretty much the same as a lot of existing answers: bit-shift all the bits into place by using `<<2` (`*4`), `<<1` (`*2`), `>>1` (`/2`) and `>>2` (`/4`), then `|` it all together. The rest is nothing but different flavours of boiler-plate. [Answer] # x86 machine code, 20 bytes In hex: ``` 89C22455C1E002D0E0D1E880E2AAC0EA0211D0C3 ``` It's a procedure taking input and returning result via AL register ## Disassembly ``` 89 c2 mov edx,eax 24 55 and al,0x55 ;Clear odd bits c1 e0 02 shl eax,0x2 ;Shift left, bit 6 goes to AH... d0 e0 shl al,1 ;...and doesn't affected by this shift d1 e8 shr eax,1 ;Shift bits to their's target positions 80 e2 aa and dl,0xaa ;Clear even bits c0 ea 02 shr dl,0x2 ;Shift right, bit 1 goes to CF 11 d0 adc eax,edx ;EAX=EAX+EDX+CF c3 ret ``` [Answer] # J, 12 bytes ``` 6532 A._8&{. ``` Uses the permute builtin `A.` with permutation index `6532` which corresponds to the bit-weaving operation. ## Usage Input is a list of binary digits. Output is a zero-padded list of 8 binary digits. ``` f =: 6532 A._8&{. f 1 0 0 1 1 1 0 1 0 1 1 1 0 1 1 0 f 1 1 1 0 1 1 0 1 1 0 1 1 0 0 1 ``` ## Explanation ``` 6532 A._8&{. Input: s _8&{. Takes the list 8 values from the list, filling with zeros at the front if the length(s) is less than 8 6532 The permutation index for bit-weaving A. permute the list of digits by that index and return ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 39 bytes ``` +`^(?!.{8}) 0 (.)(.) $2$1 \B(.)(.) $2$1 ``` Input and output in base 2, output is left-padded. [Try it online!](http://retina.tryitonline.net/#code=K2BeKD8hLns4fSkKMAooLikoLikKJDIkMQpcQiguKSguKQokMiQx&input=MTAwMTExMDE) ## Explanation ``` +`^(?!.{8}) 0 ``` This just left-pads the input with zeros. The `+` indicates that this stage is repeated until the string stops changing. It matches the beginning of the string as long as there are less than 8 characters in it, and inserts a `0` in that position. Now for the actual permutation. The straight-forward solution is this: ``` (.)(.)(.)(.)(.)(.)(.)(.) $2$4$1$6$3$8$5$7 ``` However that's painfully long and redundant. I found a different formulation of the permutation that is much easier to implement in Retina (`X` represents a swap of adjacent bits): ``` 1 2 3 4 5 6 7 8 X X X X 2 1 4 3 6 5 8 7 X X X 2 4 1 6 3 8 5 7 ``` Now that's much easier to implement: ``` (.)(.) $2$1 ``` This simply matches two characters and swaps them. Since matches don't overlap, this swaps all four pairs. ``` \B(.)(.) $2$1 ``` Now we want to do the same thing again, but we want to skip the first character. The easiest way to do so is to require that the match *doesn't* start at a word boundary with `\B`. [Answer] # Mathematica, 34 bytes ``` PadLeft[#,8][[{2,4,1,6,3,8,5,7}]]& ``` Anonymous function. Takes a list of binary digits, and outputs a padded list of 8 binary digits. [Answer] ## PowerShell v2+, 34 bytes ``` ("{0:D8}"-f$args)[1,3,0,5,2,7,4,6] ``` Translation of @LegionMammal978's [answer](https://codegolf.stackexchange.com/a/84015/42963). Full program. Takes input via command-line argument as a binary number, outputs as a binary array, zero-padded. The `"{0:D8}"-f` portion uses [standard numeric format strings](https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx) to prepend `0` to the input `$args`. Since the `-f` operator supports taking an array as input, and we've explicitly said to use the first element `{0:`, we don't need to do the usual `$args[0]`. We encapsulate that string in parens, then index into it `[1,3,0,5,2,7,4,6]` with the weaving. The resultant array is left on the pipeline and output is implicit. ### Examples *(the default `.ToString()` for an array has the separator as ``n`, so that's why the output is newline separated here)* ``` PS C:\Tools\Scripts\golfing> .\golf-bit-weaving.ps1 10011101 0 1 1 1 0 1 1 0 PS C:\Tools\Scripts\golfing> .\golf-bit-weaving.ps1 1111 0 0 0 1 0 1 1 1 ``` [Answer] ## Matlab, ~~49~~ ~~48~~ 44 bytes ``` s=sprintf('%08s',input(''));s('24163857'-48) ``` Takes input as string of binary values. Output padded. 4 bytes saved thanks to @Luis Mendo. **Explanation:** ``` input('') -- takes input s=sprintf('%08s',...) -- pads with zeros to obtain 8 digits s('24163857'-48) -- takes positions [2 4 1 6 3 8 5 7] from s (48 is code for '0') ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 17 bytes ``` 8é0$7hd|òxplò2|@q ``` [Try it online!](http://v.tryitonline.net/#code=OMOpMCQ3aGR8w7J4cGzDsjJ8QHE&input=MTAwMTExMDE) This takes input and output in binary. Most of the byte count comes from padding it with 0's. If padding the input was allowed, we could just do: ``` òxplò2|@q ``` Thanks to [Martin's solution](https://codegolf.stackexchange.com/a/84044/31716) for the method of swapping characters, e.g: ``` 1 2 3 4 5 6 7 8 X X X X 2 1 4 3 6 5 8 7 X X X 2 4 1 6 3 8 5 7 ``` Explanation: ``` 8é0 "Insert 8 '0' characters $ "Move to the end of the current line 7h "Move 7 characters back d| "Delete until the first character ò ò "Recursively: xp "Swap 2 characters l "And move to the right 2| "Move to the second column @q "And repeat our last recursive command. ``` [Answer] ## 05AB1E, ~~14~~ 12 bytes ``` žz+b¦œ6532èJ ``` **Explanation** ``` žz+b¦ # convert to binary padded with 0's to 8 digits œ6532è # get the 6532th permutation of the binary number J # join and implicitly print ``` Input is in base 10. Output is in base 2. Borrows the permutation trick from [MartinEnder's CJam answer](https://codegolf.stackexchange.com/a/84011/47066) [Try it online](http://05ab1e.tryitonline.net/#code=xb56K2LCpsWTNjUzMsOoSg&input=MTU3) [Answer] # Pyth, 19 characters ``` s[@z1.it%2tzP%2z@z6 ``` Input and output are base 2. Far from a Pyth expert, but since no one else has answered with it yet I gave it a shot. Explanation: ``` s[ # combine the 3 parts to a collection and then join them @z1 # bit 1 goes to bit 0 .i # interleave the next two collections t%2tz # bits 3,5,7; t is used before z to offset the index by 1 P%2z # bits 0,2,4 @z6 # bit 6 goes to bit 7 ``` [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), ~~27~~ 26 bytes ``` _1@ &,)}}}=}}=}}=}!{!!{{!" ``` Input and output in base 2. Output is padded. [Try it online!](http://labyrinth.tryitonline.net/#code=XzFACiYsKX19fT19fT19fT19IXshIXt7ISI&input=MTAwMTExMDE) [Answer] # [UGL](https://github.com/schas002/Unipants-Golfing-Language/blob/gh-pages/README.md), 50 bytes ``` cuuRir/r/r/r/r/r/r/%@@%@@%@@%@@@%@@%@@%@@@oooooooo ``` [Try it online!](http://schas002.github.io/Unipants-Golfing-Language/?code=Y3V1UmlyL3Ivci9yL3Ivci9yLyVAQCVAQCVAQCVAQEAlQEAlQEAlQEBAb29vb29vb28&input=MTU3) Repeatedly div-mod by 2, and then `%` swap and `@` roll to get them in the right order. Input in base-ten, output in base-two. [Answer] ## vi, 27 bytes ``` 8I0<ESC>$7hc0lxp<ESC>l"qd0xp3@q03@q ``` Where `<ESC>` represents the Escape character. I/O is in binary, output is padded. 24 bytes in vim: ``` 8I0<ESC>$7hd0xpqqlxpq2@q03@q ``` [Answer] ## Actually, 27 bytes ``` '08*+7~@tñiWi┐W13052746k♂└Σ ``` [Try it online!](http://actually.tryitonline.net/#code=JzA4Kis3fkB0w7FpV2nilJBXMTMwNTI3NDZr4pmC4pSUzqM&input=JzEn) This program does input and output as a binary string (output is zero-padded to 8 bits). Explanation: ``` '08*+7~@tñiWi┐W13052746k♂└Σ '08*+ prepend 8 zeroes 7~@t last 8 characters (a[:~7]) ñi enumerate, flatten Wi┐W for each (i, v) pair: push v to register i 13052746k push [1,3,0,5,2,7,4,6] (the permutation order, zero-indexed) ♂└ for each value: push the value in that register Σ concatenate the strings ``` [Answer] # JavaScript, 98 Bytes Input is taken in base-2 as a string, output is also base-2 as a string ``` n=>(n.length<8?n="0".repeat(8-n.length)+n:0,a="13052746",t=n,n.split``.map((e,i)=>t[a[i]]).join``) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I/O as binary strings ``` ùT8 á g6532 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=czI&code=%2bVQ4IOEgZzY1MzI&footer=Vm4y&input=MTU3) - header & footer convert from and to decimal. ]
[Question] [ ## Challenge Given a string such as `Hello World!`, break it down into its character values: `72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33`. Then calculate the difference between each consecutive pair of characters: `29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67`. Finally, sum them and print the final result: `-39`. ## Rules * Standard loopholes apply * No using pre-made functions that perform this exact task * Creative solutions encouraged * Have fun * This is marked as [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins but will not be selected. [Answer] # Python, 29 bytes ``` lambda s:ord(s[-1])-ord(s[0]) ``` The sum of the differences forms a telescopic series, so most summands cancel out and **(s1 - s0) + (s2 - s1) + … + (sn-1 - sn-2) + (sn - sn-1) = sn - s0**. If taking a byte string as input is allowed ``` lambda s:s[-1]-s[0] ``` will work as well for **19 bytes**. Test both on [Ideone](http://ideone.com/QAHFMZ). [Answer] # [MATL](http://github.com/lmendo/MATL), 2 bytes ``` ds ``` [Try it online!](http://matl.tryitonline.net/#code=ZHM&input=J0hlbGxvIFdvcmxkISc) Explanation: `d` gets the difference between consecutive characters and `s` sums the resulting array. Then, the value on top of the stack is implicitly printed. Not much else to say about that. Interestingly enough, even though Dennis discovered an awesome shortcut, using it would be significantly longer in MATL. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes ``` OIS ``` [Try it online!](http://jelly.tryitonline.net/#code=T0lT&input=&args=SGVsbG8gV29ybGQh) Take the `O`rdinals of the input string’s characters, then the `I`ncrements of that list, then the `S`um of *that* list. [Answer] # MATLAB, 16 bytes ``` @(x)sum(diff(x)) ``` This creates an anonymous function named `ans` which can be called like: `ans('Hello world!')`. Here is an [online demo](http://ideone.com/G4SqQh) in Octave which requires an additional byte `+` to explicitly convert the input string to a numeric array prior to computing the element-to-element difference [Answer] # Python, 63 bytes ``` x=map(ord,input()) print sum(map(lambda(a,b):b-a,zip(x,x[1:]))) ``` [Ideone it!](http://ideone.com/n9rEpI) [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 13 bytes Cubix is a 2-dimensional language wrapped around a cube. ``` i?u//O-t#;/.@ ``` [**Test it online!**](https://ethproductions.github.io/cubix/?code=aT91Ly9PLXQjOy8uQA==&input=SGVsbG8sIFdvcmxkIQ==) This maps to the following cube net: ``` i ? u / / O - t # ; / . @ . . . . . . . . . . . ``` Where the IP (instruction pointer) starts at the top-left of the far-left face. ### How it works First, the IP hits the mirror `/` which redirects it onto the `i` on the top face. The top face is a loop which continually inputs charcodes until EOF is reached. When the input is empty, the result of `i` is -1; the IP turns left from the `?`, hitting the `/` on the far right face and going through the following commands: * `;` - Pop the top item (-1). * `#` - Push the length of the stack. * `t` - Pop the top item and get the item at that index in the stack. This pulls up the bottom item. * `-` - Subtract. * `O` - Output as an integer. * `/` - Deflects the IP to the `@`, which ends the program. [Answer] ## JavaScript ES6, ~~42~~ 39 Bytes ``` f= s=>s[x='charCodeAt'](s.length-1)-s[x](); ; console.log(f.toString().length); // 39 console.log(f('Hello World!')) // -39 ``` Using @Dennis observation about telescope sums. ~~I think in this case the trivial solution is the shortest.~~ Saved 3 bytes by getting rid of th the `charCodeAt` repetition as suggested by @Neil. [Answer] # C#, 22 bytes ``` s=>s[s.Length-1]-s[0]; ``` Full source code with test case: ``` using System; namespace StringCumulativeSlope { class Program { static void Main(string[] args) { Func<string,int>f= s=>s[s.Length-1]-s[0]; Console.WriteLine(f("Hello World!")); } } } ``` # C# with LINQ, 17 bytes A shorter version, using LINQ, thanks to [hstde](https://codegolf.stackexchange.com/users/59728/hstde): ``` s=>s.Last()-s[0]; ``` However, an extra import is necessary: ``` using System.Linq; ``` [Answer] ## Ruby, 23 bytes ``` ->s{s[-1].ord-s[0].ord} ``` Assign to a variable like `f=->s{s[-1].ord-s[0].ord}` and call like `f["Hello World!"]` Uses Dennis's observation about telescopic series. [Answer] # reticular, 12 bytes ``` idVc~@qVc-o; ``` [Try it online!](http://reticular.tryitonline.net/#code=aWRWY35AcVZjLW87&input=SGVsbG8sIFdvcmxkIQ) Using [Dennis's observation](https://codegolf.stackexchange.com/a/94524/31957), we can shorten an iterative process into a simpler one. ``` idVc~@qVc-o; i take input d duplicate V pop input copy, push last character c get its char code ~ put it under the input in the stack @q reverse the item at the top of the stack V get the last item of that (first item of input) c convert to char - subtract o output ; and terminate ``` [Answer] # [Brain-Flak](http://github.com/DJMcMayhem/Brain-Flak), 51 bytes 48 bytes of code plus three bytes for the `-a` flag, which enables ASCII input (but decimal output. How convenient. :D) ``` {([{}]({})<>)<>}<>{}([]<>){({}[()])<>({}{})<>}<> ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eyhbe31dKHt9KTw-KTw-fTw-e30oW108Pil7KHt9WygpXSk8Pih7fXt9KTw-fTw-&input=SGVsbG8gd29ybGQh&args=LWE) This ones a *little* bit harder than my other answer, haha. Lets walk through it. ``` { While the top of the stack is nonzero: ( Push: [{}] The top of the stack times negative one. Pop this off. ({}) Plus the value on top of the stack, which is duplicated to save for later. <> On to the other stack ) <> Move back to the first stack } <> After the loop, move back again. {} We have one extra element on the stack, so pop it ([]<>) Push the height of the alternate stack back onto the first stack { While the top of the stack is nonzero: ({}[()]) Decrement this stack <> Move back to the alternate stack ({}{}) Sum the top two elements <> Move back tothe first stack } <> Switch back to the stack holding the sum ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` Ç¥O ``` [**Try it Online!**](http://05ab1e.tryitonline.net/#code=w4fCpU8&input=SGVsbG8gd29ybGQh) Uses CP-1252 encoding. **Explanation** ``` Ç Converts input string to ASCII ¥ Compute difference between successive elements O Sum the result ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 7 bytes ``` @c$)@[- ``` [Try it online!](http://brachylog.tryitonline.net/#code=QGMkKUBbLQ&input=IkhlbGxvIFdvcmxkISI&args=Wg) ### Explanation ``` @c Convert "Hello World!" to [72,101,108,108,111,32,87,111,114,108,100,33] $) Circular permute right: [33,72,101,108,108,111,32,87,111,114,108,100] @[ Take a prefix of the list - Subtract ``` Since subtract only works for an input of two integers, it will succeed once the selected prefix is `[33, 72]`. [Answer] # Haskell, 32 bytes ``` g=fromEnum f t=g(last t)-g(t!!0) ``` [Answer] ## R, 69 43 32 bytes A very non-competing answer although I thought it'd be fun to showcase a possible solution in R. ``` sum(diff(strtoi(sapply(strsplit(readline(),"")[[1]],charToRaw),16L))) ``` The only interesting aspect of this answer is the use of `sapply`and `charToRaw`. First I split the string into a vector of characters that I want to convert into its ASCII integer representations. The `charToRaw` function is not vectorized in R and instead of looping over each value in aforementioned vector I use `sapply` which effectively vectorizes the function. Subsequently take 1st difference and then sum. --- Edit: Turns out `charToRaw` transform a string into a vector where each element is the raw representation of each character, hence no need to use `strsplit` and `sapply` ``` sum(diff(strtoi(charToRaw(readline()),16))) ``` Edit2: Turns out there is an even better way, the function `utf8ToInt(x)` does exactly what `strtoi(charToRaw(x),16)` which means we can save a few more bytes (Idea taken from @rturnbull's [answer](https://codegolf.stackexchange.com/a/94582/56989) to another question): ``` sum(diff(utf8ToInt(readline()))) ``` [Answer] # Perl, 19 bytes Includes +1 for `-p` Give input on STDIN ***without final newline*** ``` echo -n "Hello World!" | slope.pl; echo ``` `slope.pl`: ``` #!/usr/bin/perl -p $_=-ord()+ord chop ``` If you are sure the input string has at least 2 characters this 17 byte version works too: ``` #!/usr/bin/perl -p $_=ord(chop)-ord ``` [Answer] # NodeJS, 82 bytes ``` x=process.argv[2],a=[],t=0;for(y in x)a[y]=x.charCodeAt(y),t+=y!=0?a[y]-a[y-1]:0 ``` Explanation: ``` x = process.argv[2] // Get the input a=[], // Initializes an array to store the differences' values. t=0; // Initializes a variable to store the total of the differences for(y in x) // Iterates over the string as an array of characters a[y]=x.charCodeAt(y) // Transforms the input into an array of integers t+=y!=0?a[y]-a[y-1]:0 // Add the difference of the last two characters, except at the first iteration ``` # JavaScript, 79 bytes ``` f=x=>{a=[],t=0;for(y in x)a[y]=x.charCodeAt(y),t+=y!=0?a[y]-a[y-1]:0;return t} ``` Same idea as above with a function input instead of an argument. [Answer] # Forth, 28 bytes ``` : f depth 1- roll swap - . ; ``` Takes a list of characters on the stack (Forth's standard method of taking parameters.) The characters are taken such that the top of the stack is the first character of the string. I move the bottom of the stack to the top, swap, then subtract and print. Garbage is left on the stack, and output is printed to stdout. If each character were pushed to the stack in order instead of reverse order, the program would be 2 bytes shorter. Not sure if that's allowed, though, because normally you push arguments in reverse order. [**Try it online**](https://repl.it/Dhf3) Called like this: ``` 33 100 108 114 111 87 32 111 108 108 101 72 f ``` [Answer] # Java, 42 ``` int f(char[]c){return c[c.length-1]-c[0];} ``` Ungolfed: ``` int f(char[] c) { return c[c.length - 1] - c[0]; } ``` Explanation: This uses the same principle as telescoping: ``` sum = c[4] - c[3] + c[3] - c[2] + c[2] - c[1] + c[1] - c[0] = c[4] - c[0] ``` Generalized for any sequence of characters of length `n`, the answer is `c[n-1] - c[0]` because all the stuff in the middle cancels out. [Answer] # PHP 7.1, ~~33~~ 31 bytes Uses [negative string offsets](https://wiki.php.net/rfc/negative-string-offsets) implemented in PHP 7.1. ``` echo ord($argn[-1])-ord($argn); ``` Run like this: ``` echo 'Hello World!' | php -nR 'echo ord($argn[-1])-ord($argn);';echo ``` # Tweaks * Saved 2 bytes by using `$argn` [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 142 Bytes, Non-competing ``` function tostack 'b' asoc stack 'a' asoc 0 'v' asoc b pop byte 'o' asoc b len while [ v o b pop byte ] 'o' asoc - + 'v' asoc b len end [ v end ``` Non-competing, as the 'tostack' command was added after the discovery of this challenge (even though it has a terrible byte count) # Test Cases ``` Hello, World! -39 Cool, huh? -4 ``` # Explanation ``` function # Push the function between this and end to the stack tostack 'b' asoc # Convert the implicit input to a stack, associate it with 'b' 0 'v' asoc # Push 0 to the stack, associate it with 'v' b pop byte 'o' asoc # Pop the top value of b (The end of the input), get the byte value, associate it with 'o'. b len # Push the size of b to the stack while [ # While the top of the stack is truthy, pop the top of the stack v # Push v to the stack o # Push o to the stack b pop byte # Pop the top value of b, push the byte value of that to the stack ] 'o' asoc # Push a copy of the top of the stack, associate it with 'o' - # Subtract the top of the stack from one underneith that, In this case, the old value of o and the byte. + # Sum the top of the stack and underneith that, that is, the difference of the old value and new, and the total value 'v' asoc # Associate it with 'v' b len # Push the size of b to the stack (which acts as the conditional for the next itteration) end [ # Pop the top of the stack, which will likely be the left over size of b v # Push the value of v to the top of the stack end # Implicitely returned / printed ``` RProgN is an esoteric language I've been working on with Reverse Polish Notation in mind. It's currently pretty verbose, with it's variable assignment being 4 characters, and such, however I plan to in future add a bit of syntatic sugar. Also, RProgN implicitly accesses arguments from the stack, and returns them the same way. Any string data left in the stack after the program has finished, is implicitly printed. [Answer] # PHP, 36 bytes ``` <?=ord(strrev($s=$argv[1]))-ord($s); ``` * Every character but the first and the last are added and substracted once each. → sum of differences == difference between first and last character * `ord()` in PHP operates on the first character of a string → no need to explicitly reduce it to a single character [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~34~~ 32 + 3 = 35 bytes +3 because of the `-a` flag required for ascii mode. [Try it online](http://brain-flak.tryitonline.net/#code=KChbXVsoKV0pe1t7fXt9XSh7fSkoW11bKCldKX08Pik&input=SGVsbG8gV29ybGQh&args=LWE) ``` (([][()]){[{}{}]({})([][()])}<>) ``` Strangely it is more efficient to actually use the definition used in the specs rather than the "trick" of subtracting first from last. This works by doing exactly that. ``` ( ) Push ([][()]){[{}]...([][()])} While the stack has more than one item [{}]({}) Subtract the top from a copy of the second <> Switch ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), ~~8~~ 5 bytes *Big thanks to Dennis for two suggestions that removed 3 bytes* ``` l)\c- ``` [Try it online!](http://cjam.tryitonline.net/#code=bClcYy0&input=SGVsbG8gV29ybGQh) ### Explanation Computes last value minus first value. ``` l e# Read line as a string ) e# Push original string except last char, then last char \ e# Swap c e# Convert to char: gives the first element of the string - e# Subtract. Implicitly display ``` [Answer] # Haskell, 36 bytes ``` sum.(tail>>=zipWith(-)).map fromEnum ``` usage: ``` Prelude> (sum.(tail>>=zipWith(-)).map fromEnum)"Hello World!" -39 ``` # Haskell (Lambdabot), 31 bytes ``` sum.(tail>>=zipWith(-)).map ord ``` [Answer] # [Zsh](https://www.zsh.org/), 22 bytes ``` c=${1[-1]} <<<$[#1-#c] ``` [Try it online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikJOZl2qtkJLPVZxaoqCrq6ACEvifbKtSbRitaxhby2VjY6MSrWyoq5wc@z8lHyjnkZqTk6@jUJ5flJOiyIXM43LPz09JqkyFcvX09LiiY7kcUQEXAA "Zsh – Try It Online") In arithmetic mode, `#name` gets the character code of the first character in `name`. We set `c` to the last character, and take the difference between the first and last codes. [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` (-).x.last<*>x.head x=fromEnum ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NXU69CLyexuMRGy65CLyM1MYWrwjatKD/XNa80939uYmaegq1CQVFmXomCikKagpIHUGe@Qnh@UU6KotL/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") Subtracts the ordinal value of the last character from the first one. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 3 bytes ``` C¯N ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=C%C2%AFN&inputs=Hello%20World!&header=&footer=) Charcodes, deltas, negate. [Answer] # [Seed](https://github.com/TryItOnline/seed), 4039 bytes Doesn't seem to work on TIO, but it works when coupled with FBBI. ``` 14 8414852681982816833433372790810698364813132893898716362540459584022688625798264387975418828592568753770315758610479370948681922136495546332842108359182479433966535765905179459065388440010157609978582001324769124099052737381611149373840917627724397208407089028643895012022628742573222012294052825237085324348444982290123104121122461666554733775475271788467486276475996175601885295303147702452726755226593471202120020410091199743017659208335573154423152801819978230729474715612051171341032334263365083856632777830962888838362419197925323841920453373876672857133617794914410360730116004434899654147180698957725800385129472017678272345459812820971385979547803648176092646145140068284050765640658811309016564056046407942182022651820035228362009982528504039804533767866420627382353719046483891910293375462106828387996245797761671261225013254207748981048605554765186147388853719963818083208243777244635745476307692488230092953697945832727395511335923455041158708566455516940361128710445734129517551071425980383868245384850414606859858328386070419359939079803074746512275418226197202836571384766956166619631171689844438573861785835116965466345655300077072895442275382922411155969198031415738356480027632734767683173461182290664943587642194391696717872166867654883153215102039820352237331385538370736495673578435286268786644516575547497324796824104315134626042330000705635177425450889072765711268672415205890660238315815153396544582388726425393852710118827047025185722269256146833775842006903080438150231695467021895363092529052520574194449676863598714517983262264357148485564703497878252076796987453939376614487678998151538038216932183036887648867146010916400020167219699363649810398529289241805610816901261682694481335373706251300527833925871180538483186233363575543039834652936143724765476480508305310882619200753413549214001157046401271519191156669194718305689324989237259136640434177325764364988116134945176126598820243998840443809752937520515344100617592630708925293861813249878688056870983944233809329996471811576900931997780578487934118491491633897231317094843722600453017152923803380210221974284736694358834261070630538144378201331181295164165912573101108878664104307565822507660429342648076645023021168927208404041863975881061432156693032967007545907712594685762148986214769140105389660472663019317931289961882347209090166368043206503779209112395539888113389407785335974662862517349671898791744588250308875572231759349870386015999899867730850506155358755663748614960022707399194198125201119524711715917827843321904976384404399309909866117302648386221353990707105795689319200425475186294089244622996442050731852097029817043141662937032584233928974737956370762054769055740438112740398572042024506348722650458410985546474473013737717240921600206923559721606463255613663371594880700597771926022187507689847687858240678832570285874435337075457716552831708888345356267662827783367565953777183820536859644451652595212270478985957060226344344006615328799484309837681549308387846900027966717655132797273586137694817492623636158543337389070780557382062590460928510862319381296648463287607060777913950944590945611345871683722732511843519102329506670894902511012732849359818448234315652916582556004294329878892425996281732479821424288647852769164824964729074599862314905063617436396577181901208863286669417671633028568895553965730176671535168886849416991134495839198428309058778632557423424054558897220151969306175456749531391645847260474651558039451142732356612220356880561099668248940964860594234916534549758712951241624081205523001565783316244873255420507329913573024484261568206576447347928383571365849256478051564364025715977517184173481323212119208578654500149740498811223293108994963782665818483798181705998628126622874671206108670316343107440206697310762264893261199201322114098489434319045842881613392743422024262546473060171303072727645787087619741180752610519691334159796822881314093039453830533166310770923481605656257998247400453809665413874039582375952009490304856930435790676573549004040517995168920956454944956745597460627149165715 ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$4\log\_{256}(96)\approx\$ 3.29 bytes ``` Oz[S ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhZL_KuigyFMqMiCtR6pOTn5Ogrl-UU5KYoQQQA) Takes the challenge literally, as that's the shortest way. ``` Oz[S # Implicit input O # Ordinals z[ # Deltas S # Sum # Implicit output ``` ]
[Question] [ For once, I was doing some real work, updating old code, and bumped into an expression that is equivalent to what would be written as ***œÄx + ex*** in good old-fashioned math. I thought it would be possible to write it shorter than it was written in the language I work with (APL), and therefore present this very simple challenge: Write a function or program that (by any means) accepts zero or more numbers, and returns (by any means) the result of the above expression for ***x =*** *each of the given numbers* with at least 3 significant digits for each result. If your language does not have ***œÄ*** and/or ***e***, use the values 3.142 and 2.718. Scoring is number of bytes, so preface your answer with `# LanguageName, 00 bytes`. Standard loop-holes are not allowed. --- Edit: Now the solution I came up with, `‚óã+*`, [has been found](https://codegolf.stackexchange.com/a/67278/43319). The original code was `(‚óãx)+*x`. [Answer] # Emotinomicon, 48 bytes / 13 characters *I do it, not because it is short, but because it is fun.* [Try it here.](http://conorobrien-foxx.github.io/Emotinomicon/int.html) You'll have to copy+paste it into the textbox. ``` üòº‚è™üÜôüò¶‚úñüòéüòø‚ûïüò®üòºüÜôüòÑ‚è© ``` Explanation: ``` üòº ‚è™ üÜô üò¶ ‚úñ üòé üòø ‚ûï üòº üÜô üòÑ ‚è© explanation üòº take numeric input ‚è™ open loop üÜô duplicate top of stack üò¶ push pi ‚úñ multiply top two elements on stack üòé reverse stack üòø pop N, push e^N ‚ûï add top two elements on stack üòº take numeric input üÜô duplicate top of stack üòÑ pop N, push N+1 ‚è© close loop ``` Here is the program in its native environment, the mobile phone: [![the image](https://i.stack.imgur.com/MJ0rI.png)](https://i.stack.imgur.com/MJ0rI.png) [Answer] # Dyalog APL, 3 characters As a tacit phrase. ``` ‚óã+* ``` Monadic `‚óã` multiplies its argument with π, monadic `*` is the exponential function `exp`. `‚óã+*` is a train such that `(‚óã+*)œâ` is equal to `(‚óãœâ)+(*œâ)`. Since this is APL, the phrase works for arguments of arbitrary shape, e. g. you can pass a vector of arbitrary length. The same solution is possible in J as `o.+^` with `o.` being `‚óã` and `^` being `*`. [Answer] # R, ~~25~~ 24 bytes ``` cat(exp(x<-scan())+pi*x) ``` Is this it? It gets input from user, assign it to `x`, calculates its exponential multiply it to `pi`, and finally `cat()`prints the result. edit: 1 bytes saved thanks to [Alex A.](https://codegolf.stackexchange.com/users/20469/alex-a) [Answer] # JavaScript (ES6), ~~39~~ 34 bytes *Saved 5 bytes thanks to @edc65* ``` a=>a.map(x=>x*Math.PI+Math.exp(x)) ``` Takes input as an array of numbers, and outputs in the same format. Thanks to the reduction, there are now three equivalent 45-byte programs, all ES5-compliant: ``` for(;x=prompt();)alert(x*Math.PI+Math.exp(x)) for(M=Math;x=prompt();)alert(x*M.PI+M.exp(x)) with(Math)for(;x=prompt();)alert(x*PI+exp(x)) ``` Inputs should be entered one at a time. Press OK without entering anything to quit. The third one highlights an interesting feature in JS: the `with` statement. While sometimes unsafe to use (thus disabled in strict mode), it can still be used to save typing out an object name and period every time you need to access it. For example, you can do this: ``` x=[];with(x)for(i=0;i<5;i++)push(length); ``` `push` and `length` are then used as properties of `x`, which will result with `x` being `[0,1,2,3,4]`. This works on *any* object, even non-variables, so for example, you can do this: ``` with("0123456789ABCDEF")for(i=0;i<length;i++)alert("0x"+charAt(i)-0); ``` `charAt` and `length` are called as properties of the string. `"0x"+x-0` converts `x` from a hex value to a number, so this `alert`s the numbers 0 through 15. [Answer] # Mathematica, ~~11~~ 10 bytes ``` N@Pi#+E^#& ``` With 1 byte saved thanks to LegionMammal978. [Answer] # Pyth, ~~11~~ 13 ``` VQ+*N.n0^.n1N ``` Now takes `x` as a list, e.g. `[1.25, 2.38, 25]` Previous (11 bytes): `+*Q.n0^.n1Q` ``` VQ + * N .n0 ^ .n1 N For each Add List Item * Pi e ^ List Item input item ``` [Answer] ## Seriously, 10 bytes ``` ,`;e(‚ï¶*+`M ``` Hex Dump: ``` 2c603b6528cb2a2b604d ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=2c603b6528cb2a2b604d&input=[1,2,3,4,5]) Takes inputs as a list (see link for example). Explanation: ``` , Get input list ` `M Map this function over it ; Copy the input value. e exponentiate ( dig up the other copy ‚ï¶* multiply by pi + add ``` [Answer] # MATLAB, 15 bytes ``` @(x)pi*x+exp(x) ``` [Answer] # TI-BASIC, 5 bytes ``` œÄAns+e^(Ans ``` TI-BASIC doesn't use ASCII bytes, so each of these is stored as one byte in the calculator: `œÄ`, `Ans`, `+`, `e^(`, and `Ans`. It assumes the previous expression is the input (like `{1,2,3}`). [Answer] # Python 2, 38 bytes (~~52~~ 49 bytes w. math) ``` lambda l:[3.142*x+2.718**x for x in l] ``` If I have to use the math module: ``` from math import* lambda l:[pi*x+e**x for x in l] ``` Input should be a list of numbers ``` f([1,2,3,4,5]) > [5.8599999999999994, 13.671524, 29.505290232, 67.143510850576007, 164.04623849186558] ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes This answer uses the current version of the language ([3.1.0](https://github.com/lmendo/MATL/releases/tag/3.1.0)), which is earlier than the challenge. ``` itYP*wZe+ ``` Input is a vector containing all numbers (list enclosed by square brackets and separated by spaces, commas of semicolons), such as `[5.3 -7 3+2j]`. Complex values are allowed. Output has 15 significant digits. ### Example ``` >> matl itYP*wZe+ > [1 2 3] 5.859874482048839 13.67224140611024 29.51031488395705 ``` ### Explanation Straightforward operations: ``` i % input t % duplicate YP % pi * % multiplication w % swap elements in stack Ze % exponential + % addition ``` [Answer] ## MATLAB: 70 bytes ``` @(x)num2str(arrayfun(@(x)(round(pi*x+exp(x),2-floor(log10(pi*x+exp(x))))),x)) ``` Test: ``` ans(1:10) 5.86 13.7 29.5 67.2 164 422 1120 3010 8130 22100 ``` Explanation: There were several issues with number formatting. Firstly, the question requires 3 sig-figs. Matlab has no built-in function for rounding by sig-figs (only by decimal places), so the following workaround was required: `floor(log10(pi*x+exp(x))))` computes the largest significant digit. `@(x)(round(pi*x+exp(x),2-floor(log10(pi*x+exp(x))))),x))` takes input `x` and rounds to 3 significant digits. Another requirement was to handle multiple inputs. The above code can work only with single number. To mitigate this, we use `arrayfun` to evaluate the function for each vector element. The last problem, Matlab displays the result of arrayfun with its own rounding that leads to outputs like `1.0e+04 * 0.0006` which violates the 3 sig-fig requirement. So, `num2str` was used to turn array into `char` format. Matlab is good for numerical analysis, but, frankly, it sucks when it comes to fine number formatting UPD: well, that's embarrassing that I confused > > with at least 3 significant digits > > > with > > with 3 significant digits > > > Anyway, I'll leave my answer in this form because the 15 bytes Matlab solution is already given by @costrom [Answer] # Julia, 12 bytes ``` x->œÄ*x+e.^x ``` This is an anonymous function that accepts an array and returns an array of floats. To call it, give it a name, e.g. `f=x->...`. Julia has built-in constants `œÄ` and `e` for‚Äîyou guessed it‚ÄîœÄ and e, respectively. The `.^` operator is vectorized exponentiation. [Answer] # Japt, 12 bytes ``` N¬Æ*M.P+M.EpZ ``` Takes input as space-separated numbers. [Try it online!](http://ethproductions.github.io/japt?v=master&code=Tq4qTS5QK00uRXBa&input=MSAyIDMgNCA1) ### How it works ``` N¬Æ *M.P+M.EpZ NmZ{Z*M.P+M.EpZ // Implicit: N = array of inputs, M = Math object NmZ{ // Map each item Z in N to: Z*M.P+ // Z times PI, plus M.EpZ // E to the power of Z. // Implicit: output last expression ``` [Answer] # J, 4 bytes ``` o.+^ ``` Same as APL `‚óã+*`, but J's `pi times` function is called `o.`, which is one byte longer. [Answer] ## Haskell, ~~22~~ 19 bytes ``` map(\x->pi*x+exp x) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802N7FAI6ZC164gU6tCO7WiQKFC839uYmaegq1CQVFmXomCikKaQrShjpGOcex/AA "Haskell ‚Äì Try It Online") Edit: -3 bytes thanks to @H.PWiz [Answer] # [Par](http://ypnypn.github.io/Par/), 8 bytes ``` ‚ú∂[‚Ä≥‚Ñó‚ÜîœÄ*+ ``` Accepts input as `(1 2 3)` ## Explanation ``` ## [implicit: read line] ‚ú∂ ## Parse input as array of numbers [ ## Map ‚Ä≥ ## Duplicate ‚Ñó ## e to the power ‚Üî ## Swap œÄ* ## Multiply by œÄ + ## Add ``` [Answer] # [Racket](http://racket-lang.org), 27 bytes ``` map(Œª(x)(+(* pi x)(exp x))) ``` when put in the function position of an expression: ``` (map(Œª(x)(+(* pi x)(exp x))) '(1 2 3 4)) > '(5.859874482048838 13.672241406110237 29.510314883957047 67.16452064750341) ``` [Answer] # CJam, 13 bytes ``` q~{_P*\me+}%p ``` Takes input as an array separated by spaces (e.g. `[1 2 3]`). [Try it online.](http://cjam.aditsu.net/#code=q~%7B_P*%5Cme%2B%7D%25p&input=%5B1%202%203%5D) ### Explanation ``` q~ e# Read the input and evaluate it as an array { e# Do this for each number x in the array... _P* e# Multiply x by pi \me e# Take the exponential of x (same as e^x) + e# Add the two results together }% p e# Pretty print the final array with spaces ``` [Answer] # Reng v.3.3, 53 bytes Noncompeting because it postdates the challenge, but hey, not winning any awards for brevity. :P [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) ``` 2¬≤5¬≥*:"G"(%3+i#II*ZA*9+(%2+#E1II0e1+√∏ 1-)E*(:0e√∏ $+n~ ``` ## Line 0 Here is a view of the stack in line 0: ``` Sequence read | Stack 2¬≤ | 4 5¬≥ | 4 125 * | 500 : | 500 500 "G" | 500 500 71 ( | 500 71 500 % | 500 0.142 3+ | 500 3.142 i | 500 3.142 <i> #I | 500 3.142 ; I <- i I | 500 3.142 <i> * | 500 3.142*<i> ZA | 500 3.142*<i> 35 10 * | 500 3.142*<i> 350 9+ | 500 3.142*<i> 359 ( | 3.142*<i> 359 500 % | 3.142*<i> 0.718 2+ | 3.142*<i> 2.718 #E | 3.142*<i> ; E <- 2.718 1II0 | 3.142*<i> 1 <i> <i> 0 e | 3.142*<i> 1 <i> <i>==0 1+ | 3.142*<i> 1 <i> (<i>==0)+1 ``` `√∏` then goes to the next Nth line. When `0` is input, this goes straight to line 2. Otherwise, we go to line 1. ## Line 1 ``` 1-)E*(:0e√∏ ``` This multiples E `i` times, which is `e^i`. We decrement the counter (initially `I`), multiply the STOS (our running `e` power) by E, go back to the counter, and do this (`i'` is the current counter): ``` Sequence read | Stack (partial) | i' : | i' i' 0 | i' i' 0 e | i' i'==0 ``` `√∏` then does one of two things. If the counter is not 0, then we go to the "next" 0th line, i.e., the beginning of the current line. If it is zero, then `0e` yields 1, and goes to the next line. ## Line 2 ``` $+n~ ``` `$` drops the counter (ON THE FLOOR!). `+` adds the top two results, `n` outputs that number, and `~` quits the program. Case 1: input is 0. The TOS is 1 ("e^0") and the STOS is 0 (pi\*0). Adding them yields the correct result. Case 2: input is not 0. The result is as you might expect. ]
[Question] [ A very simple challenge today. Output a truthy value whether the ASCII character (or it's code) supplied is a brainfuck instruction (one of `+-,.<>[]`), and a falsy value if it's a comment (everything else). ## Input ``` + # < > . P , ``` ## Output ``` true false true true true false true ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~105~~ ~~103~~ 95 bytes Outputs `\x00` for false and `\x01` for true. ``` ,>>>+++++++[<++++++<++++>>-]<+[<<->>-]<<[-[-[-[--------------[--[>+[<->-]<[--[<->[-]]]]]]]]]<+. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fx87OThsCom0gNJiys9ONtQEK2eiCWTbRuhCIAoDcaDugIl2QEhAHyIrWjYUBG229//9jAQ "brainfuck ‚Äì Try It Online") The general principle is comparing against all values (decreasing partial distances of the char-codes), using loops to logically `OR` the results, and if none matched - change the output cell from `1` to `0`. See my [`4` answer](https://codegolf.stackexchange.com/a/203339/65326) for a more detailed explanation (`4` instructions read more easily). [Answer] # [unsure](https://github.com/Radvylf/unsure), 1302 bytes ``` um um yeah err hm yeah uhhhhhhhh then ummmm uhhh errrr uhh errr ummmmm yeah err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops um then heh then uhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops um then heh then uhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops um then heh then uhhhhhh no oops oops then ummmmmmm uh errr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops um then heh then uhhhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops um then heh then uhhhh no oops oops then ummmmmm uhhh ummmmm errrrrr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops um then heh then uhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops um then heh then uhh no oops oops oops okay ``` This was not easy. Unsure is a new stack based language I've created, that uses words people tend to say when they're not sure about something. It's kind of hard to explain how such a large program works, but I'll try to give a high-level explanation. First, here's an expanded version of this program: ``` um um yeah err hm yeah uhhhhhhhh then ummmm uhhh errrr uhh errr ummmmm yeah err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops um then heh then uhhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops um then heh then uhhhhhhh no oops oops then um err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops um then heh then uhhhhhh no oops oops then ummmmmmm uh errr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops um then heh then uhhhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops um then heh then uhhhh no oops oops then ummmmmm uhhh ummmmm errrrrr uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops um then heh then uhhh no oops oops then umm err uh then heh then err um heh but um um yeah err heh no oops then but oops heh oops um then heh then uhh no oops oops oops okay ``` The first part sets up the stacks. There are two stacks, one of which is selected as the active stack. The first stack contains a `0` at the bottom (the return value), as well as 8 copies of the input character's ASCII character code, negated. After this, there are 8 sections to check for equality (first one shown as an example): ``` then heh then err um heh but um um yeah err heh no oops then but oops heh oops oops oops oops oops oops oops oops um then heh then uhhhhhhhhh no oops oops then um err uh ``` The first line will pop the first stack and add it to the first, which in this case is `43` (the character code for `+`). It also pushes `1` to the first stack. The next line is essentially an if statement, which is used to create a NOT operator by pushing `0` to the first stack if the result of adding the character code is not `0` (meaning they are not the same). The third line is the most complicated. It starts with a sort of else statement, as it only runs when the second line's if statement doesn't push `0` (and therefore the character code was 43). It will then replace the bottom of the first stack with `1`, the new output. Finally, after the "else statement", the character code is incremented to 44, for `,`, and the process is repeated 7 times. The last line, `oops okay`, just outputs the bottom item in the first stack, as the previous operations have cleared it out except for one copy of the input (`oops` discards the top of the stack, and `okay` outputs). There's definitely a few bytes I could golf here and there, might work on it later. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 9 bytes ``` []+-.<>[] ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPzpWW1fPxi469v9/bS5lLhsuOy49rgAuHQA "Retina 0.8.2 ‚Äì Try It Online") Link includes test cases. Explanation: This is actually a character class; the outer `[]`s delimit the class, as (by being placed immediately after the opening `[`) the first `]` is actually part of the class. The `,` isn't needed as the `-` creates a range from `+` to `.` which helpfully includes the `-` itself as well as the `,`. [Answer] # [Python](https://docs.python.org/2/), 16 bytes ``` '+-,.<>[]'.count ``` [Try it online!](https://tio.run/##K6gsycjPM/qfpmAb819dW1dHz8YuOlZdLzm/NK/kf3lGZk6qgqFVQVFmXolCmkZRYnl8Zl5BaYmGpuZ/bS5lLhsuOy49rgAuHS4A "Python 2 ‚Äì Try It Online") An anonymous method is shorter here than a `lambda`. See my tip [Object method as answer](https://codegolf.stackexchange.com/a/95156/20260). [Answer] ## [vJASS](https://wc3modding.info/pages/vjass-documentation/) ([Warcraft 3](https://playwarcraft3.com/en-us/)), ~~299~~ ~~278~~ 265 bytes Using `//! import zinc "<code_path>"` command to exclude `//! zinc` and `//! endzinc`. --- Prints T (True) and F (False). ``` library Q{trigger W=CreateTrigger();integer E;function onInit(){TriggerRegisterPlayerChatEvent(W,Player(0),"",false);TriggerAddAction(W,function(){for(0<=E<8){if(GetEventPlayerChatString()==SubString("+-<>.,[]",E,E+1)){BJDebugMsg("T");return;}}BJDebugMsg("F");});}} ``` --- **Readable Version:** ``` library CodeGolf{ trigger chatEvent = CreateTrigger(); integer Index; function onInit(){ TriggerRegisterPlayerChatEvent(chatEvent, Player(0), "", false); TriggerAddAction(chatEvent, function(){ for (0 <= Index < 8){ if(GetEventPlayerChatString() == SubString("+-<>.,[]", Index, Index + 1)) { BJDebugMsg("T"); return; } } BJDebugMsg("F"); }); } } ``` --- [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes +1 due to a bug fix noted by @Kevin Cruijssen -1 thanks to @Kevin Cruijssen ``` "+-,.<["¬∫I√• ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fSVtXR88mWunQLs/DS///jwYA "05AB1E ‚Äì Try It Online") an interesting approach, but sadly it's longer and it doesn't work: ``` ‚Ä¢q‚Äù;Œπ√ö‚Ä¢2√¥I√á;√Æ√• ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcOiwkcNc63P7Tw8C8g2OrzF83C79eF1h5f@/x8NAA "05AB1E ‚Äì Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 18 bytes ``` (`elem`"+-.,<>[]") ``` [Try it online!](https://tio.run/##FYlBDoIwEADv@4oNXiBAXwC9eDbhrkY2uIXG7drYvt9aTzOTOSi9WKQ4nPFW2pWFw9r0oxkme703XQnktb6d8/mtmTUntHbGQPHywPjxmtH8C1tX5WB6dpXilVPp4QQTWDCwwPDdnNCeyrjF@AM "Haskell ‚Äì Try It Online") Low-effort unnamed function. [Answer] # [4](https://github.com/urielieli/py-four), 131 bytes Outputs `\x00` for false, `\x01` for true. ``` 3.799600006010160202614146292964343199994389919999018991999901899199990189919999148991999902899199992989919999028995004999999995014 ``` [Try it online!](https://tio.run/##fchBCoBADEPRAwmStJlq7n@wOgwquPGvHl/duR92YVYgWAhEUVSFw6VU0jPlaS@Bf6LeF4/CnzcA@W6A6t4u "4 ‚Äì Try It Online") ## Explanation **4 doesn't have a simple comparison or condition instructions**, so I used while-not-zero loops to fake them and match by distances: ``` 3. 6 00 00 # set constants 6 01 01 6 02 02 6 14 14 6 29 29 6 43 43 7 99 # input as integer 1 99 99 43 - 8 99 # for each brainfuck character 1 99 99 01 - 8 99 # compare to the input, 1 99 99 01 - 8 99 # (subtracting differences to the input) 1 99 99 01 - 8 99 # and jump to the end if true, 1 99 99 14 - 8 99 # otherwise start a loop (to fake branching) 1 99 99 02 - 8 99 1 99 99 29 - 8 99 1 99 99 02 - 8 99 5 00 4 # if all comparisons failed, print 'false' and exit 9 9 9 9 9 9 9 9 # close loops 5 01 4 # print 'true' and exit ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 28 bytes ``` f(c){c=index("+-,.<>[]",c);} ``` No math here, no math there, no math anywhere. [Try it online!](https://tio.run/##LYyxDoIwFEX3fsXLMyStLcSZAm7ODm7qQB4gTbSYAkZC@PZaiHe5yT25h@IHkfcNJzFTbmxVfznKWCVZcb2jIqEXb@wAr9JY/ulMJdjMIITa0sHeWMgB5S4rkrNCzTbUdI7rgLSxUoptWvN2QdRwjCiFqL9ZVOtfQcNDCTgCXtw4tBNCCngqn/2E4m909TA6CwfNFv8D "C (gcc) ‚Äì Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 3 bytes Built-ins FTW! ``` ~B{ ``` [Try it online!](https://tio.run/##K6jMTv3/v86p@v9/JW0lAA "Pyke ‚Äì Try It Online") # Explanation ``` ~B "><+-.,[]" { Does it contain input? ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~26~~, 23 bytes ``` lambda s:s in'+-,.<>[]' ``` [Try it online!](https://tio.run/##K6gsycjPM/6fpmAb8z8nMTcpJVGh2KpYITNPXVtXR8/GLjpW/X9BUWZeiUaaRmZeQWmJhqam5n9tAA "Python 3 ‚Äì Try It Online") [Answer] # [Fig](https://github.com/Seggan/Fig), \$10\log\_{256}(96)\approx\$ 8.231 bytes ``` Ix"[]-=.," ``` [Try it online!](https://fig.fly.dev/#WyJJeFwiW10tPS4sXCIiLCIsIl0=) ~~An answer so the bot can get 30 rep to chat.~~ Never mind, realized I had enough on SF&F, but deleting this would be useless, so here ya go. [Answer] # 6502 assembly, 17 bytes ``` 0000: 69 05 29 FD A2 04 D5 0C 0008: F0 03 CA D0 F9 60 30 31 0010: 41 ``` This subroutine should be called with A set to the input, and the carry flag cleared. It will return with the Z flag indicating whether the input was a Brainfuck instruction. Here the subroutine is at `$0000` but it can go anywhere on the zero page. The asterisk in `cmp *r-1,x` forces a 2-byte zero-page-based comparison (in [this web assembler](https://www.masswerk.at/6502/assembler.html), at least). ``` .org $0000 f: adc #5 and #$fd ldx #4 loop: cmp *r-1,x beq r dex bne loop r: rts ; which is #$60 .byte $30, $31, $41 ``` ## How it works The valid Brainfuck instructions are {2b, 2c, 2d, 2e, 3c, 3e, 5b, 5d} in hexadecimal. Adding 5 to the ASCII values groups them into pairs like "n or n+2" where the second-lowest bit doesn't matter: | Instruction | ord+5 | Bit pattern | | --- | --- | --- | | `+` or `-` | `$30` or `$32` | 0011 00x0 | | `,` or `.` | `$31` or `$33` | 0011 00x1 | | `<` or `>` | `$41` or `$43` | 0100 00x1 | | `[` or `]` | `$60` or `$62` | 0110 00x0 | This means we can check if `(n+5)&~2` ‚àà {`$30`, `$31`, `$41`, `$60`}. Actually a lot of choices other than `5` work. But this one puts `$60` in the set of values to look for, which is the opcode for the `RTS` instruction. Thus we can interleave the table with the final instruction and save one byte. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), `-rt`, 10 bytes ``` -`[]+-,.<> ``` This: * Pushes the string `[]+-,.<>` onto the stack * Subtracts that string from the input. If it is a BF instruction, an empty string will be printed, otherwise, the input character will be printed. [Answer] # Python 3, 26 bytes ``` print(input()in"+-,.<>[]") ``` [Answer] # [Desmos](https://www.desmos.com/calculator), 43 bytes ``` 1\left\{42<i<47,i=60,i=62,i=91,i=93\right\} ``` [Try it online](https://www.desmos.com/calculator/gcyjw2zlqh) Desmos doesn't support strings, so this turns from relatively trivial string comparison to relatively trivial integer comparison. I tried to compress the higher numbers, but I couldn't find a nice way to exclude 61 and 92, and the sequence doesn't show up in OEIS. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-¬°`](https://codegolf.meta.stackexchange.com/a/14339/), 63 bits / 7.875 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` o"+,-.<>[] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LaE&code=byIrLC0uPD5bXQ&input=Iisi) (Because, apparently, we're scoring in bits now? ü§∑ü躂Äç‚ôÇÔ∏è) [Answer] # 6502 Machine-Language, 32 bytes ``` 0000: AD 1E 00 A2 00 DD 15 00 0008: D0 04 EE 1F 00 00 E8 EC 0010: 1D 00 D0 F1 00 3C 3E 2B 0018: 2D 2E 2C 5B 5D 08 50 00 ``` The above "ROM" includes the variables and the program. Here's a basic breakdown: ``` 0000: AD 1D 00 A2 00 DD 14 00 Program 0008: D0 04 EE 1E 00 00 E8 EC 0010: 1C 00 D0 F1 00 3C 3E 2B Brainfuck instructions 0018: 2D 2E 2C 5B 5D 08 ("<>+-.,[]" and an 8 for the length) 50 00 Input char and output byte ``` You can try it out using [This online emulator](https://www.masswerk.at/6502/) by copying the above ROM into the "RAM" field and setting the input byte (`0x001D`) to the desired character in hexadecimal. Then you can load it into memory by pressing "Load Memory", then press "Show Memory" to confirm it loaded and check the box "live update" so it will show the result once it's done. Finally, you can press "Continuous Run" and it will write the result to the last byte of the ROM (`0x001E`). `0x01` for true and `0x00` for false. Assembly Code: ``` .ORG $0000 ; PROGRAM LDA INPUT LDX #0 loop: CMP CHARS,X BNE end INC OUTPUT BRK end: INX CPX CHARSLEN BNE loop BRK ; DATA CHARS: .ASCII "<>+-.,[]" CHARSLEN: .BYTE 8 INPUT: .ASCII "P" OUTPUT: .BYTE 0 ``` To summarise, it basically reads the input character into the accumulator and then loops over the list of Brainfuck instructions using the X register and if Acc matches any of the chars it increments the output byte and exits. It's probably not very good and could also probably be smaller, but I'm not very experienced with 6502 assembly and just wanted to give it a go. Feedback welcome :) (I also haven't tested it very thoroughly so it might also not work in some cases) [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` k≈ª$∆á ``` **11 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md):** ``` "[]<>-+.,"$∆á ``` **14 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md):** ``` ¬ª√ê·πòWƒ†≈ì·π™…≤¬ª…¶BCs∆á ``` **16 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md):** ``` C¬ø‚Ǩ·ªµ√¶-j2o·∫π&‚ŵ·∫è¬øs∆á ``` Due to a bug with the `∆á` command (which will be fixed in 2.2.0), the `s` is needed in the last two answers. They will both be one byte less in 2.2.0. ### Explanations ``` k≈ª$∆á # Implicit input $ # The input... ∆á # ...is in... k≈ª # ...the string "[]<>-+.," # Implicit output ``` ``` "[]<>-+.,"$∆á # Implicit input $ # The input... ∆á # ...is in... "[]<>-+.," # ...the string "[]<>-+.," # Implicit output ``` ``` ¬ª√ê·πòWƒ†≈ì·π™…≤¬ª…¶BCs∆á # Implicit input ¬ª√ê·πòWƒ†≈ì·π™…≤¬ª # Compressed integer 4344454660629193... …¶B # ...converted to base 100 as a list... C # ...and converted to ordinals... s∆á # ...contains the input # Implicit output ``` ``` C¬ø‚Ǩ·ªµ√¶-j2o·∫π&‚ŵ·∫è¬øs∆á # Implicit input C # The ordinal of the input... s∆á # ...is in... ¬ø‚Ǩ·ªµ√¶-j2o·∫π&‚ŵ·∫è¬ø # ...the compressed list [43, 44, 45, 46, 60, 62, 91, 93] # Implicit output ``` #### Screenshots [![Screenshot 1](https://i.stack.imgur.com/lATq0m.png)](https://i.stack.imgur.com/lATq0.png) [![Screenshot 2](https://i.stack.imgur.com/RWIrBm.png)](https://i.stack.imgur.com/RWIrB.png) [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 45 bytes ``` "<>[]+-,." INPUT :F(F) X =1 F OUTPUT =X END ``` [Try it online!](https://tio.run/##K87LT8rPMfn/X0HJxi46VltXR09JwdMvIDREwcpNw02TSyFCwdaQy03BPzQEJGgbweXq5/L/vx4A "SNOBOL4 (CSNOBOL4) ‚Äì Try It Online") 1 for truthy, empty line for falsey. [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~25~~ 23 bytes *-2 thanks to @Arnauld* ``` c=>/[+-.<>[\]]/.test(c) ``` [Try it online!](https://tio.run/##DcyxDoIwEMbx3ae4ibSpFHVxgLLwCI7I0JwUIXhn2sbF@Oz1ti/55ftv/uMTxvWda@LHXIIr6PpmNLXt@vE@TY3Nc8oKdQkcFYGDUwsEHZwvVxnGaPgeAFDgluNKiw2RX8PTx0F6inQrGuQPVQXIlHif7c6LoiOg4K/8AQ "JavaScript (Node.js) ‚Äì Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 10 bytes ``` /"+-,.<>[] ``` [Try it online!](https://tio.run/##K6gsyfj/X19JW1dHz8YuOvb/fyVdJQA "Pyth ‚Äì Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 18 bytes ``` {it in "+-<>[].,"} ``` [Try it online!](https://tio.run/##y84vycnM@1@WmKOQlGaloOGckVikqaBrp@CUn5@TmpinYPu/OrNEITNPQUlb18YuOlZPR6n2f1ppnkJuYmaehqaCrUJBUWZeiUZSmoa6trqm5n8A "Kotlin ‚Äì Try It Online") [Answer] # [Arn](https://github.com/ZippyMagician/Arn), [9 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn) ``` [‚Äö‚Äö‚óт¥¬£Q7 ``` [Try it!](https://zippymagician.github.io/Arn?code=IistLiw8PltdIiY=&input=Kw==) # Explained Unpacked: `"+-.,<>[]"&` ``` "+-.,<>[]" Literal string & Contains element _ Variable initialized to STDIN; implied ``` [Answer] # Scala 2.12, 15 bytes ``` "<>+-.,[]"toSet ``` This takes the string of all brainf\*\*\* instructions and turns it into a set. Since Scala's sets are also predicates, we can treat it like a function that returns `true` when it's a valid instruction. Scala 2.12 is required for postfix operator `toSet`. [Try it online](https://scastie.scala-lang.org/1zTvpQDQTi2KAQ1iaSUS5Q) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ·∫á‚Äú+-<>[],. ``` [Try it online!](https://tio.run/##y0rNyan8///hrvZHDXO0dW3somN19P4/apjLZX24XdP9/38lZSUdBSVtJQA "Jelly ‚Äì Try It Online") ## How it works ``` ·∫á‚Äú+-<>[],. - Main link. Takes a character C on the left ‚Äú+-<>[],. - Yield "+-<>[],." ·∫á - Is C in that string? ``` [Answer] # Red, 27 bytes ``` ""= exclude input"+-,.<>[]" ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 11 bytes ``` `[]+-.<>,`c ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%60%5B%5D%2B-.%3C%3E%2C%60c&inputs=%5B&header=&footer=) More interestingly, # [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 13 bytes ``` C‚ÇŬª¬Ω¬§«ç‚ãè‚ü®Íòçƒã¬ªœÑc ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=C%E2%82%81%C2%BB%C2%BD%C2%A4%C7%8D%E2%8B%8F%E2%9F%A8%EA%98%8D%C4%8B%C2%BB%CF%84c&inputs=%5B&header=&footer=) ``` C # Get charcode ‚ÇŬª¬Ω¬§«ç‚ãè‚ü®Íòçƒã¬ªœÑ # Base-100 list of valid charcodes c # Is included? ``` [Answer] # [Julia 1.0](http://julialang.org/), 14 bytes ``` in("+-,.<>[]") ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/M09DSVtXR8/GLjpWSfN/Wn6RQqZCZp4CXFA5wNDIWN/KWomroCgzryQnTyNTwdZOIU0jU1OTKzUv5T8A "Julia 1.0 ‚Äì Try It Online") some Julia functions will return an anonymous function when fed with not enough arguments, basically `in(x) = y -> in(y,x)`. It would be a bit more interesting with `‚àà` but it costs 1 more byte. [Answer] # [Pxem](https://esolangs.org/wiki/Pxem) (pxem.mktemp.emb.posixism, `BREAK_LOOP_WHEN_INSUFFICIENT=1`), filename only: 33 bytes. The `\0001` is an unprintable whose codepoint is 0x01. ``` [<>+-,.][[email protected]](/cdn-cgi/l/email-protection)\0001.yT.o.d.a.c.a ``` [Try it online!](https://tio.run/##pTp7X@LIsv/nU/REFCIkAXRGR4yz6KDDGQWP4p3ZI05@MTQShYRNB8EH96vvrerOG2d2z152ZUjXo6vr1VWdfrLY6M@1d/qt4@psJElrZLqgE23yENDJVKOTW23qMWfhsIlGHFe1vQEl54ABDwH1pz6Fb01aA7pjagUznzJ4Iio58iZTK3Bux5TMnWBE3AetyDiRO6ADwqZ06AwdG1A8lxMcPgVUnblOQOyR5Vs28OXjHY@wMQhJXM8n7mw8JkP4MXTG1LUmlKNcBj61JqrnOxT4D0hb73KJvvlOAPOR2yeN9KYWPbbmz9RF@Y4d1xqT2XRgBVQj9Wq9plV3tK0aueodlT8ixqljU5cB8Ah4B84jxRVNPJeR/1DfI49AoKG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YgV4yw8VI3pYbGpDHZ/h3YzoUmXz4sQ8a37PBAqEEF/3dvXjB0Um0d2KM92oN85UYxffWoh@EXd9OdQ5NKxS2EUyAsnh4Cw0FmswfNUhvTADAUspsSPjbwgWlg/Vutomz5H9nv@s/B8 "yash ‚Äì Try It Online") Accepts one character from stdin as an input. Outputs a T for truthy, nothing for falsey. --- # [Pxem](https://esolangs.org/wiki/Pxem) (pxem.mktemp.emb.posixism, `BREAK_LOOP_WHEN_INSUFFICIENT=0`), filename only: 42 bytes. The `\0001` is an unprintable whose codepoint is 0x01. ``` [<>+-,.][[email protected]](/cdn-cgi/l/email-protection)\[[email protected]](/cdn-cgi/l/email-protection) ``` [Try it online!](https://tio.run/##pTp7X9rKtv/nU4wRhQhJAG21YmzRouVUwaN42x6x@cUwSBQSdiYIPrhffd@1ZvLWdu@zr1ZKZj1mzXrNWjN5tNjoz9UV/cZxdTaSpFUyXdCJNrkP6GSq0cmNNvWYs3DYRCOOq9regJIzwICHgPpTn8KnJq0C3RG1gplPGTwRlRx6k6kVODdjSuZOMCLuvVZknMgd0AFhUzp0ho4NKJ7LCQ4eA6rOXCcg9sjyLRv48vGOR9gYhCSu5xN3Nh6TIXwZOmPqWhPKUS4Cn1oT1fMdCvwHpK13uUTffCeA@cjNo0Z6U4seWfMn6qJ8R45rjclsOrACqpF6tV7TqtvaZo1c9g7LHxDjxLGpywB4CLwD54Hiiiaey8h/qO@RByDQUFu3NCBn3Yv29/EjYTNQiMPomDJGqPvg@J47AZEkBkgqnUmzicXuSbW6vU1WYT0BfK3XG8RifE1C5xJdTD0/ICeHZvPkxDiUgscpxWlszx2SfX1AH3Suhvr@eo2srwu4DcJZ7uAteMjvrNn7YsiFUoSpTmOmCAL0mFQpPONQeXcpvqhLOeJy2Wl/Ny96n416tboJi0C5v5ypl9/jaVAXJz/Mw@75eeuwZ9RCpOPO5Z@r5OyyR350L8/J2ffWKbmAb4ct8qV13pKO2ietTvO0ZRSv9vbLakW71hwt@KTNNRt@n7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QIOj10m1oLwBhtgO1XxgzDYVaTwZAUndfhhgZiaQH04puAu5KTbOeZhTwfJ7OG5KFDsG2SzTm4gPPGlmdPmj4MWbFRf8Ybo/IL0uuRz67D9uUXAgr0vrXMcARA5OEwFU9JUmd6UZ@O7inkfx5S4bEqC2QktC/XUKxM7e1FJFiLfQ3LApAD1EeCb9/mzSgCxaLfgFfga68trNvwx8oKXSP3@Sr9fgP82dBi4sWUuIMp5l3jcnQFTAzjeGe8zUt29kZshsr0phnSy/PDmMknPot69V34ZPcDCwCsEhcSNPldJOezzG3nUlVeoG79CVeXM4W2GSM0RCTpeRe9Vcwf92dnUWkK1zEz5v/JVYe06M@kvTR1ZewMARm7CVwp@or6nDpwHh4G3ya945Dzmd06Tkjm9MqGvgvzRdHTzbtd01oClktvRllLcof2ig2t32r2i1Dk3jNpz8pqBCeXxwAwPgKCSxJPxJWDtG3XY9NLAKF506g5sXUnuAKDpV9JH9UvRYYojpXI5feTErwfE4ftSQoGw2y16NwEwIcyb@Ta0t7zxLe1iA7mppN8bC6/rc20zxwOiN153eq6urm7oS7K5j0cOmH7CqaKb@0F4nR1e2PMMOsR398aPUim8JRFHW9AmQB/6/3qnJvc2zYN4oSb/Nk1ql/5v3qD55bszf31R/fqVmTdelnnrNZnsWzK/fT9GvBnz@sUY8UqMeLtAG@av4ONXwf7hRXx87oEuG04krBu9hCYq1n/IXcGUHGqOd1Ixk4lzO4L2kt6Cr/HXU3l1L3EVZd7S4ITg0Dx@wPmgXQZ5UB0TK8C3/FAxoofFpjbU8Sm@mxG9Xdk8PzZPm98zgQIhxNe9Vf3wXpFJ9G7FqW7UG6eqsYO3FqJfxF1fDnUODasUdpGMQHLYPw2NxRoMrzqkZ2YgYCkldmT8hmBh@VCtq23yFNnv6c/y/wE "yash ‚Äì Try It Online") Accepts one character from stdin as an input. Outputs a T for truthy, nothing for falsey. ]
[Question] [ Given a non-negative integer n, enumerate all palindromic numbers (in decimal) between 0 and n (inclusive range). A palindromic number remains the same when its digits are reversed. The first palindromic numbers (in base 10) are given [here](http://oeis.org/A002113): > > 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, > 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, > 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, > 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, ... > > > This is a code golf with the prize going to fewest characters. The palindromic numbers should be output one per line to stdout. The program should read n from the commandline or stdin. [Answer] ## Perl 5.10, 29 (or 39) characters ``` say for grep$_==reverse,0..<> ``` Needs the `say` feature enabled. 29 chars if you consider that to be free, otherwise 39 to add `use 5.010;`. Argument on STDIN. ## Perl, 35 characters ``` #!perl -l print for grep $_==reverse,0..<> ``` using the old perlgolf convention that `#!perl` is not counted but any flags following it are. ## Perl, 36 characters ``` print$_,$/for grep $_==reverse,0..<> ``` If none of the others qualify. [Answer] ## Befunge 320 313 303 characters (including significant newlines and whitespace) ``` &:#v_v# # :-1< v91:< v < 0 >0.@ >\25**\1-:#^_v pv p09+1g09<^_ >$+ v :>:25*%\25*/:| ^:p18:+1g18\< : > >90g 1-:90p | > ^ >| $^ < >-| ^ #< @ > 0 81p^ >:.25*,^ ^ < ``` I wonder if I could make this smaller by rerouting the paths... Edit: redid the top part to avoid an extra line. [Answer] ## Perl 5.10 - 27 characters `map{say if$_==reverse}0..<>` Reads the argument from stdin. [Answer] ## Golfscript, 15 chars ``` ~),{.`-1%~=},n* ``` [Answer] ## Ruby 1.9, 39 characters ``` puts (?0..gets).select{|i|i==i.reverse} ``` Input (must not be terminated with a newline) via stdin. Example invocation: ``` echo -n 500 | ruby1.9 palinenum.rb ``` 40 characters for a version which uses commandline args: ``` puts (?0..$*[0]).select{|i|i==i.reverse} ``` [Answer] ## [J](http://jsoftware.com/), 20 characters ``` (#~(-:|.)@":"0)>:i.n ``` [Answer] ## Python, 57 51 chars ``` for i in range(input()): if`i`==`i`[::-1]:print i ``` Usage: ``` echo 500 | python palindromic.py ``` [Answer] **Perl > 5.10 : 25 characters** ``` map$_==reverse&&say,0..<> ``` [Answer] ### APL (~~25~~ 17) ``` ↑t/⍨t≡∘⌽¨t←⍕¨0,⍳⎕ ``` [Answer] ## Javascript ~~122~~ ~~108~~ 107 chars... I'm sure this can be golfed more - I'm new to this! ``` n=prompt(o=[]);for(i=0;i<=n;i++)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n")); ``` ### or ``` n=prompt(o=[]);i=-1;while(i++<n)if(i+''==(i+'').split("").reverse().join(""))o.push(i);alert(o.join("\n")); ``` [Answer] ## Perl - 43 chars ``` for$i(0..<>){if($i==reverse$i){print$i,$/}} ``` This is my first attempt at code golf, so I'm pretty sure a Perl pro could golf it down. [Answer] ## Haskell 66 characters ``` main=do n<-readLn;mapM_ putStrLn[s|s<-map show[0..n],s==reverse s] ``` [Answer] **Mathematica 61** ``` Column@Select[0~Range~Input[],#==Reverse@#&@IntegerDigits@#&] ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) ## With the I/O format stated in the question, 8 bytes ``` ≥ℕA↔A≜ẉ⊥ ``` [Try it online!](https://tio.run/nexus/brachylog2#ARoA5f//4oml4oSVQeKGlEHiiZzhuoniiqX//zUwMA) ## With modern PPCG I/O rules, 4 bytes ``` ≥ℕ.↔ ``` [Try it online!](https://tio.run/nexus/brachylog2#q37UtuFRU9Ojzjm1D7ct@P@oc@mjlql6j9qm/P9vagAE/6MA) This is a function that generates all the outputs, not a full program like the previous example, and so doesn't comply with the spec as written, but I thought I'd show how the program would look like if the question had been written to modern I/O standards (which permit the use of functions, and output via generators). # Explanation ``` ≥ℕ.↔ ℕ Generate natural numbers ≥ less than or equal to the input . but output only the ones ↔ that would produce the same output if reversed ``` For the full program version, we create a temporary variable `A` to hold the output, explicitly labelize it (this is done implicitly for the main predicate of a program), and use the well-known `ẉ⊥` technique for outputting a generator's elements to standard output. [Answer] ### Scala 59 ``` (0 to readInt)filter(x=>""+x==(""+x).reverse)mkString("\n") ``` [Answer] ## **PHP, 59 55 53 chars** ``` for($i=0;$i++<$argv[1];)if($i==strrev($i))echo"$i\n"; ``` Usage ``` php palindromic.php 500 ``` Edit : thanks Thomas [Answer] ## C, 98 characters ``` n,i,j,t;main(){for(scanf("%d",&n);i<=n;i-j?1:printf("%d ",i),i++)for(t=i,j=0;t;t/=10)j=j*10+t%10;} ``` [Answer] # k (23 chars) ``` {i@&{&/i=|i:$x}'i:!1+x} ``` [Answer] # Befunge, 97 (grid size 37x4=148) ``` #v&#:< ,*25-$#1._.@ :>:::01-\0v >-!#^_$1- *\25*/:!#v_::1>\#* #*25*#\/#$:_$\25*% `-10:\<+_v# ``` Have a better Befunge answer to this question. This is Befunge-93 specifically; I could probably make it even more compact with Befunge-98. I'll include that in a future edit. Since you can't operate on strings in Befunge, the best I could do was compute the digit-reverse of each number (which I'm surprised I was able to manage without `p` and `g`) and compare it to the original number. The digit-reverse takes up most of the code (basically the entire third and fourth lines). Note that the program, as it stands now, prints the numbers backwards from the input down to 0. If this is a big deal, let me know. (The challenge only says to enumerate them, not specifically in increasing order.) [Answer] ## PHP, ~~64~~ 58 bytes ``` for($i=0;$i<=$argv[1];print$i==strrev($i)?$i.'\n':'',$i++) ``` Changed `$_GET['n']` to `$argv[1]` for command line input. [Answer] # [Perl 5](https://www.perl.org/), 24 bytes ``` map$_-reverse||say,0..<> ``` [Try it online!](https://tio.run/##K0gtyjH9/z83sUAlXrcotSy1qDi1pqY4sVLHQE/Pxu7/f0MDg3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ŻŒḂƇY ``` [Try it online!](https://tio.run/##y0rNyan8///o7qOTHu5oOtYe@f9w@///hgYGAA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ƒNÂQ– ``` Explanation: ``` ƒ # For N in range(0, input() + 1) N # Push N  # Bifurcate (pushes N and N[::-1]) Q # Check for equality – # If true, pop and print N ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=xpJOw4JR4oCT&input=MTAwMA). [Answer] # Python ``` n=raw_input('') for a in range(0,int(n)+1): r=str(a) if str(a)==r[::-1]: print r ``` [Answer] # Groovy, 83 ``` System.in.eachLine{(0..it.toInteger()).each{if("$it"=="$it".reverse())println(it)}} ``` [Answer] # Q (34 chars) Pass n rather than n+1 as an argument for this Q solution. ``` {i(&)({all i=(|)i:($)x}')i:(!)1+x} ``` [Answer] # Q,32 ``` {a(&)a~'((|:)')a:((-3!)')(!)1+x} ``` [Answer] ## Q (33) ``` {if[x="I"$(|:) -3!x;:x]} each til ``` Probably a neater way to do this but anyway, sample usage (you enter n+1 to get to n): ``` q){if[x="I"$(|:) -3!x;:x]} each til 10 0 1 2 3 4 5 6 7 8 9 ``` Suggestion by tmartin, gets it down to 29: ``` ({$[x="I"$(|:) -3!x;x;]}')(!) ``` Same usage. [Answer] ## Python, 106 characters ``` import sys as a print(type(a.argv[1])) for x in range(int(a.argv[1])+1): x=str(x) if x==x[::-1]:print(x) ``` usage: ``` python a.py 500 ``` [Answer] # C# (217 214 191 chars) Golfed version: ``` using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());do{var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}while(n-->0);Console.ReadLine();}} ``` Readable: ``` using System; using System.Linq; class P { static void Main() { int n = int.Parse(Console.ReadLine()); do { var t = (n + "").ToArray(); Array.Reverse(t); Console.Write(n + "" == new string(t) ? n + "\n" : ""); } while (n-->0); Console.ReadLine(); } } ``` This prints out palindromes in descending order making use of the n-->0 operator. (as n goes to 0). \*Edited version replaces do...while with while, saving 3 chars, but now you must input with n+1. ``` using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0){var t=(n+"").ToArray();Array.Reverse(t);Console.Write(n+""==new string(t)?n+"\n":"");}Console.ReadLine();}} ``` \*edited: found a better way to reverse string without converting to array: ``` using System;using System.Linq;class P{static void Main(){int n=int.Parse(Console.ReadLine());while(n-->0)Console.Write(n+""==string.Join("",(""+n).Reverse())?n+"\n":"");Console.ReadLine();}} ``` Readable: ``` using System; using System.Linq; class P { static void Main() { int n = int.Parse(Console.ReadLine()); while (n-->0) Console.Write(n + "" == string.Join("", ("" + n).Reverse()) ? n + "\n" : ""); Console.ReadLine(); } } ``` ]
[Question] [ > > [Cops thread](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread) > > > Your task as robbers is to find cops solutions and write a program in the language provided that computes the nth term of the sequence using only the bytes in the provided set. The goal will be to crack as many cops answers as possible. With each crack awarding you a single point. Cracks need not be the cop's intended solution as long as they work. [Answer] # [Haskell, xnor](https://codegolf.stackexchange.com/a/136239/3852) ``` s=show s ss=show[[s]] w h=[ss!!h]<show[h] ``` [Try it online!](https://tio.run/##JcmxDsIgFEbhnaf4m3SARElZnMQn0Kkj3oHEJjRtKenFwNuj0e3kO8HzMq1ra2w57AUs@F/OMZEoCNYxd12g608Dtc3PERavXQDpncd83CN6ZL9MMMMA5u/YfHpApmOOGRryWXG@QdYTCqpSCs5obS7UPg "Haskell – Try It Online") The first line defines `s` as the fixed point of the `show` function, which is the infinite string ``` "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\... ``` It has `"`s at indices 0, 2, 6, 14, 30… Powers of two, minus two. The second line defines `ss` as the string ``` [["\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\... ``` It has non-`\`s at indices 0, 1, 2, 4, 8, 16, 32… Powers of two, ignoring 0. We’re in luck: in ASCII, `"` < `[` < `\`, so we can write an indicator function for the less-than-backslashes in this string, and we’re done! `w h` is our answer: it checks if the `h`’th element of `ss` is less than a backslash. Well, we can’t construct a string containing only a backslash, so we construct some other string that’s always bigger than `"["`, namely `show[h]`. [Answer] # [Octave](https://www.gnu.org/software/octave/), [Stewie Griffin](https://codegolf.stackexchange.com/a/136187/31957) Anonymous function. ``` @(_)_^('^'/'/') ``` ## Explanation ``` @(_)_^('^'/'/') @(_) % anonymous function taking argument `_` _^ % that argument raised to the power of '^' % 94 / % divided by '/' % 47 % (94 / 47 == 2) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mG/PfQSNeMz5OQz1OXR8INf@naRhr/gcA "Octave – Try It Online") [Answer] # [JavaScript (ES6), Arnauld](https://codegolf.stackexchange.com/a/136238) ``` $=>eval(`${$}${atob(`ICo=`)}${$}`) ``` Outputs `0, 1, 4, 9, 16, 25, ...`. Naming the input `$` makes it look a bit more complex than it has to be. `atob('ICo=')` evaluates to `*` with leading space (found that by hand). This makes `${$}${atob(`ICo=`)}${$}` be `n *n` where `n` is input. `eval`ing gives the square. ``` function t(){Array(10).fill(0).map((_,i)=>console.log(f(i)))} f= $=>eval(`${$}${atob(`ICo=`)}${$}`) ;t() ``` [Answer] # [Python 2, Rod](https://codegolf.stackexchange.com/a/136167/34388) Very suboptimal though. Code: ``` a=sum((()or())) s=g=int(not(a)) for m in range(input()):a,s,g=s,g,sum((s,g)) print(a) ``` [Try it online!](https://tio.run/##HYsxDoAgDEV3T8HYJgzqaNLDdFBkoCUFBk@P1eEn7yfv1affKvucTG0UAEA1QMSlUaIsHUQ7sP9LLZSQJRhLOiFLHd3Fg2OLiXzx7x1crvaljHNu6ws "Python 2 – Try It Online") [Answer] ## Haskell, [Christian Sievers](https://codegolf.stackexchange.com/a/136508/34531) ``` one=product(map(pred)mempty) zero=pred(one) add(a)(b)|a==zero=b|True=add(pred(a))(addone(b)) addone(x)=ao(x)(enumFrom(x)) ao(x)(y)|x==pred(head(y))=head(y)|True=ao(x)(drop(product(map(pred)mempty))y) t(x)|x==zero=zero|x==one=one|True=add(t(pred(x)))(t(pred(pred(x)))) ``` [Try it online!](https://tio.run/##bU@7DsIwDNz5igwM8VJV7F75AjbE4BJLrWgeCqnUov57cNICC0Oss@/su/T0fPA45uwdY4jeTPekLQUdIhuwbENa4PDi6LFMtMjgQMZoAt3BSoiV69ZLnBgLUWUEoKURtajqQoEzIHmpmt1kz9FbwULW0QLrjJtHz2SkB9zBfrvKTPQl2/@cIFGTqMqlGquU0pTPyfuFTFtMsYcP/g4gWxqcQhXi4JI6KrFRSV3bpjm1t/wG "Haskell – Try It Online") Note: the `product(map(pred)mempty)` in line 5 is different to line 1, because the former is of type `Int` whereas the latter is of type `Integer`. [Answer] ## Haskell, [Christian Sievers](https://codegolf.stackexchange.com/a/136647/34531) ``` t = let _:i:_ = [0..] in let n ee ll tt = let _:_:ii:_ = [ee,tt..] in ee : n ll tt ii in (n 0 i i !!) ``` [Try it online!](https://tio.run/##Rc1LCoAwDIThq4zgQkGkuCz0JCLSRcBgWorm/jU@wN3w88Fs8dxJpFZFgJBi9exX27MbxwWcn5hBBBHor8x9kGhQ/bAxb/qlzHfqMhxsoWn6mqKVgHJwVrRIsUCfq8kt9QI "Haskell – Try It Online") [Answer] ## Haskell, [Christian Sievers](https://codegolf.stackexchange.com/a/136914/34531) ``` head.maybe[]id.head[head[flip lookup.zip[head[pred.pred.pred.floor]pi..]].map pure][head[pred.floor]pi..] ``` [Try it online!](https://tio.run/##TYxBDoAgDAS/0oPnRh/gS0gPGEpoRGhQD/p5RD3oZZLdnWyw68wx1urHwNbhYo@JDYnDO5oHPopCzHneFU/Rt9TCDj/4thdSQSRqJwq6F6af@hPqYiXBCFokbdDBrXswA@LQU70A "Haskell – Try It Online") [Answer] # [Python 2, Bruce Forte](https://codegolf.stackexchange.com/a/136619/70424) ``` f=lambda m:-m==m or m*f(m-bool(m)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIddKN9fWNlchv0ghVytNI1c3KT8/RyNXU/N/QVFmXolCmoa55n8A) Wow. This was a fun one. [Answer] # [R, Jarko](https://codegolf.stackexchange.com/a/136155/58974) I don't know R at all, so this is just a guess. ``` identity ``` [Try it online!](https://tio.run/##K/qfZvs/MyU1rySzpPJ/moaF5n8A) [Answer] # [R](https://www.r-project.org/), [Jarko](https://codegolf.stackexchange.com/a/136172/67312) ``` f=function(n)`if`(n,n*f(n-n**(n-n)),n**n) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jTzMhMy1BI08nTytNI083T0sLRGpqAvlaeZr/ixMLCnIqNQysDA100jT/AwA "R – Try It Online") Definitely took me a good five minutes to try and figure out how to get `1` from the letters, but then I remembered that `**` is `^` so that worked out nicely! (and `0^0=1` in R) [Answer] # [cQuents, Step Hen](https://codegolf.stackexchange.com/a/136189/34388) This seems to do the trick: ``` :1+z ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/38pQu@r/f0NTAA "cQuents – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), [dj0wns](https://codegolf.stackexchange.com/a/136203/31957) ``` ??=import<stdlib.h> int main(int a,char**f)<%int h=""==" ",o=""=="",c=h,p=o,m=(int)atof(*(f+o));for(;p<=m;p++)c+=m%p==h;printf("%i",c);%> ``` [Try it online!](https://tio.run/##JY5bCsMgFAX/u4pwQfCVfhaCucla7C1GIUYxrr9W6d8MnIFD80HU2r5jiDmVut71c4b302@PcNUp2nDxAVaTt0VKJ1Y23CMAIkyg059AE3qdMemIoxC2JscldyoJYVwq3OQVo8lKCVIYWUb0Jpc@dRxY6L0wbGutvb7kTnvcbe5fkJblBw "C (gcc) – Try It Online") Digraphs, digraphs everywhere! [Answer] # Ruby, [Value Ink](https://codegolf.stackexchange.com/a/136220/6828) With -n flag, `p$./$$` This is my guess for the intended solution. Ignores the input and just outputs the floor of 1/the process id. Since the process id generally can't be 0 or 1, this should always be 0. [Answer] # [Haskell](https://www.haskell.org/), [Christian Sievers](https://codegolf.stackexchange.com/a/136250/20260) ``` a(n)|pred(pred(abs(n)))==abs(pred(pred(n)))=sum(map(a)(enumFromTo(pred(pred(n)))(pred(n))))|()==()=n ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1EjT7OmoCg1RQNMJCYVAwU0NW1tQSyEOFisuDRXIzexQCNRUyM1rzTXrSg/NyQfTRGCpVmjATQGiPP@5yZm5inYKhQUZeaVKKgoAM1QSFSINtDTMzSI/Q8A "Haskell – Try It Online") [Answer] ## Haskell, [Laikoni](https://codegolf.stackexchange.com/a/136344/56725) If returning an `Int` is good enough, this does it: ``` _F _N=[_N,[_N,[_N..]!!_N..]!!_N..]!!_N ``` [Answer] # Javascript, [iovoid](https://codegolf.stackexchange.com/a/136317/72685) ``` $=>-(-($===-$)) ``` [Try it online!](https://tio.run/##BcFRCoAgDADQy@xjQxbSr627iFksxIVG11/v3fnLswx9Xu52VHcQkJ2REUSEgchPG6gSk25rTFSsT2t1aXYhoIZAlPwH) [Answer] # Haskell, [Christian Sievers](https://codegolf.stackexchange.com/a/136274/71256) ``` u(n)|negate(n)==(n)=negate(pred(n))|True=head(drop(length(enumFrom()))(enumFrom(n))) g(a)(x)|null(x)=a|True=g(u(a))(drop(length(enumFrom()))x) p(a)(b)=pred(g(rem(b)(b))(enumFromTo(negate(b))(a))) a(n)|negate(n)==n||u(negate(pred(n)))==n=n|True=p(a(pred(pred(n))))(a(pred(n))) ``` [Try it online!](https://tio.run/##dU8xDoMwDNx5RYYO9oLoA7L2BWxVB1dYATUJUUokBv6eOkCLhFTJinN3yZ3d0/vF1uacwOPi2dDEctO6HDsMkTuBuLQxse6ZOujiGMCyN1MP7JO7xdEBIh5A3mNlgBBm8U3WSte0WRhIIuBflxmrUH4@Ua/ZBiI7QVJHQjvCPl9hqcTRaQe/LAlOSxRahHUOCdn4n4hfpoDsaPBKqxAHP6mLchQUqXtT19fmkT8) Finally fixed it for Integers rather than Ints. Very slow. [Answer] # [Befunge](https://esolangs.org/wiki/Befunge), [Jordan](https://codegolf.stackexchange.com/a/136421/69481) ``` &>:1-:v ^ _$v >\:v ^ *_$.@ ``` [Try it Online!](https://tio.run/##S0pNK81LT/3/X83OylDXqoxLIU4BCOJVgCwosIuxQnDiFLTiVfQc/v83AwA) [Answer] # [R](https://www.r-project.org/), [Jarko, again](https://codegolf.stackexchange.com/a/136413/67312) ``` cat(diag(diag(('i'%in%'i'):(x=scan()),x%x%x)),sep='') ``` This differs from Jarko Dubbeldam's intended solution, but the general idea is the same: to generate `1:n` repeated `1:n` times, it leverages `diag` in two different ways: * `diag(matrix)` returns the diagonal of a matrix. * `diag(vector, nrow)` generates an `nrow`x`nrow` matrix with `vector` along the diagonal, recycling as necessary. `%x%` is the Kronecker matrix product which when applied to two numbers returns their usual product. Finally, `cat` prints the diagonal out with `sep`arator `''` which results in the sequence. [Try it online!](https://tio.run/##K/r/PzmxRCMlMzEdQmioZ6qrZuapAilNK40K2@LkxDwNTU2dClUgBNLFqQW26uqa/83@AwA "R – Try It Online") [Answer] ## C, [Yimin Rong](https://codegolf.stackexchange.com/a/136677/56725) ``` long long t(long long n, long o){ return o ? t(n,--o)-(-n) : o; } long long r(long n, long o){ return --o ? t(r(n,o),n) : n; } long long g(long n){ return n ? r(n,n) : -(--n); } ``` `t` is multiplication, `r` is exponentiation, `g` is the real function. Newlines added for readability, they aren't needed. [Answer] # [Haskell](https://www.haskell.org/), [Christian Sievers](https://codegolf.stackexchange.com/a/136717/56433) ``` ___ __=[__-__,[[[__..]!!__..]!!__..]!!__..]!!__-[[__..]!!__..]!!__ ``` [Try it online!](https://tio.run/##dU3LCoMwELz3K1booYVs0E1i9OCXBLt4KFSqQdr@fzp6LYVl57Ez7GN6P@/LUtZpzjTQ9przh860ThupKqXa2qYby85Vh6TKqiYlEGvHqvoD/BsozGSN8pBorE4Q@eIzuyue@nwTdnk3a0MNBiDRUBBDXYCWFiuCiYMlPW4uIuQD0sGDtQ5e9EcBuT7ujaY@yl7KFw "Haskell – Try It Online") [Answer] # [R by Jarko Dubbeldam](https://codegolf.stackexchange.com/a/136476/48198) Took me a while since I don't know R and I didn't manage to use `t` twice: ``` cos(pi*(t=scan())/2)/abs(cos(pi*t/2)) ``` [Try it online!](https://tio.run/##K/r/Pzm/WKMgU0ujxLY4OTFPQ1NT30hTPzGpWAMqUQLka/43@A8A) ### Explanation It uses the fact that `cos(t*pi/2)` has a period of `4` in `t` and the sequence starts with: [1, 6.123234e-17, -1, -1.83697e-16]. As you can see the signs are correct, so we just need to normalize the values but keeping the sign - that's what `x/abs(x)` does for `x != 0`. [Check the source!](https://tio.run/##NY5BCsMwDATveYXwSUoPhvRWyC/6AcdxiSGVjKVC83onTdvjzrDsls0W4Wtr02ZJk8EIzjmk3o9DmGJmKWoH6booc/raKIol92ijxsBI5AfyYVL8CTsynZ1SMxu6@5IgyrOEmlUYarJX5TTfwF3UKoZ1xTdkhv@Hh1Q4wWeTiFrbAQ "Python 3 – Try It Online") [Answer] # [CPython 3.6, by wizzwizz4](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread/136699#136699) (A000002) ``` t=int().__sub__(int()==int()) t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t)); t=int().__sub__(t).__sub__(int()==int()) d=__builtins__.__dict__;l=list(d); c=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d)) _=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d)) dd=d[l[_]].__dict__ ll=list(dd) d[l[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](dd[ll[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](d[l[_]](),(d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d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,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d)))))) ``` I manually wrote the lines up until `ll=list(dd)`, but the rest of the code was generated by this python program: ``` def construct_number(n): return "d[l[t]](("+",".join(("d",)*n)+"))" def construct_character(n): return "d[l[c]]("+construct_number(ord(n))+")" def construct_string(n): return "dd[ll[%s]](d[l[_]](),(%s))"%(construct_number(24),",".join(map(construct_character, n))) def construct_code(code): return "\nd[l[%s]](%s)"%(construct_number(19),construct_string(code)) code = construct_code("""def k(n): v=1;s=[1,1,2];c=1;r=1 for _ in range(n): for _ in range(s[c]): if r>=len(s):s.append(v) r+=1 c+=1;v=(v%2)+1 return s[n] print(k(int(input())))""") ``` The generated code could almost certainly be golfed better, but that would make the generator code more complicated. [Answer] # [CPython 3.6, by wizzwizz4](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread/136782#136782) (A000796) ``` t=int().__sub__(int()==int()) t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t));t=t.__sub__(int().__sub__(t)); t=int().__sub__(t).__sub__(int()==int()) d=__builtins__.__dict__;l=list(d); c=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d)) _=d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d)) dd=d[l[_]].__dict__ ll=list(dd) d[l[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](dd[ll[d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))]](d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,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d))),d[l[c]](d[l[t]]((d,d,d,d,d,d,d,d,d,d)))))) ``` This time, the generated code is almost twice as long. [Answer] # [Javascript (ES6) by Draco18s](https://codegolf.stackexchange.com/a/137862/21173) The solution is whatever [jsfuck.com](http://jsfuck.com) returns when given: ``` f=function(n){return 2**n;} ``` The full source is 30739 characters long: ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+(![]+[])[+[]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+!+[]]]+(!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]]+(![]+[])[+!+[]])+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]]+(![]+[])[+!+[]])+([][[]]+[])[+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]]+(+(+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+[]]))+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]]+([][[]]+[])[!+[]+!+[]]))() ``` [Answer] # [Python 3](https://docs.python.org/3/), [Mr. Xcoder](https://codegolf.stackexchange.com/a/136171/63641) ``` n=int(input()) l=[1,2,2] for i in range(2,n):l+=[1+i%2]*l[i] print(l[:n+1][n]) ``` [Try it online!](https://tio.run/##Fcu9CoAgFAbQ3adwCTRdtCbBJ5E7NPRzQT5FbOjprebDqU@/CpYxEBldMerdldYix@Sst57EUZpkyZBtw7krb6FDNh8bnjzNOTGJ2v6cU4BxlEB6jPUF "Python 3 – Try It Online") [Answer] # [Python](https://www.python.org), [totallyhuman](https://codegolf.stackexchange.com/questions/136150/restricted-mini-challenges-cops-thread/136179#136179) ``` f=lambda x:x<1or f(x-1)*x c=lambda n:(f(2*n)/f(n)/f(n+1))**2 ``` [Try it online!](https://tio.run/##NckxDoAgDADA3VcwtlWjMBJ9DKKoiRRCHOrrcTAut1x@7iOxqTXMl4vL6pRYmXQqKoD0Gkka/w9bCGCIcQjw0WpEIlNzOflW0WXwnSqO9w30iFhf) We really should stop posting our answers from the previous OEIS challenge :) [Answer] # [Python 2](https://docs.python.org/2/), [Rod](https://codegolf.stackexchange.com/a/136177/53880) ``` n=input() l=[] p=[n] for i in range(n): lp=[] for t in l: lp[:len([])]=[n] for t in p: lp[:len([])]=[n] (l,p)=(p,lp) print len(l) ``` [Try it online!](https://tio.run/##bcsxDsIwEETRfk@x5a6UAigj@SSWC4oAllaTkWUKTm9iGpq0/83w0187bmMgVfDdzSVSLsKUUeSxN61aoe2O52bwVTQ4XSf1SXG0I@Y1NlguXn7Pv/PcLRZ6Mi5BF7aKrnMQPsb18gU "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), [Bobawob](https://codegolf.stackexchange.com/a/136180/63641) ``` print '1'*input() ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EQd1QXSszr6C0REPz/38jAA "Python 2 – Try It Online") [Answer] # [Python 2, totallyhuman](https://codegolf.stackexchange.com/a/136191/34388) ``` p=int(input()) print(128*p**2+2336*p+10657) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8A2M69EIzOvoLREQ1OTq6AIxDU0stAq0NIy0jYyNjbTKtA2NDAzNdf8/98EAA "Python 2 – Try It Online") ]
[Question] [ Simply put, your goal is to create a complete program that [modifies its own source code](https://en.wikipedia.org/wiki/Self-modifying_code) until every character of the source is different than what it started as. Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc. ### Rules * Your program must halt sometime after the modification is complete. * It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file. * Standard loopholes are disallowed. * Shortest program wins. * If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage. **Edit**: If your program halts with errors, please specify it as such (and maybe say what the errors are.) [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 2 bytes ``` >@ ``` The `>` rotates the source so that it becomes ``` @> ``` The instruction pointer is now in a dead end and turns around to hit the `@` which terminates the program. Of course, `<@` would also work. [Answer] # [///](http://esolangs.org/wiki////), 1 byte ``` / ``` The program finds a `/` (the start of a pattern-replacement group), and removes it in preparation to make the replacement. Then it reaches EOF, so it gives up and halts. [Answer] # Python 2, 225 bytes ``` import sys from ctypes import* c=sys._getframe().f_code.co_code i=c_int p=POINTER class S(Structure):_fields_=zip("r"*9+"v",(i,c_void_p,i,c_char_p,i,p(i),i,c_long,i,c_char*len(c))) cast(id(c),p(S)).contents.v=`len([])`*len(c) ``` The ending source code is a string of `"0"`s whose length is equal to the number of bytes in the original compiled code object. The code finds the running code object, `sys._getframe().f_code.co_code`, and creates a structure which represents python string objects. It then gets the memory that the code actually takes and replaces it with `"0"*len(c)`. When ran, the program exits with the following traceback: ``` XXX lineno: 7, opcode: 49 Traceback (most recent call last): File "main.py", line 7, in <module> cast(id(c),p(S)).contents.v=`1+1`*len(c) SystemError: unknown opcode ``` This shows that the overwrite was successful and the program dies because `0` isn't a valid opcode. I'm surprised that this is even possible in python, frame objects are read-only, I can't create new ones. The only complicated thing this does is change an immutable object (a string). [Answer] # [evil](http://esolangs.org/wiki/Evil), 1 byte ``` q ``` evil has several memory stores - one is the source code itself and one is the *wheel* which is a circular queue which is initialised to a single zero. `q` swaps the source code and the wheel, so it replaces the source with a null-byte. However, only lower-case letters are actual operators in evil, so that character is simply a no-op and the program terminates. [Answer] # [MSM](http://esolangs.org/wiki/MSM), 8 bytes ``` '.qp.;.; ``` Transforms the source code to `pqpqpqpq` MSM operates on a list of strings. Commands are taken from the left and they treat the right side as a stack. MSM always works on it's own source. Execution trace: ``` '.qp.;.; upon start the source is implicitly split into a list of single char strings ' . q p . ; . ; ' takes the next element and pushes it on the stack q p . ; . ; . q is not a command so it's pushed p . ; . ; . q same for p . ; . ; . q p . concats the top and next to top element ; . ; . pq ; duplicates the top element . ; . pq pq concat ; . pqpq dup . pqpq pqpq concat pqpqpqpq MSM stops when there's only one element left ``` [Answer] # Malbolge, 1 or 2 bytes. ``` D ``` The Malbolge language "encrypts" each instruction after executing it, so this letter (Malbolge NOP) will become an `!` (which is also a nop), and then terminate. For some reason, the Malbolge interpreter I use requires two bytes to run, giving `DC` (both of which are nops) becoming `!U` (both of which are also nops) Edit: The initial state of Malbolge memory depends on the last two characters in the code, so it is not well defined for one character programs. (Though this code doesn't care about the initial state of memory) [Answer] **x86 asm** - 6 bytes not sure if "until every character of the source is different than what it started as" refers to each byte, each nemonic, or general modification. if I'm invalid I can change the xor to a rep xor so each bit changes values but was hoping not to do that to save 6 more bytes to stay at least a little bit comparable to these specialty golf languages. All this does is change a c2 to a c3 retn by getting live address of eip and xoring 5 bytes in front. ``` 58 | pop eax ; store addr of eip in eax 83 70 05 01 | xor dword ptr ds:[eax + 5], 1 ; c2 ^ 1 = c3 = RETN c2 | retn ; leave ``` [Answer] # [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 92 bytes Can be golfed, and I'll probably work more on it later. ``` >>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<]>>>>>--[>-<++++++]>--->>++>+++++[>------<-]>->>++[<<]< ``` ### Explanation The program generates the following commands at the end of its tape to erase itself, so it has to generate the following values on the tape: ``` [[-]<] ASCII: 91 91 45 93 60 93 ``` Make a bunch of `91`s, with nulls (shown as `_`) between to use for temp values. ``` >>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<] code__91_91_91_91_91_91_ ^ ``` Adjust the values by the differences ``` >>>>>--[>-<++++++]>--- Sub 46 >>++ Add 2 >+++++[>------<-]>- Sub 31 >>++ Add 2 [<<]< Shift left to the code code__[_[_-_]_<_]_ Zero out the code ^ ``` The tape following execution will be all zeros, with the exception of the generated code `[_[_-_]_<_]`. ### Note: This program made me realize that my Python interpreter for SMBF has a bug or two, ~~and I haven't figured out a fix yet.~~ It's fixed now. [Answer] # Emacs Lisp 22 bytes ``` (defun a()(defun a())) ``` Run from REPL: ``` ELISP> (defun a()(defun a())) a ELISP> (symbol-function 'a) (lambda nil (defun a nil)) ELISP> (a) a ELISP> (symbol-function 'a) (lambda nil nil) ``` Function now evaluates to `nil`. Alternately (unbind itself) **30 bytes** ``` (defun a()(fmakunbound 'a)(a)) ``` Evaluate and errors as `void-function`. Function existed prior to being run. [Answer] ### [Redcode](https://en.wikipedia.org/wiki/Core_War), 7 bytes, 1 instruction (Just an example. Not competing) This is a trivial example. Moves the next memory location onto itself, then halts (because the entire memory is initialized to `DAT 0 0`, which halts the program when executed.) ``` MOV 1 0 ``` [Answer] # Powershell 65 bytes ``` function a{si -pat:function:a -va:([scriptblock]::create($null))} ``` Define a function that rewrites itself to null. Evaluate it once and it eliminates itself. Alternately (deletes itself from memory) **36 bytes** ``` function a{remove-item function:a;a} ``` Calling it first removes it then attempts to evaluate recursively. Erroring out as an unknown command. [Answer] ## MIXAL, 6 bytes (counting 2 tabs) ``` STZ 0 ``` The program starts at memory location 0 and then writes 0 to memory location 0, thus erasing itself. The machine halts automatically. This is the assembly language for Donald Knuth's hypothetical MIX computer, which may be assembled and run using GNU MIX development kit (<https://www.gnu.org/software/mdk/>). [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~40~~ ~~34~~ 30 bytes ``` 0&00a6*0&1+:&060"c"l=?!.~~r >p ``` [Try it here!](http://fishlanguage.com/playground/kxTYEZwyRnnyW4rcj) Explanation: ``` 0& Adds 0 to the registry 00a6* Adds "0,0,<" to the stack; coords followed by a character ------------loop start (for clarity) 0 0 added to stack &1+:& Registry retrieved, increased by 1, duplicated, one put back in registry 0 ASCII character 0 added to stack (just a 0 but will be converted to that character when inserted in the code) 60 6 and 0 added to stack "c" The number 99 added to stack (length of code + 1 * 3) l=? Code length added to stack, checks if it is equal to 111 !. If false, pointer jumps back to character (9,0) (loop start position) ~~r >p If true, removes the 0 and 9, reverses stack, then loops the p command setting all the characters to a "<" character and the 2nd character to a " " ``` Basically this puts a bunch of 3 character blocks in the stack like so: (ypos, xpos, ASCII character) which gets reversed at the end so the final 'p' command reads (character, xpos, ypos) and sets that position in the code to that character. The first character is manually set as '<', so that the code ends up being '>p<' at the end to loop the command. Then every other character is overwritten as a ' ' including the p character. The ' ' is actually "ASCII CHAR 0" which is NOT a NOP and will give an error when read. Also there have to be an odd(?) number of characters before the 'p' command or else it wont be looped back into a last time and overwritten. [Answer] # Batch, 11 bytes ``` @echo>%0&&* ``` Modifies source code to `ECHO is on.` ``` @ - don't echo the command. echo - print ECHO is on. >%0 - write to own file. &&* - execute * command after the above is done, * doesn't exist so program halts. ``` The `@` is there so the command isn't echoed, but mostly so the two `echo`s don't line up. [Answer] # Jolf, 4 bytes, noncompeting ``` ₯S₯C ``` This `₯S`ets the `₯C`ode element's value to the input, `undefined` as none is given. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=4oKvU-KCr0M) [Answer] # (Filesystem) Befunge 98, 46 bytes ``` ff*:1100'aof0'ai 21f0'ai@ ``` Note that this program creates and manipulates a file named `a`. How it works: 1. The code creates a file named `a` containing the entire code (out to 256 characters in each dimension) shifted one space upward and two the left. 2. This program then reads the file named `a` as one line, replacing the entire first line with the contents of the `a` file. 3. The second line, which has been copied in front of the IP, is executed 4. Which reads the `a` file into the second line shifted two places to the right. As a side effect, the ending source code isn't even valid Befunge! (because it contains newlines as data in a single line) [Answer] ## Python 2, 238 bytes + 20% = 285.6 ``` # coding: utf-8 import codecs with codecs.open(__file__,'r') as f: t = f.read() n="utf-8" if t.startswith("# coding: ascii") else "ascii" with codecs.open(__file__,'w', encoding=n) as f: f.write(t[0]+" coding: "+n+t[t.find("\n"):]) ``` Basically, this toggles the current file encoding of the python source between `ascii` and `utf-8`, thus essentially changing every character of the source! ]
[Question] [ ## Challenge Write a program that applies an injective function which takes an ordered pair of strings as input and one string as output. In other words, each input must map to a unique output. ## Specifics * The input may be *any* two strings of arbitrary length, but will consist only of printable ASCII characters (codes \$[32, 126]\$). * Similarly, the output string has no length restriction, but it must consist only of printable ASCII characters. * If your language can't handle arbitrary-length strings, the program may merely work *theoretically* for strings of any size. * The mapping from inputs to outputs should be consistent between executions of the program. Otherwise, the mapping you use is completely up to you, as long as it is an injection. * The input is ordered. If the two input strings are different, they should produce a different output than if they were swapped. \$s \neq t \implies f(s, t) \neq f(t, s)\$ * Not every string needs to be a possible output. * The shortest answer in each language wins! ## Test cases The following inputs should all result in different outputs. To avoid confusion, strings are surrounded by guillemets («») and separated by single spaces. ``` «hello» «world» «lelho» «drowl» «diffe» «_rent» «notth» «esame» «Code» «Golf» «Co» «deGolf» «CodeGolf» «» «» «» «» « » « » «» « » « » « » « » «abc", » «def» «abc» «, "def» «abc' » «'def» «abc'» « 'def» «\» «"» «\\» «\"» ``` [Answer] ## brainfuck, ~~30~~ ~~29~~ ~~27~~ 23 bytes ``` ,[-[+.>]-[>+<---]>.-.,] ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ1o3WlvPLlY32k7bRldXN9ZOT1dPJ/b//7T8fMakxCIA) Inputs are separated by a `0x01` byte. This turns `["foo", "bar"]` into `fUToUToUTUTbUTaUTrUT`. To recover the original two strings, take groups of 3 characters, find the one where the second letter isn't `U`, and split there. [Answer] # JavaScript (ES6), 14 bytes Takes input as an array of 2 strings. Inspired by [Luis' answer](https://codegolf.stackexchange.com/a/193645/58563). ``` JSON.stringify ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@98r2N9Pr7ikKDMvPTOt8n9yfl5xfk6qXk5@ukaaRrRSRmpOTr6SjoJSeX5RTopSrKYmF7qSRJB0UjIOyaRkkDRY8j8A "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), ~~21~~ 20 bytes Takes input as `(a)(b)`. ``` a=>b=>[a.length,a]+b ``` [Try it online!](https://tio.run/##bcq7DYAgEADQ3jGoICobwCLG4vhrLpwBouNjaI31eyfcUG05rrZmcr4H1UFpo/QGEn2OLS2wz6ZbypXQS6TIA2fJIxITnD1U0DEhpk@Agcb@krEDB/UX "JavaScript (Node.js) – Try It Online") Returns the length of \$a\$, followed by a comma, followed by the concatenation of \$a\$ and \$b\$. [Answer] ## jq -c, 0 bytes [Try it online!](https://tio.run/##yyr8DwTRSmn5@Uo6CkpJiUVKsf/yC0oy8/OK/@smAwA) This definitely feels like cheating...? But it seems to comply with the rules of the challenge. By default, `jq` will output its input in a human-readable JSON format. The `-c` (compact) flag tells `jq` to output in "compact" style, which removes the newlines (since the challenge forbids non-printable ASCII). [Answer] # [Python 3](https://docs.python.org/3/), 3 bytes ``` str ``` A (built-in) function which, given a list of the two strings, gives a string representation of the list **[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzv7ik6H9BUWZeiUaaRrRSWn6@ko5SUmKRerFSrKbmfwA "Python 3 – Try It Online")** [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I *still* feel I must be missing something here ... ``` ®mc ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=rm1j&input=WyJvbmUiLCJ0d28iXQ) Possibly 2 bytes: ``` mq ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=bXE&input=WyJvbmUiLCJ0d28iXQ) Or stretching it with this 1-byter: ``` U ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVE&code=VQ&input=WyJvbmUiLCJ0d28iXQ) The first version maps each string in the array to its codepoints and outputs them joined with a space. The second version splits each string to a character array and outputs them joined with a space. And the third version, which feels like cheating, just outputs the input with the `-Q` flag doing the heavy lifting of `srringify`ing it. [Answer] ## Haskell, 4 bytes ``` show ``` The Haskell built-in to turn things into strings. The input is taken as a pair of strings. [Try it online!](https://tio.run/##y0gszk7NyflfbBvzvzgjv/x/bmJmnoKtQko@l4JCQWlJcEmRT56CikKxgoZSYlKyko5SSmqakiampGGMklGMkjFQQUyMkub/f8lpOYnpxf91kwsKAA "Haskell – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` jNmC ``` [Try it online!](https://tio.run/##K6gsyfj/P8sv1/n/f6XEpGQlHQWllNQ0JQA "Pyth – Try It Online") This converts each string to base 256 and then joins them in order with a `"`. Since the results are each numbers the `"` unambiguously separates them and the original strings can be recovered with [`mCsdczN`](https://tio.run/##K6gsyfj/P9e5OCW5yu//fzNjCyNDc0slM1NzS1NTCwA). [Answer] # T-SQL, 38 bytes ``` SELECT QUOTENAME(a)+QUOTENAME(b)FROM i ``` Input is taken from a pre-existing table \$i\$ with `varchar` fields \$a\$ and \$b\$, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Uses [`QUOTENAME`](https://docs.microsoft.com/en-us/sql/t-sql/functions/quotename-transact-sql?view=sql-server-2017), which surrounds the strings with `[]` and also escapes any internal brackets. Should map to a unique output. [Answer] # [Zsh](https://www.zsh.org/), 7 bytes ``` <<<$@:q ``` [Try it online!](https://tio.run/##qyrO@J@moVn938bGRsXBqvB/LRdXmoK6ukKxAggoK6TmFpRUKqRlFhWXACWKQVLIEsWpyfl5KRAtECmYTFJ@SQZIHATVoQoUwIwYkMh/AA "Zsh – Try It Online") Implicitly joins the arguments on spaces. The `q` modifier tells zsh to quote the arguments, which crucially escapes spaces, ensuring an unescaped space unambiguously separates the two arguments. (Without `q`, `"a " "b"` and `"a" " b"` would both yield `"a b"`.) [Answer] # [MATL](https://github.com/lmendo/MATL), 1 byte ``` j ``` The code takes an array of two strings as input, and outputs a string representation of that array. [Try it online!](https://tio.run/##y00syfn/P@v//2r1xKRkdQX1lFT1WgA "MATL – Try It Online") ### Explanation The code simply reads the input as a string, unevaluated. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒṘ ``` A monadic Link accepting a list of two lists of characters as its argument which yields a single list of characters. **[Try it online!](https://tio.run/##y0rNyan8///opIc7Z/z//z9aKSknMUNJR0EpLT9fvVgpFgA "Jelly – Try It Online")** ### How? It's a built-in to get Python's string representation, simples. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` ₁ö ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UVPj4W3//0crZaTm5OQr6SgolecX5aQoxQIA "05AB1E – Try It Online") Interprets each string as a base-256 integer, then prints the two in the form `[1, 2]`. --- ## 05AB1E, 1 byte (unknown validity) ``` â ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8KL//6OVMlJzcvKVdBSUyvOLclKUYgE "05AB1E – Try It Online") Takes the cartesian product of the input with itself. Quotes in the input are not escaped, which could cause confusion. I brute-forced all combinations of up to 12 `", "` and `"], ["` and didn’t find any collision; however, I can’t prove there aren’t any collisions for longer strings. If anybody can come up with a proof or counter-example, I’d highly appreciate it! The trivial 0-byter fails because of quotes not being escaped: inputs (`", "`, empty string) and (empty string, `", "`) both yield the output `["", "", ""]`. The 1-byter `º` (mirror each input string) also fails because of this: inputs (`", "" ,"`, empty string) and (empty string, `" ,"", "`) both yield the output `["", "" ,"", "" ,"", ""]`. [Answer] # C# with 26 bytes (thanks to Lukas Lang, Kevin Cruijssen and Jo King) ``` a=>b=>$"{a.Length}.{a}{b}" ``` [tio.run lambda](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrqOAwoHQdnYKaQq2/xNt7ZJs7VSUqhP1fFLz0ksyavWqE2urk2qV/ltzOefnFefnpOqFF2WWpPpk5qVqpGkoGSppaigZJSlpauJSAFYBVvAfAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` ⪫E²⭆⪪S"⪫""λ, ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMrPzNPwzexQMNIRyG4BCiUDuIEF@Rklmh45hWUlkAENTR1FJRilJSAFFgHkA3k6SjkaGqCZHSUNDWt//8vyUhVUErLLCouUVIoBuvjAgvlJCJE/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` E² Repeat twice S Input a string ⪪ " Split it on `"`s ⭆ Map over each piece and join ⪫""λ Wrap each piece in `"`s ⪫ , Join the two results with a `,` Implicitly print ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 22 bytes Many fixes thanks to mazzy ``` "$($args|% le*)"+$args ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9JRUMlsSi9uEZVISdVS1NJG8z7X8vFpaaSpqCUmJSYpKCkoJScogQTUIKKKsDFQBDKBLP/AwA "PowerShell – Try It Online") Take five, oh my. [Answer] # [R](https://www.r-project.org/), 4 bytes ``` dput ``` [Try it online!](https://tio.run/##K/qfZvs/paC05H@aRrKGUlp@vpKOUlJikXqxkqbmfwA "R – Try It Online") A built-in function which returns the string representation of the input (inspired by [Jonathan Allan's answer](https://codegolf.stackexchange.com/a/193647/41725) ) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 8 bytes ``` Compress ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zk/t6Aotbj4f2FpfkmqrbK@XmJ8cElRZl66lZ1SQoKSjV2ijZ2SurqSGlcAULTEAawuWlnXLs1BOVZN36Gaq1rJIzUnJ19JRyk8vygnRalWBygUowTkG0HYCjoKQA6UDWQBubVctf8B "Wolfram Language (Mathematica) – Try It Online") [Answer] # CSS + HTML, 55 + 20 = 75 bytes Provide the inputs in the HTML after `<code>` tags. Visually injects letters one by one from each input into the output. When an input is longer than the other one, visual spaces are shown for missing letter(s) of the shorter input. Also one comma is added in HTML to force visual output uniqueness (I hope). ``` *{position:absolute;letter-spacing:9px}code>code{left:9px ``` ``` <code>abcdefg<code>hijklmn</code>, ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 5 bytes ``` Print ``` [Try it online!](https://tio.run/##Sy7WTS7O/O@YXJKZn2dTXFKUmZceHWuXZvs/AMgs@W/NlaaRl1oeHVutlJafr6SjlJRYpFSriSQMEtABSwKF/wMA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~6~~ 3 bytes ``` &dd ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfLSXlvzVXmoJNRmpOTr5CeX5RToodXEAhHyrwHwA "Perl 6 – Try It Online") Outputs the object representation to STDERR. [Answer] # [Lua](https://www.lua.org/), 27 bytes ``` print(('%q%q'):format(...)) ``` [Try it online!](https://tio.run/##yylN/P@/oCgzr0RDQ121ULVQXdMqLb8oN7FEQ09PT1Pz////Hqk5Ofk6Ckr/y/OLclIU1QE "Lua – Try It Online") Full program, take input as arguments. Inspired by zsh answer, as it also use `%q` modifier to use internal safe-string engine. Also, I can think of just ``` ('%q%q'):format ``` but I'm not sure if this is acceptable answer. [Answer] # [sed](https://www.gnu.org/software/sed/), 19 bytes ``` N s/ /. /g s/\n/: / ``` [Try it online!](https://tio.run/##K05N0U3PK/3/34@rWF9BX09BPx3IiMnTt1LQ//8/0UoBBLmsFBIB "sed – Try It Online") ``` N # append the second string into the pattern space s/ /. /g # prefix all spaces with ".". Now ": " will not occur in the stiring s/\n/: / # replace the newline with ": " ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 6 bytes ``` uneval ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38n2b7vzQvtSwx539yfl5xfk6qXk5@ukaaRrRSRmpOTr6SjoJSeX5RTopSrKYmF7qSRJB0UjIOyaRkkDRY8j8A "JavaScript (SpiderMonkey) – Try It Online") Input array of strings, output a single string. Inspired by [Arnauld's JSON.stringify answer](https://codegolf.stackexchange.com/a/193642/44718). [Answer] # [C (gcc)](https://gcc.gnu.org/), 59 bytes Thanks to Grimy for the suggestion. Takes an array of input strings (of which "2" is the correct number for this challenge) and prints their character values, including the trailing `NUL`. Technically, the `%p` formatter used by `printf` is for pointers, but it works fine for displaying hex values of arbitrary integers if you're not picky about how they look! ``` f(s,t)char**s,*t;{for(;t=*s++;)for(;printf("%p",*t++)^5;);} ``` [Try it online!](https://tio.run/##VZHLasMwEEX3@ophIMQPFVJKV8LZdNGPsN3i2lJsUKwgTZtF8Le7khXnsRnuOVzNYtS@HNp2nlXiOKVt39gsczwjcVHGJoKKzOW5SBc42WEkleDmhL6R5@nXu0jFNIdXkLmyLi4Me6m1QY5nY3WHfMcZaqn7oDprzjqqblBKevVt5UhRjYao90q65iij@jBdKH0arVYR1shHsRJG8RggJri5kGC1cG80P22FHJbd6qY8cqie1DZ0tk8mbLmbyu/BCleIWF3Fjk2CMX9DODbDmITQ2EPLIR4w8/CXwoXBKsjXAcLtqXACPAPlxVvsAKz/UW5czcOAYg8lcip3tR@vdSqWnkromk6/5BKsccGJTfM/ "C (gcc) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 0 bytes Input as an array of 2 strings, output in the format: `Z = ["{{string 1 stringified}}","{{string 2 stringified}}"]` Inspired by [Arnauld's JSON.stringify answer](https://codegolf.stackexchange.com/a/193642/44718) and [Doorknob's empty jq answer](https://codegolf.stackexchange.com/a/193651/81957) [Try it online!](https://tio.run/##SypKTM6ozMlPN/oPBNFKJanFJUo6CkoeqTk5@QolGalFqTpcGfnlColFqQqV@aX2Cp7quQop@Zl56Qr52XpcvolF2QrFiZkpVgoxKJpiYmLykPXFKCnF/o8CAA "Brachylog – Try It Online") [Answer] # [PHP](https://php.net/), 9 bytes ``` serialize ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwMWlkmb7vzi1KDMxJ7Mq9b81F1dqcka@gkqaRrR6YlKyuo6CekpqmnqspvV/AA "PHP – Try It Online") Input is an array of 2 strings like this: `['abc', 'def']`. Uses PHP's [serialize](https://www.php.net/manual/en/function.serialize.php) to serialize the input into a string. [Answer] # [Bash](https://www.gnu.org/software/bash/), 11 bytes ``` echo ${@@Q} ``` [Try it online!](https://tio.run/##S0oszvifpqFZ/T81OSNfQaXawSGw9n8tF1eagnpGak5OvrqCukJ5flFOijpcCCiiDhdSAokpKSgBVSr9BwA "Bash – Try It Online") `${parameter@Q}` quotes the parameter for reuse as input. In the case of an array, it quotes each element. [Answer] # [Ruby](https://www.ruby-lang.org/), 12 bytes ``` ->*a{a.to_s} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf104rsTpRryQ/vrj2f0FpSbFCWrRSRmpOTr6SjoJSeX5RTopSLBdMIhEkmJSMIpSUDBJEElJXUlKKjo6NVVJS11FXj/0PAA "Ruby – Try It Online") ]
[Question] [ **Task:** Return an array with **all possible pairs** between the elements of an array. **Example** From `a=["a", "b", "c", "d"];` return `b=[["a","b"],["a","c"],["a","d"],["b","c"],["b","d"],["c","d"]]`. Pairs can be in any order as long as all possible combinations are included and obviously `["b","d"]` is the same to `["d","b"]`. **Input** Array of unique string elements composed of chars from the class `[a-z]`. **Output** 2d array containing all the possible pairs of input array's elements. **Test Cases** ``` input=["a","b","c"]; //output=[["a","b"],["a","c"],["b","c"]] input=["a","b","c","d","e"]; //output=[["a","b"],["a","c"],["a","d"],["a","e"],["b","c"],["b","d"],["b","e"],["c","d"],["c","e"],["d","e"]] ``` **Note:** I could not find a ***duplicate*** to this challenge. If there is one, alert me with a comment to drop question. [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f(a:b)=map((,)a)b++f b f _=[] ``` [Try it online!](https://tio.run/##DcNRCoAgDADQ/04xRh@KniDwJCKxlSNJRar7Lx@8i94716oqhja2odEwxluy7JwALwJ7iEkblQ4BxlP6BysIRCT0yPMxn3PGpD8 "Haskell – Try It Online") Example usage: `f ["a","b","c"]` yields `[("a","b"),("a","c"),("b","c")]`. --- With the flag `-XTupleSections` this can be shortened to 27 bytes, however the flag would need to be counted: ``` f(a:b)=map(a,)b++f b f _=[] ``` [Try it online!](https://tio.run/##DcNBCoAgEADAe69YpENRfSDwFXUIQmI1tyQzyfp@mwOzYzqs98xUYa9reWKssK110xDogmCRs@ITXQAJ8XbhgRIIZoGiFTo3@Zpbofgz5HFL3E3jG70drHncFdIP "Haskell – Try It Online") [Answer] # Mathematica, 14 bytes ``` #~Subsets~{2}& ``` **input** > > [{"a", "b", "c"}] > > > [Answer] ## Haskell, 25 bytes ``` f l=[(x,y)|x<-l,y<-l,x<y] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxzZao0KnUrOmwkY3R6cSRFTYVMb@z03MzFOwVUjJ51JQUCgoyswrUVBRSFOIVkpU0lFKAuJkpVjcUjpKKUCcqhT7HwA "Haskell – Try It Online") Outer (`x`) and inner (`y`) loop through the input list and keep the pair `(x,y)` only if `x < y`. [Answer] ## vim, ~~50~~ 48 ``` AX<esc>qqYplX@qq@qqrYpllDkxh@rq:g/./norm@r<cr>:g/X/d<cr>dG ``` Takes input in the form ``` abcd ``` and outputs as ``` ad ac ab bd bc cd ``` ### Explanation First, `AX<esc>` appends an `X` to the input in order to handle 2-length input, which is necessary for reasons that will become clear shortly. Then comes the first recursive macro, of the form `qq...@qq@q`. (Record macro `q`, run itself again at the end, end the recording, then run itself once.) In the body of the macro, `Yp` duplicates the current line, `l` breaks out of the macro if the line is now one character long, and `X` deletes the first character in the line. This has the end result of producing ``` abcdX abcX abX aX X X ``` Ignoring the `X`s for now, all we have to do is turn `abcdX`, for example, into `ab / ac / ad / aX`. This is achieved with the second recursive macro, `qr...@rq`. In this macro, we first duplicate the line (`Yp`), then delete everything but the first two characters by moving right two (`ll`) and deleting to the end of the line (`D`). Since the cursor is now on the second charcater of the line, `kx` will delete the second character from the previous line, which happens to be the one that was just paired with the first character on the line. This process is then repeated starting again from the beginning of the line (`h`) as many times as necessary due to the recursive nature of the macro. It's now just a matter of running the macro on every line, which can be achieved with `:g/./norm@r` (I'm not sure why this behaves differently than `:%norm@r`, but suffice to say, the latter does not work as intended.) Lines with `X` are deleted with `:g/X/d`, and the blank lines at the end left as a result of the construction of the `r` macro are cleaned up with `dG`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` {⊇Ċ}ᶠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/pRV/uRrtqH2xb8/x@tlKiko6CUBCKSQUSKUuz/KAA "Brachylog – Try It Online") ## How it works ``` {⊇Ċ}ᶠ ᶠ find all the possible outputs of the following predicate ⊇ the output is an ordered subset of the input Ċ the output is a list with two elements ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Œc ``` [Try it online!](https://tio.run/##y0rNyan8///opOT/h9u9HzWtifz/P1opUUlHKQmIk4E4RSkWAA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ### Code: ``` æ2ù ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8DKjwzv//49WSlTSUVBKAhHJICIFRKQqxQIA "05AB1E – Try It Online") ### Explanation: ``` æ # Powerset of the input 2ù # Keep the items of length two ``` [Answer] # Octave, 23 bytes ``` @(s)[nchoosek(+s,2) ''] ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNYMzovOSM/vzg1W0O7WMdIU0FdPfZ/Yl6xhlJiUrKS5n8A "Octave – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 44 bytes ``` f=lambda k,*s:[*s]and[[k,x]for x in s]+f(*s) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIVtHq9gqWqs4NjEvJTo6W6ciNi2/SKFCITNPoThWO01Dq1jzf0FRZl6JRpqGUqKSjoJSEohIVtLU/A8A "Python 3 – Try It Online") Takes input as individual function parameters. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~49~~ 48 bytes ``` @(x)[imag(y=(y=triu(x+j*x',1))(~~y)) real(y) ''] ``` Anonymous function that avoids the built-in (`nchoosek`). [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0IzOjM3MV2j0haISooySzUqtLO0KtR1DDU1NerqKjU1FYpSE3M0KjUV1NVj/6dpqCcmJaeoa/4HAA) ### Explanation `x+j*x'` uses broadcasting to build a matrix of complex numbers where the real and imaginary parts are all pairs of code points from the input `x`. `y=triu(...,1)` keeps the upper triangular part excluding the diagonal, making the rest of elements zero. The result is assigned to variable `y`. `y=(...)(~~y)` retains the nonzero elements in the form of a column vector, which is assigned to variable `y`. `imag(...)` and `real(...)` extract the real and imaginary parts. `[... ... '']` converts back to char to build the output. [Answer] # [R](https://www.r-project.org/), 18 bytes ``` combn(scan(,''),2) ``` reads the list from stdin, returns a matrix where the columns are pairs. [Try it online!](https://tio.run/##K/r/Pzk/NylPozg5MU9DR11dU8dI83@iQpJCskLKfwA "R – Try It Online") [Answer] # Python, 53 bytes *2 bytes saved thanks to @CalculatorFeline* ``` lambda a:[(x,y)for i,x in enumerate(a)for y in a[:i]] ``` [Try it online!](https://repl.it/Is2V/1) [Answer] # [Perl 6](http://perl6.org/), 17 bytes ``` *.combinations(2) ``` Whew, that's a long method name. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes ``` a->concat([[[x,y]|y<-a,x<y]|x<-a]) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9R1y45Py85sUQjOjq6QqcytqbSRjdRp8IGyKoAsmI1/xcUZeaVaKRpRCslKukoJQFxslKspiYXNnEdpRQgTgXJ/wcA "Pari/GP – Try It Online") [Answer] # Octave, 38 bytes ``` @(s)s([[x y]=find(s|s'),y](y<x,[2 1])) ``` Another answer to avoid `nchoosek` built-in. [Try it online!](https://tio.run/##y08uSSxL/f/fQaNYs1gjOrpCoTLWNi0zL0WjuKZYXVOnMlaj0qZCJ9pIwTBWU/N/Yl6xhlJiUnJKqpLmfwA "Octave – Try It Online") [Answer] # [Arturo](https://arturo-lang.io), 18 bytes ``` $=>[combine.by:2&] ``` [Try it](http://arturo-lang.io/playground?LTcG9a) [Answer] # Python ≥ 2.7, 55 bytes ``` lambda l:list(combinations(l,2)) from itertools import* ``` [repl.it!](https://repl.it/Is4a) [Answer] # Scala, 17 bytes ``` _.combinations(2) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 4 bytes -3 bytes thanks to [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)! ``` .cQ2 ``` [Try it online!](https://tio.run/##K6gsyfj/Xy850Oj//2ilRCUdBaUkEJEMIlKUYgE "Pyth – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` à2 ``` [Test it](http://ethproductions.github.io/japt/?v=1.4.5&code=4DI=&input=WyJhIiwiYiIsImMiLCJkIiwiZSJdCi1R) (`-Q` flag for visualisation purposes only) [Answer] # Python, 64 bytes ``` f=lambda a:sum((list(zip(a, a[i:]))for i in range(1,len(a))),[]) ``` [Answer] ## Clojure, 42 bytes ``` #(set(for[i % j(remove #{i}%)](set[i j]))) ``` Returns a set of sets :) [Answer] # Python, 74 bytes ``` f=lambda a:[(c,d) for i,c in enumerate(a) for j,d in enumerate(a) if i<j] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~38 34~~ 24 bytes ``` ->x{[*x.combination(2)]} ``` Thanks Seims for the idea that saved 10 bytes. [Try it online!](https://tio.run/##KypNqvyfZvtf166iOlqrQi85PzcpMy@xJDM/T8NIM7b2f4FCWnS0UqKSjoJSEohIVoqN/Q8A "Ruby – Try It Online") [Answer] # Javascript (ES 5), from 108 to 78 bytes I post my answer today but I obviously promise to not accept my own answer: ``` x=input; a=[]; for(n=0;n<(x.length-1);n++){for(i=n+1;i<(x.length);i++){a.push([x[n],x[i]]);}} ``` [Answer] # [J](http://jsoftware.com/), 17 bytes ``` ({~$#:I.@,)#\</#\ ``` [Try it online!](https://tio.run/##y/r/P03B1kpBo7pORdnKU89BR1M5xkZfOYaLKzU5I18hTUE9MSk5Rf3/fwA "J – Try It Online") ## Explanation ``` ({~$#:I.@,)#\</#\ Input: string S #\ Get the length of each prefix of S #\ Get the length of each prefix of S again </ Test using greater than (<) between each , Flatten I.@ Find the indices where the value is 1 $ Shape of that table #: Convert the indices to the base represented by the shape {~ Index into S at those values ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), `-p` 4 bytes ``` aCB2 ``` `CB` is the operator for combinations, not much explanation needed [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhQ0IyIiwiIiwiIiwiJ1tcImFcIjtcImJcIjtcImNcIjtcImRcIl0nIC14cCJd) [Answer] # [Go](https://go.dev), 132 bytes ``` func f[T any](S[]T)(O[][]T){if len(S)<3{O=append(O,S)}else{for a,i:=range(S){for _,j:=range(S[a+1:]){O=append(O,[]T{i,j})}}} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=jZBBSgMxGIVxO2dwEbJKMAq1ClLsGUaY7kIov9NkSJ3JDGlmISE7b-FmEHqIHkVPYzIVsWLVzfuT9778PPL8UrXDroPyASqJGtAm003XWneBVePwtnfq_Ob1SfWmRIovEJhHQQouFpTkXKTptUK1NKSgt1Ofz6HrpFmRnBU0yHojvWotAqZncwumkhEbnSVbfzocziYzQb8-jou9ZutAQwiZla63Juy7vJ2cjmVSVUKRz-6sNq42RBEuNi5eKo8BM4Tvk5Q4UPonE2X1fzCKHOkDPJ789xXJm_xosssjNpseDdjVLxG7TuHHJw3Dfr4D) A generic function that takes in a slice of type `T` and outputs a slice of slices of type `T`. A solution that does only `[]string -> [][]string` is 8 bytes longer. ### Explanation ``` func f[T any](S[]T)(O[][]T){ // boilerplate if len(S)<3{ // if the input length < 3, O=append(O,S) // just return the input }else{ // otherwise, for a,i:=range(S){ // for each 1st element, for _,j:=range(S[a+1:]){ // and each 2nd element, O=append(O,[]T{i,j})}}} // add the pair return} // return the result ``` [Answer] # JavaScript ES6, 52 bytes ``` a=>a.map((x,i)=>a.slice(0,i).map(y=>[x,y])).slice(1) ``` If there was like a `flatMap` that would save a lot of bytes. [Answer] # [Python](https://docs.python.org/2/), 55 bytes ``` f=lambda s:[(s[0],j)for j in s[1:]]+f(s[1:])if s else[] ``` [Try it online!](https://tio.run/##HcYxDoAgDADAr3SjRAd1JPElhAGERggCoSy@HhNvuvaOu5ZjTjqzfZy3wEoj682sSVLtkCAWYL0rYxbCPzISMITMQZvZeiwDkFBYd/kgpJwf "Python 2 – Try It Online") Longer than other Python answers, but it uses a different technique so I think it's worth posting. ]
[Question] [ You just recently got a new phone, but you don't quite like the way it vibrates, you've decided you want to create your own vibration patterns. So, you've written a program where you used the keywords `long`, `short` and `pause` to make your phone vibrate according to these keywords. ## Task Create a small program that accepts a string of `long`, `short`, and `pause` and outputs another string representing the phonetic sound of a phone vibrating; `Rrrr - Rr` `long` sounds are `Rrrr` `short` sounds are `Rr` (Casing matters) `pause` is a dash `-` all sounds are delimited by dash with surrounding spaces `' - '` ## Test Cases input:   `long long short long short` output: `Rrrr - Rrrr - Rr - Rrrr - Rr` input:   `long long long short short short` output: `Rrrr - Rrrr - Rrrr - Rr - Rr - Rr` input:   `short short short pause short short short` output: `Rr - Rr - Rr - - - Rr - Rr - Rr` input:   `long short short long long pause short short` output: `Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with the fewest bytes winning. [Answer] # JavaScript, ~~70~~ 63 bytes *2 bytes saved thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke)* ``` a=>a.replace(/./g,a=>[['Rr','rr','-',' - ']['onp '.search(a)]]) ``` [Try it online!](https://tio.run/##TckxDsMgDIXhq7AZpEAOUKWH6IoYLOqQVggjO@31aRp16PC@4X9PfKNmefTdN77TWJeByxWDUK@Yyc5hLtNRYoSbwATyxR8z3kCKwK0bCEooebPoUnIjc1OuFCoXu1qo3IrRjWX/eYaTji@l/w@cu4wP) [Answer] # [Pyke](https://github.com/muddyfish/PYKE), ~~22~~ 20 bytes ``` cFh.o6.&\R*\-|l4)J" - ``` [Try it here!](http://pyke.catbus.co.uk/?code=63+46+68+EF+36+A6+5C+52+2A+5C+2D+7C+6C+34+29+4A+22+20+2D+20&input=long+pause+short&warnings=1&hex=1) ``` c - split(input, " ") Fh.o6.&\R*\-|l4) - for i in ^: h - ^[0] .o - ord(^) 6.& - ^ & 6 \R* - ^ \-| - ^ or "-" l4 - ^.title() J" - - " - ".join(^) ``` The crux of this answer is the transformation of `["long", "short", "pause"]` into `[4, 2, 0]`. It gets the code point of the first letter of each word and `AND`s it with 6. By lucky coincidence it transforms to the values we're looking for. (I searched through quite a few other longer solutions before finding this one). Once that's done, we can further transform that list of ints into `["RRRR", "RR", ""]` by multiplying our int by `"R"` which then turns into `["RRRR", "RR", "-"]` and finally title casing it to get `["Rrrr", "Rr", "-"]`. We then join the resulting list by `" - "` [Answer] # [Haskell](https://www.haskell.org/), ~~71~~ ~~66~~ 59 bytes ``` g 'o'="Rr" g 'n'="rr" g 'p'="-" g ' '=" - " g _="" f=(g=<<) ``` [Try it online!](https://tio.run/##TclBCoAgFIThfacYHoG18Aa@S3SBcFEWmYrW@c0sqM3Px8yi0zZZm7OB8IJpiNQUusL4MBTKKhRB4vbIRM3MnWGl@rzr1YER4uoOtJhB1juDmrT4eLz91qDPNP0/yhc "Haskell – Try It Online") Oh right, `=<<` is concatMap. Takes advantage of the fact that `"long"` and `"short"` both have the letter `o`. [Answer] # JavaScript (ES6), ~~65~~ 59 bytes ``` s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - ` ``` ``` let f = s=>s.split` `.map(x=>x<'m'?'Rrrr':x<'q'?'-':'Rr').join` - ` console.log(f("long long short long short")); // => Rrrr - Rrrr - Rr - Rrrr - Rr console.log(f("long long long short short short")); // => Rrrr - Rrrr - Rrrr - Rr - Rr - Rr console.log(f("short short short pause short short short")); // => Rr - Rr - Rr - - - Rr - Rr - Rr console.log(f("long short short long long pause short short")); // => Rrrr - Rr - Rr - Rrrr - Rrrr - - - Rr - Rr ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~27~~ ~~25~~ 21 bytes ``` #εÇн6&'m×™'-)éθ}… - ý ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f@dzWw@0X9pqpqecenv6oZZG6rubhled21D5qWKagq3B47///xRn5RSUKOfl56QoQZkFiaXEqsgCICQA "05AB1E – Try It Online") **Explanation** ``` # # split input on spaces ε } # apply to each Çн # get the character code of the head 6& # AND with 6 'm× # repeat "m" this many times ™ # title case '-) # wrap in a list with "-" éθ # get the longest string … - ý # join to string using " - " as separator ``` Saved 3 bytes using the `AND 6` trick from *muddyfish's* [pyke answer](https://codegolf.stackexchange.com/a/140440/47066) [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ ~~69~~ 64 bytes ``` lambda s:' - '.join('Rrrr'[:ord(b[0])&6]or'-'for b in s.split()) ``` [Try it online!](https://tio.run/##hY0xC8IwFIR3f8WbfMnQIg4OBf@Ea9shocZGYl54Lw7@@hS6GIjgchzcd3fpk1eK5@KuUwnmZRcDMiB0gP2TfFR4Y2YcB@JF2fE06@NlJsYOHTFY8BGklxR8VlqXxD5mcAoDxQfsIitxri3qww@sAmqt4TZN5i33P61m@HvX1lGXDQ "Python 2 – Try It Online") **Alternates:** ### [Python 2](https://docs.python.org/2/), ~~76~~ 69 bytes ``` lambda s:' - '.join(['Rrrr','-','Rr'][ord(b[1])%3]for b in s.split()) ``` [Try it online!](https://tio.run/##hY2xCgIxEER7v2Ib2QS8A7UT/IlrcykSzniRmA2bWPj1UWwMRLCYYWDf7KRnWSkeqjvPNZi7XQzkE8IAON7IR6FwYmbc4fDWxKgV8SKs2mu5PWpHDBZ8hDzmFHwRUtbEPhZwAgPFK3wsr8SljSg3P7AGaL2F@2syj3z50@oef@f6Osr6Ag "Python 2 – Try It Online") ### [Python 2](https://docs.python.org/2/), 69 bytes ``` lambda s:' - '.join('-Rrrr'['o'in b:8-ord(b[1])%9]for b in s.split()) ``` [Try it online!](https://tio.run/##hY0xC8IwFIR3f8Vb5CVDCnXSgn/Cte2QUGMjMS@8xMFfn4qLgQgux8F9dxdfeaVwKPY8Fa8fZtGQBgQF2N3JBYHqwsw4IqELYIajIl6EGftZ7k@zJQYD7yB1KXqXhZQlsgsZrEBP4QYfSStxri3K3Q@sAmqt4TaN@pmuf1rN8PeuraMsGw "Python 2 – Try It Online") [Answer] # Mathematica, 81 bytes ``` StringReplace[#,{"long"->"Bzzz -","short"->"Bz -","pause"->"- -"}]~StringDrop~-2& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvs/uKQoMy89KLUgJzE5NVpZp1opJz8vXUnXTsmpqqpKQVdJR6k4I7@oBCIC5hcklhangvi6QG5tbB3ECJei/II6XSO1/wFAXomCQ1o02CQFsG4oCRYAE2AzkOWUYv//BwA "Mathics – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), ~~31~~ 29 bytes *1 byte saved thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) 1 byte saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)* ``` [^lhp ] l hrr h Rr p - - ``` [Try it online!](https://tio.run/##K0otycxL/P8/Oi4no0AhlosrhyujqIgrgyuoiKuAS5dLgUtBV@H//5z8vHSF4oz8ohIoCRYAEwWJpcWpyHIA "Retina – Try It Online") This is different approach than @DomHastings's [answer](https://codegolf.stackexchange.com/a/140435/72349). [Answer] ## [Perl 5](https://www.perl.org/), 39 bytes **37 bytes code + 2 for `-pa`.** ``` $_=join" - ",map/p/?"-":Bz.zz x/l/,@F ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jYrPzNPSUFXQUknN7FAv0DfXklXycqpSq@qSqFCP0dfx8Ht//@c/Lx0BTBRnJFfVILE5EJIIckjkVwYIgoFiaXFqVhUYhiAMBZDy7/8gpLM/Lzi/7oFiTkA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), 77 bytes ``` cat(c('Rrrr','Rr','-')[match(scan(,''),c('long','short','pause'))],sep=' - ') ``` Takes input through STDIN, checks whether the input matches `long`, `short` or `pause` and swaps the matches for `Rrrr`, `Rr` or `-` respectively. This is then printed with `-` padded with spaces as separator, matching the desired output. [Answer] # [Röda](https://github.com/fergusq/roda), ~~73~~ ~~57~~ ~~47~~ ~~46~~ ~~40~~ 44 bytes ``` f&a{a~=*`s\w+|l;Rr;ong;rr;p\w+;-; ; - `/";"} ``` [Try it online!](https://tio.run/##K8pPSfz/P00tsTqxzlYroTimXLsmxzqoyDo/L926qMi6AChgrWutYK2gq5Cgr2StVPs/NzEzT6GaizM6PlYhM00hTSHekKv2f3FGflGJAjJZkFhanKqQAzQIQQAA "Röda – Try It Online") +4 bytes due to rule change (must use `Rrrr` instead of any 4 letter variant). Previous code: ``` {[[split()|["Bzzz"]if[_="long"]else["Bz"]if[_1="short"]else["-"]]&" - "]} ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~93~~ ~~77~~ 76 bytes *-2 bytes thanks to Scepheo!* *-1 byte thanks to Cyoce!* Takes a NULL terminated \*\*char or equivalent as an input. ``` f(char**a){for(;*a;*++a&&printf(" - "))printf(**a&6?**a&1?"Rr":"Rrrr":"-");} ``` [Try it online!](https://tio.run/##fY4xD4IwEIV3fsWlJqQtYnRxsCp/gDiYOBmHplBogi0pxYXw22tBHRx0eXff5d3LE2klhF8oLZq@KGHfuUKZVX30EouaW0o5GaSxmFHOaJLwOG6t0k5iBCkgQt4UfPE2m3STobNFuyB2GikibPTBA3euNH4YVRAYIoApHWj4rpzR5fUGh/kMgBqjK7SEF3S1se4HfRm/oOV9V/7PmOF0yfOwjCwKKvGnDWEBbel6q2HNotE/AQ "C (gcc) – Try It Online") Explanations: ``` f(char**a){ // While the string at the current position is not NULL for(;*a; // Advances the pointer to the next string // Then if the current string is not NULL, prints a delimiter *++a&&printf(" - ") ) /* If the 1st char of the string is not a 'p' If the 1st char is not a 'l' Prints "Rr" Else Prints "Rrrr" Else: Prints "-" */ printf(**a&6?**a&1?"Rr":"Rrrr":"-"); } ``` [Answer] # [R](https://www.r-project.org/), 72 bytes Takes input from stdin, prints to stdout. ``` cat(sapply(scan(,''),switch,long="vvvv",short="vv",pause="-"),sep=" - ") ``` [Try it online!](https://tio.run/##FcrBCcAgDEDRVSQXFeIIGSaI1IJoMLal06f23x78aZZ5BWWR9gbN3AN6H1Gfc@WKbfSD4N4Bah1z/QAUvrQQJNhjEQKXHESzDw "R – Try It Online") [Answer] ## Batch, 88 bytes ``` @set/ps= @set s=%s: = - % @set s=%s:long=Rrrr% @set s=%s:short=Rr% @echo %s:pause=-% ``` Takes input on STDIN. Unfortunately loop overhead costs 26 bytes so this is just boring replacements. [Answer] # [Retina](https://github.com/m-ender/retina), 31 bytes ``` short|l Bz ong zz pause - - ``` -1 byte thanks to @[fergusq](https://codegolf.stackexchange.com/users/66323/fergusq)! [Try it online!](https://tio.run/##K0otycxL/P@/OCO/qKQmh8upiis/L52rqoqrILG0OJVLl0uBS0FX4f//HKCwApgAK0ViciGkkOSRSC4MEQWw4VhUYhiAMBZDCwA "Retina – Try It Online") [Answer] # PHP, 113 bytes ``` <?$s=[];for($i=1;$i<$argc;$i++){$c=$argv[$i][0];$s[]=($c<'m')?'Rrrr':(($c<'q')?'-':'Rr');}echo implode(' - ',$s); ``` [Try it online!](https://tio.run/##TcmxDsIgGATgV2H4kx9Sm@haQN7BlTA0iIWkFQrqYnx2bImDy@Xuu@RTrUIlnwgUqQ2/xUwhyBOHIGDMk91K17E3WLnPl4Zg9NFwKNpIClbggkzhJeeMA22w7tDjsCEy/nHWRxKWNMero0h6ggcojKtzrXWO96kWH/Pjlw1apPFZ3P/3BQ) First attempt at code golf, so probably a lot of optimisations available! [Answer] # Vim (52 bytes) `:s/long/Rrrr/ge|s/short/Rr/ge|s/pause/-/ge|s/ / - /g`*enter* Can probably be made shorter... [Answer] # Excel, 100 bytes ``` =REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","- Bzzz"),"short","- Bz"),"pause","- -"),1,2,"") ``` Per examples, Input is `SPACE` separated string, as is output. Question itself does not mention a `SPACE` requirement, allowing for a slightly shorter **97 byte** solution: ``` =REPLACE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"long","-Bzzz"),"short","-Bz"),"pause","--"),1,1,"") ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 32 bytes ``` Í /ò çl/CRrrr ço/CRr çp/- HòJa- ``` [Try it online!](https://tio.run/##K/v//3Cvgv7hTVyHl@foOwcVFRUBWfkgFpAu0Nfl8ji8yStRV@H//5z8vHQFMFGckV9UgsQEAA "V – Try It Online") [Answer] ## [AutoIt](http://autoitscript.com), 145 bytes ``` EXECUTE(STRINGREPLACE('MSGBOX(0,0,STRINGSTRIPWS(====INPUTBOX(0,0),"PAUSE",""),"LONG","Rrrr"),"SHORT","Rr")," "," - "),4))',"=","STRINGREPLACE(")) ``` (AutoIt is really bad choice for code golf, tried my best to make it small as possible) [Answer] # [Alice](https://github.com/m-ender/alice), 37 bytes ``` / lRnrhR \""orgrp-""!yi'."?-e"ySNo?@/ ``` [Try it online!](https://tio.run/##S8zJTE79/19fIScorygjiCtGSSm/KL2oQFdJSbEyU11PyV43Vaky2C/f3kH///@c/Lx0heKM/KISKAkWABMFiaXFqchyAA "Alice – Try It Online") ### Explanation This program makes the following substitutions: * `l`, `h` → `R` * `o`, `n`, `g` → `r` * `p` → `-` * Space → Space * Everything else → Nothing ``` "longhp "!i.?eyN?"RrrrR- "y' " - "So@ "longhp " Push this string ! Immediately move to tape i Take input string . Duplicate ?ey Remove all instances of the characters "longhp " from copy N Remove the remaining characters from the original, leaving only "longhp " ?"RrrrR- "y Replace the characters in "longhp " with the corresponding characters in "RrrrR- " ' " - "S Replace all spaces with " - " o Output @ Terminate ``` [Answer] # Sed, 50 bytes Takes input from `stdin`, prints to `stdout` ``` s/l\w*/Rrrr -/g s/s\w*/Rr -/g s/p\w*/- -/g s/ -$// ``` Edit - saved 2 bytes # Sed, 40 bytes Copying idea from [Nitrodon's answer](https://codegolf.stackexchange.com/a/140542/9174) ``` s/[srtaue]//g y/lhongp/RRrrr-/ s/ / - /g ``` Edit: saved another 2 bytes [Answer] # [Python 2](https://docs.python.org/2/), 69 bytes ``` lambda s:" - ".join((ord(i[0])&6)*"R"or"-"for i in s.split()).title() ``` [Try it online!](https://tio.run/##dYoxDsIwDAB3XmF5qGykRoiBAYlPsBaGoBZqFOLIMQOvT0Gwstxwd@Xls@Zti4dTS/FxGSPUPUIPGO4qmUhtJBk2Z@52vMYjqmGPVzUQkAw11JLEiTm4eJqIWzHJTpEwab5BndUcSnzWCZlXf@OPX/OJ77st "Python 2 – Try It Online") Port of my [Pyke answer](https://codegolf.stackexchange.com/a/140440/32686) [Answer] # [Paradoc](https://github.com/betaveros/paradoc) (v0.2.10), 21 bytes (CP-1252) ``` Wμ‹6&'r\°"-":Ãu}« rTc ``` [Try it online!](https://tio.run/##K0gsSkzJT/6f@T/83J5HDTvN1NSLYg5tUNJVsjrcXFp7aLVCUUjy//85@XnpCsUZ@UUlUBIsACYKEkuLU5HlAA "Paradoc – Try It Online") Takes a string on the stack and results in a string on the stack. Prepend `i` to turn into a full program that reads from STDIN. Uses `&6` like [the Pyke answer](https://codegolf.stackexchange.com/a/140440/19857) and everybody else, but joins the tokens together slightly differently, by adding a `"-"` token after each noise, deleting the last one, and then joining these tokens by spaces. Seems to save a byte over joining by `" - "`. Explanation: ``` W .. Break into words μ } .. Map over this block: ‹ .. Take the first character 6& .. Binary AND with 6, to get 4, 2, or 0 'r .. Character "r" \ .. Swap top two of stack ° .. Replicate, to get "rrrr", "rr", or "" "-" .. Push string "-" : .. Duplicate on stack à .. Compute the max... u .. ... underneath the top of the stack (so, of the .. second and third elements on the stack, i.e. the .. string of "r"s and "-") .. The mappped block ends here; we now have .. something like ["rrrr", "-", "-", "-", "rr", "-"] « .. Take all but the last r .. Join with spaces (this built-in's name is two .. characters, the first of which is a space) Tc .. Title-case ``` v0.2.11 will support shaving two more bytes by replacing `\°` with `x` and `"-"` with `'-`. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 28 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` θ{K;⁄5κ« r*; p=?X┌}}¹" - ”∑ū ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwM0I4JTdCSyUzQiV1MjA0NDUldTAzQkElQUIlMjByKiUzQiUyMHAlM0QlM0ZYJXUyNTBDJTdEJTdEJUI5JTIyJTIwLSUyMCV1MjAxRCV1MjIxMSV1MDE2Qg__,inputs=bG9uZyUyMHNob3J0JTIwc2hvcnQlMjBsb25nJTIwbG9uZyUyMHBhdXNlJTIwc2hvcnQlMjBzaG9ydA__) fun fact: if it was allowed to delimit with `-` or `-` it'd be a byte shorter [Answer] # [Ruby](https://www.ruby-lang.org/), 67 bytes ``` p ARGV[0].split(' ').map{|w|w<'m'?'Rrrr':w<'q'?'-':'Rr'}.join ' - ' ``` **This is [Johan Karlsson's JavaScript solution](https://codegolf.stackexchange.com/a/140447/34307) ported to Ruby.** If you like this answer, you should upvote Johan's answer. The key idea is to compare the word strings `'short'`, etc. to a single character in order to distinguish between words. ``` | Word | < 'm' | < 'q' | Output | |-------|-------|-------|--------| | short | false | false | 'Rr' | | long | true | N/A | 'Rrrr' | | pause | false | true | '-' | ``` Or, in alphabetical order: * long * m * pause * q * short [Try it online!](https://tio.run/##KypNqvz/v0DBMcg9LNogVq@4ICezRENdQV1TLzexoLqmvKbcRj1X3V49qKioSN0KyCkEcnTVrYAC6rV6WfmZeQrqCroK6v///y/OyC8qUcjJz0uHEBB@QWJpcSpYAAA "Ruby – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 78 bytes ``` p ARGV[0].chars.map{|c|{p:'-',o:'Rr',g:'rr',' '.to_sym=>' - '}[c.to_sym]}.join ``` The only important parts of the input are `p`, `o`, `g`, and space... ignore the rest. * `short` becomes `o` * `long` becomes `og` * `pause` becomes `p` [Try it online!](https://tio.run/##KypNqvz/v0DBMcg9LNogVi85I7GoWC83saC6JrmmusBKXVddJ99KPahIXSfdSr0ISKkrqOuV5McXV@ba2qkr6Cqo10YnQwVia/Wy8jPz/v//X5yRX1SikJOflw4hIPyCxNLiVLAAAA "Ruby – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 66 bytes ``` ' - '.join(['Rrrr','-','Rr'][ord(s[1])%3]for s in input().split()) ``` [Try it online!](https://tio.run/##ZYgxCoAwDEWvkkXSggri7CVcawdBpRVpQlIHT187CsJ/78HnJwdKY9FpKQgdYH9STMbhLCLYYleZBb0j2Yy6wdtm9AcJKMRUx3c2tle@Yq0tLDFlo7ZoIMnwNa@37vD7Xw "Python 3 – 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/1171/edit). Closed 7 years ago. [Improve this question](/posts/1171/edit) ## Problem: Given a set of integers, find the sum of all positive integers in it. ### Input: * *t* – number of test cases [*t* < 1000] * On each of next *t* lines, an integer *N* [-1000 ≤ *N* ≤ 1000] ### Output The program should output the sum of all the positive integers. [Check your code in online judge](http://www.spoj.pl/problems/SIZECON/) ### Score Score is equal to size of source code of your program except symbols with ASCII code ≤ 32. Here is the best score list: [Python Best Scores](http://www.spoj.pl/ranks/SIZECON/lang=PYTH%202.5) (Best score is 29) [Answer] # Whitespace, 0 I couldn't resist. `S`= space, `T`= tab, `N` = newline, all have ASCII codes <= 32. ``` SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN ``` Base64 encoded for easy copy & paste. ``` ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo= ``` [Answer] # Element, 17 characters plus 1 space ``` _'[_ 2:n;0>[n~+]]` ``` This is my first constructed language. It is designed to be very compact and human-readable. All of the instructions are one character long and perform a single function. Element has two stacks and a hash as memory structures. The two stacks are called the main stack and the control stack. The main stack is where arithmetic, I/O, and hash manipulation occurs. The control stack is where logic operations occur, and this stack controls the while and for loops. The basic idea behind Element is that there is a hash that stores numbers/strings, while the stack is used to perform calculations on these numbers. The results to these calculation can then assigned a certain place in the hash for future use. The different contents of the hash are called elements, so it is similar to an array but can have non-numerical names. EDIT: You can find an interpreter for Element (written in Perl) [here](http://pastebin.com/rZKMKDWv). Here is the list of operators: In some of these examples, m and n represent numbers already on the stack. ``` text --pushes the string "text" onto the main stack ' --pops from main stack and pushes onto control stack " --pops from control stack and pushes onto main stack # --pops from main stack and destroys [] --FOR statement (view the top number number from control stack and eval those many times) {} --WHILE (loop until top number on control stack is 0) ( --pops from main stack, removes first character, pushes the remaining string onto stack, and pushes the removed character onto stack ) --pops from main stack, removes last character, pushes the remaining string onto stack, and pushes the removed character onto stack ~ --pops from main stack, pushes contents of the element with that name +-*/%^ --pops two most recently named elements, adds/negates/multiplies/divides/modulates/exponentiates them, and places the result on the stack mn; --pops m and n and assigns element n the value of m mn@ --pops m and n and moves mth thing in stack to move to place n in stack m$ --pops m and pushs size of m onto the stack mn: --pops m and n and pushes m onto the stack n times mn. --pops m and n and pushes m concatonated with n m? --pops m and pushes 0 onto control stack if m is '0' or and empty string, else pushes 1 \ --escapes out of next character, so it isn't an operator and con be pushed onto the stack ><= --pops two numbers off of stack and tests, pushes 1 onto control stack if true and 0 if false ` --pops from main stack and prints &| --pops two items from control stack, performs and/or respectively, and pushes result back onto control stack ! --pops a number off of control stack, pushes 1 if 0 or empty string, 0 otherwise _ --inputs a word and pushes onto main stack m, --pops m from main stack, coverts it to char and pushes, converts to num and pushes Newlines and spaces separate different elements to be pushed onto the stack individually, but can pushed onto the stack using \ ``` Here is a walkthrough of how the program works: ``` _'[ --take the first line of input, transfer it to the control stack, and start a for loop _ 2: --take one more line of input, and duplicate it so that there are two copies n; --take one copy and put into element n 0> --push a zero onto the stack, remove the zero and the other copy of the input, and compare. A 1 will be placed on the control stack if the input was greater than zero, a 0 otherwise. [ --starts another for loop if the comparison was true. This loop will be repeated once if the comparison was true and no times if it was false, so it is the same as an IF statement. n~ --pushes n onto the main stack, then pops it ans replaces it with the contents of n, which is the number stored earlier + --takes the number and adds it to the running total, which is contained as the last item on the stack ] --ends the inner for loop ] --ends the outer for loop ` --print the top item (also the only item) on the stack to output ``` [Answer] # Perl, 31 ``` <>;$i+=$_*($_>0)while<>;print$i ``` [Answer] ## Ruby 1.9.2, 37 ``` p eval [*$<].join.gsub(/\A\d+|-\d+|\n/, '+0') ``` Call like ruby scriptname file\_with\_ints . [Answer] # Ruby, 52 ``` t=gets.to_i;s=0;t.times{i=gets.to_i;s+=i if i>0};p s ``` [Answer] # Haskell, 58 Properly operates on only `t` integers. Haven't run it against Spoj because I just don't care to register there. ``` f (x:l) = take x l main = interact $ show . sum . f . map (max 0.read) . lines ``` [Answer] ## code in **C 89 characters** --- ``` x="%d"; main(b,a,t) { for(scanf(x,&t);t;t--) { scanf(x,&a); a>0?b+=a:a; } printf(x,b-1); return 0; } ``` **I tried a lot to reduce my code less than 63 bytes, but i can reduce it only to 89 bytes. Please help me to reduce it to 63 bytes or even less.** [Answer] ## Perl, 33 ``` <>;while(<>){$i+=$_ if$_>0}print$i ``` Although the space is necessary, so it seems odd not to count it. Oh well, the rules is the rules. Hmm. I could probably get away with using a variable name which doesn't count towards the total either. The thing is, I'm not sure how I'd paste the code then. [Answer] # Clojure, 71 ``` (reduce + (filter pos? (map #(Integer/parseInt %) (next (line-seq *in*))))) ``` [Answer] In memoriam Dennis M. Ritchie ## unix 57¹72: ``` n=$(head -n1 i); echo $(($(head -n $((n+1)) i | tail -n $n | grep -v "-" | tr '\n' '+')0)) ``` assuming i is the file, containing the ints. ¹) was wrong, included the number of lines, and added 1 line too less. echo $(($(cat i | head -n $(head -n1 i) | grep -v "-" | tr '\n' '+')0)) [Answer] ### Haskell, 51 ``` main = interact $ show . f . lines f (x:l) = foldl (+) 0 $ map read l ``` (extra spaces for clarity, since they don't count) Haskell is ... interesting, since you tend to get programs with a significant number of necessary spaces. [Answer] **C,88** --- ``` x="%d"; main(b,a,t) { for(scanf(x,&t);t--;) { scanf(x,&a); a>0?b+=a:0; } printf(x,b-1); return 0; } ``` --- **After another big effort, code is one character less, please help me to reduce it more.** [Answer] # Befunge-98 (24) (Make sure you use an interpreter that can read negative numbers (seems to be a somewhat common bug, but RcFunge works)) ``` <;-1\+*`0:&\_\#;.@;:;#&0 ``` # Perl (25) (Perl allows control characters in variable names, I named my variable ^B (ASCII 2) so that it does not count towards the goal.) ``` <>;$***^B***+=$_*!/-/for<>;print$***^B*** ``` (Normal variant (27 chars)): ``` <>;$B+=$_*!/-/for<>;print$B ``` [Answer] ### APL (10) ``` +/{0⌈⎕}¨⍳⎕ ``` Explanation: * `⍳⎕`: read a line, gives a list [1..N] for user's input N * `¨`: for each element in this list... (i.e. do N times) * `0⌈⎕`: read a line, return the maximum of 0 and the entered N * We now have a list with all positive Ns the user entered, and 0s where the user entered something negative. * `+/` gives the sum of this list. * The result is output by default (because we're not doing anything else with it). [Answer] **Mathematica: 18 16** ``` Boole[#>0]&/@x.x ``` [Answer] ## PowerShell, 44 ``` ($i=$input|%{+$_})[1..$i[0]]-gt0-join'+'|iex ``` [Answer] ## Q,12 ``` {0+/x(&)x>0} ``` sample usage ``` q){0+/x(&)x>0} 1 -1 2 3 -1 6 ``` [Answer] ## befunge, 3524 ``` :0`j&1-\&:0`*+\:0`3*j$.@ ``` with a little inspiration by seeing marinus answer, I've also managed 24 characters. but I've got a completely different approach. [Answer] # PYTHON 2.x, 50 chars ``` r=input print sum(i for i in (r() for j in range(r())) if i>0) ``` [Answer] # C, 70 72 characters ``` s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",s?&i:&c);printf("%d",s-1);} ``` The results on the SPOJ site definitely seem unreal - I have no idea how to get this down to 63. However, **68** characters is reachable on some compilers by abusing undefined behaviour. The following works on x86 Linux with 32-bit gcc, on which all arguments are passed on the stack. ``` s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",&i+!s);printf("%d",s-1);} ``` [Answer] ## excel, 27 ``` =SUM(INDIRECT("A2:A"&1+A1)) ``` count t in A1, rest of data a2 and down [Answer] ## Clojure, 108 ``` (let [[n & m] (->> *in* java.io.BufferedReader. line-seq (map read-string))] (->> m (take n) (filter pos?) (apply +) println)) ``` I really wish I could avoid the `java.io.BufferedReader.` part, since it costs 24 chars itself. But AFAIK there's no facility to read lines from STDIN without it. [Answer] # Perl, 20 I know it is old and trivial, but the Perl answer can be still improved: ``` #!perl -p $.<2or$\+=$_*!/-/}{ ``` [Answer] C++: ``` #include<iostream> using namespace std; int main() { int c,n,s=0;cin>>c; while(c--) { cin>>n;s+=n*(n>0); } cout<<s;return 0; } ``` 115 characters long. Need to optimize it to 90. Any suggestions ? [Answer] ## PHP, 71 ``` <?for($s=0,$t=fgets(STDIN)+0;$t--;$s+=($n=fgets(STDIN))>0?$n:0);echo$s; ``` [Answer] ### Python: (92 characters) ``` t = int(raw_input()) n = [int(raw_input()) for i in range(t)] print(sum([n[i] for i in range(t) if n[i]>0])) ``` [Answer] ### scala ~~55~~ 54: ``` println ((for (r <- 1 to readInt; i=readInt; if i>0) yield i)sum) ``` [Answer] ## C ``` void main() { int n; scanf("%d",&n); for(int i=0;i<n;i++) { if(i>0) sum=sum+i; } printf("sum of positive numbers is %d",sum); } ``` [Answer] ## Ruby, 42 ``` s=0 gets.to_i.times { i=gets.to_i s+=i if i>0 } p s ``` (based on david4dev's answer) Best score for Ruby on spoj: <http://www.spoj.com/ranks/SIZECON/lang=RUBY> [Answer] # 45 chars in python ``` c=0 j=input for i in j()*[0]: b=j() c+=b*(b>0) print c ``` ]
[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/15372/edit) The challenge is to create a program that solves *any one* of the HQ9+ problems while looking like another language. **Note**: This is not a golf challenge. ## Rules: * The program must perform one of the following tasks when run. + Print "Hello, World!" + Print its entire source. + Print the lyrics to "99 Bottles of Beer on the Wall" (as seen [here](http://www.99-bottles-of-beer.net/lyrics.html)). * At first glance the program should look like another language. ## Grading * Working program that satisfies the rules. **+3** * Bonus points if the "other language" can be run (syntax valid). **+1** * Even more points if the "other language" can do something useful. **+3** * Lots of bonus points for the program being valid (and useful) in even more languages. **+5** for each language over 2. [Answer] ## T-SQL ``` Print 'Hello, World!' -- she said. ``` Looks like **English**. [Answer] # Ruby + C + Whitespace. This program is C but looks like (and runs as) Ruby. I also managed to throw some whitespace in there. C prints its own source (not quite a quine unfortunately). Ruby prints 99 bottles of beer and whitespace says hello. ``` #include <stdio.h> #define def int #define beer main(int i){char b[1024]; #define print(v) print(int v){ #define end ;} #define if(x) fputs(b,stdout); fgets(b,1024,f); if(x){ #define else ;} else{ #define puts #define print #define open(fn) FILE *f = fopen(fn,"r"); #define while(x) fgets(b,1024,f); while(!feof(f)){ def beer # define beer open("test.c") i=100; while ( i >= 0 ) if ( i > 0 ) print "#{i} bottle#{i==1&&''||'s'} of beer on the wall, " puts "#{i} bottle#{i==1&&''||'s'} of beer." print "Take one down and pass it around, " puts "#{i-1} bottle#{i==2&&''||'s'} of beer on the wall." puts else puts "No more bottles of beer on the wall, no more bottles of beer." puts "Go to the store and buy some more, 99 bottles of beer on the wall." end i -= 1 end return 0 end beer ``` And since SO isn't very nice to ws [here is a link](https://gist.github.com/kevincox/7709214). [Answer] # Golfscript / HQ9+ ``` 9 ``` A Golfscript quine that doubles as an HQ9+ program that prints the lyrics to 99 bottles of beer. I know this isn't a golf challenge, but I couldn't resist the desire to answer this with one character. [Answer] ## Perl, 7 points ``` 99 <?php for($i='no more',$_="`\2l\";7hF'`-{9\17p\t\2ZY\14fE\25T\133J`\35l\"76~\x3"; 99>${2}="$i bottle".(${$i+=1}<'))'?+s?:s:!'((').' of beer'; ${3}=" Take one down and pass it around, ${1}. ".ucfirst("${1}, ${2}.${3}"))${1}=$i||${2}?"${2} on the wall":'?;\''; print substr("${1}, ${2}.${3}". ($_^"jE\3\2OXH2O\5\15\10M$_").", ${2} on the wall.",3,13*$i*$i); ``` This is a Perl program that prints `Hello, World!`. **Score breakdown:** * Follows all rules: **+3** * Is valid syntax in another language: **+1** * Does something interesting in the other langauge: **+3** **Sidenote:** Once you know what it does it might seem 'obvious' where it's hanging out, but this is a dupe. The following: ``` $_="`\2l\";7hF'`-{9\17p\t\2ZY\14fE\25T\133J`\35l\"76~\x3"; print$_^"jE\3\2OXH2O\5\15\10M$_" ``` will output: ``` Go to the store and buy some moreET[J`l"76~ ``` [Answer] # JavaScript, 7 points ``` <!-- h='Hello, World!' --> /******<br> <b>Hello, World!</b><br> *******<br> This is my <i>awesome</i> Hello World page<br> *******<br> Look I can make images I'm so good at HTML:<br> <img src='http://pieisgood.org/images/slice.jpg' alt='awwww you cannot see my amazing image' /><br> <hr> These are the things this page has:<br> <ul> <li>Bold</li> <li>Italics</li> <li>Images</li> <li>Lists</li> </ul><br> I like random characters! That's what this page will finish with:<br> ;37!&$89]"]0(!)89^!&8*/81+-0;h ``` When run in JavaScript, produces "Hello, World!" When viewed as HTML, looks like this: ![screenshot](https://i.stack.imgur.com/6P5Pe.png) # Scoring * Working program that satisfies the rules **+3** * Other language syntax is valid **+1** * Other language does something useful (you can put any HTML you want in there) **+3** [Answer] **C++/Python** ``` #include <iostream> #define print(a) int main() {std::cout << a << std::endl;} print("Hello, World!") ``` Will run in Python (both 2.x and 3.x) and compile in C++ to print (with carriage return): > > Hello, World! > > > [Answer] The following prints "Hello,World" (and a random table) in HTML and "Hello, World!" in [Whitespace](http://en.wikipedia.org/wiki/Whitespace_%28programming_language%29). ``` <html> <head> <title> Hello,World! </title> <body> <p> Hello,World! </p> <table> <caption> Summary </caption> <tbody> <tr> <th>Year</th> <th>Revenue</th> </tr> <tr> <td>2012</td> <td>$100,000</td> </tr> </tbody> </table> <footer> HTML5! </footer> <!--Comment--> </html> ``` [Answer] # PHP, HQ9+, Brainfuck and Bash (23 points, I think) Looks like PHP, but... Abuse of STDERR redirection and quotes. ``` what the >&_@ is a "<?php //Boring, really ( ;[ ). This just prints Hello World!" echo "Hello, World!"; //]&> are random characters that I like putting in" ?>" program? ``` This runs and does things in all the languages listed, but looks like (slightly weird) PHP code. In Bash, it merely prints "Hello, World!" (creating junk files along the way). In HQ9+, it prints Hello World a few times (once for every occurence of `H` or `h`). In Brainfuck, it is a "cat program" - it reads from standard input and outputs its input to standard output (`><,[.,]>>`). In PHP, it prints some text: > > what the >&\_@ is a "Hello, World!" program? > > > ## Bash Explanation `>&_@` is disguised as harmless text substituting a curse, but it is in fact a redirection of STDERR to the file `_@`, so that Bash doesn't complain that `what` is not a valid program. It also eats the `is a <?php` bit and the first comment. The first comment has a quote at the end (the quotes are there to prevent `<?php` from being run). `echo "Hello, World!";` runs normally in both languages. The next comment serves to hide another quote, and there is an output redirection from STDERR to the file `are`, to eat the message " //: Is a directory". Since the closing `?>` is in quotes, it doesn't get run, and gets eaten along with the second comment and the bit after it. [Answer] ## JavaScript, 3p ``` <!-- $res = Array(); $ks = Array("", "", ""); function convert($x) { return $x["toString"](36); } for ($i=0; $i < 1000000; $i++) { this[convert($i)] = $i; if ($i == 626 || $i == 777 || $i == 865 || $i == 1176 || $i == 35761) $res[$res.length] = convert($i); if ($i == 381 || $i == 19145) $ks[0] += convert($i); if ($i == 19 || $i == 31775) $ks[1] += convert($i); if ($i == 1033 || $i == 27893) $ks[2] += convert($i); } this[$ks[0]]($res[$ks[1]]("")[$ks[2]](1)[$ks[1]](" ")); --> yay <h1>hi</h1> /// heading <p>lol</p> /// content ``` Masquerades the output of a misconfigured web server, as (something that at first glance looks like) **PHP+HTML** mess. This started out small but grew bigger as I tried to make it less obvious what it does (when evaluated as JS)... it might've become more obfuscated than the task intended, sorry about that. Anyway, the main thing I wanted to include was my trick for embedding (a subset of) HTML such that it's also valid JavaScript code, which is what you see at the end of the code. Edit: oh, I should mention, *when run in a website context the code alerts "hello world"*. [Answer] # Python/PHP/Lua/Perl/Perl 6/Ruby/JavaScript/HQ9+ (37 points) ``` print("Hello, World!") ``` This looks like "Hello, World" in Python, but it's actually a quine written in PHP. It also works in JavaScript (SpiderMonkey), Lua, HQ9+, Perl, Perl 6 and Ruby, for bonus points. [Answer] # JavaScript/Python 3/PHP/Lua/Brainfuck/bash This looks like... Umm... Obfuscated PHP? ``` #!,[.,] echo = --[[0] ] [0][0] //1#>/dev/null;echo Hello, World!;exit # ]]0 --[[0] ] [0][0] //1#<?php for ($i = 99; $i > 1;) { printf("%d bottles of beer on the wall, %d bottles of beer.\nTake one down and pass it around. %d bottle%s of beer on the wall.\n\n", $i, $i, --$i, ($i != 1 ? "s" : "")); } print("1 bottle of beer on the wall, 1 bottle of beer.\nTake on e down and pass it around. No more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more. 99 bottles of beer on the wall.\n"); die(); ?> 2//2; print("Hello world!"); exit();""" console.log("Hello, World!");/*]] f = io.open(arg[0]) print(f:read("*a")) --[[*///]]--""" ``` * If you run it in bash, JavaScript or Python it'll print "Hello, World!" * If you run it in Lua, it'll print the script's source code (if provided as the first argument to `lua`). * If you run it in PHP it'll print the lyrics of 99 bottles of beer * If you run it as Brainfuck, it'll work like `cat`. ## Score: 27 * Follows the rules: 3 * Other language can run: 1 * Does something useful: 3 (cat program) * Also works in JS/Python 3/Lua/bash: 20 I hope I'm not bending the rules too much :) [Answer] **Java written in C++** ``` #include <stdio.h> typedef char* String; class P{ public: static void println(String s){ puts(s); } }; class S{ public: P out; }; int main() { S System; System.out.println("Hello world!"); return 0; } ``` Score 3 points. [Answer] ``` print `open(__file__).read()`, 1000 // len(''' /* Calculate code conciseness score for some random JavaScript */ function print() { console.log('Hello, world!'); } <!--''') # ASCII submarine ``` This looks like Python 2, and runs as Python 2, printing its own source in Python string literal form, as well as a code conciseness score of some kind! When run as ES6, however, it prints “Hello, world!”. ]
[Question] [ [There is a challenge for multiplying two numbers so I guess this counts too](https://codegolf.stackexchange.com/q/106182/91213) Given as input a positive real number `n` compute its natural logarithm. Your answer should be within \$10^{-6}\$ for \$1 \leq n \leq 10\$ and within \$10^{-3}\$ for \$0.1 \leq n \leq 100\$. You don't need to handle numbers outside this range. See [this thread on mathematics.se](https://math.stackexchange.com/q/61279/1096272) for various approaches to this problem. Just for inspiration, feel free to use a method not on that page. Please add builtin answers to [the community wiki](https://codegolf.stackexchange.com/a/262712/91213) instead of posting them separately. ## Test Cases | x | ln(x) | | --- | --- | | 0.1 | -2.3025850929940455 | | 0.25 | -1.3862943611198906 | | 0.5 | -0.6931471805599453 | | 0.75 | -0.2876820724517809 | | 0.9 | -0.10536051565782628 | | 1.0 | 0.0 | | 1.3 | 0.26236426446749106 | | 2 | 0.6931471805599453 | | 2.718281828459045 | 1.0 | | 3.141592653589793 | 1.1447298858494002 | | 4 | 1.3862943611198906 | | 5 | 1.6094379124341003 | | 7 | 1.9459101490553132 | | 10 | 2.302585092994046 | | 53 | 3.970291913552122 | | 54.59815003314423 | 4.0 | | 99 | 4.59511985013459 | ## IO Standard IO rules apply. Importantly, you may take input as a fraction if you prefer. You may also output as a fraction, which does not need to be fully reduced. [Answer] # Excel, ~~19~~ 16 bytes With many thanks to **Dominic van Essen** for the 3-byte save: ``` =1E9*(A1^1E-9-1) ``` *Previous*: ``` =9^9*(A1^(1/9^9)-1) ``` Input in cell `A1`. The choice of `1E9` (i.e. 1000000000) is sufficient for the given test cases and required accuracy. [Answer] # Builtins These answers are in alphabetical order based on programming language. If your answer is identical to an existing one, please combine them. ## [05AB1E](https://github.com/Adriandmen/05AB1E), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žr.n ``` [Try it online!](https://tio.run/##HYvNCQJBDIVbCXsOIZkkzuS0hYigggcvCi4INmABVuNpL2IjNjJmF14@wvu5Tofj@dT7d77RpX/e98d@Ggf4PV8wjNi3TILAVHzhiroyEDIQUoSSoiqttOXMgy0rSmLiUTau3qJGFg0hg5ozzi8NN/Jo4syqYlbSitj9AQ "05AB1E – Try It Online") ## [APL (Dyalog Unicode)](https://www.dyalog.com/), 1 byte ``` ⍟ ``` [Try it online!](https://tio.run/##FcSxDcIwEADAVX4BLL//H/trGmgJC0RCoYkELTVSCiRHoaBmASQaJmCUX8TYxV1/GVfHaz@eT6VYfpXBpsXybPeb5bfl7@9DNj1sfnb7Tf2w3XVlAO@wClJrYksBna8IAgQXMYXUsKhnAXLIKBrWQpI0KgGDQAT0IATCTjSheE@EzIFA9Q8 "APL (Dyalog Unicode) – Try It Online") ## [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` *₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X@tRU@P//5aW/6MA "Brachylog – Try It Online") ## [C (gcc)](https://gcc.gnu.org/) / [PARI/GP](https://pari.math.u-bordeaux.fr) / [Julia](http://julialang.org/) polyglot, 3 bytes ``` log ``` [Try it online in C (gcc)!](https://tio.run/##HY/dboMwDIWvyVNYrSpBCVECySBi64uMXdBAWCSaIH52M/XVx0wl@8g69mfZJhuM2c9db53vwUKzj2HYz86bcet6eF/WzgX2fSPE@ZU8Wufjn@C6hPySyAS/rNCF7T720H5@wQegG3EmKHCWq0NfUr5UU8CGYAWFHIOVosqrI6XSXCqKaMGEFErnb6pQlS41jkoKSJcIcqzQUJIpXQnFeVEIKXO0NK7mJHpSuE41IZENM8QTntPWhwNpOiW4fZrxBxufLkOzZje4pLbxp4OhYOPrlCQHO/frNnvgNXnuf8aO7bDs2fj4Bw) [Attempt this online in PARI/GP!](https://ato.pxeger.com/run?1=JY5NCsJADEavErpqYRrmL85k40VEpBtLoehQKlTEpadwUxDxEJ7E2zhpF-_LF3iBPD-pGbpDm-bvDZqU-ms5Qb2FNHSnMddCluJ9GY91fPXndm2_RzlVlYKdRqNAoyXJJcKSrMCg4BRYFIKJNgqeWPssOTTeENsNOYocOJs-m5QJcqplcRIeiaMhrZ0z3tssMuO-gvv6zDyv8w8) [Try it online in Julia!](https://tio.run/##HYtNCgIxDIX3c4ocoISmTWyz0IuIC8WZoVKqyAguvHvNFF4@wvt5fGq50rcvcITbvJbW63Ptc7tP09kjOfAYZOdAGlQHFhBGB8GEiXLI@7GoZ6tEJCbRcJAoWZNakR1YkGzm7TNDGEUzifcxEnMwS/UC@DvBMvh6l7bV1v8 "Julia 1.0 – Try It Online") ## [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` {ml} ``` [Try it online!](https://tio.run/##S85KzP2fU/e/Ojen9n/dfwM9QwA "CJam – Try It Online") ## [Desmos](https://desmos.com/calculator), 2 Bytes ``` ln ``` [Try it online!](https://www.desmos.com/calculator/x7bhhsm1zj) ## Excel, 7 bytes ``` =LN(A1) ``` ## [Go](https://go.dev), 17 bytes ``` import."math" Log ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohI9pbTcEqWlpSVpuhY3TWFiuYklGUpcaaV5yQppGnkKaTn5iSVmJppQurootaS0KE_BJz9dI0-zFqrZAqwcZLSGpkI1V1p-kUKmla2BnnWmjaEBiNLWruYKKMrMK8nJ08jUARqcqanJVcsF1b9gAYQGAA) ## [J](https://www.jsoftware.com), 2 bytes ``` ^. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=Jc0xCsJAEAXQ3lN8LAxCMszs7Lg7AW0EKysPYCMGSSOInsYmCh7Co3gbN6R4___uP1_98J1T1WHdokINRls0hO1hv_s87l2T30eaxu-2nJ1PlytqQrfYgEmKYCVGaQyHEBeKgEBJcsijaM7RoCRRzMPK1LInV0QYEoRhCotknsWYVSXGoHCfnodh6j8) ## [J-uby](https://github.com/cyoce/J-uby), 9 bytes ``` :log&Math ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWK61y8tPVfBNLMiD8m4oahnp6hgYGmnqpickZCin5CjV5NVwKCgUKbtF5sVypeSkQhQsWQGgA) ## Java, 9 bytes ``` Math::log ``` [Try it online!](https://tio.run/##PU/LboMwELznK1Y5gUItG@yC6ePSqreccoxycHkV6mCEDVUU5doP6Cf2R@hC2kq7s6udmdVuo0Z10@TvU6aVtbBVdXteAXTDq64zsE45LKOpczgi5e1cX7fV/qD6yvqzEKDBDWRwtSbl0GauNi15@W3unw3uKYJreYQSHqatcm9pqk013S320vTeqHpwhXVPyhaQQlt8QL5Y9oczJSwASkIx4wLxgjIAJBiJAggxSMySMJmTC0k5SiLCOBMyvBWRSGQsUcgDQCJGG8UOB4ITIRMmKI0ixnmIIykv/nIYwO5kXXEkZnCkw7edbr2/Kzdr@P78gvWmJKrr9Omf8P35rcvqMv0A "Java (JDK) – Try It Online") ## [JavaScript (Node.js)](https://nodejs.org), 8 bytes ``` Math.log ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvHfN7EkA8T6r2GhqfkfAA "JavaScript (Node.js) – Try It Online") ## [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Æl ``` [Try it online!](https://tio.run/##HYu5DcMwDEVXUeGSIHhG4gSeJE2gBdKmsJfJFt7Ei9C0gc8H4h@f95zfzGObCce@nL//mknI0AjFbz7oDwNaBYwKTUrYeci4zzzIqqLIxh7ycvURPapo0CroNaP6ynBDj8FOpMpmUlbEBQ "Jelly – Try It Online") # [Julia 1.0](http://julialang.org/), 3 bytes ``` log ``` [Try it online!](https://tio.run/##HYtNCsJADIX3PUXoqoVhmMwkzmThScSFoJVKSaVU8AQewCN6kTEtvHyE9/N4TeMF33U41mm@12FeQGFUOAWPDoKPvHFH3ikOLECfHESTz1hi2Y5YAlkleSRkiQdOXCSLFcmBBdlmwT4zmDxLQQ4hJSSKZomcG4DnMuo6aacOWvh9vtA6GDrt@@am1/oH "Julia 1.0 – Try It Online") ## [MATL](https://github.com/lmendo/MATL), 2 bytes ``` Yl ``` [Try it online!](https://tio.run/##y00syfn/PxKIjfUMTQxNLY3MTI1NLSzNLY0B "MATL – Try It Online") ## MATLAB / [Octave](https://www.gnu.org/software/octave/), 4 bytes ``` @log ``` [Try it online!](https://tio.run/##y08uSSxL/Z@WX5SbWKKQk5@XzpVmq6en998hJz/9f5qGgZ6h5n8A "Octave – Try It Online") ## Pascal, ≥ 5 bytes The built‑in function `ln` fulfills the task. Its only parameter needs to be positive. Extended Pascal, ISO standard 10206, allows complex numbers, too. ``` ln(n) { where `n` is an acceptable numerical expression} ``` ## [Pyth](https://github.com/isaacg1/pyth), 2 bytes ``` .l ``` [Try it online!](https://tio.run/##K6gsyfj/Xy/n/38jAA "Pyth – Try It Online") ## [Python 3](https://docs.python.org/3/), 20 bytes ``` import math math.log ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCE3sSSDC0To5eSn/0/LL1LIVMjMUyhKzEtP1TDUUTA0MNC04lJQKCjKzCvRyNRRgKnVyNTU/A8A "Python 3 – Try It Online") ## [Racket](https://racket-lang.org/) ``` (log z) ``` [Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE4Wjk5KcrWFpq/v8PAA "Racket – Try It Online") ## [Rust](https://www.rust-lang.org), 7 bytes ``` f64::ln ``` [Attempt This Online!](https://ato.pxeger.com/run?1=dZJfahsxEMahjz7F9G0X1ur8lTRJe5LSBxe8EHA2YDtgE3KSvvihpQfobXqajrLYC4UsiNXo92n0zUg_fu6fD8fLn3GCx83D1PXwstseYTfBl1_Px3Fdf49Z7-520xz9_TDer8anPXSn4dzDwwRfVxBfh4kGWHMSZKuGzu6KatYPV84WAkpSM7tKJiKvjnkRNI4pu5AWqmgWKUwWXmYB15IrY2E1KhV9EfgbJzTJaGTZSuXM9SqghANgwiWWFodEsnJWzUWdFkc8698zxCkWubah5lHrALQkl0RK5pxNrHpxaZRUC3utVjW6g3wVazvp_dbYjDMGLE6sooR4M1JmHN7CPamHUSG5JSds_P-bWZJLw5K8IDs5iRkT33abJvNKFudFG5SjDl2qdG-bm8SaZ0OScBH0G7y8KTaHw3Z__Nh1u6k79bCGc5823w_xzD7BeZ6lx82p3U0Pn4G269zfr15Xr_Nzu1zm_z8) ## Swift, 40 bytes ``` import Darwin;var l={i->Float in log(i)} ``` macOS-only. ## [Thunno 2](https://github.com/Thunno/Thunno2), 2 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ÆN ``` [Try it online!](https://Not-Thonnu.github.io/run#P2hlYWRlcj0mY29kZT0lQzMlODZOJmZvb3Rlcj0maW5wdXQ9JTVCMC4xJTJDJTIwMC4yNSUyQyUyMDAuNSUyQyUyMDAuNzUlMkMlMjAwLjklMkMlMjAxJTJDJTIwMS4zJTJDJTIwMiUyQyUyMDIuNzE4MjgxODI4NDU5MDQ1JTJDJTIwMy4xNDE1OTI2NTM1ODk3OTMlMkMlMjA0JTJDJTIwNSUyQyUyMDclMkMlMjAxMCUyQyUyMDUzJTJDJTIwNTQuNTk4MTUwMDMzMTQ0MjMlMkMlMjA5OSU1RCZmbGFncz1O) ## [Vyxal](https://github.com/Vyxal/Vyxal), 2 Bytes ``` ∆L ``` [Try it online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLiiIZMIiwiIiwiMiJd) ## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 3 bytes ``` Log ``` [Try it online!](https://tio.run/##HYtBCgIxDEWvEhhwVWPTJLbZyBzAhXtxMYjoLMYB6U48e21m8R58eH@Z6uuxTHW@T@3ymd/1OsD@BO28Pts43GAHhxG@ESlAxKTuTXmzBSB0OEBCJ1NJxRG1KD1iJCG1dFTWYtl6Kb3UTvZr9MEuQbVCGiMziaQemuGv/QE "Wolfram Language (Mathematica) – Try It Online") [Answer] # [><> (Fish)](https://esolangs.org/wiki/Fish), 71 bytes Trying to solve this in ><> was the original inspiration for this challenge. Posting this now instead of waiting the usual 24 hours to hopefully inspire more esolang submissions. ``` ![i](https://$ "read a character")![0](https://$ "Push the number (0-9)")![a](https://$ "Push the hexadecimal (10-15)")![:](https://$ "Duplicate the top item on the stack")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![~](https://$ "Delete the top element of the stack")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![n](https://$ "output a number in decimal")![;](https://$ "Halt") ![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![:](https://$ "Duplicate the top item on the stack")![?](https://$ "Pop 1 value of the stack, if it's 0 skip the next instruction and move forward 2 spaces.")![v](https://$ "Change Cursor Direction")![\](https://$ "Reflect the cursor direction")![:](https://$ "Duplicate the top item on the stack")![2](https://$ "Push the number (0-9)")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![$](https://$ "Move the top element of the stack back 1")![,](https://$ "Divide the top 2 values of the stack.")![$](https://$ "Move the top element of the stack back 1")![:](https://$ "Duplicate the top item on the stack")![@](https://$ "Move the top elemnt of the stack back 2") ![}](https://$ "Shifts the entire stack left or right")![:](https://$ "Duplicate the top item on the stack")![{](https://$ "Shifts the entire stack left or right")![$](https://$ "Move the top element of the stack back 1")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![/](https://$ "Reflect the cursor direction")![/](https://$ "Reflect the cursor direction")![*](https://$ "Pop 2 values of the stack then perform the given operation.")![,](https://$ "Divide the top 2 values of the stack.")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)")![}](https://$ "Shifts the entire stack left or right")![:](https://$ "Duplicate the top item on the stack")![{](https://$ "Shifts the entire stack left or right")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![1](https://$ "Push the number (0-9)") ![/](https://$ "Reflect the cursor direction")![$](https://$ "Move the top element of the stack back 1")![+](https://$ "Pop 2 values of the stack then perform the given operation.")![@](https://$ "Move the top elemnt of the stack back 2")![$](https://$ "Move the top element of the stack back 1")![~](https://$ "Delete the top element of the stack")![/](https://$ "Reflect the cursor direction")![\](https://$ "Reflect the cursor direction")![$](https://$ "Move the top element of the stack back 1")![3](https://$ "Push the number (0-9)")![1](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.") ![\](https://$ "Reflect the cursor direction")![1](https://$ "Push the number (0-9)")![-](https://$ "Pop 2 values of the stack then perform the given operation.")![2](https://$ "Push the number (0-9)")![0](https://$ "Push the number (0-9)")![.](https://$ "Pop 2 values of the stack then move to that position.") ``` Hover over any symbol to see what it does [Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTBhOjErP3Z+MipuO1xuMioxKzo/dlxcOjIqMSsxJCwkOkBcbn06eyQtMS8vKiwrMX06ey0xXG4vJCtAJH4vXFwkMzEuXG5cXDEtMjAuIiwiaW5wdXQiOiIyIiwic3RhY2siOiIiLCJzdGFja19mb3JtYXQiOiJudW1iZXJzIiwiaW5wdXRfZm9ybWF0IjoibnVtYmVycyJ9) Based on the power series \$\ln(z)=2\sum\_{n=0}^\infty\,\frac{1}{2n+1}\left(\frac{z-1}{z+1}\right)^{2n+1}\$ from [this answer om math.se](https://math.stackexchange.com/a/61283/1096272). ><> lacks exponentiation so that too must be done with a loop. [![enter image description here](https://i.stack.imgur.com/bJ4ua.png)](https://i.stack.imgur.com/bJ4ua.png) The green loop is the big sum while the grey loop raises to the power of 2n+1 [Answer] # [Hexagony](https://github.com/m-ender/hexagony), ~~161~~ 122 bytes ``` ?.{10''2\}{}u44.\4476'*0&}=..$/:"-+{=&={{/.|"=}{{&={*={&1d000000}{{}240504"-~{&137{:_1&':!@..~<>".){{{=$/_"'\>{={<>(<\&1=/ ``` [Try it online!](https://tio.run/##JYxNCsIwFAbPYiiJVvryY7QQ8qIHCRRBqStdCcpnevUYdFbDLOZ2fZ3nx/1d65FgjVIuF5Sn95S9Hw@qN7IwUaeDGLZgyYCmj@ACNO8Z0l7Mj1aK82ZvvBiWlncjwmSlCqsT0RKToA0A7vQkVE5gxLSOWVrWtbr/wnwB "Hexagony – Try It Online") Layed out: ``` ? . { 1 0 ' ' 2 \ } { } u 4 4 . \ 4 4 7 6 ' * 0 & } = . . $ / : " - + { = & = { { / . | " = } { { & = { * = { & 1 d 0 0 0 0 0 0 } { { } 2 4 0 5 0 4 " - ~ { & 1 3 7 { : _ 1 & ' : ! @ . . ~ < > " . ) { { { = $ / _ " ' \ > { = { < > ( < \ & 1 = / . . . . . ``` My first go at a Hexagony program. Could probably still be golfed some, but I'm happy to have gotten it to side length 7. Since there are no floats in Hexagony, input and output are both fixed point \$\lfloor n\cdot10^7\rfloor\$. ### The algorithm (skip to the second paragraph if you don't care how I came up with it or why it works) The algorithm used to approximate here is one I came up with myself. I'm sure something like it has been done before, but I'll go over how the constraints of Hexagony led me to this particular method. The first useful observation is that all logarithms are the same, at least up to a constant multiple. That is, \$\log\_a(x)=\frac{\log\_b(x)}{\log\_b(a)}\$. This is nice because \$\log\_{10}\$ is easier to work with when dealing with decimal representations. In fact, it's super easy. We can approxiamte the base ten logarithm just by taking the length of the decimal representation! Unfortunately, on the range \$[0.1, 100]\$ this give us 4 possible output values. Not quite good enough. We need a way to make our numbers longer, but longer in a very specific way. Firstly, as I mentioned earlier, we can't even enter \$0.1\$ into Hexagony, so we pad the lengths and get some necessary input precision by multiplying everything by \$10^7\$. Then, we use another simple logarithm observation: \$\log(x)=\frac{1}{n}\log(x^n)\$. Which is to say, up to another constant multiple (which was already necessary), we can take our input to any power before taking the logarithm. Great, so we just take the input to some super high power, take the length of the result and multiply it by something. But there's still a problem. While this idea *technically* works, it means that we'd be multiplying and measuring the length of numbers millions of digits long. I'd never be able to verify any test cases. We've successfully made our numbers longer, now we need to make them shorter. So we break the large exponent into steps, and at each step we truncate the input. By looking at how much we truncate each time we can give an approximation for how long we think it would have gotten if it didn't truncate. This approxiamtion becomes our logarithm. So, for the actual algorihtm: We take the input and keep a running count of how many digits long we think it is. We enter a loop. For each iteration, we square the input and double this running count (since squaring roughly doubles length). We then truncate the input to the first 7 digits, and add the number of digits we took off to our running count. Iterating 24 times gives us more than enough precision. We then take our predicted length, add a constant, multiply by a constant and print it out. ### The agony So how is this implemented exactly? I'll refer to the memory graph as it is labeled below. as well as the colored paths. [![colored paths for reference](https://i.stack.imgur.com/LXrVbm.png)](https://i.stack.imgur.com/LXrVbm.png) [![memory after computing ln(2)](https://i.stack.imgur.com/rgywam.png)](https://i.stack.imgur.com/rgywam.png) Note that I only use one instruction pointer for this program, which is probably not optimal. We begin on the blue path. This initializes some variables, putting the input in A, `10` in H, `100000000` in I, and `24` on L leaving the memory pointer in L. Then on to the main loop in green. The main loop first uses G and F to square A, then similarly uses E and K to double D. Moving the memory pointer to B, we then use the yellow path to redirect into a sub loop on the orange tiles. This sub loop uses B an C to divide A by 10, compare against I and increment D. Once the input is less than I, We use the red path to traverse back to the main loop, putting the memory pointer back on L and decrementing. L serves as the main loop counter. Once L is 0, we break out of the main loop and on to the purple track. The purple track uses C and J to do the final subtraction and multiplication on the output in D. The final output ends up in J Visualizations done with [hexagony.net](https://hexagony.net/). [Answer] # Dyalog APL (no builtin), 13 12 bytes Dyalog does have the builtin [`⍟`](https://help.dyalog.com/18.2/Content/Language/Primitive%20Functions/Natural%20Logarithm.htm), but this way it's more fun :) ``` (⊢-1-÷∘*)⍣=⍨ ``` Basically just Newton's method: $$ x\_{n+1} = x\_n - \frac{f(x\_n)}{f'(x\_n)} $$ where (L is the number we are taking the log of) $$ f(x) = e^x - L \\ f'(x) = e^x \\ x\_{n+1} = x\_n - \frac{e^{x\_n} - L}{e^{x\_n}} = x\_n - 1 - \frac L {e^{x\_n}} $$ ``` (⊢-1-÷∘*)⍣=⍨ ⍨ ⍝ ‎⁡x_0 is L ⍣= ⍝ ‎⁢repeat Newton's method until x_n and x_n+1 are "equal": ⊢-1- ⍝ ‎⁣x_n - 1 - ÷∘* ⍝ ‎⁤L / e^x_n 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` "Equal" here means $$ \left|x\_n-x\_{n+1}\right|\leq10^{-14}\max\left(\left|x\_n\right|, \left|x\_{n+1}\right|\right) $$ [test cases](https://tio.run/##VVDBSsNAEL3nK@a2ibbLTnbXZA9@RL9A0jSWwLIJJpUU6U2KKBE9CN4EvRTvInisf7I/EidFDx7em/eYYeftZLWdLtaZrZbDYJ3fPoT@9nWK0@9Pf/N8FPn@7dT3uyDPmqKhruAIgseaaEQykgHkgiAhhpgnmMbpCKWNUBokR4XaxCda6tQkRoICDQmgAC1BK65NiloIKVGpWIIxg79/qmtaJlVgHZK4mo2r/d312cEcEyM533/B/7jg@4/Nb2aSNDPbBGxedYzezNdsce4aFpAeP4pRiBSZAkU0AaxjwKwLu4jqfFXatnTw55u2qBtYuba0kFfusrhYFi4vmO/f/fZxDDGxbuL7FyoY7XeHew0/) | x | ln(x) | builtin ln(x) | steps until convergence | | --- | --- | --- | --- | | 0.1 | -2.3025850929940455E0 | -2.3025850929940455 | 8 | | 0.25 | -1.3862943611198906E0 | -1.3862943611198906 | 7 | | 0.5 | -6.9314718055994520E-1 | -0.6931471805599453 | 7 | | 0.75 | -2.8768207245178090E-1 | -0.2876820724517809 | 7 | | 0.9 | -1.0536051565782634E-1 | -0.10536051565782628 | 7 | | 1 | 1.1102230246251565E-16 | 0 | 8 | | 1.3 | 2.6236426446749117E-1 | 0.26236426446749106 | 7 | | 2 | 6.9314718055994530E-1 | 0.6931471805599453 | 7 | | 2.718281828459045 | 9.9999999999999990E-1 | 1 | 8 | | 3.141592653589793 | 1.1447298858494002E0 | 1.1447298858494002 | 8 | | 4 | 1.3862943611198906E0 | 1.3862943611198906 | 9 | | 5 | 1.6094379124341003E0 | 1.6094379124341003 | 9 | | 7 | 1.9459101490553135E0 | 1.9459101490553132 | 11 | | 10 | 2.3025850929940460E0 | 2.302585092994046 | 14 | | 53 | 3.9702919135521220E0 | 3.970291913552122 | 55 | | 54.59815003314423 | 4 | 4 | 57 | | 99 | 4.5951198501345900E0 | 4.59511985013459 | 100 | gotta say, ln(1) resulting in 1e-16 is kinda annoying but well within the spec This is 1 byte less than an implementation of Jos Woolley's, `1e9ׯ1+*∘1e¯9`, but probably still has some room to be golfed further. [Answer] # [R](https://www.r-project.org), 18 bytes ``` \(x)1e9*(x^1e-9-1) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGavMSS0qLEnPic_HTbpaUlaboWm2I0KjQNUy21NCriDFN1LXUNNSESN3ORFGukVhRoGGpqciXm5GhogAQMrQwNNHWRlYBFNG2AhpihqTMw0MemGCIM1mEMtXTBAggNAA) Port of [Jos Woolley's Excel answer](https://codegolf.stackexchange.com/a/262714/95126), using a constant of `1e9` to avoid needing parentheses to express its reciprocal of `1e-9`. [Answer] # [Minecraft Data Pack](https://minecraft.fandom.com/wiki/Data_pack) via [Lectern](https://github.com/mcbeet/lectern), 1144 bytes ``` @function a:a summon bat ~ ~ ~ {Attributes:[{Name:generic.armor}]} data merge storage {a:[[9.,-0.9,-0.69,-0.45,-0.26,-0.14,-0.073,-0.038,-0.02,-0.011,-0.0056,-0.0029,-0.0015,-7.6e-4,-3.9e-4,-2.e-4,-1.1e-4,-5.6e-5,-2.9e-5,-1.5e-5,-7.6e-6,-3.9e-6,-2.e-6,-1.1e-6,-5.6e-7],[-1073741824,1073741824,546146222,278783439,140411372,70331752,35347866,18065629,9420929,5157943,2618732,1354293,700005,354538,181900,93273,51298,26115,13523,6995,3544,1819,933,513,261]],Operation:2,UUID:[I;0,0,0,1]} execute as @e[type=bat] run function a:b @function a:b data modify entity @s Attributes[].Base set from storage i data modify storage Amount set from storage a[0][0] data modify entity @s Attributes[].Modifiers append from storage : execute store result score a run attribute @s generic.armor get execute if score a matches 1..29 store result entity @s Attributes[].Modifiers[-1].UUID[] int 1 store result score v a run data get storage a[1][0] attribute @s generic.armor modifier remove 0-0-0-0-1 execute if score a matches 1..29 run scoreboard players operation o a += v a data remove storage a[][0] execute if data storage a[][] run function a:b ``` The function is `a:a`. Takes input in data storage `: i`, as a double. Outputs via a scoreboard `o a`, scaled up by 466320149. If we cannot assume a clean world with no bats, it's +8 to start with a `kill @e` command. If we mustn't kill the player it's another +10 for `[type=bat]`. If we cannot assume the objective `a` already exists it's +34 for `scoreboard objectives add a dummy`. If we can't assume the value `o` doesn't exist yet it's +29 for `scoreboard players set o a 0`. Using a variant of binary search, we go over the values in `a`, multiply our value by `1+x` using attributes, and if it's 1 or more we keep the multiplication and add the log of `1/(1+x)` to our answer. Because the log decreases by less than half in each step we get the correct answer. We start with a multiplication by 10 to deal with the case of \$0.1\leq x<1\$. We only perform the multiplication if the result is less than 30, to prevent the value going over 100. We need to use 30 because `generic.armor` is clamped to it. Uses the fact that the storage name in Minecraft can be empty, as can the score holder. The scoreboard objective could've been as well, but then `scoreboard players operation o a += v a` wouldn't work because spaces are trimmed at the end of each line. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` *İ}’×ʋȷ9 ``` [Try it online!](https://tio.run/##HYu7DcJADIZXuYIKWZaf3HkCJqFBWYACCdFQMABiBwo6BkgKxBhZ5HAi/f5k/Y/jYRhOvW@n93m@PMfH7/79RIfxtpmvr33vhAyFUHzhiroyoGTAqFAkhZWbtOXMgywrimzsITtXb1EjiwYlg5ozyi8NN/Ro7ESqbCZpRfwB "Jelly – Try It Online") Uses the formula \$\ln(z) \approx 10^9(z^{10^{-9}} - 1)\$, adapted slightly from [Jos Woolley's answer](https://codegolf.stackexchange.com/a/262714/66833) ## How it works ``` *İ}’×ʋȷ9 - Main link. Takes z on the left ȷ9 - 10^9 ʋ - Last 4 links as a dyad f(z, 10^9): } - To 10^9: İ - Take it's reciprocal * - Raise z to the power 10^-9 ’ - Decrement × - Multiple by 10^9 ``` # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ’÷‘*÷ṛɗȷŻḤ‘¤SḤ ``` [Try it online!](https://tio.run/##HYuxDQIxDEVXSUGFIitObBJPwADMQINuAboTDSMAor2SPofoiJBgjMsiwXeS/fX1/v@HfdcdW6v9reTaX9clT8/77/LNn9c0Dkrew05Ns@W8qqfHtjUHaI0Dz7MuEhcVazRACNZ4PYiYfJqfWBxpJQASsvgNB04SRYtkjQZRZ06dAiZgScjOhYBEXpHIHw "Jelly – Try It Online") Uses the series definition $$\ln(z) = 2\sum^\infty\_{n = 0} \frac 1 {2n+1} \left(\frac {z-1} {z+1}\right)^{2n+1}$$ For this series, \$1000\$ is more than enough to provide the required accuracy, as pointed out by [mousetail](https://codegolf.stackexchange.com/users/91213/mousetail) for -1 byte! ## How it works ``` ’÷‘*÷ṛɗȷŻḤ‘¤SḤ - Main link. Takes z on the left ’ - z-1 ‘ - z+1 ÷ - (z-1)/(z+1) ¤ - Last links as a nilad: ȷ - 10^4 Ż - [0, 1, 2, ..., 1000] Ḥ - [0, 2, 4, ..., 2000] ‘ - [1, 3, 5, ..., 2001] ɗ - Last 3 links as a dyad f((z-1)/(z+1), [1, 3, 5, ..., 2001]): * - [(z-1)/(z+1), (z-1)/(z+1)^3, (z-1)/(z+1)^5, ...] ÷ṛ - [(z-1)/(z+1), ((z-1)/(z+1)^3)/3, ((z-1)/(z+1)^5)/5, ...] S - Sum Ḥ - Unhalve; Double ``` [Answer] # [Python 3](https://docs.python.org/3/), 24 bytes ``` lambda x:1e9*(x**1e-9-1) ``` [Try it online!](https://tio.run/##BcHBCoAgDADQe1@x4yYGjU4K/UkXI61BqYgH@/r1Xv36XfKqadv1Ce9xBhieozM4jOE4u5lJU2kgIBlayFdEtsALk58AapPcUSwkFCL9AQ "Python 3 – Try It Online") Port of Jos Woolley's Excel answer (and Dominic van Essen's R answer). Somehow only 4 bytes off the built-in. [Answer] # [Ruby](https://www.ruby-lang.org/), 20 bytes CW because it's literally a copy-and-paste of [The Thonnu's Python 3 answer](https://codegolf.stackexchange.com/a/262721/11261). ``` ->n{1e9*(n**1e-9-1)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhZbdO3yqg1TLbU08rS0DFN1LXUNNWshUjsLFNyiDfQMY7lADEM9AwjD0jIWIr9gAYQGAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` I×Xχχ⊖XNXχ±χ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYIyC/PLVIw9BAR8HQQFNHwSU1uSg1NzWvJDUFKuWZV1Ba4leamwRkAxUg1PulpieWpAKZmhBg/f@/ocF/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @JosWooley's Excel answer. ``` N Input number X Raised to power χ Predefined variable `10` X Raised to power χ Predefined variable `10` ± Negated ⊖ Decremented × Multiplied by χ Predefined variable `10` X Raised to power χ Predefined variable `10` I Cast to string Implicitly print ``` Importing `math.log` from Python costs 11 bytes: ``` I▷math.logN ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEw7UsMScssUhDKTexJEMvJz9dSUfBM6@gtMSvNDcptUhDEwis//83NPivW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Python](https://www.python.org), 84 bytes ``` def f(x): g=i=999;s=1|-(x>1);x=x**s-1 while i:g=i+x*(i*i/g-(i:=i-1)) return x*s/g ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZFBktMwEEWLZXQKLe0Qa9QttaTOlDnBLNlTAexEVU7ssj1gqjgDF2CTDdwJTkN7khWzcEn6v_Vft_zz9_BtPvWX6_XX89xW6c_7z02r22Ip90of61wz8-NUw_eqWN5B-bjUy3Y7VaD011PuGp33UvR22RZ5mx-OVZH3da6gLJUem_l5vOhlOz0c79lzO_ZnfT7MJ53PQz_OOk-fun5qlGr7UT_pfNH90FwKu9Lzrte1VA9F8-XQ7Z7MNHR5LtbsYcyXuZCCXVvkcndPKe7Hw8fpw9x3NTRVKMsb-_r3zQ9rQG8qNM4iJbKMzN56ImUNkjhgXArI3gUA4MQ2iLMa1gR24CMkSySXyIkRbw6mGBLaiJ4gJsvi8IsBllywBBQoJgyYFBirN9ZY2bh1I6ILHoP3IXoGweEqv2KhkROm9fPE0rHeSJRyBjwQYyBHiSO7VQbvI3JKlLwMZ1H5VX0110tEsKJFBvTOg7VOxVUVpPQCnoXvwKEC6fr_R5MEwTnD0SIDgyNCQFTkDXECkjQZwqMUeWmVeV2JaeWTBSeM23_5Bw) #### Thanks @xnor for -1. ### How? Evaluates a continued fraction <https://en.wikipedia.org/wiki/Euler%27s_continued_fraction_formula> [Answer] # Python, 85 Bytes ``` f=lambda x:sum(1/y for y in range(9**7,round(x*9**7)+1))if x>1else-f(1/x)if x-1else 0 ``` * Thanks to TheThonnu for their 86 byte suggestion, probably borrowing the `9**7` idea from Command Master. * Thanks to c-- for showing it is 1 byte shorter to not have a k variable. --- Uses numerical integration. [Try It Online! (I've used the Pypy implementation in the TIO website since it's apparently 4x faster)](https://tio.run/##HUzbasMwDH3evkKPduZ4li9zVNh@ZOwho3EXaJ2QtmB/fSYHpIN0bmt9/C3Z9Wtd676nz@t4@z2PUE73503ge4W0bFBhzrCN@TIJ6rqotuWZz6J07ZFvKOWcoHzhdL1PfeJUOYj@IMDsraK0im@jUYHRNjQ8IB5IClhA7RRYHh1xsENbH8h4tjiNHgPZj@DCQJHY6BWwEDlm@GIieB1owGCMc@i9ZYro5/T6sm5zfogkipT7Pw) [Answer] # [JavaScript (Node.js)](https://nodejs.org), 18 bytes ``` x=>1e9*(x**1e-9-1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1s4w1VJLo0JLyzBV11LXUPO/NVdyfl5xfk6qXk5@ukaahoWmjm9iSQaYZ6Gp@R8A "JavaScript (Node.js) – Try It Online") Port of Excel answer [Answer] # [C (gcc)](https://gcc.gnu.org/), 44 bytes ``` float f(float x){return(pow(x,1e-9)-1)*1e9;} ``` [Try it online!](https://tio.run/##bVPbjpswEH3fr7Ai7QqyQD22x3iazfah6lc0eaCs2UbNkgioFjXKr5eOIYnStAgfw/FcD0OZvpblMFTbXdGJKpr2Pj40vvvZ1NF@9x71CfiU4hTiOXhaHIdN3Ym3YlNHsTjcCb4mr863Xft1LZbiIDNIhMwUBhwhH5ESAZkMoBOh@M5ycMqFZZCkYSOdgQEkZVGjo5zY0GSJQF45L5DhRQcwGZIDlFJrMEaxIVF2XFxV5Pu9Lzv/MhWVqkxLhQ4lKSLD2ThdyqU4q8hoCwDkSFomZWaJg3JxEpFtUY@kcrl1SubKIORO0kiCRG0lAlrMnbLKhUbl2L5V2hpljbG5IQiR/xf4pAj3kCtyDp3h4qQaVfqnNMisZCYnUEYb4OYDx4E4PhjiqBr0qOzfvdqgLOVSERBoRAVKBWVlACQMCVCC5kAnCctd3Xai/F40c0Zf/vDNpONs1X9Rq54@88JZIq7f9ez8AXaNiMKgbOoX37ObXJwen0S7@eV3VXT@OvGHEzG/MAvx@Dhanyfsaso41jRpo8F6cXPe8nkVdfEt75m/zMOtayh0X7Sjb/GtjbxIRRtzqVH3vATx8MBpn5Y8fOKT4J/Bio9h01dJ9g3HqKLZfSXSZ8F4365qFqdLRJtc9As51iev44jTf8bq3B2H32W1LV7bId2@Den7Hw "C (gcc) – Try It Online") *Port of [Jos Woolley](https://codegolf.stackexchange.com/users/116680/jos-woolley)'s [Excel answer](https://codegolf.stackexchange.com/a/262714/9481)* [Answer] # BQN, 2 bytes ``` ⋆⁼­⁡​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­ ⁼ # ‎⁡The inverse of ⋆ # ‎⁢the function e^x 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` yeah ok this might be cheating :) can mark as community wiki or delete and move to the builtin answer if enough people complain [Answer] # Swift 5.6, no imports, 146 bytes Swift has no `log` or `pow` builtins -- you have to import those from C! Here's a Swift answer that doesn't use any imports: ``` let i:(Float,Int)->_={x,y in(0..<y).reduce(1){n,_ in n*x}} func l(x:Float)->Float{2*(0...126).reduce(0){$0+i((x-1)/(x+1),2*$1+1)/(.init($1)*2+1)}} ``` [SwiftFiddle link](https://swiftfiddle.com/lpegraykyzejjagr4nxe2nvsiu) with test cases. Uses [this method](https://math.stackexchange.com/a/61283) from the linked Math.SE post. 126 is just the magic number needed to get the requisite precision for \$\ln\left(99\right)\$. This works in later versions of Swift, but I'm pinning it to 5.6 in case exponentiation is added in the future. `i` is a handwritten exponentiation function where the exponent must be a positive integer (called `Int` instead of `UInt` to save bytes). [Answer] # Python, 130 bytes ``` def f(x): x,m=(1/x,-1)if x<1 else(x,1) while x>1.03:x,m=x**.5,m<<1 r=x**.5 return m*90*(x-1)/(7*x+32*((x+1)*r+2*x)**.5+12*r+7) ``` This algorithm is derived from Carlson's version of Borchard's algorithm, which uses a modified arithmetic-geometric mean. Carlson's version adds Richardson acceleration. See Carlson, B. C. “An Algorithm for Computing Logarithms and Arctangents.” *Mathematics of Computation*, Apr 1972 <https://doi.org/10.2307/2005182> My version is essentially two loops of Carlson's, with range reduction. It only uses elementary operations and square roots. Its absolute error is under 5e-14. Here are some error plots: [![error plot, 0.1 - 1](https://i.stack.imgur.com/fJcs9.png)](https://i.stack.imgur.com/fJcs9.png) [![error plot 1 - 100](https://i.stack.imgur.com/tGVSr.png)](https://i.stack.imgur.com/tGVSr.png) [Try it in SageMathCell](https://sagecell.sagemath.org/?z=eJxVT0FqwzAQvBv8h4UeLMmKYzmU0GAXSg859dYPGLKKBZJlVgrW8yvR5tDTzuzMDrMv8DmTDX5tAnxcv8D6ewdDHn4LHVy91XiTsJu4ABJ5gs36WFeavAM3561xm6dY7uqqrm6oQbPEL3UFSbqJqWOSB8WNhjQqQBuQJal4lvfFWIT0rrr-dCneJET3Kt04qqzSLy0I44NWcOKtFyzlrCM7i9SeBsFYahUX1A4i8eJu1ZDZmT-bRAyxlHlmlGZwKF0zqKvyCiseCUxJUH3PeRcWv7M7mZs1K4bpmx4oQdPs8A9HEy1Ozb-shv8AuUVd5w==&lang=python) [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 12 bytes `$x'¿Fäeäx-\-` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=JHgnv0bkZeR4LVwt&in=Mg==) [check all test-cases](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=JHgnv0bkZeR4LVwtCgqr5KMiCm1heCBlcnJvcjogIqUtYVJ3q6M=&in=KDEvMTAgMS80IDEvMiAzLzQgOS8xMCAxIDEzLzEwIDIgMjcxODI4MTgyODQ1OTA0NS8xMDAwMDAwMDAwMDAwMDAwIDMxNDE1OTI2NTM1ODk3OTMvMTAwMDAwMDAwMDAwMDAwMCA0IDUgNyAxMCA1MyA1NDU5ODE1MDAzMzE0NDIzLzEwMDAwMDAwMDAwMDAwMCA5OSkKCjAKCigKLTIzMDI1ODUwOTI5OTQwNDU1LzEwMDAwMDAwMDAwMDAwMDAwCiAtMTM4NjI5NDM2MTExOTg5MDYvMTAwMDAwMDAwMDAwMDAwMDAKIC0wNjkzMTQ3MTgwNTU5OTQ1My8xMDAwMDAwMDAwMDAwMDAwMAogLTAyODc2ODIwNzI0NTE3ODA5LzEwMDAwMDAwMDAwMDAwMDAwCiAtMDEwNTM2MDUxNTY1NzgyNjI4LzEwMDAwMDAwMDAwMDAwMDAwMAogMAogMDI2MjM2NDI2NDQ2NzQ5MTA2LzEwMDAwMDAwMDAwMDAwMDAwMAogMDY5MzE0NzE4MDU1OTk0NTMvMTAwMDAwMDAwMDAwMDAwMDAKMQoxMTQ0NzI5ODg1ODQ5NDAwMi8xMDAwMDAwMDAwMDAwMDAwMAogMTM4NjI5NDM2MTExOTg5MDYvMTAwMDAwMDAwMDAwMDAwMDAKIDE2MDk0Mzc5MTI0MzQxMDAzLzEwMDAwMDAwMDAwMDAwMDAwCiAxOTQ1OTEwMTQ5MDU1MzEzMi8xMDAwMDAwMDAwMDAwMDAwMAogMjMwMjU4NTA5Mjk5NDA0Ni8xMDAwMDAwMDAwMDAwMDAwCiAzOTcwMjkxOTEzNTUyMTIyLzEwMDAwMDAwMDAwMDAwMDAKIDQKNDU5NTExOTg1MDEzNDU5LzEwMDAwMDAwMDAwMDAwMAop) ## Explanation Uses Newtons method starting at `0` to approximate the result. ``` $x ; store the input in x '¿F ; repeat 191 times (enough for all test-cases) äeäx-\- ; replace top stack value y starting at 0 with ; y-(e^y-x)/e^y (step in Newton method) ; implicitly print result ``` # Itr, [17 bytes](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=JHh4PjMqaSe_RuRl5HgtXC0=&in=LTE=) `$xx>3*i'¿Fäeäx-\-` Also works for negative (and complex) inputs `x>3*i` sets the initial value to `3i` if the real part of the input is negative ]
[Question] [ The challenge is to remove vowels (a, e, i, o, u) from string from STDIN (yes, I know, simple). You can expect that your program will be not ran with any arguments in `argv`. Example: ``` This program will remove VOWELS. So we can now speak without them. ``` Is changed to: ``` Ths prgrm wll rmv VWLS. S w cn nw spk wtht thm. ``` There is a catch. The winning entry is decided basing on number of different bytes. For example `a ab` has three different bytes (`a`, `b` and space). If two or more entries will have this same ammount of different bytes, then fallback is done on number of bytes for those entries. [Answer] ## Brainfuck, 8 distinct (2121 total) ``` >,+[-<>>>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>[-]+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>>[-]++<[-<+>>>>->>>->>>->>>->>>->>>->>>->>>->>>->>>-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<>]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>[<<<]+>-[<-<.>>-]<[<<<]<[-]>,+] ``` The distict characters: [`<>+-[],.`](http://en.wikipedia.org/wiki/Brainfuck#Commands). Works with interpreters that use `-1` for `EOF`. > > $ echo ' > > This program will remove VOWELS. > > So we can now speak without them. > > ' | bf vowel-rm.bf > > > > Ths prgrm wll rmv VWLS. > > S w cn nw spk wtht thm. > > > > > > [Answer] ## Whitespace, 3 points (218 chars) You knew it was coming. ``` ↲___↲____↲⇥↲⇥_____↲___⇥_____⇥↲___⇥___⇥_⇥↲___⇥__⇥__⇥↲___⇥__⇥⇥⇥⇥↲___⇥_⇥_⇥_⇥ ↲___⇥⇥____⇥↲___⇥⇥__⇥_⇥↲___⇥⇥_⇥__⇥↲___⇥⇥_⇥⇥⇥⇥↲___⇥⇥⇥_⇥_⇥↲↲___⇥↲_↲_↲⇥_⇥↲___ _↲⇥⇥⇥⇥__⇥↲⇥_↲↲_↲_⇥↲↲__↲↲⇥__↲↲_↲↲↲__⇥↲____↲⇥⇥⇥_↲_↲⇥___↲⇥↲__↲_↲_↲↲____↲↲↲↲ ``` (\_ = space, ⇥ = tab, ↲ = newline) Here's the script encoded in base64: ``` CiAgIAogICAgCgkKCSAgICAgCiAgIAkgICAgIAkKICAgCSAgIAkgCQogICAJICAJICAJCiAgIAkg IAkJCQkKICAgCSAJIAkgCQogICAJCSAgICAJCiAgIAkJICAJIAkKICAgCQkgCSAgCQogICAJCSAJ CQkJCiAgIAkJCSAJIAkKCiAgIAkKIAogCgkgCQogICAgCgkJCQkgIAkKCSAKCiAKIAkKCiAgCgoJ ICAKCiAKCgogIAkKICAgIAoJCQkgCiAKCSAgIAoJCiAgCiAKIAoKICAgIAoKCgo= ``` And here's the program written in visible assembler-like form: ``` ioloop: charin 0 push 0, 'A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u' ckloop: dup jz out get 0 sub jz skip jump ckloop skip: jz ioloop jump skip out: get 0 dup jz done charout jump ioloop done: exit ``` [Answer] ### SED (10 distinct bytes, 13 total) ``` s/[aeIou]//gI ``` Sample usage: ``` echo The quick brown fox jumps over the lazy dOg. | sed -e s/[aeIou]//gI ``` outputs: ``` Th qck brwn fx jmps vr th lzy dg. ``` [Answer] # Perl: 8 or 10 distinct characters ## `s///` solution: 10 distinct, 13 total The (purported; see below) sed technique always works in perl, too, and yields the name number of distinct characters (10): ``` s/[aeiou]//gi ``` For example: ``` $ echo 'This program will remove VOWELS. So we can speak without them.' | perl -ple 's/[aeiou]//gi' Ths prgrm wll rmv VWLS. S w cn spk wtht thm. ``` That’s 10 distinct characters, as this proves: ``` $ echo 's/[aeiou]//gi' | perl -nle '@s{split//}=(); print scalar keys %s' 10 ``` The problem with the sed solution is that its `/i` is *not* part of POSIX sed, and thus is not portable: ``` $ echo 'This program will remove VOWELS. So we can speak without them.' | sed -e 's/[aeiou]//gi' sed: 1: "s/[aeiou]//gi": bad flag in substitute command: 'i' ``` That’s running on an OpenBSD system. In contrast, because `/i` is indeed always part of standard perl, you ***can*** count on its always being there. Unlike sed. If you want to include “y” in the list of vowels, it is of course one greater if you use the same technique: ``` $ echo 'This nifty program remove any VOWELS. So we easily can speak without them.' | perl -ple 's/[aeiouy]//gi' Ths nft prgrm rmv n VWLS. S w sl cn spk wtht thm. $ echo 's/[aeiouy]//gi' | perl -nle '@s{split//}=(); print scalar keys %s' 11 ``` And it is now 14 total characters. ## `tr[][]` solution: 8 distinct 10 total You could also use `tr///` to remove anything it matches. Perl can even use sed’s `y///` alias for `tr`: ``` y/aeiou//d ``` which is now 8 distinct characters, but does’t work on uppercase. You end up having to add 5 more characters to cope with the casemaps: ``` $ echo 'y/aeiouAEIOU//d' | perl -nle '@s{split//}=(); print scalar keys %s' 13 ``` and of course that’s now 15 total. However, adding “y” to the mix as a vowel doesn’t up the number of distinct characters as it did with the `s///` version: ``` $ echo 'This nifty program remove any VOWELS. So we easily can speak without them.' | perl -ple 'y/aeiouy//d' Ths nft prgrm rmv n VOWELS. S w sl cn spk wtht thm. ``` So that’s still just the original 8 distinct out of 11 total: ``` $ echo 'y/aeiouy//d' | perl -nle '@s{split//}=(); print scalar keys %s' 8 ``` --- # *EDIT*: Accounting for Diacritics And what about inputs like `Renée’s naïveté`? The correct output should of course be `Rn’s nvt`. Here’s how to do that, using v5.14’s `/r` flag for `s///`: ``` $ echo 'Renée’s naïveté' | perl5.14.0 -CS -MUnicode::Normalize -nle 'print NFD($_)=~s/[aeiou]\pM*//rgi' Rn’s nvt ``` That’s 27 distinct characters: ``` $ echo 'print NFD($_) =~ s/[aeiou]\pM*//rgi' | perl -nle '@s{split//}=(); print scalar keys %s' 27 ``` You can trim that to 26 if you can guarantee that you’re running at least v5.10 by swapping out the `print` for a `say`: ``` $ echo 'Renée’s naïveté' | perl -Mv5.14 -CS -MUnicode::Normalize -nlE 'say NFD($_) =~ s/[aeiou]\pM*//rgi' Rn’s nvt $ echo 'say NFD($_) =~ s/[aeiou]\pM*//rgi' | perl -nle '@s{split//}=(); print scalar keys %s' 26 ``` And you can get it down to 22 if you don’t mind moving the diacritics instead of removing them: ``` $ echo 'Renée’s naïveté' | perl -Mv5.14 -CS -MUnicode::Normalize -nlE 'say NFD($_) =~ s/[aeiou]//rgi' Rń’s n̈vt́ ``` Which is ... *interesting* to look at, to say the least. :) Here’s its distinct-count: ``` $ echo 'say NFD($_) =~ s/[aeiou]//rgi' | perl -nle '@s{split//}=(); print scalar keys %s' 22 ``` ## *Good luck getting any other language to properly deal with diacritics using fewer characters than this!* [Answer] ## C, 22 20 19 distinct characters. Letters needed for `main`, `putchar`, `getchar` = 12. Punctuation - `(){};` = 5. Operators - `&-`= 2. ``` i;ii; p(c){ (c&ii-(-ii-ii))-(i-ii-ii-ii-ii-ii-ii)&& (c&ii-(-ii-ii))-(i-ii-ii-ii-ii-ii-ii-i-i-i-i)&& (c&ii-(-ii-ii))-(i-ii-ii-ii-ii-ii-ii-ii-(-i-i-i))&& (c&ii-(-ii-ii))-(-ii-ii-ii-ii-ii-ii-ii-i-i)&& (c&ii-(-ii-ii))-(i-ii-ii-ii-ii-ii-ii-ii-ii-(-i-i))&& putchar(c); } a(c){c-i&&n(p(c));} n(c){a(getchar());} main(){ n(i---ii---ii---ii---ii---ii---ii---ii---ii---ii---ii---ii---i); } ``` `main` invokes undefined behavior (too much `--` in one line). I don't care about the expression value, and it does decrement `ii` the right number of times. Can be fixed easily by separating the decrements with `;`. But it's so much nicer as it is. Old version, 20 characters: Actually 21, because I didn't notice that some spaces are significant and must be counted, but they can be replaced with parentheses easily. ``` ii;iii;c;a; main(i){ i=c;i-=--c; ii=-i-i-i-i-i-i-i-i-i-i-i; iii=i-ii-ii-ii-ii-ii-ii-ii-ii-ii-ii; -(c=a=getchar())-i&&main( (c&=ii- -ii- -ii)- - a&& -ii-ii-ii-ii-ii-ii- i- c&& -ii-ii-ii-ii-ii-ii- -i- -i- -i- c&& iii- -ii- -ii- -ii- i-i-i-i-i- c&& iii- -ii- -ii- -ii- -i- c&& iii- -ii- -ii- i-i-i-i- c&& putchar(a)); } ``` Can perhaps be improved further, by compiling with `gcc -nostartfiles`, and renaming `main` to `_start`. `min` are removed (after some variable renaming), `_s` added. But then I need to use `exit()`, which adds 3 chars. Instead of `_start`, any name can be used, and it works in Linux. This allows going down to 18 chars, but is very non-standard. [Answer] ## GolfScript (7 distinct bytes, 103 total) Sufficiently much of an improvement over [w0lf](https://codegolf.stackexchange.com/users/3527/w0lf)'s [answer](https://codegolf.stackexchange.com/a/6038/194) that I think it qualifies as a separate one: ``` [9-99))--9+99))99))))))99)9+))9-9)99--)99-9+9--9+9-))99-9+9)))--9+99-9+-9+9-)99-9+9)))-)99)9-9-)))]''+- ``` ### 12 distinct bytes, 13 total: ``` 'aeiouAEIOU'- ``` [Answer] ## Binary Whitespace (2 distinct chars, 324 total chars) `TTSSSTTSSSSTTTSTTTSSSSSSTTSSSTSSSSSSTSTTSSSTSSSSTSSTSTTSSSTSSSTSSSTSTTSSSTSSSTSTSTSTSTTSSSTSSTSSTSSTSTTSSSTSTSSSSSTSTTSSSTSTSSSTSSTSTTSSSTSTSSTSSSTSTTSSSTSTSSTSTSTSTSTTSSSTSTSTSSTSSTSTTTTSSSTSTTSTTSTTTSSTSTTSSSSTTTSTSTSTSSSTSTTTSSTTTTSTTSTSTTTTSSTTTTTSSSTTTTSTTTTTTSSTSTTSSSSTTTSTSTSSTTSTTTSSSSTTTSTTSSTTSTTSTTTTSSSSTTTTTTTT` where S,T,L denotes Space,Tab,Linefeed, respectively. (Shamelessly obtained by converting the [Whitespace answer by "breadbox"](https://codegolf.stackexchange.com/a/6045/3440) into Binary Whitespace -- this posting should probably be a comment to his answer, but it's too long.) Binary Whitespace is [Whitespace](https://web.archive.org/web/20150623025348/http://compsoc.dur.ac.uk/whitespace/) converted to a prefix-code language by everywhere using TS instead of T and using TT instead of L; e.g. the BWS instruction to push -5 onto the stack is SSTSTSSTSTT instead of SSTTSTL, etc. Link: A both-ways [translator for an arbitrary 3-symbol language and its binary prefix-code versions](https://sites.google.com/site/res0001/whitespace/programs/trans32.py) [[archive](https://github.com/wspace/res0001-trans32)]. NB: It would be straightforward to design a true *bitwise* interpreter for Binary Whitespace programs regarded as *bit*-sequences, rather than char-sequences (e.g. using 0,1 bit-values instead of S,T characters, respectively). The above would then be a 324-*bit* program requiring 41 bytes of storage. [Answer] ### Golfscript (8 distinct bytes, 837 total) ``` [9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) 9))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))]''+- ``` Explanation: 1. The program creates the following array of integer values: `[97 101 105 111 117 65 69 73 79 85]` (corresponding to the ASCII codes of `a,e,i,o,u,A,E,I,O,U`). Each number is represented by pushing on stack the value `9`, followed by the needed number of `)` (increment operators). For example, the number `67` is obtained using `9` and 58 `)`s 2. Using `''+`, the array is converted into the string `"a,e,i,o,u,A,E,I,O,U"`, representing all vowels 3. The subtraction sign ('-') is then used to subtract all vowels from the source string The 8 unique characters that were used: `[`,`]`,`9`,`)`,`+`,`-`,`'` and `(space)` [Answer] ## Unreadable (2 distinct, 2666 total) Since everyone is posting Turing tarpits, I thought I'd use this one. It's not a very well-known one but it does exist ( <http://esolangs.org/wiki/Unreadable> ) and it has only two characters. ``` '""""'""""'""""'""""""'"""'""'""'""'""'""'""'""'""'""'"""'""""'"""""'"""""""'"""'""""'""" "'""""'""""""'"""'""""""""'"""""""'"""'""""""'""'"""'""'""'""'""'""'""'"""""""'""'"""'""" "'""""""'""'""'"""'""'""'""'""'""'""'""'"""""""'""'""'"""'""""""'""'""'""'"""'""'""'""'"" '""'""'""'""'"""""""'""'""'""'"""'""""'""""'""""""'""'""'""'""'"""'""'""'""'""'""'""'""'" "'""'"""""""'""'""'""'""'"""'""""""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'"""" """'""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'"" '"""""""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'"""'""'""'""'""'""'""'""'""'"" '""'""'""'"""""""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'""'""'""'"""'""""" """'""""""""'"""""""'""'""'""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'""'""'""'""'"""' ""'""'"""""""'""'""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'""'""'""'"""'""""""""'"""" """"'""""""""'""""""""'"""""""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'"""'""'" "'"""""""'""'""'""'""'""'"""'""""'""""'""""""'""'""'""'""'""'""'"""'""""""""'""""""""'""" """"'""'""'""'""'""'"""'""""'""""""'""'""'""'""'""'"""'""""""""'""""""""'""""""""'""""""" "'"""""""'""'""'""'""'"""'""""""'""'""'""'""'"""'"""""""'""'""'""'"""'""""'""""'""""""'"" '""'""'"""'""'""'""'""'"""""""'""'""'"""'""""""'""'"""'""'""'""'""'""'""'"""""""'""'"""'" """'""""""'"""'""'""""""""""'"""""'"""""""'"""'""""'""""'""""""'""'""'""'""'""'""'""'""'" "'""'""'"""'""'""'""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'""'""'""'""'""' """'""""""""'"""'""""'"""""""""'""""""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'"""'""" ""'""""""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'"""'""""'""""'""""""'""'""'""'""'""' ""'""'""'""'""'""'""'""'"""'"""""""'"""'""""""'""'""'""'""'""'""'""'""'""'""'""'""'""'""' """'"""""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'"""'""""'"""""""""'"""""""'""'""'""' ""'""'""'""'""'""'""'""'""'""'""'"""'"""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'""'"" '""'"""'""""'""""""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'""""""""'"""""""'""'""' ""'""'""'""'""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'""'""'""'""'""'""'""" '""""""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'"""'""""'"""""""""'"""""""'" "'""'""'""'""'""'""'""'""'""'""'""'""'"""'""""""'""'""'""'""'""'""'""'""'""'""'""'""'"""' ""'"""""""'""'""'""'""'""'""'""'""'""'""'""'""'"""'"""'""""""'""'""'""'""'""'""'""'""'""' ""'""'"""'""""""""'"""""""'""'""'""'""'""'""'""'""'""'""'""'"""'"""'""""'"""""""""'"""""" ""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'""' ""'""'""'""'""'""'""'""'""'""'"""'"'""""""""'"""""""'"""'"""'""""""'"""'""'"""""""""" ``` [Answer] ## VBA - 25 22 distinct bytes (120 total) I know this won't win with so many different bytes, but here it is in VBA. `(space)`,`(newline)`,`"`,`,`,`(`,`)`,`=`,`a`,`b`,`c`,`d`,`e`,`E`,`I`,`l`,`n`,`O`,`p`,`R`,`S`,`u`,`1` ``` Sub S(u) u=Replace(Replace(Replace(Replace(Replace(u,"u","",,,1),"O","",,,1),"I","",,,1),"e","",,,1),"a","",,,1) End Sub ``` \*`,,,1` allows for ignoring case. (`1` represents the constant `vbTextCompare`) [Answer] # JavaScript, 6 (7325 total) ``` [][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()((!![]+[])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[!+[]+!+[]]+(!![]+[])[+!+[]]+(+(+!+[]+[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+[!+[]+!+[]]+[+[]])+[])[+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[+!+[]+[!+[]+!+[]+!+[]]]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[+[]]+(![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+[]]+([][(!![]+[])[!+[]+!+[]+!+[]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()+[])[!+[]+!+[]+[!+[]+!+[]]]+(![]+[+[]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+(![]+[+[]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[[]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]([[]])+[]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[!+[]+!+[]]]+([+[]]+![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[!+[]+!+[]+[+[]]]) ``` This uses [JSFuck](http://www.jsfuck.com/) to turn `r=>r.replace(/[aeiou]/g,"")` into six unique characters. [Answer] # Scala, 25 total bytes, 15 distinct bytes ``` _ filterNot "aeiou".toSet ``` [Try it in Scastie!](https://scastie.scala-lang.org/tOczovYFRxmzClRcmGcalA) [Answer] # [Itr](https://github.com/bsoelch/OneChar.js/blob/main/ItrLang.md), 4 distinct characters, 5197 bytes *newlines for readability* ``` ( (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L (()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())L )© ``` [online interpreter](https://bsoelch.github.io/OneChar.js/?lang=Itr&src=KCgoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkpTCgoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKC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koKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKCkoKSgpKUwpqQ==&in=IlRoaXMgcHJvZ3JhbSB3aWxsIHJlbW92ZSBWT1dFTFMuClNvIHdlIGNhbiBub3cgc3BlYWsgd2l0aG91dCB0aGVtLiI=) ## Explanation It is possible to execute arbitrary Itr code using only `()L©`: `(()...())` creates an array of empty arrays `L` gets the length of that array `©` interprets the (flattened) array as a sequence of characters and executes that sequence The code that is encoded by this program is `äµ»»AEIOUaeiou«=S¬«×`: ``` ä ; duplicate the (implicit) input µ» « ; map over all characters in the input »AEIOUaeiou«=S ; is the character in the string "AEIOUaeiou" ¬ ; negated × ; pick the elements that have a one in the second array ``` [Answer] ## Python 3.x, 19 distinct chars, 62 total ``` print(''.join(x for x in input() if x.lower() not in 'aeiou')) ``` [Answer] ## J, 21 characters (18 distinct) ``` 'AEIOUaeiou'-.~1!:1[1 ``` [Answer] # K, 29. (18 distinct bytes) ``` {i@&~(i:0:0)in(_i),i:"AEIOU"} ``` distinct bytes: {@&~(:0)in\_,"AEIOU} ``` k){i@&~(i:0:0)in(_i),i:"AEIOU"}` Hello WoOOrld "Hll Wrld" ``` [Answer] **ASM - 6 distinct characters 520 source characters** (MsDOS .com) Assembled using A86 ``` db 10110100xb db 00000110xb db 10110010xb db 11111111xb db 11001101xb db 00100001xb db 01110101xb db 00000001xb db 11000011xb db 10001010xb db 11010000xb db 10111110xb db 00011101xb db 00000001xb db 10111001xb db 00001010xb db 00000000xb db 01000110xb db 00101010xb db 00000100xb db 01110100xb db 11101010xb db 11100010xb db 11111001xb db 10110100xb db 00000110xb db 11001101xb db 00100001xb db 11101011xb db 11100010xb db 01000001xb db 00000100xb db 00000100xb db 00000110xb db 00000110xb db 00001100xb db 00000100xb db 00000100xb db 00000110xb db 00000110xb ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 16 bytes, 14 distinct **Solution:** ``` ^[;v,_v:"AEIOU"] ``` [Try it online!](https://tio.run/##y9bNz/7/Py7aukwnvsxKydHV0z9UKVYpJCOzWKGgKD@9KDFXoTwzJ0ehKDU3vyxVIcw/3NUnWOn/fwA "K (oK) – Try It Online") **Explanation:** Using except (`^`) to filter out the vowels. ``` ^[;v,_v:"AEIOU"] / the solution ^[; ] / except (^) projection v:"AEIOU" / save vowels as v _ / lowercase (_), "AEIOU" => "aeiou" , / join (,) v / uppercase vowels ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 4 bytes, 4 distinct characters ``` k∨$F ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=k%E2%88%A8%24F&inputs=This%20program%20will%20remove%20VOWELS.%0ASo%20we%20can%20now%20speak%20without%20them.&header=&footer=) Only works with single-line strings. Explanation: ``` # Implicit input k∨ # Constant "aeiouAEIOU" $ # Swap top two values F # Remove from second string any characters in first string # Implicit output ``` [Answer] # Unary, ~3.081e1915 bytes, 1 distinct character Specifically, [this](https://tio.run/##HZVHlhtJDESvBCBhjyOtZj/3f9SPUktsUlkJE45///z/3@/3bD1qMtcn5vnUWURdXfY@776XrznvvLOOmHnVs/bOo3mMd5M31f48wi85uJ2J63zLwTObmtu8vDCaUSfMeq6eHq/YRw@rNb/m5NzMffnok@71us3Kh1pB9bW59@qte4/vo3CzBY2YuIx/@2ap7ZGUnXjba8yyUY/We2@acavt0W4CALKDWh1jZekZkXMsXsvYM9fHoq9fr1t9e8XktmVbF5MNk9MWZGwplTv8bDnAWdMjfBs0GScH7IBmOlj6bCO2kvtU5j0fLllzuHvTm8DNZIKHY0EERS@y0tqzWXm3wwsmfNztEjCBrPri9ri9uckFE5Wgmc2kx1T3QK6LuYa6QDvCADaWQ2@wZUHoSoBkF@iuiO4cgXOqrM24EeJi@Ln1E4aQXGBw/kYNgWT0clDzgELsTkl0miEOfk56WW5BabJbgKK0dgDykt0MPsGMUQBQfWi3DWKcqLVJfiBXLJ1RxgmyQKv82keR5S8Ft3nGTuqTvr8dwZsJ7YmEhAaaanQ/PvFBB@jK6ZSGzhEgACModDwyhjG9MwF2OP5MY5/HgvbeNYXn27pY62EQJPOGWsEmQAJ6iJn3JZ1D24tG0oYTgRWs8zEdzeGaBZAF7oBhTFMswoWskVoW5pEUPKJgtCLNMv5rsfoY7/UhPAyLaq0ScQf@oxIgJBeA2JdS3oXkgLuQ36k6CADjFSfOffFZsAErQN4rTUSLATmI7WHiBTyaCnSKbWkHUoq3sDD9yYunV7YHBwMz@oCD25MlGT9O0wECUGBg1jbNSFOISwxN5eb5EaIpfnm49JvthkZwii@gHuRJnnKswVJMiUTkEBZ4UnDBfMlK@AIEjZQohR1yHqyFMHgCp@MCrQNumxwmmMZj0YR5RII8ekGOBAEyQglpc/265CviQTCGy85PYVA03S8FiBpYEcLE3mgMpxuyihUW2sSXjPrUYqFJ0fLRkK6QQPAYDR6ZS5SZoom9yUQ4wuPATFHxGSXTY7RTasmCMhZAsxeDQzCxSs5BuuKGKGY4npA1cTvTucIOsRPe@RmJQKervMxbGc957IUk98FLH8NMuAgzDQPTDWvqq8DIMaZE7dpw9F@8SrFGRzR2kjBxfXIk@h6FMk02v28R8kH4wccXYcvzKBqTo6@USnGjLVhR3Vyx5uQbsUDGkb/enwWhMJSmXquvQQKQnivpEB/oFoSRM@C6WGR/RAmeC/FkL2lAUiFtVnIjgNBF8IWFMeEA/khPrHeUQBCURGeswUvs/H7/AA) is how many `0`s are required. Simply a Unary port of the [brainfuck answer by @ceased to turn clockwis](https://codegolf.stackexchange.com/a/6033/101522). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ḟØc ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmHZyT///8/JCOzWKGgKD@9KDFXoTwzJ0ehKDU3vyxVIcw/3NUnWI8rOF@hPFUhOTFPIS@/XKG4IDUxG6iuJCO/tEShJCM1Vw8A "Jelly – Try It Online") [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 17 bytes, 13 distinct ``` ((⌊,⊢)'AEIOU')~⍨⊢ (⌊,⊢)'AEIOU' ⍝ concatenate with lower case version of string ~⍨⊢ ⍝ remove vowels ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/P@1R2wQNjUc9XTqPuhZpqju6evqHqmvWPepdAeQDpRXU3fLznRKL1AE "APL (Dyalog Extended) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 7 distinct bytes, ~~2091~~ 2082 bytes ``` c="%c%%c%%%%c%%%%%%%%c" ex=c==c ee=c=="" exec"e=%x%%x"%ex%ex exec"e%%%%%%%%=%x%%x%%%%x"%ee%ex%ee exec"ee=%x%%x"%e%ee exec"ee%%%%=%x%%x"%ex%e exec"e=%x%%x"%ee%e exec"ec=ex%cex"%e exec"xe=ec%cec"%e exec"xx=xe%cxe"%e exec"xc=xx%cxx"%e exec"ce=xc%cxc"%e exec"cc=ce%cce"%e exec"xee=ce%cec"%e exec"cee=ce%cxx"%e exec"exe=ce%cex%%cxx"%e%e exec"xxe=ce%cec%%cxe%%%%cxx"%e%e%e exec"cxe=ce%cec%%cxx%%%%cxc"%e%e%e exec"ece=cc%cex"%e exec"xce=cc%cex%%cxe"%e%e exec"cce=cc%cex%%cxx"%e%e exec"eex=cc%cex%%cec%%%%cxe%%%%%%%%cxx"%e%e%e%e exec"xex=cc%cex%%cxe%%%%cxc"%e%e%e exec"cex=cc%cex%%cec%%%%cxx%%%%%%%%cxc"%e%e%e%e exec"exx=cc%cex%%cxe%%%%cxx%%%%%%%%cxc"%e%e%e%e exec"xxx=cc%cex%%cec%%%%cxe%%%%%%%%cxx%%%%%%%%%%%%%%%%cxc"%e%e%e%e%e exec"cxx=cc%cex%%cce"%e%e exec"ecx=cc%cex%%cec%%%%cce"%e%e%e exec"xcx=cc%cex%%cxe%%%%cce"%e%e%e exec"ccx=cc%cec%%cxe%%%%cce"%e%e%e exec"eec=cc%cxx%%cce"%e%e exec"xec=cc%cex%%cxx%%%%cce"%e%e%e exec"cec=cc%cec%%cxx%%%%cce"%e%e%e exec"exc=cc%cxe%%cxx%%%%cce"%e%e%e exec"xxc=cc%cec%%cxe%%%%cxx%%%%%%%%cce"%e%e%e%e exec"cxc=cc%cex%%cec%%%%cxe%%%%%%%%cxx%%%%%%%%%%%%%%%%cce"%e%e%e%e%e exec"ecc=cc%cxc%%cce"%e%e exec"xcc=cc%cec%%cxc%%%%cce"%e%e%e exec"ccc=cc%cex%%cec%%%%cxc%%%%%%%%cce"%e%e%e%e exec"eeee=cc%cxe%%cxc%%%%cce"%e%e%e exec"xeee=cc%cex%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e exec"ceee=cc%cec%%cxe%%%%cxc%%%%%%%%cce"%e%e%e%e exec"exee=cc%cex%%cec%%%%cxe%%%%%%%%cxc%%%%%%%%%%%%%%%%cce"%e%e%e%e%e exec"xxee=cc%cxx%%cxc%%%%cce"%e%e%e exec"""x="" """ exec"x%c=c%%xcx%%xxee%%xcx%%ecx"%e exec"x%c=c%%xee%%xee%%xxe%%cec"%e exec"x%c=c%%cxc%%xec%%xxc%%cee"%e exec"x%c=c%%ecx%%eec%%xcc%%cee"%e exec"x%c=c%%xcx%%ceee%%cxx%%exc"%e exec"x%c=c%%cee%%ecx%%exe%%exe"%e exec"x%c=c%%ccx%%cxc%%xcc%%ce"%e exec"x%c=c%%ecx%%ce%%xec%%xxc"%e exec"x%c=c%%ce%%ecx%%xxee%%xxe"%e exec"x%c=c%%ccc%%ecc%%exc%%xec"%e exec"x%c=c%%eeee%%cee%%exe%%exe"%e cx="""ecc xcc xec xxc eeee xee xee xxe cec cxc xec xxc cee cxx cex cxx ce xec xxc xee cxx xcx xec cxc xeee ece xce cce eex xex xee cxe exx ccx cxc xcc ce cxx ce xec xxc ce xcc cxx exee xxx xec xxc ecc xeee eeee cee exe exe""" exec"exec%cx"%ce ``` [Try it online!](https://tio.run/##lVXLjtswDLznK1wD/oHedehhge4pp35AMR00wQZJkATN7NenpB6W/Mh2G9iyQw6HQ4qQz@@33en49fFA6AcMfuUlvvQbKiAEbEh/9m4geoZBw6B@oOzKthKVfP7mAEYMM6YGNrYalAjnOTiaEMwPujFZxECYBdWiIA4QqwVBFqUaBQZZlGoUEGBRaKK8Yk6okU0Nky0JZVKTveoo8e6JNRbAyDeBKEEwgdCkAtOSR9OQy6xFtJ5WDH0bi4dpkzVuWNVVi1ebY00Z1ihVKTGjpFYoP8BL/5A8zH4tRe1wQ4K2V8SSPgNqo5eKZxAUCJ5CaEPrEC0kKHvydq3yFwieQqjMz6cQCQuVTetHdO0a/rP1DUVtcNaFRd1o5WC9rysK8FwxSTZdWN/OgpkO9QdtGAPwuQCqzbDSOHymcSoscWLWa@l7@Vncl/PYjrdgQJtYW@Qnany1Ia/HRoZEZ1xir9qTMyFiSrl6xb0j5whG7ojAOiJm9/7lcaGWadyZmFwItSABSgNymlUdYFW7zJFBKhUvc0QeRImRaJEkVUFOhcI3wId8I79pt/wraV81lVsGM4eVMAKMx/7LnsrP0aXsst5FWwrzr6SD7LYhsATuVAa7UuOAEhjOP6eNwYhWJlWqclFS@IL0RfZ7HCxfBp8i8PH4zsPh1N12@2tn18/uervsj7@7@/626/6c3nm4dl@6b8dfBnm9dvft5a27v5rvx/n8culu2@1f "Python 2 – Try It Online") I'm using the algorithm of [this question](https://codegolf.stackexchange.com/a/110722/103772) to translate the following code in the code above to only use `e`, `x`, `c`, `"`, `=`, `%` and newline. Make sure to follow the link to understand how the transformation works ## code before transformation: (~~57~~ 54 bytes) ``` print"".join(a[a in"aeiouAEIOU":]for a in raw_input()) ``` [Try it online!](https://tio.run/##FYyxCsIwFEV/5ZqpXRwc3ToUzJSpk4gErOZpeC8kr4Z@fYxwp3MON@0ahE@tpUysxhzfQjz4qwex8SvJNs3WLeZ8e0rGnyL7eidOmw7j2NpljVGggQr6PIr2oxcqacBX9jUWHDDxoye2oLr8QbXdLSnNGercDw "Python 2 – Try It Online") Even if the first code isn't golfed, this one is :p Thanks to dingledooper for -3 bytes on the second program [Answer] # MATL, 8 bytes (all distinct) ``` t13Y2m~) ``` [Try it on MATL Online](https://matl.io/?code=t13Y2m%7E%29&inputs=%5B%27This+program+will+remove+VOWELS.%27+10+%27So+we+can+now+speak+without+them.%27%5D&version=20.9.2) Just a straight up golf, didn't really find any trick to reuse characters to reduce unique bytecount. `13Y2` is a literal containing `aeiouAEIOU`. Take a duplica`t`e of the input string, make a logical (boolean) array indicating which letters of the input are not (`~`) `m`embers of that literal, and index (`)`) at those places, to return an array of only non-vowel characters. [Answer] # [Ruby](https://www.ruby-lang.org/), 8 distinct, 557 bytes ``` eval""<<11+11+11+1+1+1<<11+11+11+11+11+1+1+1+1+1+1+1<<"<<"<<11+11+11+1+1+1<<"<"<<11+11+11+11+1+1<<111+1+1+1<<"ea"<<11+11+11+11+11+11+11+11+11+1<<11+11+11+11+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1<<111+1+1+1+1<<111+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1+1<<11+11+11+1+1+1+1+1+1+1<<11+11+11+11+1+1+1<<11+11+11+11+11+11+11+11+1+1+1<<"ae"<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1<<111<<111+1+1+1+1+1+1<<11+11+11+11+11+11+11+11+1+1+1+1+1<<11+11+11+11+1+1+1<<11+11+11+11+11+11+11+11+11+1+1+1+1+1+1<<11+11+11+1+1+1+1+1+1+1+1<<111+11+1<<111+11+1+1+1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWt5h0U8sSc5SUbGwMDbWhCASR-QhRbbisEhih61FCFYSbhFCQmoiuAg1h1Y9buTa6HWgcAiZgQnRP4TCECHOBvk1MJeBbVPPJcjppDiPKr_AwRGGBICTVQBPPgptOIRmZxQoFRfnpRYm5CuWZOTkKRam5-WWpCmH-4a4-wXpcwfkK5akKyYl5Cnn55QrFBamJ2UB1JRn5pSUKJRmpuXoQowA) Encodes the following 30 byte (21 unique) program in the minimum distinct characters `eval"<1+` using the technique from [GB's answer to this question](https://codegolf.stackexchange.com/a/110764/52194). ``` $><<$<.read.gsub(/[aeiou]/i){} ``` [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 17 distinct, 28 bytes ``` a: {a,e,i,o,u,A,E,I,O,U}=>* ``` If we didn't have to support uppercase letters, **12 distinct, 18 bytes**: ``` a: {a,e,i,o,u}=>* ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 18 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 2.25 bytes, 2 distinct characters ``` 011110011111001000 ``` [Try it Online! (link is to bitstring)](https://vyxal.pythonanywhere.com/?v=2#WyIhIiwiIiwiMDExMTEwMDExMTExMDAxMDAwIiwiIiwid2FpdCJd) Vyncode FTW! The actual program is encoded as a bitstring. I also shaved a character off of @Aaroneous Miller's answer [Answer] # [Lua](https://www.lua.org/), 12 distinct characters, 3245 2924 bytes ``` load(('').char(#'################################################################################################################')..'r'..('').char(#'#########################################################################################################')..('').char(#'##############################################################################################################')..('').char(#'####################################################################################################################')..'(('..('').char(#'#########################################################################################################')..'o'..('').char(#'##############################################')..'r'..('').char(#'#####################################################################################################')..'ad'..('').char(#'#######################################')..('').char(#'##########################################')..'a'..('').char(#'#######################################')..('').char(#'##########################################################')..('').char(#'#######################################################################################################')..('').char(#'###################################################################################################################')..('').char(#'#####################################################################################################################')..('').char(#'##################################################################################################')..'('..('').char(#'#######################################')..('').char(#'###########################################################################################')..'a'..('').char(#'#####################################################################################################')..('').char(#'#########################################################################################################')..'o'..('').char(#'#####################################################################################################################')..('').char(#'#################################################################')..('').char(#'#####################################################################')..('').char(#'#########################################################################')..('').char(#'###############################################################################')..('').char(#'#####################################################################################')..('').char(#'#############################################################################################')..('').char(#'#######################################')..('').char(#'############################################')..('').char(#'#######################################')..('').char(#'#######################################')..')))')() ``` [Try it online!](https://tio.run/##1ZS/DoIwEId3n@ISh2uXvoWbiQNG5wYaSywcKSCPXxEWZ7C92rnJd3@@37lRh@BIV0IgSlVa7cURj4nfTFboUSmWIj50vu556V/znw1gXADSLjqfQQtZV9vQ25e/YlNTM5E3g8zkEFuGItZLwa1d1HT8qRc/OKK5jiDKTKMtKrIBSQRLavFG2J4a0yKXaEopUQoZwtXWPXSeHl43MNXOgTcNvQzcLvfTuVCHgmAyUOoWWpqg74x@zv8GS@MAgzWNegM "Lua – Try It Online") Uses the characters `#load(').chr`. Essentially, this program builds the string `print((io.read'*a':gsub('[aeiouAEIOU]','')))`, loads it as a function, and then runs it. Thanks to [xigoi](https://codegolf.stackexchange.com/users/98955/xigoi) for saving about 300 bytes. [Answer] ## PHP - 30 distinct bytes ``` <?=preg_replace('/[aeiou]/i','',fgets(STDIN)); ``` [Answer] ### bash 26 distinct, 37 total ``` c=$(cat -) echo "${c//[aeiouAEIOU]/}" ``` sorted: ``` ""$$()-///=AEIOU[]aacccceehiootu{}" scala> code.toList.distinct.length res51: Int = 26 scala> code.length res52: Int = 37 " ""$$()-///=AEIOU[]aacccceehiootu{}" scala> code.distinct.sorted res56: String = " "$()-/=AEIOU[]acehiotu{}" ``` Result (preserves linefeeds): ``` echo "This program will remove VOWELS. So we can now speak without them." | ./cg-6025-remove-vowels.sh Ths prgrm wll rmv VWLS. S w cn nw spk wtht thm. ``` For tr, it isn't clear how to count: '-d aeiouAEIOU' as 10 or 13: ``` echo "This program will remove VOWELS. So we can now speak without them." | tr -d aeiouAEIOU ``` ]
[Question] [ ## Definition of long text Long text usually **shows emphasis**, for instance, `loooooool` or `yaaaaaaaaaay`. Usually the vowel is replicated many times. In this challenge we require: * At least 3 times, which means `yaaay` and `yaaaay` are allowed, but `yay` and `yaay` are not. * Consistent, which means that shoes can turn out be `shoooeees` or `shooooeeees` but not `shoooeeees` or `shooooeees`. Of course, it seems that no one would do that, however, this is to reinforce the next law. * Undoubling, which means `beeping` turns out to be `beeepiiing` or `beeeepiiiing` but not `beeeeeepiiing` or `beeeeeeeepiiiing`. This is not the case for long text, but such makes this challenge non-trivial. * Thus, the long text **might** turn out shorter than the original text, that is, `aaaaa` can turn out to be `aaa`. ## Your challenge ### Input Your input will be a sentence, that is, you may **not** assume there are only words. We do **not** guarantee all will be English words, so look out for `theeeeeeeeese`. ### Output The long text for the input. ## Test cases **We assume you repeat 3 times**. `The fox yawns...` => `Theee fooox yaaawns...` `Everything is good!!!!!` => `Eeeveeerythiiing iiis goood!!!!!` and **NOT** `EEEveeerythiiing iiis gooooood!!!!!` `Eeny, meeny, miny, moe` => `Eeeeeeny, meeeny, miiiny, moooeee` `AAARGH` => `AaaRGH` `Weeeeeeeeheeeeeee` => `Weeeheee` **Note the treatment of capital letters**: The first letter remains capital, and the others are lowered. `eE` will be `eeeEee`, they won't be the same. "Undoubling" only happens for letters which are of the same case (like `ee` or `AA`, but not for `Ee`) **Only the letters from `a`, `e`, `i`, `o`, and `u` are vowels, case insensitive**. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 10 bytes ``` ĠƛhA[h:d⇩+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwixKDGm2hBW2g6ZOKHqSsiLCIiLCJIRWNrayJd) Nice simple answer. ## Explained ``` ĠƛhA[h:d⇩+ Ġƛ # to each group of consecutive characters: hA # is the character a vowel? [ # if so: h:d # Push the character and a string with two copies of that character ⇩+ # and add the lowercase version of that to the character. # The -d flag flattens all sublists to depth 1 and then sums the list. ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 29 bytes Now handles undoubling thanks to [@Jo King]! ``` s/((?i)[aeiou])\1*/$1\L$1$1/g ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX0PDPlMzOjE1M780VjPGUEtfxTDGR8VQxVA//f//kIxUhbT8CoXKxPK8Yj09PS7XstSiypKMzLx0hcxihfT8/BRFEOByTc2r1FHITYVQmWAyP5Ur1ZXLKTW1AKgcpDkRBfzLLyjJzM8r/q9bAAA "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes ``` ŒgµŒlṁ3fØcȯaẆḢ) ``` [Try it online!](https://tio.run/##y0rNyan8///opPRDW49Oynm4s9E47fCM5BPrEx/uanu4Y5Hm/4e7txxuf9S0JvL//5CMVIW0/AqFysTyvGI9PT0FLtey1KLKkozMvHSFzGKF9Pz8FEUQAEqk5lXqKOSmQqhMMJmfyuXo6Bjk7sEVngoFGVCaK5ErEYjyuVxduVJJA7kgQykAoUAHAQA "Jelly – Try It Online") ``` Œgµ ) For each run of consecutive equal elements: Œl Lowercase it, ṁ3 mold it to length 3, fØc remove non-vowels, ȯ and substitute the original run if that left it empty. aẆḢ Fix the capitalization: a vectorizing logical AND with Ẇ each sublist of the run, individually a because of something to do with how vectorization handles depth? Ḣ and take the head of the resulting list. ``` [Answer] # [Python](https://www.python.org), 78 bytes ``` lambda s:re.sub(r"([aeiouAEIOU])\1*",lambda m:m[1]+2*m[1].lower(),s) import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3_XISc5NSEhWKrYpS9YpLkzSKlDSiE1Mz80sdXT39Q2M1Ywy1lHSginKtcqMNY7WNtECUXk5-eWqRhqZOsSZXZm5BflGJQlEq1NTYgqLMvBKNNA0lx5wc9WKF8tScHIWSjMQShdS8FBAXBJQ0Nbng6lxT8yp1FHJTIVQmmMxHVeLo6Bjk7gEUgliyYAGEBgA) I don't read Perl unless under duress, but if would I'd have to note that this looks very similar to @Dom Hastings' answer. [Answer] # JavaScript (ES6), 63 bytes Repeats 3 times. ``` s=>s.replace(/([AEIOUaeiou])\1*/g,([c])=>c+(c+c).toLowerCase()) ``` [Try it online!](https://tio.run/##dYrRCoIwGEbve4rl1ZY16QEUJKSCIIiiC/NizF9d2H7ZTPPprcCrWOfmg/Odu@iElUY17UpjDmMRjjaMLDfQ1EICDWgaJ/vjRYDCZ8Zu60VQLmkqMxZG0qfSl4y3eMAezEZYoIyNErXFGniNJS2od66AFPgig@i15Zx7jM1@kqQDM7SV0iVRlpSI@fyLqwQ9OPQD/njl1ggOG8fxabtzHFeYqKb9NOMb "JavaScript (Node.js) – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~28~~ bytes ``` ((?i)[aeiou])\1* $1$l$1$l$1 ``` [Try it online!](https://tio.run/##K0otycxLNPz/X0PDPlMzOjE1M780VjPGUItLxVAlB4L//w/JSFVIy69QqEwszyvW09Pjci1LLaosycjMS1fILFZIz89PUQQBLtfUvEodhdxUCJUJJvNTuVJduZxSUwuAykGaE1EAAA "Retina – Try It Online") Link includes test cases. Explanation: Port of @DomHastings' Perl answer, but Retina's `$l` operator only operates on the next token, so either as here it has to be repeated for each token to be lowercased or the letters need to be grouped `$1$l$($1$1` which here happens to be the same length as the group does not need to be explicitly closed. Unfortunately Retina's repetition operator does not help here as `$12*$l$1` parses as `${12}*$($l$1)` so the best we can do is `${1}2*$l$1` which is still the same length. Edit: Saved 1 byte thanks to @DomHastings by porting his `(?i)` golf from his answer. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` γεDlžMÃĀiÙDlDJ]J ``` Uses the legacy version of 05AB1E, because [there is a bug in the new version with `Ā` (Python-style truthify builtin) on empty strings `""`, incorrectly giving a truthy result instead of falsey](https://github.com/Adriandmen/05AB1E/issues/189). [Try it online.](https://tio.run/##MzBNTDJM/f//3OZzW11yju7zPdx8pCHz8EyXHBevWK///5WUlEIyUhXS8isUKhPL84r19PS4XMtSiypLMjLz0hUyixXS8/NTFEGAyzU1r1JHITcVQmWCyfxULkdHxyB3D67wVCjIgNJcqa5A0wE) **Explanation:** ``` γ # Split the (implicit) input-string into parts of equal adjacent # characters ε # Map over each part: D # Duplicate the current part l # Lowercase the copy žM # Push the vowels constant "aeiou" à # Only keep those characters from the lowercase copy Āi # If it's non-empty (thus a part with vowels): Ù # Uniquify to a single character D # Duplicate it l # Lowercase the copy D # Duplicate that again J # Join the three characters together ] # Close the if-statement and map J # Join everything back together # (after which the result is output implicitly) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 23 bytes ``` ṁ?oS:oR2_←Iȯ€"AEIOU"a←g ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY32@cFW@UFG8Y/aJnieWP@oaY2So6unf6hSIlAg/f///9FKIRmpCmn5FQqVieV5xXp6eko6Sq5lqUWVJRmZeekKmcUK6fn5KYogAJJJzavUUchNhVCZYDI/FSjh6OgY5O4BZISnQkEGlAaK@WYWF4NQQUGmUiwA "Husk – Try It Online") ``` ṁ?oS:oR2_←Iȯ€"AEIOU"a←g g # group identical adjacent letters ṁ # and, for each group, do this and combine the results: ? # if ← # the first element a # in uppercase form ȯ€"AEIOU" # is one of "AEIOU" ← # then get the first element, _ # lowercase it, R2 # duplicate it, S:o # and add that to itself; I # otherwise leave the group unchanged ``` [Answer] # [Python](https://www.python.org), ~~82~~ ~~80~~ 79 bytes ``` lambda s,*e:''.join([c,(c+2*c.lower())*(e!=c)][(e:=c)in"AEIOUaeiou"]for c in s) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY69CsJAEIR7n2JNk7sYr7ASwSKFqFVAFAu1iOeeOdFbyY8xL2JjExB9J9_GaIKgU-wHM8My18cxT0IyxU31l_c0Ue3u098Hh_UmgNh1sGfbYkfasIV0mWx1HCn2lGHEOHcYNvuSrxYMeyW1sbzB2J8FqCm1VooikKANxLx-ezlG2iRMMWsaIig6Qx5kJhZCgMV545sOThiVm7TZgo5hS7RpvvVXQpO7cMAK-nMJfyqe502Gox9rjrXCmmVarSuKii8) First time realising that you can use the walrus operator (`:=`) in list comprehension to store the previous value of the iterable. Just needs to be initialised -1 byte thanks to @Unrelated String [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r"(%v)%1*"Ï+²v ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIoJXYpJTEqIs8rsnY&input=WwoiVGhlIGZveCB5YXducy4uLiIKIkV2ZXJ5dGhpbmcgaXMgZ29vZCEhISEhIgoiRWVueSwgbWVlbnksIG1pbnksIG1vZSIKIkFBQVJHSCIKIldlZWVlZWVlZWhlZWVlZWVlIgpdLW1S) (Includes all test cases) ``` r"(%v)%1*"Ï+²v :Implicit input of string r :Replace "(%v)%1*" :Regex /([AEIOUaeiou])\1*/g Ï :Pass the first submatch (i.e., the first character in the match) through the following function + :Append ² :The character duplicated v :And lowercased ``` [Answer] # [Factor](https://factorcode.org) + `grouping.extras math.unicode sequences.repeating`, ~~119~~ ~~111~~ ~~109~~ ~~102~~ ~~100~~ 95 bytes ``` [ [ ] group-by values [ dup "aeiouAEIOU"⊂ [ 3 cycle 1 cut >lower append ] when ] map-concat ] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RVC7TsNAEBSi81csrrElRINAQnIRhTQgARGFFaHNeROfsG-PeySxEA0lv0CTBj6Bf4GSL-Gsc5Rp5nZnNLt7H18LFI7N9vfgcHo3uR6fAxqDnYWlYa-lWua0cQYtoLUsLDyRUdSApWdPSpANL2fBKym4ImjR1fmK-kS79-wiJEfDzr03GNKELkyDiyR5SSAgva8JFryBDtfK5nmexvZoRaZzde-VYUvm6qjHTiXVHUNLkaSinpgGtSiK2_HVUDzQgHrgNHn99G6Rnf08llDCLH5BNu9ghY0Pp5ZQeQ0pkmRfjCY30_Tv_S10T0F0oiE4AeEdXDa8JgOoNakqpKxrUoFa1JlgJdDBLI75LkEbqUINglvNloBQ1FHcbiP_Aw) Unfortunately Factor's regular expressions are very limited by design so they can't be used to help much. This is still maybe quite golfable regardless. * `[ ] group-by values` Break the input into groups of contiguous equal characters. * `[ ... ] map-concat` Map each group to a sequence, all of which get concatenated together in the end. * `dup "aeiouAEIOU"⊂` Is it a group of vowels? * `[ 3 cycle 1 cut >lower append ] when` Make it length three and 'capitalize' it if so. (i.e. "aaa" -> "aaa", "AAA" -> "Aaa") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~63~~ ~~47~~ 43 bytes ``` ([AEIOUaeiou])\1* $1$1$1 rT`L`l`\1([AEIOU]) ``` ~~This can definitely be shorter..~~ It can, see [*@Neil*'s Retina answer](https://codegolf.stackexchange.com/a/247524/52210). My answer uses the older version, which didn't had builtin `$l` yet (nor `$1$1$1` to `3*$1`). ~~I again have the feeling this can be shorter..~~ And it can: -16 bytes thank to *@Neil*, and I've been able to golf it slightly more. [Try it online.](https://tio.run/##K0otycxL/P9fI9rR1dM/NDE1M780VjPGUItLxRAEuYpCEnwSchJiDKEqYjX//w/JSFVIy69QqEwszyvW09Pjci1LLaosycjMS1fILFZIz89PUQQBLtfUvEodhdxUCJUJJvNTuRwdHYPcPbjCU6EgA0pzpbqmckW6OnoAAA) **Explanation:** Get all consecutive matches of 1 or more of the same vowels, and shorten/extend them to three of these vowels: ``` ([AEIOUaeiou])\1* $1$1$1 ``` Lowercase every match of two adjacent uppercase vowels by transliterating in reverse order: ``` rT`L`l`\1([AEIOU]) ``` [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 34 bytes ``` :%s/\v([aeiouAEIOU])\1*/\1\L\1\1/g ``` [Try it online!](https://tio.run/##K/v/30q1WD@mTCM6MTUzv9TR1dM/NFYzxlBLP8YwxgeIDfXT//8PyUhVSMuvUKhMLM8r1tPT43ItSy2qLMnIzEtXyCxWSM/PT1EEAS7X1LxKHYXcVAiVCSbzU7kcHR2D3D24wlOhIANKAwA "V (vim) – Try It Online") Very similar to other regex based solutions. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~125~~ ~~121~~ 119 bytes * -2 thanks to ceilingcat Scans for vowels and coalesces duplicates, lowercasing the extra output vowels. ``` i,c;f(char*s){for(;c=*s++;){if(index("aeiou",c|32)){for(;i=c==*s;s++);for(;i<3;)putchar(c|!!i++*32);}else putchar(c);}} ``` [Try it online!](https://tio.run/##PVDPa8MgFL7nr3gRBmpsGOvROshhbOcx2GHsEIwmQqslmrYhzb@@zDRp3@F7fj@e@JSbWsppMkxyjWVTttSTQbsWcymozzJOBqOxsZW6YFQq4zrE5HX7QtaUEVLEII9Rwhdlt@Xk2IX5MiyvaWqyjMYBPqq9V/BwojBOxgY4lMbikzMVgSEBmF2g/udXzAwAfTUKtLtAX56tz/McsUV/O6m2D42xNRgPtXNVOtfDVrZncFBLMzd06u4WRfH5/nFn32qtZu2r8RxxZEBpiNDxJNJ5xyA8h07QEP9nXshjhMjyeoBjG5fSGD15EK@AGHSE3wyNl9OYjNOf1Puy9tPm/A8 "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` FS¿¬⁼ιψ«ι≔ωψ¿№AEIOU↥ι«≔ιψ↧ι↧ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLQkuKQoMy9dQ1NTITNNQcMvv0TDtbA0MadYI1NHoVITKFzNxRkAVFKikalpzcXpWFycmZ6nUQ6SBHJBepzzS4GySo6unv6hSjoKoQUFqUXJicWpQA0Q7TBNmVBNUPN88ssRCnEL13LV/v/v6OgY5O7xX7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS ``` Loop over the characters of the input string. ``` ¿¬⁼ιψ« ``` If this is not a duplicate vowel, then: ``` ι ``` Output the current character. ``` ≔ωψ ``` Clear the last duplicate vowel. ``` ¿№AEIOU↥ι« ``` If this is a vowel, then: ``` ≔ιψ ``` Store the last vowel. ``` ↧ι↧ι ``` Output the lowercased vowel twice. [Answer] # [Go](https://go.dev), ~~440~~ 428 bytes ``` import(."regexp";."strings") type S=string func f(s S)S{M,Q,N,x:=MustCompile,Repeat,NewReplacer,`((?i)[aeiou]` L:=[]S{} for _,r:=range`AEIOU`{c:=S(r);l:=ToLower(c);L=append(L,Q(c,3),c,Q(c,2),c,Q(l,3),l,Q(l,2),l)} R:=N(L...) l:=R.Replace(s) for;l!=s;l,s=R.Replace(l),l{} return N([]S{"AAA","Aaa","EEE","Eee","III","Iii","OOO","Ooo","UUU","Uuu"}...).Replace(M(x+`)`).ReplaceAllString(M(x+`+)`).ReplaceAllString(l,"$1"),"$1$1$1"))} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVLditQwFMbbPEU2KCRsLKg30hKlSNGB-dmd7uDFONjQPe0UM01JWmeGMk_izSB45wv4Br6CPo1JOy5emMJ3Dt9Jz_mSL1--lvr8o5H5J1kC3smqRtWu0aYNSLFrybeuLZ6-_P3o-0jSgBgo4dCQKCC2NVVdWsJQe2wAp2IkUNHVOS6oxSlL-xm_5XN-CMWss-0bvWsqBXwJDciWz2HvMiVzMDyj9HXF1hIq3W0yNA3FepP2J1Rogz9yEwoj6xKyOJksVlmfhyKlhkUqFHd6qvdgaM6iqZBNA_U9nfJbmvMXjOdD8nxMlGfUkDhGsRNahmJOp0EQMOQ6LYOLGmqZnxupK2Ejxe0_FeV-dKoMtJ2p8Zx6kSSOY8JJLKXDJEk8AjicTCYeq8rhYrHwqLXD1WrlsevIyc9-aD6jh-uMZQ9ErFQ6XOlYuf5vSXHy-BlhHv1HGDuNpv36ORjhLaUM9yiXFiwOBV5vRqN6crcFXOgDPsp9bZ0UTDgmyWcwx3brNuDK4lLr-yu_xhrUR453MIZqQA2-4u5g-fadz97DZW0vkfx1cZg--IhHMT26cULagpLsic2weIV9_FC7Npb7J8QYOqHLec7nMf4B) What no regex backtracking does to a mfer. Looking at other answers, Golang lacks the following regex features that other answers are dependent on: * Backtracking `(abc)\1` * Lowercase mode `\L` So, I've had to make do with a mix of regex and pure string replacement using `strings.Replacer`s to handle the lack of backtracking and lowercase mode. ### Edits * -12 bytes by moving the code for initializing the translation pairs for `R` out of the function. ### Explanation ``` import(."regexp";."strings") // boilerplate imports type S=string // alias string for byte saving func f(s S)S{ // function of string to string // define the following: // - abbreviations for commonly-used functions // - a partial shared regex M,Q,N,x:=MustCompile,Repeat,NewReplacer,`((?i)[aeiou]` // create a new replacer that maps "AAA"=>"A", "AA"=>"A", etc R:=N(func()(L[]S){for _,r:=range`AEIOU`{c:=S(r);l:=ToLower(c);L=append(L,Q(c,3),c,Q(c,2),c,Q(l,3),l,Q(l,2),l)};return}()...) // do the replacement... l:=R.Replace(s) // ...while the input hasn't changed for;l!=s;l,s=R.Replace(l),l{} return // create another replacer, for the uppercase case N([]S{"AAA","Aaa","EEE","Eee","III","Iii","OOO","Ooo","UUU","Uuu"}...).Replace( // match `((?i)[aeiou])`... M(x+`)`).ReplaceAllString( // replace (de-duplicated) vowels... M(x+`+)`).ReplaceAllString(l,"$1"), // with 3 copies of the vowel "$1$1$1"))} ``` [Answer] # [Julia 1.0](http://julialang.org/), 59 bytes ``` !x=replace(x,r"((?i)[aeiou])\1*"=>i->i[1]lowercase(i[1]^2)) ``` [Try it online!](https://tio.run/##PYzBboMwEETv/orFJ7uiSPRYiVQcUHuuKuWQppKBTdjKtZEhCUj5d2qD2zl4d@bN@vuiSeXTsiRT4bDXqkExpY4L8ULyoJDs5Sg/8wde7OhxR4f8qO0NXaMGFMF9PUm5nKwDAjLgULWaDA5CMvBSaQ0FDL2mUVAKHIod8A31jsyojVAhS9QWJt4VUMP9/s95NfXYjNg@A0@hlgxNu3x0CCc7waxuZsiyLPzhMwypXXMVCauu6OaxI3MGGuBsbZsEhYsK8epvVkxrgbZK7LAKzZzCD26D1tdiPEX8oxFTLFjrI1aW5fvrW@iWSvmN7TGqizOwffS/ "Julia 1.0 – Try It Online") sadly Julia doesn't seem to support `\l` or `\L` ]
[Question] [ Your boss wants you to write code like this: ``` public static boolean isPowerOfTen(long input) { return input == 1L || input == 10L || input == 100L || input == 1000L || input == 10000L || input == 100000L || input == 1000000L || input == 10000000L || input == 100000000L || input == 1000000000L || input == 10000000000L || input == 100000000000L || input == 1000000000000L || input == 10000000000000L || input == 100000000000000L || input == 1000000000000000L || input == 10000000000000000L || input == 100000000000000000L || input == 1000000000000000000L; } ``` (Martin Smith, at <https://codereview.stackexchange.com/a/117294/61929>) which is efficient and so, but not that fun to type. Since you want to minimize the number of keypresses you have to do, you write a shorter program or function (or method) that outputs this function for you (or returns a string to output). And since you have your [very own custom full-range unicode keyboard](https://www.youtube.com/watch?v=3AtBE9BOvvk) with all 120,737 keys required for all of unicode 8.0, we count unicode characters, instead of keypresses. Or bytes, if your language doesn't use unicode source code. Any input your program or function takes counts towards your score, since you obviously have to type that in as well. Clarifications and edits: * Removed 3 trailing spaces after the last `}` * Removed a single trailing space after `return` * Returning a string of output from a function/method is ok [Answer] # PostgreSQL, 158 characters ``` select'public static boolean isPowerOfTen(long input) { return '||string_agg(' input == 1'||repeat('0',x)||'L',' ||')||'; }'from generate_series(0,18)x ``` [Answer] # CJam, 52 characters ``` YA#_("𐀑򀺸󆚜񸎟񜏓񞍁򛟯󩥰󾐚򉴍􍼯𹾚򶗜򳙯󭧐񹷜񊽅𸏘򴂃򦗩󧥮𤠐𰑈򶂤𘏧󔆧򇃫󡀽򊠑񊩭򯐙񛌲񊚩𤱶𻺢"f&bY7#b:c~ ``` [Try it online!](http://cjam.tryitonline.net/#code=WUEjXygi8JCAkfKAurjzhpqc8biOn_Gcj5Pxno2B8pufr_OppbDzvpCa8om0jfSNvK_wub6a8raXnPKzma_zraeQ8bm3nPGKvYXwuI-Y8rSCg_Kml6nzp6Wu8KSgkPCwkYjytoKk8JiPp_OUhqfyh4Or86GAvfKKoJHxiqmt8q-QmfGbjLLxipqp8KSxtvC7uqIiZiZiWTcjYjpjfg&input=) ### Stage 1 Using Unicode characters U+10000 to U+10FFFF, we can encode 20 bits in a single character. CJam uses 16-bit characters internally, so each one will be encoded as a pair of [surrogates](https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates), one in the range from U+D800 to U+DBFF, followed by one in the range from U+DC00 to U+DFFF. By taking the bitwise AND of each surrogate with 1023, we obtain the 10 bits of information it encodes. We can convert the resulting array from base 1024 to base 128 to decode an arbitrary string of Unicode characters outside the BMP to an ASCII string. The code does the following: ``` YA# e# Push 1024 as 2 ** 10. _( e# Copy and decrement to push 1023. "𑅰󻢶񹱨񉽌񍍎񄆋򎿙򧃮񑩹󠷽􂼩􉪦񭲣񶿝򭁩󭰺􄔨񍢤𘎖񮧗򦹀𹀠񐢑񜅈𠟏򘍎󾇗򲁺􅀢򅌛񎠲򦙤򃅒𹣬񧵀򑀢" f& e# Apply bitwise AND with 1023 to each surrogate character. b e# Convert the string from base 1024 to integer. Y7# e# Push 128 as 2 ** 7. b e# Convert the integer to base 128. :c e# Cast each base-128 to an ASCII character. ~ e# Evaluate the resulting string. ``` ### Stage 2 The decoding process from above yields the following source code (**98 bytes**). ``` "public static boolean isPowerOfTen(long input) { return ""L || input == ":S6>AJ,f#S*"L; }" ``` [Try it online!](http://cjam.tryitonline.net/#code=InB1YmxpYyBzdGF0aWMgYm9vbGVhbiBpc1Bvd2VyT2ZUZW4obG9uZyBpbnB1dCkgewogIHJldHVybgogICAiIkwKICB8fCBpbnB1dCA9PSAiOlM2PkFKLGYjUyoiTDsKfSI&input=) The code does the following: ``` e# Push the following string. "public static boolean isPowerOfTen(long input) { return " e# Push the following string and save it in S. "L || input == ":S e# Discard the first 6 characters of S. The new string begins with " input". 6> e# Elevate 10 (A) to each exponent below 19 (J). AJ,f# e# Join the resulting array, using the string L as separator. S* e# Push the following string. "L; }" ``` [Answer] # Vim 97 keystrokes ``` ipublic static boolean isPowerOfTen(long input) { return || input == 1L<esc>qyYpfLi0<esc>q16@yo}<esc>3Gxx ``` Well, I'm on a roll today with vim producing java, so why not continue the trend! [Answer] # Java, ~~217~~ ~~215~~ ~~220~~ ~~219~~ 192 bytes Golfed: ``` public static String b(){String s="public static boolean isPowerOfTen(long input) {\n return\n input == 1L",z="";for(int i=0;i++<18;){z+="0";s+="\n || input == 1"+z+"L";}return s+";\n}";} ``` Ungolfed: ``` public static String a(){ String s = "public static boolean isPowerOfTen(long input) {\n return\n input == 1L", z=""; for (int i=0; i++ < 18;) { z += "0"; s += "\n || input == 1"+z+"L"; } return s + ";\n}"; } ``` (first answer, wuhu) Thanks! -2 bytes: user902383 -1 byte: Denham Coote Changes: * used tabs instead of spaces * missed the last line of output: 18 -> 19 * removed inner loop * changed from printing to returning string [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~99~~ ~~97~~ ~~96~~ ~~94~~ ~~93~~ 87 bytes Code: ``` “‚Æ£‹ÒŒ€ˆPowerOfTen(“?“¢„î®) { «‡ “?19FN0›i" ||"?}’ î® == ’?N°?'L?N18Qi';,"}"?}"", ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCc4oCaw4bCo-KAucOSxZLigqzLhlBvd2VyT2ZUZW4o4oCcP-KAnMKi4oCew67CrikgewogwqvigKEKICAg4oCcPzE5Rk4w4oC6aSIgIHx8Ij994oCZIMOuwq4gPT0g4oCZP07CsD8nTD9OMThRaSc7LCJ9Ij99IiIs&input=) Uses **CP-1252** encoding. [Answer] ## PowerShell, 120 bytes ``` 'public static boolean isPowerOfTen(long input) {' ' return' " $((0..18|%{" input == 1"+"0"*$_})-join"L`n ||")L;`n}" ``` The first two lines are simply string literals, which are output as-is. The third line starts with three spaces, and ends with `L;`n}"` to finish off the last couple bytes. The middle bit inside the script block `$(...)` is constructed by for-looping `%` from `0` to `18` and each iteration constructing a string that starts with `input == 1` concatenated with the corresponding number of zeros. This will spit out an array of strings. We then `-join` each element of the array with `L`n ||` to achieve the newline-pipes. That big string is the output of the script block, which gets inserted automatically into the middle and output. ``` PS C:\Tools\Scripts\golfing> .\go-generate-some-java.ps1 public static boolean isPowerOfTen(long input) { return input == 1L || input == 10L || input == 100L || input == 1000L || input == 10000L || input == 100000L || input == 1000000L || input == 10000000L || input == 100000000L || input == 1000000000L || input == 10000000000L || input == 100000000000L || input == 1000000000000L || input == 10000000000000L || input == 100000000000000L || input == 1000000000000000L || input == 10000000000000000L || input == 100000000000000000L || input == 1000000000000000000L; } ``` [Answer] # Pyth, ~~118~~ ~~106~~ 103 bytes ``` s[." {Z-L¡JxÙÿ LæÝ<­í?¢µb'¥ÜA«Ç}h¹äÚÏß"\nb*4dj"\n || "ms[." uøs|ÀiÝ"*d\0\L)U19\;b\} ``` [Try it online!](http://pyth.herokuapp.com/?code=s[.%22%0A%7BZ-L%C2%A1Jx%C3%99%C2%9F%C3%BF%C2%87%06%0A%C2%9BL%C2%8C%C3%A6%C3%9D%3C%C2%AD%C3%AD%3F%C2%A2%C2%B5%07%C2%93b%27%C2%A5%C2%98%C3%9CA%C2%AB%C3%87%7D%0F%12%10h%C2%95%C2%B9%C3%A4%C3%9A%C2%84%C3%8F%C2%86%C3%9F%19%C2%8E%22%5Cnb*4dj%22%5Cn++||+%22ms[.%22+u%01%07%C3%B8%C2%8Es|%C3%80i%C3%9D%22*d%5C0%5CL%29U19%5C%3Bb%5C%7D&debug=0) All this string hardcoding really eats a lot of bytes up~~, but nothing I can do about it~~. **Update:** Saved 3 bytes by using a packed string. Thanks @user81655 for the hint! [Answer] # C# (CSI) 181 180 179 byte ``` string i=" input == 1",e="public static bool";Console.Write(e+@"ean isPowerOfTen(long input) { return "+i+string.Join(@"L ||"+i,e.Select((_,x)=>new string('0',x)))+@"L; }") ``` There is only one little trick involved. The straight forward way to write this would be: ``` string.Join("L\n || input == 1",Enumerable.Range(0,18).Select(x=>new string('0',x))) ``` by using the string with the first 18 characters of the text which I need anyways I can get rid off the lengthy Enumerable.Range. This works because string implements IEnumerable and there is a version of Select that hands the item (not needed) and the index which we want to the lambda function. [Answer] # Javascript, ~~172~~ ~~157~~ ~~152~~ ~~150~~ 148 bytes ``` p=>`public static boolean isPowerOfTen(long input) { return${[...Array(19)].map((x,i)=>` ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``}; }` ``` ``` f=p=>`public static boolean isPowerOfTen(long input) { return${[...Array(19)].map((x,i)=>` ${i?'||':' '} input == 1${'0'.repeat(i)}L`).join``}; }` document.body.innerHTML = '<pre>' + f() + '</pre>' ``` [Answer] # C, ~~158~~ 155 bytes ``` i;main(){for(puts("public static boolean isPowerOfTen(long input) {\n return");i<19;)printf(" %s input == 1%0.*dL%s\n",i++?"||":" ",i,0,i<18?"":";\n}");} ``` Try it online [here](http://ideone.com/vWyFmE). [Answer] # Jelly, 75 bytes (These are bytes in Jelly's [custom codepage](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md).) ``` 0r18⁵*;@€⁶j“¢œḤḅg^NrÞḢ⁷ẉ»“⁵®UẆƓḃÐL⁴ṖịṛFþẈ¹9}¶ ƁḋȮ¦sẒẆd€Ḟɼ¿ỌṀP^µ\f@»;;“L;¶}” ``` [Try it here.](http://jelly.tryitonline.net/#code=MHIxOOKBtSo7QOKCrOKBtmrigJzCosWT4bik4biFZ15OcsOe4bii4oG34bqJwrvigJzigbXCrlXhuobGk-G4g8OQTOKBtOG5luG7i-G5m0bDvuG6iMK5OX3CtiDGgeG4i8iuwqZz4bqS4bqGZOKCrOG4nsm8wr_hu4zhuYBQXsK1XGZAwrs7O-KAnEw7wrZ94oCd&input=) ### Explanation ``` 0r18 Range [0..18] ⁵* Take the 10^ of each number ;@€⁶ Prepend a space to each number j“...» Join by compressed string "L\n || input ==" “...»; Prepend compressed string "public static ... ==" ;“L;¶}” Append "L;\n}" ``` [Answer] # Vimscript, 120 bytes Might as well use the right tool for the job. This assumes that autoindent, etc have not been set. `^[` and `^M` are escape characters for the `ESC` and `CR` characters respectively. The `a` macro duplicates the current line and adds a 0 to the copy. The `:norm` line generates all the boilerplate and the `indent == 1L` line, then uses `a` to create the others. ``` :let @a='yyp$i0^[' :norm ipublic static boolean isPowerOfTen(long input) {^M return^M || input == 1L^[18@a$a;^M} :3s/||/ / ``` In case the trailing spaces the sample output had on two lines weren't typos, here's a 126 byte version that includes them. ``` :let @a='yyp/L^Mi0^[' :norm ipublic static boolean isPowerOfTen(long input) {^M return ^M || input == 1L^[18@a$a;^M} :3s/||/ / ``` [Answer] ## ES6, ~~139~~ 138 bytes ``` document.write(`<pre>${( _=>"0".repeat(19).replace(/./g,` || input == 1$\`L`).replace(` ||`,`public static boolean isPowerOfTen(long input) { return `)+`; }` )()}</pre>`); ``` I do so love these triangle generation questions. Note: Snippet includes header and footer, but these aren't included in the byte count. [Answer] # Oracle SQL 9.2, 311 bytes ``` SELECT REPLACE(REPLACE('public static boolean isPowerOfTen(long input) {'||CHR(10)||' return'||c||';'||'}', 'n ||', 'n'||CHR(10)||' '),CHR(10)||';', ';'||CHR(10)) FROM(SELECT LEVEL l,SYS_CONNECT_BY_PATH('input == '||TO_CHAR(POWER(10,LEVEL-1))||'L'||CHR(10),' || ')c FROM DUAL CONNECT BY LEVEL<20)WHERE l=19 ``` [Answer] # Perl 5 - ~~130~~ 141 ``` @s=map{'input == 1'.0 x$_."L\n ||"}0..18;$s[$#s]=~s/\n \|\|/;\n}/g;print"public static boolean isPowerOfTen(long input){\n return\n @s" ``` EDIT: fixed to have exact indentation [Answer] ## Kotlin, ~~194~~ 193 characters ``` fun main(u:Array<String>){var o="public static boolean isPowerOfTen(long input) {\n\treturn" var p:Long=1 for(k in 0..18){ o+="\n\t" if(k>0)o+="||" o+=" input == ${p}L" p*=10 } print("$o;\n}")} ``` Test it at <http://try.kotlinlang.org/> [Answer] ## Ruby, ~~125~~ 119 bytes ``` $><<'public static boolean isPowerOfTen(long input) { return '+(0..19).map{|i|" input == #{10**i}L"}*' ||'+'; }' ``` Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for -6 bytes! [Answer] # jq, 123 characters (121 characters code + 2 characters command line option.) ``` "public static boolean isPowerOfTen(long input) { return \([range(19)|" input == 1\("0"*.//"")L"]|join(" ||")); }" ``` Sample run: ``` bash-4.3$ jq -nr '"public static boolean isPowerOfTen(long input) { > return > \([range(19)|" input == 1\("0"*.//"")L"]|join(" > ||")); > }"' public static boolean isPowerOfTen(long input) { return input == 1L || input == 10L || input == 100L || input == 1000L || input == 10000L || input == 100000L || input == 1000000L || input == 10000000L || input == 100000000L || input == 1000000000L || input == 10000000000L || input == 100000000000L || input == 1000000000000L || input == 10000000000000L || input == 100000000000000L || input == 1000000000000000L || input == 10000000000000000L || input == 100000000000000000L || input == 1000000000000000000L; } ``` [On-line test](https://jqplay.org/jq?q=%22public%20static%20boolean%20isPowerOfTen%28long%20input%29%20%7B%5Cn%20%20return%5Cn%20%20%20%20%5C%28[range%2819%29|%22%20input%20==%201%5C%28%220%22*.//%22%22%29L%22]|join%28%22%5Cn%20%20||%22%29%29%3B%5Cn%7D%22&j=null) (Passing `-r` through URL is not supported – check Raw Output yourself.) [Answer] # Javascript 175 bytes Let's do this regularly ``` var s = "public static boolean isPowerOfTen(long input) {\n\treturn\n\t\tinput == 1"; for (var i = 1; i < 20; i++) { s += "\n\t|| input == 1"; for (var j = 0; j < i; j++) { s += "0"; } s += "L" ; } s += ";\n}"; alert(s); ``` Pretty small. Now, some javascript magic, like no semicolons needed, or no var's, etc.: ``` k="input == 1" s="public static boolean isPowerOfTen(long input) {\n\treturn\n\t\t"+k+"L" for(i=1;i<20;i++){s+="\n\t|| "+k for(j=0;j<i;j++)s+="0";s+="L"}s+=";\n}" alert(s) ``` [Answer] ## Python (3.5) ~~137~~ 136 bytes ``` print("public static boolean isPowerOfTen(long input) {\n return\n ",'\n || '.join("input == %rL"%10**i for i in range(19))+";\n}") ``` **Previous version** ``` print("public static boolean isPowerOfTen(long input) {\n return\n ",'\n || '.join("input == 1"+"0"*i+"L"for i in range(19))+";\n}") ``` [Answer] # ANSI-SQL, 252 characters ``` WITH t as(SELECT ' 'x,1 c,1 l UNION SELECT' ||',c*10,l+1 FROM t WHERE l<19)SELECT 'public static boolean isPowerOfTen(long input) {'UNION ALL SELECT' return 'UNION ALL SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19)FROM t UNION ALL SELECT'} '; ``` Ungolfed: ``` WITH t as (SELECT ' ' x,1 c,1 l UNION SELECT ' ||',c*10,l+1 FROM t WHERE l<19) SELECT 'public static boolean isPowerOfTen(long input) {' UNION ALL SELECT ' return ' UNION ALL SELECT x||' input == '||c||'L'||SUBSTR(';',1,l/19) FROM t UNION ALL SELECT '} '; ``` Not a serious attempt, just poking at the Oracle SQL/T-SQL entries. [Answer] # JavaScript (Node.js), 156 bytes ``` s="public static boolean isPowerOfTen(long input) {\n return " for(i=1;i<1e19;i*=10)s+="\n "+(i-1?"||":" ")+" input == "+i+"L" console.log(s+";\n} \n") ``` The `i-1` will only be 0 (and thus falsey) on the very first round (it's just slightly shorter than `i!=1`. Suggestions welcome! [Answer] ## Perl 5, 137 bytes Not based on the previous Perl answer, but it is somehow shorter. I believe it can be shortened down again by taking care of the first "input" inside the loop, but I didn't try anything yet (at work atm) ``` $i="input";for(1..18){$b.=" || $i == 1"."0"x$_."L;\n"}print"public static boolean isPowerOfTen(long $i) {\n return\n $i == 1L;\n$b}" ``` [Answer] # CJam, 112 chars ``` "public static boolean isPowerOfTen(long input) { return input == 1"19,"0"a19*.*"L || input == 1"*"L; }" ``` [Answer] ## AWK+shell, 157 bytes ``` echo 18|awk '{s="input == 1";printf"public static boolean isPowerOfTen(long input) {\n return\n "s"L";for(;I<$1;I++)printf"\n ||%sL",s=s"0";print";\n}"}' ``` The question did say to count everything you would have to type. This does have the added bonus of being able to select how many lines would be placed in the isPowersOfTen method when the boss inevitably changes his mind. [Answer] ## T-SQL ~~289~~, ~~277~~, ~~250~~, 249 bytes ``` SELECT'public static boolean isPowerOfTen(long input){return '+STUFF((SELECT'||input=='+N+'L 'FROM(SELECT TOP 19 FORMAT(POWER(10.0,ROW_NUMBER()OVER(ORDER BY id)),'F0')N FROM syscolumns)A FOR XML PATH(''),TYPE).value('.','VARCHAR(MAX)'),1,2,'')+';}' ``` **Update:** Thanks @Bridge, I found a few more spaces too :) **Update2:** Changed CTE to subquery -27 chars :) **Update3:** Another space bites the dust @bridge :) [Answer] # R, 185 bytes ### Golfed ``` options(scipen=999);p=paste;cat(p("public static boolean isPowerOfTen(long input) {"," return",p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"),"}",sep="\n")) ``` ### Ungolfed ``` options(scipen=999) p=paste cat( p("public static boolean isPowerOfTen(long input) {", " return", p(sapply(0:19,function(x)p(" input == ",10^x,"L",sep="")),collapse="\n ||"), "}", sep="\n") ) ``` [Answer] # Perl 6 (115 bytes) ``` say "public static boolean isPowerOfTen(long input) \{ return {join "L ||",(" input == "X~(10 X**^19))}L; }" ``` `X` operator does list cartesian product operation, for example `10 X** ^19` gives powers of ten (from 10 to the power of 0 to 19, as `^` is a range operator that counts from 0). Strings can have code blocks with `{` (which is why I escape the first instance of it). [Answer] ## Java, 210 / 166 Score is depending on whether returning the input from a function meets the definition of 'output'. Console output (210): ``` class A{public static void main(String[]z){String a=" input == 1",t="L\n ||"+a,s="public static boolean isPowerOfTen(long input) {\n return\n "+a;for(int i=0;++i<19;)s+=t+="0";System.out.print(s+"L;\n}");}} ``` String return (166): ``` String a(){String a=" input == 1",t="L\n ||"+a,s="public static boolean isPowerOfTen(long input) {\n return\n "+a;for(int i=0;++i<19;)s+=t+="0";return s+"L;\n}";} ``` Legible version: ``` String a() { String a=" input == 1", t = "L\n ||"+a, s = "public static boolean isPowerOfTen(long input) {\n return\n "+a; for (int i = 0; ++i < 19;) s += t += "0"; return s + "L;\n}"; } ``` [Answer] ## Batch, ~~230~~ ~~208~~ ~~206~~ 205 bytes ``` @echo off echo public static boolean isPowerOfTen(long input) { echo return set m=input == 1 echo %m%L for /l %%a in (1,1,17)do call:a call:a ; echo } exit/b :a set m=%m%0 echo ^|^| %m%L%1 ``` Edit: Saved 22 bytes by avoiding repeating `input ==` and reusing the subroutine for the line with the extra semicolon. Saved ~~2~~ 3 bytes by removing unnecessary spaces. ]
[Question] [ This is the robbers' thread. The cops' thread [goes here](https://codegolf.stackexchange.com/questions/67756/printing-ascending-ascii-cops). In the cops thread, the task was to create a program that outputs printable ASCII characters in ascending order. The robbers task is to unscramble the code the cops used to produce this output. The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical. Cops can not use comments in their code, but robbers are free to use them. The winner of the robbers thread will be the user who has cracked the most submissions by January 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win. The submission should be formatted like this: # Language, nn characters (including link to answer), Cop's username Code: ``` alphaprinter ``` Output ``` abcdefghijklmnopqrstuvwxyz ``` Optional explanation and comments. # Leaderboard: **A crushing victory by [Adnan](https://codegolf.stackexchange.com/users/34388/adnan)!** ``` Adnan: 7 Pietu1998: 3 Mitch Schwartz: 2 Quintopia: 2 Martin Büttner: 2 cat: 1 Dennis: 1 insertusernamehere: 1 isaacg: 1 jimmy23013: 1 MegaTom: 1 plannapus: 1 user81655: 1 ``` [Answer] # [Brainfuck, 48 bytes, Adnan](https://codegolf.stackexchange.com/a/67787/2537) ``` ++++[>++++[>++++<-]<-]+++[>++++++++<-]>++[>+.<-] ``` Pretty straightforward, generating 64 and then 26. It might be a little red herring that ``` ++++[>++++[>++++<-]<-]>>+ ``` is a way to get 65, so you might try to do something like ``` ++++[>++++[>++++<-]<-]>>+[>+++++>++<<-----]>>[<.+>-] ``` before noticing that it's a dead end. [Answer] # [Python 2, 76 characters, wnnmaw](https://codegolf.stackexchange.com/a/68009/34388) Code, with obfuscated version below: ``` print "BKT]f"#__h______________________v_____________,___)_________)_______) print __________h______________________v_____________,___)_________)_______) ``` This outputs `BKT]f`. Not the intended version, that's for sure haha. Tested [here](http://mathcs.holycross.edu/%7Ekwalsh/python/) [Answer] # [CJam, 12 characters, Dennis](https://codegolf.stackexchange.com/a/67766/25180) ``` ":0[Aa#":,:^ ``` It's in the tips... [Answer] # [CJam, 8 characters, Martin Büttner](https://codegolf.stackexchange.com/a/67809/30164) Code (with blanked code): ``` {`:)$}_~ __:_____ ``` Output: ``` %*;a|~ ``` [Try it online.](http://cjam.tryitonline.net/#code=e2A6KSR9X34&input=) I sort of had a feeling about this from the moment I saw it. And I thought I didn't know CJam... [Answer] # [Labyrinth, 5 characters, Martin Büttner](https://codegolf.stackexchange.com/a/67762/34388) Code: ``` !!!>@ ``` [Test it here](http://labyrinth.tryitonline.net/#code=ISEhPkA&input=) Output: ``` 000000 ``` [Answer] # [JavaScript (ES6), 17 characters, Neil](https://codegolf.stackexchange.com/a/67797/41859) As the OP posted a function, here's a solution using a function: ``` ()=>xxx=11000+233 __=____=_________ ``` The anonymous function can be invoked like: ``` (()=>xxx=11000+233)(); ``` A more ridiculous solution I had at first: ``` xx=yyyy=z=11230+3 __=____=_________ ``` When run in the console, it will print the number `11233`. [Answer] # [PHP, 28 characters, Niet the Dark Absol](https://codegolf.stackexchange.com/a/67800/34388) I found several versions for this task: **Original version:** ``` <?=@implode(range('a','z')); ``` **My version:** ``` <?=join('',range('a', 'z')); ``` **23 character version:** ``` <?=join('',range(a,z)); ``` **26 character version:** ``` <?=implode('',range(a,z)); ``` Of course, you can just add several whitespaces to get to the 28 character mark. Tested [here](http://codepad.org/) [Answer] # [Jolf, 27 characters, Cᴏɴᴏʀ O'Bʀɪᴇɴ](https://codegolf.stackexchange.com/a/67804/34388) After a few hours of trial and error, I got it haha: ``` on-pl'u'Wa-n"vwxyz"`--'01_2 ``` Including obfuscated code: ``` on-pl'u'Wa-n"vwxyz"`--'01_2 ________W___________--_____ | ``` Try it [here](http://conorobrien-foxx.github.io/Jolf/#code=b24tcGwndSdXYS1uInZ3eHl6ImAtLScwMV8y) (**step run** seems to be the only one working with alert) --- ### Explanation First thing I got stuck on was the placement of the while loop. I didn't seem to get it on the right place haha. After getting it right, the second thing I noticed was the placement of the underscore. I thought I almost got it, until I got stuck on the underscore (gg Cᴏɴᴏʀ O'Bʀɪᴇɴ). Here is full explanation of the code: ``` on-pl'u'Wa-n"vwxyz"`--'01_2 o # assign n # n / standard variable pl # pl = "abcdefghijklmnopqrstuvwxyz" - 'u # pl - "u" = "abcdefghijklmnopqrstvwxyz" 'W # a string in the middle doing nothing -n"vwxyz" # n - "vwxyz" a # alert( ` # is an extra semicolon -'01 # "0" - 1 - _2 # ("0" - 1) - negative 2 ``` In pseudocode: ``` n = minus("abcdefghijklmnopqrstuvwxyz", "u"); "W"; alert(minus(n,"vwxyz")); ; minus(minus("0", 1), negative(2)); ``` I'm interested to see what the actual solution was :) [Answer] # [Pyth, 6 bytes, Pietu1998](https://codegolf.stackexchange.com/a/67888/20080) ``` Ssy>TG ``` Take the last 10 letters of the alphabet, form all subsets, concatenate, sort. [Answer] # [R, 60 bytes, Fax Machine](https://codegolf.stackexchange.com/a/67878/6741) Code: ``` cat(c(0:9,LETTERS[1:8],LETTERS[20:26],letters[4:23]),sep="") ``` Output: ``` 0123456789ABCDEFGHTUVWXYZdefghijklmnopqrstuvw ``` [Answer] ## [Seriously, 7 characters, by quintopia](https://codegolf.stackexchange.com/a/67898/8478) ``` 2'aNsES ``` [Tested here.](http://seriouslylang.herokuapp.com/link/code=3227614e734553&input=) Splits 99 bottles of beer around `a`s and sorts the third chunk. [Answer] # [Python 3, 58 bytes, Mathias Ettinger](https://codegolf.stackexchange.com/a/67946/2537) ``` import string;print(''.join(sorted(string.printable))[5:]) ``` Basic use of [string](https://docs.python.org/3.1/library/string.html) module. [Answer] ## [05AB1E, 13 characters, Adnan](https://codegolf.stackexchange.com/a/67759/47050) Code (and blanked code): ``` 1TD*<F3<*}bRJ __D____<_____ ``` Output: ``` 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 ``` Explanation: ``` 1 Push 1 TD*< Push 99 F } For loop 3<* multiply top of stack by 3-1 (e.g. double it) b convert to list of binary digits (note we have just computed 2^99) R reverse it J join it into a string. (top of stack implicitly printed) ``` [Answer] ## [JavaScript, 83 characters, BlockCoder1392](https://codegolf.stackexchange.com/a/67806/8478) ``` a=aaaaraaaa=uaaaa=aasaa=console;b=0;a.log("Hi~~~");auaaaaaaaAaaaaaaaa =aeaaaa="^~^" ``` A bit too many characters for such a short string. [Answer] ## [JavaScript (ES6), 60 characters, insertusernamehere](https://codegolf.stackexchange.com/a/67812) Code: ``` e=e=>{try{a}catch(e){return[...e.toString()].sort().join``}} e_e_______a__a____e___e________e__o___________o______o______ ``` Output (in Chrome): ``` :ERacddeeeeeeffiinnnoorrrrst ``` I knew this immediately because I was about to do the same thing! xD [Answer] # [Pyth, 6 characters, Adnan](https://codegolf.stackexchange.com/a/67853/30164) Code (with blanked code): ``` S`.n 3 S_____ ``` Output ``` .0113345678888999 ``` [Try it online.](https://pyth.herokuapp.com/?code=S%60.n%203&debug=0) It's φ's representation, sorted. This could've been done in 5, if you remove the space. [Answer] # [Malbolge, 254 characters, frederick](https://codegolf.stackexchange.com/a/68198/34388) Obfuscated version: ``` _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ _____ __ ``` My version: ``` ('&%: ^"!65 4Xzyx w4-Qs rpo'K mlk"' ~Dfdc ba}v< ::8[Z XnVlq }0/mO ,*MbK JH^6# 4`C|0 ?U=Sw uPsaq L4on2 Mjjh, ged)c '<$$p ]!};Y WiVxS eRQ>= ).K]l Ij"Fh gfedc b,=;z L\q%H X3E2C /ng-k N*KJI 8%6#D ~2^Ai >g<<d tUr`6 oJ"!1 /|{CU f)d>b <A_^! \};Yj yUxTS dtsr` ML ``` This will output: ``` `AB\cd` ``` You can try it [here](http://zb3.github.io/malbolge-tools/#interpreter). [Answer] # [Befunge, 11 characters, histocrat](https://codegolf.stackexchange.com/a/68026/31203) Code: ``` 89'**'z...@ ``` Output: ``` 1223788 ``` That was fun. This is an alternate solution I also found: ``` 8]..@#37.z' ``` [Answer] ## [05AB1E, 7 characters Adnan](https://codegolf.stackexchange.com/a/68141/47050) Code and blanked code: ``` 576T*uH ___T___ ``` Output: ``` 22368 ``` Explanation: ``` 576 Push this number. T Push ten. * Multiply. (5760) u Convert to string. H Interpret as a hex number and push decimal (22368) (implicit output). ``` I almost positive this wasn't the original program, but thanks to Adnan for providing the one bit of information that made it possible (the `u` command). [Answer] This answer is invalid and shouldn't count towards my score (not that I'm anywhere near winning anyways) because I didn't see it had already been cracked. # [Python 3, 58 characters, Mathias Ettinger](https://codegolf.stackexchange.com/a/67946/46231) Code, with original code below: ``` x=range(95); print(''.join((chr(i+32) for i in x ) )) ______________print(_______(_______________________)_____) ``` Clearly not the intended solution, which was: ``` import string;print(''.join(sorted(string.printable))[5:]) ``` Output: ``` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` (Note the leading space.) A fun one to crack: it took me a while to figure how to get the `genexpr` to work properly. :) [Answer] # [Pyth, 17 characters, Luke](https://codegolf.stackexchange.com/a/67768/30164) Code (with blanked code): ``` S`u]G6*T`t"#X0231 ___________#____1 ``` Output: ``` ""''''''''''''''''''''0000000000111111111122222222223333333333XXXXXXXXXX[[[[[[]]]]]] ``` [Try it online.](https://pyth.herokuapp.com/?code=S%60u]G6*T%60t%22%23X0231&debug=0) This was fun. I got it to 18 bytes multiple times using `#` as the filter operator, but then I figured out I could just discard it from the string. If you remove the `t` and the `#` the result would probably be the shortest Pyth code for that output. Basically: * `"#X0231` makes the string `#X0231` * `t"#X0231` removes the `#`: `X0231` * ``t"#X0231` gets the string representation: `'X0231'` * `*T`t"#X0231` multiplies it by 10: `'X0231''X0231''X0231'`… * `u]G6*T`t"#X0231` wraps it in an array 6 times * ``u]G6*T`t"#X0231` gets the string representation: `[[[[[['X0231'`…`'X0231']]]]]]` * `S`u]G6*T`t"#X0231` sorts it to get the output [Answer] # [CJam, 9 characters, by username.ak](https://codegolf.stackexchange.com/a/68204) ``` 'a{_)}25* ``` [Try it online!](http://cjam.tryitonline.net/#code=J2F7Xyl9MjUq&input=) ### How it works ``` 'a e# Push the character 'a'. { }25* e# Do 25 times. _ e# Copy the character on the stack. ) e# Increment the copy. ``` [Answer] # [Perl 5, 30 characters, msh210](https://codegolf.stackexchange.com/a/68119/34388) Obfuscated + my version: ``` print_________________________ print "9:;\@AFGHLMNRSTYZ_`a" ``` This will output: ``` 9:;@AFGHLMNRSTYZ_`a ``` Tested [here](http://codepad.org/WvTdnhzD) [Answer] # [Python 2, 62 characters, RikerW](https://codegolf.stackexchange.com/a/68200/34388) Obfuscated version: ``` ______________________________________________________________ | | || | | || ``` My version: ``` print "ab_c_de___".replace("_","")#___________________________ ``` This simply removes all the underscores and outputs `abcde`. Tried it [here](http://mathcs.holycross.edu/%7Ekwalsh/python/) ]
[Question] [ This happy individual is known in folklore as the Easter Bunny. [![Easter Bunny](https://i.stack.imgur.com/U75Ab.png)](https://i.stack.imgur.com/U75Ab.png) # Colours It is created using 4 colours: * Light pink * Dark pink * White * Black (I'm happy for these colours to be approximated in your answer. It does not need to be this precise shade) # Shapes It is constructed of these shapes: * Two tall ellipses in light pink (outer ears). They have the same height and width. * Two tall ellipses in dark pink (inner ears). They are smaller than the outer ears and one is drawn on top of each of the outer ears. They are the same height and width. * One large circle in light pink (head). It intersects with the bottom third of both outer ears (but no higher). * Two circles in white (outer eyes). They are drawn on the head. Their diameter is less than the width of the outer ears. They have the same horizontal position as the outer ears. * Two circles in black (inner eyes). They have a smaller diameter than the outer eyes. One is drawn on each of the outer eyes. * One vertical line in black (upper mouth). It is drawn on the head and is lower than the bottom of the outer eyes. It is roughly equidistant from each eye. * Two arcs in black (lower mouth). They are drawn on the head and arc downwards from a horizontal line. Both intersect with the bottom of the upper mouth, but one goes right and the other goes left. --- # The Rules * Use any language and tools you like. * Output can be an image, html, svg, or other markup. * It's code golf, so aim to do it in the smallest number of bytes. * Please include a screenshot of the result. * Please feel free to approximate the colours defined. # Happy Easter! [Answer] # T-SQL, ~~445~~ 439 bytes ``` DECLARE @ GEOMETRY='MULTIPOINT((3 3),(7 3))', @l GEOMETRY='CIRCULARSTRING(3 6,3.3 9,3 12,2.7 9,3 6)',@r GEOMETRY SET @[[email protected]](/cdn-cgi/l/email-protection)(.6)SET @[[email protected]](/cdn-cgi/l/email-protection)('CIRCULARSTRING(7 6,7.3 9,7 12,6.7 9,7 6)') SELECT*FROM(VALUES(@),(@),(@),(@r.STBuffer(.3)),(@),(@),(@),(@),(@),(@),(@),(@),(@), (@),(@),('CIRCULARSTRING(7 0,6 -1,5 0,5 1,5 1,5 0,5 0,4 -1,3 0)'), (GEOMETRY::Point(5,1,0).STBuffer(5).STUnion(@r.STBuffer(1.3)).STDifference(@.STBuffer(.4))) )a(g) ``` This site could use more T-SQL-based drawings! Run on SQL 2017, but uses [SQL geo-spatial storage features added back in SQL 2008](https://docs.microsoft.com/en-us/sql/relational-databases/spatial/spatial-data-sql-server?view=sql-server-2017). Line breaks are for readability only. Output: [![enter image description here](https://i.stack.imgur.com/D5KcH.png)](https://i.stack.imgur.com/D5KcH.png) So, this was a pain to do in T-SQL, since spatial objects aren't exactly designed for drawing (no "ellipse" object, for example). Even more, getting the colors even *close* to right required a bit of trial and error. Basically I'm constructing the following geometric objects: 1. The eyes (`@`), which are points expanded into disks using `STBuffer(.6)` (the set of all points within 0.6 of those starting points) 2. The ears (`@r`), which are generated as pointy curves, but are "puffed out" using `STBuffer` into either the inner or outer ears 3. The face, which is a disk plus the ears minus the eyes. I have to construct this and display it as a single object, or SQL would display it in different colors. 4. The mouth, which is a curve created using `CIRCULARSTRING` To get the colors right, I have to `SELECT` these *in the proper order*. SSMS has [a built-in sequence of colors for objects displayed in the spatial results pane](https://alastaira.wordpress.com/2011/03/31/more-drawing-fun-with-sql-server/), so the dark pink inner ears had to come *4th*, and the light pink face had to come *16th*. This required putting in a whole bunch of extra copies of the eyes, which is ok since we want them as close to black as possible (colors are somewhat transparent, so stacking them makes them darker). Help and inspiration from the following resources: * [Drawing in color in SQL](https://alastaira.wordpress.com/2011/03/31/more-drawing-fun-with-sql-server/) * [Botticelli’s Birth of Venus using T-SQL](https://michaeljswart.com/2010/02/more-images-from-the-spatial-results-tab/) * [SQL Server Christmas card](https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d52c686e-30cc-4ae0-bdc7-ae4a2536cd64/sql-server-spatial-christmas-ecard?forum=sqlspatial) **EDIT**: Moved the bunny down by 4 units, which changes some coordinates to a single digit, saving 6 bytes. No change in displayed output. [Answer] # [Red](http://www.red-lang.org), ~~375~~ ~~340~~ 329 bytes ``` Red[needs 'View]f: 'fill-pen p: 'pen e: 'ellipse c: 'circle t:[5x5 0 180]view[base 200x200 #FFF draw compose[(p)pink(f)pink(c)100x100 30(e)75x25 20x60(e)105x25 20x60(p)#E28(f)#E28(e)79x35 12x35(e)109x35 12x35(p)#FFF(f)#FFF(c)88x92 8(c)112x92 8(p)#000(f)#000(c)88x92 5(c)112x92 5 line 100x108 100x115 arc 95x115(t)arc 105x115(t)]] ``` [![enter image description here](https://i.stack.imgur.com/Bnjqv.jpg)](https://i.stack.imgur.com/Bnjqv.jpg) [Answer] # Ruby with [Shoes](http://shoesrb.com/), 240 characters ``` Shoes.app{['fcc',[0,40,60],[5,0,20,50],[35,0,20,50],'f99',[t=10,t,t,h=30],[40,t,t,h],'fff',[t,55,15],[35,55,15],'000',[14,58,7],[38,58,7]].map{|v|stroke fill v rescue oval *v} nofill line h,75,h,80 arc 25,80,t,t,0,3.14 arc 35,80,t,t,0,3.14} ``` Sample output: ![Shoes window screenshot with easter bunny](https://i.stack.imgur.com/8bfF3.png) [Answer] # Python, 368 bytes Using matplotlib. ``` from matplotlib import pyplot as l,patches as p,transforms as t;z=0,;[l.gca().add_patch(p.Wedge(z*2,R,s,360,width=w,color=(r,o,o),transform=t.Affine2D.from_values(X,0,0,9,350+x*n,y*9)))for R,s,w,r,o,X,x,y in zip([11,7,15,4,2,2,99],z*5+(180,359),[None]*5+[.2,.4],(1,)*4+z*3,(.8,.6,.8,1)+z*3,[4,4]+[9]*5,[7,7,0,6,6,2,98.8],[51,51,30,35,35,24,26])for n in[-9,9]];l.show() ``` Result: [![enter image description here](https://i.stack.imgur.com/Gz8bN.png)](https://i.stack.imgur.com/Gz8bN.png) Ungolfed: ``` from matplotlib import pyplot, patches, transforms z = 0, # store zero as a tuple for later repetition for radius, startAngle, width, red, other, xStretch, x, y in \ zip([11 ,7 ,15 ,4 ,2 ,2 ,99 ], # radius z * 5 + (180,359 ), # start angle [None] * 5 + [.2 ,.4 ], # wedge width (None = full) (1,) * 4 +z * 3 , # red channel (.8 ,.6 ,.8 ,1) +z * 3 , # other color channels [4]*2 + [9]*5 , # x stretch factor [ 7 ,7 ,0 ,6 ,6 ,2 ,98.8 ], # x [51 ,51 ,30 ,35 ,35 ,24 ,26 ]): # y # | | | | | | | # | | | | | | "straight" line for upper mouth # | | | | | | approximated by large radius arc # | | | | | | # | | | | | Arc for lower mouth # | | | | | # | | | | Inner eye circle # | | | | # | | | Outer eye circle # | | | # | | Circle for head # | | # | Inner ear ellipse # | # Outer ear ellipse for n in [-9, 9]: # draw left and right side mirrored pyplot.gca().add_patch( patches.Wedge( z*2, # center = (0, 0), actual location set by the transform below radius, startAngle, 360, # end angle width = width, color = (red, other, other), # only red channel varies from the others transform = transforms.Affine2D.from_values( # affine transform matrix xStretch, # x stretch factor 0, 0, # unused cross-axis coefficients for skew/rotation 9, # y stretch factor x * n + 350, # x value reflected by n, centered at 350 y * 9 ))) # y value pyplot.show() ``` [Answer] # JavaScript + [P5.js](http://p5js.org), ~~291~~ ~~276~~ 273 bytes A lot of small changes this time around.. that don't change the byte size at all. ``` setup=_=>{createCanvas(u=400,u);(e=ellipse,f=fill)`#fcc`;e(u/=2,u,x=150,x);e(x+=10,z=99,50,z);e(w=240,z,50,z);f`#f77`;e(x,z,y=30,80);e(w,z,y,80);f``;e(w,v=180,y,y);e(x,v,y,y);f(0);e(w,v,y=9,y);e(x,v,y,y);noFill(line(u,225,u,250));arc(195,...a=[245,y,y,0,PI]);arc(205,...a)} ``` [Try it online!](https://www.openprocessing.org/sketch/701763) Explanation: ``` setup = _ => { createCanvas(u=400, u); // Create basic canvas. (e = ellipse, f = fill)`#fcc`; // Light pink e(u /= 2, u, 150, 150); // These first few lines end up defining short-hand names for functions. e(x += 10, z = 99, 50, z); // Throughout the code, you will see e(w = 240, z, 50, z); // lots of variable definitions. f`#f77`; // Dark pink e(x, z, y = 30, 80); // Another variable declaration e(w, z, y, 80); f``; // Empty fill argument = white, apparently? (Eyes start here) e(w, v = 180, y, y); // I'll just stop commenting on declarations now e(x, v, y, y); f(0); // fill(x) = fill(x, x, x) e(w, v, y = 9, y); e(x, v, y, y); noFill(line(u, 225, u, 250)); // Last part of bunny starts here. // Get rid of fill so the bunny doesn't look bad arc(195, ...a= [245, y, y, 0, PI]); arc(205, ...a) // arc() creates something similar to a semi-circle. } ``` [Answer] ## Javascript, ~~381~~ 326 bytes Thanks Arnold and Epicness. ``` (d=document).body.appendChild(a=d.createElement`canvas`);b=a.getContext`2d`;'A707|A7,/|Z707|Z7,/|MZAA|CR--|UR--|CR**|UR**|Id**|Nd**|La(+'.split`|`.map(x=>x.split``.map(c=>c.charCodeAt()-40)).map((x,i)=>b[b.beginPath(b.fillStyle='#'+'fccf77fff000'.substr('030306699'[i],3)),b.ellipse(...x,0,0,3*-~(i<9)),i>8?'stroke':'fill']()) ``` [Answer] # [HTML](https://www.w3schools.com/html/), ~~280~~ 278 bytes ``` a{color:#FFC8C8;}b{color:#FF7F7F;font-size:6px;margin-left:-10px;}m,n,j,d{display:block;}m{margin:-15px -3px;font-size:40px;}n{margin:-35px 5px;color:#FFF;font-size:15px;}j{margin:-14px 1px;color:#000;font-size:10px;} ``` ``` <a>⬮<b>⬮</b><a>⬮<b>⬮</b><m>⬤<n>● ●<j>●‌‌ ‌‌ ‌‌ ●<d>‌‌ ‌‌ ‌‌ w ``` Here is a screenshot: [![enter image description here](https://i.stack.imgur.com/8nVp6.png)](https://i.stack.imgur.com/8nVp6.png) Citations * Oval characters: <https://unicode.org/charts/PDF/U2B00.pdf> * Invisible character: <https://stackoverflow.com/a/17979246/7668911> [Answer] # Lua + [LÖVE/Love2D](https://love2d.org/), 328 bytes ``` l=love g=l.graphics c=g.setColor e=g.ellipse a=g.arc f="fill" k="line" o="open"function l.draw()c(1,.7,.7)e(f,50,82,40,40)e(f,30,28,10,25)e(f,70,28,10,25)c(1,.4,.4)e(f,30,28,5,18)e(f,70,28,5,18)c(1,1,1)e(f,35,73,8,8)e(f,65,73,8,8)c(0,0,0)g[k](49,90,49,99)a(k,o,45,96,5,.5,2.7)a(k,o,53,96,5,.5,2.7)e(f,35,73,4,4)e(f,65,73,4,4)end ``` [Try it online!](https://repl.it/repls/MicroAdolescentOpengl) [![enter image description here](https://i.stack.imgur.com/ftD2M.png)](https://i.stack.imgur.com/ftD2M.png) [Answer] # Processing, ~~388~~ ~~343~~ 319 chars/bytes Not very elegant, but here it is. Saved bytes by making the image smaller. ``` int b=50,c=60,g=70; noStroke(); //Face fill(#FFCCCC); ellipse(b,g,c,c); //Outer ears ellipse(40,25,15,b); ellipse(c,25,15,b); //Inner ears fill(#FF9999); ellipse(40,25,7,30); ellipse(c,25,7,30); //Outer eyes fill(-1); ellipse(40,g,10,10); ellipse(c,g,10,10); //Inner eyes fill(0); ellipse(40,g,5,5); ellipse(c,g,5,5); //Mouth stroke(0); line(b,80,b,85); noFill(); arc(53,85,5,5,0,PI); arc(48,85,5,5,0,PI); ``` [![enter image description here](https://i.stack.imgur.com/NerSg.png)](https://i.stack.imgur.com/NerSg.png) [Answer] # [PostScript](https://de.wikipedia.org/wiki/PostScript), ~~688~~ ~~484~~ ~~468~~ ~~439~~ 359 bytes Golfed version: ``` <</F{closepath fill}/C{0 360 arc}/c{curveto}/s{setrgbcolor}/M{moveto}/h{7 15 M 7 25 1 25 1 15 c 1 5 7 5 7 15 c F 1 .5 .5 s 6 15 M 6 22 2 22 2 15 c 2 8 6 8 6 15 c F 1 1 1 s 4 3 2 C F 0 0 0 s 4 3 1 C F 0 -3 M 0 -5 lineto stroke 1 -5 1 180 0 arc stroke}>>begin 80 60 translate 5 5 scale .2 setlinewidth 1 .7 .7 s 0 0 10 C F gsave h grestore -1 1 scale h showpage ``` Ungolfed version: ``` % define some short-named procedures for later use << /F {closepath fill} /C {0 360 arc} /c {curveto} /s {setrgbcolor} /M {moveto} /h { % procedure for drawing one half 7 15 M 7 25 1 25 1 15 c % ellipse for outer ear 1 5 7 5 7 15 c F 1 .5 .5 s % dark pink 6 15 M 6 22 2 22 2 15 c % ellipse for inner ear 2 8 6 8 6 15 c F 1 1 1 s % white 4 3 2 C F % circle for outer eye 0 0 0 s % black 4 3 1 C F % circle for inner eye 0 -3 M 0 -5 lineto stroke % line for upper mouth 1 -5 1 180 0 arc stroke % arc for lower mouth } >> begin 80 60 translate % over-all shift 5 5 scale % over-all scale .2 setlinewidth 1 .7 .7 s % light pink 0 0 10 C F % large circle for head gsave h grestore % right half -1 1 scale h % left half showpage ``` Result: [![bunny](https://i.stack.imgur.com/10fuy.png)](https://i.stack.imgur.com/10fuy.png) [Answer] ## SVG (HTML5), 415 bytes ``` <svg width=48 height=80><g fill=#fdd><circle cx=24 cy=52 r=24 /><ellipse cx=12 cy=16 rx=8 ry=16 /><ellipse cx=36 cy=16 rx=8 ry=16 /></g><g fill=#f99><ellipse cx=12 cy=16 rx=4 ry=12 /><ellipse cx=36 cy=16 rx=4 ry=12 /></g><g fill=#fff><circle cx=16 cy=44 r=6 /><circle cx=32 cy=44 r=6 /></g><circle cx=16 cy=44 r=3 /><circle cx=32 cy=44 r=3 /><path stroke=#000 fill=none d=M18,60a3,3,180,0,0,6,0v-6v6a3,3,180,0,0,6,0 ``` Keeping the height below 100 to help save precious bytes, but still the longest... [Answer] # Java, ~~508~~ 472 bytes ``` import java.awt.*;v->new Frame(){Graphics2D G;Color C;void d(int...d){G.fillOval(d[0],d[1],d[2],d[3]);}{add(new Panel(){public void paint(Graphics g){G=(Graphics2D)g;G.setPaint(C.PINK);d(0,65,99,99);d(22,0,24,75);d(58,0,24,75);G.setPaint(C.MAGENTA);d(27,5,14,65);d(63,5,14,65);G.setPaint(C.WHITE);d(24,85,20,20);d(60,85,20,20);G.setPaint(C.BLACK);d(30,91,8,8);d(66,91,8,8);G.drawArc(41,124,9,11,0,-180);G.drawArc(50,124,9,11,0,-180);G.drawLine(50,119,50,130);}});show();}} ``` This is the resulting bunny: [![enter image description here](https://i.stack.imgur.com/0GmeC.png)](https://i.stack.imgur.com/0GmeC.png) **Explanation:** ``` import java.awt.*; // Required imports for almost everything v-> // Method with empty unused parameter and no return-type new Frame(){ // Create a new Frame Graphics2D G; // Graphics2D-object on class-level Color C; // Color variable to save bytes with static calls void d(int...d){ // Create an inner method with integer-varargs as parameter G.fillOval( // Draw a circle/oval, filled with the current color: d[0],d[1], // With the first two integers as starting x,y position d[2], // Third as width d[3]));} // And fourth as height { // Then open an initializer-block inside the Frame-class add(new Panel(){ // And add a Panel to the Frame we can draw on public void paint(Graphics g){ // Override the Panel's paint-method G=(Graphics2D)g; // Set the Graphics2D-object with the parameter G.setPaint(C.PINK); // Set the color to pink (255,175,175) d(0,65,99,99); // Draw the head circle d(22,0,24,75); // Draw the left ear d(58,0,24,75); // Draw the right ear G.setPaint(C.MAGENTA); // Change the color to magenta (255,0,255) d(27,5,14,65); // Draw the inner part of the left ear d(63,5,14,65); // Draw the inner part of the right ear G.setPaint(C.WHITE); // Change the color to white (255,255,255) d(24,85,20,20); // Draw the left eye d(60,85,20,20); // Draw the right eye G.setPaint(C.BLACK); // Change the color to black (0,0,0) d(30,91,8,8); // Draw the left pupil d(66,91,8,8); // Draw the right pupil G.drawArc(41,124,9,11,0,-180); // Draw the left mouth elipse G.drawArc(50,124,9,11,0,-180); // Draw the right mouth elipse G.drawLine(50,119,50,130);}}); // Draw the line of the mouth show();}} // And finally show the Frame on the screen ``` [Answer] # [Racket](https://racket-lang.org) – 597 bytes ``` #!racket/gui (require pict)(show-pict(let*([c cc-superimpose][f filled-ellipse][h hc-append][v vc-append][r rotate][p"pink"][E(c(f 85 140 #:color p)(f 50 90 #:color"maroon"))][I(c(f 60 60 #:color"white")(f 30 30 #:color"brown"))][M(dc(λ(D X Y)(define-syntax-rule(S a ...)(send D a ...))(let([P(S get-pen)][B(S get-brush)])(S set-brush(new brush%[style 'transparent]))(S set-pen(new pen%[width 5]))(S draw-arc(+ 1 X)Y 48 48(- pi)0)(S set-brush B)(S set-pen P)))50 50)])(v -40(h 20(r E .2)(r E -.2))(c(f 220 220 #:color p)(v 20(h 40 I I)(v -25(filled-rectangle 8 30 #:color"darkbrown")(h M M))))))) ``` [Here's the TIO link.](https://tio.run/##VVHNTuMwEL7zFEMQ2vEiF5NtVl2OCA49VELaCyjKwTjTxmpwzMRp4Nl4B16pOGkLxRpr5ps/e75hbdYUttuzUx6ty1VnT5DppbNM4K0JAtuq6eVgYk3hN@YGjJFt54nts29aKvIlLG1dUymprq0fPBVURmrvyZVFvoHNN2DgJugQc3zirVsnRX6HBpcwy@BqquDs2jR1w@BF9GUK/n25kmfNTeMSIYp8Ppb8VYMcwn1lAyVD2R81yMH/xE2/q1pgafDjHW/hAR4FlrS0jmT75oJ@ldzVhP9Bw2QyiUPHz8LtHolhcszvY3hFQcZBYrObPXrirq1EISJsDxAd9TBa53kb3mqCX4G1a71mcqEQh@TYaUyN@jzvbRkqyHbRknUvNRu8gCt4EI8wnUVBGXci1I@34OaoG9wLISJrmRp@tAE5VVhBqpDhDiapGLWMhhgJTFM13iPSN0N2BXETc5iPLdIM9@tlMkG7VRxndkxwqXm9JzlWLmAhdme7/QQ) Note that TIO can not display the `pict`, hence why it shows an error. Feel free to use the link as a means to verify byte count and/or copy code into a local file. --- ## Screenshot from DrRacket [![Screenshot of the Easter Bunny drawn in a new window; ran in DrRacket.](https://i.stack.imgur.com/YCgeB.png)](https://i.stack.imgur.com/YCgeB.png) Yeah, I'm using Light Theme at 12am xD ## Explanation of the code This explanation uses the ungolfed version of the program, but I will explain what I did to golf it up along the way. On line one, we set the language to `racket/gui`. This us to create GUIs and use some pieces of Racket's canvas API (we use the `brush%` and `pen%` classes to make new styles for them). Right underneath the language statement, we import the `pict` package. This package sort of works like JavaScript's Canvas API. ``` #lang racket/gui (require pict) (show-pict ...) ``` We then start the program by calling `show-pict` which renders a picture to the screen. While Racket has already made picts for fishes and files, it doesn't have a pict for an easter bunny. So let's make one! To make the eyes and the ears, we can use filled ellipses. In pict, they are defined simply as `filled-ellipse`. The function receives the following input: ``` (filled-ellipse width height #:color [fill-color]) ``` Now we want to center an ellipse inside of another (the outer one for the outer ear/eyeball and the inner ellipse for the inner ear/pupil). To that, we simply use the function `cc-superimpose` (standing for "align center x, align center y, on top of another pict"). ``` (let ([ear (cc-superimpose (filled-ellipse 85 140 #:color "pink") (filled-ellipse 50 90 #:color "maroon"))] ;; Inner ear [eye (cc-superimpose (filled-ellipse 60 60 #:color "white") (filled-ellipse 30 30 #:color "brown"))]) ;; Eye pupil ...)) ``` Now comes a trickier part: the mouth. I say it is tricky because it involves using the canvas context API to draw arcs. `pict` provides a neat little function called `dc` which allows use to access the `d`rawing `c`ontext for the canvas. It accepts three arguments: a function that draws the pict using the context, width and height. The function that it receives must also receive three arguments, but this time, they are: the drawing context and the current `x` and `y` positions for the pen and brush. ``` (dc (lambda (dc dx dy) ...) width height) ``` To tell the context to draw something or to configure the pen and brush, we use the `send` function to call the one of the object's methods. In our case, we set the brush to `'transparent`. ``` (send dc set-brush (new brush% [style 'transparent])) ``` Now that the basic functionality is mostly explained, let's create the mouth once and for all. ``` (let ([ear (cc-superimpose (filled-ellipse 85 140 #:color "pink") (filled-ellipse 50 90 #:color "maroon"))] ;; Inner ear [eye (cc-superimpose (filled-ellipse 60 60 #:color "white") (filled-ellipse 30 30 #:color "brown"))] ;; Eye pupil [mouth (dc (λ (dc dx dy) ;; Save old pen/brush state (define old-pen (send dc get-pen)) (define old-brush (send dc get-brush)) ;; Set new styles for pen/brush (send dc set-brush (new brush% [style 'transparent])) (send dc set-pen (new pen% [width 5])) ;; Draw an arc of width/height 48 at (dx+1,dy) counter-clockwise (send dc draw-arc (+ 1 dx) dy 48 48 (- pi) 0) ;; Reset to default pen/brush for `dc` function (send dc set-brush old-brush) (send dc set-pen old-pen)) 50 50)]) ...)) ``` One thing to note is `(+ 1 dx)`. I had a rendering issue where the arc would be one pixel to the left of the nose, and this seemed to fix it. I think it might be caused from putting the arcs side-by-side using `hc-append`. Let's add these facial features to the actual face. ``` (let ([ear (cc-superimpose (filled-ellipse 85 140 #:color "pink") (filled-ellipse 50 90 #:color "maroon"))] ;; Inner ear [eye (cc-superimpose (filled-ellipse 60 60 #:color "white") (filled-ellipse 30 30 #:color "brown"))] ;; Eye pupil [mouth (dc (λ (dc dx dy) ;; Save old pen/brush state (define old-pen (send dc get-pen)) (define old-brush (send dc get-brush)) ;; Set new styles for pen/brush (send dc set-brush (new brush% [style 'transparent])) (send dc set-pen (new pen% [width 5])) ;; Draw an arc of width/height 48 at (dx+1,dy) counter-clockwise (send dc draw-arc (+ 1 dx) dy 48 48 (- pi) 0) ;; Reset to default pen/brush for `dc` function (send dc set-brush old-brush) (send dc set-pen old-pen)) 50 50)]) ;; Ears + Face (vc-append -40 ;; Ears (hc-append 20 (rotate ear .2) (rotate ear -.2)) ;; Face (cc-superimpose (filled-ellipse 220 220 #:color "pink") (vc-append 20 ;; Eyes (hc-append 40 eye eye) (vc-append -25 ;; Nose (filled-rectangle 8 30 #:color "darkbrown") ;; Mouth (hc-append mouth mouth)))))) ``` The `vc-append` appends picts vertically, and `hc-append` appends picts horizontally. Both functions receive an optional spacing parameter as it's first argument. So the arcs for the mouth have no space between them, but the eyes have 40 pixels between them. To fit the nose and the mouth snuggly together, I used -25 as the spacing. Putting the program together is as simple as placing the `let` block inside of `show-pict`. ## A cleaner more declarative way ``` #lang racket/gui (require pict) (define ear (cc-superimpose (filled-ellipse 85 140 #:color "pink") (filled-ellipse 50 90 #:color "maroon"))) (define ears (hc-append 20 (rotate ear .2) (rotate ear -.2))) (define eye (cc-superimpose (filled-ellipse 60 60 #:color "white") (filled-ellipse 30 30 #:color "brown"))) (define eyes (hc-append 40 eye eye)) (define nose (filled-rectangle 8 30 #:color "darkbrown")) (define mouth (dc (λ(dc dx dy) (define old-pen (send dc get-pen)) (define old-brush (send dc get-brush)) (send dc set-brush (new brush% [style 'transparent])) (send dc set-pen (new pen% [width 5])) (send dc draw-arc (+ 1 dx) dy 48 48 (- pi) 0) (send dc set-brush old-brush) (send dc set-pen old-pen)) 50 50)) (define nose+mouth (vc-append -25 nose (hc-append mouth mouth))) (define eyes+nose+mouth (vc-append 20 eyes nose+mouth)) (define face (cc-superimpose (filled-ellipse 220 220 #:color "pink") eyes+nose+mouth)) (define easter-bunny (vc-append -40 ears face)) (show-pict easter-bunny) ``` ## How I golfed the code While the `let` statement is cool, its brother `let*` is cooler. A normal `let` statement doesn't allow other variables inside of its binding block to see each other. but this isn't the case with `let*`: ``` ;; Normal let - Can't use `f` in let binding (let ([f filled-ellipse] [red-circle (filled-ellipse 50 50 #:color "red")]) (cc-superimpose (f 50 50 #:color "yellow") red-circle)) ;; Cooler let* (let ([f filled-ellipse] [red-circle (f 50 50 #:color "red")]) (cc-superimpose (f 50 50 #:color "yellow") red-circle)) ``` Because I use `cc-superimpose`, `vc-append`, `hc-append`, etc. a lot, I used `let*` so that I could bind them to shorter names: ``` (let* ([c cc-superimpose] [f filled-ellipse] [h hc-append] [v vc-append] [r rotate] [p "pink"]) ...) ``` I then proceeded to rename all variables to shorter names, ear becomes `E`, eye becomes `I`, etc. After that was done, I started to ponder what I could do with the dreaded mouth `send`s. I ended up creating a macro :) ``` (let* (... [M (dc (λ (D X Y) ;; This macro will replace (S get-pen) with (send D get-pen) (define-syntax-rule (S a ...) (send D a ...)) (let ([P (S get-pen)] [B (S get-brush)]) (S set-brush (new brush% [style 'transparent])) (S set-pen (new pen% [width 5])) (S draw-arc (+ 1 X) Y 48 48 (- pi) 0) (S set-brush B) (S set-pen P))) 50 50)]) ...) ``` Once that was done, I deleted all unnecessary spaces. The golfed code and the code I used in the explanation are basically identical. If you don't want to open a new window, simply remove the call to `show-pict`. Pict only displays well in DrRacket. If you try to print a pict to a console like CMD or terminal, you'd see `#<pict>` which is Racket's way of telling you "Yes the statement returned something, but I can only tell you what type of object it returned. ## Conclusion It's 2am now as I write this conclusion, hope everyone enjoyed this little tutorial-ish explanation! **Have an amazing week!** [Answer] # [Scala](http://www.scala-lang.org/), with [Java AWT](https://docs.oracle.com/javase/8/docs/api/java/awt/package-frame.html)(Abstract Window Toolkit). 714 bytes Port of [@Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/184696/110802) in Scala. --- Golfed Scala code. ``` import java.awt._;import java.awt.event._;object M extends App{new Frame{def d(g:Graphics2D,x:Int,y:Int,w:Int,h:Int)=g.fillOval(x,y,w,h);add(new Panel{override def paint(g:Graphics){val g2=g.asInstanceOf[Graphics2D];g2.setPaint(Color.PINK);d(g2,0,65,99,99);d(g2,22,0,24,75);d(g2,58,0,24,75);g2.setPaint(Color.MAGENTA);d(g2,27,5,14,65);d(g2,63,5,14,65);g2.setPaint(Color.WHITE);d(g2,24,85,20,20);d(g2,60,85,20,20);g2.setPaint(Color.BLACK);d(g2,30,91,8,8);d(g2,66,91,8,8);g2.drawArc(41,124,9,11,0,-180);g2.drawArc(50,124,9,11,0,-180);g2.drawLine(50,119,50,130);}});setSize(new Dimension(200,200));setVisible(true);addWindowListener(new WindowAdapter{override def windowClosing(e:WindowEvent):Unit=System.exit(0);})}} ``` This is the resulting bunny. [![enter image description here](https://i.stack.imgur.com/GbPz3.png)](https://i.stack.imgur.com/GbPz3.png) Ungolfed Scala code. ``` import java.awt._ import java.awt.event._ object ScalaMain extends App { new Frame { def d(g: Graphics2D, x: Int, y: Int, w: Int, h: Int): Unit = g.fillOval(x, y, w, h) add(new Panel { override def paint(g: Graphics): Unit = { val g2d = g.asInstanceOf[Graphics2D] g2d.setPaint(Color.PINK) d(g2d, 0, 65, 99, 99) d(g2d, 22, 0, 24, 75) d(g2d, 58, 0, 24, 75) g2d.setPaint(Color.MAGENTA) d(g2d, 27, 5, 14, 65) d(g2d, 63, 5, 14, 65) g2d.setPaint(Color.WHITE) d(g2d, 24, 85, 20, 20) d(g2d, 60, 85, 20, 20) g2d.setPaint(Color.BLACK) d(g2d, 30, 91, 8, 8) d(g2d, 66, 91, 8, 8) g2d.drawArc(41, 124, 9, 11, 0, -180) g2d.drawArc(50, 124, 9, 11, 0, -180) g2d.drawLine(50, 119, 50, 130) } }) setSize(new Dimension(200, 200)) setVisible(true) addWindowListener(new WindowAdapter { override def windowClosing(e: WindowEvent): Unit = System.exit(0) }) } } ``` ]
[Question] [ In Australian Football, goals are worth 6 points and behinds are worth 1 point. Scores may include the number of goals and behinds, as well as the total score. Given the number of goals and behinds for two different teams, determine which team won the game. Take four integers `g1, b1, g2, b2` as input, and output two distinct values for whether the first team or the second team inputted won. Input format is flexible, but input order must allow it to be obvious which team is first. For example, `g1, g2, b1, b2` would be allowed, but `b1, g2, g1, b2` would not. ## Test Cases Test cases will use `true` for the first team winning and `false` for the second team winning. Input is in the format `(g1,b1),(g2,b2)`. ``` (1,0),(0,1) true (2,0),(0,11) true (10,8),(11,1) true (0,0),(1,0) false (100,100),(117,0) false (7,7),(5,12) true (2,0),(0,13) false ``` As an example, for input `(10,8),(11,1)`, team 1 scored 10 goals and 8 behinds, for a total of \$10\*6+8\*1=68\$ points, while team 2 scored \$11\*6+1\*1=67\$ points, so team 1 wins. No input will be a draw - your program's behavior on draw input does not matter. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḅ6M ``` A monadic Link accepting a list of lists of integers, `[[g1,b1],[g2,b2]]`, which yields a list `[1]` or `[2]`. (Draws would yield `[1,2]`) ...Or a full program printing `1` or `2`. **[Try it online!](https://tio.run/##y0rNyan8///hjlYz3////0dHG@kYxOpEG@gYGsfGAgA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjlYz3/9HJz3cOeNR05qjew63A6ksIH7UMEdB107hUcPcyP//o6OjDXUUDGJ1FKINdBQMY2O5dKKjjZBEoEKGQLYFSMzQEK7MAKoMbABUFUiLAUTU0BwuDmSZg8RMgbJGmHYYA4ViAQ "Jelly – Try It Online"). ### How? ``` ḅ6M - Link: list of lists of integers, X 6 - literal six ḅ - convert (X) from base 6 (vectorises) M - maximal indices ``` [Answer] # [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), 9 DECLEs1 ≈ 12 bytes A routine taking input in **R0** (\$g\_1\$), **R1** (\$b\_1\$), **R2** (\$g\_2\$) and **R3** (\$b\_2\$) and setting the sign flag if the 2nd team wins, or clearing it otherwise. ``` **275** PSHR R5 ; push return address **110** SUBR R2, R0 ; R0 -= R2 **082** MOVR R0, R2 ; R2 = R0 **04C** SLL R0, 2 ; R0 <<= 2 **0D0** ADDR R2, R0 ; R0 += R2 **0D0** ADDR R2, R0 ; R0 += R2 **0C8** ADDR R1, R0 ; R0 += R1 **118** SUBR R3, R0 ; R0 -= R3 **2B7** PULR R7 ; return ``` The CP-1610 has no multiplication instruction and may only shift by 1 or 2 positions at a time, so we compute the following expression instead: ``` ((R0 - R2) << 2) + (R0 - R2) + (R0 - R2) + R1 - R3 ``` ### Full test code ``` ROMW 10 ; use 10-bit ROM width ORG $4800 ; map this program at $4800 ;; ------------------------------------------------------------- ;; ;; test code ;; ;; ------------------------------------------------------------- ;; main PROC SDBD ; set up an interrupt service routine MVII #isr, R0 ; to do some minimal STIC initialization MVO R0, $100 SWAP R0 MVO R0, $101 EIS ; enable interrupts SDBD ; R4 = pointer to test cases MVII #@@data, R4 MVII #$200, R5 ; R5 = backtab pointer @@loop PSHR R5 ; save R5 on the stack MVI@ R4, R0 ; load the next test case MVI@ R4, R1 ; into R0 .. R3 MVI@ R4, R2 MVI@ R4, R3 CALL score ; invoke our routine BMI @@true MVII #$80, R0 ; set output to '0' B @@output @@true MVII #$88, R0 ; set output to '1' @@output PULR R5 ; restore R5 MVO@ R0, R5 ; draw the output SDBD ; was it the last test case? CMPI #@@end, R4 BLT @@loop ; if not, jump to @@loop DECR R7 ; loop forever @@data DECLE 1, 0, 0, 1 ; test cases DECLE 2, 0, 0, 11 DECLE 10, 8, 11, 1 DECLE 0, 0, 1, 0 DECLE 100, 100, 117, 0 DECLE 7, 7, 5, 12 DECLE 2, 0, 0, 13 @@end ENDP ;; ------------------------------------------------------------- ;; ;; ISR ;; ;; ------------------------------------------------------------- ;; isr PROC MVO R0, $0020 ; enable display CLRR R0 MVO R0, $0030 ; no horizontal delay MVO R0, $0031 ; no vertical delay MVO R0, $0032 ; no border extension MVII #$D, R0 MVO R0, $0028 ; light-blue background MVO R0, $002C ; light-blue border JR R5 ; return from ISR ENDP ;; ------------------------------------------------------------- ;; ;; routine ;; ;; ------------------------------------------------------------- ;; score PROC PSHR R5 ; push the return address SUBR R2, R0 ; R0 -= R2 MOVR R0, R2 ; R2 = R0 SLL R0, 2 ; R0 <<= 2 ADDR R2, R0 ; R0 += R2 ADDR R2, R0 ; R0 += R2 ADDR R1, R0 ; R0 += R1 SUBR R3, R0 ; R0 -= R3 PULR R7 ; return ENDP ``` ### Output [![output](https://i.stack.imgur.com/A6UrN.gif)](https://i.stack.imgur.com/A6UrN.gif) *screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)* --- *1. A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This routine is 9 DECLEs long.* [Answer] # [International Phonetic Esoteric Language](https://github.com/bigyihsuan/International-Phonetic-Esoteric-Language), 12 bytes (WIP language) (OLD) ``` 6ɪθɪt6ɪθɪtʈo ``` Outputs `1` for true and `0` for false. No TIO interpreter yet, but is runnable by cloning the repository above, and calling `python main.py "code here"`. The TL;DR of the language is that it's a stack-based language where every instruction is a character from the [International Phonetic Alphabet](https://en.wikipedia.org/wiki/International_Phonetic_Alphabet). Takes in arguments as 4 inputs from STDIN, in the order `g1, b1, g2, b2`. Might be golfed down to less than 12 bytes once loops are fully implemented. ``` 6ɪθɪt6ɪθɪtʈo 6 ; Push 6 ɪ ; Take number input, push θ ; Pop 2, multiply, push ɪ ; Take number input, push t ; Pop 2, add, push 6 ; Push 6 ɪ ; Take number input, push θ ; Pop 2, multiply, push ɪ ; Take number input, push t ; Pop 2, add, push ʈ ; Pop 2, if a > b push 1, otherwise 0 o ; Pop, print ``` [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda g,b,G,B:6*g+b>6*G+B ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSFdJ0nHXcfJykwrXTvJzkzLXdvpf0FRZl6JRpqGoY4BEBpqanLBRIwgIshChgY6FkARFGVgRToGKKqAIiBsaI4ibq5jrmOqY2iEaYexpuZ/AA "Python 3 – Try It Online") Not incredibly interesting answer. [Answer] # [Cascade](https://github.com/GuyJoKing/Cascade), 16 bytes ``` #6& > |/ + * & ``` [Try it online!](https://tio.run/##S04sTk5MSf3/X9lMjcuOS6FGn0tBm0tLQe3/f0MFAyA0BAA "Cascade – Try It Online") Reuses the same `6*a+b` logic for both teams then prints whether the first scores higher than the other [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 22 bytes ``` (a,b,c,d)=>a*6+b>c*6+d ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9Wmpdsk5lXooOMk/Lzc@zSbP9rJOok6STrpGja2iVqmWkn2SUDyZT/1lzhRZklqRppGoYGOhY6hoY6hpqa1v8B "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 34 bytes ``` import StdEnv $a b c d=a*6+b>c*6+d ``` [Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r4xLJVEhSSFZIcU2UctMO8kuGUim/A8uSQSqsFVQUTBUMABCw///ktNyEtOL/@t6@vx3qcxLzM1MLgYA "Clean – Try It Online") Defines `$ :: Int Int Int Int -> Bool` with arguments taken like `$ g1 b1 g2 b2` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes ``` *×6+*>*×6+* ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf6/B0M20tOwj135qrOLFSIU2hJtcqXT8mRVtfIS2/SCEnMy@1@L@GoY6Bpo6GgY6hpgIUlBSVpnJpGMHE4RIQcUMDHQughKEhXAdE3ACsHmQazJy0xJxisAagIQZgSUNzsDRUwlzHHChoqmNopIndZmNNZJMA "Perl 6 – Try It Online") Takes input as 4 integers, and basically just does as the question asks [Answer] # [J](http://jsoftware.com/), 12 bytes ``` >&(1#.6 1*]) ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7dQ0DJX1zBQMtWI1/2tyKXClJmfkKxgCVaQBsSGEawTjQvmGBgoWQAFDQ5gCA7ACoC6YvAEYg5SYwwTNgTBNwVTB0EgBzVTj/wA "J – Try It Online") [Answer] # [33](https://github.com/TheOnlyMrCat/33), 22 bytes ``` 6OxcOasz6OxcOaclmzh1co ``` [Try it online!](https://tio.run/##Mzb@/9/MvyLZP7G4CkIn5@RWZRgm5///b6RgwGWgYGgMAA "33 – Try It Online") Takes the input as 4 delimited integers, and returns 0 for the first team winning, 1 for the second. ## Explanation: ``` 6Oxc | Multiplies the first number by 6 Oa | Adds the second number 6Oxc | Multiplies the third number by 6 Oa | Adds the fourth number sz clmz | Subtract this from the first team's score h1co | Print 0 if the first team's score is greater, 1 otherwise ``` -4 bytes if nondistinct results are allowed: ``` 6OxcOasz6OxcOaclmo ``` Will output the score difference; positive results mean the first team win, negative means the second team win. [Answer] # [Scala](http://www.scala-lang.org/), 11 bytes ``` _*6+_>_*6+_ ``` [Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJmnUM2VkpqmkAtkaiQWpRdbKTgWFSVWRgeXFGXmpcdqWoXmZZYo2AKVlSXmKBQn5xelWml45pXoIGFNWzun/Pyc1MQ82//xWmba8XZg8j9XAdCMkpw8DbA2DUMdAyA01NREEzeCiGNKGBroWADFsWgBa9AxwKIDKA7ChuZYZM11zHVMdQyNcLnAGChRy1X7HwA "Scala – Try It Online") Takes 4 Integers in the order of `g1 b1 g2 b2`. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~45~~ ~~38~~ ~~36~~ ~~32~~ ~~29~~ 28 bytes ``` ,[>,[<++++++>-],]-[[-<]>>]>. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9pGGwzsdGN1YnWjo3VtYu3sYu30/v83NzAwBAA "brainfuck – Try It Online") Thanks to @Jo King for -8 bytes Input is b1, g1, b2, g2 (goals and behinds are exchanged) Prints þ, if team 1 won. Prints null, if team 2 won. code: ``` [tape: p1, p2, print marker] [Get input and calculate scores] , input behinds of team 1 [ while input >, go to next cell and input goals of team [<++++++>-] add it 6 times to behinds ,] repeat this with the second pair of values [Determine, which one is better] - set print marker [ while score of both teams is greater than zero [-<] decrement and go to previous cell (team 1 or empty cell/in the first run, it will decrement the print marker a second time) >> return to team 2 (or two cells to the right of the first team that became 0) ] > go one cell right. If team 1 won, we are at the print marker now If team 2 won, we are one cell right of the print marker . Print that ``` [Answer] # Scratch 3.0 ~~17~~ 16 blocks, ~~160~~ 143 bytes *Score comes from proposed scoring method [here](https://codegolf.meta.stackexchange.com/a/5013/78850)* *1 block/17 bytes saved thanks to @A* (or Uzer\_A on scratch)\_ [![Program in better blocks](https://i.stack.imgur.com/Xw3TN.png)](https://i.stack.imgur.com/Xw3TN.png) [Try it on Scratch](https://scratch.mit.edu/projects/332406370/) *As Scratchblocks*: ``` when gf clicked repeat(2 ask[]and wait set[m v]to((answer)*(6) ask[]and wait change[m v]by(answer add(m)to[x v end say<(item(1) of [x v]) > (m) ``` ## Answer History [![Program in blocks](https://i.stack.imgur.com/naYcR.png)](https://i.stack.imgur.com/naYcR.png) Pretty much a port of my Keg answer. [Try it on Scratch](https://scratch.mit.edu/projects/332039766/) Input is in the form of `g1, b1, g2, b2` *In Scratchblocks syntax* ``` when gf clicked repeat(0 set[m v]to(0 ask[]and wait change[m v]by((answer)*(6) ask[]and wait change[m v]by(answer add(m)to[x v end say<(item(1) of [x v]) > (m) ``` Now I know what you're saying... *why golf in scratch?!?* Well, it's fun. That's why. Also, Scratch is unique in that it isn't very often featured here on CGCC. [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 10 bytes (SBCS) ``` (2|¿¿6*+)> ``` [Try it online!](https://tio.run/##y05N//9fw6jm0P5D@820tDXt/v83NDDgAmEgaWgOAA "Keg – Try It Online") As an Australian, I approve of this question. Input taken as: ``` b1 g1 b2 g2 ``` And 0 means team 2 and 1 means team 1 ## Explained ``` (2| #twice ¿¿ #get input in the form of bn, gn where n is the team number *6+ #multiply the goals by 6 and add the values )> #compare the two values to determine the winner ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 6δβZk ``` Input as a nested list `[[g1,b1],[g2,b2]]`. Output `0` if team 1 wins and `1` if team 2 wins. -1 byte thanks to *@Grimy* for reminding me about `δ`. [Try it online](https://tio.run/##yy9OTMpM/f/f7NyWc5uisv//j4421DGI1Yk20DGMjQUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/s3Nbzm2Kyv6v8z86OtpQxyBWJ9pAxzA2VkchOtoIxoXyDQ10LIAChoYwBQZgBSBdUHmgWgOwkKE5TNBcxxwoYKpjaIRmqHFsbCwA). **Explanation:** Apparently arbitrary base conversion on nested lists doesn't work without an explicit ~~map~~ outer product. ``` δβ # Apply arbitrary base-conversion double-vectorized, 6 # using the (implicit) input-list of lists and 6 as base # (i.e. [a,b] becomes 6a+b (or to be more precise: 6¹a + 6⁰b)) Z # Get the maximum of this mapped list (without popping the list itself) k # And get the 0-based index of this maximum in the mapped list # (after which the top of the stack is output implicitly as result) ``` [Answer] # Zsh, 19 bytes [try it online!!](https://tio.run/##qyrO@J9fpaFZ/V9Dw0xLxVBbxcgOSBtrq5hoav5PTc7IV1Cx56rlyq9SMFQwAEJDENMIwgSzDQ0ULIBMiARYWMEAIm4AwYbmEAFzIDRVMDRCMsD4PwA) ``` ((6*$1+$2>6*$3+$4)) ``` Input order is `g1 b1 g2 b2`. Exit codes `0==true` and `1==false` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~39~~ ~~35~~ ~~31~~ 26 bytes ``` e(a,b,c,d){a=(a-c)*6>d-b;} ``` 0 is false 1 is true Input to function is (g1, b1, g2, b2) Thanks to Doorknob for -5 bytes [Try it online!](https://tio.run/##fY5BCsIwEEXX5hShIiQysUlFI1R7EjfppGpAo2hdlZ49xrjUyGcGPm8eDIojYpg6j@en7ej20Vt3XZya0DEDLSBYPpgdMwL5fN1Y0dZjcL6nF@M843Qgk9s99gMrZnbvC@iYAhmjOK@/WfVhv6GSsIksoyYRZMaM7D1KZy40aFiBqv59tUywLKlKkTFxEzKGFw "C (gcc) – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 62 bytes ``` ([((({})({}){}){}{}[(({})({}){}){}{}]<(())>)(<>)]){({}())<>}{} ``` Outputs `1` if the first team lost, and `0` if they won (or tied). [Try it online!](https://tio.run/##SypKzMzTTctJzP7/XyNaQ0OjulYThMGoujYaXSDWRkNDU9NOU8PGTjNWsxooA@Ta2AFl/v83UjAAQkNjAA "Brain-Flak – Try It Online") ``` # Input: G B g b ( <(())>) # Push 1 under... ({})({}){}){}{} # 6G + B [ ] # Minus (({})({}){}){}{} # 6g + b <> # Switch stacks ([( ( )]) # Push 0 under -(6G+B-6g+b) ({}())<> # Add 1 and switch stacks... { } # until one stack reaches 0 {} # Pop, leaving either 1 or 0 ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 35 bytes ``` param($g,$b,$h,$c)$g*6+$b-gt$h*6+$c ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVdRyVJRyVDRyVZUyVdy0xbJUk3vUQlA8RK/v//vzkQmv43NAIA "PowerShell – Try It Online") [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 751 bytes ``` the game:a game o soccer for a moment of my fun,i kicked my leg o,i hurt a player o.m.gee,o no suddenly i then apologized a little o.m.gee,o no but really,i loved a good soccer battle a game i am doing,i love it there is a game,a twenty-to-one unwinnable match(as we called it,i mean)a match we won a wonder of an event i saw i played,i go in again i am happy in a match-up of teams,i am pumped then o,a coach i saw played soccer i know i do admire a game o soccer o,a match was not a bummer,and also i am making in an extra score i think i saw a split net,a hole i ripped out a net i am ready to win a match o,my people and i love a sport,a bit o soccer i am going in a game,i score,i win o really,i am doing a game o soccer play ball i am gonna wi-n ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?ZVLbjpwwDH3PV/ixlZhVL2/9G0M8IZrEjkJYlv789gQYjdoKiUBiH59L2iwUOMsvPhYyWmyapLq7VWLKlkUb2Z3yTvdVh0iPOD3E9/8kwRl25rU21JbEOxrtLb8FkcFIzS2r96Jpp0htFiUulizE3wBgSrG1JH83jGujKpzSDuBk70dhMPMXLxr5aLroRuJM3qKGq5xic5hU8bHQWTQwtQ0q9luzm6nQqltU5TEJZW7T/IUX2oQmTMW42ACVhfUrn8f9bDPFSLw9KMANVpL37kykhTcXT/EencEoQmfgqO5gN3Mp@7F3wt3W0hGacF6Go6KsuYh3h0EGtpMxph7IF@4zFLivtuHIG7HPETL/za0DXLQhS60nM645Sx1YYWZa7HQt8wO2HcQg5qNVpmWyKq5HFfVxEcBuQVCk0oA8W@qm11jAmGzt6Dg5lSI3v1Mz2l5qwQc3pYgVNHYCV0wd1mqHHAFuL4HACfYkduYXT2JYAezsdT@e2f9nQncNNyWlJyDiRvNNP3@4b3i@//wc2f8B) Boy, this was a tough one to write. Input is in the following format: ``` g1 b1 g2 b2 ``` This gives the error code of "Mismatched IF/EIF" if the first team wins, and "Unexpected EOF" if the second team wins. (Incidentally, a tie is treated as the second team winning). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes ``` \d+ $* (1*), $1$1$1$1$1$1 (1*);\1$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi0vDUEtTh0vFEAHBQtYxhir//xvqGFgb6BhyGUFoQy5DAx0La0NDoJABUAgoDRQBShgA2YbmQJ65jrm1qY6hEUyHMQA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs `1` if the second team doesn't win and `0` if it does. Explanation: ``` \d+ $* ``` Convert the input to unary. ``` (1*), $1$1$1$1$1$1 ``` In each pair, multiply the first number by six and add the second. ``` (1*);\1$ ``` Check whether the second number is greater than the first. Alternatively, you could use `^(1*);\1` which would output `0` if the first team wins and `1` if it doesn't. [Answer] # [PHP](https://php.net/) (7.4), 32 bytes ``` fn($g,$b,$G,$B)=>$g+$b/6>$G+$B/6 ``` [Try it online!](https://tio.run/##bc/BCoMwDAbge58iSA6KQa1jOnA68OJDOA8qVgdDi7rT2LO7TmVOWEqh8OVvG9nI6XyRjWQMRTiJVseasCBMCGMjjLA2sbC9CBMTY9ubAtU3VsM4QAgpA1UpJ0ctnhGsZdsw9o9qUXfRjXfKHTop3NI7nZPk7G4W@X34hhV/NveXpj375NORuPv/5fVfh19dwpmaUXR9lZcN6Ouw@QDzyYDnHK/KpgP91o4GCt2yrBUt0K6tFrDX9AY "PHP – Try It Online") [Answer] # [ABC-assembler](https://github.com/Ourous/abc-wrapper-linux), ~~111~~ 74 bytes ``` .o 0 4 iiii f subI pushI 6 mulI addI subI pushI 0 ltI .d 0 1 b rtn ``` [Try it online!](https://tio.run/##VZBbbsQgDEW/YRXewERkNOoC@pdVWLwyoXII4jFSpdk7JaSTafkxl2sf20ilLzIluyqysQ4py5gBsUf@ikwVRwYQBMScMNlcAh8MjCA4@1oDoInuYSMffEtBPmzdeueyUNKCfjMWUH9rsug8puC8bWkNJDooRdCSCOfi9c4QjaI4mx3RJ6ojKWyhXceze8yeP2GxFGyEvTC7zUPeOgnyYkHqXCSd3gEW/N2pDzc13BPu40uJXV3/eur0PnZ1Pea@gWvn@IW5dvbv08xZKmo6izhbCzUpjZn@W20NytPB6xu3pWqtF/UD "ABC-assembler – Try It Online") It doesn't use anything above the most basic stack operations: ``` subI | B = [g1-g2,b1,b2] pushI 6 | B = [6,g1-g2,b1,b2] mulI | B = [6*g1-6*g2,b1,b2] addI | B = [6*g1+b1-6*g2,b2] subI | B = [6*g1+b1-6*g2-b2] pushI 0 | B = [0,6*g1+b1-6*g2-b2] ltI | B = [0<6*g1+b1-6*g2-b2] ``` [Answer] # [Perl 5](https://www.perl.org/), 18 bytes ``` say<>*6+<>><>*6+<> ``` [Try it online!](https://tio.run/##K0gtyjH9/784sdLGTstM28bODkr//2/CZcxlxGX4L7@gJDM/r/i/rq@pnoGhAQA "Perl 5 – Try It Online") Input is line separated: ``` g1 b1 g2 b2 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes ``` 6#+#2>6#3+#4& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b730xZW9nIzkzZWFvZRO1/QFFmXkm0sq5dmoODcqyavkM1V7WhjgEQGtbqcFUbQZhgtqGBjgWQCZEAC@sYQMSBTBA2NIcImOuY65jqGBohGWBcy1X7HwA "Wolfram Language (Mathematica) – Try It Online") straightforward and boring [Answer] # Whitespace, 115 bytes ``` [S S S N _Push_0][S N S _Duplicate_0][T N T T _STDIN_as_integer][T T T _Retrieve_integer][S S S T T S N _Push_6][T S S N _Multiply][S N S _Duplicate][S N S _Duplicate][T N T T _STDIN_as_integer][T T T _Retrieve_integer][T S S S _Add][S N S _Duplicate][S N S _Duplicate][T N T T _STDIN_as_integer][T T T _Retrieve_input][S S S T T S N _Push_6][T S S N _Multiply][S N S _Duplicate][S N S _Duplicate][T N T T _STDIN_as_integer][T T T _Retrieve_input][T S S S _Add][T S S T _Subtract][N T T N _If_negative_jump_to_Label_NEGATIVE][S S S N _Push_0][T N S T _Print_as_integer][N N N _Exit_Program][N S S N _Label_NEGATIVE][S S S T N _Push_1][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Prints `0` if team 1 wins and `1` (could also be `-1` for the same byte-count) if team 2 wins. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDIAxJcnBBBhDhIAkUAn0IgBvG4QFo4QTJAANYNEgby//83NDDgAmNDcy4DAA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Integer g1 = STDIN as integer Integer t1 = g1*6 Integer b1 = STDIN as integer t1 = t1 + b1 Integer g2 = STDIN as integer Integer t2 = g2*6 Integer b2 = STDIN as integer t2 = t2 + b2 If(t1 - t2 < 0): Goto NEGATIVE Print 0 Exit program Label NEGATIVE: Print 1 (implicitly exit with an error) ``` One minor note: since the inputs are guaranteed to be \$\geq0\$, I'm using that to my advantage to re-use the inputs as heap-addresses for the subsequent inputs. With challenges which can have negative inputs I'd have to re-push `0` as heap-address, since heap-addresses cannot be negative. [Answer] # [Ruby](https://www.ruby-lang.org/), 21 bytes ``` ->a,b,x,y{b-y>6*x-=a} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ0mnQqeyOkm30s5Mq0LXNrH2f4FCWrShjgEQGsZygThGEA6UZ2igYwHkwCTBUjoGMDkgB4QNzWFC5jrmOqY6hkYoRhnH/gcA "Ruby – Try It Online") Worked around the boring solution, saved a byte and called it a day. [Answer] # [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 84 bytes Just the simple "multiply by 6, sum and compare" aproach, except the math support is extremelly lacking. ``` {@set*A argv.0,6}{@incbyargv.1 A}{@set*B argv.2,6}{@incbyargv.3 B}0{@ifB is lowerA}1 ``` Outputs `0` for false and `01` for true. --- Ungolfed: ``` {@// multiply the first argument by 6} {@set* teamA argv.0, 6} {@// add the 2nd argument to the previous result} {@inc by argv.1 teamA} {@// same as before, for argument 3 and 4} {@set* teamB argv.2, 6} {@inc by argv.3 teamB} {@echo 0} {@// alternative: teamA is greater than teamB} {@if teamB is lower than teamA} {@echo 1} {@/} ``` Everything should be clear with the comments (`{@// ... }`) added. [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Input as a 2D-array. Outputs `1` for team 1, `0` for a draw or `-1` for team 2. ``` mì6 rg ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bew2IHJn&input=WwpbMSwwXQpbMCwxXQpd) ``` mì6 rg :Implicit input of array m :Map ì6 : Convert from base-6 digit array r :Reduce by g : Sign of difference ``` [Answer] # [Go](https://golang.org/), 44 bytes ``` func f(a,b,x,y int)bool{return a*6+b>=x*6+y} ``` [Try it online!](https://tio.run/##S8//X5CYnJ2YnqqQm5iZx8WVmVuQX1SioJSWW6L0P600L1khTSNRJ0mnQqdSITOvRDMpPz@nuii1pLQoTyFRy0w7yc62AkhV1kIUgwzR0FSo5lJQUAAaoRdQBNSUk6eRpmGoo2AARoaamlhkDUAyYMLQHKgMqKb2PwA "Go – Try It Online") ]
[Question] [ ### Challenge Create a console program to display each byte of a file. --- ### Winning Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins. --- ### Rules * Program **must be a console application**, meaning that it will be ran from some sort of command-line interpreter; * Every byte must be uppercase hexadecimal, separated by a space, and it must be 2 digits; *(put number 0 before it if it has 1 digit)* * File **must be read** using IO or alternative, and not hard-coded; * File path must be specified as a **command-line argument or a user prompt (like STDIN)**; * **No [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) please**; --- ### Example test.txt (ends with LF) ``` Hello World! ``` ``` $ ./hexdump.exe test.txt 48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A ``` [Answer] # [C (gcc)](https://gcc.gnu.org/) on \*nix, ~~73~~ 71 bytes ``` i;main(c,v)int**v;{for(c=open(v[1],0);read(c,&i,1);printf("%02X ",i));} ``` [Try it online!](https://tio.run/##DcpBCoQwDADAr4igNFJFvQb/sSAeSmwloK10pR7Erxud81C9EIkwboa9Ip2A/VFVCS8XoqIh7NarNHaTbgGjNfN3StYd4B6/6VRetP0vyzUD4C0iDYXZNgeHh9xqlr/U5ws "C (gcc) – Try It Online") [Test suite](https://tio.run/##NYxBC8IgGEDv/ooPqdDh1rarW7e6dg0imJk2aepYtoLot5sdOj14PN5Z3Pt4lRLyJ@SvBGga2O530XArjCOSzdS4kGUzf2s/Edn6UTkyH6sTKymflLikZmVYRfk4pVITvCzrA2BmKOWfmF4IaTOotrO3oOzYISRFgA3gxU9jhIq1KPwj/EXs1TD4Lw) *-2 bytes thanks to Johan du Toit* This relies on `O_RDONLY == 0` and on `int_one == 1` where `int int_one; *(char*)&int_one = 1;`. [Answer] # [Ruby](https://www.ruby-lang.org/), 26 bytes ``` $<.bytes{|b|$><<"%02X "%b} ``` [Try it online!](https://tio.run/##TY7BCoMwEETv@YptULyUUnos0i/w2EOvG1ztwmJkEwNS@@1p9NTb8HjMjC5uzblqL26NFD6b26pH29r6enuBrd035w4hcZgRnqQU0GAihKgI0pA6irEggeTFQ/A6H85IU2SBAXVAkd05G0MQl5Jg5EU4FRKi8lTU3su@saNRuceEgNBzKIfwbmzXvD0cvSf4y/YH "Ruby – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~45~~ 40 bytes ``` "$(gc $args -ra|% *ay|%{'{0:X2}'-f+$_})" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lFIz1ZQSWxKL1YQbcosUZVQSuxska1Wr3awCrCqFZdN01bJb5WU@n/fw@g@nyF8PyinBRFrv96@nqZeQWlJXolmfkA) *-5 bytes thanks to mazzy* [Answer] # Java 11, ~~156~~ 154 bytes ``` import java.nio.file.*;interface M{static void main(String[]a)throws Exception{for(int b:Files.readAllBytes(Path.of(a[0])))System.out.printf("%02X ",b);}} ``` -2 bytes thanks *to @Holger*. [Try it online](https://tio.run/##DY3LigIxEEX3fkUUhES0RlzqSmHEjSC4GEFclN2JVk861STlC/HbY7aXc85t8I6Tpv7PmdqOo6imDBCIwZG3MFpQEBsdVlZt30lQqFJ3plq1SEHvJVK4HE9o5Br5kdTvs7KdEIe346iLq87zdQkliBbrpferl9ikdyhXYKfxOD0ZY/avJLYFvgl0JShOD4bT2UENxmez@Hxy3ljvWf1x9HW/l@EHKHQFLkdf) by using `./.input.tio` as argument file-path, which will have a given input as file-content. **Explanation:** ``` import java.nio.file.*; // Required import for Files and Paths interface M{ // Class static void main(String[]a) // Mandatory main method throws Exception{ // With mandatory thrown clause for the readAllBytes builtin a[0] // Get the first argument Path.of( ) // Get the file using that argument as path Files.readAllBytes( ) // Get all bytes from this file for(int b: ) // Loop over each of them: System.out.printf( // And print the current byte "%02X ",b);}} // As uppercase hexadecimal with leading 0 // and trailing space as delimiter ``` [Answer] # [PHP](https://php.net/), ~~60~~ ~~59~~ 54 bytes ``` <?=wordwrap(bin2hex(implode(file($argv[1]))),2,' ',1); ``` * -1 byte thanks to manassehkatz * -5 bytes thanks to Blackhole [Try it online!](https://tio.run/##K8go@P/fxt62PL8opbwosUAjKTPPKCO1QiMztyAnPyVVIy0zJ1VDJbEovSzaMFZTU1PHSEddQV3HUNP6/3@P1JycfIXw/KKcFMX/evp6mXkFpSV6JZn5AA "PHP – Try It Online") [Answer] # Perl 5 (`-aF//`), 23 bytes ``` printf"%02X ",ord for@F ``` [TIO](https://tio.run/##K0gtyjH9/7@gKDOvJE1J1cAoQkFJJ78oRSEtv8jB7f9/j9ScnHyF8PyinBRFrn/5BSWZ@XnF/3UT3fT1AQ) [Answer] ## Python 3, 59 bytes -11 bytes thanks to Mostly Harmless! -8 bytes thanks to James K Polk! -24 bytes thanks to Blue! ``` print(' '.join('%02X'%ord(i)for i in open(input()).read())) ``` [Try it online!](https://tio.run/##VcgxCoAwDADA3VfUoSRdougnfIKr0IqRkpRSB18fxc3p4MrdDpXZrFSWhuCATmVB8OO0gtcakcOu1bFjcVqSIEu5GoZANW3xNZjRQN9SY@2WlLP2v3sA) This is pretty straightforward; it opens a filename given as input on STDIN, reads it, converts each character to its ASCII value, converts each number to hex, strips off the `"0x"` that precedes hexademical values in Python, pads the value with a zero if necessary, then joins the values together with spaces. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 bytes Anonymous tacit prefix function. Returns (and implicitly prints, if the value isn't otherwise consumed) a two-row matrix with the top 4 bits represented as a decimal number 0–15 in the top row and the bottom 4 bits similarly represented in the bottom row. That is, the matrix has as many columns as the file has bytes. ``` 16 16⊤83 ¯1∘⎕MAP ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v7pGak5OvoxCeX5SToqj@qG@qX0BoiHpJboFeSUWJ@n9DMwVDs0ddSyyMFQ6tN3zUMQOowtcx4H/ao7YJj3r7gDxP/0ddzYfWGz9qmwjkBQc5A8kQD8/g/2lwUwA "APL (Dyalog Unicode) – Try It Online") `⎕MAP` map the argument filename to an array `∘` with parameters: `¯1` the entire length of the file `83` read as 8-bit integers `16 16⊤` convert (anti-base) to 2-position hexadecimal [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~ 33 ~~ 23 bytes ...with a lot of help: -3 thanks to [manatwork](https://codegolf.stackexchange.com/users/4198) -4 thanks to [spuck](https://codegolf.stackexchange.com/users/87944) -3 thanks to [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745) ``` echo `xxd -c1 -p -u $1` ``` **[Try it online!](https://tio.run/##S0oszvj/PzU5I18hoaIiRUE32VBBt0BBt1RBxTDh/3@P1JycfIXw/KKcFEUurvCixAKFpNTK/LwUhfLMlJIMhfw0BaAuPQA "Bash – Try It Online")** Note that the TIO link above uses input - we can write files locally, so [this](https://tio.run/##NYxBDoMgFET3nGKamLiCxhW7rnsDtyofSxP0E8RIT48a0tVkMu/NNG6uWOMY7dt6z@g5enoI0ccxYLI/XgnHl5IDz8iZVIsX0hJUyklUsfrDNUKaDjJA7mi6odxoiPwRxi1M0FrXqp53/F/KCQ "Bash – Try It Online") shows it working as a program taking a file path. [Answer] # [Kotlin](https://kotlinlang.org), ~~130~~ ~~127~~ ~~104~~ ~~93~~ 92 bytes ``` fun main(a:Array<String>){java.io.File(a[0]).readBytes().forEach{print("%02X ".format(it))}} ``` [Try it online!](https://tio.run/##FcqxCsJADADQ3a84C8LdEoujiKCguDsoiEOwV41eLyWmQin99qjr471YE2WzusuuQcoelxsR7FdHFcr3dRie@EEghj2l6PFSXgNIxGrba3z7ADXLDm@Pof119cWsXJxd8dcG1ZOGMI5mh5gSuxNLqqYTgzlQbjsFJf4C "Kotlin – Try It Online") Edit: -11 bytes thanks to @ChrisParton Edit: Working TIO Edit: -1 byte thanks to @KevinCruijssen [Answer] # [Dart](https://www.dartlang.org/), ~~140~~ 134 bytes ``` import'dart:io';main(a){print(new File(a[0]).readAsBytesSync().map((n)=>n.toRadixString(16).toUpperCase().padLeft(2,'0')).join(' '));} ``` [Try it online!](https://tio.run/##DYuxCgIxEAV/5brsgoTTwsJDQQUrKw8rsViSVXN6SUgW9BC/PaZ7M8yzlKQUN8aQRNkKKxdUZx5snkD4jcl5Ac/v5uBeDHRpr6gTk93m3SSc@8kbQD1SBPC43ngt4UTWfXqpzzvMl1jNOUZOe8pc00j2yDeBxUy1ClEPwXlQTZ3dr5Q/ "Dart – Try It Online") -6 bytes because I forgot to reduce variable names [Answer] # Haskell, ~~145~~ 143 bytes ``` import System.Environment import Text.Printf import Data.ByteString main=getArgs>>=Data.ByteString.readFile.(!!0)>>=mapM_(printf"%02X ").unpack ``` [Answer] # Rust, 141 bytes (contributed version) ``` use std::{io::*,fs::*,env::*};fn main(){for x in File::open(args().nth(1).unwrap()).unwrap().bytes(){print!("{:02X} ",x.unwrap())}println!()} ``` # Rust, 151 bytes (original version) ``` fn main(){std::io::Read::bytes(std::fs::File::open(std::env::args().nth(1).unwrap()).unwrap()).map(|x|print!("{:02X} ",x.unwrap())).count();println!()} ``` [Answer] ## bash+Stax, 6+4+1=11 bytes This is complete theory craft at this point. You can't actually run this. If everything works according to its spec this would work, but not everything does yet. The bash script is ``` ]<$1 ``` and the stax program must be compiled and saved to ] is ``` ╛↕ßú┼_ ``` Set your character set to ISO 8859-1 (Windows-1252 won't work here) and go Unpacked and explained ``` _ push all input as a single array F run the rest of the program for each element of the array |H write the hex of the byte to standard output | write a space to standard output ``` [Answer] # [Emojicode](http://www.emojicode.org/), ~~186~~ 162 bytes ``` 📦files🏠🏁🍇🔂b🍺📇🐇📄🆕🔡👂🏼❗️❗️🍇👄📫🍪🔪🔡🔢b❗️➕256 16❗️1 2❗️🔤 🔤🍪❗️❗️🍉🍉 ``` Try it online [here.](https://tio.run/##S83Nz8pMzk9JNfv//8P8ycvSMnNSiz/M718AxI0f5ve2f5g/pSkJyNgFlAVyJgDx5JYP89umAiUWfpg/sQmocM@judPf7@iHkBBNE4FqJq8GslcB1a2CqJ2yKAmqcN5UI1MzBUMzCNdQwQimdcoSBRAB0odmZicI//@vl5lXUFqiV5KZDwA "Emojicode – Try It Online") Ungolfed: ``` 📦 files 🏠 💭 Import the files package into the default namespace 🏁 🍇 💭 Main code block 🔂 b 💭 For each b in ... 🍺 💭 (ignoring IO errors) 📇 🐇 📄 💭 ... the byte representation of the file ... 🆕 🔡 👂🏼 💭 ... read from user input: ❗️ ❗️ 🍇 👄 💭 Print ... 📫 💭 ... in upper case (numbers in bases > 10 are in lower case) ... 🍪 💭 ... the concatenation of: 🔪 🔡 🔢 b ❗️ ➕ 256 💭 b + 256 (this gives the leading zero in case the hex representation of b is a single digit) ... 16 💭 ... represented in hexadecimal ... ❗️ 1 2 💭 ... without the leading one, ❗️ 🔤 🔤 💭 ... and a space 🍪 ❗️❗️ 🍉 🍉 ``` [Answer] # [Perl 6](http://perl6.org/), 45 bytes ``` @*ARGS[0].IO.slurp(:bin).list.fmt('%02X').say ``` [Try it online!](https://tio.run/##K0gtyjH7/99ByzHIPTjaIFbP01@vOKe0qEDDKikzT1MvJ7O4RC8tt0RDXdXAKEJdU684sfL/f4/UnJx8HYXy/KKcFMX/evp6mXkFpSV6JZn5AA) * `@*ARGS[0]` is the first command-line argument. * `.IO` turns that (presumed) filename into an `IO::Path` object. * `.slurp(:bin)` reads the entire file into a `Buf` buffer of bytes. (Without the `:bin` the file contents would be returned as a Unicode string.) * `.list` returns a list of the byte values from the buffer. * `.fmt('%02X')` is a `List` method that formats the elements of the list using the given format string, then joins them with spaces. (Convenient!) * `.say` prints that string. [Answer] # Node.js, 118 bytes ``` console.log([...require("fs").readFileSync(process.argv[2])].map(y=>(y<16?0:"")+y.toString(16).toUpperCase()).join` `) ``` What the result looks like: [![enter image description here](https://i.stack.imgur.com/YGHkD.png)](https://i.stack.imgur.com/YGHkD.png) Btw the content of `test.txt` in the example is as follows: > > `做乜嘢要輸出大楷姐,搞到要加番toUpperCase()去轉番,咁就13byte啦。` > > > (Why on earth is upper-case output necessary. I had to add the conversion with `toUpperCase()`, and that cost 13 bytes.) > > > [Answer] # [D](https://dlang.org), 98 Bytes ``` import std;void main(string[]s){File(s[1]).byChunk(9).joiner.each!(a=>writef("%02X ",a.to!byte));} ``` [Try it Online!](https://tio.run/##BcFLCsIwEADQq6QFIYEyfnZSdCOIN1AoXaRmtFPTTEmmShHPHt9zOdM4cRSVxNVvJqdGS0EniRSeTZvM90wedWq2rYFuOfVzeOm9gYEpYAS0977Q9nD8RBJ86HK12d1UWVkQLrpF0Jj6l/MFvedKXTl6V2RYA4VpFhDiPw) [Answer] # Python 3, 75 bytes Mostly a copy of [Maxwell's python 2 answer.](https://codegolf.stackexchange.com/a/188074/3139) ``` import sys print(' '.join('%02X'%b for b in open(sys.argv[1],'rb').read())) ``` [Answer] # Racket, 144 bytes This submission does output a trailing space, and no trailing newline. Let me know if this is considered a loophole :) ``` (command-line #:args(f)(for([b(call-with-input-file f port->bytes)])(printf"~a "(string-upcase(~r b #:base 16 #:min-width 2 #:pad-string"0"))))) ``` ## Cleaned up ``` (command-line #:args (f) (for ([b (call-with-input-file f port->bytes)]) (printf "~a " (string-upcase (~r b #:base 16 #:min-width 2 #:pad-string "0"))))) ``` [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 71 bytes ``` : f slurp-file hex 0 do dup c@ 0 <# # # #> type space 1+ loop ; 1 arg f ``` [Try it online!](https://tio.run/##ZY@7DsIwDEV3vuJSRlQeYgOEGPkDli5R4rSVDI6cVIWvD23pgIQ8@Orq6Fj2oqkpaz@uHAskeoSNH4Jue1glk6j0LROcSoDrAmJV4EbMgrsou2X1LFQSem3/UM9dbH46yxJnpprlMNNJjGU@wiNyp@HLNPTCDk4ml70O@bzCNBekdyDEYCxhvwbLYD8tDjBaw@ec5zc@ "Forth (gforth) – Try It Online") *TIO has `3 arg` in the last line because TIO passes "-e bye" to the command line parser before passing in the code* ### Code Explanation ``` : f \ start a function definition slurp-file \ open the file indicated by the string on top of the stack, \ then put its contents in a new string on top of the stack hex \ set the interpreter to base 16 0 do \ loop from 0 to file-length - 1 (inclusive) dup c@ \ get the character value from the address on top of the stack 0 <# # # #> \ convert to a double-length number then convert to a string of length 2 type \ output the created string space \ output a space 1+ \ add 1 to the current address value loop \ end the loop ; \ end the word definition 1 arg f \ get the filename from the first command-line argument and call the function ``` [Answer] ## Javascript, 155 bytes ``` for(b=WScript,a=new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(b.Arguments(0));;b.echo(('0'+a.read(1).charCodeAt(0).toString(16)).slice(-2))) ``` [Answer] ## VBScript, 143 bytes ``` set a=CreateObject("Scripting.FileSystemObject").OpenTextFile(WScript.Arguments(0)):while 1 WScript.echo(right("0"+Hex(Asc(a.read(1))),2)):wend ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~94~~ 89 bytes ``` Print@ToUpperCase@StringRiffle@IntegerString[BinaryReadList@Last@$ScriptCommandLine,16,2] ``` [Try it online!](https://tio.run/##JcixCsIwEADQ3a9QcAwRHZyDXRQ6SKs4iMPRXutBcgnXc/Drz4DLG14CfWMCpQHMrkKs4ZbvpaA0sGDotdbc0TRFDBdWnFH@9zwRg3w7hLGlRUMLlW0/CBVtckrA9Rnd/ugOL7Mzxpjd@pEljpuV@Z0nLh/1SvkH "Wolfram Language (Mathematica) – Try It Online") The code is quite self-explanatory because of the long command names. It should be read mostly from right to left: ``` $ScriptCommandLine is a list of {scriptname, commandlinearg1, commandlinearg2, ...} Last@... extracts the last command-line argument BinaryReadList@... reads the named file into a list of bytes IntegerString[...,16,2] converts each byte to a 2-digit hex string (lowercase) StringRiffle@... converts this list of strings into a single string with spaces ToUpperCase@... converts the string to uppercase Print@... prints the result to stdout ``` [Answer] # [Gema](http://gema.sourceforge.net/), 45 characters ``` ?=@fill-right{00;@radix{10;16;@char-int{?}}} ``` Sample run: ``` bash-5.0$ gema '?=@fill-right{00;@radix{10;16;@char-int{?}}} ' <<< 'Hello World!' 48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A ``` [Try it online!](https://tio.run/##S0/NTfz/397WIS0zJ0e3KDM9o6TawMDaoSgxJbOi2tDA2tDM2iE5I7FINzOvpNq@trZW4f9/j9ScnHyF8PyinBRFAA "Gema – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes ``` jdcr1.Hjb'w2 ``` [Try it online!](https://tio.run/##K6gsyfj/PysluchQzyMrSb3c6P9//fyCEv0CoASY0CuoBAA "Pyth – Try It Online") Takes input as user prompt (no way to access command-line arguments AFAIK). ``` jd # join on spaces c 2 # chop into pieces of length 2 r1 # convert to uppercase .H # convert to hex string, interpreting as base 256 (*) jb # join on newlines ' # read file as list of lines w # input() ``` (\*) I'm not 100% sure if this is intended, but one base 256 digit (as in, one character), will always convert into exactly 2 hex digits, eliminating the need to pad with zeroes. [Answer] ### [C#](https://docs.microsoft.com/en-us/dotnet/csharp/) [.NET](https://dotnet.microsoft.com) Framework 4.7.2 - ~~235~~ ~~213~~ ~~203~~ ~~191~~ ~~175~~ 140 bytes [Try it online!](https://tio.run/##Pc3BagIxEIDhe59iugdJ0AbpdaGgolhosXQLFpY9zGajDqRJyYyiLH32dBHxP3/wW36ybHM@MoU9VBcW92NeN6X1yAwfPQsKWThF6uAdKSiWNMi6Qd3TTqF5c2Evh5fpaLQi78zyTCyssJ42Wve7mBzagzphghYowNV8Ouxm3s8v4u7ydl7EwHEg20TiVGu@YnX9qeL7udDjAgpd/g3lvHbexwlsY/Ld40M2FH6PYoTiPw) ``` using System.IO;class P{static void Main(string[]a){foreach(var b in File.ReadAllBytes(a[0])){System.Console.Write(b.ToString("X2")+" ");}}} ``` --- ``` using System; using System.IO; namespace hexdump { class Program { static void Main(string[] args) { // Read the bytes of the file byte[] bytes = File.ReadAllBytes(args[0]); // Loop through all the bytes and show them foreach (byte b in bytes) { // Show the byte converted to hexadecimal Console.Write(b.ToString("X2") + " "); } } } } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ``` IvyÇh2j' 0.:' Jvy? ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fs6zycHuGUZa6goGelbqCV1ml/f//rB6pOTn5CuH5RTkprAA "05AB1E – Try It Online") Explanation: ``` IvyÇh2j' 0.:' Jvy? Iv Loop through each character in input y Push current character Ç ASCII value h Convert to hexadecimal 2j Pad with at least 2 spaces ' 0.: Replace all spaces with 0s ' J Add space to end vy? Convert to string and print IvyÇh2j' 0.:' Jvy? ``` [Answer] # [Free Pascal](https://www.freepascal.org/), 81 B ``` var c:char;begin while not EOF do begin read(c);write(hexStr(ord(c),2):3)end end. ``` Note, output has a leading blank and no trailing newline: `48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A` --- **−3 B**: By default the FPC (FreePascal Compiler) has the “FPC compiler compatibility mode” selected. When compiling in FPC’s “ISO standard compiler compatibility mode” the file buffer variables (here specifically `input^`) and “low-level” I/O routines like `get` become available. The following code needs to be compiled with `fpc ‑MISO sourceCode.pas`: ``` begin while not EOF do begin write(hexStr(ord(input^),2):3);get(input)end end. ``` --- **−10 B**: *Furthermore*, *if* `input` was guaranteed to be non-empty, we can use a `repeat … until …` loop instead of the bulky `while … do begin … end`: ``` begin repeat write(hexStr(ord(input^),2):3);get(input)until EOF end. ``` ]
[Question] [ **Objective**: Given a positive integer `n`: * If `n` is odd, output the list of `n` numbers closest to `0` in increasing order * If `n` is even, output a Falsey value. **Test cases**: ``` 5 -> [-2,-1,0,1,2] 4 -> false (or any Falsey value) 1 -> [0] ``` --- ## Reference implementation ``` function update(){ var num = +document.getElementById("yield").value; if(num){ var out = document.getElementById("output"); if(num % 2 == 1){ // base is balanced var baseArr = []; for(var i=0;i<num;i++){ baseArr.push(i-Math.floor(num/2)); } out.innerHTML = baseArr.join(" "); } else { out.innerHTML = "false"; } } else { out.innerHTML = "<i>enter input</i>"; } } setInterval(update,1); ``` ``` * { font-family: "Constantia", "Consolas", monospace; } [type="number"] { width: 10px; width: 2em; } #output { font-family: "Consolas", monospace; } ``` ``` Input: <input type="number" id="yield" value="3"> is <span id="output"><i>enter input</i></span> ``` [Answer] # Pyth, 10 bytes ``` *-R/Q2Q%Q2 ``` [Try it online.](https://pyth.herokuapp.com/?code=%2a-R%2FQ2Q%25Q2&input=3) ### How it works ``` (implicit) Store the input in Q. /Q2 Calculate Q/2 (integer division). -R Q Subtract that value (-R) from each element in [0, ..., Q-1] (Q). * %Q2 Repeat the resulting array Q%2 times. ``` [Answer] ## APL, ~~16~~ ~~15~~ 13 bytes Thanks to @Dennis for -2 bytes! ``` ⌊(⍳⊢×2|⊢)-÷∘2 ``` This is a monadic train that gives an empty array for even input. Below is the diagram: ``` ┌────┴─────┐ ⌊ ┌────────┼─┐ ┌─┴─┐ - ∘ ⍳ ┌─┼───┐ ┌┴┐ ⊢ × ┌─┼─┐ ÷ 2 2 | ⊢ ``` First, `⊢×2|⊢` gives the input times its mod 2; that is, odds will give themselves, and evens give 0. We use `⍳` to create a list of numbers from 1 to that (`⍳0` gives the empty array), and then we subtract half the input and floor. [Answer] # Mathematica, ~~32~~ ~~30~~ 24 bytes ``` OddQ@#&&Range@#-(#+1)/2& ``` Code-golfing trick: The last argument to `And` doesn't have to be a boolean. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` %₂1&~l≠≜o ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X/VRU5OhWl3Oo84Fjzrn5P//b/rfEQA "Brachylog – Try It Online") ### Explanation An interesting (ab)use of Brachylog's backtracking algorithm: ``` %₂1 First, assert that the input mod 2 is 1 (if not, the predicate fails) & Then, the input ~l is the length of some list ≠ in which all elements are different ≜ Generate a list that matches those conditions Brachylog will try to fill the array with integers, starting from 0 and increasing in absolute value; since they all have to be different, the result will be of the form [0, 1, -1, 2, -2, ...] o Sort ascending ``` [Answer] ## PowerShell, ~~50~~ 52 Bytes ``` param($a)$b=$a/2-.5;(0,((0-$b)..$b-join' '))[($a%2)] ``` Oof. Pretty verbose answer. Takes input `$a`, then sets a new variable `$b` as the "floor" of `$a/2`. Generates a new number range from `(0-$b)` to `$b`, then `join`s the range with spaces, and has that as the second element of a two-element array (the first element is `0`). Then uses `$a%2` to index into that array for output. Alternate version using more "traditional" if/else flow, at 54 bytes: ``` param($a)$b=$a/2-.5;if($a%2){(0-$b)..$b-join' ';exit}0 ``` Edit - Needed to add some logic to output a falsey value if the input is even [Answer] ## Haskell, ~~37~~ ~~36~~ 31 bytes ``` g n=take(n*mod n 2)[-div n 2..] ``` Unbalanced is indicated by the empty list. Usage example: `g 7` -> `[-3,-2,-1,0,1,2,3]`. @xnor found 5 bytes. Thanks! [Answer] # J, 12 bytes ``` i:@%~2&!*2&| ``` This is a monadic verb that returns `0` (falsy) for even numbers. Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(i%3A%40%25~2%26!*2%26%7C)%203). ### Test run ``` (i:@%~2&!*2&|) 3 _1 0 1 (i:@%~2&!*2&|) 2 0 ``` ### How it works ``` Right argument: y 2&| Take y modulo 2. 2&! Calculate y C 2 = y(y-1)/2. * Multiply the results. %~ Divide the product by y. This yields (y-1)*(y%2)/2 = (y-1)/2 (y even) | 0 (y odd). @ Take the result and... i: apply the bilateral index generator z -> (-z ... z). ``` [Answer] # JavaScript (ES6), ~~44~~ ~~43~~ ~~42~~ 41 bytes [crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/a/61414/42545) ``` n=>[...Array(n&1&&n--)].map((x,i)=>i-n/2) ``` For odd inputs, returns a integer array of length `x`, centered at `0`; for even, returns 0. I think this is as short as it can get. (Saved a couple bytes thanks to @edc65 and @ןnɟuɐɯɹɐןoɯ!) ES6 alternative: (42 bytes, thanks to @intrepidcoder) ``` x=>x%2&&[for(y of Array(x--).keys())y-x/2] ``` Suggestions welcome! [Answer] # Python 2, ~~34~~ 32 Bytes Right now I'm not sure if I can output whatever I want if it's not balanced, so currently this just returns an empty list in the case of an unbalance-able base. It's an anonymous lambda function, so give it a name to use it. ``` lambda k:k%2*range(-k/2+1,-~k/2) ``` [Answer] ## [Minkolang 0.10](https://github.com/elendiastarman/Minkolang), 18 bytes ``` nd2%?.d2:~r[dN1+]. ``` ### Explanation ``` n Take input as integer (k) d2%?. Duplicate k and stop if it's even d2:~ Duplicate k, then divide by 2 and negate to get first number r Put k on top [ ]. Loop k times and then stop dN1+ Duplicate, output as integer, and increment ``` [Answer] # [DUP](https://esolangs.org/wiki/DUP), 31 bytes ``` [a:a;2/b:[b;_[$b;<][$1+]#][0]?] ``` `[Try it here.](http://www.quirkster.com/iano/js/dup.html)` Anonymous lambda. Usage: ``` 5[a:a;2/b:[b;_[$b;<][$1+]#][0]?]! ``` # Explanation ``` [ ] {lambda} a: {store input to a} a;2/ {divmod a by 2} b: {store quotient to b, top of stack is now remainder} [ ][ ]? {conditional} b;_ {if remainder is 1, get b and negate it} [ ][ ]# {while loop} $b;< {while top of stack is less than b} $1+ {duplicate and increment} 0 {otherwise, leave falsy value} ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes ``` ∷$½:N$ṡ∧ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%88%B7%24%C2%BD%3AN%24%E1%B9%A1%E2%88%A7&inputs=9&header=&footer=) ## Explanation ``` ∷$½:N$ṡ∧ ∷ Parity $ Swap (putting the input on top again) ½ Half : Duplicate N Negate $ Swap ṡ Range from a to b ∧ Logical AND ``` [Answer] # CJam, ~~13~~ 12 bytes ``` {_2md@,@f-*} ``` This is an anonymous function that pops an integer from the stack and pushes a digit array (odd base) or an empty array (even base) in return. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri%0A%20%20%7B_2md%40%2C%40f-*%7D%0A~p&input=3). ### How it works ``` _ e# Copy the input (N). 2md e# Push N/2 and N%2. @ e# Rotate N on top of the stack. , e# Push [0 ... N-1]. @ e# Rotate N/2 on top of the stack. f- e# Subtract N/2 from each element of [0 ... N-1]. * e# Repeat the resulting array N%2 times. ``` [Answer] # O, 18 ``` M(.e\2/.@{_}dmrr]p ``` [Live demo.](http://o-lang.herokuapp.com/link/code=M(.e%5C2%2F.%40%7B_%7Ddmrr%5Dp&input=3) [Answer] # Vitsy, ~~27~~ 25 Bytes I'm gonna golf this down tomorrow, but I really ought to go to bed now. ``` D2M)[&1]D1-i*}\[D2/NaO2+] D Duplicate the input. 2M)[&1] If the input is even (input%2=0) generate a new stack and push 1 to it. D Duplicate the top value - if it wasn't even, this will be the input. Otherwise, it's one. 1- Subtract one (to balance around zero) i* Additively invert } Shift over an item in the stack - this ensures that we have either the input or one on top. \[ ] Repeat input times. D2/N Duplicate the top item and print it out. aO Newline (I'm pretty sure this is valid separation) 2+ Add one to the top item of the stack. ``` [Answer] ## R, 30 bytes ``` function(n)(x=(1-n)/2*n%%2):-x ``` Roughly, `x:-x` returns the integers from `x` to `-x`, where I set `x` to `(1-n)/2`. I also use the modulo-2 factor `n%%2` in the definition of `x` to force `x` to zero when `n` is even, in which case, `0:0` returns `0` (falsey). [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 16 bytes ~~18~~ ``` x%2Þr(xØ)ßl-x/2) ``` Pretty simple. The special characters are actually just "abbreviations" for longer code sequences. I still haven't made permalinks so you'll have to copy paste into the [interpreter](http://vihanserver.tk/p/TeaScript/) ### Explanation ``` x%2 && // If x is NOT even return falsy, else... r(x--) // Range 0-input. Subtracts one from input m(# // Loop through range l- // Current item in loop, minus... x/2 // input - 1, divided by two ) ``` This answer is non-competing [Answer] # F#, 38 bytes The falsey result is an empty list. ``` let O n=if n%2<1 then[]else[-n/2..n/2] ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 21 chars / 37 bytes ``` ô[…Ѧ(ï&1⅋ï‡)]ć⇀_-ï/2⸩ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=5&code=%C3%B4%5B%E2%80%A6%D1%A6%28%C3%AF%261%E2%85%8B%C3%AF%E2%80%A1%29%5D%C4%87%E2%87%80_-%C3%AF%2F2%E2%B8%A9)` Here's a 20-char / 35-byte answer (non-competing, since the answer uses changes implemented after the question was asked): ``` ô(ï%2⅋ѨĶ(ï‡)ć⇀$-ï/2⸩ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=5&code=%C3%B4%28%C3%AF%252%E2%85%8B%D1%A8%C4%B6%28%C3%AF%E2%80%A1%29%C4%87%E2%87%80%24-%C3%AF%2F2%E2%B8%A9)` [Answer] # Japt, ~~21~~ 19 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. ``` U%2&&(X=-U/2+K o1-X ``` For odd inputs, returns a integer array of length `x`, centered at `0`; for even, returns 0. Rough JS translation: ``` output(U%2&&(X=-U/2+.5).range(1-X)); ``` where `x.range(y)` creates a list of integers from `x` to `y`. [Test it online!](http://ethproductions.github.io/japt/?v=master&code=VSUyJiYoWD0tVS8yK70gbzEtWA==&input=Nw==) --- In modern Japt, this is only 11 bytes: ``` u ©Uo-U/2-½ ``` [Try it online!](https://tio.run/nexus/japt#@1@qcGhlaL5uqL6R7qG9//9bAgA "Japt – TIO Nexus") [Answer] # [R](https://www.r-project.org/), 26 bytes ``` a=scan();-(i=a%/%2*a%%2):i ``` [Try it online!](https://tio.run/##K/r/P9G2ODkxT0PTWlcj0zZRVV/VSCtRVdVI0yrzvynX//8A "R – Try It Online") Integer-divide input by 2, and multiply by input modulo 2 (so it becomes zero if input is even). Then output the range of integers from negative to positive of this value. (for a fairer comparison with the previous (half-decade-old!) [R](https://www.r-project.org/) answer, the approach here would be [28 bytes](https://tio.run/##fctBCoAgEADAe/8QNIjK6hL4lmUzA0F2Qe3S57cf7HmYKhcWpJhuIIiFW2odOsOXKgd5Xoo9M1l0k80BzWz8iMZ4d2Yl2sUNiq6qelU3VXdVDzeI/A) as a function). [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 6 (or 4?) [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ½k¥¿╤< ``` Outputs `0` as falsey output. [Try it online.](https://tio.run/##y00syUjPz0n7///Q3uxDSw/tfzR1ic3//6ZcJlyGXIZGXIbGAA) If we're allowed to output `[0]` as falsey output, even though \$n=1\$ results in `[0]` as truthy output as well, this could be **4 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)** instead: ``` ¥*½╤ ``` [Try it online.](https://tio.run/##y00syUjPz0n7///QUq1Dex9NXfL/vymXCZchl6ERl6ExAA) **Explanation:** ``` ½ # Integer-divide the (implicit) input-integer by 2 k # Push the input-integer again ¥ # Modulo-2 ¿ # If input%2 is truthy / 1 / odd: ╤ # Pop the input//2 and push a list in the range [-input//2, input//2] # Else (it's falsey / 0 / even instead): < # Check if the (implicit) input is smaller than input//2, which is falsey / 0 # (after which the entire stack joined together is output implicitly as result) ¥ # Modulo-2 on the (implicit) input-integer (1 if odd; 0 if even) * # Multiply that by the (implicit) input-integer ½ # Integer-divide it by 2 ╤ # Pop and push a list in the range [-(input%2*input//2), input%2*input//2] # (after which the entire stack joined together is output implicitly as result) ``` [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 37 bytes ``` lambda x:x%2*[*range(-x//2+1,x//2+1)] ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHCqkLVSCtaqygxLz1VQ7dCX99I21AHQmnG/i8oyswr0UjTAJGZeQWlJRqaQPDfFAA "Python 3.8 (pre-release) – Try It Online") [Answer] # Perl, 36 bytes I have a feeling this can be shortened: ``` $,=$";$n=<>;print$n%2?-$n/2..$n/2:0; ``` Range treats floats as integers, so, e.g. 5/2 = 2.5 gets silently converted to 2. (If formatting doesn't matter, then remove `$,=$";` for a total of 30 bytes). [Answer] ## Powershell, 49 bytes ``` param($a)$b=$a/2-.5;"[$(-$b..$b-join",")]"*($a%2) ``` Even numbers evaluated to `$false` since they provide an empty line output. ``` ("[$(-$b..$b-join",")]"*($a%2))-eq $True ===> False ``` Odd numbers output the exact reference string. You can save 4 more bytes (now `45`) by removing the `[]` from the output string. ``` PS> .\balanced.ps1 4 PS> .\balanced.ps1 5 [-2,-1,0,1,2] PS> .\balanced.ps1 0 PS> .\balanced.ps1 1 [0] PS> ``` ## Powershell, 36 Bytes ``` param($a)$b=$a/2-.5;(-$b..$b)*($a%2) ``` This has the same falsey result but outputs the list of numbers separated by newlines: ``` PS> .\balanced-newline.ps1 4 PS> .\balanced-newline.ps1 1 0 PS> .\balanced-newline.ps1 5 -2 -1 0 1 2 PS> ``` [Answer] # Perl 6, 25 bytes The shortest lambda expression I could come up with that outputs a list rather than a range is: ``` {$_%2&&|((1-$_)/2..$_/2)} # 25 ``` Testing: ``` for 0..10 -> $a { if {$_%2&&|((1-$_)/2..$_/2)}($a) -> $b { say "$a.fmt('%5s') $b" } else { say "$a.fmt('%5s') False" } } ``` ``` 0 False 1 0 2 False 3 -1 0 1 4 False 5 -2 -1 0 1 2 6 False 7 -3 -2 -1 0 1 2 3 8 False 9 -4 -3 -2 -1 0 1 2 3 4 10 False ``` This takes advantage of the fact that Perl 6 treats the number `0` as a false value. If the output had to be exactly `False` you could replace `$_%2` with `$_!%%2`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 5 bytes ``` HŒRxḂ ``` [Try it online!](https://tio.run/##y0rNyan8/9/j6KSgioc7mv5bHt19uP1R05r/AA "Jelly – Try It Online") ## Explanation ``` HŒRxḂ Main monadic link H Halve ŒR Balanced range x Repeat Ḃ parity of n ``` *-1 byte by finding out there's almost a builtin for this* [Answer] # [Risky](https://github.com/Radvylf/risky), 10 bytes ``` 0?+0*:?\2__?+0-_?/2 ``` [Try it online!](https://radvylf.github.io/risky?p=WyIwPyswKjo_XFwyX18_KzAtXz8vMiIsIlszM10iLDBd) ## Explanation ``` 0 range ? input + + 0 0 * repeat : 0 ≠ ? input \ mod 2 2 _ map _ ? item + + 0 0 - - _ ? input / / 2 2 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` È#¹;D(ŸR ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4gjwrk7RCjFuFI&input=Nw) Explanation: ``` È# # If input % 2 == 0, end the program ¹ # Push the first input from the register ; # Halve, push input / 2 rounded down D # Duplicate top of the stack ( # Negate Ÿ # Inclusive range, pushes [a .. b] R # Reverse the array ``` Uses **CP-1252** encoding. [Answer] # PHP, 50 bytes ``` <?=($n=$argv[1])&1?join(_,range(-$k=$n/2|0,$k)):0; ``` program, takes input from STDIN, prints `_` delimited list or `0`. or ``` function f($n){return$n&1?range(-$k=$n/2|0,$k):0;} ``` function takes argument, returns array or `0`. ]
[Question] [ Bob has a startup that is developing a product that uses “advanced AI” and “black magic” to automatically code-golf computer programs. Unfortunately, Bob is running out of cash and desperately needs money from investors to keep his company running. Each investor that Bob has contacted wishes to schedule a meeting with a certain start and end time. However, some of meeting times conflict with each other. Bob wishes to meet with as many investors as possible so he can raise the largest amount of money. How many investors can Bob meet with, given that Bob can only meet with one investor at a time? ## Input Format Input is given as an array of pairs (or the equivalent in your chosen language). Each pair p represents one investor, where `p[0]` is the start time of the investor’s meeting and `p[1]` is the end time. For example, in the test case `[(0,10),(5,10),(12,13)]`, there are three investors: one who wants to meet from time 0 to time 10, one who wants to meet from time 5 to time 10, and one who wants to meet from time 12 to time 13. Meetings will always have a positive duration, and a meeting that ends at time `k` does not conflict with a meeting that starts at time `k`. You may use any reasonable I/O method for input. ## Test Cases ``` [(0,10),(5,10),(12,13)] => 2 (investors 1 and 3) [(10,20),(10,20),(20,30),(15,25)] => 2 (investors 1 and 3) [(0,3),(1,5),(1,5),(1,5),(4,9),(6,12),(10,15),(13,18),(13,18),(13,18),(17,19)] => 4 (investors 1,5,7 and 11) [(1,1000),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7)] => 6 (every investor except the first) [(1,2),(101,132),(102,165),(3,9),(10,20),(21,23),(84,87)] => 6 (investors 1,2,4,5,6,7) ``` ## Output Your program should output an integer, the maximum number of investors that Bob can meet with. Standard loopholes are prohibited. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in each language wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ 52 bytes Based on [xnor's answer](https://codegolf.stackexchange.com/a/224524/64121). -1 byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)! ``` f=lambda l,t=0:-min([a<t or~f(l,b)for a,b in l]+[0]) ``` [Try it online!](https://tio.run/##bU9LboQwDN1zCi8T1ZXyIQyMykkQi6AOGqQQUCaomk2vThNnFlXVjZ08v4@9P@N98@o8597Zdfq04DD24vq@Lp4N9iPCFr5n5nDi8xbA4gSLBze@DWLk59d9cTeQ1wpsCPaJ4I8V@sTYj8h4BeH2OFxMyMyIkKA9LD6yMsAXoe@Tjp8DEygFR2ZKkwql5iOCgmpgUqAi9NWVQE1/g8oQq8oGOkNo/tQau1QblKo4SBpplO1//YKyy451jk27CMrBrFUUoLEmU0PLNmR9yYqGFCUkKXV5pTsaQ7Lu9wGJmM3aGtsi/gE "Python 2 – Try It Online") This is a recursive function which takes 2 arguments: * `l`: a list of all offered meetings * `t`: the time our last meeting ended (initially 0) The list comprehension iterates over all offered meetings `(a, b)`. If the meeting starts before our last meeting ended (`a<t`), `a<t or ...` evaluates to `True`, which is basically the same as `1` in Python. Otherwise `f(l,b)` is called to see how much more meetings we can fit in if we take the current meeting. The bitwise inverted value of this gets into the list. If `a<t` was false for any meeting `(a, b)` in the comprehension, `min` returns the smallest of all possible `~f(l,b)` values. Then `-min(...)` returns `-~f(l,b)==1+f(l,b)` for some meeting. Otherwise `-min(...)` is equal to `0`. --- 47 bytes if we can assume that the input is not empty: ``` f=lambda l,t=0:1-min(a<t or-f(l,b)for a,b in l) ``` [Try it online!](https://tio.run/##bU9LisMwDN3nFFraoII/cZqU8UlKFw7T0IDjBNdh6OlTW@5iGGYj2U/vI22v9FiDOo7JereM3w48Jisu8rTMgbmvBGs8TczjyKc1gsMR5gCeHz@P2d9BXhpwMboXQtgXsHm47YnxBuL9ufuUkYkRIUNbnENidYAfgrVZx48rEygFR2Zqkwql5jcEBc2VSYGK0E9XAjX9DSpDrKYY6AKh@VNbHHLtUKrqIGmkUfb/9TPKoTi2JTbvIigHi1ZRgMaWTA0t25H1uSg6UtSQrNT1le/oDMmG3wdkYjHrW@yr@A0 "Python 2 – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 49 bytes ``` If[#==0m,1,1+#0[#.m]]&[m=Boole[#>=#2&~Outer~##]]& ``` [Try it online!](https://tio.run/##bU49a8MwEN3zNw689Fp0kuWPQcF069RCuwkPItgkUNnFcScj/3VXPiVQSpd70rt7H97N5867@XJyW2@2l96CMcIjIT2AsPDk2zaz3jyP42dn4WhAZuvr99xNK0BcbW/TZZgtPB77pvmY3HD9Gq9dA222vp/csC6HZRFIIuCiE5BEUiFgXJBAydQNpUDFf41Sp5PI7ATqPzPHOs4CSSY98UohVf9hiVTfImMJwRm4KyXbK8zZUnPLgo3L@30KiDqVXrF@oVlU/64eD3erKseqvFenEA5h@wE "Wolfram Language (Mathematica) – Try It Online") Input `[{starting times}, {ending times}]`. Finds the least power `n` such that \$M^n=\mathbf{0}\$, where `M` is an adjacency matrix representing possible next meetings. [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` f=lambda l,t=0:max([1+f(l,b)for a,b in l if a>=t]+[0]) ``` [Try it online!](https://tio.run/##bU9LjoMwDN1zCi8T1Yt8CIVK6UUQi6ApKlKgKA2a6elp4nQxGs3GTp7fx95e8f5Y1XFM1rtl/HLgMVpxWdwP6@VpYh5HPj0COBxhXsHDPIG72jicejHw4/s@@xvISwUuBPdCWPcFbGJue2S8gnB77j4mZGJESNAW5jWyMsAPwdqk40fPBErBkZnSpEKp@YCgoOqZFKgI/XQlUNPfoDLEqrKBzhCaP7XGLtUGpSoOkkYaZftfP6PssmOdY9MugnIwaxUFaKzJ1NCyDVmfs6IhRQlJSl1e6Y7GkKz7fUAiZrO2xraI3w "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 43 36 35 bytes ``` 1#@}.(#~0{]>://&.|:@/:{:"1) ::]^:a: ``` [Try it online!](https://tio.run/##hY1BC4JAEIXv/opHRia0q7Prag4YQtCpU3eDiCS69AOs/vo2rhF0isc8BuZ7b25@ppMeDSPBCjlYRmlsD/udp7h96mX8yoduw1m20A9uMx54RimYuyOf2KfR5Xy9o4eFwVzClMONRgZkMV0TpVQSTbtB84cuA1EFgsJRViMRi0LkRKWomugi0ESfQiu0@06BWsixXFrc@ILWv16Bav8G "J – Try It Online") Uses greedy algorithm. Probably more to golf.... ## orig brute force, 43 bytes ``` [:>./(2#:@i.@^#)(#*;-:~.@;)@#<@([+i.@-~)/"1 ``` [Try it online!](https://tio.run/##VYzNCsIwEITvPsXQCG3Upt2kPza1EhB68uS14EUs6sU36KvHbSqCDLO77H47Lx@peERnEWOHHJadKpwu594P9qiyRAvrnspdhUzEpk3tpFwrnTi4ZNjyPp1kFpGXq/vt8YZGhxGG@5qDKEc5F9IgswBVAOoAULjxqPnDoGCVrIpVL3QRaKJvnmG6/LlAw@SczSm84uv@v9agxn8A "J – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` <þ¬æ×Ƭ`L ``` ``` <þ¬æ×Ƭ`L <þ outer product less than ¬ negate (outer product greater than or equal to) æ× matrix multiply Ƭ` apply until converged using itself as the left argument L length ``` Uses the method from the mathematica answer <https://codegolf.stackexchange.com/a/224523/95516> go upvote that! [Try it online!](https://tio.run/##RY69DQIxDIX7m4IBnkR@LrmcxAhsEEWioUG3AC0NI7ABVWagIBKDsEh4TjiQf@TYfl98Oi7LudZdeTxzuZfbKx/2tVy370uuNQ4xKjhokxC1grhNCWz3l2F2CZtoWm2ZXZ9z0GyE77LVJ6IsmWIzyQRAh9XnL51KA0u1g29/K/VvYPptKQkZyDEaYeQykZbhhS93WQQKhlQ/ "Jelly – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 42 bytes ``` f=->a,b=0{a.map{|c,d|c<b ?0:-~f[a,d]}.max} ``` [Try it online!](https://tio.run/##bVBBDsIgELz7Ch4wGhZKbY3VhxAOUO3NxGhMNLZ@vS5LTIzxsgM7O7MDl1t6zPPQLXcRqdPPuDrF83PscRj7bVJ7vVm@Bh9xCBMz92nu4/V4VZ3y3muQDvBOQHkyIBu44UnDZOaDRsPK3cG4kGdZa3MD7qdWaLnWIFP0JJQFNf9wDWqLH3EILTuQlUbsLSqxdJKyFuP1Z74sYJ0tJ05fOxG139F5MFs1FRqWhoW8v3xSGs9q8ClM8xs "Ruby – Try It Online") This answer is heavily inspired by [xnor's](https://codegolf.stackexchange.com/a/224524/100752) python answer. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` W⌊ΦEθ⮌ꬋ⊟κ∨⌈υ⁰⊞υ⊟ιILυ ``` [Try it online!](https://tio.run/##bYtLC8IwEITv/oocN7BCY32VHgVPVovX0EMowQbTh3lU/31MehT3MMvMfNN2wrSj0CG8O6UlgUoNqvc9nJV20kAlJnghuctZGivhSSmS6@jgIq2FepxiguSWuM8y89FmdDlSe9uBR5IwRWm5qo0aHJyETfvh4WIbuTIEznmGeYOc4e5Ht1hE3SPbpChDtlQ5suO/f0BWNE0T1rP@Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Eθ⮌κ ``` Reverse each investor meeting, so that the end time comes first and the start time second. ``` Φ...¬‹⊟κ∨⌈υ⁰ ``` Destructively compare the start times with the latest end time so far, returning just the possible end times of the next meeting. ``` W⌊ ``` Take the earliest such time, if any. While it exists: ``` ⊞υ⊟ι ``` Push that earliest ending time to the predefined empty list. ``` ILυ ``` Output the number of meetings in the list. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 164 bytes Exponential time. Am I proud of myself? No. ``` c(v)=if(#v>1,(sum(i=2,#v,(v[1][1]<v[i][2])&&(v[1][2]>v[i][1]))+c(v[^1])),0) p(v)=vector(2^#v-1,i,vecextract(v,i)) m(v)=vecmax(vector(2^#v-1,i,#p(v)[i]*!c(p(v)[i]))) ``` [Try it online!](https://tio.run/##bU/basMwDH3PX4xAsTYVLCVOE1j6I8aFELrhh9CQpaZ/n9pyHkoZGF2OzzmS5mHxx99520YVoPc/qgxnQvV3n5TvGcuAKlhy8X0H651lB4dDhtidBSIH8BXl9pIq1FDMyStcx/W2KL6U4UjoMfbXx7oM46oCeoBi2lnT8FDv5DJZRPPPj1HtJQBs26Ss1UjaoTU5ESNVzkHfc5F@SSMLvmfWWElvkM0LL8IJRfMWa@xibJA4m5B8VUjtf/mE1IlpnYfHnbRMwyRnmVFhLb5Glm7E/SSiZhflUVFc5Sqe1BhRdq@XRGLya2tsd/0T "Pari/GP – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 52 bytes ``` g=(a,e,m)=>a.map(([S,E])=>m=S<e|E>m?m:E)|m&&g(a,m)+1 ``` [Try it online!](https://tio.run/##fVLLTsMwELz3K/YCtZUlxEnTJymnHjlxNJGwUqcY5VElVgUCvr2sHR4FIS62d2d2Zu31ozqovujM3l407VYfy@y4y5hCjTXP1iqs1Z4xeYubnMI6u73Sr5t1fV0vN/y1Pj/fEbXmgTha3dtC9bqHDO5HkkUoIo4sHTYRo0h4DtkaYmCmORC77XoQoJotJJwKRISxp37scYSJj1OM0/9LiemImP5aJ7igdYoiHnSFhxIU87/2GYrF4DP54YMpzryXEL5PulHkG0MnG3vvBCfeL/VXnnrX2SA2BaYPunuGT0nQT4XeW7APGkrT9XZQHXok9WQ40YtNUy@9OH0VIjrD@QTn3wan3cZIbaCzH92HtjM142G/r4xl47tmzP1AK1dXfaZdMOb8Y9QKQefc5aSbvi0e2OXdNrjcDYTGIUHDw7JS9sZVHBAMgvIlBs5oStcgc1iClAQpaSAAkec5Rwj0qSKXEWVXo6@vE5Ztt1EEM2m@ungZAVTaQksfq2SG@ABF2/RtpcOq3bEWHZRloAl646vjOw "JavaScript (Node.js) – Try It Online") Greedy join meetings that ends earliest. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 56 bytes ``` \d+ $* O^$`1*,(1+) $1 ^ ¶ +m`^(1*)(¶.*\1,(1+)) ¶$3$2 \G¶ ``` [Try it online!](https://tio.run/##VU5JCsMwDLzrHS44jigeOc6CH5BjPxBCCu2hh/YQ@rY8IB9z5UALPWg0aEYjrff343XNJzsuebrVZBxdZrPAsUVdkQHNtG9UP5fZwlV2385uwiFWKphghKZx33L2DJ9iAQgjEDyL8gPFc1AeWSIpTeD4q4aH1DKkWKGjwOj/sWMMBE32msGSRBMCN7oZ9WCr2x2VObyaQun6QBvVM3zvqxxS33DffQA "Retina 0.8.2 – Try It Online") Link includes test cases. Takes `;`-delimited meetings. Explanation: ``` \d+ $* ``` Convert to unary. ``` O^$`1*,(1+) $1 ``` Sort by descending meeting end. ``` ^ ¶ ``` Insert a marker for the latest meeting end so far. ``` +m`^(1*)(¶.*\1,(1*)) ¶$3$2 ``` Repeatedly match the meeting with the earliest end whose start is not before the latest meeting end so far, update the latest meeting end, and keep track of the number of meetings. ``` \G¶ ``` Convert the number of meetings to decimal. [Answer] # [Python 2](https://docs.python.org/2/), ~~145~~, ~~143~~, 142 bytes Saved **2 bytes** thanks to Wasif pointing out that I didn't need to assign the `lambda` function to a variable. ``` lambda t:max(all(min(e,y)<=max(s,x)for(x,y),(s,e)in k(p,2))*len(p)for r in range(len(t))for p in k(t,r)) from itertools import* k=combinations ``` [Try it online!](https://tio.run/##bY/LbsMgEEX3/opZQjQLgx95qP6StAvS4haFlzBRk693YZxFVXXDwJl77wzxkb@Cl@s8va5WucuHgnxy6s6UtcwZzzQ@@MtUyYJ3PofE7oVgeWluPFxZRMn5zmrPYm1DgoKT8p@aVZg50Qgkzpg4b@YUHJisUw7BLmBcDCnvmuv0HtzFeJVN8Mv6/WWsBnFqQKWkHgj@5mAqOfGWGW8g6eVmcyEzI0FBMRmf2dbAp2Caio@vZ9aiaMviw1aERNHxNwQJzZmJFiXRZ5UtdvQeUA6kampAVxEOf84ej@UcUcgtQVCrQ3H4r@5RHGtiX8eWXVqag9UraUCHPYUOtOxI0fvqGMmxDSnObruVf4wD2Y6/P1CENezQ42Ez/wA "Python 2 – Try It Online") Brute force approach. The program uses list comprehension to iterate through the powerset of the meetings. [Answer] # [R](https://www.r-project.org/), 85 bytes ``` f=function(m)`if`((s=sum(m|1))<3,s|1,max(1+f(m[,m[1,]>=m[2]|m[2,]<=m[1]]),f(m[,-1]))) ``` [Try it online!](https://tio.run/##nZHLboMwEEX3@QpL3djqVGJszEMK@RGEEkpMw8KmwiRNJP6dOphERVGy6MYz8uPec8fdeGh/tro0l61Wqm/Ml83GOquPpuqb1lDNdk29o9Rm9qipHpCxtQA7IOjyTPG9pjoHnSMUm0znvBjcAsXa9VgUDKbjDywYY49GtPpszJ5WNAAMGFRUzhU5oHBPyBvJNoSTijbmpGzfdpYgKc2eCLZ6LocBcK9za3gAwu9I4PL/yk5mUgH5WEJIryUC5LM3@mMBmDxpYsD0ThMuaUBCPBEhvgzrZhb4bDAZc88oIPRU0k828nDx3S5yduqkugu5mRJ1rtR3T/qDInXT2f617xzTAYi5dd8WSW@eLufvbk9USQjJEuFvYg4OF66Qq/EX "R – Try It Online") Input is matrix with start times in row 1 and end times in row 2. **How?** ``` how_many_meetings= f=function(m){ # f = recursive function, m = input matrix if((s=sum(m|1))<3)return(s|1) # if there's only one or zero investors in the matrix, return that number, else{ # otherwise return(max( # return the max of 1+f(m[,m[1,]>=m[2]|m[2,]<=m[1]]), # 1 (the first investor in the matrix) + recursive call with # all investors in the matrix that don't overlap with him/her, f(m[,-1])) # or just a recursive call without the first investor in the matrix ) } } ``` ]
[Question] [ Given you have an infinite sequence of numbers defined as follows: ``` 1: 1 = 1 2: 1 + 2 = 3 3: 1 + 3 = 4 4: 1 + 2 + 4 = 7 5: 1 + 5 = 6 6: 1 + 2 + 3 + 6 = 12 7: 1 + 7 = 8 ... ``` The sequence is the sum of the divisors of `n`, including 1 and `n`. Given a positive integer `x` as input, calculate the lowest number `n` which will produce a result greater than `x`. **Test cases** ``` f(100) = 48, ∑ = 124 f(25000) = 7200, ∑ = 25389 f(5000000) = 1164240, ∑ = 5088960 ``` **Expected Output** Your program should return **both** `n` and the sum of its divisors, like so: ``` $ ./challenge 100 48,124 ``` **Rules** This is code-golf so the shortest code in bytes, in each language wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~12~~ ~~11~~ 10 bytes ``` 1Æs>¥#ḢṄÆs ``` [Try it online!](https://tio.run/##y0rNyan8/9/wcFux3aGlyg93LHq4swXI@Q8UMzAwAAA "Jelly – Try It Online") -1 byte thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)! ## How it works ``` 1Æs>¥#ḢṄÆs - Main link. Argument: n (integer) 1 ¥# - Find the first n integers where... Æs - the divisor sum > - is greater than the input Ṅ - Print... Ḣ - the first element Æs - then print the divisor sum ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` ∧;S?hf+S> ``` This program takes input from the "output variable" `.`, and outputs to the "input variable" `?`. [Try it online!](https://tio.run/##SypKTM6ozMlPN/pf96htw6Omxv@POpZbB9tnpGkH2/3/b2hg8D8KAA "Brachylog – Try It Online") ## Explanation ``` ∧;S?hf+S> ∧;S There is a pair [N,S] ? which equals the output h such that its first element's f factors' + sum S equals S, > and is greater than the input. ``` The implicit variable `N` is enumerated in increasing order, so its lowest legal value is used for the output. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 53 bytes ``` {#,f@#}&@@Select[Range[x=#]+1,(f=Tr@*Divisors)@#>x&]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/b9aWSfNQblWzcEhODUnNbkkOigxLz01usJWOVbbUEcjzTakyEHLJbMsszi/qFjTQdmuQi1W7b@@g0K1oY6CoQEIAwkjUwMDg9rY/wA "Wolfram Language (Mathematica) – Try It Online") Tries all values between 2 and x+1, where x is the input. (The `Select` returns a list of all values that work, but the function `{#,f@#}&` takes all of these as inputs, and then ignores all its inputs but the first.) [Answer] # [R](https://www.r-project.org/), 71 bytes ``` function(x)for(n in 1:x){z=sum(which(n%%1:n==0));if(z>x)return(c(n,z))} ``` [Try it online!](https://tio.run/##DcZBCoAgEAXQfadwE/yBFmPQprDLSIMumsCSxOjs1lu91MQ1yeqveCgKyZGgJqqxc6GnujPvuEP0Adr3dlbnmGiJgroWStuVk8JDh0r0NoFlpk4wTvynfQ "R – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes ``` §eVḟ>⁰moΣḊN ``` -1 byte, thanks to @Zgarb! [Try it online!](https://tio.run/##AR8A4P9odXNr///Cp2VW4bifPuKBsG1vzqPhuIpO////MTAw "Husk – Try It Online") [Answer] # [R](https://www.r-project.org/), 73 bytes ``` n=scan();while(1){d=(x=1:T)[!T%%x];if(sum(d)>n)break;T=T+1};cat(T,sum(d)) ``` [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTujwjMydVw1CzOsVWo8LW0CpEM1oxRFW1ItY6M02juDRXI0XTLk8zqSg1Mds6xDZE27DWOjmxRCNEByKn@d/QwOA/AA "R – Try It Online") Outgolfed by [duckmayr](http://codegolf.stackexchange.com/a/149747/76266). [Answer] # [Japt](https://github.com/ETHproductions/japt/), 15 bytes ``` [@<(V=Xâ x}a V] ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=W0A8KFY9WOIgeH1hIFZd&input=MTAw) --- ## Explanation Implicit input of integer `U`. `[]` is our array wrapper. For the first element, `@ }a` is a function that run continuously until it returns a truthy value, passing itself an incrementing integer (starting at 0) each time, and outputting the final value of that integer. `â` gets the divisors of the current integer (`X`), `x` sums them and that result is assigned to variable `V`. `<` checks if `U` is less than `V`. The second element in the array is then just `V`. [Answer] # [Clojure](https://clojure.org/), 127 bytes ``` (defn f[n](reduce +(filter #(zero?(rem n %))(range 1(inc n))))) (defn e[n](loop[i 1 n n](if(>(f i)n){i,(f i)}(recur(inc i)n)))) ``` [Try it online!](https://tio.run/##JYzBCsJADETvfkVACgl6aH9AP6R4kG0ikTVbgntR/PY1285pZpg3KZdndW4NFxYDme2GzktNDCcUzW92OOKHvVyjf4HBQIR@twfDhGoJjLoOO8@dz6Wss8IU40gqeEEBJaOvnjf3i6tUfcN7H2q4umF8jmOEPw "Clojure – Try It Online") thanks to @steadybox for -4 bytes! [Answer] # [Ruby](https://www.ruby-lang.org/), 58 bytes Full program because I'm not sure if lambdas are allowed. /shrug ``` gets $.+=1until$_.to_i.<v=(1..$.).sum{|n|$.%n<1?n:0} p$.,v ``` [Try it online!](https://tio.run/##KypNqvz/Pz21pJhLRU/b1rA0ryQzRyVeryQ/PlPPpsxWw1BPT0VPU6@4NLe6Jq9GRU81z8bQPs/KoJarQEVPp@z/f0MDAwA "Ruby – Try It Online") # Explanation ``` gets # read line ($_ is used instead of v= because it cuts a space) $.+=1 # $. is "lines read" variable which starts at 1 because we read 1 line until # repeat as long as the next part is not true $_.to_i # input, as numeric .<v= # is <, but invoked as function to lower operator prescedence (1..$.) # Range of 1 to n .sum{|n| # .sum maps values into new ones and adds them together $.%n<1?n:0 # Factor -> add to sum, non-factor -> 0 } p$.,v # output n and sum ``` [Answer] ## JavaScript (ES6), ~~61~~ 58 bytes ``` f=(n,i=1,s=j=0)=>j++<i?f(n,i,i%j?s:s+j):s>n?[i,s]:f(n,++i) ``` ``` <input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o> ``` Edit: Saved 3 bytes thanks to @Arnauld. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` >LʒÑO‹}нDÑO ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fzufUpMMT/R817Ky9sNcFyNL8/98QAA "05AB1E – Try It Online") Leaves the output on the stack, as allowed [per meta consensus](https://codegolf.meta.stackexchange.com/a/8507/59487). I added `)` for the sake of visualization, but the program also implicitly prints the top of the stack. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 32 bytes ``` {⍺<o←+/o/⍨0=⍵|⍨o←⍳⍵:⍵,o⋄⍺∇⍵+1}∘0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR727bPKBDG39fP1HvSsMbB/1bq0BMkBij3o3A3lWQKyT/6i7Baj0UUc7kKdtWPuoY4YB0AQFQ0MuIGFgACFBlJEpkAYA "APL (Dyalog Unicode) – Try It Online") *⍵o⍺⍵.* [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 14 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 1[:Λ∑:A.>?ao←I ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MSU1QiUzQSV1MDM5QiV1MjIxMSUzQUEuJTNFJTNGYW8ldTIxOTBJ,inputs=MTAw,v=0.12) Explanation: ``` 1 push 1 [ while ToS != 0 :Λ get the divisors ∑ sum :A save on variable A without popping .>? ← if greater than the input ao output the variable A ← and stop the program, implicitly outputting ToS - the counter I increment the counter ``` [Answer] # C, ~~79~~ 78 bytes ``` i,n,s;f(x){for(i=n=s=0;x>s;s+=n%++i?0:i)i-n||(++n,i=s=0);printf("%d %d",n,s);} ``` [Try it online!](https://tio.run/##LcxBCsIwEIXhfU4RAoEZJoUouHGInkVSIrNwlKZCoe3ZYwO@5cfPy8Mz59YkaKhcYMG1vCeQpKmmyMutcqWknkju8Soog24bEGmQHiB/JtG5gPOj9aPrL8h7O8y@HqKAZjX2WIFT7PV3ruAc8h/Pl9jZ7O0H) [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` `@Z\sG>~}@6M ``` [Try it online!](https://tio.run/##y00syfn/P8EhKqbY3a6u1sHM9/9/QwMDAA "MATL – Try It Online") ### Explanation ``` ` % Do...while @ % Push iteration index (1-based) Z\ % Array of divisors s % Sum of array G % Push input >~ % Greater than; logical negate. This is the loop condition } % Finally (execute on loop exit) @ % Push latest iteration index 6M % Push latest sum of divisors again % End (implicit). Run new iteration if top of the stack is true % Display stack (implicit) ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 11 bytes ``` dΣ@> ↑#(:dΣ ``` [Try it online!](https://tio.run/##S0/MTPz/P@XcYgc7rkdtE5U1rIDsR01r9P7/NzQwAAA "Gaia – Try It Online") Leaves the output on the stack, as allowed [per meta consensus](https://codegolf.meta.stackexchange.com/a/8507/59487). I added `€.` for the sake of visualization, but the program also implicitly prints the top of the stack. [Answer] # [Haskell](https://www.haskell.org/), 59 bytes ``` f x=[(i,s)|i<-[1..],s<-[sum[d|d<-[1..i],i`mod`d<1]],s>x]!!0 ``` -1 byte, thanks to @nimi! [Try it online!](https://tio.run/##JYnBCoQgFAB/5XUrMNF7eukzREh41j42LXoGHfp3V9jDwDDzCfyN@17rCo9xPQkeXppGp6X0gpvwnRy@@E/kBS3pwAUn7du3j@86VVOgDAa2WOYjl5gLg7UGzotyAQlr44oBq1bqBw "Haskell – Try It Online") [Answer] # [Ohm v2](https://github.com/nickbclifford/Ohm), 11 bytes ``` £^DVΣD³>‽;« ``` [Try it online!](https://tio.run/##y8/INfr//9DiOJewc4tdDm22e9Sw1/rQ6v//jUwNDAwA "Ohm v2 – Try It Online") [Answer] # [Factor](http://factorcode.org), 88 ``` USE: math.primes.factors [ 0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ] ``` Brute-force search. It's a quotation (lambda), `call` it with `x` on the stack, leaves `n` and `f(n)` on the stack. As a word: ``` : f(n)>x ( x -- n f(n) ) 0 0 [ drop 1 + dup divisors sum pick over > ] loop rot drop ; ``` [Answer] # Python 3, 163 bytes ``` def f(x): def d(x):return[i for i in range(1,x+1) if x%i==0] return min(i for i in range(x) if sum(d(i)) >x),sum(d(min(i for i in range(x) if sum(d(i)) >x))) ``` [Answer] # [Python 3](https://docs.python.org/3/), 100 bytes ``` d=lambda y:sum(i+1for i in range(y)if y%-~i<1) f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j)) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8U2JzE3KSVRodKquDRXI1PbMC2/SCFTITNPoSgxLz1Vo1IzM02hUlW3LtPGUJMrDaa8wio3M09DI0snRSNLUxOkJwuhp0LbEKSrwsYWLPu/oCgzr0QjTcNQU5MLzjYwAPKUYVwjUwOQwH8A "Python 3 – Try It Online") Thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)'s comment on the previous python 3 attempt, I have just greatly expanded my knowledge of python syntax. I'd never have thought of the -~i for i+1 trick, which saves two characters. However, that answer is 1) not minimal and 2) doesn't work for x=1 (due to an off-by-one error which is easy to make while going for brevity; I suggest everyone else check their answers for this edge case!). Quick explanation: `sum(i+1for i in range(y)if y%-~i<1)` is equivalent to `sum(i for i in range(1,y+1)if y%i<1)` but saves two characters. Thanks again to Mr. Frech. `d=lambda y:sum(i+1for i in range(y)if y%-~i<1)` therefore returns the divisors of y. `f=lambda x:min((j,d(j))for j in range(x+1)if x<=d(j))` is where I really did work. Since comparing a tuple works in dictionary order, we can compare j,d(j) as easily as we can compare j, and this lets us not have to find the minimal j, store it in a variable, and /then/ compute the tuple in a separate operation. Also, we have to have the <=, not <, in `x<=d(j)`, because d(1) is 1 so if x is 1 you get nothing. This is also why we need `range(x+1)` and not `range(x)`. I'd previously had d return the tuple, but then I have to subscript it in f, so that takes three more characters. [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` def f(n): a=b=0 while b<n: a+=1;i=b=0 while i<a:i+=1;b+=i*(a%i<1) return a,b ``` [Try it online!](https://tio.run/##JY3BCoMwEETP2a/YSyFWD1HoJU2u/scGIy7IVkJE@vWpSS8zw2OYOb55@8hUyhJXXLV0FpB88Abw2niPGJxYUNT78c2Nqz9nR5YrDb3np6YHu7EDTDGfSZCG0BbntqiOxJJRhvYAMOu7eosx1aaXqaH8AA "Python 2 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 91 bytes ``` i->{for(int j=0;j++<i;)for(int k=0,l=0;k++<j;)if((l+=j%k<1?k:0)>i)return k+","+l;return"";} ``` [Try it online!](https://tio.run/##jY4xa8MwEEZ3/4rDUJCwI5RCl8p2t0CGThlLB9Wxk5MUSdjnQAj@7a5C0q7tdve@Nzyjz3oVYufN3i6t0@MI7xr9NQMYSRO2YJIhJkIn@sm3hMGLzeOotp66QzeUsKMB/aGBI9QLrpprHwaGnsDUUpmiqFDxH2RrWbqEbcJGcewZc0Vtnmy1frOvkjfIh46mwYMt8jIvnLq/ea7mRWUpLE5fLoU9@s4B93BKzewe8fEJmt/6YXcZqTuJMJGIaSHn2VHoGN2FraXkXP0hPb/I/2g361ecs3n5Bg "Java (OpenJDK 8) – Try It Online") (timeout on third test case) [Answer] # [Perl 5](https://www.perl.org/), 60 + 1 (`-p`) = 61 bytes ``` $"=$_;until($_>$"){$_=$/=0;$\--;$_+=$\%$/?0:$/until++$/>-$\} ``` [Try it online!](https://tio.run/##HcpBCoAgEAXQu8gPChm0RZtEu4gwqxaCqJStoqs3QW/92n7kRQTKg91VesojOEBNN9jDeOsQiRxYe8QBZrMrzP@0hgmE@IjM1r619VTLKdQ@ "Perl 5 – Try It Online") Output format: *sum*-*n* [Answer] ## Clojure, 102 bytes ``` #(loop[i 1](let[s(apply +(for[j(range 1(inc i)):when(=(mod i j)0)]j))](if(> s %)[i s](recur(inc i))))) ``` [Answer] # PHP, 69 bytes ``` for(;$argv[1]>=$t;)for($t=$j=++$i;--$j;)$t+=$i%$j?0:$j;echo$i,',',$t; ``` [Answer] # [Perl 6](http://perl6.org/), 48 bytes ``` {first :kv,*>$_,map {sum grep $_%%*,1..$_},0..*} ``` [Try it online!](https://tio.run/##DcpBCoMwEAXQq3xkLG0YhmTRLlr0KoMLI9KGhsQKEnL22Ld@cU6fRwsHLh5DK35NecPzvbMZSTlMESX/ApY0R5D2vWEnQlrZipja8nSgI8Uwovgr6U2WNW@1g/8m3Nn9lzhrX@0E "Perl 6 – Try It Online") ]
[Question] [ Inspired by [this](https://chat.stackexchange.com/transcript/message/38366096#38366096) and the following chat: [![Inspiration](https://i.stack.imgur.com/STXcP.jpg)](https://i.stack.imgur.com/STXcP.jpg) Your task is to output the following: ``` _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/ ``` Extra leading or trailing whitespace is allowed, as long as it does not change the appearance of the cube. As usual, returning the above or a list of strings from a function is allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 23 bytes ``` F³⁺⁺×\_³×\/⁻³ι¶ ‖M↑×_ ³ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw1hTIaAoM69EwzElBYxDMnNTizWUYmLilXQUjDV1FOAC@kAB38y80mINYx2FTE1NoJxSTJ6CkqamNVdQalpOanKJb2ZRUX6RhlVoAVAMYi5Ue7wC2DhN6////@uW/dctzgEA "Charcoal – Try It Online") Link is to verbose version of code. Not very Charcoal-y I know. I didn't realise that `‖M↓` deliberately moves the cursor so I had originally tried `F³«P⁺×/_³×/\⁻³ι↗»‖M↓×_ ³` which didn't work, because I was trying to do it upside-down. If you want something more Charcoal-y then try `G↗³←⁶↘³/\¶\/G↖³←⁷↘³_\¶\_↘‖M↑×_ ³` for 32 bytes: [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pwyq0ICgzPaNER8FYR8HKJzUNyDIDslzyy/MQEkr6MTExeTEx@kqa1lxIWiHqETrNMXXGQ3TGg3T65pelaiAUAEWCUtNyUpNLfDOLivKLQCaCzC/KzCvRCMnMTS3WUIpXUAKao6lp/f//f92y/7rFOQA "Charcoal – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 27 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Y=Q∫+ZΔ○H!╝Ηūf⅟Ξ∆׀Æģ≠a⁶‘6«n ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=WSUzRFEldTIyMkIrWiV1MDM5NCV1MjVDQkglMjEldTI1NUQldTAzOTcldTAxNkJmJXUyMTVGJXUwMzlFJXUyMjA2JXUwNUMwJUM2JXUwMTIzJXUyMjYwYSV1MjA3NiV1MjAxODYlQUJu) Sadly, the palendromization version `qE½Dε▒2β[}█O%q‘6«n╬∑` [doesn't really work](https://dzaima.github.io/SOGLOnline/?code=cUUlQkREJXUwM0I1JXUyNTkyMiV1MDNCMiU1QiU3RCV1MjU4OE8lMjVxJXUyMDE4NiVBQm4ldTI1NkMldTIyMTE_) [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 35 bytes ``` 00000000: 5350 5088 0741 2e05 05fd 7830 8ce1 82b3 SPP..A....x0.... 00000010: 806c 0413 c889 8907 4330 8f4b 01c1 036a .l......C0.K...j 00000020: 8671 00 .q. ``` [Try it online!](https://tio.run/##hYw9DsIwFIN3TuETPDnN3ysbYmSpxAlISJFQGRgq9fYhge58g73YX1pTWspjfdXKnSO89YSnKhidwVDoQT/fEdUSmouBDskC12kSOUljY8/Dz2CaQxky6IxFVh2hIyOc7ffZJdBkA9pwA2SRL2fKpdVzdwzdEWJbEX@Rt9T6AQ "Bubblegum – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~97 94 93~~ 89 bytes ``` ">knknknk//>k>knknknk/>k>k>knknknkk>k>k>n>n>n>k>k>n>n>n>/k>n>n>n>//n/n/n///"01. of- ``` [Try it online!](https://tio.run/##S8sszvj/X8kuOw8M9fUl7bLhHDAbxpMEs@3ywFASwdSXhLP0JfP0QVBfX8nAUI8rP033/38A "><> – Try It Online") Edit 3: Figured out that you can use the character "" (ascii 25) - Now the process just takes 15 off every stack item and prints. Also removed extra directional instructions and replaced all with 1 move (01.) [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` i=7 while i:k=min(i,7-i);i-=1;print' '*(3-k)+'\/___ '[i/3::3]*3+k*'\//\\'[i>2::2] ``` [Try it online!](https://tio.run/##DcgxCoAgGAbQvVO4mZZIOgS/2EVSnII@LIsIotNbb3zne69HMbXCj82zYlsYKPsdpUU/KggH5Qd3Xig3Z1y2VmXR8aBTSozP0JbIRmm7LP/UIfw3GSITa/0A "Python 2 – Try It Online") [Answer] # Tail, 99 bytes ``` #!/bin/tail -n+2 _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/ ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~98~~ 94 bytes *@KevinCruijssen suggested this...* *-4 bytes thanks to @HyperNeutrino and @WheatWizard* Output Hardcoding solution: ``` print(r""" _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/""") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Eo0hJSUlBQSEeBLkUFPTjwTCGC84CshFMICcmHgzBPC4FBA@oGcYBGqn5/z8A "Python 3 – Try It Online") **or, 98 bytes:** ``` print(" _ _ _\n /_/_/_/\\\n /_/_/_/\/\\\n/_/_/_/\/\/\\\n\_\_\_\/\/\/\n \_\_\_\/\/\n \_\_\_\/") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ0lBQSEeBGPyFBT048EwJgbIgbHBPAQHzI2JB0MIP08BiQs0BMZT0vz/HwA) --- # [Python 3](https://docs.python.org/3/), 139 bytes Dumb Python 3 Non-Hardcoding sumbmission, sure it can be golfed. Surprisingly, compressing the two `for`s in just one loop is longer: ``` p=print;p(' '*3+"_ "*3) for i in range(3):p(abs(2-i)*' '+'/_'*3+'/'+i*"\/"+'\\') for i in range(3):p(i*' '+'\\_'*3+'\\'+"/\\"*abs(2-i)+'/') ``` [Try it online!](https://tio.run/##bcwxCsMwDEDRvacwWmRJBEO8tfQmgpBC0mpxhJulp3disnb/7/tv/2wlt@ZPr1b2h0cMyFlgCsCZbutWgwUroc7lvcRMd4/z6xvHwYjPVDBNvceEYgyaQFAV/0O7hOpFzk4gqQL3ow0j9Q21dgA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 140 bytes ``` print(' '*3+"_ "*3,'\n'+'\n'.join(abs(2-i)*' '+'/_'*3+'/'+i*"\/"+'\\'if i<3else (i-3)*' '+'\\_'*3+'\\'+"/\\"*abs(i-5)+'/'for i in range(6))) ``` [Try it online!](https://tio.run/##LczLCsIwEIXhVxlmM7kYAwZd9VEGSoVUR2RS0m58@pigm7P6zr99jmfR1NpWRQ9DQC55nAFdOhEr@THnVxE1y303lyDWdeQpzkNSJC8OOWKHTLKCTCm/9wxGQvpT5p/twGNkRjdSEq52/NdSQUAU6qKPbG7W2ta@ "Python 3 – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 42 bytes ``` 0000: e0 00 4f 00 22 5d 00 10 68 13 e2 04 15 00 b7 11 │ à.O."]..h.â...·. 0010: 7a 0e c5 f5 30 27 b5 b3 3d 39 8f a6 1f f9 74 52 │ z.Åõ0'µ³=9.¦.ùtR 0020: c5 66 98 bd bd 0a 9a 8d 44 00 │ Åf.½½¶..D. ``` [Answer] # Java 8, 112 bytes ``` o->" _ _ _\n /_/_/_/\\\n /_/_/_/\\/\\\n/_/_/_/\\/\\/\\\n\\_\\_\\_\\/\\/\\/\n \\_\\_\\_\\/\\/\n \\_\\_\\_\\/" ``` Hard-coded output. [Try it here.](https://tio.run/##XY9BDoIwEEX3nOKHVVmIBzB6A3Xh0hpSSjXFOiVQSIzh7DggGGNmMul/M2n@L1WnVr4yVBb3QTvVNNgrS68IsBRMfVXa4DBK4BRqSzdoccxLowN8smHeRzyaoILVOICwxeBXu5jvs7EkAetsKilZfN@T/FUTkDJbeqGEf8hf/qJ4GH1wV23u2MVspvO2wIPDiI/x8wUqmZM8m2AeqW9DWvEqOBKUakGtc8kcqh/e) [Answer] # [Retina](https://github.com/m-ender/retina), 59 bytes ``` _¶ /_/\¶ /_/V\¶/_/VV\¶\_VVV¶ \_VV¶ \_V ._ $&$&$& V \/ ``` [Try it online!](https://tio.run/##K0otycxL/P@fS0FBIf7QNgUF/Xj9GCANpMKANIgC0THxYWFhQGEQDVIFpLn04rlU1ECQK4wrRv//fwA "Retina – Try It Online") Explanation: The first stage simply creates the following: ``` _ /_/\ /_/V\ /_/VV\ \_VVV \_VV \_V ``` The second stage then expands all the `_`s by repeating them and the previous character 3 times, while the third stage turns the `V`s into `\/`s. [Answer] # [PHP](https://php.net/), 77 bytes ``` <?=strtr(' _ _ _ 0\ 01\ 011\ 2111 211 21',["/_/_/_/","\/","\_\_\_"]); ``` [Try it online!](https://tio.run/##K8go@P/fxt62uKSopEhDXUFBIR4EuRQUDGK4FAwMY7gMDIGEkaGhIZeCEYgAkuo60Ur68WCopKMUAybiQVApVtP6/38A "PHP – Try It Online") [Answer] # C#, 86 bytes ``` o=>@" _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/" ``` [Try it here.](https://tio.run/##RY3NCsIwEITveYqhpxb8eYDaIgieLB568FIodQ0SiQl0U0Gkzx6TgJa5zLc7wxCvyY7ST6zMHe2bnXyWgvTAjOYjAHaDU4SXVTc0gzJ5Ea/AcTK0O18fktwKrRtDvQahgrdVvc9Coo8K2W2f1Im/C36xAbo@KZHAQqH8g8zH0TJNH6xhq@XmMionT8rInHIzaV0U8T@L2X8B) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ 31 bytes ``` „_ 3×Âð'/:3F„/\«∞2ä`RˆD}\)¯R«.c ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcO8eAXjw9MPNx3eoK5vZewGFNCPObT6Ucc8o8NLEoJOt7nUxmgeWh90aLVe8v//AA "05AB1E – Try It Online") **Explanation** ``` „_ 3× # push the string "_ _ _ "  # push a reversed copy ð'/: # replace spaces with slashes 3F # 3 times do „/\« # append "/\" ∞ # mirror 2ä` # split into 2 separate parts on stack Rˆ # reverse the second part and push to global list D # duplicate the remaining part } # end loop \) # discard the last copy and wrap stack in a string ¯R # push the global list and reverse it « # append to the rest of the list .c # pad lines to equal length ``` **Alternate 31 byte solution** ``` „ _3×3FDð'/:„/\«∞2ä`R.Á})ÀÀÀ.c¦ ``` [Answer] # CSS, ~~225~~ 223 bytes *-2 bytes thanks to Stephen S, extra spaces removed* I'm not exactly sure if this counts because CSS isn't *really* a programming language, but technically CSS can be standalone since the `<html>` element is autogenerated if there isn't one. ``` html:after{content:' _ _ _ \A /_/_/_/\005c\A /_/_/_/\005c/\005c \A /_/_/_/\005c/\005c/\005c \A \005c_\005c_\005c_\005c/\005c/\005c/ \A \005c_\005c_\005c_\005c/\005c\/\A \005c_\005c_\005c_\005c /';white-space: pre;} ``` # And here's a version with a monospaced font, **~~247~~ 246 bytes**. *-1 byte thanks to Stephen S, extra spaces removed* ``` html:after{font-family:'Courier';content:' _ _ _ \A /_/_/_/\005c\A /_/_/_/\005c/\005c \A /_/_/_/\005c/\005c/\005c \A \005c_\005c_\005c_\005c/\005c/\005c/ \A \005c_\005c_\005c_\005c/\005c\/\A \005c_\005c_\005c_\005c /';white-space: pre;} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~32~~ 31 bytes ``` "/ _\"•₁7æ¤ÝI}?ÕR&Ü•4вè4ôJ€∞ø¨» ``` [Try it online!](https://tio.run/##AT4Awf8wNWFiMWX//yIvIF9cIuKAouKCgTfDpsKkw51JfT/DlVImw5zigKI00LLDqDTDtErigqziiJ7DuMKowrv//w "05AB1E – Try It Online") 100% different method than Emigna. --- **Edit:** If I start with the pattern already transposed I can cut out 3 bytes. --- ``` "/ _\" # Push ASCII-art characters used. •₁7æ¤ÝI}?ÕR&Ü•4в # Push transposed version of base-4 pattern. è # Replace all digits in base-4 number with appropriate symbol. 4ô # Split into groups of 4. J # Join together. €∞ # Mirror each row (technically column). ø # Transpose back. ¨» # Remove the extra "_ _ _", and print with newlines. ``` [Answer] # JavaScript (ES6), 95 bytes ``` _=>String.raw` _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/` ``` # JavaScript (ES6), ~~103~~ 94 bytes *-9 bytes thanks to @Shaggy* ``` _=>` _ _ _ ${a=`/_/_/_/\\`} ${a}/\\ ${a}/\\/\\ ${b=`\\_\\_\\_\\/`}\\/\\/ ${b}\\/ ${b}` ``` # JavaScript (ES6), 106 bytes ``` _=>` _ _ _ /_/_/_/\\ /_/_/_/\\/\\ /_/_/_/\\/\\/\\ \\_\\_\\_\\/\\/\\/ \\_\\_\\_\\/\\/ \\_\\_\\_\\/` ``` [Answer] # Ruby, ~~72~~ 70 bytes ``` 7.times{|i|puts' '*(j=i^i/4+3)+'_ \_/_'[-i/3*2,2]*3+'/\/'[i/4,2]*j^=3} ``` Latest edit: avoid double `\` by enclosing strings in `''` instead of `""`. **Ungolfed** (note in Ruby negative string indexes wrap around. `-1` is the last character.) ``` 7.times{|i| #7 lines. puts" "*(j=i^i/4+3)+ #Print j= 3,2,1,0, 0,1,2 spaces. "_ \\_/_"[-i/3*2,2]*3+ #Print 3 repeats of 2 characters from the string, index 0,-2,-2,-2,-4,-4,-4. "/\\/"[i/4,2]*j^=3 #Print 2 characters from the string, /\ or \/, repeated 3^j times. } ``` [Answer] # Windows Batch, 122 bytes ``` @echo _ _ _ @echo /_/_/_/\ @echo /_/_/_/\/\ @echo /_/_/_/\/\/\ @echo \_\_\_\/\/\/ @echo \_\_\_\/\/ @echo \_\_\_\/ ``` Pretty self-explantory. [Answer] ## Brainf\*ck 387 bytes Not even sure if this is still a thing but I was bored and did it for sh\*ts and giggles :) ``` ++++++++[->++++>++++>++++>++++<<<<]+++++[->>+++>+++>+++<<<<]<+++[->+++++<]>[->>>+++>+++<<<<]>>>>+++<<<...<+++[->.>>>.<<<<]<<++++++++++>+++++++++++++.<.>>>..>.<<+++[->>>>.<<.<<]>>>.<<<<.<.>>>.>.<<+++[->>>>.<<.<<]>>>.<.>.<<<<.<.>>>>.<<+++[->>>>.<<.<<]>>>.<.>.<.>.<<<<.<.>>>>>.<<<+++[->>>>.<.<<<]>>.>.<.>.<.<<<.<.>>>.>>.<<<+++[->>>>.<.<<<]>>.>.<.<<<.<.>>>..>>.<<<+++[->>>>.<.<<<]>>.<<<.<.>> ``` Edit: TIL: I am 54.28% more effective than some generator I found online ^.^ Edit2: [Try it online](https://copy.sh/brainfuck/?c=KysrKysrKytbLT4rKysrPisrKys-KysrKz4rKysrPDw8PF0rKysrK1stPj4rKys-KysrPisrKzw8PDxdPCsrK1stPisrKysrPF0-Wy0-Pj4rKys-KysrPDw8PF0-Pj4-KysrPDw8Li4uPCsrK1stPi4-Pj4uPDw8PF08PCsrKysrKysrKys-KysrKysrKysrKysrKy48Lj4-Cj4uLj4uPDwrKytbLT4-Pj4uPDwuPDxdPj4-Ljw8PDwuPC4-Pgo-Lj4uPDwrKytbLT4-Pj4uPDwuPDxdPj4-LjwuPi48PDw8LjwuPj4KPj4uPDwrKytbLT4-Pj4uPDwuPDxdPj4-LjwuPi48Lj4uPDw8PC48Lj4-Cj4-Pi48PDwrKytbLT4-Pj4uPC48PDxdPj4uPi48Lj4uPC48PDwuPC4-Pgo-Lj4-Ljw8PCsrK1stPj4-Pi48Ljw8PF0-Pi4-LjwuPDw8LjwuPj4KPi4uPj4uPDw8KysrWy0-Pj4-LjwuPDw8XT4-Ljw8PC48Lj4-) Make sure Wrap is on for Memory overflow behaviour in the options [Answer] # COBOL, 238 bytes Compiled with open-cobol. Note that the indentation is a single tab, not spaces, even if this website formats it that way. ``` IDENTIFICATION DIVISION. PROGRAM-ID. a. PROCEDURE DIVISION. DISPLAY " _ _ _". DISPLAY " /_/_/_/\". DISPLAY " /_/_/_/\/\". DISPLAY "/_/_/_/\/\/\". DISPLAY "\_\_\_\/\/\/". DISPLAY " \_\_\_\/\/". DISPLAY " \_\_\_\/". STOP RUN. ``` [Answer] # [Perl 5](https://www.perl.org/), 89 bytes ``` say" _ _ _";$r[7-$_]=($r[$_]=$"x(3-$_).'/_'x3 .'/\\'x$_.$/)=~y|/\\|\\/|r for 1..3;say@r ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJJQUEhHgSVrFWKos11VeJjbTWALBCtolShYQwU0dRT149XrzBWANIxMeoVKvF6KvqatnWVNUBuTUyMfk2RQlp@kYKhnp6xNdBMh6L////lF5Rk5ucV/9f1NdUzMDQAAA "Perl 5 – Try It Online") [Answer] # Deadfish~, 687 bytes ``` {iii}iiccc{iiiiii}iiic{dddddd}dddc{iiiiii}iiic{dddddd}dddc{iiiiii}iiic{{d}ii}dddddc{ii}iicc{i}iiiiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{{d}ii}ddc{ii}iic{i}iiiiic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{{d}ii}ddc{iiii}dddc{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiiii}ddc{ddddd}iic{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{{d}ii}ddc{{i}dd}iiciiicdddciiicdddciiicdddc{dddd}dddddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiic{dddd}dddddc{dddd}iiic{ii}iic{iiiiii}ciiicdddciiicdddciiicdddc{dddd}dddddc{iiii}iiiiic{dddd}dddddc{dddd}iiic{ii}iicc{iiiiii}ciiicdddciiicdddciiicdddc{dddd}dddddc ``` [Try it online!](https://deadfish.surge.sh/#Wksa932yULJJQFiV//f8oCxK//v+UBYlV2X/8oskpYJQL+V/9koF/K/+yUC/lf/ZKCwSq7L+UWSlglAv5X/2SgX8r/7JQL+V/9koLBK/7/+UFglV2X8oL/lAv5X/2SgX8r/7JQL+V/9koLBK/7/+UFglf9//KCwSq7L+VS/sgn8E/gn8r/v/5QWCV/3/8oLBK/7/+V/2JRZKAuCfwT+Cfyv+//lBYJX/f/yv+xKLJKAuCfwT+Cfyv+//gA==) [Answer] # [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 86 bytes Replace the ␀ with an actual null byte (0x00). ``` <[.<]␀/\_\_\_\ /\/\_\_\_\ /\/\/\_\_\_\ \/\/\/_/_/_/ \/\/_/_/_/ \/_/_/_/ _ _ _ ``` [Try it online!](https://tio.run/##K85NSvv/3yZazyaWQT8mHgwVFLj0Y@AcMBvG4wKz9ePBkAvBVOCCsxS44hVAUEHh/38A "Self-modifying Brainfuck – Try It Online") ## Explanation Another literal output answer. ``` <[.<] - Print the source code in reverse until a NULL byte is found. ␀ - Null, replace with 0x00. Ends program. <the rest> - The cube in reverse. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, ~~33~~ 32 bytes -1 bytes thanks to Aaron Miller ``` »\!¡øoΠ¥⅛831‟½ø↲p∇±₀WṀ»‛_ k/+τ7/ ``` ## Explanation ``` »\!¡øoΠ¥⅛831‟½ø↲p∇±₀WṀ» - Push a base-4 number containing the cube ‛_ k/+τ - Change to custom base, replacing the numbers with the symbols. 7/ - Divide into seven lines. <j flag> - Join by newlines <implicit output> - Print it! ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=j&code=%C2%BB%5C!%C2%A1%C3%B8o%CE%A0%C2%A5%E2%85%9B831%E2%80%9F%C2%BD%C3%B8%E2%86%B2p%E2%88%87%C2%B1%E2%82%80W%E1%B9%80%C2%BB%60_%20%2F%5C%5C%60%CF%847%2F&inputs=&header=&footer=) [Answer] # Zsh, 86 bytes Port of the PHP solution. [Try it online!](https://tio.run/##JYYxDsAwCMR2XnEbYyBr8xSkLK3anS3i75S0smV5@ZPp1wn2kGjzIw4PDbMWd12vm7/BYwwGMDcEiBFEjUQrXVUJfafKmS8) ``` sed 's|0|/_/_/_/|;s|1|\\/|g;s|2|\\_\\_\\_|'<<<' _ _ _ 0\ 01\ 011\ 2111 211 21' ``` But the naïve approach only costs 1 extra, for [87 bytes](https://tio.run/##qyrO@P9fwcbGRl0BCOJBkEtBQT8eDGO44CwgG8EEcmLiwRDM41JA8ICaYRz1//8B) ... ``` <<<' _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/' ``` [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` print r""" _ _ _ /_/_/_/\ /_/_/_/\/\ /_/_/_/\/\/\ \_\_\_\/\/\/ \_\_\_\/\/ \_\_\_\/""" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EoUhJSUlBQSEeBLkUFPTjwTCGC84CshFMICcmHgzBPC4FBA@oGcYBGvn/PwA "Python 2 – Try It Online") ]
[Question] [ The goal of a Rosetta Stone Challenge is to write solutions in as many languages as possible. Show off your programming multilingualism! # The Challenge Your challenge is to implement a program that will input a list of numbers and output the rule used to generate each successive number in the series, *in as many programming languages as possible*. You are allowed to use any sort of standard library function that your language has, since this is mostly a language showcase. ## What is a "series?" A series is an ordered list of integers. Each successive number in the series can be generated by applying a simple rule to the previous number in the series. In this challenge, the rule consists of multiplying the number by a constant, and then adding a second constant. Both of the constants can be any integer. The goal of this challenge is to output those two constants. For the series `2 5 11`, the rule can be written as `2 1`. This means that each number is the previous number, times 2, plus 1. An important fact is that most series have exactly one rule. Some series have either an infinite number or none at all, but you will not have to deal with this. ## Input Input will be a list of three different integers which are the numbers in the sequence. The numbers can be either space, comma, or newline delimited, but please specify which. I am going to be flexible on this limitation because certain languages may have input restrictions. Here are four examples of input: ``` 0 7 14 2 5 11 2 0 -4 5 -19 77 ``` ## Output Output will be two integers which represent the rule used to generate the series. The first number will be the multiplicative constant, while the second number will be the additive constant. The formatting of the output can be space, comma, or newline delimited. I am flexible on this limitation as well. Here are the corresponding examples of output: ``` 1 7 2 1 2 -4 -4 1 ``` # The Objective Winning Criterion As for an objective winning criterion, here it is: Each language is a separate competition as to who can write the shortest entry, but the overall winner would be the person who wins the most of these sub-competitions. This means that a person who answers in many uncommon languages can gain an advantage. Code-golf is mostly a tiebreaker for when there is more than one solution in a language: the person with the shortest program gets credit for that language. ## Rules, Restrictions, and Notes Your program can be written in any language that existed prior to April 9th, 2012. I will also have to rely on the community to validate some responses written in some of the more uncommon/esoteric languages, since I am unlikely to be able to test them. --- # Current Leaderboard This section will be periodically updated to show the number of languages and who is leading in each. * AWK (32) - mellamokb * bash (31) - Peter Taylor * Befunge (29) - Howard * bc (39) - kernigh * brainfuck (174) - CMP * C (78) - l0n3\_shArk * C++ (96) - leftaroundabout * Common Lisp (88) - kernigh * Cray Chapel (59) - Kyle Kanos * csh (86) - kernigh * Cuda (301) - leftaroundabout * dc (30) - kernigh * DOS BATCH (54) - mellamokb * Element (27) - Howard * es (95) - kernigh * Factor (138) - kernigh * Felix (86) - kirbyfan64sos * Fortran (44) - Kyle Kanos * Go (101) - Howard * GolfScript (16) - Howard * Golflua (44) - Kyle Kanos * Haskell (35) - leftaroundabout * J (23) - Gareth * Java (141) - Howard * JavaScript (47) - mellamokb * Julia (71) - M L * Lua (51) - Howard * Mercury (319) - leftaroundabout * MoonScript (48) - kirbyfan64sos * Nimrod (146) - leftaroundabout * Owl (22) - r.e.s. * Pascal (88) - leftaroundabout * Perl (57) - Gareth * PHP (61) - mellamokb * PicoLisp (72) - kernigh * Piet (56) - M L * PostScript (61) - Howard * Python (40) - Howard * Q (36) - tmartin * QBasic (34) - mellamokb * R (50) - r.e.s. * Ruby (44) - Howard * Scala (102) - Gareth * SQL (57) - Aman ZeeK Verma * TI-83 BASIC (25) - mellamokb * Unlimited Register Machine (285) - Paxinum * VBA (57) - Gaffi * Whitespace (123) - r.e.s. * zsh (62) - kernigh --- # Current User Rankings Equal ranks are sorted alphabetically. 1. Howard (9): Befunge (29), Element (27), Go (101), GolfScript (16), Java (141), Lua (51), PostScript, (61) Python, (40) Ruby (44) 2. kernigh (8): bc (39), Common Lisp (88), csh (86), dc (30), es (95), Factor (138), PicoLisp (72), zsh (62) 3. leftroundabout (6): C++ (96), Cuda (301), Haskell (35), Mercury (319), Nimrod (146), Pascal (88) 4. mellamokb (6): AWK (32), DOS BATCH (54), JavaScript (47), PHP (61), QBasic (34), TI-83 BASIC (41) 5. Gareth (3): J (23), Perl (57), Scala (102) 6. Kyle Kanos (3): Cray Chapel (59), Fortran (44), Golflua (44) 7. r.e.s. (3): Owl (22), R (50), Whitespace (123) 8. kirbyfan64sos (2): Felix (86), MoonScript (48) 9. M L (2): Julia (71), Piet (56) 10. Aman Zeek verma (1): SQL (57) 11. CMP (1): brainfuck (174) 12. Gaffi (1): VBA (57) 13. l0n3\_shArk (1): C (78) 14. Paxinum (1): Unlimited Register Machine (285) 15. Peter Taylor (1): bash (31) 16. tmartin (1): Q (36) [Answer] ## QBasic, 42 ``` INPUT "",a,b,c m=(c-b)/(b-a) PRINT m;b-m*a ``` Requires input with commas, outputs with spaces (is this ok?) --- ## Mercury, 319 ``` :-module r. :-interface. :-import_module io,list,int,char,string. :-pred main(io::di,io::uo)is det. :-implementation. main(!IO):-io.read_line_as_string(J,!IO),(if J=ok(I),[A,B,C]=list.map(string.det_to_int,string.words_separator(char.is_whitespace,I)),M=(C-B)/(B-A)then io.format("%d %d",[i(M),i(B-M*A)],!IO)else true). ``` --- ## Haskell, ~~85~~ 81 ``` f[a,b,c]|m<-(c-b)`div`(b-a)=[m,b-m*a] main=getLine>>=mapM_ print.f.map read.words ``` Now inputs with spaces, outputs with newlines. --- ## C, 80 ``` main(a,b,c,m){scanf("%d %d %d",&a,&b,&c);m=(c-b)/(b-a);printf("%d %d",m,b-m*a);} ``` --- ## C++, 96 ``` #include<iostream> main(){int a,b,c,m;std::cin>>a>>b>>c;m=(c-b)/(b-a);std::cout<<m<<' '<<b-m*a;} ``` --- ## Nimrod, 146 ``` import strutils var q:array[0..3,int] b,m:int for i in 0..2:q[i]=ParseInt(readLine(stdin)) b=q[1] m=(q[2]-b)div(b-q[0]) echo($m,",",$(b-m*q[0])) ``` Input w/ newlines, output comma. --- This one won't count, but I feel it still fits in in some way: ## Mathematical theorem, 713 characters of LaTeX ``` \documentclass{article}\usepackage{amsmath}\usepackage{amsthm}\begin{document}Theorem: for a sequence $(a_i)_i$ of integers with $a_2\neq a_1$ where $a_3-a_2$ is divisible by $a_2-a_1$, $m:=\frac{a_3-a_2}{a_2-a_1},\ p:=a_2-m\cdot a_1$ give rise to a sequence\[b_i:=\begin{cases}a_1&\text{for }i=1\\b_{i-1}\cdot m+p&\text{else}\end{cases}\] such that $b_i=a_i\ \forall i\leq 3$. Proof: $i=1$ is trivial,\[\begin{aligned}b_2=&b_1\cdot m+p=a_1\frac{a_3-a_2}{a_2-a_1}+a_2-\frac{a_1a_3-a_1a_2}{a_2-a_1}=a_2,\\b_3=&b_2\cdot m+p=\frac{a_2a_3-a_2^2}{a_2-a_1}+a_2-\frac{a_1a_3-a_2^2}{a_2-a_1}\\=&\frac{a_2a_3-a_1a_3+(a_2-a_1)a_2-a_2^2+a_1a_2}{a_2-a_1}\\=&\frac{a_2-a_1a_3+0}{a_2-a_1}=a_3.\end{aligned}\]\qed\end{document} ``` ![Output of the LaTeX mathematical-theorem solution](https://i.stack.imgur.com/ymax6.png) --- While we're at writing `:=` definitions... ## Pascal, ~~90~~ 88 ``` program r;var a,b,c:integer;begin;read(a,b,c);c-=b;c:=c div(b-a);write(c,' ',b-c*a);end. ``` --- ## Cuda, 301 ``` #include<stdio.h> __global__ void r(int*q){if(!(blockIdx.x|threadIdx.x)){q[1]-=*q;q[1]/=(*q-q[2]);*q-=q[1]*q[2];}} main(){int p[3],*q;scanf("%d%d%d",p+2,p,p+1);cudaMalloc(&q,24);cudaMemcpy(q,p,24,cudaMemcpyHostToDevice);r<<<1,1>>>(q);cudaMemcpy(p,q,24,cudaMemcpyDeviceToHost);printf("%d %d",p[1],*p);} ``` [Answer] ### GolfScript, 16 characters ``` ~1$- 1$3$-/.p@*- ``` Input is given as space-separated list. ### JavaScript, 56 characters ``` p=prompt;x=alert;a=p();b=p();x(m=(p()-b)/(b-a));x(b-a*m) ``` Input is given on prompt. ### Ruby, 44 characters ``` a,b,c=eval("[#{gets}]");m=c-b;p m/=b-a,b-m*a ``` Input is here given as comma-separated list. ### Python, 40 characters ``` a,b,c=input();m=c-b;m/=b-a;print m,b-m*a ``` Input is again comma-separated. ### Java, 141 characters ``` enum E{E;static int s(){return new java.util.Scanner(System.in).nextInt();}{int a=s(),b=s(),m=s()-b;m/=b-a;System.out.print(m+" "+(b-a*m));}} ``` Input separated by newline. ### Lua, 51 characters ``` r=io.read a,b=r(),r() m=(r()-b)/(b-a) print(m,b-m*a) ``` Input separated by newline. ### Go, 101 characters ``` package main import"fmt" var a,b,c int func main(){fmt.Scan(&a,&b,&c) c-=b c/=b-a fmt.Print(c,b-a*c)} ``` Input separated by newline. ### Fortran, 90 characters ``` PROGRAM X READ(*,*)I,J,K K=(K-J)/(J-I) WRITE(*,*)K,J-I*K END ``` Input separated by newline. ### Befunge, 29 characters ``` &01p&:11p:&-01g11g-/:.01g*-.@ ``` ### PostScript, 61 characters ``` 2 5 14 1 index sub 1 index 3 index sub idiv dup = 3 2 roll mul sub = ``` ### Owl, 23 characters ``` <%<%<$-1`4'-/%.32)2'*-. ``` Input separated by newline. ### [Element](https://codegolf.stackexchange.com/questions/1171#5268), 27 characters ``` _-a;_3:'-_+"a~+/2:`a~*+\ `` ``` Input separated by newline. [Answer] ## Brainfuck - 174 ``` ,>,>,<[>->+>+<<<-]>>>[<<<+>>>-]<<<<[>>>->+<<<<-]>>>>[<<<<+>>>>-]<<[->- [>+>>]>[+[-<+>]>+>>]<<<<<]>>>[<<<+>>>-]<[-]<[-]<.[>>+<<-]>>[<<<<[>>+>+ <<<-]>>>[<<<+>>>-]>-]<<[<->-]<. ``` ## Piet - 82? Not sure how to measure competitive golf here. I'm gonna go with total image size (in codels) Mine is 41x2: ![enter image description here](https://i.stack.imgur.com/jNKn3.png) ## Befunge - 34 ``` &00p&10p&10g-10g00g-/:.00g*10g\-.@ ``` ## English - 278 ``` The multiplier is the quotient of the difference of the second and third values and the second and first values. To generate a new term, multiply the current term by the multiplier and add the difference of the first value and the product of the multiplier and the second value. ``` Not sure if this counts, but thought I'd give it a shot. It is remarkably difficult to describe even a simple algorithm accurately. Kinda wish English supported some kind of grouping symbol to establish precedence. [Answer] ## AWK, 35 characters ``` {m=($3-$2)/($2-$1);print m,$2-$1*m} ``` * Input format: `2 0 -4` ## bc, 39 characters ``` define f(a,b,c){ m=(c-b)/(b-a) m b-a*m} ``` * Input format: `z=f(2, 0, -4)` * The input is a `bc` expression. After `bc` reads the source file, it reads the standard input. This is why the input must look like a function call. * I use OpenBSD `bc`, which requires a newline after the `{`. ## Common Lisp, 88 characters ``` (let*((a(read))(b(read))(c(read))(m(/(- c b)(- b a))))(format t "~A ~A" m (- b(* a m)))) ``` * Input format: `2 0 -4` ## csh, 86 characters ``` set i=(`cat`) @ m=($i[3] - $i[2]) / ($i[2] - $i[1]) @ n=$i[2] - $i[1] * $m echo $m $n ``` * Input format: `2 0 -4` * The 86th character is newline at end of file. `csh` is the only language for which I count newline at end of file. This is because `csh` never runs the last command unless newline is there. * `set i=($<)` does not work, because `$<` has no word splitting. ## dc, 30 characters ``` ?scsbsalclb-lbla-/psmlblalm*-p ``` * Input format: `2 0 _4`, where `_` is the underscore. ## es, 95 characters ``` i=(`cat) b=$i(2) m=`{expr \( $i(3) - $b \) / \( $b - $i(1) \)} echo $m `{expr $b - $i(1) \* $m} ``` * Input format: `2 0 -4` * `es` is the *extensible shell* by Paul Haahr and Byron Rakitzis. ## Factor, 138 characters ``` USING: eval formatting io kernel locals math ; contents eval( -- a b c ) [let :> ( a b c ) c b - b a - / dup a * b swap - "%d %d" printf ] ``` * Input format: `2 0 -4` ## PicoLisp, ~~74~~ 72 characters ``` (in()(let(r read a(r)b(r)c(r)m(/(- c b)(- b a)))(print m (- b(* a m))))) ``` * Input format: `2 0 -4` * EDIT: Lost 2 characters by changing `a(read)b(read)c(read)` to `r read a(r)b(r)c(r)`. ## TI-83 BASIC, ~~63~~ 61 characters ``` :Input A :Input B :Input C :(C-B)/(B-A)→M :Disp M :Disp B-A*M ``` * Input format: `2` ENTER `0` ENTER `¯4` ENTER, where `¯` is the calculator's unary minus. * I counted Unicode characters; `→` (the right arrow) counts as U+2192. For example, the calculator counts `Input A` as 2 characters, but I count `Input A` as 7 characters. I also count `:` as 1 character. * EDIT: I miscounted: there are 61, not 63, characters. ## zsh, 62 characters ``` i=(`cat`) ((b=i[2],m=(i[3]-b)/(b-i[1]),n=b-i[1]*m)) echo $m $n ``` * Input format: `2 0 -4` [Answer] ## AWK (32) ``` {m=$3-$2;print m/=$2-$1,$2-$1*m} ``` Demo: <http://ideone.com/kp0Dj> --- ## bash (38) ``` awk '{m=$3-$2;print m/=$2-$1,$2-$1*m}' ``` Demo: <http://ideone.com/tzFi8> --- ## DOS/BATCH (54 55) ``` set/a m=(%3-%2)/(%2-%1)&set/a n=%2-%m%*%1&echo %m% %n% ``` Takes parameters as space-separated list of arguments. --- ## Java (143 185) > > `enum R{R;{int a=0,b=0,c,i=2;for(;(c=new java.util.Scanner(System.in).nextInt()+b*--i)+i>=c;b=c)a+=c*i;c/=b-a;System.out.print(c+" "+(b-a*c));}}` > > > --- ## JavaScript (48 61 67) ``` p=prompt;m=p(b=p(a=p()))-b;alert([m/=b-a,b-a*m]) ``` ​ Demo: <http://jsfiddle.net/BT8bB/6/> --- ## PHP (61 77) ``` <?list(,$a,$b,$c)=$argv;$c-=$b;echo($c/=$b-$a).' '.$b-=$c*$a; ``` Demo: <http://ideone.com/CEgke> --- ## QBasic (34) ``` INPUT a,b,c m=(c-b)/(b-a) ?m;b-m*a ``` --- ## TI-83 Basic (25 ~~41~~) ``` :Prompt A,B,C :(C-B)/(B-A :Disp Ans,B-AAns ``` Yes, the missing right parenthesis is on purpose. It's a well-known optimization technique that closing the parentheses before a STO operation is not necessary in TI-83 Basic programming. [Answer] ## Whitespace, 123 ``` ``` I/O is newline-separated. (To obtain the source code, enter edit mode and copy the whitespace between the preformat tags; or, see the online [example at Ideone](http://ideone.com/yEpjd).) Explanation, where S,T,L represents Space,Tab,Linefeed: ``` Pseudocode Whitespace ---------- ---------- push 0 SS SSL readn TLTT push 1 SS STL readn TLTT push 2 SS STSL dup SLS readn TLTT retr TTT push 1 SS STL retr TTT - TSST push 1 SS STL retr TTT push 0 SS SSL retr TTT - TSST / TSTS dup SLS outn TLST push 10 SS STSTSL outc TLSS push 0 SS SSL retr TTT * TSSL push 1 SS STL retr TTT swap SLT - TSST outn TLST exit LLL ``` --- ## R, 50 ``` x=scan(n=3);y=diff(x);z=y[2]/y[1];c(z,x[2]-x[1]*z) ``` I/O is space-separated. --- ## Owl **---22---** ``` < <%<-2`2`-/%.10)2'*-. ``` I/O is newline-separated. **---19---** (if this version is allowed; but I think it's cheating, since the \ is executable code): ``` 1`-1`3`-/%.32)2'*-. ``` I/O is space-separated. Command-line usage: `owl prog 5 19\ 77` (the \ acts as a postfix unary minus in Owl). [Answer] ## J, 23 characters ``` (],1{x-0{x*])%~/2-/\x=: ``` Usage: ``` (],1{x-0{x*])%~/2-/\x=: 5 _19 77 _4 1 ``` Negative numbers are represented by underscores in J. ## PHP, 88 characters ``` <?php list($x,$y,$z)=split(' ',fgets(STDIN)); $a=($z-$y)/($y-$x); echo$a." ".($y-$a*$x); ``` ## Scala, 102 characters ``` val x=readLine.split(" ").toList.map(_.toInt) val a=(x(2)-x(1))/(x(1)-x(0)) print(a+" "+(x(1)-x(0)*a)) ``` ## Perl, 57 characters ``` s!(.+) (.+) (.+)!$a=($3-$2)/($2-$1);$a." ".($2-$1*$a)!e ``` Requires the '-p' option, for which I have added 2 characters. Assumes that the input is valid to save some characters. All my answers take space separated numbers. [Answer] ## PHP, 74,72,69 ``` <?fscanf(STDIN,'%d%d%d',$a,$b,$c);echo($d=($c-$b)/($b-$a)).' '.($b-$d*$a); ``` When input is passed as arguments: ``` <?echo($d=($argv[3]-$argv[2])/($b=$argv[2]-$a=$argv[1])).' '.($b-$d*$a); ``` Now, as @mellamokb suggested, using $n=$argv: ``` <?$n=$argv;echo($d=($n[3]-$n[2])/($b=$n[2]-$a=$n[1])).' '.($b-$d*$a); ``` ## C, 77,78 ``` main(a,b,c,d){printf("%d %d",d=(c-b)/(b-a),b-d*a,scanf("%d%d%d",&a,&b,&c));} ``` ^ doesn't work so, here's the stuff: [thanks to @ugoren for bringing it to notice] ``` main(a,b,c,d){printf("%d %d",d,b-a*(d=(c-b)/(b-a)),scanf("%d%d%d",&a,&b,&c));} ``` [Answer] ## VBA, 57 characters ``` Sub x(a,b,c) y=(c-b)/(b-a) MsgBox y & " " & b-a*y End Sub ``` (*This is basically the same as the other 'BASIC' functions, but I didn't see any VBA submissions out there already.*) [Answer] ### bash (42 chars) Pure bash: ``` ((m=($3-$2)/($2-$1),c=$2-m*$1));echo $m $c ``` ### bash (31 chars) Shelling out to something else: ``` owl -p"<%<%<$-1`4'-/%.32)2'*-." ``` (Based on Howard's [OWL implementation](https://codegolf.stackexchange.com/questions/5429/rosetta-stone-challenge-find-the-rule-for-a-series/5432#5432)) [Answer] This is (non-optimized) code for the unimited register machine, described here: <http://www.proofwiki.org/wiki/Definition:Unlimited_Register_Machine> The input should be in register 1,2 and 3, and the output will be in register 1, 2 after the program is done. Non-negative and non-integer numbers are not handled, but inputs 0,7,14 and 2,5,11 are handled correctly. `Zero[8] Trans[2,11] Jump[3,11,7] Succ[11] Succ[8] Jump[11,11,3] Zero[5] Trans[1,12] Jump[2,12,13] Succ[12] Succ[5] Jump[12,12,9] Zero[17] Trans[8,13] Jump[13,17,25] Zero[16] Trans[5,14] Jump[13,14,22] Succ[14] Succ[16] Jump[14,14,18] Succ[9] Trans[16,13] Jump[17,17,15] Zero[6] Zero[20] Jump[9,6,40] Zero[7] Trans[1,21] Jump[20,7,36] Succ[21] Trans[21,19] Trans[19,21] Succ[7] Jump[7,7,30] Trans[21,18] Trans[18,20] Succ[6] Jump[6,6,27] Trans[20,4] Zero[10] Trans[4,15] Jump[2,15,47] Succ[15] Succ[10] Jump[15,15,43] Trans[9,1] Trans[10,2]` EDIT: by removing brackes, and shortening instruction names: **URM 285** `Z8 T2,11 J3,11,7 S11 S8 J11,11,3 Z5 T1,12 J2,12,13 S12 S5 J12,12,9 Z17 T8,13 J13,17,25 Z16 T5,14 J13,14,22 S14 S16 J14,14,18 S9 T16,13 J17,17,15 Z6 Z20 J9,6,40 Z7 T1,21 J20,7,36 S21 T21,19 T19,21 S7 J7,7,30 T21,18 T18,20 S6 J6,6,27 T20,4 Z10 T4,15 J2,15,47 S15 S10 J15,15,43 T9,1 T10,2` [Answer] # DOS-BATCH, 98 ``` @ECHO OFF&SET/P p=&SET/P q=&SET/P r=&SET/A m=(%r%-%q%)/(%q%-%p%)&SET/A n=%q%-%p%*%m%&ECHO %m% %n% ``` Input in separate lines # Bash, 51 ``` m=$((($3 - $2)/($2 - $1))) echo $m $(($2 - $m*$1)) ``` Example : `sh prog.sh 2 0 -4` (space separated arguments) # Perl, 84 ``` @s=split(/ /,&lt;STDIN&gt;);$m=($s[2]-$s[1])/($s[1]-$s[0]);print $m." ".($s[1]-$s[0]*$m); ``` # Java, 297 ``` import java.util.*;public class A{public static void main(String a[]){StringTokenizer s=new StringTokenizer(new Scanner(System.in).nextLine());int i=4;int[] p=new int[i];while(i-->1)p[3-i]=Integer.parseInt(s.nextToken());p[3]=(p[2]-p[1])/(p[1]-p[0]);System.out.print(p[3]+" "+(p[1]-p[0]*p[3]));}} ``` Space separated input, space separated output. # SQL, 57 ``` select (&3-&2)/(&2-&1),&2-((&3-&2)/(&2-&1)*&1) from dual ``` This is a sad entry, but 'just' solves the purpose. The query binds input at runtime 1,2,3 are variables in order of input. [Answer] # Q, 36 ``` {a,x[2]-x[1]*a:%[x[2]-x 1;x[1]-x 0]} ``` usage ``` q){a,x[2]-x[1]*a:%[x[2]-x 1;x[1]-x 0]}each(0 7 14;2 5 11;2 0 -4;5 -19 77) 1 7 2 1 2 -4 -4 1 ``` [Answer] ## Fortran 44 ``` read*,i,j,k;k=(k-j)/(j-i);print*,k,j-i*k;end ``` Input will be in a single line (comma or space separated) ## [Cray Chapel](http://chapel.cray.com/) 59 ``` var i,j,k:int;read(i,j,k);k=(k-j)/(j-i);write(k," ",j-i*k); ``` Input will be on single line, no newline (add 2 chars for that by using `writeln` in place of `write`). ## [Golflua](http://mniip.com/misc/conv/golflua/) 44 ``` r=I.r;a,b=r(),r();m=(r()-b)/(b-a);w(m,b-m*a) ``` Newline delimited input, space delimited output [Answer] # Julia, 71 characters Space delimited input and output. `i,j,k=int(split(readline(STDIN)));println("$(l=div(k-j,j-i)) $(j-i*l)")` Example input and output: ``` julia> i,j,k=int(split(readline(STDIN)));println("$(l=div(k-j,j-i)) $(j-i*l)") 5 -19 77 -4 1 ``` # Piet, ~~86~~ ~~60~~ 56 codels (14x4), codel size 10 for better visibility I could actually shrink down the amount of codels by a whopping 35%. I didn’t expect such a good outcome. Coding this program backwards was, as I expected, quite successful. I doubt it can be shorter than this, but I would be really interested if anyone could find a smaller solution. The challenge does not state if the program has to stop after showing the result, so my smallest (56 codel) program should be valid. It just loops back to the beginning after showing the result, asking for a new triplet of integers. Due to the tight packing there is no place for the output of two newline characters, but that is no problem with the npiet interpreter, because it always prints a ‘?’ if it awaits input. There are two possible sizes to build a looped version, but a version that runs only once is only possible in a program that’s at least 64 codels (16x4) big. The versions below show the reason. Maybe it’s also interesting for those who are familiar with Piet. **The final, most tightly packed 56 codel version, with a loop**: ![Find Rule For A Series 56 codels](https://i.stack.imgur.com/GYgMt.png) Second version (60 codels), with a loop ![Find Rule For A Series 60 codels](https://i.stack.imgur.com/IPbUl.png) If the 56 codel version is against the rules, here is the **final 64 codel version, running only once**: ![Find Rule For A Series 64, run once](https://i.stack.imgur.com/rxljO.png) My first version (86 codels) ![Find Rule For A Series 86 codels](https://i.stack.imgur.com/t4uk6.png) Input and output are newline delimited. Example input and output: ``` D:\codegolf\npiet-1.3a-win32>npiet ml_series.png ? 5 ? -19 ? 77 -4 1 ``` For looped versions, looking a bit uglier: ``` D:\codegolf\npiet-1.3a-win32>npiet ml_series_56_codels.png" ? 5 ? -19 ? 77 -4 1? 5 ? -19 ? 77 -4 1? 5 ? -19 ? 77 -4 1? ``` I chose newline as delimiter because coding ASCII 10 (\n) obviously needs only 7 codels, compared to ASCII 32 ( ) which needs 8 codels or even ASCII 40 (,) which needs 9 codels. Coding backwards from the result to the first input is a great way to reduce the codel use for ROL operations. The stack order at the beginning and at the end are known, the rest is easily done by hand. Here is a text version of the 64 codel program (with stack), in my made-up shorthand. The shorter programs just don’t terminate but loop back to the beginning. ``` NOP ADD DIV GRT DUP INC END 0 + / > = c ~ PSH SUB MOD PTR ROL OUN X - % # @ N POP MUL NOT SWI INN OUC ? * ! $ n C 1 1 1 2 2 1 a,b,c: input for series 5 5 3 3 c c cb 3 3 D: c-b b b bb b bbb b bcD D Da E: b-a bb b bb b baa a aaa a abE F F: D/E, (c-b)/(b-a), mul. const. bbb b ba a abb b bbb b bDDFFF 5 G: a*F, a(c-b)/(b-a) aaaa a aa a aaa a aaa a aaaaaaG 55 10 H: b-G, b-a*F, add. const. aaaaa a ab b bbb b bbb b bbbbbbbH HH H H n=n==5X1X@3X1X@n2X1X@-3X1X@-/=N*-5X= + CN~ | | | | || |||\____/ || | | | | || ||| | |+———— output add. const. | | | | || ||| | +————— output newline character | | | | || ||| +—————————— 5 DUP + =10, ASCII for \n | | | | || ||+————————————— H, add. const. | | | | || |+—————————————— G | | | | || +——————————————— output mul. const. | | | | |+————————————————— F, mul. const. | | | | +—————————————————— E | | | +———————————————————————— D | | +—————————————————————————————— input c | +——————————————————————————————————————————— input b +————————————————————————————————————————————— input a ``` [Answer] # MoonScript(48 chars, newline delimited input, space delimited output) ``` r=io.read a,b=r!,r! m=(r!-b)/(b-a) print m,b-m*a ``` # Felix(86 chars, newline delimited input, comma delimited output) ``` gen r()=>int $ readln stdin; var a,b=r(),r(); var m=(r()-b)/(b- a); println(m,b- m*a); ``` # Julia(84 chars, space delimited input, space delimited output) ``` a,b,c=tuple(map(int,split(readline(STDIN)))...) m=(c-b)/(b-a) println("$m $(b-m*a)") ``` ]
[Question] [ This small challenge derives from my annoyance at discovering that numpy doesn't have a built in function for it. # Input An n by m matrix of integers. # Output The maximum value in the matrix and the 2d coordinates of one of its occurrences. The coordinates should be in the order (row\_idx, col\_idx) if your code is no shorter than it would be with (col\_idx, row\_idx). Otherwise it can be (col\_idx, row\_idx) but if so, please explain it in your answer. 1-based indexing is allowed too # Examples ``` Input [[1, 2], [3, 4]]. Output (4, (1, 1)) Input [[-1]]. Output (-1, (0, 0)) Input [[6], [5], [4], [3], [2], [1]]. Output (6, (0, 0)) Input [[1, 2, 3, 4], [0, 2, 5, 3], [-5, -2, 3, 5]]. Output (5, (1, 2)) ``` # Note [numpy](https://numpy.org/) answers gratefully received too. [Answer] # [Julia 1.0](http://julialang.org/), 7 bytes ``` findmax ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/Py0zLyU3seK/Q3FGfrkClKcRbahgpGCsYGKtYABkmCoYWyvomirogsRMYzX/AwA "Julia 1.0 – Try It Online") Outputs `(value, CartesianIndex(row_index, col_index))` (1-indexed) [Answer] # [Python](https://www.python.org/) + [Numpy](https://numpy.org/doc/stable/index.html), 48 bytes ``` lambda x:(x.max(),divmod(x.argmax(),x.shape[1])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU9BDoIwELzzij22SSGgYAwJL6k91ABCYktTiilv8UJi9Ac-xt_YFvGyuzM7s5m9v9RsukEuj7Y6PSfTxsdPeuXiXHOwJbKJ4BZhUvc3MdQOcn1ZGZuMHVcNzRjGP9-7F2rQBuQk1Ax8BKki04xmhApoBEBpRmDHCNA9gZwxErg426aDXxW-5EHkS5D_Fd5PILgdnQZUOMKj2A3xui0Yi1jUDhoM9BJChtIdULqXBrVIKveH5jMyeAu_LGv_Ag) [Answer] # [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 9 bytes ``` ⊢⊚⊃=∘/↥♭. ``` [Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4oqi4oqa4oqDPeKImC_ihqXima0uCgpmIFtbMSAyXVszIDRdXQpmIFtbwq8xXV0KZiBbWzZdIFs1XSBbNF0gWzNdIFsyXSBbMV1dCmYgW1sxIDIgMyA0XSBbMCAyIDUgM10gW8KvNSDCrzIgMyA1XV0K) ``` ⊢⊚⊃=∘/↥♭. . # duplicate ♭ # deshape /↥ # maximum ⊃=∘ # mask of where the max exists in input ⊚ # coordinates of the ones ⊢ # first ``` [Answer] # JavaScript (ES6), 52 bytes Returns `[max, y, x]`. ``` m=>m.map((r,y)=>r.map((v,x)=>m=v<m[0]?m:[v,y,x]))&&m ``` [Try it online!](https://tio.run/##bY3BDoMgEETv/QpOBpLFaCs9NMV@COFArDZtXDHYEP16CnhrvEz27c7sfIw3S@fe85dP9tmHQQaULZZoZkodbEy2bgcPawSU/o6q0g@8KQ8brJqxosDQ2WmxY1@O9kUHqlQN5KyBqAuQRkfP6d/A68P1NYVEkibHk@RHx/ZUAySXRE@VScRFIh4Hvl9FCocf "JavaScript (Node.js) – Try It Online") [Answer] # [Python](https://www.python.org) + numpy, 61 bytes ``` lambda x:max(zip(x.flat,ndindex(x.shape))) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU5BDoIwELzzij0WU4woGEPCS7CHGmhoQktTlgT8igdJjP7J39gW9bK7MzszmdvLzNj2enmI8vwcUSSnd9lxdak5TIXiE7lKQ6at6DhSXUtdN5ODQ8tNE8dxJGyvQI_KzCCV6S1uviF3bAYcoIQqAqiqlMKeUagOFDLGaOCS9Hcd_Sv3IwsiP4L8r_B-CsHt6F1AuSM8StyRrN-csYhForeAIDWEDoULMFZqJIJwa_lM0DVfay7Luj8) Returns the last index of the maximal value. Different 63 bytes, maybe `key=` can shorten this a bit? ``` lambda x:max((b,a)for a,b in ndenumerate(x)) from numpy import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=PU7dCoIwFL73Kc7lFhOyNEKQHmTtYuJGQpsyj6DP0kVC1Dv1Nm2zujk_3x_f7dXPeOns8tDV-TmiTo_v01WaupEwlUZOhNRMUt05kKyG1oJtlB2NchIVmShNtOsMeKSfoTV953DzjbmjGnCACngCwHnGYCcY8D2DXAgWsTT7XYdAFWHkURRGlP8Vwc8guj28jV_hgfCl_khXthAiEUnoi6Ft7FD6gN61Fokm0jk5E6SUrjWXZd0f) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 3 bytes ``` Þė↑ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLDnsSX4oaRIiwiIiwiW1sxLCAyLCAzLCA0XSwgWzAsIDIsIDUsIDNdLCBbLTUsIC0yLCAzLCA1XV0iXQ==) And they said maximum by tail was useless! Now who's laughing! (me... It's me who's laughing) Outputs `[[x, y], item]`. ## Explained ``` Þė↑­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌­ Þė # ‎⁡Multidimensional enumeration ↑ # ‎⁢Maximum by tail 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [R](https://www.r-project.org), 35 bytes Almost built-in, but `which.max` flattens the input. ``` \(x,m=max(x))c(m,which(x==m,T)[1,]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3lWM0KnRybXMTKzQqNDWTNXJ1yjMykzM0Kmxtc3VCNKMNdWI1oUo70jRyE0uKMis0kjUMdYx0jHVMNHXyivLLbY10kipBdIimJhdcka4hMs_MylBHAazYDJtiuIk6BkDaFMjSNdXRBYmYQu0wRmiDuGfBAggNAA) Fixed indexing and returned result, thanks to Giuseppe. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 29 bytes ``` {s=Max@#,#&@@#~Position~s-1}& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277v7rY1jexwkFZR1nNwUG5LiC/OLMkMz@vrljXsFbtf0BRZl6JgkO6Q3W1oY6CkY6CsY6CSa2OQrUBmGcKFADxdIEMXYisaW3t//8A "Wolfram Language (Mathematica) – Try It Online") -1 byte from @att [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 11 bytes −1 byte thanks to Mukundan314 Requires `⎕IO←0` which is default on many systems. Returns `[max, row_idx, col_idx]` ``` M,⍴⊤,⍳M←⌈/, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/311HvVuedS1BEht9gWKPOrp0Nf5nwZi9fY96mp@1LsGqODQeuNHbROBuoKDnIFkiIdnMEgNSMQr2N9PPTraUEfBKFZHIdpYR8EkNladC1VW1xBTzAyk3BREmIA1ggiwEVjUgkzXUQCbDVRgAOaZAgVAPF0gQxciawrUCQA "APL (Dyalog Unicode) – Try It Online") `⌈/` the maximum (lit. maximum reduction) of the  `,` ravelled (flattened) argument `M←` store that as `M` (for **M**aximum) `,⍳` **i**ndex of first location of that in the ravelled (flattened) argument `⍴⊤` the shape-radix representation of that `M,` prepend the Maximum [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜Z=kIнg‰, ``` 0-based; outputs the maximum and coordinate on separated newlines. [Try it online](https://tio.run/##yy9OTMpM/f//9Jwo22zPC3vTHzVs0Pn/PzraUMdIx1jHJFYn2gDIMtUxBrJ0TXV0QaKmsbEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLkFQO5OpX/T8@Jss2uvLA3/VHDBp3/h7bZ/4@OjjbUMYrViTbWMYmN1VGIjtY1hNBmQEFTIDYBSQIxSBFUCqhDB6ReJ9oAyDLVAUnrmurogkRNY2NjAQ). **Explanation:** Unfortunately, 05AB1E lacks multidimensional builtins, so things are done manually. Otherwise this could have been 4-5 bytes probably. ``` ˜ # Flatten the (implicit) input-matrix Z # Push its maximum (without popping the list) = # Print this max with trailing newline (without popping again) k # Pop both now, and get the 0-based index of this max in the list Iнg # Push the width of the input-matrix (push input; first item; length) ‰ # Divmod the index by this width , # Pop and print it with trailing newline as well ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒĖṚ€Ṁ ``` A monadic Link that accepts a (multidimensional) array and yields a pair, `[maximum-value, [row, column, ...]]` using 1-indexing. (Identifying the last location of the maximum-value.) **[Try it online!](https://tio.run/##y0rNyan8///opCPTHu6c9ahpzcOdDf///4@OVjDUUVAwAmJjIDaJ1eFSiFYwADJNodgYLKQLZOrCVJkChWIB "Jelly – Try It Online")** ### How? While Jelly has both `ŒM` (get *all* multidimensional indices of maximal elements), `œị` (get element at multidimensional index y), and `œi` (get first multidimensional index of y), amongst some others I think this may be the tersest approach... ``` ŒĖṚ€Ṁ - Link: multidimensional array of comparables, A ŒĖ - multidimensional enumerate Ṛ€ - reverse each (from [coordinates, value] to [value, coordinates]) Ṁ - maximum ``` [Answer] # [Perl 5](https://www.perl.org/) `MList::Util=max -p` 58 bytes ``` $\=max/-?\d+/g;/\[[^[]*$\\b/;say$`=~y/[//-1;say$&=~y/,//}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lxjY3sUJf1z4mRVs/3Vo/Jjo6LjpWSyUmJknfujixUiXBtq5SP1pfX9cQzFUDcXX09Wur//@PjjbUUTCK1VGINtZRMImN/ZdfUJKZn1f8X9fXVM/A0ABI@2QWl1hZhZZk5oCs@a9bAAA "Perl 5 – Try It Online") Output format is ``` row column max ``` [Answer] # [Haskell](https://www.haskell.org/), ~~56~~ 55 bytes *Another one bytes the dust thanks to [DLosc](https://codegolf.stackexchange.com/users/16766).* ``` f m=maximum[(c,(y,x))|(y,r)<-e m,(x,c)<-e r] e=zip[0..] ``` [Try it online!](https://tio.run/##XU5BDoMwDLvzCh9bKUWwwU7jCXtBlUOFilaNIgRMYtP@3rXdTuTgxI4d5W7Whx3HEAb4zpvd@afXoifxol3KT2yLvCoLT2KnPo8LF7Z7u1lXZclhs@u2ooOG1jXhxAR9JjTMBf4VFa3qg3BJxjZBkyMJcvhoTEcJ@WSkVWZtFBJTcVC/bcsMLgpv3BS/8Wa@QcyLmzaUGCTym@EL "Haskell – Try It Online") Heh, this is technically a built-in solution. Outputs as `(max, (y, x))`. ## Weird output solution, ~~46~~ 39 bytes *-7 bytes thanks to to [DLosc](https://codegolf.stackexchange.com/users/16766).* ``` maximum.e.map(maximum.e) e=(`zip`[0..]) ``` [Try it online!](https://tio.run/##XU5BCsIwELznFXNsIQmttt76BF8QFxpKqsFGgqkgPt6YRPHQPQw7szvDXHS4mmWJ83CKTj@tezhppNO@@rOamaEaX9aPqpGS6riasAYMUFCq5dgRh9pzdEQMv0mKEu1GOOTHPkNXLBmKefuYQzlKZKJNYX0SMhNpEd9rTwRizGl7S21S5yMqf7e3FRJzjVIzvqd50ecQxeT9Bw "Haskell – Try It Online") This effectively does the same thing but outputs as `((max, x), y)`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes ``` c⌉M&iiʰ.hhM∧ ``` Outputs as `[[max, col], row]`. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/lRT6evWmbmqQ16GRm@jzqW//8fHW2oo2Cko2Cso2ASq6MQbQDmmQIFQLx4ICMeImsaG/s/AgA "Brachylog – Try It Online") **Explanation** ``` c⌉M&iiʰ.hhM∧ c Flatten the matrix (i.e. nested list of numbers) ⌉ Get the maximum M Call that value M & Start over with the original list of lists i Non-deterministically get some [element, index] pair (i.e. a row and its row index) iʰ Apply the same operation to that row, turning it into an element and its column index We now have [[element, col], row] for some as-yet-unknown element . That nested list is the output hh Take the first element of the first element of that list M Assert that it is the same as the max calculated earlier ∧ Break unification with the output ``` ## Nicer output format, 14 bytes ``` c⌉M&iiʰgᵗc.hM∧ ``` Outputs as `[max, col, row]`. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/lRT6evWmbmqQ3pD7dOT9bL8H3Usfz//@hoQx0FIx0FYx0Fk1gdhWgDMM8UKADixQMZ8RBZ09jY/xEA) **Explanation** ``` c⌉M&iiʰgᵗc.hM∧ c⌉M&iiʰ Same as above, giving [[element, col], row] for an unknown element gᵗ Wrap the last item in a singleton list: [[element, col], [row]] c Concatenate: [element, col, row] . That list is the output hM∧ Its first element is the same as the max ``` To output as `[max, row, col]` is **15 bytes**; the only change is to transpose the matrix first with `\`: ``` c⌉M&\iiʰgᵗc.hM∧ ``` To output as `[max, [row, col]]` as originally requested is... longer. Brachylog doesn't handle mixed-type lists very well. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 12 bytes ``` (*+&=)\||//\ ``` [Try it online!](https://ngn.codeberg.page/k#eJwlirsNwCAQxXqmeFUEySHC51LkKZtQMwXD5xCVLcvj9ed1fKHPmVJ3bsBnFFa0sFwk5i0PRSmNlVIoO9oJO3kbFZVREVfRgB8eEBDs) ``` |// max \ (mat, ) ( )\| (max, ) &= indices *+ first ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes ``` I⌈EA⟦⌈ικ⌕ι⌈ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2h45hWUlmho6ihEw0QzgZxsHQW3zLwUjUwdBYRwrCYQWP//Hx0dbaijYKSjYKyjYBIL1GkA5pkCBUA8XSBDFyJrGhsb@1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the highest possible row with the maximum value but the lowest possible column in that row. Explanation: ``` A Input array E Map over rows ι Current row ⌈ Maximum value κ Current index ⌕ First index of ι Current row ⌈ Maximum value ι In current row ⟦ Make into list ⌈ Take the maximum I Cast to string Implicitly print ``` Getting the maximum column of the maximum row can be done for 14 bytes: ``` I⌈EA⟦⌈ικ⌈⌕Aι⌈ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzexIjO3NBdIF2h45hWUlmho6ihEw0QzgZxsHQUY1y0zL8UxJ0cjEyGUqakZqwkE1v//R0dHG@ooGOkoGOsomMQCTTEA80yBAiCeLpChC5E1jY2N/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` I⌈EA⟦⌈ικ As above ⌕A Find all indices of ι Current row ⌈ Maximum value ι In current row ⌈ Take the maximum ``` Getting the lowest possible row with the lowest possible column takes a massive 21 bytes: ``` IE⌈Eθ⟦⌈ι±κ⌕ι⌈ι⟧⎇⊖κι±ι ``` [Try it online!](https://tio.run/##RY3NCgIxDIRfpccupODfnjwq3hQP3koPoRs0uO1qraJPX7MVNRCYbyZD/AmTH7AvZZ84Zr3CW9ZbvMg@OdxD1VdQ9svcgNrRETPps8gNx04zqH/sxD1Qipheek0@UaCYqavX/OtyM86yFGvtFNQM1BzUwsmjSaVWjJGMCPNJW@dcMY/@DQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Negates the row number, which gives you the highest possible negated row, but then has to negate it again for display. [Answer] # [Go](https://go.dev), 147 bytes ``` import."slices" func f(I[][]int)(m,x,y int){m=Max(I[0]) for _,r:=range I{m=max(m,Max(r))} for a,r:=range I{x,y=a,Index(r,m) if y>-1{break}} return} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=bVHBSgMxEMVrvmJcEHZhtrTaiigRBD30oIj2VovEdVcWu2nJprJLzFd49FIEf8Lf8KRf4yRpsYIQkpd5b95MJq9vD7Plx1xkj-Ihh0qUkrGyms-U7kRFpaP3hS7Sg6-XdayellleR6xYyAyKeDiejCel1ElcYYMtOGgqfi4aorqThBUzBbeoDrkSkgoMiayIrNBJVJJYrxCbCvLhAofyPicFVgkrC2iP0565U7l4tJapXC-UtKG1761P3c5zGEGt1SLTYEo5h1VbRzCdZQgNgm_NMvYkFOi81jVwEo0MMyupMT2EXYtg9hD6lkAfgUI9ixuatOeYlOJdWn-ofZc7cFvfu7jN-_mU_X8yXEEEX45kXX8bUMDdUgJpYAcuf-CbIT9Gj_DDd38VJ2AYu1RkN5VxxDm_Hp1cjeiM1qPXcMghjDa827DfmRBVxLpDE_NTJgK2OeiOA8_P0IRb43AbcAsGfL0ijnaegB_Dzj36BfEaJTcyQvC2-PsBGHzd0bitTcDSYzabP7s4Da2v_na5DOcP) Returns as `max, x, y`. Assumes that the matrix is non-empty. ### Explanation ``` import."slices" func f(I[][]int)(m,x,y int){ m=Max(I[0]) // default value for max, to account for negatives for _,r:=range I{m=max(m,Max(r))} // find the max of the whole matrix for a,r:=range I{ // find the location of the max x,y=a,Index(r,m) // the current row index, and the index of the max if y>-1{break}} // if the max is in this row, exit the loop return } ``` [Answer] # Rust + ndarray, 41 bytes ``` |a|a.indexed_iter().max_by_key(|(_,x)|*x) ``` A closure of type `fn(&Array2<u8>)->Option<((usize, usize), &u8)>`. `ndarray_stats` has an `argmax`, but it's very verbose at 46 bytes: ``` {use ndarray_stats::*;|a|(a.max(),a.argmax())} ``` [Answer] # Google Sheets, 63 59 bytes ``` =+sort(tocol(A:N&","&row(A:N)&","&column(A:N)),tocol(A:N),) ``` Put the 2D array in cells `A1:N1000` and the formula in cell `P1`. Singularizes the data and coordinates and sorts in descending order. Uses unary plus `+` to extract just the first result. Gives 1-indexed coordinates. [Answer] # APL(NARS), 109 chars ``` r←f w;i;j;s;h;k;a;b j←1⋄s←¯∞⋄h←k←⍬⋄(a b)←⍴w i←1 →4×⍳∼w[i;j]>s⋄h←i⋄k←j⋄s←w[i;j] →3×⍳a≥i+←1⋄→2×⍳b≥j+←1 r←s(h,k) ``` 19+23+3+30+21+8+5=109 How to use&test: ``` ⎕fmt f 2 3⍴ 1 4 3 2 ¯1 5 ┌2───────┐ │ ┌2───┐│ │5 │ 2 3││ │~ └~───┘2 └∊───────┘ ⎕fmt 2 3⍴ 1 4 3 2 ¯1 5 ┌3──────┐ 2 1 4 3│ │ 2 ¯1 5│ └~──────┘ ``` it would return the max and the first coordinates it finds max [Answer] # [Haskell](https://www.haskell.org) + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 22 bytes ``` xB cr<Asx<<(mM eu<+eu) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5LDoIwFNz3FG8JsU1EwRhSTHTnwoR90wWRNhIBEdqEu7BhY7yCV-E2toXootOZN-8zw_uWdXdRluOUFFXzaBU8dVYWshA5pK0odS7QYqRIxjFj51pxTg6eZwg2z3fw0kqS_Ucm_QmuLT12PaVedQGh6UroxZ4GJTrVQYIAGDAWYNhwDGyLIeTcFA1nJPjRnTUjC6Frs-AG_i12BQa3wMi1U5EpWEUMIbMbuQGOUJUVtbtvsnlNCxSkDy7VHHEc5_8L) Outputs as `((x,y),v)` # Strange order, 21 bytes ``` xB(cr<cr)<(mM eu<+eu) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU49DoIwGN17im8ssU1EwRgCDm4OJuxNB4JtJAJiaRPvwsJiPIJn4Ta2hejQ1_e-9_284X0t-puo63HKqqa7Kw0PU9SVrMQFciVqcxFoMXIkk4SxU6s5pweMLSH2BR5eRku6_8jsecSlSksVpLg5gzDpSpjFnQYtet1DhgAYMBYS2HACbEsg4twWLWc0_NGdM2MHkW9z4Af-LW4FAb_AyrVXsS04RS2hsxv7AY5QU1Stv2-z4U5BCjIAn2qOOI7z_wU) Outputs as `(x,(y,v))` # Different strange order, 21 bytes ``` mx<g<m(mx<g) ``` ``` g=fzp nn ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5LDoIwEN33FLOEpE1EwRgE9y5M2DddkNAisa0IJTFehQ0b4xE8C7exLUYX8-a9efMbX-eyv3AppzlvVHvtDNyGUjai4RUUHZdDxdHXKJBIU0qP2jBGDkFgCbYRengORpDdW-TqntWZClwK93UuHi1ovbjzaHhvesgRAAVKIwxrhoFuMMSM2aLllEQ_unVm4iD2bQ78wL_FrcDgF1i58iqxBaeIJWRxEz_AEFJlo_19dYKg7SADEYL_anlxmpb8AQ) Outputs as `((v,y),x)` # Reflection This answer is hampered by the fact I haven't yet implemented any array handling functions, so this has to work with lists. That asside, I have a couple of thoughts: * There should be a flipped version of `eu`. I approximate this with `fzp nn` in the final version. * `cr<cr` is a useful enough function to have a short version. [Answer] # APL+WIN, 32 bytes Prompts for matrix: ``` (⌈/,m),(,(⍳↑⍴m)∘.,⍳1↓⍴m)[↑⍒,m←⎕] ``` [Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv8ajng59nVxNHQ0djUe9mx@1TXzUuyVX81HHDD0dIN/wUdtksEA0WGaSTi5QK9CI2P9A3Vz/07iMFIyA8oYKRgrGCiZcaVyGCoZA/qH1hmC2GZBtpmCqYAKUNVIAiQFVIdQrGABpUyDr0HpTIAaJmXJxAQA "APL (Dyalog Classic) – Try It Online") [Answer] # [Racket](https://racket-lang.org/), 114 bytes Output in the format `(value row_idx col_idx)` ``` (λ(x[y(apply append x)][m(apply max y)][i(index-of y m)][l(length(car x))])(list m(quotient i l)(remainder i l))) ``` [Try it online!](https://tio.run/##TY1BDoIwEEX3nOInLpwumohSL0NYNFCwsRSsNSln8w5eCaeERBd/Mv/N/5mg27uJ68FpPyBspqDO9NYb9Ct93pTqhfQ8uwU8je@QRFOPOxp1wsLekvWdSXLqwZCBI2f8EG/U6sAN0Qhy9hkx0uM1RWt8hIUTFMyoczVsVohVFAX1OBKVOAvQBRXTHcnyt1/5qFhVDrFy@O/MbeQu6MSbQo5IBZmpyn@@ "Racket – Try It Online") ``` (λ(x [y (apply append x)] ; flatten the matrix [m (apply max y)] ; find the max value [i (index-of y m)] ; index of the value [l (length (car x))]) ; length of a row (list m(quotient i l)(remainder i l))) ; format output ``` ]
[Question] [ Write a program which takes two arrays of positive integers as input. One of them (your choice which) will have one item missing compared to the other. Your program must figure out what is missing. # Rules You can choose which array has one missing: You can take ordinary then missing or vice versa. Arrays may contain duplicates. # Testcases ``` [1,2,3], [1,3] => 2 [3,3,3,3,3], [3,3,3,3] => 3 [4,6,1,6,3,5,2], [3,6,2,5,4,6] => 1 [9,9,10,645,134,23,65,23,45,12,43], [43,134,23,65,12,9,10,645,45,9] => 23 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), 24 bytes Takes two lists \$ a \$ and \$ b \$, where \$ b \$ has the missing number. ``` lambda a,b:sum(a)-sum(b) ``` [Try it online!](https://tio.run/##TU7ZCsIwEHzPV@ybCYxijhZaqD9SRVK0tNAjtKni19fEC9l7ZnZZ9/DNOKi1Lo5rZ/vqYsmiyuel51ZsY6nEem/a7koyZ8QtqBKgcfGOCuqt49eb7UCTvZ/bwS2ei93sutbzDRUH2gjByE3t4Kn@311LCQV9AoVGn6JUsVLjYxH/tpHTrDRIIUNoJFBvPg0nEgTipZGszJBB7pGaBFIbqCBJYo6zgnmdNfqPC@hvI3j2fkQ/AQ "Python 2 – Try It Online") Given that \$ a \$ and \$ b \$ differ by a single number, we can trivially obtain the answer by computing the difference of sums. [Answer] # JavaScript (ES2019), 25 bytes ``` a=>eval(a.flat().join`^`) ``` [Try it online!](https://tio.run/##dY7dCoMwDIXv9xRetnCma1MHXrgXEYfF6VCKHVN8/S4OJwM38sNJ8oWkt7Md62f3mI6DvzWhzYPNL81snbBx6@wkZNz7bqiulQy1H0bvmtj5u2hFUSjoEoUuSymjJInU4QcAYkRxXiG9gwirMfhRK0w72OAMxUFI38eJtWbN/f9vZMigTjibFIoMNC@lS15qDbMcNvQ14ua2wJ5tv1N4AQ "JavaScript (Node.js) – Try It Online") Take input as `f([array1, array2])`. Calculate xor of all input numbers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` œ- ``` [Try it online!](https://tio.run/##y0rNyan8///oZN3/h5fr//8fbawDhbE6CjBOLAA "Jelly – Try It Online") Just the set difference builtin [Answer] # [R](https://www.r-project.org/), 19 bytes ``` sum(scan(),-scan()) ``` [Try it online!](https://tio.run/##K/r/v7g0V6M4OTFPQ1NHF0Jr/jdUMFIw5uIyVDD@DwA "R – Try It Online") Same idea as [dingledooper's Python answer](https://codegolf.stackexchange.com/a/230275/86301), using R's terser syntax for `sum`. Input is taken from STDIN, with the two multisets separated by a newline. [Answer] # Haskell, 12 bytes ``` foldl(-).sum ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZp2CrUFCUmVeioKKQphBtqWOpY2igY2ZiqmNobKJjZKxjZgoiQXwjHRPjWIVoE2MkKaAgXAMQWcZypdnG/E/Lz0nJ0dDV1Csuzf3//19yWk5ievF/3eSCAgA "Haskell – Try It Online") A cooler way to write `(\x y->sum x-sum y)`. For example, ``` (foldl(-).sum) [4,6,1,6,3,5,2] [3,6,2,5,4,6] === (foldl (-) (sum [4,6,1,6,3,5,2])) [3,6,2,5,4,6] === (4+6+1+6+3+5+2)-3-6-2-5-4-6 === 1 ``` [Answer] # JavaScript (ES6), 43 bytes Expects `(a)(b)`, where `b` has one item missing. Returns a singleton. This one is a bit overkill and would work with several missing items. ``` a=>b=>b.map(v=>a.splice(a.indexOf(v),1))&&a ``` [Try it online!](https://tio.run/##dY7BDoIwDIbvPgUnsyV1uHWQcIBX8AGIhwnDYJARMcS3nx0qMRizrtvf/2vai5nMWN3a4b7rXW19k3uTFycKcTUDm/LCiHHo2soyI9q@to9DwyYOkvPt1vjK9aPrrOjcmTWslKCOnJWUeBTHkdz8@oCBkOGZGbVmEN4ncMt3ZnHNakhB0kVIXpORhCJBxr8dMshA7iHVCUjUoKglCTloBXoeq/HLo@rSQZF9Fkf/BA "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 35 bytes Using [dingledooper's sum trick](https://codegolf.stackexchange.com/a/230275/58563). Same input format. Returns an integer. ``` a=>b=>eval(a.join`+`+'-'+b.join`-`) ``` [Try it online!](https://tio.run/##dY7RCoMwDEXf9xW@WTHq2lTBB/0RGVidDqXYMYe/36W6yXCMpmlu7wnJqBY1t4/h/owmc@1sX1hVlE1RdovSTMWjGaY6rEM/8sNmU1Ed2NZMs9FdrM2N9aziIC4BqygFXpJ4/PTrAzqCu2dlxJFBeB/H7eXK4pGVkAGni5Buk5GEIEHGvx1yyIGfIZMpcJQgqCV12WkBch0r8cuj372DIv8sjvYF "JavaScript (Node.js) – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 3 bytes ``` v∑¯ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=v%E2%88%91%C2%AF&inputs=%5B%5B4%2C6%2C1%2C6%2C3%2C5%2C2%5D%2C%20%5B3%2C6%2C2%2C5%2C4%2C6%5D%5D&header=&footer=) Very epic port of the python answer. Takes original and missing in a list. ## Explained ``` v∑¯ v∑ # sum of each list ¯ # and deltas ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~50~~ \$\cdots\$ ~~44~~ 43 bytes Saved ~~5~~ 6 bytes thanks to an idea from [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!! ``` c;f(a,b)int*a,*b;{c=*a?f(a+1,b+1)^*a^*b:0;} ``` [Try it online!](https://tio.run/##lZJtb4IwEMff@ykaEhPAMxMKJsqcL5Z9Cp/S1uJ0mxprMjPDVx@7UsqDe0gm0pT7/393xxXR3wiR5yJJXQbc2@7PPgOfJ1cx8dkUg70AeC/wlj5b@nw8SLIcPeSNbfeu17l2CP504CzVecWC2YJMyDWAECgMsqSWeCXdCCw0AgV7tbkbuc1SI0YwhABvCjFWbvPU8kOUYtDWdo7IGEYwgmAAwyiGgEYQIhDrVT@HEN22VVIYr93oq3Lgf6QROyC/4NSKGa4cF9gZ2A21m8hUsxhvYNxi3GLcYjyqKxJ5OUpxlmuDohddiIa09IhndvJxleJFntBEtM2ZX57C@WX0iHfsAGk@U6ck08OJuLrEdr@WF8QGSbm9J2r7IQ@pa4t7d2XAryIJ6fUKt0fM91ONiGEqO6bCsUjaBl4Z@E8GolA3H3IdP55QSV1n5jSC@AbFC@xM82y2W@i2ds2WmnBXddc4jd1Uj2Ts4KqRRsLsW70FkL9K8v@X5L@VLE4b01YnfjubqifSfyDdNemq@R4TKqiOX04myibPOln@KdJXtlF5//0L "C (gcc) – Try It Online") Inputs \$2\$ zero-terminated arrays (since pointers to arrays in C carry no length information) of positive integers with the \$2^{\text{nd}}\$ array the same as the \$1^{\text{st}}\$ except for a missing number. Returns the missing number. ### Explanation Since exclusive-or (\$\oplus\$) is associative and commutative, \$n\oplus n=0\$, and \$n\oplus 0=n\$ we can simply exclusive-or all the numbers from both arrays together to yield the missing number. This is also guaranteed to always fit inside an `int` as no extra bits are ever needed. [Answer] # [Red](http://www.red-lang.org), 34 bytes ``` func[a b][foreach u b[alter a u]a] ``` [Try it online!](https://tio.run/##XY1bCsMgEEX/s4q7hPoEu4z@ynxoVFooTZG6fjumJSRBHa9zjlpz6recPE3pUcq1l/aafUAkX5aaw3xHQ/Th@ckVAY0C9XddYsbQ4QUkFGEE3qY9UviPgbd4UDQsBC8FA/nTLD9owOCkOjiIC6w2EEpDsmlGHWcJvX6i1Y5xd7vB01H/Ag "Red – Try It Online") ~~sum - sum.~~ -4 from dingledooper using the xor trick from tsh. -15 bytes from Galen Ivanov using his [`alter` tip.](https://codegolf.stackexchange.com/a/229320/80214) # [Red](http://www.red-lang.org), ~~71~~ 63 bytes ``` func[a b][remove-each v a[c: NONE <> find b v replace b v""c]a] ``` [Try it online!](https://tio.run/##XU3LCsIwELznKwbvgmmSQot481rBa8ghTTZY0LYE7O/HRKVU2dfszuxuJJ@u5LVhfgihTeE5Om3RGx3pMS20J@tuWGC1a9FdujOOJ4Rh9OjzNNJ8t44K3u2csSbNceoJ5RY0RwVhUEAubEsJfK3QK/yRSNTgOQQUqo@szgcVMvEnbdCAH1BLBS4kqqxUJZe@gnw/kWLD5em6kb0xDCy9AA "Red – Try It Online") Summing is shorter, but really, I just wanted to try using `remove-each`. Returns a series with a single value (the differing element). Works as a general multiset difference as well. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` +ᵐ- ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wXxtI6P7/Hx0dbahjpGMcq6MAZBjHguhoYx0oBPFgTLCMiY6ZjiEQG@uY6hhBZM2A2k11gBIQFZY6ljqGBjpmJqY6hsYmOkZABaYgEsQ30jEBG2lijCQHFIXrACLL2NhYAA "Brachylog – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 18 bytes ``` ->a,b{a.sum-b.sum} ``` [Try it online!](https://tio.run/##TUw7DoMwDN05BQd4VHVsImWAi0QZyMCGVLViQKhnD3agFbL9ZL@P32veyjyUbpyQ9@nxWZcuG37Lq51jDAigJ7z0IBY4hu8N7XYQTmij8E1T9p/QDik19ZHAg3QYmreUuuH0UOHnYVx16ud6aaTmypNx5QA "Ruby – Try It Online") --- # [Ruby](https://www.ruby-lang.org/), 15 bytes ``` ->*a{eval a*?^} ``` [Try it online!](https://tio.run/##TUxLCoMwEN33FFnLK3QyYyAL24OECCnUVRcitFDEs8eJsSLzYd5vps/zl4cuX@9Nml/f9DapefRLHs0QgocH3eCkBbHAMlxbdsEWwhEmCJ80ZY@Eto/xsj0SOJAOQ/MlpW5YBSr8PYy9ql7PXSM1bzwVLq8 "Ruby – Try It Online") Based on tsh's Javascript solution. Thanks to *@G B* for -3 on the 15 byte solution [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` x)-Vx ``` x : Sums all elements in the array [Try it online!](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=eCktVng&input=WzQsNiwxLDYsMyw1LDJdLCBbMyw2LDIsNSw0LDZdIA) Same idea as [dingledooper's answer](https://codegolf.stackexchange.com/a/230275/104561). [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes ``` S`, O` +`^(.+¶)\1 1G` ``` [Try it online!](https://tio.run/##TYoxCoRADEX73GNB8SObSWZgmANsaWErEostbCyWPdsewIuNEWSR/CT89//n/V23pT6a0UodDTQYdTY3fbf/2omJ@GW1MgKkMIQE15TrkyKBfQURwWnyboRTysjgJ5JGsCiCZ/G8pw9QKSq3wNG/7soH "Retina 0.8.2 – Try It Online") Takes arrays on separate lines but link is to test suite that splits on semicolons for convenience. Works on strings (if they don't contain commas or newlines) as well as integers. Explanation: ``` S`, ``` Split each array into separate strings. ``` O` ``` Sort both arrays. ``` +`^(.+¶)\1 ``` Remove leading duplicates. ``` 1G` ``` Remove trailing (assumed) duplicates. [Answer] # [Julia](http://julialang.org/), 15 bytes ``` a\b=sum([a;-b]) ``` [Try it online!](https://tio.run/##VU3LCsIwELz7FTkqjOBmN4Eg9UfSHtJbpZZSLfTgv8etlhLZ987s7H3uu0RLzqluq@f8OMZ0PbfNKUeCBTemNtppfd/MOHXDqx8OkbHZF977kiLwIA2Gg91oXhUdFPmnBgTQBV4ciAVWiW7N62whvyfCBajr/UQ9lHr5Aw "Julia 1.0 – Try It Online") similar to [dingledooper's answer](https://codegolf.stackexchange.com/a/230275/98541) [Answer] # [J](http://jsoftware.com/), 5 bytes ``` XOR@, ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/I/yDHHT@a3KlJmfkKxgp2CoYAkljhTQgbQwRNAYKGsNhGowFkTQESmqY6JjpGAKxsY6pjpEmSAmQYwTkACX@AwA "J – Try It Online") A port of [tsh's clever answer](https://codegolf.stackexchange.com/a/230279/15469). [Answer] # [yuno](https://github.com/hyper-neutrino/yuno), 4 bytes ``` ΣϾ_/ ``` [Try it online!](https://yuno.hyper-neutrino.xyz/#WyIiLCLOo8++Xy8iLCIs1LgiLCIiLCIiLFsiWzksOSwxMCw2NDUsMTM0LDIzLDY1LDIzLDQ1LDEyLDQzXSIsIls0MywxMzQsMjMsNjUsMTIsOSwxMCw2NDUsNDUsOV0iXV0= "yuno online interpreter") Port of the Python solution. I don't have multiset difference built-in yet. ``` ΣϾ_/ ᴋ Main Link Ͼ ᴋ For each list Σ ᴋ Take its sum / ᴋ Then reduce over _ ᴋ Subtraction ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Unfortunately, all of Japt's methods for getting the differences between 2 arrays don't take duplicates into account so we have to go with a longer method. Takes input as a 2D-array, in either order. ``` mx ra ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bXggcmE&input=WwpbMSAyIDNdClsxIDNdCl0) [Answer] # [Java (JDK)](http://jdk.java.net/), 21 bytes ``` a->b->a.sum()-b.sum() ``` [Try it online!](https://tio.run/##nZBNb4JAEIbv/ooJicnSDEQETcRq4qVJD00P9oYcFgWL5Su7i4lp/O10WNBobC8NzO7OvPM@C3PgR24ddl9NmlelUHCg3K5VmtlP88FDLamLrUrL4ldRKhHzvJW2GZcS3nhawPcAoKqjLN2CVFzRdizTHeSksbUSabEPQuBiL03dCvDSX/H8Wqi1JiJ8lJQ8CsslJLBouLWMrCW3ZZ0z04q6vZlrWlIKYEcuQMVS@XcXAbR1LgQ/SVjoBrJGUn8Uc7CrZHGxV5/EdUxbVlmqmBEibDaBYc5vMURYaVQ/BtaBg1F4saFhmnbOK/0zjCLex8L3jzyr4/fkjhb9RXP@QxOxrDNFyMTmVZWdGDe7w0q23ujavD5JFed2WSu7oiGohBlD6cNwNyyMbhzYw3rLedDGuWkCB8fo0mDo4IZN4GL/tKXLsQk8nKJD4eIEx500JeMESSB5hjN0Rjj1Jui4Ho5JnbRrm4/R0zDPvdGoenXQOwt/AA "Java (JDK) – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 16 bytes ``` [ [ Σ ] bi@ - ] ``` [Try it online!](https://tio.run/##TVBLDoIwFNxzivEAEmkLCRqJO@PGjXFFWNRaI0E@oXVhCKfxPl4JH5BUO837dGZem96ksnU7nE@H434NaUytDArdVvqBUtr7FPxnlav6qtG02tpX0@aVxcbzOg@0OkIABo5@qsbcY4FtAuYE3KH/65yQO6FARDMiIkOaOYsjqsKJcYbAGWJCsEIkQgRcgJE8HOPYM4j5Qko/ko6dhXb8917u9UOKFJ83MlzyHZbIho7o6WeSUjYwVqrCH74 "Factor – Try It Online") [Answer] # MATLAB/Octave, 17 bytes ``` @(a,b)sum([a,-b]) ``` [Try it online!](https://tio.run/##TU5LCoMwEN17CpcJvILJTAKhCN5Dsoiiu7YL214/Tvwh82HmfYb5jN/0n3LuVMKgl99L9QmPIeo8t@m9PKtZ9QYWFFHLQFEXhHBEQc9xYxgeRorgYHfWi91BiF0REGAaeHYwxLAicKWX3YK3k0w3TtDLIRnktxU "Octave – Try It Online") Like most of answers here makes use of difference of sums. MATLAB got its own builtin `setdiff` but for one it doesn't work with multisets just regular sets and for second it's 1 byte longer. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes Takes input as an array containing two sub-arrays. ``` c r^ c // Flatten, then r^ // reduce with XOR. ``` [Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=YyByXg==&input=W1s5LDksMTAsNjQ1LDEzNCwyMyw2NSwyMyw0NSwxMiw0M10sIFs0MywxMzQsMjMsNjUsMTIsOSwxMCw2NDUsNDUsOV1d) [Answer] # [Wolfram Language (Mathematica)](https://codegolf.stackexchange.com/questions/230271/whats-missing-aka-the-vanilla-multiset-difference-challenge/230275#230275), 11 bytes ``` Tr@#-Tr@#2& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277P6TIQVkXRBip/Q8oyswrUXBIj6421FEw0lEwrtVRADGNa2O5EHLGQAE4AqlA4iGrM9FRMNNRMASTQElToJFQ1WZg04ECICUoeix1FIDI0AAobgKUNzQGqjAC6TCF0GBBoF4TsMUmxmhKQFIxXMgmgLBlbex/AA) Used algorithm from [dingledooper's answer](https://codegolf.stackexchange.com/questions/230271/whats-missing-aka-the-vanilla-multiset-difference-challenge/230275#230275) [Answer] # [Perl 5](https://www.perl.org/), 35 bytes ``` $_=pop@F;for$f(@F){s/,$f\b|\b$f,//} ``` [Try it online!](https://tio.run/##fYvNCsIwEITvPsUeclAYaTebBIoIPfUpCmLBgFBMaL2pr27cokf1G/aXmXyaRl@KOexzym23i2kycd12m9tcwcR@uPeDiaiqRylMQv9gWMhK6K1fCD5SZyBLnpzObzgEsJbAw66cEIsjqylPbKkhrik4jXvdiRo04Br6gfpgBcEvfbktnDxTvp7TZS7bYx5f "Perl 5 – Try It Online") [Answer] # [J-uby](https://github.com/cyoce/J-uby), 11 bytes ``` :*&:sum|+:- ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWq6201KyKS3NrtK10ISI3lxQouEVHR1vqWOoYGuiYmZjqGBqb6BgZ65iZgkgQ30jHxDhWRyHaxBhJDigK1wFElrGxsVwQo0x0zHQMgdhYB2gCSB9QvY4RkAOUQKgy1oFCiAoIEy5rCNQAljEEi0LcumABhAYA) ## Explanation ``` :* & :sum | +:- :* & :sum | # Map with .sum, then +:- # difference ``` ]
[Question] [ # Code-Bowling Challenge Write a program or function that produces the same output, no matter how you re-arrange the source code. *(Output can't be an error)* --- # [Pangram](https://codegolf.meta.stackexchange.com/q/11737/16513) Scoring * Your score is the amount of unique characters in your source code. > > A program with source code `AJB` would have a score of `3` > > A program with source code `AAJ` would have a score of `2` > > A program with source code `111` would have a score of `1` > > > > > * This is a [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'") variant. The program with the highest score wins! *(For your convenience an automated scoring tool has been created [**here**](http://jsfiddle.net/ur608qwt/3/))* --- ## Challenge Rules 1. **Input** The program/function can take an input, that's entirely optional though. 2. **Output** This output can be *anything* you want, but it should be non-nil, non-null, non-empty, and non-error. *(Therefor output must be at least 1 byte)* 3. **Rearrangement** No matter how the source code is re-arranged, the output should be the same. Example:    Program: `ABJ` outputs `hello world`, as does programs: [`AJB`, `JAB`, `JBA`, etc.] --- This is a [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'") variant. The program with the highest number of characters wins! [Answer] # Lenguage, 1,112,064 points if UTF-8 My program consists of every possible UTF-8 character. [It prints out "Hello world", and uses 1.75 \* 1076 yottabytes of space.](https://esolangs.org/wiki/Lenguage) (To generate the program, you simply need to make a file with 17498005810995570277424757300680353162371620393379153004301136096632219477184361459647073663110750484 characters, ensuring that each possible UTF-8 character is in the file) [Answer] ## Many languages, 2 points ``` 0. ``` Produces `0.0` as `0.` or `.0`. Requires liberal number parsing that's OK with a decimal point at the start or end, assuming 0 for the missing integral or decimal part. `0000000.` would give the same score. This also works in the following languages (in some cases with a different output, as indicated): * Python REPL * Javascript REPL * MATLAB (produces `ans = 0`) * Octave (produces `ans = 0`) * MATL (produces `0`) * CJam * Retina (produces `0`) * [Stacked](https://tio.run/nexus/stacked#@2@g9z@/tOQ/AA) (produces `0`) --- For Python, I think this is the only way to get a score above 1, as the possibilities can be exhausted. * Any binary or unary operator will fail as the last character * Any of `[](){}` require a match and will fail if the closing one comes first * A tabs or space can't start a line. Newlines can't be used in REPL. * A `,` can't be the first character * A `#` placed first would comment everything and produce not output * A starting `\` is an invalid line continuation * Backticks (Python 2) must be paired, and them surrounding nothing is an error * `$`, `!`, `?`, and `@` can't be used without other unusable characters This leaves letters, digits, `_`, `.`, and quotes. * With quotes, any non-string outside them gives an error. * Letters with possible digits and `_` makes variable names, of which some permutation always doesn't exists. The leaves digits and `.`. Permuting different digits gives a different number unless all the digits are `0`. So, I think zeroes and `.` is the only way to get a score above `1`. But, I don't know the Python lexer well, so I could be missing something. [Answer] ## [CJam](https://sourceforge.net/p/cjam), score 15 ``` T U V LMOQR[]0q ``` [Try it online!](https://tio.run/nexus/cjam#@x@iEMoVxunj6x8YFB1rUPj/PwA "CJam – TIO Nexus") Always prints `0000`: * `0` just pushes a zero. * `T`, `U`, `V` are variables which are pre-initialised to zero. * `L`, `M`, `O`, `Q`, `R` are variables which are pre-initialised to an empty list, so they don't show up in the output. * `[` and `]` may or may not wrap things in a list, but they don't have to be matched correctly and the output is flattened for printing anyway. * `q` reads the input which is empty and hence doesn't show up in the output either. * linefeed, space and tab are ignored by the parser. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~3~~ ~~5~~ 6 points *The idea to add whitespace was taken from [Bijan's answer](https://codegolf.stackexchange.com/a/113200/36398)*. ``` lv T1 ``` The code, or any permutation thereof, outputs three ones separated by newlines. [**Try it online!**](https://tio.run/nexus/matl#@59TxqUQYvj/PwA "MATL – TIO Nexus") ### Explanation * Function `l` by default pushes number one to the stack. * Literal `1` does the same. * Literal `T` pushes `true`, which is displayed as number one. * Space and newline are separators, and here do nothing. * `v` concatenates the whole stack so far into a column vector. So for example `v` after `T` would concatenate the first two numbers into a column (and then the next number would be pushed). An initial `v` would produce an empty array. At the end of the code, the stack is implicitly displayed, with the following rules: * Each element or array in the stack is displayed on a different line. * Column vectors are displayed with each element on a different line. * The empty array causes no output. So any permutation of the input characters produces `1` three times in different lines. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score ~~53~~ 101 ``` ¶ ¤$¥&+ABDFHNPQSUVX^_aborv|®²×ȧȯḄḅḌḞḢḤḷṀṂṚṛṠṢṪẠạị«»()kquƁƇƊƑƘⱮƝƤƬƲȤɓɗƒɦƙɱɲƥʠɼʂƭʋȥẸẈẒẎŻẹḥḳṇọụṿẉỵẓḋėġṅẏ ``` Using only characters that are part of Jelly's [code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page). Jelly has implicit input of `0`, and the first half (up to and including `ạị«»`) of the string of code above consists mostly of monadic (uppercase) and dyadic (lowercase and symbols) atoms that when given a zero or a list containing only one zero (or two such inputs in the case of dyads) return a zero or a list containing only one zero. The exceptions are: * The space: it is ignored (even though it is in the code-page). * The pilcrow, `¶` separates links (as does a line feed - but that is really the same byte), but no other bytes will reference the code before it anyway. * the scarab, `¤`, instructs the parser to treat everything to it's left starting at a nilad (or constant) as a constant (and works as a first atom). * the Dollar, `$`, instruct the parser to treat the two links to it's left as a monad (and, somewhat surprisingly, works as a first atom) * the Yen, `¥`, similarly instructs the parser to treat the two links to it's left as a dyad. * The recommended, `®`, recalls the value of the registry, initially `0` (it's counterpart copyright, `©`, breaks when used as the very first atom as it is arity is found from the arity of the link to it's left, which is not yet set). The code from the parentheses, `(` and `)` and on, are currently unused code points, these all get parsed and each causes a new chain (much like a newline would, although they don't have the effect of creating callable links like a newline, but that's no problem here as nothing tries to do so). [Answer] # TI-Basic (83 series), 93 points (99 on a TI-84 Plus) ``` 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZθnπeiAnsrandgetKeyZXsclZYsclXsclYsclXminXmaxYminYmaxTminTmaxθminθmaxZXminZXmaxZYminZYmaxZθminZθmaxZTminZTmaxTblStartPlotStartZPlotStartnMaxZnMaxnMinZnMinΔTblTstepθstepZTstepZθstepΔXΔYXFactYFactTblInputNI%PVPMTFVP/YC/YPlotStepZPlotStepXresZXresTraceStep ``` All the digits, all the one-byte variables (including θ and *n*, the independent variables for polar and sequential graphing), the constants π, *e*, and *i*, some not-quite-variables (`Ans`, `rand`, and `getKey`), and 59 different [window variables](http://tibasicdev.wikidot.com/window-tokens) (all the ones that are guaranteed to be defined). Implied multiplication guarantees that the result will be 0 when we take this in any order. If this is running on a fresh calculator, all the variables will be 0; even if not, `getKey` will be 0 because there's no time to press a key before the program returns a value. On a TI-84 Plus or higher, we can get 6 more points by adding the tokens `getDate`, `getTime`, `startTmr`, `getDtFmt`, `getTmFmt`, `isClockOn`. The result will now always be `{0 0 0}` because `getDate` and `getTime` return lists of length 3 and the implied multiplication distributes over the elements. I think these are all the possible tokens to use: any actual commands are prefix, infix, or postfix (meaning they won't work at the beginning or end of the program) and any other variables might be undefined (and cause an error when used). [Answer] # (non-competing) Brainf-ck, 63 bytes Well, I don't know if this is considered cheating, but... ``` .abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ``` The dot prints the current character (0x00) and the rest of the characters do nothing. This could technically be expanded infinitely, so please let me know if this is considered cheating. [Answer] ## Haskell, 3 points ``` + 1 ``` No matter how rearranged this code always returns function which increments input. Examples of usage in repl: ``` >(+ 1) 1 2 >(1+ ) 1 2 >( +1) 1 2 ``` [Answer] # [√ å ı ¥ ® Ï Ø ¿](https://github.com/ValyrioCode/Valyrio) , 128,234 (?) points I arrived at 128,234 with help from @DestructibleLemon. This program uses all Unicode characters (128,237) except `o`,`O` and `ł`. Oddly enough, two of these are output commands. Surely, though, no language could use all those characters, right? Well this language just ignores the commands it doesn't recognise. Problem solved. This language will, by default, output the following: ``` ===== OUTPUT ===== ================== ``` which is non-nil, non-null, non-empty and non-error. *Note: if this violates some unwritten rule, notify me in the comments and I'll change this. If you know my score (assuming this is allowed), also post in the comments.* [Answer] # J, 3 bytes ``` 1 ``` The chars 1, space and newline will always print 1. [Answer] # [///](https://esolangs.org/wiki////), ~~1~~ 2 points ``` \_ ``` [Try it online!](https://tio.run/nexus/slashes#@x8T//8/AA "/// – TIO Nexus") I have no clue how to do it in any other Turing-complete language. Of course, there is HQ9, but that just feels cheaty. 1 byte thanks to @Martin Ender. [Answer] ## [Dots](https://github.com/josconno/dots/blob/master/dots.py), 1,114,111 characters (if using unicode). `<87 dots here> Every Unicode character except NUL and . here` Explanation: ``` 1 leading binary number 1010 010 increments the value under the pointer 1010111 111 prints out chr(1) ``` So the resulting binary string is `1010111`, which converted to decimal is 87, so we need 87 dots. Every other character is a comment, so we use every character except a NUL, because Python3 stops reading the file then, and a dot, because dots aren't comments. [Answer] # [Prelude](https://esolangs.org/wiki/Prelude), score 1,112,051 (When only considering the printable ASCII `[\t\n -~]`, the score is **84**. If we consider [all Unicode code-points](https://codegolf.stackexchange.com/a/113204/32353), the score is **1,112,051**.) ``` ! " #$ %&'+,-./0:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ``` (then append all characters `[\u{7f}-\u{10ffff}]` after it.) Always print `0`. --- Prelude is a parallel stack-based language, where the stack is pre-filled with infinite numbers of 0s. * `+`: Pop two values (always 0), add them (0), and push to stack. * `-`: Pop two values (always 0), subtract them (0), and push to stack. * `#`: Pop a value and discard it. * `!`: Pop a value and output it as a *number* (always 0) (spec says "character" but interpreter says "number"; either case, a byte is printed) * `0`: Pushes 0. * `^`, `v`, `V`: Pushes the top value of the previous/next parallel programs ("voices"), but the stacks of all "voices" are filled with 0, so they always push 0. * other characters: no-op. So there are only 13 characters we need to avoid: * `(`, `)`: Unpaired parenthesis will cause error * `1`–`9`: We only want to output 0. * `?`: We don't want to input anything. * `*`: Causes very complicated consistency check for the code before and after a line consisting of a lone `*`. So we need to either remove the new line or remove the `*`. The reference implementation uses Python 2's [`.readline()`](https://docs.python.org/2/library/io.html#io.IOBase.readline) which a "new line" could mean `\r` or `\n`. So it is better to just remove the `*`. [Answer] # [Deadfish](https://esolangs.org/wiki/Deadfish#Batch), score 86 ``` o.ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghjklmnpqrtuvwxyz?!|[]_-();'"*&^$#@!1234567890+=<>,/\: ``` If that's illegal, then there's also ``` o ``` (score 1) ]
[Question] [ In the spirit of [Hello world! with NO repetition](https://codegolf.stackexchange.com/questions/18925/hello-world-with-no-repetition) Write a program that prints the string "the quick brown fox jumps over the lazy dog" with optional newline. The entire program must not repeat any characters. Note that the string to be printed *does* repeat characters, so you will have to get around that limitation somehow. Note that the winning condition is [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), i.e. *the highest-voted answer* wins. Update: To make this a little easier, repetition is allowed but you must attempt to minimize it. Programs with less (or no) repetition are given precedence over programs with some repetition. [Answer] # Microsoft Word from 97 to 2003 (and some Mac Word versions) — 10 characters No repetitions, but doesn't quite match specs - 10 characters: ``` =rand(2,1) ``` Output: ``` The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. ``` Matches specs, other than capitalization and punctuation, one repetition - 10 characters: ``` =rand(1,1) ``` Output: ``` The quick brown fox jumps over the lazy dog. ``` Newer versions of Microsoft Word use `=rand.old(1,1)` which duplicates `d` and `1`. There might be a way to use a field `{=SUM(3,-2)}` as input to rand() but my installation is having issues with fields -- namely, they're not working... "Bob" has confirmed that `{=SUM(3,-2)}` (with some difficulty) can be used to replace the first `1`, but `=` is repeated... ``` =rand({=SUM(3,-2)},1) ``` Provided you get Word to update `SUM` first, the output is: ``` The quick brown fox jumps over the lazy dog. ``` [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting) — 36 characters ``` 덆둥긇굵늖꽫긆깲닷덮긂롦닲롸껂걪덖륰댲걯덦넬댢건늆넠닆굺뎒걤닶댬首坼 ``` (expects empty input) ## Explanation: ``` Push the string "the quick brown ,fo,x, jumps ove,r the lazy dog," 덆둥긇굵늖꽫긆깲닷덮긂롦닲롸껂걪덖륰댲걯덦넬댢건늆넠닆굺뎒걤닶댬 Retrieve last character from the string (",") 首 Regular expression string-split 坼 ``` The result is the list `["the quick brown ", "fo", "x", " jumps ove", "r the lazy dog", ""]`, which is automatically concatenated into a single string for output. [Answer] ## Perl 6 (76 chars, no doubles) The script (will be mangled by the board software, but there's En Space up to Thin Space and NL and LF and tab) ``` say EVAL lc q{<the Quiţk Brown fïX jUmpS ůvťɲ Tɨå ìšzY dOg>~&(127.CHR x 43)} ``` * It uses EVAL (thanks again for making it uppercase) and `<foo bar>` quote words which supports all the special space characters as word separators. * `say` joins the list of strings using space, works nicely here :) * Next I use `~&` and 127 to bit shuffle to plain ascii. Extra complication: `'Ŭ'.lc` becomes `'ŭ'` so that becomes an `s` instead of the `r` I needed. Adding 128 some extra times helps :) A version with backslash escapes instead of unicode characters to show they're all different ``` say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)} ``` If you want to verify they're all unique, use this script (I used `Qb"string"` to have basic quoting with only backslash escapes) ``` .say for Qb"say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)}" .comb.Bag.grep(*.value > 1).map: {.key.ord.base(16) ~ " $_" } ``` Or execute it directly using ``` EVAL Qb"say\x[3000]EVAL\x[9]lc q{<the\x[2003]Qui\x[163]k\x[2004]Brown\x[2005]f\x[EF]X\x[2006]jUmpS\x[2007]\x[16F]v\x[165]\x[272]\x[2008]T\x[268]\x[E5]\x[2009]\x[EC]\x[161]zY\x[200A]dOg>~&(127.CHR\x[0A]x\x[0D]43)}" ``` [Answer] ## PHP - 67 bytes ``` <?echo$g^¶¥€¼½ˆ•.${~˜}=ÂÍåœÌýü¡¦Åþ¾’‹Ï†£‘ƲáºëÓâæÝ—ߙ󖎸·³ø‰ï®ÜØÔ; ``` *Copy-Paste, save as Latin-1 (Ansi).* This is a 7-byte xor-cipher, using the string `¶¥€¼½ˆ•` for salt. One repeated character: `$`. [Answer] # Haskell, 71 characters ``` map(\c->chr$mod(ord c)128)"tŨeఠquiţkĠbŲɯwnȠfѯxРjѵŭŰsܠůvťѲठѴѨѥਠlšzyଠɤկg" ``` Yet another 7-bit modulo solution. Repeated characters: ``` c 3 d 2 m 2 o 2 r 2 ( 2 ) 2 " 2 ``` First time golfing with Haskell; anyone more experienced in the language, feel free to improve. I wanted to make the anonymous function point-free to avoid having to mention a variable twice, but I don't know if it'd be a net benefit. ]
[Question] [ Weirdo Incorporates have a weird way of grading their staffs by the number of days they were present in the office: ``` 0 - 13 : F 14 - 170 : E 171 - 180 : D 181 - 294 : C 295 - 300 : B 301 - 365 : A Note: The range is inclusive (i.e. 0-13 means 0 days and 13 days both will evaluate as grade 'F'). ``` # Objective: Write a program/function that outputs/returns the grade of an employee for the number of days [within inclusive range of 0-365] attended by the employee. # Rules: * You may take input as a string or a number but must output as a string/alphabet (You may choose either lower or upper-case.) * Standard loopholes apply. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins! # Test cases: ``` 12 => F 15 => E 301 => A 181 => C ``` # Scoreboard: ``` var QUESTION_ID=142243,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Javascript (ES6), 51 bytes ``` n=>"ABCDEF"[(n<14)+(n<171)+(n<181)+(n<295)+(n<301)] ``` ## Alternative solutions (longer): ~~53~~ 52 bytes (-1 byte thanks to @Arnauld) ``` n=>"FEDCBA"[n>300?5:n>294?4:n>180?3:n>170?2:+(n>13)] ``` ~~55~~ 53 bytes (-2 bytes thanks to @Neil) ``` n=>"AFEDCB"[[14,171,181,295,301].findIndex(m=>n<m)+1] ``` 55 bytes ``` n=>"FEDCBA"[[13,170,180,294,300].filter(m=>n>m).length] ``` ## Example code snippet: ``` f= n=>"ABCDEF"[(n<14)+(n<171)+(n<181)+(n<295)+(n<301)] console.log(f(12)) console.log(f(15)) console.log(f(301)) console.log(f(181)) ``` [Answer] # TI-Basic, 40 bytes ``` sub("FEDCBA",sum(Ans≥{0,14,171,181,295,301}),1 ``` [Answer] # [J](http://jsoftware.com/), 31 bytes ``` 'FEDCBA'{~13 170 180 294 300&I. ``` [Try it online!](https://tio.run/##y/r/P03B1kpB3c3VxdnJUb26ztBYwdDcQMHQwkDByNJEwdjAQM1Tj4srNTkjX0HDOk1TzU4BKAtUZAJRZ24IVmtoYQhWb2RpCtIDxIYKxmam//8DAA "J – Try It Online") ## Explanation ``` 'FEDCBA'{~13 170 180 294 300&I. Input: n 13 170 180 294 300 Constant array [13, 170, 180, 294, 300] &I. Use it with interval index to find which of the intervals (-∞, 13], (13, 170], (170, 180], (180, 294], (294, 300], (300, ∞) n can be inserted at {~ Index into 'FEDCBA' This string and return that char ``` [Answer] # [Python 3](https://docs.python.org/3/), 50 bytes Thanks to @jferard for -4 bytes. ``` lambda n:chr(70-sum(n>ord(x)for x in"\rª´ĦĬ")) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjmjSMPcQLe4NFcjzy6/KEWjQjMtv0ihQiEzTymm6NCqQ1uOLDuyRklT839BUWZeiUaahqGRpiYXnGOKxDE2MESWsgDy/gMA "Python 3 – Try It Online") # [Python 3](https://docs.python.org/3/), 54 bytes ``` lambda n:chr(70-sum(n>x for x in[13,170,180,294,300])) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjmjSMPcQLe4NFcjz65CIS2/SKFCITMv2tBYx9DcQMfQwkDHyNJEx9jAIFZT839BUWZeiUaahqGRpiYXnGOKxDE2MESWsgDy/gMA "Python 3 – Try It Online") Saved 2 bytes thanks to @mathmandan, and indirectly thanks to @JonathanFrech. # [Python 2](https://docs.python.org/2/), 56 bytes ``` lambda n:"ABCDEF"[sum(n<x for x in[14,171,181,295,301])] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPSsnRydnF1U0purg0VyPPpkIhLb9IoUIhMy/a0ETH0NxQx9DCUMfI0lTH2MAwVjP2f0FRZl6JRpqGoZGmJhecY4rEASpElrIA8v4DAA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18 17 15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` NịØAx“A©r½ɗÇ‘¤ ``` A monadic link taking a number and returning a character. **[Try it online!](https://tio.run/##ASYA2f9qZWxsef//TuG7i8OYQXjigJxBwqlywr3Jl8OH4oCYwqT///8xNA "Jelly – Try It Online")** or see [all input-output pairs](https://tio.run/##ATIAzf9qZWxsef//TuG7i8OYQXjigJxBwqlywr3Jl8OH4oCYwqT/MzY24bi2xbzDh@KCrCRH/w "Jelly – Try It Online"). ### How? ``` NịØAx“A©r½ɗÇ‘¤ - Link: number, d N - negate d ¤ - nilad followed by link(s) as a nilad: ØA - uppercase alphabet yield = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" “A©r½ɗÇ‘ - code-page indices = [65,6,114,10,157,14] x - times = 'A'x65+'B'*6+'C'x114+'D'x10+'E'*157+'F'*14 ị - index into (1-indexed & modular - hence the negation to allow all Fs to be together at one end) ``` [Answer] # C, ~~62~~ 61 bytes *Thanks to @Jonathan Frech for saving a byte!* ``` f(n){putchar(70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuqC0JDkjsUjD3EBXI8/G0MTewApImRvaG4JoC0N7IyBtZGlqbwykjQ0M7U2sTDU1rWv/Z@aVKOQmZuZpaHJVcykAQZqGoZGmNdC8Yg0lJU1rmJgpphjQGCwKLVAEa/8DAA) # C, 57 bytes ``` #define f(n)70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5) ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU0jT9PcQFcjz8bQxN7ACkiZG9obgmgLQ3sjIG1kaWpvDKSNDQztTaxMNf9n5pUo5CZm5mloclVzKQBBQRFQKE1DSTU5Jk9JB2iioZGmpjUOKVOcUkALcGuzAMvV/gcA) # C (gcc), 54 bytes ``` f(n){n=70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs/W3EBXI8/G0MTewApImRvaG4JoC0N7IyBtZGlqbwykjQ0M7U2sTDWta/9n5pUo5CZm5mloclVzKQBBQRFQKE1DSTU5Jk9JRyFNw9BIU9Mah5QpTimgFbi1WYDlav8DAA) # C (gcc), 50 bytes *Using [@Herman Lauenstein's solution](https://codegolf.stackexchange.com/a/142247/61405).* ``` f(n){n=65+(n<14)+(n<171)+(n<181)+(n<295)+(n<301);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs/WzFRbI8/G0EQTTJkbQmgLCG1kaQqmjQ0MNa1r/2fmlSjkJmbmaWhyVXMpAEFBEVAoTUNJNTkmT0lHIU3D0EhT0xqHlClOKZDxOLVZgOVq/wMA) [Answer] # [Kotlin](https://kotlinlang.org), 56 bytes ``` {v->'F'-listOf(13,170,180,294,300).filter{it<v}.count()} ``` [Try it online!](https://tio.run/##ZcpBC4IwGMbxe59iNzeYsrkiExMiCDp16BOMSBut15ivw5B99mXXfG7/H8@zQ2sgeu3IWNIzIEvr42OufZx8WienJLWmx0tDpeJyK7gsBM93a66EYFljLN7dZLDyIbt1AyBlITYDkJc2QLVr@5IcnNOf6orOQFszMq3IvPdcaIGOVOaM/dNmQUrI5a34WYhf "Kotlin – Try It Online") ## Beautified ``` { v-> // Count the grades passed, then subtract that from F 'F' - listOf(13,170,180,294,300) .filter { it < v } .count() } ``` ## Test ``` var x:(Int)->Char = {v->'F'-listOf(13,170,180,294,300).filter{it<v}.count()} fun main(args: Array<String>) { println(x(12)) println(x(15)) println(x(301)) println(x(181)) } ``` [Answer] # [Japt](https://github.com/ETHproductions/japt/), ~~23~~ 21 bytes ``` 'Gc-[#ªT#´D294L*3]è<U ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=J0djLVsjqlQjtEQyOTRMKjNd6DxV&input=MzAx) --- ## Explantion Implicit input of integer `U`. ``` 'Gc- ``` Subtract from the codepoints of the (single character) string `G` ... ``` è<U ``` The count of elements less than `U` ... ``` [#ªT#´D294L*3] ``` In the array of 170 (`#ª`), 0 (`T`), 180 (`#´`), 13 (`D`), 294 (literal) & 300 (`L*3`), so formatted and ordered to avoid the use of delimiting commas. `0` could be removed (subtracting from the codepoint of `F` instead) but then a comma would need to be added or `C*F` (12\*15) used for `180`, ultimately saving no bytes. [Answer] # [R](https://www.r-project.org/), ~~50~~ 44 bytes ``` LETTERS[6-sum(scan()>c(13,170,180,294,300))] ``` [Try it online!](https://tio.run/##K/r/38c1JMQ1KDjaTLe4NFejODkxT0PTLlnD0FjH0NxAx9DCQMfI0kTH2MBAUzP2v6HpfwA "R – Try It Online") same as the javascript answer, but uses R's vectorization and LETTERS builtin to come in a tiny bit shorter. Thanks to [rturnbull](https://codegolf.stackexchange.com/users/59052/rturnbull) for shaving off those last 6 bytes. [Answer] # [Python 2](https://docs.python.org/2/), 77 bytes ``` lambda n:chr(70-sorted(_*(n>(0,13,170,180,294,300)[_])for _ in range(6))[-1]) ``` [Try it online!](https://tio.run/##XchBCsIwEADAr4SedmUDm0ZSLdiP1BKibWxBNyXm4uujZ08Ds3/KmqSt8XKtz/C6zUFJf18zdKzfKZdlBn8AGYDJWDLdjxNTez6SZcbRTxhTVl5tonKQxwIOcdRmwvr31jns97xJUZ4aPTQUwWP9Ag "Python 2 – Try It Online") [Answer] # [Recursiva](https://github.com/officialaimm/recursiva), ~~49~~ 30 bytes ``` Y(++++<a301<a295<a181<a171<a14 ``` [Try it online!](https://tio.run/##K0pNLi0qzixL/P8/UkMbCGwSjQ0MbRKNLE1tEg0tgCxDcxBh8v8/kAcA "Recursiva – Try It Online") Allow me to answer my own question in my own language. :D * saved 19 bytes by using technique from @Herman Lauenstein's amazing [JS answer](https://codegolf.stackexchange.com/a/142247/59523) # Explanation: ``` Y(++++<a301<a295<a181<a171<a14 <a301<a295<a181<a171<a14 calculate true/false for all the conditions ++++ sum up all the conditions to obtain n which can be either 0,1,2,3,4 or 5 ( yield upper-case Alphabet Y Get n-th element ``` [Answer] # [Perl 5](https://www.perl.org/), 47 + 1 (-p) = 48 bytes ``` $_=((F)x14,(E)x157,(D)x10,(C)x114,(B)x6)[$_]||A ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZDw02zwtBER8MVSJma62i4AGkDHQ1nIAUSdtKsMNOMVomPralx/P/f2MzgX35BSWZ@XvF/3QIA "Perl 5 – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 28 bytes ``` G6<13T17*180T30*294]5FhQ>)s@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=G6%3C13T17%2a180T30%2a294%5D5FhQ%3E%29s%40&input=181&warnings=0&hex=0) # Explanation ``` G6<13T17*180T30*294]5FhQ>)s@ - Full program. T is the constant for 10. G - The lowercase alphabet. 6< - With the letters after the index 6 trimmed. 13 - The literal 13. T17* - The integer 170, composed by 17 * 10, to save whitespace. 180 - The literal 180. T30* - The integer 300, composed by 30 * 10. 294 - The literal 294. ]5 - Create a list of 5 elements. FhQ>) - For each element in the list. h - Increment. Q - The input. > - Is smaller ^^ than ^? Yields 1 for truthy and 0 for falsy. )s - Close loop and sum. @ - Get the index in the alphabet substring explained above. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes ``` “n-'‘+⁹;“ỌẠÇ‘ð>SịØA ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5w8XfVHDTO0HzXutAbyHu7uebhrweF2oNDhDXbBD3d3H57h@B/Ib1oDRN5AHPn/f7SBjiEQGcfqRBua6BiaANnmBiCOuSGQZapjaAHmWRjqGBkZ6BhZmgB5RpamQJa5jrEBSM7YwFDH2NhAx9jMNBYA "Jelly – Try It Online") Footer executes all test-cases and formats the output. [Answer] # Pyth, 30 bytes ``` @GtlfgTQmCdc"\r ª ´ & , m"d ``` The site doesn't seem to show the character with code point 1, so you need to insert a character with code point 1 before the `&`, `,`, and `m` at the end (Replace all `1`s with character with code point 1): ``` @GtlfgTQmCdc"\r ª ´ 1& 1, 1m"d ``` [Answer] # [Pyth](https://pyth.readthedocsio), 25 ~~26~~ bytes ``` @<G6sgRQ[13*17T180*30T294 ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=%40%3CG6sgRQ%5B13%2a17T180%2a30T294&test_suite=1&test_suite_input=12%0A15%0A301%0A181&debug=0)** # Explanation ``` @<G6sgRQ[13*17T180*30T294 - Full program. G - The lowercase alphabet. < 6 - With the letters after the index 6 trimmed. We will call "S". [ - Initialise a list literal. 13 - The literal 13. *17T - The integer 170, composed by 17 * 10, so save whitespace. 180 - The literal 180. 294 - The literal 294. *30T - The integer 300, composed by 30 * 10. gRQ - For each element, return 1 if is is ≥ the input. 0 otherwise. s - Sum. @ - Get the index into S of ^. - Output implicitly. ``` [Answer] # [Ly](https://github.com/LyricLy/Ly), 74 bytes ``` n(14)L["F"o;]p(171)L["E"o;]p(181)L["D"o;]p(195)L["C"o;]p(301)L["B"o;]"A"o; ``` [Try it online!](https://tio.run/##y6n8/z9Pw9BE0ydayU0p3zq2QMPQ3BDEc4XyLMA8FyjP0hTEc4bwjA3Ack4gnpIjkPz/39AYAA "Ly – Try It Online") A simple if-chain approach. I doubt it can be made much shorter. [Answer] # [Bash](https://www.gnu.org/software/bash/), 55 bytes ``` echo obase=16\;10 $[$1<{14,171,181,295,301}]|tr \ +|bc ``` [Try it online](https://tio.run/##S0oszvj/PzU5I18hPymxONXW0CzG2tBAQSVaxdCm2tBEx9DcUMfQwlDHyNJUx9jAsDa2pqRIIUZBQbsmKfn///9AKQA) or [Verify test cases](https://tio.run/##DcqxDoIwFIXhvU9xhm6WpAcENeiTgAOFEly4CWUgEZ/92ukfvj8MadFZNhz4rLBsMQlS3FEUsIfGcRFIGFJ8selbetjO8vnl1fFGxztd@ahd5fl7n/uGHricYdRJ1qjK0rA2GU0ec/0f). [Answer] # Java 8, 55 bytes ``` n->n<14?'F':n<171?'E':n<181?'D':n<295?'C':n<301?'B':'A' ``` [Try it here.](https://tio.run/##hZBLD4IwEITv/oq9lR4kghoVH8TnTS4ejYdaUYuwECgkxvDb64Jejck2@XZ2Mpk0EpXoplmI0eVhZCyKAvZC4asDoFCH@VXIEIJmBZB3kYO0SAfkU5JqejSFFlpJCABhDga7C5w5A5/tmEcwcny2bWlMtGnInQx9tm6o3yNtxTy2ZGb6CcvKc0xh38wqVRdIqJB10LnC2/EEgn/aHJ6FDhM7LbWd0UnHaKEtLcflbbffhuE/w9j546Da/PsBtXkD) Alternative **57 bytes**: ``` n->(char)(n<14?70:n<171?69:n<181?68:n<295?67:n<301?66:65) ``` [Try it here.](https://tio.run/##hVDLDoJADLz7FT3uHiCg8lb5ArlwNB7WFXURC4GFxBi@HYtwNSRtOp1OJpPmohNGWWWYX5@DLETTwFEo/KwAFOqsvgmZQTKuAPIhapCMeEAeEdVTUzVaaCUhAYQ9DGgc2KjkDHf2NvaskKZnx24wAp@AT2AdOLHrEdhYxLih6/Ahmuyq9lKQ3ezaleoKL4rEUl0rvJ/OIPiUJ303OnuZZavNik66QIamZPaa/9L9FzhLAt9eUFBqPr@gH74) Alternative **60 bytes**: ``` n->"FEDCBA".charAt(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5) ``` [Try it here.](https://tio.run/##hVDLCsJADLz7FaGn3YPFrS2@XerrpheP4mFdq26taWlXQcRvr6n2KoWEIZPJMCRWD9VOswjj47XUiSoKWCuDrxaAQRvlJ6Uj2FQjgL6oHDQjHpCPiHpTUxVWWaNhAwgTKLE9dVbLxXwWOm51EVqGY@HLzpCgJ6SosC@kR@gNAtkl7HaE9IcBL0c/x@x@SMixNn6k5gg3SsW2Njd43u1B8V@k7bOw0c1N79bNaGUTZOhqJjz@DfhfEDQJ@qJBQZl5/YV3@QE) Maybe some kind of formula can be find to get 0-5 in a shorter way than `n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5` using the last approach. Still investigating this. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 59 bytes ``` (,'F'*14+,'E'*157+,'D'*10+,'C'*114+,'B'*6+,'A'*65)["$args"] ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0NH3U1dy9BEW0fdFUibmgMZLkCGAZB2BtJgGSd1LTMg5QikTDWjlVQSi9KLlWL///9vbGAIAA "PowerShell – Try It Online") Similar-ish to Jonathan Allen's Jelly answer, in that we're constructing an array of all the letters concatenated together, then indexing into that array with the input `$args`. [Answer] # [Rabbit~](https://github.com/Ghilt/Rabbit), 50 bytes (Noncompeting, postdates question. I just finished the interpreter(yay) and wanted to try and solve something. This is also my first code golf thing ever) ``` =>FEDCBA$<({.0-\_-^\-&^?n&&}_}\>\{{\>:.¤})Ð"ỤṅỌrḲA ``` It basically takes the differences from one grade to the next 14,157,10,114,6,65 (encoded as `ỤṅỌrḲA`) and subtracts from the input. If a negative number is found it stops progressing along the 'FEDCBA' sequence and outputs the letter. ### Small explanation of this beautiful piece of syntax Rabbit~ uses a grid based memory with one or several carets you can move around; this solution uses 2. ``` =>FEDCBA$<({.0-\_-^\-&^?n&&}_}\>\{{\>:.¤})Ð"ỤṅỌrḲA - Full program. FEDCBA - Load bytes into grid Ð"ỤṅỌrḲA - Load bytes 14,157,10,114,6,65 into second line of data grid = - Read input > < _ ^ ^ _ > > - Move caret (most instructions read from the grid below the active caret) $ - Create a new caret ( ) - Loop {.0 } } {{ } - Conditional statement checking if value at caret == 0 then move active caret to next grade else print and quit - - - - Subtract \ \ \ \ - Cycle active caret & && - Bitwise and to see if number is negative ?n - Get negative sign bit :. - Print value at caret as character ¤ - Terminate program ``` [Answer] # Excel, 53 bytes Sum of conditions, then returns the required ASCII character: ``` =CHAR((A1<14)+(A1<171)+(A1<181)+(A1<295)+(A1<301)+65) ``` Alternative solutions: Summing conditions, return string index (63 bytes): ``` =MID("ABCDEF",(A1<14)+(A1<171)+(A1<181)+(A1<295)+(A1<301)+1,1) ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 30 bytes **Solution:** ``` "FEDCBA"@0 14 171 181 295 301' ``` [Try it online!](https://tio.run/##y9bNz/7/X8nN1cXZyVHJwUDB0ETB0NxQwdDCUMHI0lTB2MBQ3dDI@P9/AA "K (oK) – Try It Online") **Explanation:** Index into the correct bucket: ``` "FEDCBA"@0 14 171 181 295 301' / the solution 0 14 171 181 295 301' / bin (') input in a bucket "FEDCBA"@ / index (@) into "FEDCBA" ``` [Answer] # [Jotlin](https://github.com/jrtapsell/jotlin), ~~48~~ 41 bytes ``` {v->'F'-l(13,170,180,294,300).f{a<v}.l()} ``` Whole program: ``` var x:(Int)->Char = {v->'F'-l(13,170,180,294,300).f{a<v}.l()} println(x(12)) println(x(15)) println(x(301)) println(x(181)) ``` Ported my previous Kotlin answer [here](https://codegolf.stackexchange.com/questions/142243/weird-grading-system/142267#142267). [Answer] # [V](https://github.com/DJMcMayhem/V), 37 34 bytes ``` aFEDCBA5äh113äh9äh156äh13ähÀ|vyVp ``` [Try it online!](https://tio.run/##K/v/P9HN1cXZyVHa9PCSDENDYyBpCWKZmoFIEPdwQ01ZZVjB////DU0A "V – Try It Online") Hexdump: ``` 00000000: 3133 4146 1b31 3536 4145 1b39 4144 1b31 13AF.156AE.9AD.1 00000010: 3133 4143 1b35 4142 1b36 3441 411b eec0 13AC.5AB.64AA... 00000020: 7c76 7956 70 |vyVp ``` Basic idea: * Print `FEDCBA`, create 5 copies of B, 113 copies of C etc. resulting in the string `FFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEDDDDDDDDDCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCBBBBBA` (There is probably a more efficient way to do this) * Go to `n`th column (`n` is the first argument), copy a single character and replace the entire string with it. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` •5r¥[‚=€®•3ô›_ASsϤ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMi06JDS6MfNcyyfdS05tA6oIDx4S2PGnbFOwYXH@4/tOT/f0MA "05AB1E – Try It Online") [Answer] ## Perl 6, ~~42~~ 39 bytes ``` {chr(65+[+] "\rª´ĦĬ".ords »>»$_)} ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 bytes ``` 5"«µħĭ",+|oH-VA@] ``` [Run and debug online!](https://staxlang.xyz/#c=5%22%0E%C2%AB%C2%B5%C4%A7%C4%AD%22%2C%2B%7CoH-VA%40%5D&i=12%0A13%0A14%0A15%0A301%0A181&a=1&m=2) ## Explanation Bytes counted in CP437. ``` 5"«µħĭ",+|oH-VA@] 5 - 5 minus the result of the following "«µħĭ" [14, 171, 181, 295, 301] ,+ Append input |oH Index of last element if the array were to be sorted VA@] Letter in the alphabet with the given index ``` [Answer] # Excel, 49 bytes `=MID("FEDCBA",MATCH(A1,{0;14;171;181;295;301}),1)` just taking advantage of the MATCH function's default match type behaviour but i'm sure there's a shorter answer if someone has more experience with excel, please comment any ways i can improve this answer! [Answer] # C#, 110 bytes ``` x=>{if(x<14)return"F";if(x<171)return"E";if(x<181)return"D";if(x<295)return"C";if(x<301)return"B";return"A";}; ``` [Try it online](https://tio.run/##Pc7NCsIwEATgVwk5JQeL9QeVWEGrnhRED55DupZATSCbSkvps1eLTfc0fDOHVThR1kHXlahNTh41engLVUhEopoMCsilB4Le9TUybTxxXKCXXivysTojV6kN4w2SOqmSXaNfrNrGC@7Al87QMxV/WcWBToHWIx0Hmm2WgdKB5tNxdaBiSHsqWpFag7aA6Om0B1b3v0U36RBYaO4gs4s2wPjvRNt23Rc "C# (.NET Core) – Try It Online") ]
[Question] [ # Intro: I remember, when I was a kid, I would get a calculator and keep on pressing the `+` button, and see how high I could count. Now, I like to program, and I'm developing for iOS. Counting is a fundamental skill for both humans and computers alike to do. Without it, the rest of math can't be done. It's done simply by starting at `1` and repetitively adding `1` to it. # The challenge: This is but a simple challenge. What I would like your program to do is print from `1` to whatever `Integer` it takes in. However, I'll throw a twist in it, since decimal counting is kinda boring: **The counting cannot be in base 10, it has to show itself counting in binary.** So, to count to 5, using 32-bit integers, it would look like this: ``` 0000 0000 0000 0000 0000 0000 0000 0001 ..... 1 0000 0000 0000 0000 0000 0000 0000 0010 ..... 2 0000 0000 0000 0000 0000 0000 0000 0011 ..... 3 0000 0000 0000 0000 0000 0000 0000 0100 ..... 4 0000 0000 0000 0000 0000 0000 0000 0101 ..... 5 ``` It's a computer. They know binary best. Your input can be either a 32-bit or 64-bit integer. It is truly up to you. **However, if you use 32-bit integers, your output *must* be 32-bit integers *in binary*, and if you use 64-bit integers, your output *must* be 64-bit integers *in binary*.** # Sample input: a 32-bit integer, `5` # Sample output: ``` 0000 0000 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000 0000 0010 0000 0000 0000 0000 0000 0000 0000 0011 0000 0000 0000 0000 0000 0000 0000 0100 0000 0000 0000 0000 0000 0000 0000 0101 ``` # Scoring: Your score is equal to however many bytes your code is. As this is Code Golf, lowest score wins. ## Bonus points: If you show, in the output, the number it's at as a base 10 number (for example, `0000 0000 0000 0000 0000 0000 0000 0001` in binary is equal to the base 10 `1`), multiply your score by `0.8`. If you group 4 digits of output like I did, then multiply your score by `0.8` (again). **This isn't required.** Do not round up, and do not round down. Your score is a floating-point number. # Good luck! [Answer] ## APL, 10 characters Another on in APL. Assumes`⎕IO←1` (the default). No bonus points. Reads the number from the input device. If your APL uses 64 bit integers instead of 32 bit integers, substitute 64 for 32 as needed. Notice that APL transparently converts to floating point numbers when the range of an integer is exceeded. It's hard thus to exactly say what integer size APL works with. ``` ⍉(32⍴2)⊤⍳⎕ ``` ### explanation ``` 2 ⍝ the number 2 32⍴2 ⍝ a vector of 32 twos. (32⍴2)⊤X ⍝ X represented as base 2 to 32 digits precision ⍳X ⍝ a vector of the integers from 1 to X ⎕ ⍝ a number queried from the terminal (32⍴2)⊤⍳⎕ ⍝ the output we want, flipped by 90° ⍉(32⍴2)⊤⍳⎕ ⍝ the output we want in correct orientation (⍉ is transpose) ``` [Answer] # JavaScript (*ES6*) 56.8 (71\*0.8) 32 bit version, as JavaScript can not handle 64 bit precision (at most 53 bits using floating point doubles) Without grouping ``` f=n=>{for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).slice(1),i)} ``` With grouping - score 60.16 (94\*.64) ``` f=n=>{for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).slice(1).match(/..../g).join` `,i)} ``` **Test** in any browser (ES5) ``` function f(n) { for(i=0;i++<n;)console.log((8*(8<<26)+i).toString(2).substr(1).match(/..../g).join(' '),i) } // Test console.log = function(x,y) { O.innerHTML += x+' '+y+'\n' } ``` ``` Count to: <input id=I><button onclick="O.innerHTML='';f(+I.value)">-></button> <pre id=O></pre> ``` [Answer] # Pyth, 18 \* 0.8 \* 0.8 = 11.52 bytes ``` VSQjd+c.[64.BN\04N ``` Example output: ``` 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 5 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0110 6 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0111 7 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1000 8 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1001 9 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1010 10 ``` [Answer] # Pyth, 19 \* 0.8 \* 0.8 = 12.16 bytes ``` VSQjd+cjk.[032.BN4N ``` Example output for input 5: ``` 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0101 5 ``` [Demonstration.](https://pyth.herokuapp.com/?code=VSQjd%2Bcjk.%5B032.BN4N&input=10&debug=0) [Answer] ## Python 2, 48 \* 0.8 = 38.4 ``` i=0;exec"i+=1;print format(i,'032b'),i;"*input() ``` Converts a number to binary, uses string formatting to convert it to binary with 32 digits, and then also prints the decimal number for the bonus. Uses an `exec` loop to increment from `1` to the input value. [Answer] # CJam, 13.44 (21 × 0.64) ``` ri{)_2b64Ue[4/S*S@N}/ ``` [Try it online.](http://cjam.aditsu.net/#code=ri%7B)_2b64Ue%5B4%2FS*S%40N%7D%2F&input=5) [Answer] # APL, 23.68 (37 × .8 × .8) ``` {⎕←(⍕⍵),⍨⊃,/,/' ',⍨⍕¨8 4⍴(32⍴2)⊤⍵}¨⍳⎕ ``` [Answer] # KDB(Q), 50 \* 0.8 \* 0.8 = 32 I feel a bit sad with my submission :( There should be a better way to do this! ``` {-1{" "sv raze@'string(0N 4#0b vs x),x}@'1+til x;} ``` # Explanation ``` 1+til x / counting { }@' / lambda each (0N 4#0b vs x),x / convert to binary and join with input " "sv raze@'string / convert to string, concatenate each string and join with space {-1 ;} / print and surpress output in lambda ``` # Test ``` q){-1{" "sv raze@'string(0N 4#0b vs x),x}@'1+til x;}5 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 5 ``` [Answer] # Common Lisp, 96.0 Score: `(* 150 .8 .8)` ``` (lambda(y)(flet((p(n &aux(x(format()"~39,'0b ~:*~d"n)))(dolist(p'(4 9 14 19 24 29 34))(setf(aref x p)#\ ))(princ x)(terpri)))(dotimes(i y)(p(1+ i))))) ``` ## Example Calling the function with 10: ``` 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0101 5 0000 0000 0000 0000 0000 0000 0000 0110 6 0000 0000 0000 0000 0000 0000 0000 0111 7 0000 0000 0000 0000 0000 0000 0000 1000 8 0000 0000 0000 0000 0000 0000 0000 1001 9 0000 0000 0000 0000 0000 0000 0000 1010 10 ``` ## Explanation `(format()"~39,'0b ~:*~d" #b101010101010)` gives: ``` "000000000000000000000000000101010101010 2730" ``` The intermediate string (an array) is modified to put a space character at the following zero-based indices: 4 9 14 19 24 29 34. Then it is printed. Note that the apparently straightforward `(format t"~39,'0,' ,4:b ~:*~d" #b101010101010)` format does not do what we want. It prints: ``` 00000000000000000000000001010 1010 1010 2730 ``` (the padding is not grouped by 4) [Answer] # Ruby, 28 (35 \* 0.8) ``` ?1.upto(*$*){|x|puts"%.32b #{x}"%x} ``` [Answer] # C, 97 \* 0.8 \* 0.8 = 62.08 ``` a,x;main(b){for(scanf("%u",&b);a++<b;printf("%d\n",a))for(x=32;x--;)printf("%*d",x%-4-2,a>>x&1);} ``` Example output for input "5": ``` 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0101 5 0000 0000 0000 0000 0000 0000 0000 0110 6 0000 0000 0000 0000 0000 0000 0000 0111 7 0000 0000 0000 0000 0000 0000 0000 1000 8 0000 0000 0000 0000 0000 0000 0000 1001 9 ``` ~~I could add one more whitespace character to separate the decimal numbers from the binary numbers, but technically the problem doesn't require it, I think?~~ EDIT: Thanks, CL! [Answer] # Octave, 23 characters ``` dec2bin(1:input(""),32) ``` Example output for input 5: ``` ans = 00000000000000000000000000000001 00000000000000000000000000000010 00000000000000000000000000000011 00000000000000000000000000000100 00000000000000000000000000000101 ``` [Answer] # MatLab, 19 bytes ``` @(x)dec2bin(1:x,32) ``` Not too much to this one, MatLab has a built in decimal to binary converter and automatically prints the result. [Answer] # Julia, 42 bytes This is a bit shorter without the bonuses. ``` n->for i=1:n println(lpad(bin(i),64,0))end ``` This creates an unnamed function that takes an integer and prints the binary representation of each number from 1 to *n*, each left padded with zeros to 64 characters. --- ### With bonuses, 78 bytes \* 0.8 \* 0.8 = 49.92 ``` n->for i=1:n for j=1:4:64 print(lpad(bin(i),64,0)[j:j+3]*" ")end;println(i)end ``` This creates an unnamed function that takes an integer and prints the binary representation as before, this time split into groups of 4 with the number in base 10 at the end. [Answer] # Common Lisp, score: 64.0 *100 bytes \* 0.8 \* 0.8* I'm pretty happy with my score, but I still feel like there should be a possibility to simplify my code a bit. ## Output ``` 0000 0000 0000 0000 0000 0000 0000 0001 1 0000 0000 0000 0000 0000 0000 0000 0010 2 0000 0000 0000 0000 0000 0000 0000 0011 3 0000 0000 0000 0000 0000 0000 0000 0100 4 0000 0000 0000 0000 0000 0000 0000 0101 5 0000 0000 0000 0000 0000 0000 0000 0110 6 0000 0000 0000 0000 0000 0000 0000 0111 7 0000 0000 0000 0000 0000 0000 0000 1000 8 0000 0000 0000 0000 0000 0000 0000 1001 9 0000 0000 0000 0000 0000 0000 0000 1010 10 ``` ## Code ``` (defun r(n)(dotimes(i n)(format t"~{~a~a~a~a ~}~a~%"(coerce(format()"~32,'0B"(1+ i))'list)(1+ i)))) ``` ## Explanation As described in [coredump's answer](https://codegolf.stackexchange.com/a/53304/42187), the format string ``` "~32,'0B" ``` does output base2 numbers but there seems to be no possibility to get the grouping right as well. Hence I *coerce* the string into a list and iterate over it by picking out groups of 4 with this format string: "~{~a~a~a~a ~}~a~%" After each group of 4 there's a blank, and after the last group, the base10 number is printed. ## Without grouping (60x0.8 => 48.0) ``` (defun r(n)(dotimes(i n)(format t"~32,'0B ~:*~a~%"(1+ i)))) ``` This uses ~:\* to process the (single) format argument again. [Answer] ## PHP, 51.84 (81 × .8 × .8) 32-bit version, as PHP is limited to only 32-bit on Windows regardless of whether the OS is 64-bit. Takes one command line argument. ``` for($i=0;$i++<$argv[1];)echo chunk_split(str_pad(decbin($i),32,0,0),4," ")."$i\n"; ``` [Answer] ## CoffeeScript, 60.8 (76 × .8) 32-bit version for [reasons mentioned above](https://codegolf.stackexchange.com/a/53282/22867), as CoffeeScript compiles down to JavaScript. ``` f=(x)->console.log(("0".repeat(32)+i.toString 2).slice(-32),i)for i in[1..x] ``` With grouping it becomes slightly longer: 64.64 (101 × .8 × .8) ``` f=(x)->console.log(("0".repeat(32)+i.toString 2).slice(-32).match(/.{4}/g).join(" "),i)for i in[1..x] ``` [Answer] # Haskell, 56 bytes ``` f n=putStr$unlines$take n$tail$sequence$replicate 32"01" ``` Usage: ``` *Main> f 5 00000000000000000000000000000001 00000000000000000000000000000010 00000000000000000000000000000011 00000000000000000000000000000100 00000000000000000000000000000101 ``` For 64bit, replace the `32` with `64`. Every other number works, too. [Answer] ## J, 20 bytes ``` (32#2)#:>:i.".1!:1<1 ``` Sample input and output: ``` 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 ``` [Answer] # Swift: 98.56 (154 \* 0.8 \* 0.8) ``` for x in 1...Int(Process.arguments[1].toInt()!){var p=String(x,radix:2) let q=count(p) for i in 0..<32-q{p=(((q+i)%4==0) ?"0 ":"0")+p} println("\(p) \(x)")} ``` [Answer] ## Ruby, 64 bit ### 70 \* 0.8 \* 0.8 = 44.8 bytes (split, decimal) ``` 1.upto(gets.to_i){|i|puts ("%064d"%i.to_s 2).scan(/.{4}/)*?\s+" #{i}"} ``` ### 51 \* 0.8 = 40.8 bytes (decimal) ``` 1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2)+" #{i}"} ``` ### 67 \* 0.8 = 53.6 bytes (split) ``` 1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2).scan/.{4}/} ``` ### 44 bytes (no bonuses) ``` 1.upto(gets.to_i){|i|puts "%064d"%i.to_s(2)} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Lb32jsäð0:» ``` -2 bytes thanks to *@Mr.Xcoder*. Outputs without space-delimiter nor sequence-number. [Try it online.](https://tio.run/##MzBNTDJM/f/fJ8nYKKv48JLDGwysDu3@/98UAA) **Explanation:** ``` L # List of range [1,input] # i.e. 5 → [1,2,3,4,5] b # Convert each to a binary string # i.e. [1,2,3,4,5] → ['1','10','11','100','101'] 32j # Join everything together with a minimum length per item of 32, # which basically prepends spaces to make it length 32 # i.e. ['1','10','11','100','101'] → ' 1 10 11 100 101' sä # Split it into the input amount of parts # i.e. 5 → [' 1',' 10',' 11',' 100',' 101'] ð0: # Replace every space with a 0 # i.e. ' 101' → '00000000000000000000000000000101' » # Join everything together by newlines (and output implicitly) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` õȤùTH ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9cik%2bVRI&input=NQ) ``` õȤùTH :Implicit input of integer õ :Range [1,input] È :Map each X ¤ : To binary string ù : Left pad T : with 0 H : to length 32 :Implicit output joined with newlines ``` ## With bonuses, 8.96 bytes ``` õȤùTH ò4 pX ¸ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9cik%2bVRIIPI0IHBYILg&input=NQ) ``` õȤùTH :As above ò4 :Partitions of length 4 pX :Push X ¸ :Join with spaces ``` [Answer] # JavaScript, 50 bytes ``` f=n=>n&&print(n.toString(2).padStart(32,0,f(n-1))) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P802z9YuT02toCgzr0QjT68kP7gEyEzXMNLUK0hMCS5JLCrRMDbSMdBJ08jTNdTU1PyfpmGq@R8A) ## With first bonus, 41.6 bytes ``` f=n=>n&&print(n.toString(2).padStart(32,0,f(n-1)),n) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P802z9YuT02toCgzr0QjT68kP7gEyEzXMNLUK0hMCS5JLCrRMDbSMdBJ08jTNdTU1MnT/J@mYar5HwA) ## With both bonuses, 44.8 bytes ``` f=n=>n&&print(...n.toString(2).padStart(32,0,f(n-1)).match(/.{4}/g),n) ``` [Try it online!](https://tio.run/##DcfLCYAwDADQbSSBGv/gRZfoBKHSqmAsNXgRZ6@@29v55sulLWp5jzn7SaZZiiKmTRSISEhPq/8CtEiRF6ucFLrW1MaDlA0iHaxuhYqe/q0CGsHsYcD8AQ) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, ~~7~~ ~~6~~ 5 bytes ``` vΠ₆↳› ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwids6g4oKG4oaz4oC6IiwiIiwiMjAiXQ==) The benefits of having built-ins to pad things with spaces and to convert spaces to 0s. Uses 64 bit integers. ~~two can play at the flag game Japt.~~ ## Explained ``` vΠ₆↳› vΠ # Convert each number in the range [1, input] to binary ₆↳ # left pad each binary string with spaces so that it's length 32 › # replace spaces with 0s # join on newlines because of `-j` flag ``` ]
[Question] [ # TASK print integers n, where `12 <= n <= 123456789`, and all pairs of consecutive digits in n have the same positive difference between them (e.g. 2468 but not 2469). # NO INPUT. # Output: ``` 12 13 14 15 16 17 18 19 23 24 25 26 27 28 29 34 35 36 37 38 39 45 46 47 48 49 56 57 58 59 67 68 69 78 79 89 123 135 147 159 234 246 258 345 357 369 456 468 567 579 678 789 1234 1357 2345 2468 3456 3579 4567 5678 6789 12345 13579 23456 34567 45678 56789 123456 234567 345678 456789 1234567 2345678 3456789 12345678 23456789 123456789 ``` # Rules 1. Standard loopholes apply. 2. no input *shortest code wins.* ***Credits*** [anarchy golf](http://golf.shinh.org/p.rb?hopping%20number%20fixed) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes ``` 9œcḊẎIE$ÐfY ``` [Try it online!](https://tio.run/##y0rNyan8/9/y6OTkhzu6Hu7q83RVOTwhLfL/fwA "Jelly – Try It Online") ### How it works ``` 9œcḊẎIE$ÐfY Main link. No arguments. 9 Set the argument and return value to 9. Ḋ Dequeue; yield [2, ..., 9]. œc Take all k-combinations of [1, ..., 9], for each k in [2, ..., 9]. Ẏ Concatenate the arrays of k-combinations. Ðf Filter the result by the link to the left. IE$ Compute the increments (I) of the combination / digit list and tests if all are equal (E). Y Join the results, separating by linefeeds. ``` [Answer] # [Python 2](https://docs.python.org/2/), 81 bytes ``` k=71 exec"k+=1;r=range(k/8%9+1,10,k%8+1)\nif r[k/72:]:print`r`[1:k/24+2:3]\n"*576 ``` [Try it online!](https://tio.run/##BcHbCkBAEADQd18hpbBqzbosq/0SFGldmhqaPPD165z7e46LlPdoNQTudWuEwkLPlhfaXYKyjTsBORQ5xq2AdKRzC3lAqZWZzM0nPTPPAxiUqhLKlNNIUVbrxvsf "Python 2 – Try It Online") [My solution](http://golf.shinh.org/reveal.rb?hopping%20number%20fixed/xnor_1500168464&py) from anarchy golf. The idea is to iterate over all possible triples of length, start value, and step, which gives sorted outputs. The triple is encoded as a value `r` from `72` to `647`, and the components are extracted as `k/72`, `k/8%9`, and `k%8`. Starting `k` high enough avoids single-digit numbers from being output. xsot [saved two bytes](http://golf.shinh.org/reveal.rb?hopping%20number%20fixed/xsot%20%28xnor%29_1500216149&py) off this by replacing the `range` with a hardcoded string of digits `'123456789'`. This was written under the constraint of a two second runtime limit. A slower strategy that filters numbers rather than generating these may be shorter. [Answer] # C, ~~166~~ 152 Bytes ``` p,l,d,i=11;main(){for(char s[10];i<=1e9;){sprintf(s,"%d",++i);p=0;for(l=strlen(s);--l>0;){d=s[l]-s[l-1];if(!p)p=d;if(p^d|d<1)break;p=d;}if(!l)puts(s);}} ``` 6 bytes saved thanks to @KevinCruijssen! 8 bytes saved thanks to @JonathanFrech! [Try it online](https://onlinegdb.com/BJAGZXHTZ) The fully formatted version of the above code can be seen below. ``` #include <string.h> #include <stdio.h> int main( void ) { int prev_diff, diff, len; int num = 11; char str[10]; while(num<123456789) { prev_diff = 0; sprintf(str,"%d",++num); len = strlen(str)-1; for( ; len > 0; len-- ) { diff = str[len] - str[len-1]; if( prev_diff == 0 ) { prev_diff = diff; } if( prev_diff != diff || diff < 1 ) { break; } prev_diff = diff; } if ( len == 0 ) { puts(str); } } } ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~, 13 bytes ``` DIµEȧ>0Ȧ Ç77# ``` [Try it online!](https://tio.run/##y0rNyan8/9/F89BW1xPL7QxOLOM63G5urvz/PwA "Jelly – Try It Online") One byte saved thanks to @MrXcoder! This is extremely inefficient, so it'll time out on TIO, but if it ever finishes, it will produce the correct output. You can try it with smaller numbers here: [Try it online!](https://tio.run/##y0rNyan8/9/F89BW1xPL7QxOLOM63G5moPz/PwA "Jelly – Try It Online") Explanation: ``` # Helper link: # D # The Digits of 'n' I # The increments (deltas, differences) between digits µ # Give that array as an argument to the rest of this link: E # Are all elements equal? ȧ # AND >0 # Are all elements greater then 0? Ȧ # And is there at least one element? # (in the differences, so that numbers < 10 are false) # # Main link: # 77# # Return the first 77 'n's for which Ç # The helper link is truthy ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes ``` •7=›ζ•FNS¥DËs0›PN11›&&– ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcMic9tHDbvObQOy3PyCDy11OdxdbAAUCfAzNARSamqPGib//w8A "05AB1E – Try It Online") --- Replace `•7=›ζ•` with 7000 to have it finish on TIO, or just hit the "terminate" button before it times out, resulting in the numbers printed up until that point. [Answer] # Mathematica, 79 bytes ``` Select[Range@123456789,Min[s=Union@Differences@IntegerDigits@#]>0&&Tr[1^s]==1&] ``` [Try it online!](https://tio.run/##BcHBCgIhEAbgVxECTx2ytm7GHPbSIYitTmIg8msDuxPovL9935b0iy0p5zSK8WY8sSJrWJJUkDuepvNlf2cJ3b@Ff0Izl4IGyeh0E0VFm7mydtrF68HaVwvu06P3zsbxaCxqqIw/ "Wolfram Language (Mathematica) – Try It Online") with a lower number because it is very slow here is another approach that constructs all the numbers in 1sec # Mathematica, 123 bytes ``` Union[FromDigits/@(F=Flatten)[Table[Partition[#,i,1],{i,2,9}]&/@Select[F[Table[Range[j,9,k],{j,9},{k,9}],1],Tr[1^#]>1&],2]] ``` [Try it online!](https://tio.run/##LcuxCoMwEIDhVxEEaeFA4uZgyVAyS2unkMJVor2aREhvE589NdDpX77fI7@tR6YR01R0RXoEWoNWcfVXmom/tTypTjlktuGsB3w5q3uMTJxdCQTCwEbQQLubqpZ36@zIWv3pDcNs9QdaWA52dIdtyTRvQ9TiWZqLqAw0xqQ@UuBCTukH "Wolfram Language (Mathematica) – Try It Online") all numbers in a sec [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 13 bytes ``` ÖifȯεuẊ≠Ṗ…"19 ``` Prints newline-separated numbers to STDOUT. [Try it online!](https://tio.run/##ASAA3/9odXNr///DlmlmyK/OtXXhuoriiaDhuZbigKYiMTn//w "Husk – Try It Online") -1 byte due to inspiration from H.PWiz. ## Explanation ``` ÖifȯεuẊ≠Ṗ…"19 …"19 The string "19" rangified: "123456789" Ṗ Powerset: ["","1","2","12","3",...,"123456789"] fȯ Filter by function: (input is sublist, say "2469") Ẋ≠ Consecutive codepoint differences: [2,2,3] u Remove duplicates: [2,3] ε Is it a one-element list? No, so "2469" is dropped. Öi Sort the result by integer value, implicitly print separated by newlines. ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 76 bytes ``` Differences@IntegerDigits@#~MatchQ~{a_?Positive..}&&Print@#&~Array~123456789 ``` [Try it online!](https://tio.run/##BcE7CoAwDADQwwgdBf86WaGLg6AnkFCiZrBCGgQRe/X63gly4AlCFmI0tG3I6Cx6PTrBHdnQTuJ1EiYQeyzhhbWfL09CN6bpp9TM5EQnKgzM8IQsL8qqbtouxh8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~37~~ 28 bytes ``` ⍪x/⍨{1=≢∪2-/⍎¨⍕⍵}¨x←11+⍳1E9 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4AkkNm7qkL/Ue@KakPbR52LHnWsMtIFcvsOrXjUO/VR79baQysqgEoNDbUf9W42dDUBAA) (with shorter range, due to time-out) **How?** `x←11+⍳123456789` - `11, 12... 1e9` into `x` `¨` - for each     `⍎¨⍕⍵` - break into digits     `2-/` - get differences list     `∪` - get unique elements     `1=≢` - length == 1? `x/⍨` - use this as a mask on the range created `⍪` - and columnify [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` ÖifoEẊ≠ftṖ…"19 ``` [Try it online!](https://tio.run/##AR8A4P9odXNr///Dlmlmb0XhuoriiaBmdOG5luKApiIxOf// "Husk – Try It Online") [Answer] # Batch, ~~210~~ 200 bytes No optimizations, so very slow - takes about 25 seconds until 12345, so for the complete output you'd have to wait about 3 days. ``` @set z=@set/a %z%c=12 :a @echo %c% :c %z%c+=1&if %c%==123456790 exit/b %z%n=c %z%d=n%%10-n/10%%10 @if %d% leq 0 goto c :d %z%n=n/10 @if %n% leq 9 goto a %z%e=n%%10-n/10%%10 @if %e%==%d% goto d @goto c ``` [Answer] # Java 8, ~~169~~ ~~168~~ 145 bytes ``` v->{byte[]a;for(int i=9,d,l;++i<1e9;System.out.print(l<1?i+"\n":""))for(a=(i+"").getBytes(),d=0,l=a.length;--l>0&&d*(d^(d=a[l]-a[l-1]))<1&d>0;);} ``` Port of [*@Jacobinski* C answer](https://codegolf.stackexchange.com/a/145644/52210) (after I golfed it a bit). -23 bytes thanks to *@Nevay*. **Explanation:** [Try it here.](https://tio.run/##LY9Nb4MwDIbv@xUWB5QMguDYhTBp9/VSaRfGJDdJabo0IAhIVcVvZ2Gt5A/Zsl897wVnZF2v3UX9rtLiOMInGnd/ATDO6@GEUsN@GwHmziiQ5GtrM@Vht4QMMXr0RsIeHAhYZ1bdjzev6wb5qRtI0AEjdqlKLU8SUxZ6xw@30etr1k0@64dwQGxZvJsk@nbRWxRRuv2hIGET0azV/iPojYSmSuSpFZhZ7Vp/5ozZKo9j9UrUD1ECa9uwUFjRUFoWsapyTvmy8gdmPx1twHzS/ru5Bq/k4ANCWzeA9GHUZZK4ydqnx2X9Aw) (It's a bit too slow near the end, so doesn't print the final number on TIO. It prints the final number locally in about 20 seconds, though.) ``` v->{ // Method with empty unused parameter and no return-type byte[]a; // Byte-array for(int i=9, // Index integer, starting at 9 d, // Difference-integer l; // Length integer ++i<1e9; // Loop (1) from 10 to 1,000,000,000 (exclusive) System.out.print( // After every iteration: print: l<1? // If `l` is 0: i+"\n" // The current integer + a new-line : // Else: "")) // Nothing for(a=(i+"").getBytes(), // Convert the current item as String to a byte-array d=0, // Reset the previous integer to 0 l=a.length; // Set `l` to the length of the byte-array --l>0 // Inner loop (2) from `l-1` down to 0 (exclusive) &&d*(d^(d=a[l]-a[l-1]))<1 // As long as the previous difference is either 0 // or the current diff is not equal to the previous diff &d>0; // and the current diff is larger than 0 ); // End of inner loop (2) // End of loop (1) (implicit / single-line body) } // End of method ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` TžhŸʒS¥D0›PsË& ``` [Try it online!](https://tio.run/##AR8A4P8wNWFiMWX//1TFvmjFuMqSU8KlRDDigLpQc8OLJv// "05AB1E – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ ~~97~~ 95 bytes *-2 bytes thanks to @JonathanFrech* ``` n=11 while n<1e9: n+=1;Q=`n`[1:] if`n`<Q>1==len({int(a)-int(b)for a,b in zip(`n`,Q)}):print n ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8/W0JCrPCMzJ1Uhz8Yw1dKKSyFP29bQOtA2IS8h2tAqlkshMw3ItAm0M7S1zUnN06jOzCvRSNTUBVFJmmn5RQqJOkkKmXkKVZkFGkCVOoGatZpWBUVAeYW8//8B "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~76~~ 75 bytes ``` n=9 while n<2e8: n+=1 if`n`in`range(n%10,0,~n%100%11-11)`[-2::-3]:print n ``` Takes about 3 minutes locally. [Try it online!](https://tio.run/##K6gsycjPM/r/P8/Wkqs8IzMnVSHPxjjV3IpLIU/b1pBLITMtIS8hMy@hKDEvPVUjT9XQQMdApw5EG6gaGuoaGmomROsaWVnpGsdaFRRl5pUo5P3/DwA "Python 2 – Try It Online") (modified to print all numbers but the last) [Answer] ## JavaScript (Firefox 30-57), 105 bytes ``` document.write(`<pre>`+( _=>[for(x of s=`123456789`)for(y of s)for(z of s)if(x*z<10-y)s.replace(/./g,c=>c<y|(c-y)%z|c-y>x*z?``:c)] )().join`\n`+`</pre>`); ``` Loops over lengths from 2 to 10 (x is the index of the last character and therefore 1 less than the length), starting digits from 1 to 9 and step from 1 to 9, then filters on the end digit being less than 10 and if so generates the result by filtering out digits from the digit string. [Answer] # [Pyth](https://pyth.herokuapp.com/?code=j.f%26%21tl%7BK.%2BjZT%2aF%3ER0K66+12&debug=0), 21 bytes Port of [Dennis' clever approach](https://codegolf.stackexchange.com/a/145610/59487). ``` jjLkf!t{.+Tsm.cS9dtS9 ``` [Try it here!](https://pyth.herokuapp.com/?code=jjLkf%21t%7B.%2BTsm.cS9dtS9&debug=0) # [Pyth](https://pyth.herokuapp.com/?code=j.f%26%21tl%7BK.%2BjZT%2aF%3ER0K66+12&debug=0), 23 bytes ``` j.f&!tl{K.+jZT*F>R0K77T ``` This times out on the online interpreter, but works if given enough time and memory. [Try it online with a lower number](https://pyth.herokuapp.com/?code=j.f%26%21tl%7BK.%2BjZT%2aF%3ER0K66T&debug=0). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes ``` 1e9:"@Vdu0>TX=?@ ``` [**Try it online!**](https://tio.run/##y00syfn/3zDV2ErJISyl1MAuJMLW3uH/fwA) with `1e9` replaced by `1e3` so that it doesn't time out in the online compiler. [Answer] # JavaScript (ES6), 121 bytes Not nearly as short as [Neil's answer](https://codegolf.stackexchange.com/a/145634/58563), but I thought it was still worth posting. Works by building a powerset of `'123456789'` where all non-matching entries are truncated and prefixed with `0`, sorting the results in numerical order and keeping only the 77 relevant ones. ``` _=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77) ``` ### Demo ``` let f = _=>[...'123456789'].reduce((a,x)=>[...a,...a.map(y=>y[1]-y[0]+(y.slice(-1)-x)?'0':y+x)],['']).sort((a,b)=>a-b).slice(-77) console.log(f().join` `) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 106 bytes ``` main(i,j,k,l){for(i=1;i<9;i++)for(j=8;j;j--)for(k=0;k<j/i;puts(""))for(l=0*k++;l<=i;)putchar(57-j+k*l++);} ``` [Try it online!](https://tio.run/##HYzBDoIwEAX/hVPLtgEOBs3rfgxpIu5uUYN6Mnx7RY4zk0yOc861LpPcnQQNFor/Xh@rEx4g6QIh8n9WPkOhMR5k3MOSdoLn5/1yTeMPXbhvjQglscDvKd@m1Z3GqGRt2U/Yav0B "C (gcc) – Try It Online") The ungolfed (prettified) version: ``` int main() { int length, start_with, max_step, step, nth; for (length = 2; length <= 9; length++) { for (start_with = 1; start_with < 9; start_with++) { max_step = (9 - start_with) / (length - 1); for (step = 1; step <= max_step; step++) { for (nth = 0; nth < length; nth++) { putchar('0' + start_with + step * nth); } puts(""); } } } return 0; } ``` [Answer] # JavaScript (ES6), ~~109~~ 104 bytes Works by generating all possible numbers: loops through each increment from 8 to 1 (variable `i`), loops through each starting digit from 8 to 1 (variable `j`), loops through each digit between `j` and `10-i` (variable `k`) and generates a string `t` by appending `k` to the current `t`. At each step `t` is added to the output array. ``` (o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)} ``` [Try it online!](https://tio.run/##NYxBDoIwEEX3nsKwmklpo0uC40WMi4IFCk2HtEUXDWevJMbdfy8vf9ZvHftg1yQ9v0wZqADT41lbapDu@TNZZ0BKi3mmpv3hQlLOmBNVlVj@7na9HBWrdYsTJEGLIIv7Hkzagj@zihwSgK6741bLDvfSnnr2kZ1RjkcYAJUzfkxTfUxsyxc "JavaScript (Node.js) – Try It Online") ``` f= (o=[],i=9)=>{while(--i){j=9;while(k=--j){t=""+k;while(k<10-i)o.push(t+=k+=i)}}return o.sort((a,b)=>a-b)} ; console.log(f().join("\n")) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 71 bytes ``` Flatten@Array[If[(x=#2+#3 #)<10,FromDigits@Range[#2,x,#3],{}]&,{8,8,8}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfLSexpCQ1z8GxqCixMtozLVqjwlbZSFvZWEFZ08bQQMetKD/XJTM9s6TYISgxLz01WtlIp0JH2ThWp7o2Vk2n2kIHCGtj/wcUZeaVKDik/QcA "Wolfram Language (Mathematica) – Try It Online") Lightning fast due to constructing rather than selecting the output. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~228~~ ~~174~~ ~~170~~ 163 bytes ``` o->{int i=11,x,y,z,l;for(;i++<1e9;){char[]w=(""+i).toCharArray();for(x=w[1]-w[0],y=1,z=0;y<w.length;z+=l>0&l==x?0:1)l=w[y]-w[y++-1];if(z<1)System.out.println(i);}} ``` [Try it online!](https://tio.run/##fZBBT4MwGIbP8CuaHQwN0NCjls7ojPGg8eBx4dCxbiuWlrRlDBZ@O9YFvRjXU783T958z1exI0t1w1W1/ZxE3WjjQOUz1Doh0auwjoR/4l2rSie0Qo/ief5eo1Za2bbm5hpzpcc6w1ntW6TkpdPG/s886XYj@cdlIGHY@EmUoJTMWvDGhALnMLCOOR/@LJW/bypfuwSqrTfcvOgGUDDpdHkWygFBMU5OSZ8MiSQ7bSIi4jjH/JbAc3lgZl10NFosYgGR0ysfPBjD@ghe2BPt1rhIu3VWJD3FyUAz0ucdklzt3YEMMZXL7EZSerrP7jCUHu@/8T6OU1wQsYuGHMOP3jpeI9061Bi/k1SRgGQcJy8YzIaz01GLLai9Z@RPINR@XQAGvTOYX/DriFhZ8sZFqpUSkgsQjOE4fQE "Java (OpenJDK 8) – Try It Online") [Answer] ## JavaScript (ES6), 145 bytes A straight-forward approach with little magic. ``` Array(123456790).fill().map((x,i)=>(''+i).split('')).map((a,i,d) => {d=a[1]-a[0];d>0&a.every((n,j)=>j<1||n-a[j-1]==d)?console.log(a.join('')):0}) ``` Running the snippet will consume a lot of memory... [Answer] # PHP, ~~85~~ 84 bytes ``` for(;++$d<9||++$a<9*$d=1;sort($r))for($x=$y=$a+1;10>$y+=$d;)$r[]=$x.=$y;print_r($r); ``` [try it online](http://sandbox.onlinephpfunctions.com/code/e9f1157aaa6103265b9e504b22c39175e8645fe0). sorting cost 17 bytes. This version prints the results ordered differently: ``` while(++$d<9||++$a<9*$d=1)for($x=$y=$a+1;10>$y+=$d;)echo" ",$x.=$y; ``` ]
[Question] [ I am learning [Ruby](http://en.wikipedia.org/wiki/Ruby_%28programming_language%29) and wrote my first nontrivial code to solve this problem. The challenge is to generate the first *n* elements of the [Stöhr sequence](http://mathworld.wolfram.com/StoehrSequence.html), *S*, which is defined as follows: > > S[0] = 1 > > > S[n] is the smallest number that cannot be expressed as the sum of two distinct previous elements in the sequence. > > > Thus the sequence begins with 1, 2, 4, 7, and 10. The next element is 13, because 11 (=1+10) and 12 (=2+10) are sums of previous elements, but 13 is not. I am looking for the shortest code. My own, in Ruby, is 108 characters long, but maybe I'll wait to see what others come up with before posting it? [Answer] # APL, 7 In APL you can choose if you want to work with index 0 or index 1. You do this by setting global variable ⎕IO←0 If we choose to work in index 0 we have: ``` +\3⌊1⌈⍳ ``` Explanation: ``` ⍳ creates a sequence 0...n (0 1 2 3 4 5) 1⌈ takes whichever is bigger, number in sequence or 1 (1 1 2 3 4 5) 3⌊ takes whichever is lower, number in sequence or 3 (1 1 2 3 3 3) +\ partial sums for the sequence (1 2 4 7 10 13) ``` Try it on [tryapl.org](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20+%5C3%u230A1%u2308%u237310&run) [Answer] # Haskell - ~~11~~ 21 Lazy infinite sequence ``` 1:2:[4,7..] ``` Function that returns just supplied number of members (sigh) ``` flip take$1:2:[4,7..] ``` [Answer] # Python 2, ~~37~~ 35 bytes ``` lambda n:[1,2][:n]+range(4,n*3-4,3) ``` Making use of a pattern... [Answer] # CJam, 14 bytes ``` 1l~{_p_3e<+}*; ``` [Test it here.](http://cjam.aditsu.net/) Starts at 1. Then, *S[n] = S[n-1] + min(S[n-1], 3)*. ``` 1l~{_p_3e<+}*; 1 "Push 1."; l~ "Read and evaluate input N."; { }* "Repeat this block N times.": _p "Duplicate the last number and print it."; _3e< "Duplicate it again, and take minimum with 3."; + "Add to last number."; ; "Discard final number to prevent output."; ``` This generalises easily to *h*-Stöhr sequences if we replace *3* by *2h-1*. [Answer] Brainfuck, 13 chars ``` +.+.++.[+++.] ``` Or 30 chars if we want to limit it to n outputs: ``` ,->+.<[->+.<[->++.<[->+++.<]]] ``` [Answer] # Python, 136 bytes ``` def f(n): if n<1:return[1] x=f(n-1);y=set(x)|{a+b for a in x for b in x if a!=b};return x+[min([a for a in range(1,max(y)+2)if{a}-y])] ``` Straight from the definition. I'm not sure how much I can golf this — it's certainly a lot longer than I expected. [Answer] # J, 14 chars This just hardcodes the `[1,2, 4+3*k (k=0..n-1) ]` sequence and takes the first `N`. ``` ({.1,2,4+3*i.) 10 1 2 4 7 10 13 16 19 22 25 ``` . # J, 18 chars This one uses a linear combination of `[0,1,2,3...]`, `[1,1,0,0...]` and `[0,1,1,1...]`. Should be shorter but can't seem to golf it. ``` ((3&*+<&2-2**)@i.) 10 1 2 4 7 10 13 16 19 22 25 ``` [Answer] # [Prelude](http://esolangs.org/wiki/Prelude), ~~32~~ 20 **Edit:** ...with twice the voices now! ``` ?(1-) 4 +3 2 ^ 1 !^ ``` This assumes the [Python interpreter](https://web.archive.org/web/20060504072747/http://z3.ca/~lament/prelude.py) with `NUMERIC_OUTPUT = True`. Like the Brainfuck submission this answer assumes that input is given in the form of a code point. This is partly [to get more attention for this meta discussion](http://meta.codegolf.stackexchange.com/q/4708/8478) (and partly, because I love Prelude). So if you want to print the first 32 numbers, say, you need to put a space on STDIN. Of course, this means there's an upper limit to the valid inputs, but this answer isn't winning anyway, so I think within the limitations of Prelude this is fine. ## Explanation In Prelude, all lines are executed in parallel, which line having its own stack, initialised to an infinite amount of zeroes. There is only a single instruction pointer (pointing at columns), so if you enter a loop on one voice, all other voices will loop along with it. In the following I've transpose the code, so that I can annotate lines instead of columns: ``` ?421 Read a character into the first stack. Push 4, 2, 1 onto the other stacks, respectively. Generally, the fourth stack will hold the next number to be printed, the third stack the one after that, and the second stack the number two steps ahead. ( Start a loop if the input wasn't 0. 1+ ! Push a 1 onto the first stack. Add the top elements in the second stack. On the first iteration this will be 0 and 4, so it does nothing. On all further iterations this will increment the last number by 3. -3^^ Subtract one from the first stack. Push a 3 onto the second stack for the next iteration. Copy the last value from the second to the third, and the third to the fourth stack. ) If the top of the first stack is not 0, jump back to the column after the (. ``` [Answer] # JavaScript (ES6) 92 As a recursive function based upon the problem definition ``` S=(n,v=1,s=[],r=0)=>[for(a of s)for(b of s)r+=(a-b&&a+b==v)]|r||(s.push(v),--n)?S(n,v+1,s):s ``` Using the pattern 1,2, 1+3\*k : 58 ``` S=(n)=>(i=>{for(t=1;n>r.push(t+=i);i+=(i<3));})(0,r=[])||r ``` Side note: finding the h-Stöhr sequence (verifying the sum of up to `h` numbers instead of just 2). The `R` function tries all possibile sums of up a given number of list elements. ``` S=(n,h=2,s=[],v=1,R=(t,v,l,i=0,r=t,w)=>{ for(;r&&l&&v[i];i++) w=[...v],r=!R(t-w.splice(i,1),w,l-1) return!r; })=>R(v,s,h)||(s.push(v),--n)?S(n,h,s,v+1):s ``` **Ungolfed** roughly equivalent (and ES5 compatible) ``` function S(n, v, s) { var r=0,a,b v = v||1 s = s||[] for(a of s) for(b of s) { if (a != b && a+b == v) r++; } if (r == 0) { s.push(v); --n; } if (n != 0) return S(n,v+1,s) else return s } ``` **Test** In FireFox/FireBug console. Simple function: ``` S(20) ``` > > [1, 2, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55] > > > Advanced function: ``` S(10,5) ``` > > [1, 2, 4, 8, 16, 32, 63, 94, 125, 156] > > > [Answer] # [><> (fish)](http://esolangs.org/wiki/Fish), 72 65 49 46 chars ``` 1n1-:?!;' 'o2n1-v v1&no' ':<4&;!?:< >-:?!;&3+^ ``` Input is supplied to interpreter: ``` >fish.py stohr.fish -v 10 1 2 4 7 10 13 16 19 22 25 ``` My first ><> program, suggestions appreciated. [Answer] # ><>, 31 bytes ``` 4i1nao:?!;2nao1-:?!;$:nao3+$d0. ``` Reads in a single char, uses its code point (e.g. space = 32) and prints the numbers one on each line. [Answer] # Perl6   22 / 30 I'm going to see if Perl6 can deduce the sequence for me. To do that I used the REPL built into Perl6 ``` $ perl6 > 1,2,4,7...* Unable to deduce arithmetic or geometric sequence from 2,4,7 (or did you really mean '..'?) > 1,2,4,7,10...* 1 2 4 7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 ... ``` Hmm, I see the pattern that Perl deduced. After 4 to get the next value you just add 3. ``` 1,2,4,*+3...* ``` Which saves one character making the code to get an infinite list of the numbers in the Stöhr sequence 13 characters long. This code only does something useful in the REPL since it prints the *gist* of the result for us. To get it to print otherwise you would have to explicitly tell Perl to print the results. ``` $ perl6 -e 'say 1,2,4,*+3...*' ``` ( `* + 3` is simply a way to get a code reference which returns 3 added to it's only argument. Other ways to write it would be `{ $_ + 3 }`, or `-> $i { $i + 3 }`, or `{ $^i + 3 }` or `sub ($i){ $i + 3 }` ) --- The shortest way to create something [Callable](http://doc.perl6.org/type/Callable) to generate the first *n* elements is to get a slice of the elements. ``` {(1,2,4,*+3...*)[^$_]} # 22 ``` In void context that would generate the first `$_` values, then promptly throw them away. In anything other than void context it creates an anonymous code block ( a basic subroutine without a name ) which takes one argument. ``` # store it in a scalar variable my $sub = {(1,2,4,*+3...*)[^$_]}; say $sub.(5); # 1 2 4 7 10 # use it immediately say {(1,2,4,*+3...*)[^$_]}.(5); # 1 2 4 7 10 # pretend it always had a name my &Stöhr-first = {(1,2,4,*+3...*)[^$_]}; say Stöhr-first 5; ``` If you really think it has to have a name to qualify as a valid for this challenge you would probably do this: ``` sub s(\n){(1,2,4,*+3...*)[^n]} # 30 ``` Though since `s` is also used for the substitution operator, to call this the parens are non-optional. ( You could have given it a different name I suppose ) ``` say s(5); # 1 2 4 7 10 ``` [Answer] I see there is already a MUCH better java answer but i spent a while on this and i'm going to post it. even if it sucks. ## Java 313 char (+4 to fit it on screen) ``` import java.util.*;public class S{public static void main(String[] a){ Set<Integer> S=new HashSet<Integer>();S.add(1);int i=1,k=0; while(S.size()<=new Integer(a[0])){if(S.contains(i)){}else{k=0;for(int j:S){ for(int l:S){if(l!=j){if((j+l)==i)k=1;}}}if(k==0)S.add(i);}i++;}for(int x:S) {System.out.println(x);}}} ``` always grateful to get any tips or pointers on how to improve [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Ż«3»1Ä ``` [Try it online!](https://tio.run/##y0rNyan8///o7kOrjQ/tNjzc8v//f0MDAwA "Jelly – Try It Online") Exactly the same as the APL answer, uses the fact that the partial sums are \$1, 1, 2, 3, 3, 3, ...\$ [Alternative 6 byters](https://tio.run/##y0rNyan8///o7kOrjQ/tNjzcwmV8aPWjjesMrYHMIENroDCQcXQ3SIHRo4YZYA5QMB@o9P///4YGBgA) ## How it works ``` Ż«3»1Ä - Main link. Takes n on the left Ż - [0, 1, 2, ..., n] «3 - Min with 3; [0, 1, 2, 3, 3, 3, ...] »1 - Max with 1; [1, 1, 2, 3, 3, 3, ...] Ä - Cumulative sum ``` The alternatives all work by generating the partial sums, just in different methods [Answer] ## T-SQL 204 Assumes that the input is in a variable called @N. I can make a procedure if you want, but there really isn't a good way to get STD\_IN in T-SQL. Also, yay for moral bonus! ``` DECLARE @Q INT=0,@B INT=2 DECLARE @ TABLE(A INT)WHILE @N>0 BEGIN SET @N-=1 WHILE @B>1 BEGIN SET @Q+=1 SELECT @B=COUNT(*)FROM @ C,@ B WHERE C.A+B.A=@Q END INSERT INTO @ VALUES(@Q)SET @B=2 END SELECT*FROM @ ``` [Answer] # Mathematica, 27 bytes Hmmm, still no Mathematica answer? Here are two: ``` NestList[#+3~Min~#&,1,#-1]& Array[i=1/2;i+=3~Min~i&,#]& ``` both define an unnamed pure function which receives an integer and returns a list of integers. This is based on the same recurrence relation as my CJam submission. Note that the `Array`-based code starts from `1/2`, because the recurrence relation is always applied before the value is returned. [Answer] ## Java, 46 ``` n->IntStream.iterate(2,x->x==2?1:x+3).limit(n) ``` [Answer] # Python - not even close (139) Acting under the assumption that this weren't easily calculable as others have done, the shortest solution I've found is below: ``` from itertools import combinations as C x,i,n=[],1,input() while len(x)<=n: if i not in [sum(y) for y in C(x,2)]:x.append(i) i+=1 print n ``` [Answer] # Clojure - 130118 ``` (defn s[n](last(take n(iterate #(if(<(count %)3)(conj %(+ (apply + %)1))(conj %(+(last %)(second %)(first %))))[1])))) ``` Un-golfed version: ``` (defn stohr [n] (last (take n (iterate #(if (< (count %) 3) (conj % (+ (apply + %) 1)) (conj % (+ (last %) (second %) (first %)))) [1])))) ``` Share and enjoy. [Answer] # Ruby - ~~108~~ 88 ``` q=->n{*k=1;(m=k[-1];k<<([*m+1..2*m]-k.combination(2).map{|i,j|i+j})[0])while k.size<n;k} ``` This uses the definition of the sequence. More readable version: ``` q=->n{ *k=1 ( m = k[-1] k << ([*m+1..2*m] - k.combination(2).map{|i,j|i+j})[0] ) while k.size < n k } ``` > > print q[10] > > > [1, 2, 4, 7, 10, 13, 16, 19, 22, 25] > > > [Answer] ## STATA 51 ``` di 1 2 _r(a) loc b=3*$a-2 forv x=4(3)`b'{ di `x' } ``` [Answer] # TI-BASIC, 41 27 30 bytes *For your calculator* ``` Input N:For(I,1,N:I:If I>2:(I-2)3+1:Disp Ans:End ``` [Answer] # [GML](http://en.wikipedia.org/wiki/GameMaker:_Studio#Scripting), 67 bytes ``` n=argument0;for(i=1;i<=n;i++){t=i;if i>2t=(i-2)*3+1show_message(t)} ``` ]
[Question] [ ### [SE will be down/read only ~~today~~ 2017-05-04 at 00:00 UTC until 00:20 UTC.](https://meta.stackexchange.com/q/295285/338745) Your challenge is to output a truthy value if SE is down/read only and a falsy value if SE is not. You may not have any input, and you must use date builtins to determine if SE is down/read only (no actually querying the SE api!) Example output: ``` 12:34 UTC 03 May 2017 -> false 00:00 UTC 04 May 2017 -> true 00:20 UTC 20 May 2017 -> undefined, see below ``` That's undefined behavior, because it's too far after the window of time. To be clear, you can assume your program will be run from UTC `8:00` today (5/3/17) to UTC `1:00` tomorrow (5/4/17). ``` 00:21 UTC 04 May 2017 -> false 00:20 UTC 04 May 2017 -> true 00:10 UTC 04 May 2017 -> true ``` Note that any truthy or falsy values are allowed, not just `true` and `false`. You must be accurate to the nearest second, and no changing the system clock! You may assume that your program is being run on a machine on the `+0 UTC` time zone. [Answer] # JavaScript (ES6), ~~26~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes Saved 3 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) and 1 byte thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke). ``` _=>new Date/12e5%72<1 ``` Checks if time passed in current day is less than 1200000ms (1200s or 20min). Assumes downtime to be 20 minutes not 21, which appears to be the case in the linked post. `00:20UTC` is the exclusive upper bound. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~32~~ ~~26~~ ~~11~~ ~~9~~ 8 bytes ``` žažb«21‹ ``` Explanation: ``` ža Is the current hour & žb current minute « concatenated ‹ less than 21 twenty one? ``` [Try it online!](https://tio.run/nexus/05ab1e#@390X@LRfUmHVhsZPmrY@f//17x83eTE5IxUAA "05AB1E – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), ~~41~~ 39 bytes Saved 2 bytes thanks to [Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) ``` import time print time.time()/1200%72<1 ``` [Try it online!](https://tio.run/nexus/python2#@19QlJlXohAfn5lbkF9UEh@voVSSmZuqpKkHojQ09Q2NDAxUzY1sDP//BwA "Python 2 – TIO Nexus") Uses the same algorithm as my JS and Charcoal answers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` 6ŒT|0Ḍ<21 ``` Requires `TZ` to be set to `UTC`, which is the case for TIO. [Try it online!](https://tio.run/nexus/jelly#@292dFJIjcHDHT02Rob//3/Ny9dNTkzOSAUA "Jelly – TIO Nexus") ### How it works ``` 6ŒT|0Ḍ<21 Main link. No arguments. 6ŒT Get the current time as a string, in the format HH:MM. |0 Bitwise OR each character with 0. This casts the characters to int and maps the non-digit character : to 0. Ḍ Undecimal; convert from base 10 to integer. <21 Compare the result with 21, so 00:00 to 00:20 return 1, all others return 0. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~32~~ 11 bytes ``` K/12e5%72<1 ``` [Try it online!](https://tio.run/nexus/japt#@@@tb2iUaqpqbmRj@P//17x83eTE5IxUAA "Japt – TIO Nexus") [Answer] # JS (ES6), ~~52~~ ~~50~~ 49 bytes ``` y=>(x=new Date).getUTCMinutes()<21&&!x.getUTCHours() ``` Why is `Date` so long? Just gets the minutes past `00:00` and returns `true` if they are < 21, and `false` otherwise. [Answer] ## zsh, 38 37 bytes: ``` date +%H\ %M|read h m;((h==0&&m<21)) ``` [Answer] ## bash, 40 bytes: ``` read h m< <(date +%H\ %M);((h==0&&m<21)) ``` [Answer] # APL (Dyalog), 14 bytes ``` ∧/1 20>2↑3↓⎕TS ``` `∧/` is it all-true (AND reduction) that `1 20>` these numbers are greater than `2↑` the first two elements of `3↓⎕TS` the current **T**ime **S**tamp with three elements dropped [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes ``` ‹﹪÷UPtime.time⟦⟧¹²⁰⁰¦⁷²¦¹ ``` Prints `-` for truthy, nothing for falsy. ## Explanation ``` UPtime.time⟦⟧ Python function time.time() ÷ ¹²⁰⁰ Divided by 1200 ﹪ ¦⁷² Modulo 72 ‹ ¦¹ Less than 1 ``` [Try it online!](https://tio.run/nexus/charcoal#@/@oYef7nasOb3@/Z@v7PRtKMnNT9UDEo/nLHs1ffmjnoU2PGjcA0aFljxq3H9p0aNmhnf//AwA "Charcoal – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), 17 bytes ``` /o \T@/4&;'-.C+n ``` [Try it online!](https://tio.run/nexus/alice#@6@fzxUT4qBvomatLqqr56yd9/8/AA "Alice – TIO Nexus") Assumes to be run on a machine whose timezone is set to UTC (like the TIO server). ### Explanation While in Ordinal mode, the IP bounces diagonally up and down through the program. While in Cardinal mode, the IP wraps around the edges like most other Fungeoids. ``` / Reflect to SE. Switch to Ordinal. T Push a string representing the current date and time, in the format: YYYY-MM-DDTHH:MM:SS.mmm±AA:BB / Reflect to E. Switch to Cardinal. 4& Run the next command 4 times. ; Discard four elements from the top of the stack. Since we're in Cardinal mode, this attempts to discard four integers. But the top stack value is a string so it gets implicitly converted to all the integers contained in the string. So year, month, day, hour, minute, seconds, milliseconds, timezone hour, timezone minute will be pushed separately. Then the last four of these will be discarded, so that we end up with the minute and the hour on top of the stack. ' Push 21. - Subtract it from the minutes. Gives something negative for minutes 0 to 20. .C Compute the binomial coefficient n-choose-n. This gives 0 for negative results and 1 for non-negative ones. SE is down if both this value and the current hour are zero. + Add the two values. Iff they are both zero, we still get a zero. n Logical NOT of the value. Turns 0 into 1 and everything else into 0. \ Reflect to NE. Switch to Ordinal. o Implicitly convert the result to a string and print it. @ Terminate the program. ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes *Thanks to Dennis for several corrections* ``` Z'1\480*7< ``` [Try it online!](https://tio.run/nexus/matl#@x@lbhhjYmGgZW7z/z8A "MATL – TIO Nexus") ### Explanation ``` Z' % Push current date and time as a float. Integer part is day, decimal part is time 1\ % Modulo 1. This gives the time, in units of one day 480* % Multiply by 480 7< % Less than 7? Note that 21 minutes / one day equals 7 / 480. Implicitly display. ``` [Answer] # Python 3 (NON-REPL) + time, ~~81~~ 77 bytes -4 bytes thanks to Bahrom ``` import time;e=str(time.strftime('%H:%M'));print(e[:2]=='00'and int(e[3:])<21) ``` A naïve approach, turning the current date to string and analysing its characters. [Answer] # Pyth, 11 bytes ``` &g20.d7!.d6 ``` [Online interpreter link](http://pyth.herokuapp.com/?code=%26g20.d7%21.d6&debug=0) [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~55~~ ~~53~~ ~~51~~ 50 bytes *-1 byte from @robbie0630's comment.* ``` a=`date +%s`;echo $[1493856000<a&a<1493857200?1:0] ``` [Try it online!](https://tio.run/nexus/bash#@59om5CSWJKqoK1anGCdmpyRr6ASbWhiaWxhamZgYGCTqJZoA@GaGxkY2BtaGcT@/w8A "Bash – TIO Nexus") The advantage of this solution is that it works for any date (so will return `1` only for the period defined in the challenge, as it uses epoch time). [Answer] # Swift + Foundation, 178 bytes ``` import Foundation;var d=String(describing:Date());func g(_ s:Int)->String{return String(d[d.index(d.startIndex,offsetBy:s)])};print(g(11)+g(12)=="00" ?Int(g(14)+g(15))!<21:false) ``` Quite short by swift standards. **[Check it out!](http://swift.sandbox.bluemix.net/#/repl/5909c110ef829376a284faab)** As in my Python answer, I basically converted the current `Date` to a string and have analysed its digits, depending on which I printed the bool. [Answer] ## R, 65 bytes ``` library(lubridate) x=Sys.time() print(all(!hour(x)&minute(x)<21)) ``` Checks if the hour == 0 and the minute < 21. [Answer] # PostgreSQL, 43 characters ``` select now()between'170503'and'170503 0:20' ``` Just because I prefer SQL for date/time calculations. Sample run: ``` bash-4.3$ psql -c "select now()between'170503'and'170503 0:20'" ?column? ---------- f (1 row) ``` ]
[Question] [ In the shortest amount of code in any programming language, filter out the duplicate items in an array of which the order is irrelevant. Here are some test cases: ``` [1, 2, 2, 3, 1, 2, 4] => [1, 2, 3, 4] ['a', 'a', 'b', 'a', 'c', 'a', 'd'] => ['a', 'b', 'c', 'd'] ``` > > I also should note that there currently aren't any open questions that meet these exact criteria. > > > [Answer] # 1-byte built-ins ### [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) ``` Ù ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8Mz//6PVE9V1FCBEEpyVDGelqMcCAA "05AB1E (legacy) – Try It Online") Alternatively: ``` ê ``` [Try it online!](https://tio.run/##MzBNTDJM/f//8Kr//6PVE9V1FCBEEpyVDGelqMcCAA "05AB1E (legacy) – Try It Online") ### [APL (Dyalog Unicode)](https://www.dyalog.com/) ``` ∪ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HHqv9pj9omPOrte9TV/Kh3zaPeLYfWGz9qm/iob2pwkDOQDPHwDP6fpmCoY6hjrGMChMY6RjpmOkYA "APL (Dyalog Unicode) – Try It Online") ### [Jelly](https://github.com/DennisMitchell/jelly) ``` Q ``` [Try it online!](https://tio.run/##y0rNyan8/z/wv/f//9Hqieo6ChAiCc5KhrNS1GMB "Jelly – Try It Online") # [W](https://github.com/A-ee/w) ``` U ``` # [Stax](https://github.com/tomtheisen/stax/) ``` u ``` # [MATL](https://github.com/lmendo/MATL) ``` u ``` [Try it online!](https://tio.run/##y00syfn/v/T//2hDHQUjMDLWUYCwTWIB) # [MathGolf](https://github.com/maxbergmark/mathgolf/) ``` ▀ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RtIb//6MNFYyA0FgBRJvEAgA) # [Seriously/Actually](https://github.com/mego/seriously) ``` ╔ ``` # [Japt](https://github.com/ETHproductions/japt/) ``` â ``` [Try it online!](https://tio.run/##y0osKPn///Ci//@jDRWMgNBYAUSbxAIA) # [Pyth](https://github.com/isaacg1/pyth) ``` { ``` [Try it online!](https://tio.run/##K6gsyfj/v/r/f0MdQx1jHRMgNNYx0jHTMQIA "Pyth – Try It Online") # [Husk](https://github.com/barbuz/Husk) ``` u ``` [Try it online!](https://tio.run/##yygtzv7/v/T////RhjpGQGisA6JNYgE "Husk – Try It Online") # [Pyke](https://github.com/muddyfish/PYKE) ``` } ``` [Try it online!](https://tio.run/##K6jMTv3/v/b//2hDHQUjMDLWUYCwTWIB "Pyke – Try It Online") # [Canvas](https://github.com/dzaima/Canvas) ``` D ``` [Try it online!](https://tio.run/##S07MK0ss/v///Z4l//9HG@ooGIGRsY4ChG0SCwA "Canvas – Try It Online") # [Vyxal](https://github.com/Vyxal/Vyxal) ``` U ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJVIiwiIiwiWzEsIDIsIDIsIDMsIDEsIDIsIDRdIl0=) [Answer] # [Python 3](https://docs.python.org/3/), ~~15~~ 3 bytes Reduced to 3 bytes thanks to [a'\_'](https://codegolf.stackexchange.com/users/92069/a)!!! ``` set ``` [Try it online!](https://tio.run/##TU5LCoMwEN3nFLNLAtlohIKQLnuC7tSF1UgFUcmMiyI5exo/lcIwvM885s0fek@jDp0pA1oKZJEQDAgmikRBuo9WcOCsUqeqNyJVvOI1V3Cs14WaC7U8Zv7s5hRjVjIXP61Pt9h84eWS3hId3Uc94E/IGu5ZNzkgZaEfYa@XM9gq4uTItmLokUQnSErJYHb9GBlfyYO5w4oeVldYY7DyXLLwBQ "Python 3 – Try It Online") # Without set # [Python 3](https://docs.python.org/3/), ~~35~~ \$\cdots\$~~30~~ 29 bytes Saved 3 bytes thanks to [a'\_'](https://codegolf.stackexchange.com/users/92069/a)!!! Saved a byte thanks to [Jitse](https://codegolf.stackexchange.com/users/87681/jitse)!!! Saved a byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!!! ``` lambda l:list(dict(zip(l,l))) ``` [Try it online!](https://tio.run/##TU/LCoMwELznK/aWBHKpCgUhPfYLelMPUSMNpCrJemjFb0/jo1JYlpnZHXZ2fONz6NPQyTJY9apbBTa3xiNrTYPsY0ZmheWcB9QePUhghBUXAclWqYAdZ5U41HQlXMQtqqiAvdUnak7U0uj5GzeHGL2cuHhpfrhJ5xMtp@R6SeP0rqz/CVlDF9INDlBoMD1s8XICa0Q/ONQt297oGMb0BEZn@sjojAvIG8x@gdkVWkpfLZSHLw "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 3 bytes ``` set ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzvzi15H@Ogq1CtKGOoY6xjikYm@hYxHIVFGXmlWikaeRoav4HAA "Python 3 – Try It Online") It [also works on Python 2](https://tio.run/##K6gsycjPM/qfZhvzvzi15H@Ogq1CtKGOoY6xjikYm@hYxHIVFGXmlWikaeRoav4HAA) Or without `set`: ## [Python 3](https://docs.python.org/3/), ~~34~~ ~~29~~ 26 bytes ``` lambda l:[*dict(zip(l,l))] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHHKlorJTO5RKMqs0AjRydHUzP2f46CrUK0oY6hjrGOKRib6FjEchUUZeaVaKRpAJX8BwA "Python 3 – Try It Online") Thanks to Jonathan Alan and Surculose Sputum for helping me golf this one! [Answer] # Java 8, ~~27~~ 15 bytes ``` S->S.distinct() ``` Stream I/O. [Try it online.](https://tio.run/##dVDLasMwELznK5ZcLBFnoY9TQwOh1zY9@Fh6WMtqkStLwVoHQsm3u@sHpWCKkIZlZndGW9OZtnX11RtPKcELufC9AnCBbftBxsJxKAFq0WHHzmPi1lKDxQhg1H9MoXfSeV3Jk5jYGThCgMe@2O4LrFxiFwwr3e8GxakrvShm4Tm6ChqJomSWC59v70B6ysE2sbrJb@Xc5QPejzYzkVGWj7ec0cxYZYs0o8nY9VrW1jAi/roUl8S2wdgxniQA@/Dnm4e2pUtCjlM4RXqzfoD1JqBZqqadiEajid6Lz3JhTxMR22Hos2xGaT3HvfY/) **~~27~~ 22 bytes:** ``` java.util.HashSet::new ``` -5 bytes thanks to *@OlivierGrégoire*. List input, Set output. [Try it online.](https://tio.run/##ZY9NT8MwDIbv@xXWLk21EomPU6cdEBcOYxx6RBzcNEBKl021OzSh/fbihLChTVFi2X6c93WLO7xqm8/RdEgET@j89wTAebb9GxoLq5ACtMLpgV2nK8tg1ClfOmJY5nPBDhN5iJGdgRV4WIwn7BHpQ0bL0tuvcR7A7VB3AiZ@t3ENrEVeVdw7//7yCpj/arMlVtfFjZzbIsS7qJYaGWZFvHWKJsUmuzAVReLUc91aw1rro8rZRoF6QLKwAHH8r3vf97gPiDqrkUaKdcyTv2pPbNd6M7Deyk7cefX37WxawnTmtTlW8uT2MP4A) [Answer] # [Ruby](https://www.ruby-lang.org/), 8 bytes ``` ->a{a&a} ``` or ``` ->a{a|a} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cusTpRLbH2f0lqcUmxgq1CNJeCQrShjoIRGBnrKEDYJrE6IAn1RHUdBQiRBGclw1kp6rFcsVxgo/RSE5MzFKoVahJrFAoU0vSSE3NyNBI1FWq5/gMA "Ruby – Try It Online") Set intersection (`&`) or set union (`|`), both of which remove duplicates. Shorter than the built-in `uniq` method. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 6 bytes ``` D` G`. ``` [Try it online!](https://tio.run/##K0otycxL/P/fJYHLPUHv//9ErkSuJCBOBuIUAA "Retina 0.8.2 – Try It Online") Doesn't work on empty strings. Explanation: ``` D` ``` Replace all duplicates with empty strings. ``` G`. ``` Remove all empty strings. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 13 bytes ``` a=>new Set(a) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i4vtVwhOLVEI1Hzf3J@XnF@TqpeTn66RppGtKGOERAag6EJFJrCIUwEIg9SaRirqWn9HwA "JavaScript (Node.js) – Try It Online") Unfortunately `Set` must be used with `new`, otherwise the answer will be just 3 bytes: `Set`, as a function. [Answer] # Batch, 182 Bytes ``` @Echo Off&Setlocal EnableDelayedExpansion For %%A In (%~1)do ( Set M=F IF "!O!"=="" (Set O=%%A) Else ( For %%B in (!O!)do If %%A==%%B Set M=T IF !M!==F Set O=!O!,%%A)) ECHO(!O! ``` [![TIO not available.](https://i.stack.imgur.com/Q26eE.png)](https://i.stack.imgur.com/Q26eE.png) Builds a string starting with first element of the original string, compares each element of the new string against the next element of the original string, assigning and testing a troothy value before appending the next element to the new string. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 5 bytes ``` Union ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PzQvMz/vf0BRZl6JgkN6dLWhjoIRGBnrKEDYJrWxXAh5pUQlHTBOgtLJUDpFqTb2/38A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Io](http://iolanguage.org/), 18 bytes Io doesn't allow assigning functions. It's terrible! ``` method(x,x unique) ``` [Try it online!](https://tio.run/##y8z/X6FgZasQ8z83tSQjP0WjQqdCoTQvs7A0VfN/hUZOZnGJhqGOkY6xjqGmpkJBUWZeSU7efwA "Io – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes ``` W⁻θυ⊞υ⊟ιυ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDNzOvtFijUEehVFNTIaC0OEOjVEchIL9AI1NT05oroCgzr0SjVNP6///oaPVEdR0FCJEEZyXDWSnqsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Works best on strings due to the way Charcoal prints numbers by default. Explanation: ``` W⁻θυ ``` Remove all occurrences of elements in the result from the input. While this temporary value is not empty... ``` ⊞υ⊟ι ``` ... push the last element of that value to the result. ``` υ ``` Print the result. [Answer] # [Haskell](https://www.haskell.org/), 29 bytes ``` f(a:b)=a:f[x|x<-b,x/=a] f x=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SpJ0zbRKi26oqbCRjdJp0LfNjGWK02hwrbif25iZp5tQVFmXolKWrShjpGOMRib6JjE/gcA "Haskell – Try It Online") This answer gives us the list with the first occurrence of every element. # [Haskell](https://www.haskell.org/), 33 bytes ``` f(a:b)=[a|notElem a b]++f b f x=x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SpJ0zY6sSYvv8Q1JzVXIVEhKVZbO00hiStNocK24n9uYmaebUFRZl6JSlq0oY6RjjEYm@iYxP4HAA "Haskell – Try It Online") This answer gives us the last occurrence of every element. [Answer] # [Erlang (escript)](http://erlang.org/doc/man/escript.html), 41 bytes Great thanks for the Haskell answer! (so that I can port it) ``` u([H|T])->[H]++u([X||X<-T,X/=H]);u(I)->I. ``` [Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/W/VCPaoyYkVlPXLtojVlsbyI2oqYmw0Q3RidC39YjVtC7V8ARKeur9z03MzNOIBqnMzLcqL8osSdUAqjbUMdIx1DHWMYzV1NT7DwA "Erlang (escript) – Try It Online") # [Erlang (escript)](http://erlang.org/doc/man/escript.html), ~~79~~ 72 bytes It's a recursive definition of uniquifying. The premise is that Erlang doesn't have a set-conversion built-in. ``` u([H|T])->case string:find(T,[H])of nomatch->[H];_->[]end++u(T);u(I)->I. ``` [Try it online!](https://tio.run/##FYw9C8MgFAD3/oqMT6IB2y2BzMnuJlLEmPRB8wx@0KX/3drpuOHOx7elQ/jkIl653moBvXyVYWJ2Nvku5Yh0jDvSBorrxbCwdxROm91LzM2nZ4PxtPV9AcWmAmtr16GeFgn0f4Rh/ETMHtpb8juX/MGlYWyoPw "Erlang (escript) – Try It Online") # Explanation ``` u([H|T])-> % Try to split the input into a head & tail. case string:find(T,[H])of % Check whether H is a substring of T. % Strings are lists in Erlang, so it % doesn't raise a type error when applied on lists. nomatch->[H]; % If false, return head. _->[]end % Else, return empty list. ++u(T); % Recurse down until ... u(I) % ... the operand is an empty list, ->I. % where the operand is returned ``` ``` [Answer] # [Sledgehammer](https://github.com/tkwa/Sledgehammer), 2 bytes ``` ⠓⣻ ``` Decompresses into this Wolfram Language function: ``` Union ``` [Answer] # perl -E, 23 bytes ``` @_{<>}=0;say for keys%_ ``` Reads an array from `STDIN`, one element per line. Writes the unique elements to `STDOUT`, elements separated by two newlines. (No TIO link, as it seems to not terminate the final line of the input with a newline, which leads to an incorrect output). [Answer] # [R](https://www.r-project.org/), 6 bytes ``` unique ``` [Try it online!](https://tio.run/##K/qfZvu/NC@zsDT1f5pGsoahjpGOsY6JjiGQNNUx0tT8/x8A "R – Try It Online") [Answer] # perl -MList::Util=uniq -E, 17 bytes ``` say for uniq@ARGV ``` Accepts an array as arguments, prints the unique elements to `STDOUT`, one element per line. [TIO](https://tio.run/##K0gtyjH9/784sVIhLb9IoTQvs9DBMcg97P///6n/k/8n/k/5nwQkk8HsJChO/JdfUJKZn1f8X9fXVM/A0ABI@2QWl1hZhZZk5tiCDAEA) [Answer] # IBM/Lotus Notes Formula, 10 bytes ``` @Unique(i) ``` Takes input from multi-value field `i`. Screenshots below. [![enter image description here](https://i.stack.imgur.com/MKJ5S.png)](https://i.stack.imgur.com/MKJ5S.png) [![enter image description here](https://i.stack.imgur.com/eVi0N.png)](https://i.stack.imgur.com/eVi0N.png) [Answer] # [Symja](https://symjaweb.appspot.com/), 16 bytes ``` DeleteDuplicates ``` [Try It Online!](https://symjaweb.appspot.com/input?i=m:=DeleteDuplicates;m(%7B1,1,1,1,2%7D)) [Answer] # [Clojure](https://clojure.org/), 3 bytes ``` set ``` [Try it online!](https://tio.run/##S87JzyotSv2vkZKappD2vzi15L8ml0ZBUWZeSU6egkaaQrShjoIRGBnrKEDYJrGaaGqUEpV0FCBEEpyVDGelKAF1/AcA "Clojure – Try It Online") Returns a set, or preserving order: # [Clojure](https://clojure.org/), 8 bytes ``` distinct ``` [Try it online!](https://tio.run/##S87JzyotSv2vkZKappD2PyWzuCQzL7nkvyaXRkFRZl5JTp6CRppCtKGOghEYGesoQNgmsZpoapQSlXQUIEQSnJUMZ6UoAXX8BwA "Clojure – Try It Online") [Answer] # MOO, 36 bytes ``` return #372:remove_duplicates(@args) ``` Extremely implementation-specific. The shortest non-implementation-specific way of doing this is `return $list_utils:remove_duplicates(@args)` (43 bytes). Unfortunately, functions aren't first-class objects in this language, so `#372:remove_duplicates` (22 bytes) is a syntax error and thus isn't valid. The shortest way of doing this without using a builtin is `x={};for y in (args[1])x=setadd(x,y);endfor return x;` (53 bytes) [Answer] # T-SQL, 24 bytes ``` SELECT DISTINCT v FROM t ``` Takes input as separate rows in a table *t* with varchar field *v*, which is permitted [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Without an `ORDER BY`, SQL returns the rows in a non-prescribed order. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), 69 bytes ``` #import<set> using s=std::set<int>;s f(int*a,int l){return s{a,a+l};} ``` This is what I like about C++: It has a lot of features. [Try it online!](https://tio.run/##hZDBTsQgEIbvfYpJTAQUo0VPbbcvsu4BabuStNAA9WDTZ69T0E01Gidk8s8w3z8BNY53Z6XW9UoPo3Wh8m2os8lrcwZ/8KEpCuxU2oS69NBRFDeSY4aeza4NkzPgZ8nlbb@UC7oY1U9NC5W2PrhWDnWWbdOD1Ia@Wd2wbM4AY2tK5/LjCQ4w5xxEPI8ckn5ayv2cSHNEEg4pvVyUuqiGIBUxZY1HcAoWrvEBOcId3fZx8Pq9talg97vi@HBirPyNFl@02NNiT4tPOuKddTTCGgrYtrPY3iL@qLJTgKrCa0wESFr67Yo8G/LTTSU38YebepWOKvaf57J@AA "C++ (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 86 bytes ``` i,j;f(a,l)int*a;{for(i=l;i--;)for(j=l;j--;)i-j?a[i]-a[j]?:bcopy(a-~i,a+i,--l-i<<2):0;} ``` Hoping to roll the two loops together. [Try it online!](https://tio.run/##nVDBboMwDL3zFRHVRDKSrc16auj6IYhDmsBmxAABnbYh9uvMIajdYadZVvycZz9bNuLFmHkGXqqCal4xqId7rcai6SgcKwVCKOaSEpPSJSDKk04hEzots9PhbJr2k2rxDVzHwIWoBCSJZIetmuYN1Ka62Jwk/WCheXh9DoKNzQuoc6KrvKYfjPTwlTcFoscVIUy3GQsCXIW8aajpewOWBWNA0Nyn7rpdmpEjGXecyMWfOPF4P6nfddLXRTrixD/nKzJXZCPsWtrwCCjO/XYOMqZuhLwR0hGecafCaYCDtgpDQvYY4pgttLO2w4KChneWhNyvD9kq3F6Gnobhf9TMqib/UpvmHw "C (gcc) – Try It Online") # [C (gcc)](https://gcc.gnu.org/), 87 bytes ``` i,j;f(a,l)int*a;{for(i=j=l;i-=j--==l;j=j?:l)i-j?a[i]-a[j]?:bcopy(a-~i,a+i,--l-i<<2):0;} ``` Turns out longer. [Try it online!](https://tio.run/##nZDBToQwEIbvPEXDxtBKqyzuiYI8COHQLaDTIBBgjUrw1XGgZNeDJydN50v/mX8m1eJF62UBbmRFFa8ZNOO9klPV9hQSk9QSRGKESJBMYtIIK4RJVQa5UJnJ0@is2@6TKvENXPnAhagFxHHIokDOywEaXV@KksTDWED78PrsOIeirKApiarLhn4wMsBX2VZIjzshZkHOHAd3IW8KGvreQsGcySEY66Pq@2OWk4RMR07C7TxxYvk0y991oa3zlMeJvc5X0lcqPOza2vAX0Jzb7VZkTN6E8CaEq2CV9a9wGuCgQGKKyQmT77NNXqPrsaCi7l1BXG7Xh3w37i7jQF33P256dwv/cpuXHw "C (gcc) – Try It Online") [Answer] ## [sh + POSIX utilities](https://tio.run/##S0oszvj/vzi/qERBt/T/f0MuIyA05gLRJlyJQJgExMlAnAIA), 7 bytes ``` sort -u ``` ## sh + POSIX utilities, 9 bytes ``` sort|uniq ``` --- ### Notes * The TIO uses `bash` because it doesn't provide plain `sh`, but it should work fine in any shell. * I was flexible with the input (one entry of the array per line, no other markers) because `sh` doesn't have arrays. If you wanted to do it with, e.g., `bash` arrays, you could do this ([TIO](https://tio.run/##S0oszvj/P9FWw1DBCAiNFUC0iUIiECYBcTIQp2hyFRRl5pWkKairFsfkqSsoqVQnRjvE1iop1CgU5xeVKOiW/v8PAA)): ``` a=(1 2 2 3 1 2 4 a a b a c a d) printf '%s\n' "${a[@]}" | sort -u ``` [Answer] # [Factor](https://factorcode.org/), 7 bytes ``` members ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpSrFBQlFpSUllQlJlXomDNxVWtYKhgBITGYNpEoZbrf25qblJqUfF/vf8A "Factor – Try It Online") ]
[Question] [ **Challenge:** Produce the following output using as few chars as possible: ``` _ _ _ _ _ _ _ | | | | ___| | | ___ __ _____ _ __| | __| | | | |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | | | _ | __/ | | (_) | \ V V / (_) | | | | (_| |_| |_| |_|\___|_|_|\___( ) \_/\_/ \___/|_| |_|\__,_(_) |/ ``` **Rules and restrictions:** * You may not use [FIGLet](http://www.figlet.org/) or any similar tools. (Otherwise, `figlet Hello, world!` would be a trivial and pretty much unbeatable solution.) * Your program must consist entirely of printable [ASCII](http://en.wikipedia.org/wiki/ASCII) characters — specifically, code points 9 (TAB), 10 (LF) and 32 – 126. (If your language / OS requires CRLF line breaks, you may use those instead of plain LFs.) Yes, this regrettably disqualifies any language that requires non-ASCII characters (or non-textual data) as part of its syntax. * The output must look exactly like the example above. You may, however, include extra whitespace around the output if you want. You may assume 8-character [tab spacing](http://en.wikipedia.org/wiki/Tab_key#Tab_characters) (or your chosen platform's native default setting, if it has a consistent one). Ps. To set the par, I came up with a 199-char Perl solution. I won't post it yet, though, in case someone comes up with it independently. (Also, it's kind of cheesy.) Of course, this shouldn't discourage you from posting your own solution, even if it's longer. --- **Update:** Now that [han has beaten it](https://codegolf.stackexchange.com/a/4378/3191) by one char, here's my cheesy 199-char Perl solution: ``` use Compress'Zlib;say uncompress unpack u,'M>-I]BT$*`S$,`^]YQ=R:0,&_Z<DP?8@?WVQJ]E2J"%E$$@)R(/(/MCJ*\U!OM`Z#=5`4Y>6M=L\L%DMP&DB0V.4GQL&OOGB$4:%`4TT4!R8O-Z(^BTZWNV?>F86K:9+""-35*-LNC:T^D:_$#%^`";"DD0' ``` It's very similar to [D C's solution](https://codegolf.stackexchange.com/a/4361/3191) (and all the other zlib/gzip-based solutions in various languages), except that I used [uuencoding](http://en.wikipedia.org/wiki/Uuencoding) instead of [base64](http://en.wikipedia.org/wiki/Base64) for the compressed text and a few other minor golfing tricks. --- **Update 2**: I think it's time to officially accept a winner. The first place goes to [konsolenfreddy](https://codegolf.stackexchange.com/users/3307/konsolenfreddy)'s PHP code, since, however you count the chars, it *is* the shortest submitted so far. In fact, combining it with the optimized DEFLATE stream from my 199-char Perl code yields an even shorter 176-char solution: ``` <?=gzinflate(base64_decode("fYtBCgMxDAPvecXcmkDBv+nJMH2IH99savZUqghZRBICciDyD7Y6ivNQbwOg3VQFOXlrXbPLBZLcBpIkNjlJ8bBr754hFGhQFNNFAcmLzeiPotOt7tn3plq2mSwgjU1SjbLo2tPpGvxAxfgA")); ``` However, I do think that [han](https://codegolf.stackexchange.com/users/3031/han) deserves a special honorary mention for getting so close without using any pre-written decompression tools. Congratulations to both of you, and a happy new year to everyone! [Answer] # Perl 5.10 - 195 198 202 203 characters Here's an entry that does not require any libraries beyond basic regexp matching. The encoded string is 131 characters, and the code to decode and print it takes up 64 characters (assuming no newline at the end of the source). The idea is to represent common 3-character strings by lower case letters. ``` s!!xfefxxf\t\t\tf efyx no| cnocfxefxceyxm|xmn nm|wtnwtgt/uvy \\| 'ym|w`o| pepyy/o| _ogrr/ _opn (ml l lbyly|by( )fiihyjm lb,y_ \t\tf |/!;s!\w!substr'(_)\___ \_/|_| | V \ / _',-95+ord$&,3!eg;say ``` The encoder is a lot longer and unfortunately not very readable right now. The basic idea is to use dynamic programming to find the shortest encoding for each line, given a fixed set of string substitutions. The string of substitutions on the last line was built by trial and error, and it is possible that another string of substitutions might lead to a shorter program than above. One trick here is that some substitutions are shorter than 3 characters long: due to the way perl `substr` works, `x` is replaced by ' `_`' and `y` by '`_`'. The latter is necessary because `\w` in the regex matches '`_`', which is then replaced by '`(_)`'. [Answer] ## Brainfuck - 862 characters: ``` >++++[<++++++++>-]>-----[<---->---]<+++>>--[<+>--]<---<<.>.<...>.<.... ..>.<.>.<.............................>.<.....>.<.>.>>++++++++++.<.<<. >>.<<.>>.<<.>>.<<.>...>.<<.>>.<<.>>.<<.>...<....>..<......>.....<..>.< .>..>.<<.>>.<<.>..>.<<.>>.<<.>>.>.<.<<.>>.<.>.<<.>>.>>>-[<->+++++]<--- -.<<<<.>.<.>---.+++<.>>.<<.>>.>>.<<<<.>.<.>---.<...>.<.>.<.>>>>.<<<.<. >>>>.<<<<.>>>>.<<<<.>+++.<.>---.>.<<.>>>>>>---[<+>+++++++]<++.<<<<+++. .>.<<.>>.>>.<<<<.>.+.-<.>>.<<.>>.>.<.<<..>.<..>>.<<..>..>>>.<<<<.>>.<< .>>.<<.>>>>>+.<<<<.>>>>+.<<<<<.>>.<<...>---.<.>------.<..>.<.>>>>.<<<< .>>>>>-.<<<<+++++++++.>>>>+.<<<<<.>>.<<.>>.<<..>>.<<.>>.<<.>>>>>-.<<<< .>.<<.>>.<.>.>.<.<.>.<<.>>.<.>.<---.+++...>.<.>.<.>.<---.+++...>>>>.<< <<<.>>>>>+.<<<<<...>---.+++.>>>.<<<---.+++.>>>.<<<<.>---.+++...>>>.<<. <.>.<<..>>.<.>.<---.+++..>>>>+++.<<<<.>>>>----.<<<<.>>>>+.<<.<<<...... ..............>>.>>.<. ``` [Answer] ## Python (2.x), 194 characters ``` print'eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc'.decode('base64').decode('zip') ``` [Answer] ## Javascript, ~~273~~ ~~265~~ 264 characters ``` " _2_22_ _2222222226_26_ _10 0 3_0 | 3_2 32233_6_ 30 30 |10_0/ _ 4 0/ _ 424 4 /4 / / _ 4| '30/ _` 01|6_6|63/ 0 (_) |24 V6V / (_) 060 (_0_|1|_0_|43_|_543_( )24_/4_/ 43_/56543,_(_)12222226|/".replace(/\d/g,function(a){return'| |,\n, ,__,\\,|_|, '.split(',')[a]}) ``` :( [Answer] This answer is longer than just printing the string; however, just for the fun of it, here it is: ## Python, 485 characters ‚ò∫ ``` import sys data= ',C6UBKq.)U^\\ 8[hHl7gfLFyX6,;p\'SlYpN@K-`Kbs#fSU+4o~^_h\\dJDy{o9p?<GnLTgG{?ZM>bJE+"[kHm7EavoGcS#AQ^\\>e_' table= " _|\\/(\n)V'`," key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2))) number= 0 for char in data: number= number*95 + ord(char) - 32 mask= 1<<655 decoder= key while mask: index= mask & number and 1 try: decoder= decoder[index] except TypeError: sys.stdout.write(table[decoder]) decoder= key[index] mask>>= 1 ``` Since I have one of the shortest ASCII representations of the compressed original text, I must have the longest scrollbar in my code! It's a win! :) [Answer] ## PHP, ~~194~~ 189 characters ``` php -r'=gzinflate(base64_decode("dU/BDcQgDPszhX+lUqVs0xeSb5AMf3ZI+7qDACa2EwABeNXR4M/goxqJPUm+oLinEishKTdbKtuMQsTCC6C1EApUInHIvOlP+9zbO6PaTZ6+ynZDEZ1INFuNRu5z+ZVsMHHax1DAibCqZRdVZ/z6esYX"));' ``` It's basically the same as the Python and Perl answer, slightly shorter [Answer] > > In other languages: [**C** (original version), 209 chars](https://codegolf.stackexchange.com/revisions/20382/1); [**Perl**, 200 chars](https://codegolf.stackexchange.com/revisions/20382/4). > > > ## J, ~~167~~ 160 chars (47 + 113) Another no-builtin-compression submission. Uses a pretty straightforward variable-length encoding, encoding each character as a series of 1 bits and separating characters by 0 bits. The compressed string is a mere 113 characters. ``` ('a _|\/',CR,'()V`,'''){~#;.2,(6$2)#:40-~3&u:'8H1(((((H:f[4ZS4ZP2(RPMAMANf[>CZD[F;I[OVFF;TgfS5aGd[7T9JW4[eG[+Of7ddg?d[.AfT]WUASE=S>bSdgI]cS[RWBYSE?gSeG_X(()WG(' ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 137 bytes ``` "9&BO]h>&)>3ieuCoKVKVnuOoT'E-^Z(1.3u[);h1[RTOGqTZkoQx?KMy&9ctG&*y~HxR9%GYn.rYMdMcOOq^wXc@%zy*P[*Q"90|E|B"0+1"{%",``_|\/()V'"@]}R.1 |t54/m ``` [Run and debug it](https://staxlang.xyz/#c=%229%26BO]h%3E%26%29%3E3ieuCoKVKVnuOoT%27E-%5EZ%281.3u[%29%3Bh1[RTOGqTZkoQx%3FKMy%269ctG%26*y%7EHxR9%25GYn.rYMdMcOOq%5EwXc%40%25zy*P[*Q%2290%7CE%7CB%220%2B1%22%7B%25%22,%60%60_%7C%5C%2F%28%29V%27%22%40]%7DR.1+%7Ct54%2Fm&i=&a=1) It works like this. 1. Start with a big string literal. 2. Convert to integer by decoding as a base-90 number. 3. Convert that number to binary. 4. Runs of `0`s followed by a `1` are translated into non-space characters. 5. All remaining `1`s are replaced with spaces. 6. The resulting string is split into 54-character lines. [Answer] ## Python (2.7.x), 218 characters ``` import base64,zlib; print zlib.decompress(base64.b64decode("eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc")) ``` Pretty straightforward... not terribly pleased with this attempt. [Answer] ## Bash, ~~199~~ ~~196~~ 193 characters ``` base64 -d<<<H4sIAAAAAAAAAz1PQQ6AIAw7S+IfelMTk/3GE0l9CI+3HRPYoHQtAxCAMzduGliMiL0NzElygSz+LiYhLWc1VekzDFU6FoCyIxRIYuBgyd7f5+5eGdnv5OWjbA8UUcRAVbORfBN0v5MFTlw2MhQwEVaV7KYu2tv88IgPjUlb7QoBAAA=|zcat ``` Close enough... EDIT: Down to 193! [Answer] ## bash, 196 192 ``` base64 -d<<<H4sIAO4SqFMCA3VPQQ7AIAi7+4re5pIl/GYnk+4hPH4U0dOmILUUUBCAPEOBn8Wlao65SW6QudWJSYSUM5sqlQlZJAY2QPiAhSEJx8GSPVWm0TppOa3z1DWqboRZEY7K5pzmMw49kgU6TtXRwiDCpCrZxejTvn7u1l5z59MGKQEAAA|zcat ``` [Answer] ## Perl, 230 characters ``` use Compress::Zlib; use MIME::Base64; print uncompress(decode_base64('eNo9T8ENxCAMe5cp/DsqVco2fSH5BsnwZ4ccEIhxbAIgAK9KvDRwGBEjsSfJA6r2N7EISbmrpbLNKFRYOABaC6FAEYkPW/Ztm1t7Z1S3ydtHuV4ooolEV6vPyJ2XH8kGE7d9DAVMhFUte6h7xv5rxg8sf0Qc')); ``` This is basically the same as my Python answer. I'd like to see the 199-character version.. sounds like magic. [Answer] # Perl, ~~294~~ 290 bytes. The compressed string alone, is ~~151~~ 130 bytes. This isn't short, but it was really fun to write. ``` @t=split//,"_|\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'Ph?`@Ooooo1l410````0066600?03l0001PP06600HHB1Q064L4D<8h8^::<DLL4@J0032>1D<90h<>00hHI@6QhYllLX3@`hHI@1Q04P@1Q04@002080R001I^80a074001Q07208P0B0X34ooo`ST';$b=~s/(1)|(0.{4})/$1?" ":$t[ord pack"B8","000$2"]/eg;print$b @t=split//," _|x"x4 ."\\/\n()V',`";$b.=substr unpack("B8",chr(-48+ord)),2,6 for split//,'4100A0000000001017:8R5HR5@1@05E15R5R;:9Ra4`8\\A<0<30a`<C4C2=URa7PRbP@PG4R<g@P<3D=C4cM288S=RK:HV`EVK1G<d0`LL74`EaV2K1Mg=db0000002ab';$b=~s/1(1.{4})|(..)/$t[ord pack"B8","000".($2?"000$2":$1)]/eg;print$b ``` [Answer] # Perl, 346 bytes The compressed string alone, is 111 bytes. ``` @t = split//, " _|\\/\n()V',`"; $k=[0,[1,[2,[[3,4],[[5,6],[7,[[8,9],[10,11]]]]]]]]; $b .= substr unpack("B8", chr(-48+ord)), 2, 6 for split//,'@P900000PBlc<b[<bX:0ZXUIUIVlcFKZLI^Y`LLMhjjW<oJcMGncNHS5MIW]l`ho3lMNgc<IW]V]i[=KUF]KUG[hL^l^^EMeSFiGmNggP001^Pl'; $d = $k; $o.=$d=~/^\d/?$t[$s=$d,$d=$$k[$_],$s]:($d=$$d[$_],"")for split//,$b; print $o ``` Trying to understand what the python with `key= (0,(1,((((7,5),(6,(8,(11,(9,10))))),(4,3)),2)))` was doing, I ended up making a very similar looking perl version. [Answer] ## PHP 590 obviously, i'm not trying to win, just got interested on trying another compression scheme, altough it can't even beat the simpler 302 plain text PHP solution of just copy-pasting it works as a bitmap on 10 channels "golfed" ``` <? $l=['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'],'|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'],'/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'],'\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'],'('=>[3=>'e8,b8lc','1s,4'],')'=>[3=>'3k,2t4w','g,1'],'V'=>[3=>'0,18y680'],'`'=>[2=>'0,g'],"'"=>[2=>'0,6bk'],','=>[4=>'0,g'],];$p=@str_pad;$b=@base_convert;$i=-1;while($i++<5){$h=' ';foreach($l as$c=>$r)if(@$r[$i]){$a=explode(',',$r[$i]);$d=str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0));foreach($d as$j=>$v)$v&&$h[$j]=$c;}echo"$h\n";} ``` readable ``` <?php $l = ['_'=>['l8kqo,ei','9uo6,2fko0','52m0w,5r1c','540lc,5maq','lifeo,19i7ai'], '|'=>[0,'1h39j4,105','1h2k8w,q9x','14l2jk,wlx','1h39j4,wlc','1s,0'], '/'=>[2=>'b9c0,n3kao','pa8,18y68','0,mihog','w,0'], '\\'=>[2=>'pc5,a0zy8','2,0','b9c1,am2kg'], '('=>[3=>'e8,b8lc','1s,4'], ')'=>[3=>'3k,2t4w','g,1'], 'V'=>[3=>'0,18y680'], '`'=>[2=>'0,g'], "'"=>[2=>'0,6bk'], ','=>[4=>'0,g'], ]; $p=@str_pad; $b=@base_convert; $i=-1; while($i++<5){ $h = str_repeat(' ',54); foreach($l as $c=>$r) if(@$r[$i]){ $a = explode(',',$r[$i]); $d = str_split($p($b($a[0],36,2),27,0,0).$p($b($a[1],36,2),27,0,0)); foreach($d as$j=>$v) if ($v) $h[$j]=$c; } echo "$h\n"; } ``` [Answer] # Pylongolf2, 300 bytes ``` " _ _ _ _ _ _ _ | | | | ___| | | ___ __ _____ _ __| | __| | | | |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | | | _ | __/ | | (_) | \ V V / (_) | | | | (_| |_| |_| |_|\___|_|_|\___( ) \_/\_/ \___/|_| |_|\__,_(_) |/"~ ``` I couldn't find any classy encoding methods, so I'm *probably* not competing. [Answer] ## Golf-Basic 84, 325 ``` :" "_Str1t` _ _ _ _ "d`Str1d`Str1t`_ _ _"t`| | | | ___| | | ___ __ _____ _ __| | __| | |"t`| |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | |"t`| _ | __/ | | (_) | \ V V / (_) | | | | (_| |_|"t`|_| |_|\___|_|_|\___( ) \_/\_/ \___/|_| |_|\__,_(_)"t` |/" ``` Assuming a calculator could print backticks, backslashes, single pipes, and underscores. [Answer] ## HTML + JS (223 unicode characters) Just for fun: ``` <body onload=p.innerHTML=unescape(escape("òÅüòĆòÅüòĆòĆòĆß∞†ß∞†òĆòĆòĆòĆòĆòĆòĆòĆòĆòĆòĆòĆòĆòĆß∞†òĆòĆß∞†ß∞äØÄ†ØÄ†ØÄ†ØÄ†ß±üß±ºòźòźòÅüß±üòĆòĆß±üòĆòĆòĆß±üß±üß∞†òÅüòÅüß±ºòźòÅüß±ºòźòźí°ºòźß±ºòźõ∞†ß∞†ßĆØÄ†ØÄØòÅüòÅúòĆòÅúòÅúòÄØßĆõ∞†õ∞†ß∞†ßźòÄßß±üØÄ†ØÄØòÅü®Ä†ØÄ†ØÄäØÄ†òÅüòĆØÄ†òÅüß∞ØòźòźòÄ®ß∞©òźòĆòÅúòÅñòĆ•††õ∞†öÅüöê†ØÄ†ØÄ†òźòźòÄ®ß±ºòźß±ºí°ºß±ºòźß±ºßÅüß±üØÅüØÅüØÅúß±üß∞®òÄ©òĆòÅúß∞ØßÅüõ∞†ßÅüß±üõ±ºß±ºòĆØÅüØÅúß±üõÅüöÅüöêäòĆòĆòĆòĆòĆòĆòĆòĆòĆòĆØÄØ").replace(/uD./g,''))><pre id=p> ``` NB: you have to save it in a "UTF-8 with BOM" HTML file. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 220 byes = script:9 + archive:211 ``` tar xOf t ``` [Try it online!](https://tio.run/##dVDBisIwEL3nKx71YAUlHyEonjws7KkwW2tKC7UpNe5K6b93Z6apXnaTSfLmzXuZkM7/uP5euaaZUpOAAF16RPDPoEWVbE0yYp5E9AJaXi4jJVhNc1VV0SmJ5VqGFwCvDJYDSoxYU5R9vZ3yBtnJas@UNpKy8RMcNhIjYlVbqXOGmbyWIkixEStZDghhRRVlW@KrxPnXR4w2MdLnw4Xd3rfBtQEldgffF86EvMdQlB7MmaMoqrq5noK7MbOCf4TuEVC3rMgvnCHvi6r@drjXg5vE/TyXCNP0Cw "PowerShell ‚Äì Try It Online") The Powershell script to create the archive `t` (see TIO): ``` ( " _ _ _ _ _ _ _", "| | | | ___| | | ___ __ _____ _ __| | __| | |", "| |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | |", "| _ | __/ | | (_) | \ V V / (_) | | | | (_| |_|", "|_| |_|\___|_|_|\___( ) \_/\_/ \___/|_| |_|\__,_(_)", " |/" ) | Set-Content f -Force tar zcfo t f Get-ChildItem t # output info about archive size ``` [Answer] # [Fig](https://github.com/Seggan/Fig), \$274\log\_{256}(96)\approx\$ 225.535 bytes ``` Dr_tem[82]\r-reIX3vb/pBNI9@xbV1?^csytMxrA)YVtY.5yfDryr#(K{bAe,YSkOIU9\|tet&RZF_n+!\;TlNE'T3OB{GGqqvpiP 61;Y#nh0^=vOX6@vxmixkmqp<&y<%;b?=|FG&!6*XI*<glXG,bt|0Kv`/lO;OEx7[`$vT4ljhkSGVaE'</\z{uF8L2E2yXU%r\Ws9F;cF4FXZVD}TL?qdxQ;slDX~lyO# K_+lFV52P-Io9a.7JuDaWJ/sAo,lCChg=5 P9^=[B ``` [Try it online!](https://fig.fly.dev/#WyJEcl90ZW1bODJdXFxyLXJlSVgzdmIvcEJOSTlAeGJWMT9eY3N5dE14ckEpWVZ0WS41eWZEcnlyIyhLe2JBZSxZU2tPSVU5XFx8dGV0JlJaRl9uKyFcXDtUbE5FJ1QzT0J7R0dxcXZwaVAgNjE7WSNuaDBePXZPWDZAdnhtaXhrbXFwPCZ5PCU7Yj89fEZHJiE2KlhJKjxnbFhHLGJ0fDBLdmAvbE87T0V4N1tgJHZUNGxqaGtTR1ZhRSc8L1xcent1RjhMMkUyeVhVJXJcXFdzOUY7Y0Y0RlhaVkR9VEw/cWR4UTtzbERYfmx5TyMgS18rbEZWNTJQLUlvOWEuN0p1RGFXSi9zQW8sbENDaGc9NSBQOV49W0IiLCIiXQ==) Boring text compression answer. Doesn't compress very well due to the compressor being much more optimized for words and spaces before words than characters. Fun fact: when designing Fig, I was considering making the compressor use RLE in the character case, but decided to do capitalization instead :( ]
[Question] [ ## Background We define the two types of chain to be a string that contains only dashes, "-", or only underscores, "\_". We link two chains using one equals sign, "=". Criteria: 1. The type of chain must change following an equals sign. 2. You must link the chains, you can do so multiple times, and it does not matter what length the chains are so long as they are equal to or above one. 3. The chain must not start or end with an equals sign. 4. No two equals signs may be adjacent. 5. There must be at least three characters, and both types of chain must show up. 6. The chain must only contain underscores, dashes, and equals signs. ## Your Task Given a string, return True if it is a valid two-parallel-linked-chains (tplc) and return False otherwise. * Input: The string will be maximum 256 characters long. It may contain characters which are not underscores, dashes, or equals signs. * Output: Return either True or False, depending of if it is valid tplc or not. **Explained Examples** ``` Input => Output ______=-------=___=-----=_=- => True ``` The string is a valid tplc because it follows all criteria. ``` Input => Output => False ``` Empty string does not satisfy criteria 5. ``` Input => Output =_=- => False ``` The string starts with an equals sign, and does not satisfy criteria 3. ``` Input => Output ___ => False ``` There is only one type of chain, so the string does not satisfy criteria 5. ``` Input => Output __==--- => False ``` There are two consecutive adjacent equals signs, so the string does not satisfy criteria 4. ``` Input => Output _=- => True ``` The string satisfies all criteria. ``` Input => Output _=----=___=--@- => False ``` The string contains a forbidden character, @, so the string does not satisfy criteria 6. ``` Input => Output __=__ => False ``` The type of chain does not change after an equals sign, so does not satisfy criteria 1. ``` Input => Output ___--- => False ``` The chains are not linked (no equals sign), and does not satisfy criteria 2. **Test Cases** ``` Input ~> Output ~> False _ ~> False _- ~> False == ~> False ==_ ~> False -_- ~> False _== ~> False =_=- ~> False ____ ~> False -=__£ ~> False *=___ ~> False ->-=_ ~> False __=]- ~> False 0x=+y ~> False --X__ ~> False _==-- ~> False -=_=_ ~> False _-==_- ~> False _-_-_= ~> False _==__= ~> False _=--__ ~> False ___=__ ~> False --=__ _ ~> False __=___=___ ~> False ______=----&---- ~> False ___=---------=________-_____ ~> False --------=_________=-=_=-=_=----=__==----- ~> False -=_ ~> True _=- ~> True -=__=--- ~> True _=--=___ ~> True _=-=_=-=_ ~> True __=------ ~> True __=------------=____________=--------------=_____________=-------- ~> True ---------=____________=----------=_=-=_=---------------=_______________________ ~> True ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. [Answer] # Regex, ~~36~~ ~~32~~ ~~30~~ 29 bytes ``` ^(?=.*=)(_|(^|\b=)-+(=_|$))*$ ``` [Try it online!](https://regex101.com/r/zBEoXZ/1) -1 thanks to @InSync which allowed for another -1 This is my first regex answer, so it's quite possible I missed some optimizations. ## Explanation We start with a `(?=.*=)` to make sure the string contains a `=`. Once we know it does, we can use the following DFA. Let's convert it to a regular expression. [![DFA](https://i.stack.imgur.com/49JxL.png)](https://i.stack.imgur.com/49JxL.png) We'll start by removing the bottom two states, and making sure there's only a single accepting state: [![DFA2](https://i.stack.imgur.com/bTqXT.png)](https://i.stack.imgur.com/bTqXT.png) Now we remove the left state. [![DFA3](https://i.stack.imgur.com/h4XTM.png)](https://i.stack.imgur.com/h4XTM.png) We can remove the `-+` since it's inconsistent with there being a `=` in the string, so we get: [![DFA4](https://i.stack.imgur.com/FWVQA.png)](https://i.stack.imgur.com/FWVQA.png) which is equivalent to `(-+=)?_(_|=-+=_)*(=-+)?`. Then, we can notice the duplication of `=-+`, and since we end with `$` regardless we can optimize it to `(-+=)?_(_|=-+(=_|$))*`. Now, we can do the same for `-+=`, and optimize it to `(_|(^|=)-+(=_|$))*`. However, this introduces the problem that a match can start with `=`. To fix this, we can notice that `_` is a word character, while `-` and `=` aren't. This means that `\b=` matches iff the previous character was `_`, which works in our scenario. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` f⁾-_Œgj”=⁼>E ``` [Try it online!](https://tio.run/##y0rNyan8/z/tUeM@3fijk9KzHjXMtX3UuMfO9f/h9oc72/JOTn64Y5EtUDSE6@jkhzsXP2qYo1BnpwAUOLxcn@vh7i2H2x81rYn8/x8k6paYU5zKFY/E1EWwbW2R2UiKdJFVxaMoi7dFlgICFIW6yJK6QDNR@EBoi6I8HpWvq4tiHFAWma@rC@KiKLCFqEHVBBLTBQI1EIFqnC4M2MZDgW48qh8wFAA12UIxRNgWYgqSFkjIhRSVgv0AZ4MVQ1XCJHVhroUJQMxGiMDciCmC7q54NBk0OYQkwkGEDEHyKE5jEQBmLgA "Jelly – Try It Online") ``` f⁾-_ Filter out all characters but -_. Œg Group runs of consecutive equal elements. j”= Join on =. ⁼ Does this result equal the input? >E And, are the elements of the input not all equal? ``` [Answer] # JavaScript (ES6), 70 bytes This code is using an explicit finite-state machine rather than regular expression functions. Expects a list of characters and returns **0** or **1**. ``` a=>a.map(c=>a|=(s=+"0X00XX11X143"[s+5*"-_=".indexOf(c)])>2,s=2)&&a&s<2 ``` [Try it online!](https://tio.run/##jVDBToQwEL3zFaQHtnV3GkA96XDTqxcPJEiahgV3DcKGrkYT/x2L0BZ2s4mTtDOdNzN9897kp1RFtz8coWm3ZV9hLzGR/F0eaKGDH6QK1yRMwzBNoyiNbq5Jpta3VwQEEr5vtuXXU0ULlrMk3iiMWRDIQN3HfdE2qq1LXrevdJU9ylp95yt252We7xOyGW4xORg9ovETAAYRFhJoUtosCCYJutfGYqBoSoSLAWyrzpoYQIe@BXDEXOHwBm3BcLl2MIZiMhCO2xmoG3A6YxrHCbo893jVdg@y2FHlY@LPBaxoxjlXOWNaQW8h7UuTPXcfx91MXUArzcT07yfHG0dG9jVSsqsDzHd0Ky4WESfICebApRIXJ8xkuTjTGfmvXP0v "JavaScript (Node.js) – Try It Online") This could be **[56 bytes](https://tio.run/##lVBNb4MwDL3zKxDS1rDViI/eOnOYtP2CHSIxFEUZaTcxqEg7aVL/O0sbEihVDzMitt@LHft98R@uRPe520PTflS9xJ5jzqNvviNCB0ckCoM4o3SVxDShNImDQj1kj@IuK8M8XSpMwyO/V09pL9pGtXUV1e2GLIpXXqvfchGuvcLz/SBYnk42ODAe0fqBAMswRzG0kDZHggVB17pYf@iusDEGcKUaHWM06YQDayf4bMDGh69IXYDDb2A0HfT10otk271wsSXKx9yfqiPJ80HKqiMq1Lb2vAvp3pvirTvstxP1AN3qw7Lnx8DJgGYol5mp3J5gp5qm813YjJlxI3kpxs0OE2Vu9hwt@Idi/R8)** if the input was guaranteed to contain only underscores, dashes and equal signs. (This version expects a list of ASCII codes.) ## States * State **0**: We are within a `"-"` chain and expect either another `"-"` or a `"="`. * State **1**: We are within a `"_"` chain and expect either another `"_"` or a `"="`. * State **2**: This is the initial state where we expect either `"-"` or `"_"`. * State **3**: We are just after a `"="` preceded by a `"_"` chain. We now expect a `"-"`. * State **4**: We are just after a `"="` preceded by a `"-"` chain. We now expect a `"_"`. * State **X**: An error has occurred. ## State-transition table This table gives the new state based on the current state and the next character. ``` | 0 1 2 3 4 X ----+------------ "-" | 0 X 0 0 X X "_" | X 1 1 X 1 X "=" | 4 3 X X X X ``` The rightmost column is not stored in the lookup string because the **X** state is actually encoded as *NaN*, which forces any further lookup index to be evaluated to *NaN* as well and leaves the state unchanged till the end. We don't have to store the trailing **X**'s either. Hence the final lookup string: `"0X00X" + "X11X1" + "43"`. ## Output The input is correct if and only if: * We end up in state **0** or **1**. * We've reached state **3** or **4** at least once. [Answer] # [Python](https://www.python.org), 74 bytes ``` lambda s:0<2*(c:=(s+s[::-1]).count)("_=-")==2*len(s)-c("_")-c("-")+c("_-") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hVLBSsQwEAWP-YrQgyS7nWXdk5Qdbwp68eJNJXTXLQbWJLTpQQTB7_CyIPpP-jUm23aT7CJOaTPvzZvHTMn7l3m2j1ptPiq8-2xtBaffV-vyafFQ0qaYzmcjtiyQNePmtijg5J5PlrpVlrNMIGQccTZarxRrOCwdlW0Px489cmfveF7pmhoqFdXGqae8IFTmItdoJo2tpWF8YsraSiu1Yhl9PaMZJ9TUUlkm84pJnuvebPNz9HapTGu96rq1LiOEEo8uynWzIiJKgfYZYmARIwk4jd9k_jIKbYnaLRo5uqCxEOIiOOsEuwcTuUgxQGLnqjEG8DARYKdJmzwHLo79J7WDIVD0ASLd4UDgmrB_Oxo7l9BCoPuDN3W7XWKXb9W9dCjCMO5AdOaBGYY8ZPYHE3uVvVoohoH-M4k2_dM2xM63u4q_) ## How? Looking at the counts of certain substrings we can enforce Rules 1,3,4 by requiring that #"-=\_" + #"\_=-" = #"=" and rule 5 by requiring this number be positive. Rule 2 by requiring neither "-\_" nor "\_-" occurring, i.e. their counts being zero. Rule 6 by requiring #"=" + #"-" + #"\_" = |s| (the length of the input). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~20~~ ~~15~~ ~~13~~ 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „-_Ãγ'=ýQIË› ``` -2 bytes porting [*@UnrelatedString*'s Jelly answer](https://codegolf.stackexchange.com/a/262494/52210), so make sure to upvote that answer as well! -1 byte thanks to *@CommandMaster* Outputs `1` for truthy and `0` for falsey. [Try it online](https://tio.run/##yy9OTMpM/f//UcM83fjDzec2q9se3hvoebj7UcOu///jwcBWFwJs4WxbIA0A) or [verify all test cases](https://tio.run/##dU4xCgIxEPxKSKHNzROWe4O1yKJgYWUhCNcdCDY24gP8hJ1gld5H3EdiLrtrzpObkGV3ZjaZ/WG92W3jsam968435@smXGPX3sHh9H7MKbwWTbh07TNWcel95Tzngr4SSc0UhGMlmWRMUBpCIPm1S4dUZOsAXUiMdEBqnJIkvFn6CQmzvtgaDMQKsOX4k5Kd9ApNsp/NpNltyibL@Y1hL2hCoIQpWX7@5JEy0oo4jDy5P8g/@WKBX30A). **Previous 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:** ``` '=¡€Ôι€Ù˜{„-_SQ ``` Outputs `1` for truthy and `0` for falsey. [Try it online](https://tio.run/##yy9OTMpM/f9f3fbQwkdNaw5PObcTRM08Paf6UcM83fjgwP//48HAVhcCbOFsWyANAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/ddtDCx81rTk85dxOEDXz9JzqRw3zdOODA//r/I9WUtJRUIoHE7og0tYWQoKFdCFi8VDBeFsIFwigwroQAV2geigLCG2hkvEwlq4uVANQBMLS1QUyFKCCthBxmBIQTxcI1EAETJsuDNjGQ4FuPMwdGFJA5bZQDBG2hegHK7aFuh3GAyuCuRPuDJgJUBfq6iIcg3ALip3xaDJocghJZCfj1I/kfpwmIoBSLAA). Or [verify all test cases with add debug-lines](https://tio.run/##dVDNSgMxEL73KYYc/IHNCxRCDxXBoxRPpSxpTd3gmrSbbEvxUnwGL0IRvHsWPAntUfAh@iLrZJO4tdrZ3dmZb75v8u1qw4dSVLNFdbZdri7UpLRtIJsPgl3SwtSb5NIC3loBYaQNiHWO2fqFtUhXKyVGVlxDqeS0lOMFCD7KYMILt6WzfXjdPCLvSkllRZELPhNuFXYa7FzXROOYX@//rxtqm0EujTUoAptJgxpZxOVPqDrPubViZwh6HCR4Cgcj1U0uasTJPleo6enCekGE75n72G4mRrcwz4TNRIFvbqEQd1wqPN6AmJY8d0v7hJKEpGQAJ/NM4gfjUJcFck2Z21P/j7bLZ5r2LpNq/dap@oQkgAqXqMuM@VxD1GNpAFPmW4wAUw9Q5IcKLxaGaawoDQJEfEUpFhBA5vFIcR3FOHIpymgMloagafTxZ4R0Fh4PM6@vySx4j11Nij5/bMQNwSGljZnGy68z073J3qwZ7lo@qN/xf3BjE2TwDQ), to better understand what's going on. **Original ~~25~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:** ``` ê…-=_ÊI„-_‚åI'=¡õåM ``` Outputs a reversed boolean (`0` for truthy; `1` for falsey). If this is not allowed, a single trailing byte can be added to reverse it. [Try it online](https://tio.run/##yy9OTMpM/f//8KpHDct0beMPd3k@apinG3@46VHDrMNLPdVtDy08vPXwUt///@PBwFYXAmzhbFsgDQA) or [verify all test cases](https://tio.run/##dU4xCgIxEPxKSKEIt09Y7gW@QGVRsLCyEIR0h4WFpaWFYKGFvR8wP8lHYi67a86Tm5Bld2Y2me1uudqs497V1oTj2djaRf8MzQOQ/MmF5grkD6G5@Lsb4/vmX/4@jdVkHmfWVsZSLtBWRK6ZAuZISEIeE4QGJiD5pUsHRSTtAGQhMdxBCkZGSGReLe0ECaO26BookARAmuNPSnaUyzTyfjajZNcpmzTnN4a@IAkBSpiS5edP6ik9rYjdyIP7nfyDLxbYxQc). **Explanation:** ``` „-_à # Only keep the "-_" characters of the (implicit) input-string, # removing any other characters γ # Split this string into equal adjacent groups '=ý '# Join it with "="-delimiter Q # Check if this string is equal to the (implicit) input, # resulting in 1 or 0 for truthy/falsey respectively I # Push the input-string again Ë # Check if all of its characters are the same (or it's an empty string) › # Check that the first check is larger than the second # (aka, verify whether the first is truthy and second is falsey) # (after which the result is output implicitly) ``` ``` '=¡ '# Split the (implicit) input-string by "=" € # Map over each substrings: Ô # Connected uniquify the characters in the substring ι # Uninterleave it into two parts € # Map over both inner lists: Ù # Uniquify the list of substrings ˜ # Flatten the pair of lists of strings { # Sort it „-_SQ # Check if what remains is equal to pair ["-","_"] # (after which the result is output implicitly) ``` ``` ê…-=_Ê # Rules 5 and 6: ê # Sorted-uniquify the characters in the (implicit) input-string …-=_ # Push string "-=_" Ê # Pop both, and check whether they're NOT equal I„-_‚å # Rule 1: I # Push the input-string again „-_ # Push string "-_"  # Bifurcate it; short for Duplicate & Reverse copy ‚ # Pair the two together: ["-_","_-"] I å # Check for both whether they occur in the input-string I'=¡õ '# Rules 3 and 4: I # Push the input-string yet again '=¡ '# Split it on "=" õå # Check if this list of parts contains an empty string "" M # Push the largest integer on the stack (also looks within lists) # (after which it is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes ``` ∧№θ=∧⌊⪪θ=⬤θ№”{“→↘λΠz*”✂θκ⁺³κ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMxL0XDOb8UyCrUUVCyVdLUUQAJ@WbmZeaW5moEF@RkIkvl5IA4EA1Kurq6tvG2QBwPJHWVdBSCczKTU0EKsnUUAnJKizWMgUxNCLD@/18XBkA64MBWF0ncFoxRAYpqJPBftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for a tplc, nothing if not. Explanation: ``` ∧№θ= ``` The input must contain at least one `=`, and... ``` ∧⌊⪪θ= ``` ... it must not contain leading, consecutive or trailing `=`s, and... ``` ⬤θ№”{“→↘λΠz*”✂θκ⁺³κ ``` each sliding window of length 3 must be contained within the compressed string `---=_=-=___=--`. [Answer] # Regex with conditionals, 29 bytes ``` ^((?(2)=(?!\2))(-|_)\2*){2,}$ ``` [Try it online!](https://tio.run/##hU85DgIxDOz9CpAA2Qg36a0t@cRqDQUFDQWiA94efOwFSOAkGsfjxDPX0@18OdY17g@1Q2ywkGCzbAsR8kOpLVu6l91zVSuLggqDoQGzXzyPqsSBZIIcsgzvG@ON@eAmEv4@ln7wr@@mADB9DCK2FVjdgOVuSdOFuG421sGWeE0DmL3DcoMYsQizWQlmkLbp7c90jYo4hXwrlbkXH5mPXw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^(...){2,}$ ``` Match at least two chains. ``` (?(2)=(?!\2)) ``` If there is a previous chain, then it must be a different chain separated by `=`. ``` (-|_)\2* ``` Match a chain, but capturing only its first character. # Regex with lookbehind, ~~31~~ 30 bytes ``` ^(-+|_+)(=(-|_)(?<!\3=.)\3*)+$ ``` [Try it online!](https://tio.run/##hU85DgIxDOz9CpAAJURDsy0WJZ9YYSgoaCgQ5f49@NgLkMBJNI7HiWce1@ftfqnrdDzXU0LppOTECZ3kdNgv24Z3uW22uaxqBQsJgxQVALtY7lX2Q8E4OWQR1jfGG/PBTST9fcz94F/fTUGk@kDMuoUgZkBzsyThgk03lDXQxVYTB8A6NFfwEQs3GxVnBmmb3v5M16gIIeRbKc@92Mh4/AI "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^(-+|_+) ``` Match a leading chain. ``` (...)+$ ``` Match at least one more chain. ``` =(-|_)(?<!\3=.) ``` Ensure that each chain differs from the previous chain. (We don't have to match `\3` twice because the `.` much match the `\3` we just captured.) ``` \3* ``` Match the rest of this chain. # Regex with capture groups, 32 bytes: ``` ^(-|_)\1*(=(?!\1)(?<1>-|_)\1*)+$ ``` [Try it online!](https://tio.run/##hU85DgIxDOz9CpAAJaAptsdsuZ9YYSgoaCgQJX8PPrIHIIGTaByPE8/cL4/r7VzWqTuVY8JTct9sE6d22Tc5tfvmUGt5tyoFLCQMUlQA7GK5V9kPBePkkEVY3xhvzAc3kfT3MdfBv76bgkj1gZh1C0HMgOZmScIFm24oa6CLrSYOgHVoruAjFm42Ks4M0jbV/kzXqAgh5Fspz73YyHj8Ag "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ^(-|_)\1* ``` Match an initial chain, but capturing only its first character. ``` (...)+$ ``` Match at least one more chain. ``` =(?!\1) ``` Ensure that each chain differs from the previous chain. ``` (?<1>-|_)\1* ``` Match the next chain, but capturing only its first character, pushing it to the original group. [Answer] # [Brainfuck](https://esolangs.org/wiki/Brainfuck), 379 bytes (wrap + soft non-wrap) ``` >+>>+++[>+++++<-]>[>+++>++++<<-]<,[>+<<+>-]>>[<-<+>>-]<[<[>->+<<-]>-----[<<<->>> >[<+<+>>-]<<[>+>+<<-]>+++++[-]]]<[>>+<<-],[<[>>+<-<-]>[>[<+<+>>-]>>[<<<->+>>-]<< <-[<<[-]>>+>[<+>>>+<<-]<[-]]>[>>+<<-],<<[>+>-<<-]>>[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2NvcmUgYW5kIHJlc2V0cyA0NQogICAgICAgICAgWyBub3QgYW4gdW5kZXJzY29yZQogICAgICAgICAgICA8PDxbLV0-Pj4-ICAgICAgICAgICAgIyBNYXJrIGFzIGludmFsaWQKICAgICAgICAgICAgWzwrPCs-Pi1dPDxbPis-Kzw8LV0gICMgQWRkIDkwIGFnYWluCiAgICAgICAgICAgID4rKysrWy1dICAgICAgICAgICAgICAjIEFkZCA1IGFuZCByZXNldDsgd2UgY2FuIGFkZCA0IGJlY2F1c2UgbnVsbCB3b3VsZCBoYXZlIGJlZW4gZmlsdGVyZWQgYWxyZWFkeQogICAgICAgICAgXQogICAgICAgICAgPls8PCs8Kz4-Pi1dPDw8KysrKys-PiAgIyBBZGQgNTAgdG8gc3BvdCBvZiBuZXh0IGNoYWluIHZhbHVlCiAgICAgICAgXQogICAgICAgIDxbPis-Kzw8LV0gICAgICAgICAgICAgICAgIyBSZSBhZGQgNDUgaWYgc3RhcnRlZCB3aXRoIGh5cGhlbiBhbmQgY29weSBiYWNrIGZvciBjb21wYXJpc29uIHRvIG5leHQgdmFsdWUKICAgIF0KICAgID5bPDwrPj4tXTwsICAgICAgICAgICAgICAgICAgICMgU2V0IG5leHQgdmFsdWUgYW5kIG1vdmUgdG8gc3RhcnQgcHJldmlvdXMKICBdCkxJTkVTIDU3IFRPIDYzOiBPdXRwdXQKICBzdHJpbmcgZW5kZWQgcG9pbnRlciBhdCAzCiAgPDw8Wy0-KzxdPi0tWzxdICAgICAgICAgICAgICAgICAjIE1vdmUgb25lIHRvIHRoZSByaWdodCBpZiB2YWxpZCBzdHJpbmcKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgVGhyZWUgb3B0aW9uczoKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKiBlaXRoZXIgbm8gZXF1YWxzIHNpZ24gc28gbmV2ZXIgZ28gcmlnaHQKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKiBlcXVhbHMgc2lnbiBidXQgYWxzbyBpbnZhbGlkIGdvIHJpZ2h0IHRoZW4gYmFjayB0byBsZWZ0CiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICogZXF1YWxzIHNpZ24gYW5kIHZhbGlkIGdvIHJpZ2h0IHRoZW4gYmFjayB0byBsZWZ0CiAgPj4-Pj4uICAgICAgICAgICAgICAgICAgICAgICAgICAjIE91dHB1dCBtaW51cy9sZXNzIHRoYW4gc2lnbgo$) Outputs `-` for False and `<` for True. With EOF = 0. It's been a while since I did anything in brainfuck. I'm sure I missed something that can obviously be golfed further. This program works for the usual implementation that wraps cells at 255, but also for programs without wrap (soft non-wrap: they accept negative numbers). Accepting negative numbers bloats the size quite a lot, because you always need to go back to a point where you're certain the number isn't negative for `[-]` to terminate. I might come back to simplify the wrapping version, there's at least 65 free bytes to save and maybe more. It's nice how the ASCII value for `_` (95) is almost double `-` (45) and that `-` and `=` (61) almost have a common divisor of 15. Creating the constants is either unnecessary or can be easily combined. I did not yet try using a state-machine that sets up the `-` and `_` values and compares each chain to the appropriate one, but I think that could actually make the opposite + valid check simpler. ## Summary of steps ``` LINES 4 TO 6: setup LINES 8 TO 17: check if valid first character LINES 19 TO 55: core: consume alleged chain and mark if invalid LINES 23 TO 52: not identical: is the next value an equals sign and the value after that the opposite chain LINES 26 TO 31: Check if interruption an equals sign LINES 33 TO 39: Check if next chain not identical to current LINES 42 TO 52: Check if new chain is valid LINES 57 TO 63: Output ``` ## Summary of cells | When | 0 | 1 | 5 | 6 | | --- | --- | --- | --- | --- | | Always (except when being used) | Is there at least one `=` in the chain | Is there NOT [an invalid transition or an invalid character (including EOF after `=`)] | 45: `-` | 60: `<`, `=` - 1 | | When | 2 | 3 | 4 | | --- | --- | --- | --- | | Interrupted by `=`? | Previous chain value | Interrupt - 61 | 60, then next chain | | Identical chain | 0 | Previous chain value, then 0 | 0 | | Not identical chain | 0 | 0 | Next chain value | | Non-destructively `-` or `_`? | 0 or 50 | 45 | 0 or (50, then 0) or (other, then 0) | ## Full code with comments ``` OUTPUTS MINUS FOR FALSE AND LESS THAN FOR TRUE works both with wrap and without wrap (soft) LINES 4 TO 6: setup >+>>+++[>+++++<-]> # Create marker for invalid and value 15 [>+++>++++<<-] # Create 45 and 60 <,[>+<<+>-]> # Store first input twice to validate as hyphen or underscore and compare to next values LINES 8 TO 17: check if valid first character >[<-<+>>-] # Compare to hyphen <[ not a hyphen <[>->+<<-]>----- # Test against 95 underscore and resets 45 [ not an underscore <<<->>>> # Mark as invalid [<+<+>>-]<<[>+>+<<-] # Add 90 again >+++++[-] # Add 5 and reset ] ] <[>>+<<-] # Reset 45 if started with hyphen LINES 19 TO 55: core: consume alleged chain and mark if invalid Left (third) cell contains the previous value ,[ while there is a new value <[>>+<-<-] # Compare to previous LINES 23 TO 52: not identical: is the next value an equals sign and the value after that the opposite chain >[ not same chain check if equals sign >[<+<+>>-] # Reset value and store for later LINES 26 TO 31: Check if interruption an equals sign >>[<<<->+>>-] # Compare to equals sign <<<-[ chain interrupt not an equals sign <<[-]>> # Mark as invalid +>[<+>>>+<<-]<[-] # Reset value and 60 then remove value ] >[>>+<<-], # Move 60 back if not already and store next chain value LINES 33 TO 39: Check if next chain not identical to current <<[>+>-<<-] # Compare to previous chain value >>[ not equal to previous chain <[>+<-] # Reset new chain value pointer now moves one left ] <[ non empty only if pointer didn't move left and values were equal <<[-]>>[-]< # Mark as invalid and remove stored value of previous chain ] <<[-]+>> # Mark as having an equals sign in the string LINES 42 TO 52: Check if new chain is valid >>>[<-<+>>-] # Compare to hyphen <[ not a hyphen <[>->+<<-]>----- # Test against 95 underscore and resets 45 [ not an underscore <<<[-]>>>> # Mark as invalid [<+<+>>-]<<[>+>+<<-] # Add 90 again >++++[-] # Add 5 and reset; we can add 4 because null would have been filtered already ] >[<<+<+>>>-]<<<+++++>> # Add 50 to spot of next chain value ] <[>+>+<<-] # Re add 45 if started with hyphen and copy back for comparison to next value ] >[<<+>>-]<, # Set next value and move to start previous ] LINES 57 TO 63: Output string ended pointer at 3 <<<[->+<]>--[<] # Move one to the right if valid string Three options: * either no equals sign so never go right * equals sign but also invalid go right then back to left * equals sign and valid go right then back to left >>>>>. # Output minus/less than sign ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 66 bytes ``` a=>!!a.map(c=>a|=s=+"XX22200XX03X1"[s+5*"-_=".indexOf(c)],s=4)&a+s ``` [Try it online!](https://tio.run/##jVJNb8IwDL3nV5geoAVcSmGnydw2aadddqjUVVFU6GBiLSJs2iT@O0to8wET0hw1sd@zXecp7@JLyHK/2R2wbparU0UnQYteT8QfYheWtBBHkjQKsixN0yTJsmSWTYNcju6GAXIK4k29XH0/V2EZFWNJ86gvRvI0GTIAGKMz4Bo5ehhQBzkQ0CAGA/KgFoSnenPwwaMOEphCCjOYM0DI1Er1YsAVk5yBhAGphEwlqpANJ6xsatlsV/G2eQsH@aPYyp9iEN2zXDUMgrHeeXdgexKZsyPQMNxSnAykzJJoQFS11udaQpPCnY9oSxVqfETlgiWo5VyijrVofb25cqs48c6Qu9n@kKqAuq@Fqe2g0gsWV83@QZTrUAItwBewCvM4jmURRUrBS2lf6/xl/3lYe@oiWWm6Sc9/cnNTO5GN2pHs1RH9O5L30LyL8CvminPkpRI3O3iy3OzpLPivXKdf "JavaScript (Node.js) – Try It Online") Modified from Arnauld's `!!a.map(...)` is `true` or `1` when used in bitwise operation. `a` is the bitor of all historical value of `s`, so if `a` and `s` have different lowest bit then `a` has `1` and `s` has `0` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 11.5 bytes (23 nibbles) ``` ^==*"=";`=|$?"_-"$$_<< ``` Inspired by [Unrelated String's Jelly answer](https://codegolf.stackexchange.com/a/262494/95126). Outputs a non-empty list (truthy) if the input is a valid, an empty list (falsy) if the input is not valid. ``` ^==*"=";`=|$?"_-"$$_<< # full program ^==*"=";`=|$?"_-"$$_<<$ # with implicit arg added; | # filter $ # the input ? $ # for letters that occur in "_-" # "_-" `= # and split into chunks $ # of identical items ; # (save this for later); * # now join these chunks "=" # using "=" between them == # and check if this is equal to _ # the input (1 if it is, 0 otherwise); ^ # finally, use this value to replicate $ # the saved chunks from earlier << # but without the last one ``` [![enter image description here](https://i.stack.imgur.com/koDSl.png)](https://i.stack.imgur.com/koDSl.png) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `G`, ~~90~~ ~~86~~ 79 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), ~~11.25~~ ~~10.75~~ 9.875 bytes ``` \_‹↔Ġ\=j₍≈≠ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJ+Rz0iLCIiLCJcXF/igLnihpTEoFxcPWrigo3iiYjiiaAiLCIiLCIhKC4qKSB+PiAoXFxkKVxuIH4+IDFcbl8gfj4gMVxuXy0gfj4gMVxuPT0gfj4gMVxuPT1fIH4+IDFcbi1fLSB+PiAxXG5fPT0gfj4gMVxuPV89LSB+PiAxXG5fX19fIH4+IDFcbl89PS0tIH4+IDFcbl8tPT1fLSB+PiAxXG5fLV8tXz0gfj4gMVxuXz09X189IH4+IDFcbl89LS1fXyB+PiAxXG5fX189X18gfj4gMVxuLS09X18gXyB+PiAxXG5fXz1fX189X19fIH4+IDFcbl9fX19fXz0tLS0tJi0tLS0gfj4gMVxuX19fPS0tLS0tLS0tLT1fX19fX19fXy1fX19fXyB+PiAxXG4tLS0tLS0tLT1fX19fX19fX189LT1fPS09Xz0tLS0tPV9fPT0tLS0tLSB+PiAxXG4tPV8gfj4gMFxuXz0tIH4+IDBcbi09X189LS0tIH4+IDBcbl89LS09X19fIH4+IDBcbl89LT1fPS09XyB+PiAwXG5fXz0tLS0tLS0gfj4gMFxuX189LS0tLS0tLS0tLS0tPV9fX19fX19fX19fXz0tLS0tLS0tLS0tLS0tLT1fX19fX19fX19fX19fPS0tLS0tLS0tIH4+IDBcbi0tLS0tLS0tLT1fX19fX19fX19fX189LS0tLS0tLS0tLT1fPS09Xz0tLS0tLS0tLS0tLS0tLS09X19fX19fX19fX19fX19fX19fX19fX18gfj4gMCJd) Ports jelly but uses inverted booleans. Truly goofy hours here. ## Explained ``` \_‹↔Ġṅ\=j₍≈≠­⁡​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁣‏⁠‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌­ ↔ # ‎⁡The input filtered to only keep characters from \_‹ # ‎⁢the string "_-" Ġṅ # ‎⁣Grouped on consecutive characters \=j # ‎⁤Joined on "="s ₍≈ # ‎⁢⁡Check whether every item is the same (inverted boolean here makes it so that 0 means there's more than one pipe type) ₍ ≠ # ‎⁢⁢Check that the string does not equal the input (inverted boolean here means 0 means its the same) 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 19 bytes ``` q{SM.:{McQ\=2,M]"-_ ``` [Try it online!](https://tio.run/##K6gsyfj/v7A62FfPqto3OTDG1kjHN1ZJN/7/fyVdKLCNhwFbIBuCocJghq4SAA "Pyth – Try It Online") Feels like there's one or two more bytes to be shaved here, but I couldn't get them for now. ### Explanation ``` # implicitly assign Q = eval(input()) cQ\= # split q on "=" {M # deduplicate each element, turning runs into single chars .: 2 # get all sublists of length 2 SM # sort each sublist { # deduplicate the whole list q ,M]"-_ # compare to [["-", "_"]] ``` [Answer] # [Python 3](https://docs.python.org/3/), 60 97 bytes * Edit: missed some of the rules, will revisit! fun challenge! ``` lambda s:{str({*q})for q in s.split('=')}=={"{'-'}","{'_'}"}and(s.count("-=-")+s.count("_=_")==0) ``` [Try it online!](https://tio.run/##dVHNDoIwDL77FIsHB8Z68WbSqy@gR5MFgkQS5G9wMGTPPovTwDotGU2/fv3Wds2zv9fVweZ4tWXySLNE6OOo@y4at62J87oTrSgqofe6KYs@kihjgziuRwnSrHfkFXljm66oKH2@10OZifQmTkmpbzJeuUQeES9eRuCFiCz02cDoivMVMgIZrwBGAbqFQ/Qhr1MBBMDVicMgAEIEp6FjBtUTDGSb6RdIw9dQfQxUMGHAoTr8HAejE5qrvn7xbJdu8F4NkO/Rb@@tG/SMrg0Ounb4SgB@DD3P7I2kWIbl5uTP1fwVWuzpr/RspG1f "Python 3 – Try It Online") # Python 3.9, 53 bytes 3.9 allows str unpacking/decoding which doesnt work in 3.8 (at least not on TIO). The dreaded "works on my computer" lol. ``` lambda s:{str(*{*q})for q in s.split('=')}=={'-','_'} ``` As always any help is appreciated! [Answer] # [J](http://jsoftware.com/), 44 bytes ``` 1-:&~.2+/\'_-=';@(2<@(,3#~1~:#)@~.;._1@,i.)] ``` [Try it online!](https://tio.run/##lZHPTgMhEMbvPsUoZgHLjLKNF1oaookn48Fru8HE1KgXH6CVV6@z3d0W@ucgyTbAfL9v5qPfmyuSH@AdSDBwB44/JHh8fX7aWHRVonp0u5ARvZwEVU@DMmORbHJCh0QTijaYL9LNRl@8PBBILxVSggkoxZBcJUgOlHFIOoh6PXfs5jU0K0rjGYnQgObTllVSomshJMPeOqhYN29rWjSMppa0EO2aLunuasWNKr/FxkovBrthhkqpey8oqOTYSN/wSEvq5pm7bhpOsBuna19PRdv2ps8wAEjBHwVodmkNv4gSohmeI8290R2rro1T12seINmRnZEVdIJc0f9Q@0tzx//FNJhUsc@EbLKmTu6WH2pJVYuLToqOxf0VE4pfib2EPokGhpbvnz/wAVLudjHb4n7vfb7PRJirYiGLPi/xKoSYFZG1RWNukbPcJPqCjuUZsXDnan5G9o9QCHynKaH2DnlV7U9ph8PysV8Yy0hHAoZ8/3XXvnPpEVnEL8IUlS1eZj0YfOhT5EM8DLHPUEwZDyoHtX3xOOpZlyz3Wd/9kps/ "J – Try It Online") Surprisingly difficult problem to golf well in J. I tried a few approaches. Here we: * Convert `_-=` to `0 1 2` * Split on 2, and to each split group... * Take the unique and... * Append nothing to it if it has length 1, otherwise append a 3 * The result at this point will have the alternating form `0 1 0 1...` or `1 0 1 0...` iff it is a valid chain * To check this, we take all sums of consecutive elements, take the unique of the result, and check if it is 1 [Answer] # [JavaScript (Node.js)](https://nodejs.org), 84 bytes Interesting challenge! This is a more classic JS solution, quite longer than the two "finite-state machine" answers. ``` p=>!p.split`=`.some(a=(s,i)=>(s<1|[...s].some(c=>c!="_-"[((p[0]!='_')+(a=i))%2])))&a>0 ``` [Try it online!](https://tio.run/##dVHBUoMwEL3zFTQzlmTKMq1HdfGkX@ANmTRDU4uDwBDq6IxXb36C/lx/BFMDCdTpZkg2@/Ytuy/P4lWorMnrFspqI7stdjXGszpSdZG3a1xHqnqRVCBVYc4wVjerjySKIpUaIMM4myHhQBJK62SZzjDgAVtoRs7YxWXK2FzEy04oJZsWaV7W@zaUb7XMWrkJG6n2RYtbE2f6B1lVqqqQUVE9UdrDiAPhlhy@P31yRQ4/Xz5hC5PAPG9MC5J7Uaj3NGDXXuL5PiHhcef9AeZEHM4egAHhFuI4hLRZEIYgaK719UKbwp0PYKk6OvgA2vUtgAZzicc7aJsfN0eHwZD3Btz19g/UBOw/E0ZTQaenXrStmjuR7ajyMfbNA@lXXjIt21TPxzJ5aPbtbiQpoNWjb@@vvGsWTRv2Zvqw8wKMB3NzTbrnJ8gJ5sDp@GcrjLQ4W9MZOa/RirHuFw "JavaScript (Node.js) – Try It Online") --- * The two `some` are basically two `every` negated, with their inner condition also negated * The first `some` parses each string between and around the `=`, and the second `some` parses each character inside each string and controls that they all have the correct value (using the index of the string inside the splitted array, and the starting character of the whole input) * The `a>0` controls that the input contains at least one `=` * The `s<1` controls that no string are empty between and around the `=` ]
[Question] [ It's obviously ellipsisessieses. Inspired by [a chat message](https://chat.stackexchange.com/transcript/message/39560898#39560898). # Your challenge Given a list or space or comma-separated string of words, ellipsisessiesesify them. To ellipsisessieses-ify a word: 1. Start with the word. 2. Add the first letter of the original word to the end. 3. Add 2 of the last letter of the original word to the end. 4. Add the second-to-last letter of the original word to the end. 5. Add the first letter of the original word to the end. 6. Add the last letter of the original word to the end. 7. Repeat steps 5 & 6 once. 8. You're done! # You can assume: * The input words will only be alphanumeric * Input & output can be a space-separated string or list * The input will contain only words * The words will be at least 2 letters long * The input will match the regex `/^[a-z0-9]{2,}( [a-z0-9]{2,})*$/i` * You can have a different input and output format * *More to come...* # Test cases: ``` ellipsis -> ellipsisessieses goat -> goatgttagtgt covfefe -> covfefeceefcece programmer5000 -> programmer5000p000p0p0 up vote down goat -> upuppuupup voteveetveve downdnnwdndn goatgttagtgt it is golf yo -> itittiitit isissiisis golfgfflgfgf yoyooyyoyo crossed out 44 is still 44 -> crossedcddecdcd outottuotot 4444444444 isissiisis stillslllslsl 4444444444 ``` Shorteststtsstst answerarrearar ininniinin bytesbssebsbs winswssnwsws! [Answer] # JavaScript (ES6), ~~58~~ 57 bytes *NB: This turns out to use the same trick as Jonathan Allan in [this Jelly answer](https://codegolf.stackexchange.com/a/140393/58563) (though I noticed after posting).* *Saved 1 byte thanks to Jonathan Allan* Works on arrays of strings. ``` s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1))) ``` ### Test cases ``` let f = s=>s.map(s=>s+'01120101'.replace(/./g,n=>s.substr(-n,1))) console.log(f(['ellipsis'])) console.log(f(['goat'])) console.log(f(['covfefe'])) console.log(f(['programmer5000'])) console.log(f(['up', 'vote', 'down', 'goat'])) console.log(f(['it', 'is', 'golf', 'yo'])) console.log(f(['crossed', 'out', '44', 'is', 'still', '44'])) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13 12~~ 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁽×ʠb3’ịṭµ€K ``` A full program that takes a list of lists of characters and prints the space separated output. **[Try it online!](https://tio.run/##y0rNyan8//9R497D008tSDJ@1DDz4e7uhzvXHtr6qGmN9////6OVSguUdBSUyvJLUkF0Sn55HohOz08sUYoFAA "Jelly – Try It Online")** ### How? ``` ⁽×ʠb3’ịṭµ€K - Main link: list of lists of characters e.g. ["this","is","it"] µ€ - for each word in the input: e.g. "this" ⁽×ʠ - base 250 literal 5416 5416 b3 - converted to base 3 [2,1,1,0,2,1,2,1] ’ - decrement [1,0,0,-1,1,0,1,0] ị - index into the word "tssitsts" ṭ - tack to the word ["this",["tssitsts"]] K - join the results with spaces ["this",["tssitsts"]," is",["issiisis"]," it",["ittiitit"]] - implicit print thistssitsts isissiisis itittiitit ``` --- Alternatively a list of words to list of words is also possible in **11 bytes**: ``` ⁽×ʠb3’ị;@µ€ ``` `⁽×ʠb3’` may also be replaced by `4,⁵Bj-` for the same byte count (`[4,10]` in binary is `[[1,0,0],[1,0,1,0]]` joined by `-1` is `[1,0,0,-1,1,0,1,0]`). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` εD•Lz•3вÍèJ« ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3FaXRw2LfKqAhPGFTYd7D6/wOrT6//9o9cwSdR31zGIgkZ6fkwakKvPVYwE "05AB1E – Try It Online") **Explanation** ``` ε # apply on each word in input D # duplicate the word •Lz• # push the base-255 compressed number 5416 3в # convert to a list of base-3 digits (yields [2, 1, 1, 0, 2, 1, 2, 1]) Í # subtract 2 from each (yields [0, -1, -1, -2, 0, -1, 0, -1]) è # index into the word with these numbers J # join to string « # append to the original word ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~52~~ 49 bytes 3 bytes thanks to Arnauld. ``` (\w)(\w+) $1$2$1 (.)(.)(.)\b $1$2$3$2$2$1$3$2$3$2 ``` [Try it online!](https://tio.run/##JYrBCoMwEETv@xV7yMFQKNrav/ESdSML0Q3ZqPTr01RhHjPMTKLMmyulGU5beVgwnXmZDpqnvTWMd/Wu1OHySikUAkdlhUVchkkOT54gJlmSW1dKn7ZtYY94SCac5dzwOnJG1hqDx6/AlESVZpQ9Y9//F80cQs0/ "Retina – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` lambda s:[i+i[0]+i[-1]*2+i[-2]+(i[0]+i[-1])*2for i in s] ``` [Try it online!](https://tio.run/##RY7BDoIwEETvfMXeioIJEr2Q8CW1B5QWNyls0y0Yvx4pENnDzs7LZjLuG940lLOpH7Nt@mfbAFcSM5SFWtblqs5l1FJl6cFO59KQBwQcgNUcNAeGGqQU2lp0jCxUDlJ01ITtetFktNGbcZ463/S99veiKDY2OpGDmCjoqC19hqhHAIbol@CVWhP1S3u4J2bdRkTj@ne7Hd8c0NodKpUk/@Zr7SqBZZzHIYBJ8TT/AA "Python 2 – Try It Online") I think this is my fastest FGITW and it's not even that impressive. :P [Answer] # [Python 3](https://docs.python.org/3/), 60 bytes ``` lambda k:[x+''.join(x[-int(i)]for i in"01120101")for x in k] ``` [Try it online!](https://tio.run/##RY/NDoIwEITvPMXGSyX@pPhzMfFJag8ora6UbtNWhKdHChr3MjtfNpMd18cH2f2gz5fBlM21KqE@iW7F2PZJaJed2KCNS8ylJg8IaBe8KHa84MUiT6gbEdRyiCrEAGcQgilj0AUMTK5BsDuVcd5u1Gql1Wycp7svm0b5I@d8Zi/H1sBaiippRW@b9B@AMfkxeKJGJ@3pG@4pBFUlRK/p7nD4X4eIxnyhlFn2KwPT26cMxnE@NdVj13z4AA "Python 3 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` F⪪S «ι↑E”o∨↙8”§ι±Iκ→ ``` [Try it online!](https://tio.run/##NYuxCsIwFEVn@xWPTC@QQuNYJ3HqUBGLHxDamAZDEtrXKIjfHuPgnc45cMdZLWNQLud7WACH6Cxh5@NGAy3WG@QCGDDO4V3tLqUQWn74Y3uLAnoVkTVS7hvZSCbgSJ2f9AutgLM2ijSe1Er44L@Vax@SxvZqzUxFPzlvEVIgDVN4ejBBUZXrlOvVfQE "Charcoal – Try It Online") Link is to verbose version of code. Only happened to read @Arnauld's answer after coding this but this is basically a port of it. Explanation: ``` F « Loop over S Input string ⪪ Split at spaces ι Print the word ”o∨↙8” Compressed string 01120101 E Map over each character Iκ Cast character to integer ± Negate §ι Circularly index into word ↑ Print array upwards, prints each element rightwards → Move right ``` [Answer] # sed, 46 bytes ``` s/^\(\(.\).*\(.\)\(.\)\)$/\1\2\4\4\3\2\4\2\4/g ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/LkYjRkMvRlNPC0xBCE0V/RjDGKMYEyA0BtNArJ/@/39qTk5mQXFmMQA "sed – Try It Online") [Answer] # JavaScript (ES6), ~~74~~ 60 bytes ``` s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a) ``` Takes input as an array, and outputs an array. -9 bytes thanks to Programmer5000 **Test cases:** ``` let f= s=>s.map(s=>s+(a=s[l=s.length-1],b=s[0])+a+a+s[l-1]+b+a+b+a) console.log(JSON.stringify(f(['ellipsis']))) // ellipsisessieses console.log(JSON.stringify(f(['goat']))) // goatgttagtgt console.log(JSON.stringify(f(['covfefe']))) // covfefeceefcece console.log(JSON.stringify(f(['programmer5000']))) // programmer5000p000p0p0 console.log(JSON.stringify(f(['up', 'vote', 'down', 'goat']))) // upuppuupup,voteveetveve,downdnnwdndn,goatgttagtgt console.log(JSON.stringify(f(['it', 'is', 'golf', 'yo']))) // itittiitit,isissiisis,golfgfflgfgf,yoyooyyoyo console.log(JSON.stringify(f(['crossed', 'out', '44', 'is', 'still', '44']))) // crossedcddecdcd,outottuotot,4444444444,isissiisis,stillslllslsl,4444444444 ``` [Answer] # Mathematica, 89 bytes ``` ((f[a_]:=#~StringTake~a;k=#<>(q=f@1)<>(w=f[-1])<>w<>f@{-2}<>q<>w<>q<>w)&/@StringSplit@#)& ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 17 bytes Uses the same trick as in [@Jonathan's answer](https://codegolf.stackexchange.com/a/140393/59487). ``` m+dsm@dttkj5416 3 ``` **[Try it here!](https://pyth.herokuapp.com/?code=m%2Bdsm%40dttkj5416+3&input=%5B%27ellipsis%27%5D&test_suite_input=%5B%27ellipsis%27%5D%0A%5B%27goat%27%5D%0A%5B%27covfefe%27%5D%0A%5B%27programmer5000%27%5D%0A%5B%27up%27%2C+%27vote%27%2C+%27down%27%2C+%27goat%27%5D%0A%5B%27it%27%2C+%27is%27%2C+%27golf%27%2C+%27yo%27%5D%0A%5B%27crossed%27%2C+%27out%27%2C+%2744%27%2C+%27is%27%2C+%27still%27%2C+%2744%27%5D&debug=0)** or [**Check out the test Suite** (Give it some time).](https://pyth.herokuapp.com/?code=m%2Bdsm%40dttkj5416+3&input=%5B%27ellipsis%27%5D&test_suite=1&test_suite_input=%5B%27ellipsis%27%5D%0A%5B%27goat%27%5D%0A%5B%27covfefe%27%5D%0A%5B%27programmer5000%27%5D%0A%5B%27up%27%2C+%27vote%27%2C+%27down%27%2C+%27goat%27%5D%0A%5B%27it%27%2C+%27is%27%2C+%27golf%27%2C+%27yo%27%5D%0A%5B%27crossed%27%2C+%27out%27%2C+%2744%27%2C+%27is%27%2C+%27still%27%2C+%2744%27%5D&debug=0) Port of my Python solution, ~~**19 bytes**~~ **18 bytes**: ``` m+dsm@d_k+0j1144 3 ``` [Answer] # Dyalog APL, ~~51~~ 49 bytes Requires `⎕ML←3` ``` ∊{⍺,' ',⍵}/{S←1,L←≢⍵⋄⍵,⍵[∊S(L-0 1)S S]}¨' '(≠⊂⊢)⍞ ``` -9 bytes thanks to @Adám in chat! [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcYgFpB@1NFV/ah3l466grrOo96ttfrVwUBRQx2Qmkedi4BCj7pbgCRIMhqoOFjDR9dAwVAzWCE4tvbQCqA2jUedCx51NT3qWqT5qHfe//@lBQpl@SWpCin55XkK6fmJJQA) [Answer] # [Paradoc](https://github.com/betaveros/paradoc) (v0.2.10), 13? bytes (CP-1252) ``` µ96Qó3BÌDX=v+ ``` [Try it online!](https://tio.run/##K0gsSkzJT/6vVFqgUJZfkqqQkl@ep5Cen1iiFP7/0FZLs8DDm42dDve4RNiWaf@vTfgPAA "Paradoc – Try It Online") Takes a list of words, and results in a list of words on the stack. A small variation on the base-3 trick. Maybe it's time to work on my base 250-whatever compressor. Explanation: ``` μ .. Map the following block over each word (the block is .. terminated by }, but that doesn't exist, so until EOF) .. (The word is on the stack now.) 96Qó .. 96 * 26 (Q in base 26) = 2496, a hack to prevent us from .. needing a space to separate this from the following number. 3B .. Convert 2496 to base 3 to get [1,0,1,0,2,1,1,0] ÌD .. Negate and reverse to get [0,-1,-1,-2,0,-1,0,-1] X .. Push the loop variable: the word being mapped over =v .. Index, vectorize; map over the indices by indexing them .. into the word + .. Concatenate with the original word ``` (Byte-counting question: Now that I'm actually demonstrating this in TIO, it take a list of words on the stack and results in a list of words on the stack, but you can't really do much with that list of words unless you close the block started by µ. Should I count that closing brace?) [Answer] # Wolfram Language/Mathematica, 66 bytes ``` StringJoin[StringSplit[#,""]/.{a_,___,b_,c_}:>{#,a,c,c,b,a,c,a,c}]& ``` Just whipped it up real quick, might have a minor improvement here or there. [Answer] # [Perl 5](https://www.perl.org/), ~~55~~ 49 + 1 (-a) = ~~56~~ 50 bytes *used a trick from @Arrnauld's post to save a couple bytes* ``` say map$_.'01120101 '=~s/\d/substr$_,-$&,1/egr,@F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhN7FAJV5P3cDQ0MjA0MBQQd22rlg/JkW/uDSpuKRIJV5HV0VNx1A/Nb1Ix8Ht///0/MQShcySf/kFJZn5ecX/dX1N9YD6/usmAgA "Perl 5 – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~38~~ 30 bytes *-8 bytes thanks to ASCII-only.* ``` F⪪S «ι§ι⁰ײ§ι±¹§ι±²×²⁺§ι⁰§ι±¹ ``` [Try it online!](https://tio.run/##dY/BCsIwEETv@Yqlp11sQXvtyWMPitAvCG2sgZCEuqmK@O1rBQ/NoXPbneEN09/01AftRK5hAuyis4ytj4k7nqwfkUoooCCCt4JFl@XJaKlZXUdu/WCeaEvYU@ackmMb3QvrElapsxk1GzwQ0RboH6lpG7jLizcbMsBvS6M@IinCHNjAEB4exqBZSTVLdXdf "Charcoal – Try It Online") Link is to verbose version. Note the trailing space. [Answer] # Java 8, 117 bytes ``` a->{int i=0,l;for(String s:a){char c=s.charAt(0),d=s.charAt(l=s.length()-1);a[i++]+=""+c+d+d+s.charAt(l-1)+c+d+c+d;}} ``` Takes the input as a String-array, and modified this original array instead of returning a new one to save bytes. Can most likely be golfed some more.. **Explanation:** [Try it here.](https://tio.run/##tVPLboMwELznK1acQCSISumlFpXyAc0lxygH1xjq1NjIXogixLfT5dHk0mMRmPUOs55ZG6685TtbS3PNvwdV1dYhXAlLGlQ6OTjH755thObewwdXptsAKIPSFVxIOI4pQGtVDiI8oVOmPF94xAjuadDtkaMScAQDGQx8995ROags3WpWWLcUgX/jUSe@uAOR@WScHDBMo23@zDRNtTQlfoXR7iVi/Kzi@BJnQRCLOKfryaTXE0aD9f3AZit186nJyuJoMl1RSw/fQBamfp7A2D/5NvL2ALtAaq1qr3zQs4luEhFOzGjOT3ePskpsg0lNNahNOG9kgnZeZaEv/L9VSstxXQVh20IWcl2R2tnS8aqS7jVN03W1mjrYBq1FSSG3N0Nh/V1USDL0MYxauqBwtysfm7Pey5yUaCF67ve/Bjz9s3pG/sVBv@mHHw) ``` a->{ // Method with String-array as parameter and no return-type int i=0, // Index-integer (starting at 0) l; // Length-integer which we use multiple times for(String s:a){ // Loop over the input array char c=s.charAt(0), // The first character of the word d=s.charAt( // The last character of the word l=s.length()-1); // and set `l` at the same time to `length()-1` a[i++]+= // Append to the current value in the array: "" // String so the characters aren't appended as integers +c // + the first character +d+d // + two times the last character +s.charAt(l-1) // + the single-last character +c+d+c+d; // + the first + last character two times } // End of loop } // End of method ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 106 bytes ``` n=>{for(int i=0,x;i<n.Length;){var h=n[i];x=h.Length-1;char y=h[0],j=h[x];n[i++]=h+y+j+j+h[x-1]+y+j+y+j;}} ``` [Try it online!](https://tio.run/##NU7BboMwDL3nKyxOIErVntNUqnbtDtMOO6AcoswQF@ZMJGMgxLezMG2yrSc/@z09GyrrB9y@AnELr3OI@CGF7U0I8LKIEE0kC6Ond3g2xHmxiJuN5PkS4pAktb62amN1XRo/5MQRSJ0Ok6QLH@/IbXSyWEYzgFNck5aTcn98dZbWpcOsXH3Sh0eCScv0VJZauXIuH6kSV53175JGrusmBUDq3bJTjN/wn2PJsO/pM1DIDlnrTUxg/dhgg9m6q9q8K6RIMdFYl@8GIxBDVzx5Dr7H49tAEe/EmI/FLljFuv0A "C# (.NET Core) – Try It Online") Lambda function that takes input as array of strings, and modifies original array for output ]
[Question] [ The task is simple: your program reads an integer as an input, and prints whether it is a prime or not. You can print "yes/no", "true/false" or anything what unambiguously identifies the result. The challenge is, the code has to work with its rows and columns transposed. To exclude the obvious solution (shortest "simple" solution repeated vertically char-by-char with the use of comments), the metric is a little bit different from the usual code-golf: **Because formatting is very important in this challenge**, the code size is measured in the area of the smallest rectangle the code fits in. In other words, whitespace does count, and the lines should be filled to be of equal length (you don't have to actually do it when you post the solution, for simplicity's sake). For example ``` int main() { return 0; } ``` would have a size of 4\*13 = 52, (and obviously it does not fit either of the two criteria: prime detection and transposable.) Smallest size wins. You can use any language, and any library function except if the sole purpose of that function is to find, generate, or detect primes. # Edit: While the winner would probably be the Golfscript solution, I'll award a 50 point bounty for the best C or C++ solution! [Answer] ## C, 2\*70 2\*60 Prints `y` for primes, nothing otherwise. **EDIT**: Changed code to save 10 chars. Must be run without paramters (so `m=1`). ``` main(m,n){for(scanf("%d",&n);n%++m&&n>1;);n-m||puts("y");}/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ ``` The method for handling the transposition is quite generic, and can be applied to any program. It's based on converting this: ``` abcd/* \\\\*/ ``` To this: ``` a\ b\ c\ d\ /* */ ``` And both mean simply `abcd`. [Answer] # C - 13x13 Reads the input from stdin and prints a `1` for prime and a `0` for not prime. ``` ////m(i;(a=)< ////aans")a;2 //:Di)tc%;;p) //O n{ adfau+ main//bn"o%t4 (a){///f,r-c8 int b///&(-h) ;scanf///bba; ("%d",&///;r} a);for(b///( =a;a%--b;//( );putchar((b <2)+48);} ``` edit: compiles with gcc and clang now, other compilers weren't tested [Answer] ## C, 12x12 chars A two-dimensional solution, unlike [my other answer](https://codegolf.stackexchange.com/a/8626/3544), based on the same code (and like it, prints `y` for prime, nothing for composite). The structure is similar to [Quasimodo's answer](https://codegolf.stackexchange.com/a/8625/3544), but my code is shorter, and I think my usage of comemnts is a bit more efficient, so I can fit 12x12. ``` ////m()s";np ////am{c%n>u ////i,fad%1t ////nnon"+;s main//rf,+)( (m,n//((&m;" ){for(//n&ny scanf(//)&-" "%d",&n)//m) ;n%++m&&//|; n>1;);n-m|| puts("y"); } ``` [Answer] ## GolfScript, 13 × 1 ``` ~.,2>{1$\%!}? ``` GolfScript strikes again! Repeats the input if it is prime, otherwise prints the input concatenated with its smallest proper divisor. Yes, I know that's stretching the definition of "anything what unambiguously identifies the result", but doing anything fancier would cost a few extra characters. If you want nicer output, appending the three characters `;]!` to the code yields `1` for primes and `0` for composite numbers. The algorithm is really inefficient, just brute force trial division from 2 to *n*−1. Most GolfScript operators are only single characters, so this code works just as well transposed. Annoyingly, though, the assignment operator `:` doesn't allow whitespace between itself and its target, so I had to do this entirely without variables. [Answer] ## Perl, 14 x 14 I think I'm getting the hang of this. Specify the number as a command line argument, outputs `0` or `1`. Probably more room for improvement. ``` $ n=pop;$p|= ! ($n%$_)for 2 ..$n/2; print!$p+m~ n(.r =$.i pn$n o%nt p$/! ;_2$ $);p pf + |o m =r ~ ``` [Answer] # Q Abused comments for a symmetric, character inefficient solution. ``` /{///////////////////////////////// {(~)any 0=mod[x;2+(!)x-2]}"I"$(0:)0 /~ /) /a /n /y / /0 /= /m /o /d /[ /x /; /2 /+ /( /! /) /x /- /2 /] /} /" /I /" /$ /( /0 /: /) /0 ``` Takes input from STDIN, returns a boolean. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~1x5~~ 1x3 (~~5~~ 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)) This isn't one big program; each line is a separated alternative program to tackle the prime check (without using the prime builtin). ``` ÑPQ ÒgΘ ÒQP ÕαΘ fQO fs¢ f`Q ``` -2 bytes thanks to *Grimy*. Whitespaces in between lines are no-ops in 05AB1E, and since I only use 1-byte commands, this works fine after transposing. Outputs `1`/`0` for truthy/falsey respectively. [Try the first one online](https://tio.run/##yy9OTMpM/f//8MSAwP//DY0B) or [verify some more test cases for all of them (with eval builtin `.V`)](https://tio.run/##yy9OTMpM/f@/pozL0PTYJD8uv8MTKpUO71cozyzJUMjMKygtUQDyHrVNUlCyr9QL0/n///DEgECuw5PSz80AkoEBXIenntsIZKcF@nOlFR9axJWWEAgA). Transposed: [Try the first one online](https://tio.run/##yy9OTMpM/f//8ESuAK7A//8NjQE). **Explanation:** ``` Ñ # Get a list of all divisors of the (implicit) input-integer # (which would be only 1 and the integer itself for primes) P # Take the product of that list Q # And check if it's equal to the (implicit) input-integer Ò # Get a list of all prime factors of the (implicit) input-integer g # Get the amount of those prime factors by taking the length of the list Θ # Check if that's equal to 1 (so only itself is a prime factor) Ò # Get a list of all prime factors of the (implicit) input-integer including duplicates Q # Check for each if it's equal to the (implicit) input-integer # (1 if truthy; 0 if falsey) P # Take the product of those checks (resulting in either 1 or 0 as well) Õ # Get the Euler totient of the (implicit) input-integer α # Take the absolute difference with the (implicit) input-integer Θ # Check if that's equal to 1 f # Get a list of all prime factors of the (implicit) input-integer without duplicates Q # Check for each if it's equal to the (implicit) input-integer O # And take the sum of that (resulting in either 1 or 0) f # Get a list of all prime factors of the (implicit) input-integer without duplicates s # Swap to get the (implicit) input-integer ¢ # And count how many time it occurs in the list f # Get a list of all prime factors of the (implicit) input-integer without duplicates ` # Dump all the content of this list onto the stack Q # Check if the top two values are equal, or if only a single value is present, it will # use the (implicit) input-integer as second value # For all these program the same applies at the end: # (implicitly output the result with trailing newline) ``` NOTE: If only a truthy/falsey value is valid, and it doesn't necessary has to be distinct, either `Òg` or `Õα` could be used as valid 2-byters, since only `1` is truthy in 05AB1E, and everything else is falsey: [Try both of them for some test cases](https://tio.run/##yy9OTMpM/f@/pozL0PTYJD8uv8MTKpUO71cozyzJUMjMKygtUQDyHrVNUlCyr9QL0/n///CkdK7DU89tBAA). If builtins were allowed, a single `p` would have sufficed: [Try it online](https://tio.run/##yy9OTMpM/f@/4P9/Q2MA) or [verify some more test cases](https://tio.run/##yy9OTMpM/W9oemyS3@EJ9koKj9omKSjZ/y/4r/MfAA). [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 7×1 ``` v̀i'PA@ ``` [Try it online!](https://tio.run/##KyrNy0z@/7/sTEOmeoCjw///5gA "Runic Enchantments – Try It Online") Runic cares not for your feeble attempts at source rearrangement! Conforming to the requirement of still functioning after having the source transposed cost +3 bytes (+2 rectangle width) for the reflection modifier and entry point. [Transposed](https://tio.run/##KyrNy0z@/7@M60wDVyaXOlcAlyOXw///5gA) or [transposed, but leaving the combining character attached to its parent](https://tio.run/##KyrNy0z@/7/sTANXJpc6VwCXI5fD///mAA). [Answer] # dzaima/APL, 8×9 = 72 ``` {t←0,1↓⍳⍵ ←⍵∊∘.×⍨t 0∊ ,∘ 1. ↓× ⍳⍨ ⍵t } ``` [Try the original](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/6hIgZaBj@Kht8qPezY96t3IpAAWA9KOOrkcdM/QOT3/Uu6KES8EAyFcAAy4FHaAEjG2oB2MBTTg8Hc4BmbUCwdtaAmbW/tfketQ3FWhD2qEVQDWGBv8B "APL (dzaima/APL) – Try It Online") or [transposed](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/agUI4CoBcg10DB@1TX7Uu/lR71YuIB9IPeroetQxQ@/w9Ee9K0q4DIBcqHodoDCUaagHZQA1H54OY4NMWQHnbC0Bs2r/a3I96psKNDvt0AqgEkOD/wA)! [Answer] # [Python 3](https://docs.python.org/3/), 28 x 28 size ``` lambda i:i>1 and \ all(i%j for j in range(2,i)) ml=""" " b(" " di" " a%" j i :f io >r 1 j a ni dn r a n g e ( 2 , i ) \)""" ``` [Try it online!](https://tio.run/##fZCxCoQwEET7fMUSEBKwOD2uEbwvsVmJ8VbiKsHmvj6XrIWN3BaPZWbYMNm/x2fjZ/L9kAKuo0Ogjt4NIDu4ZlAYgqFqAb9FWIAYIvI8mbYma9Uaeq013I1Wo7l3xHT0x8Qqmyo/l0lFUp2XfSt8x8JG9DODsnOJKsein64kAYWnPgsnoRG2wlooF8AWDjY3S6U1Xa1fD9vJ7T0SH4Zq8Cb/Q/oB "Python 3 – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~26~~ 25x5 ``` n=>!( P/**//*- = * P =* /** - r >**/= r=>n%--r?P(r):~-r)( /*////= % * /*/n *1 )//>*/ / *//) ``` [Try it online!](https://tio.run/##NYsxDsIwFEP3nMIMlZKU8AsjkLB17hWqUlBQlaBf1JGrh1@JerH1bL/6pZ8Hju@PS/k@ltaX5MNOoyNriaxTHhYdvIUAOGxiqCALD/YhVc7xrdNszl/HRiuSK0mHCvL@S2BS9ghDFCytYGtkbcojM/TSMyI8movYFadmDXVtMOQ052k8TPmp4x6tjsaUHw "JavaScript (Node.js) – Try It Online") Transposed: ``` n=>/* = **1 >**/ ! //) (P=// // P=r=> /*= * * > / */n% /*% /*- * -*/ --r ? P ( r ) : ~ -/* r*/ r)// (n) ``` [Try it online!](https://tio.run/##Jc29DoIwEAfw/Z7i70DSHtZDR7W4MfMKBNFgSGuKYfTV8ajL775zr27p5j6N748L8T6sjV@Dr4XJg/lINbOAdhCxZFovQoAW1PrkaxLWLWLUEGIJBbRTYNOpDMdCziXNgVu2zZrsv2@z5@w36/S7TvUWyeaPJtj1ERPM0iWM8KguGq44VVtSlhZ9DHOchsMUn2bcozGjtesP "JavaScript (Node.js) – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10x11 ``` {⍵∊∘.×⍨1↓⍳⍵ ∊ ∘ . × ⍨ 1 ↓ ⍳ ⍵ } ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqR71bH3V0PeqYoXd4@qPeFYaP2iY/6t0MFOVSAIqDiBlcCnpcCoenA9m9K7gUDIF022QQZzOI2KoABbVAAw@tMFUwUzBXMDRQMDRUMDRSMDRWMDRVMASKWCgYWgIA "APL (Dyalog Unicode) – Try It Online") Corrected the function to comply with the specifications. Thanks @Adám for the heads-up. Returns **0 for truthy, 1 for falsy**. ### How ``` {⍵∊∘.×⍨1↓⍳⍵ ⍝ Dfn. everything below this is a noop up until closing the brace ⍳⍵ ⍝ Range [1..arg] 1↓ ⍝ Dropping the first element (yields [2..arg]) ∘.×⍨ ⍝ Multiplication table for each element in the vector ⍵∊ ⍝ Check if the argument is in the table. ``` The transposed version is the exact same. ]
[Question] [ **This question already has answers here**: [Is this number a prime?](/questions/57617/is-this-number-a-prime) (367 answers) Closed 6 years ago. A [Sophie Germain Prime](https://en.m.wikipedia.org/wiki/Sophie_Germain_prime) is a [prime number](https://en.m.wikipedia.org/wiki/Prime_number) **P** such that **2P+1** is prime as well. Given a *prime number* as input, your task is to determine whether it is a Sophie Germain Prime. [Standard Input/Output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) rules and [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. This is a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'"), so standard rules for this tag apply (returning two distinct and *consistent* values for each case, e.g: `True`/`False`). --- # Test Cases ### Truthy (Sophie Germain primes) These are the first few of them (OEIS [A005384](https://oeis.org/A005384)): ``` 2, 3, 5, 11, 23, 29, 41, 53, 83, 89, 113 ``` ### Falsy ``` 7, 13, 17, 31, 37, 43, 47 ``` --- Please note that answers with explanations are encouraged! It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), hence the shortest code in bytes in every language wins! [Answer] # x86-64 Machine Code, 24 bytes ``` 01 FF FF C7 6A 01 59 89 F8 FF C1 99 F7 F9 85 D2 75 F5 39 F9 0F 94 C0 C3 ``` The above code defines a function that takes a single parameter (the input value, known to be a prime) in `EDI` (following the [System V AMD64 calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI) used on Gnu/Unix), and returns a Boolean result in `AL` (`1` if the input is a Sophie Germain prime, `0` otherwise). The implementation is very similar [to the solution to this challenge](https://codegolf.stackexchange.com/a/131494/58518), since all we really have to do is determine whether a number is prime using as little code as possible, which means an inefficient iterative loop. Basically, we take the input and immediately transform it into `2 × input + 1`. Then, starting with a counter set to 2, we loop through and check to see if the counter is a factor. The counter is incremented each time through the loop. As soon as a factor is found, the loop ends and that factor is compared against `2 × input + 1`. If the factor is equal to the test value, then that means we didn't find any smaller factors, and therefore the number must be prime. And since we have thus confirmed that `2 × input + 1` is prime, this means that `input` must be a Sophie Germain prime. **Ungolfed assembly language mnemonics:** ``` IsSophieGermainPrime: add edi, edi ; input *= 2 inc edi ; input += 1 push 1 pop rcx ; counter = 1 .CheckDivisibility: inc ecx ; increment counter mov eax, edi ; EAX = input (needs to be in EAX for IDIV; will be clobbered) cdq ; sign-extend EAX into EDX:EAX idiv ecx ; EDX:EAX / counter test edx, edx ; check the remainder to see if divided evenly jnz .CheckDivisibility ; keep looping if not divisible by this one cmp ecx, edi ; compare counter to input sete al ; set true if first found factor is itself; ret ; otherwise, set false ``` [Answer] # [Python](https://docs.python.org/), ~~46 43 41~~ 40 bytes -1 byte using [code suggested elsewhere by Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) (`2*n+1` may be calculated as `n-~n` - that is, `2*n+1=n-(-1-n)`) ``` f=lambda n,p=3:p>n or(n-~n)%p*f(n,p+2)>0 ``` A recursive function. Returns `True` if the prime number input, `n`, is a Sophie Germain prime and `False` if not. **[Try it online!](https://tio.run/##HYzBCsIwEETP@hVzkSa6BZuk1Baaf6losKCbUHPx4q/HjYflvZmBTZ/8iGxKCfNzeV1vC5jSbKfkGXFT3H5ZH9IxKKlPRvtzCXFDvr8zVoYyBEvoCV1HMKJmJDjxXvxSb6ybyCAUdEIruxU6yW7Q036XtpXz/yuhaX1DCKomXX4)** Works by multiplying the remainders of the division of the candidate number `n-~n` (which is equal to `2*n+1`) after dividing by `p`, while `p` is less than `n`, starting at `p=3` and incrementing by `2` at each iteration. This is sufficient since `n` is greater that the square root of `2*n+1` (`n-~n`) for `n` greater than `2`. Also, since `2` is a Sophie Germain prime we can start testing with `p=3` and add `2` at each iteration rather than `1`. If the original `n` was greater than `2` the product of the resulting remainders is returned, so if the candidate has any factors the resulting `0` forces the result to be `0` too. The final `>0` forces all the positive products to return `True` and the `0`s to return `False` (to fulfil the "distinct and consistent" requirement). Also beats: ...the 41 byte Python 3 (with sympy): ``` import sympy lambda n:sympy.isprime(n-~n) ``` ...and the 42 byte Python 2 full program **[Try It](https://tio.run/##JY7BDoIwDIbP7Cl6MYDssg2CEPcwCDMswa7BGfXpZ4eH5vuav2lL37gG1GkOi7NlWSa0@uyRXrGqGyXIGvFe/eYATzRSY7Wg3WMEumLicXGM2m163JZpjO4ZxT3skAU8QqUlGAmdBKUkaFY9SGjZO/ZLriFnLD2ToZiGc8NsuW/7ehTF/@axvnAfN0N@N/0A)**: ``` n=2*input()+1 p=3 while n%p:p+=2 print p<n ``` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` f=lambda n,k=3:n%k^k/2>0<f(n,k+2)or k>n ``` [Try it online!](https://tio.run/##JYzRCoMwDEWft6/Ii9CygGtaccr0UwZ1oyjVWKQv@/ousodwTm7CTd8870ylhGH12/TxwBgH23MVX7Gm8f4MSpIb6f2AOHIJwsnn9wwLgyIEi9AgGINAotQhOPFG/HFOd96sRlCtmCRGaOXDCp3srtX99ZKOhTNsPqmA/35dfg "Python 2 – Try It Online") ### Alternate versions ``` f=lambda n,k=3:n%k^1>0<f(n-1,k+2)or k>n ``` ``` f=lambda n,k=3:~-n%k>0<f(n-1,k+2)or k>n ``` ``` f=lambda n,k=3:n%k!=1==f(n-1,k+2)or k>n ``` [Answer] # Mathematica , 13 bytes ``` PrimeQ[2#+1]& ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` {2*)mp} ``` [Try it online!](https://tio.run/##S85KzP1flPm/2khLM7eg9n/df0NDYwA "CJam – Try It Online") [Answer] # Pyth, 4 bytes *Almost an anagram for Pyth.* ``` P_hy ``` [Try it online!](https://pyth.herokuapp.com/?code=P_hy&input=23&debug=0) Other semi-anagrams: `Pt_y`, `P_tyh`. **How?** ``` y # Double h # Increment _ # Negate P # Prime? ``` P for positive argument factorizes; to test primality one should provide the negation of the number tested. [Answer] # MATL, 4 bytes ``` EQZp ``` Prints 1 for a Sophie Germain prime and 0 otherwise. Try it at [MATL Online](https://matl.io/?code=EQZp&inputs=53&version=20.1.1) **Explanation** ``` % Implicitly grab input as a number E % Multiply by 2 Q % Add one Zp % Check if this is a prime number % Implicitly display the result ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` x>p ``` Prints `1` if the *prime number* input is a Sophie Germain prime, and `0` if it is not (prints `1` if double the input plus one is prime). **[Try it online!](https://tio.run/##MzBNTDJM/f@/wq7g/39TAA "05AB1E – Try It Online")** ### How? ``` x>p - implicit input: number n x - pop n then push n, 2*n > - pop 2*n then push 2*n+1 p - pop 2*n+1 then push is prime? (2*n+1) {True:1; False:0} - implicit print of top of stack ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~47~~ ~~43~~ 42 bytes *-4 bytes thanks to Leaky Nun. -1 byte thanks to Erik the Outgolfer.* ``` lambda n:all((n-~n)%i for i in range(2,n)) ``` [Try it online!](https://tio.run/##PY3LCsIwEEX3@Yq7ERKIizxKbaFfoi4iNhqI05Jm48Zfj1MXDgznDBfmru/6XMi2OF1aDq/bPYDGkLOUdPyQOiTEpSAhEUqgxyytJqVanbe6YcLZajiNTsMYDctqBw3P3rGf9h32jKVnMgzTce6Ynm/fX4X4d/z@jgI8a0lUEWVS7Qs "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ×₂+₁ṗ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r///D0R01N2o@aGh/unP7/v6GhMQA "Brachylog – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ḥ‘ÆP ``` A monadic link returning `1` if the *prime number* input is a Sophie Germain prime, and `0` if it is not (yields `1` if double the input plus one is prime, `0` otherwise). **[Try it online!](https://tio.run/##y0rNyan8///hjiWPGmYcbgv4//@/KQA "Jelly – Try It Online")** ### How? ``` Ḥ‘ÆP - Link: number n Ḥ - double n ‘ - increment ÆP - is prime? ``` [Answer] # C, 43 bytes ``` i;f(x){for(x=x*2+1,i=1;x%++i;);return x>i;} ``` Returns `0` if `x` is a Sophie Germain prime, `1` otherwise. [Try it online!](https://tio.run/##fY9BCoMwEEX3niIIQtLYRRKllcGexE2xTcmisQQLAfHsqVgoFPzOch7v/5n@@Oj7lBxZHsVkh8BjGw9aqtK1imIhpSNB4T6@g2fx4mhOzo/seXWei2zK2DKvsKwsz4tb5/OSWa6FoG1iIKkhUQoijfN0A1GFA2sceN5Bzc7xq/YHO//DJyziOoUtg18z2Ko2ur5gdeb0AQ) # C (gcc), 38 bytes ``` i;f(x){for(x=x*2+1,i=1;x%++i;);x=x>i;} ``` [Try it online!](https://tio.run/##fY9BCoMwEEX3niIIQtLYRaLSymBP4qakpMyiaZEuAuLZ02ChUPA7y/94f2bc8e5cSkxeRjX75yTjEA9Wm5oHQ7HSmklRzi5MS@LwFo8rB6mKuRB5XlOOvCyr2xjKWnhplaJt0kDSQWIMRBb32R6iFhd2uPC8g/qd41ftD47hh09YxOsMthr8WoOtdmPXF6zOkj4) [Answer] # [PHP](https://php.net/), 39 bytes prints 1 for true and nothing for false ``` for($d=$n=$argn*2+1;$n%--$d;);echo$d<2; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkrmT9Py2/SEMlxVYlzxYsqGWkbWitkqeqq6uSYq1pnZqcka@SYmNk/f8/AA "PHP – Try It Online") [Answer] # [Neim](https://github.com/okx-code/Neim), 3 bytes ``` ᚫ>𝐌 ``` [Try it online!](https://tio.run/##y0vNzP3//@Gs1XYf5k7o@f/f0NAYAA "Neim – Try It Online") -1 thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx). [Answer] # Julia 0.6, 20 bytes ``` x->∉(0,(x-~x)%3:x) ``` [Answer] # Python 2, 55 bytes: ``` lambda n:len(filter(lambda p:(2*n+1)%p,range(2,n)))>n-3 ``` # Python 2, 48 bytes, different logic: ``` lambda n:all(map(lambda p:(2*n+1)%p,range(2,n))) ``` [Answer] # [Clojure](https://clojure.org/), 60 bytes ``` #((fn[n](some(fn[a](=(mod n a)0))(range 2 n)))(+(* 2 %)1)) ``` [Try it online!](https://tio.run/##FcdBCoAgEAXQqwxE8H9tyn0nCRdSFoWOYXV@s917S0jnm30puPKhT1A0wKazWtwp@p/OYkJMq6g4DiSy092LEWVNj66y5UgaspQP "Clojure – Try It Online") This is an anonymous function - to use the function, do this: ``` (#(...) {number}) ; This will output a value ``` Returns `False` if prime is a Sophie Germain prime, `True` otherwise. [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` *2Ä j ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=KjLEIGo=&input=Nw==) Probably won't get shorter than this... An alternative solution which might be shorter in other languages: ``` ¤Ä n2 j ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=pMQgbjIgag==&input=Nw==) `¤` converts the input to binary, `Ä` appends a 1, and `n2` converts back from base 2 (Japt doesn't have a built-in for converting from binary). [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 17 bytes ``` p->isprime(2*p+1) ``` [Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L9A1y6zuKAoMzdVw0irQNtQ839iQUFOpUaBgq6dAlA8rwTIVAJxlBTSNAo0NXUUwKqLNQwNDDQ1/wMA "Pari/GP – Try It Online") [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 7 bytes ``` ?µ:*2+1 ``` ## Explanation ``` ? PRINT µ the result of the prime-test (-1 for true. 0 for false) :*2+1 with the input times 2 plus 1 as argument ``` [Answer] # [braingasm](https://github.com/daniero/braingasm), ~~8~~ 5 bytes ``` ;*+q: ``` Works like this: ``` ; Input a number *+ Double and increase it q: Print 1 or 0 depending on wether the current number is prime ``` edit: don't need prime check on input [Answer] # MATLAB / Octave, 18 bytes ``` @(x)isprime(2*x+1) ``` Anonymous function. [Try it online!](https://tio.run/##y08uSSxL/Z9mG/PfQaNCM7O4oCgzN1XDSKtC21Dzf5qGkSZXmoYxiDDV5AKS5iCmobHmfwA) [Answer] ## Ruby 2.3.1, 44 bytes ``` lambda{|p|(2...2*p+1).all?{|r|(2*p+1)%r!=0}} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzPycxNyklsbqmoEbDSE9Pz0irQNtQUy8xJ8e@uqYIKAbmqxYp2hrU1v4vKC0pVkjTSwZKKxhxIfOMUXimXChccxSeofF/AA) [Answer] # [C (gcc)](https://gcc.gnu.org/), 46 bytes ``` f(x,i){for(i=2;i<x;)(x-~x)%i++?:(x=i=0);x=!x;} ``` [Try it online!](https://tio.run/##DchBDoIwEADAM31FxZDsBjCgN5fqW0xLdRNsTQWzCcGvV@c4tr1bm7MHaRhXHxOwORIPQgjSfgUrruvrGcSw6ZDE7IS2vOdgp8WNenjPjuPhcVGKw6yfNw7wiexwVcUr/ctDWbmy0R76/oRIqkjjvKSgO1Jb/gE "C (gcc) – Try It Online") Returns `0` if SG prime, `1` otherwise. [Answer] # Julia 0.4, ~~17~~ 16 bytes *1 byte saved thanks to @Tanj* ``` x->isprime(x-~x) ``` `isprime` was deprecated in Julia 0.5. [Answer] # Excel VBA, 59 Bytes Anonymous VBE immediate window function that takes input from cell `[A1]` to and outputs to the vbe immediate window Must be run in a clean module *or* the value of `j` must be reset to `0` before use ``` n=[2*A1-1]:For i=2To n-1:j=IIf(n/i=Int(n/i),i,j):Next:?j<>0 ``` [Answer] # [,,,](https://github.com/totallyhuman/commata), 5 [bytes](https://github.com/totallyhuman/commata/wiki/Code-page) ``` 2×1+p ``` Unlike other golflangs, ,,, doesn't have builtins for incrementing and doubling because I thought I'd rather use those bytes for other things. :P ## Explanation Take input 23 for example. ``` 2×1+p implicit input [23] 2 push 2 [23, 2] × pop 23 and 2 and push 23 * 2 [46] 1 push 1 [46, 1] + pop 46 and 1 and push 46 + 1 [47] p pop 47 and push whether it is prime [1] implicit output [] ``` [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 9 bytes ``` #|2A+1?pz ``` Had to fix an interpreter bug to get this working, so no TIO link. ### Explanation ``` #|2A+1 The last item in the input, which will become n, equals the first item in the input times two, plus one. ? Mode: query. Returns true if n is in the sequence, and false otherwise. pz Sequence: each item is the next prime after the previous item. ``` ]
[Question] [ **This question already has answers here**: ["Hello, World!"](/questions/55422/hello-world) (974 answers) Closed 1 year ago. It's well known that **Brainf\*ck** is very bad at Kolmogorov-complexity problems, for example, it requires around 100 characters just to print "Hello world". However, there might be texts where Brainf\*ck is just very good at. Your task is now to write a program that takes no input, and it displays the following: ``` ☺ ``` That is, a smiley face (ASCII 1, if you browser does not render it). Brainf\*ck can do it in 2 characters. ``` +. ``` **Try to find a language that beats it!** We assume your console can actually display that character (or your font has it, etc.). Shortest code wins. If there are more of the same length, the first wins, but I'll upvote the others as well. **EDIT:** I'm very sorry, I did not think the first post arrives this soon. A quick edit: the language has to be Turing-complete! [Answer] ## FALSE (2) ``` 1, ``` All that reading about BF paid off! False is an ancestor of Brainfuck. [Answer] ## C, 18 chars Far from beating Brainf\*\*k, but as good as C can get (I guess). Only works on little-endian platforms, must run without parameters. ``` main(c){puts(&c);} ``` [Answer] # Micronetics System MUMPS 4.4 (7 chars) ``` w $c(1) ``` [Answer] ## Brainf\*ck (only 2 characters) ``` +. ``` [Answer] Doesn't beat 2 chars, but: ## **PHP 11 chars.** ``` <?=chr(1)?> ``` --- For everyone saying you can simply place the smiley in php and it will output `☺`: Running it with php.exe in the command line gives `Γÿǁ` and placing it in the browser gives `☺` It does **not** work. [Answer] # DC - 2 characters ``` 1P ``` It doesn't require any explanation. [Answer] ### Golfscript, 3 characters ``` "☺" ``` Not a golfscript expert, but I don't believe there is a way to convert an integer into the corresponding ASCII character using only 1 character, so it seems like this is the shortest it can get [Answer] # PHP (1) ``` ☺ ``` Technically this is a valid PHP file (a web server will happily serve it). [Answer] # LaTeX (51/77 characters) Short solution ``` \documentclass{book} \begin{document} ☺ \end{document} ``` Good solution (Compile with `latex main.tex`): ``` \documentclass{book} \usepackage{wasysym} \begin{document} \smiley \end{document} ``` [Answer] # J (3 chars) ``` '☺' ``` The code require appropriate font. According to [Wikipedia](http://en.wikipedia.org/wiki/J) > > In the Wingdings font, the letter "J" is rendered as a smiley face (note this is distinct from the Unicode code point U+263A, which renders as ☺). > > > [Answer] # Q/k (9 chars) Can't do it in 2 unfortunately. ``` -1"\001"; ``` I seem to recall a bug in an older version of the interpreter which produced the other smile symbol in less characters. I'll look it up. Edit: found the quirk. It only appears to work on windows versions of the interpreter: ``` q)1(1b); ☺ ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 9 bytes ``` ``` [Try it online!](https://tio.run/##K8/ILEktLkhMTv3/X0FBgZOLk0tB4f9/AA "Whitespace – Try It Online") ``` ssstl push 1 on stack tlss output char ``` [Answer] # Burlesque - 6 Characters `,1L[sh` Explanation: `,` pops stdin. `1L[` pushes one and convert to char (by codepoint) `sh` is used to switch to pretty format. (Otherwise it would print a leading `'`). [Answer] ## Tcl, 1 ``` ☺ ``` Displays a ☺ with some other stuff. There are rumors that this also works with PHP or other languages. [Answer] ## Arduino, 24 ``` char a=1;Serial.print(a) ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 2 characters Push the number 1 and print it. (Surprised that `1,` also works; -1 from Lyxal.) ``` 1, ``` [Try it online!](https://tio.run/##y05N//8/xlDn/38A "Keg – Try It Online") # [Keg](https://github.com/JonoCode9374/Keg), 1 character Keg is actually Turing-complete, and any unrecognized command acts as a push onto the stack. ``` ☺ ``` [Try it online!](https://tio.run/##y05N////0Yxd//8DAA "Keg – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 characters Just a boring hard-coding. It's encoded in CP437. ``` "☺ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f6dGMXf//AwA "05AB1E – Try It Online") # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` 1ç ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8PDy//8B "05AB1E – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 2 bytes ``` 1] ``` [Run and debug it](https://staxlang.xyz/#c=1]&i=) [Answer] # [chevron](https://ch.superloach.xyz/?inp=&src=PuKYug%3D%3D) - 4 bytes/2 runes ``` >☺ ``` [Answer] # Perl 6 (7 chars) ``` say '☺' ``` I'm bending the rules a little by assuming that a \n is welcome to avoid shell prompt mess. [Answer] # JavaScript, 10 Bytes ``` alert("☺") ``` [![enter image description here](https://i.stack.imgur.com/oeiao.jpg)](https://i.stack.imgur.com/oeiao.jpg) [Answer] # SmileBASIC, 3 characters ``` ?"☺ ``` ​​ [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 5 bytes if a program should output the smile face char. ``` '☺' ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X/3RjF3q//8DAA "PowerShell – Try It Online") --- # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 7 bytes if a program should output the char with code 1. ``` [char]1 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Pzo5I7Eo1vD/fwA "PowerShell – Try It Online") [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 2 bytes ``` 1H ``` [Try it online!](https://tio.run/##S8/PScsszvj/39Dj/38A "Gol><> – Try It Online") Just for completeness. Push a single 1, print all the contents as characters and halt. [Answer] # [MineFriff](https://github.com/JonoCode9374/Minefriff), 5 bytes ``` C1,o; ``` [Try it online!](https://tio.run/##y83MS00rykxL@//f2VAn3/r/fwA "MineFriff – Try It Online") Simply: * Treat the temp register as a character * Add one to the register and push * Output the top item and finish. [Answer] # [C (gcc)](https://gcc.gnu.org/), 15 bytes ``` f(){puts("☺");} ``` ☺ [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oLSkWEPp0YxdSprWtf8z80oUchMz8zTK8jNTNLmquRSAAKjMmqv2PwA "C (gcc) – Try It Online") ]
[Question] [ Interestingly, although there are challenges that work with images, there is no challenge to simply output an image. This is that challenge Goal: output an image in the shortest possible code. Output: Any image output is accepted. Files would be preferable, but most any non-character on the screen will function as an image. An example of this is matplotlib output. For languages that do not support file saving or direct image output, it is acceptable to output what would be the image file's content to any other kind of output. If a language supports saving to a file, this is not an option. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest code that can accomplish the task will win. [Answer] # MATLAB, 3 bytes ``` spy ``` Displays the following image in a figure window. Tested on Matlab R2017b and R2023b. Very old Matlab versions produced a different image. [![enter image description here](https://i.stack.imgur.com/CfgAn.png)](https://i.stack.imgur.com/CfgAn.png) ## Explanation From the [documentation](https://www.mathworks.com/help/matlab/ref/spy.html): > > `spy(S)` plots the sparsity pattern of matrix `S`. Nonzero values are colored while zero values are white. The plot displays the number of nonzeros in the matrix, `nz = nnz(S)`. > > > When called without input arguments, `spy` uses a default image. This is not documented, but it is [well known](https://undocumentedmatlab.com/articles/spy-easter-egg-take-2). [Answer] # [Pyxplot](http://pyxplot.org.uk), 1 byte ``` p ``` `p` is an abbreviation for the `plot` command. When `p` is called as a bare keyword in the default environment, the file `pyxplot.eps` is created in the working directory, showing the default plot axes. [![enter image description here](https://i.stack.imgur.com/S4Fq0.png)](https://i.stack.imgur.com/S4Fq0.png) [Answer] # [Desmos](https://desmos.com/calculator) (or any graphing calculator really), 0 bytes Ok this might be bending the rules quite a bit, but the output is the graph on the right (albeit empty, but still with axis lines and such) upon loading the Desmos Graphing Calculator website. Please say so if this isn't allowed; I will promptly delete this answer if that is the case. [Answer] # PICO-8, 5 bytes ``` spr() ``` Displays sprite 0 at (0,0). Sprite 0 is, conveniently enough, the only sprite that's not empty by default. [![A PICO-8 terminal with a graphic displayed.](https://i.stack.imgur.com/IHe1S.png)](https://i.stack.imgur.com/IHe1S.png) [Answer] # Google Sheets, 17 bytes ``` =sparkline({1;0}) ``` Inserts a diagonal line in the formula cell. See [sparkline()](https://support.google.com/docs/answer/3093289). Multi-cell image with Unicode: (**13 bytes**) ``` =cursorpark() ``` ![cursorpark](https://i.imgur.com/JSYwPWT.png) The function is undocumented. [Answer] # [Mathematica (Notebook interface)](https://www.wolfram.com/mathematica/), 3 bytes ``` Red ``` In recent versions of Mathematica (I don't remember since when), color objects are displayed as colored boxes in the notebook interface. [![enter image description here](https://i.stack.imgur.com/8zPRJ.png)](https://i.stack.imgur.com/8zPRJ.png) [Answer] # HTML (Stack Snippet), 9 bytes ``` <img src= ``` Displays the "broken image" icon. Abuses the fact that the stack snippet wraps the HTML input inside a template HTML document, so what ends being parsed is `<img src=<script type="text/javascript">` (thanks @Kaiido). Google Chrome and Microsoft Edge: [![image of the chrome and edge "broken image" icon](https://i.stack.imgur.com/LSQ8o.png)](https://i.stack.imgur.com/LSQ8o.png) Firefox: [![image of the firefox "broken image" icon](https://i.stack.imgur.com/SWbXt.png)](https://i.stack.imgur.com/SWbXt.png) # HTML, 11 bytes ``` <img src=/> ``` Same thing but works outside of stack snippets. [Answer] # [Uiua](https://www.uiua.org/), ~~9~~ 6 bytes ([SBCS](https://www.uiua.org/pad?src=0_7_1__IyBTaW5nbGUtYnl0ZSBjaGFyYWN0ZXIgZW5jb2RpbmcgZm9yIFVpdWEgMC44LjAKIyBXcml0dGVuIGhhc3RpbHkgYnkgVG9ieSBCdXNpY2stV2FybmVyLCBAVGJ3IG9uIFN0YWNrIEV4Y2hhbmdlCiMgMjcgRGVjZW1iZXIgMjAyMwojIEFQTCdzICLijbUiIGlzIHVzZWQgYXMgYSBwbGFjZWhvbGRlci4KCkNPTlRST0wg4oaQICJcMOKNteKNteKNteKNteKNteKNteKNteKNteKNtVxu4o214o21XHLijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbXijbUiClBSSU5UQUJMRSDihpAgIiAhXCIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX7ijbUiClVJVUEg4oaQICLiiJjCrMKxwq_ijLXiiJril4vijIrijIjigYXiiaDiiaTiiaXDl8O34pe_4oG_4oKZ4oan4oal4oig4oSC4qe74paz4oeh4oqi4oeM4pmtwqTii6_ijYnijY_ijZbiipriipviip3ilqHii5XiiY3iip_iioLiio_iiqHihq_imIfihpnihpjihrvil6vilr3ijJXiiIriipfiiKfiiLXiiaHiip7iiqDijaXiipXiipziipDii4XiipniiKnCsOKMheKNnOKKg-KqvuKKk-KLlOKNouKsmuKNo-KNpOKGrOKGq-Kags63z4DPhOKInuK4ruKGkOKVreKUgOKVt-KVr-KfpuKfp-KMnOKMn-KVk-KVn-KVnCIKQVNDSUkg4oaQIOKKgiBDT05UUk9MIFBSSU5UQUJMRQpTQkNTIOKGkCDiioIgQVNDSUkgVUlVQQoKRW5jb2RlIOKGkCDiipc6U0JDUwpEZWNvZGUg4oaQIOKKjzpTQkNTCgpQYXRoVUEg4oaQICJ0ZXN0MS51YSIKUGF0aFNCQ1Mg4oaQICJ0ZXN0Mi5zYmNzIgoKRW5jb2RlVUEg4oaQICZmd2EgUGF0aFNCQ1MgRW5jb2RlICZmcmFzCkRlY29kZVNCQ1Mg4oaQICZmd2EgUGF0aFVBIERlY29kZSAmZnJhYgoKIyBFeGFtcGxlczoKIwojIFdyaXRlIHRvIC51YSBmaWxlOgojICAgICAmZndhIFBhdGhVQSAi4oqP4o2PLuKKneKWveKJoOKHoeKnuyziipdAQi4iCiMgRW5jb2RlIHRvIGEgLnNiY3MgZmlsZToKIyAgICAgRW5jb2RlVUEgUGF0aFVBCiMgRGVjb2RlIGEgLnNiY3MgZmlsZToKIyAgICAgRGVjb2RlU0JDUyBQYXRoU0JDUwo=)) Outputs an actual image. ``` ↯.⊂.30 ``` `30`  put the number 30 on the stack (numeric arrays of size 30×30+ output as images) `.` duplicate (now we have two 30s on the stack) `⊂` join (into single array, leaving `[30,30]` on the stack) `.` duplicate (now we have two `[30,30]`s on the stack) `↯` reshape (now we have a 30×30 array of 30s on the stack) [Try it on uiua.org](https://uiua.org/pad?src=0_6_1__4oavLuKKgi4zMA==) [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), 15 bytes ``` SCREEN 9 DRAW"D ``` Starting in the middle of the screen, draw a short vertical line in the default white foreground color. Output when run on [Archive.org](https://archive.org/details/msdos_qbasic_megapack): [![A black screen with a tiny white line in the middle and the text "Press any key to continue" at the bottom](https://i.stack.imgur.com/bKlsO.png)](https://i.stack.imgur.com/bKlsO.png) [Answer] # HTML, 8 bytes Outputs a transparent-black canvas image. On most browsers you can right-click "Save image as..." on it. ``` canvas { border: 1px solid } /* not required */ ``` ``` <canvas> ``` [Answer] # Python 3, 18 bytes ``` import antigravity ``` [Answer] # (ba)sh: 20 bytes Black pixel: ``` echo P1 1 1 1 >i.pbm ``` White pixel: ``` echo P1 1 1 0 >i.pbm ``` Utilizes the rather rarely-used PBM format. PPM is it's bigger brother, supporting RGB. Red pixel (more bytes): ``` echo P3 1 1 1 1 0 0 >i.pbm ``` Very useful protocol when piping images from stdout of one program to stdin of another, not so much for anything else. But it's still an image... ### Phylosophical answer: Browser: 1 byte ``` $ ``` It's rendered from a font file onto your screen. It's a shape consisting of multiple bytes. Therefore, it's an image? [Answer] # [PBM](https://netpbm.sourceforge.net/doc/pbm.html), 8 bytes ``` P1 1 1 1 ``` Or, if you don't consider an image file as a valid submission, any program that outputs the bytes above. [Answer] # [Brainfuck](https://github.com/TryItOnline/brainfuck), 60 bytes ``` -[+>++[++<]>]>.>>-[-[-<]>>+<]>->>-[<+>-----]<--.<.>.<.>.<.>. ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70yqSgxMy-tNDl7wYKlpSVpuhY3bXSjte20taO1tW1i7WLt9OzsdKOBEMixA4nogvg22na6IBBro6urZ6NnB8cQM6BGwYwEAA) Outputs the same PBM image of [these](https://codegolf.stackexchange.com/a/267425/73593) [answers](https://codegolf.stackexchange.com/a/267424/73593). [Answer] # Windows, 1 keystroke PrintScreen Output to clipboard [Answer] # JavaScript (browser), ~~58~~ 47 bytes ``` f= _=>document.createElement("canvas").toDataURL() ;document.write(`<a href="${f()}">Right-click to download</a>`) ``` Outputs a transparent 300×150 rectangle. Edit: Saved 11 bytes thanks to @Kaiido. [Answer] # TI-BASIC, 1 byte ``` DispGraph ``` Displays the graph screen. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 41 bytes ``` new System.Drawing.Bitmap(9,9).Save("p"); ``` Creates a transparent 9x9 pixel PNG image. ]
[Question] [ **This question already has answers here**: [Say What You See](/questions/70837/say-what-you-see) (34 answers) Closed 3 years ago. You are too make a program that take an integer as the input and outputs the first what ever that number was of the [look and say sequence](http://en.wikipedia.org/wiki/Look-and-say_sequence). For example: ``` $ ./LAS 8 [1,11,21,1211,111221,312211,13112221,1113213211] ``` The exact way you output the list is unimportant, as long as users can distinctly see the different numbers of the sequence. Here is the catch though. **You can't use any sort of user-defined variable.** For example: 1. No variables, including scoped variables. 2. When you have functions, they can not have a name. (Exception, if your language requires a main function or similar to work, you may have that function.) 3. When you have functions, they can not have named arguments. Also, you may not use a library with specific capabilities relating to the look and say sequence, and you can not access the network, or provide your program with any files (although it can generate and use its own.) This is code golf, so shortest code in characters wins! [Answer] ## Haskell 206 Chars ``` import Data.List import Control.Applicative import Data.Function main= readLn >>= print .(flip take (map read $ fix (("1":). map (concat .(map ((++)<$>(show . length)<*>((:[]). head))). group))::[Integer])) ``` It works by using the group function to group them into groups of equal things. Then it uses applicatives with functions to build a function that simultaneously reads the length, and appends it to with one the elements. It uses a fix and a map to create a recursive definition (point-free.) And there ya go. [Answer] # J (42 chars) Point-free (also called tacit) programming is natural in J. ``` ,@:((#,{.);.1~(1,}.~:}:))&.>^:(<`((<1)"_)) ``` That's a function, to use it you write the code, a space, and the input number. For example, ``` ,@:((#,{.);.1~(1,}.~:}:))&.>^:(<`((<1)"_)) 8 ┌─┬───┬───┬───────┬───────────┬───────────┬───────────────┬───────────────────┐ │1│1 1│2 1│1 2 1 1│1 1 1 2 2 1│3 1 2 2 1 1│1 3 1 1 2 2 2 1│1 1 1 3 2 1 3 2 1 1│ └─┴───┴───┴───────┴───────────┴───────────┴───────────────┴───────────────────┘ ``` Notice the pretty boxes in the output. *Addendum*: Here are a couple of "cheats" I was too bashful to use at first, but now that I've seen other use them first... * Here's a 36 char version with a different "calling convention": replace 8 with the number of terms you want. ``` ,@:((#,{.);.1~(1,}.~:}:))&.>^:(<8)<1 ``` * And if having extra zeroes in the output is OK, here's a 32 char version: ``` ,@:((#,{.);.1~(1,}.~:}:))^:(<8)1 ``` [Answer] # Bash and coreutils, 111 73 chars ``` eval echo 1\|`yes 'tee -a o|fold -1|uniq -c|(tr -dc 0-9;echo)|'|sed $1q`: ``` `uniq -c` is doing the heavy lifting to produce the next number in the sequence. `yes`, `sed` and `eval` create the necessary number of repeats of the processing pipeline. The rest is just formatting. Output is placed in a file called `o`.: ``` $ ./looksay.sh 8 ubuntu@ubuntu:~$ cat o 1 11 21 1211 111221 312211 13112221 1113213211 $ ``` [Answer] ## GolfScript, 36 chars ``` ~([1]\{.[0\{.2$=!{0\.}*;\)\}/](;}*]` ``` Variables are pretty rarely used in GolfScript, and this task certainly doesn't need them. Input is on stdin, output to stdout. For example, the input `8` gives the output: ``` [[1] [1 1] [2 1] [1 2 1 1] [1 1 1 2 2 1] [3 1 2 2 1 1] [1 3 1 1 2 2 2 1] [1 1 1 3 2 1 3 2 1 1]] ``` I may write a detailed explanation of this code later, but at least you can easily tell that it uses no variables by the fact that it doesn't include the variable assignment operator `:` anywhere. [Answer] ## GolfScript (31 chars) ``` ~[]\{[1\{.2$={;\)}1if\}*].n@}*; ``` Adapted from my answer to a [previous look-and-say question](https://codegolf.stackexchange.com/q/2323/194). This one has a less onerous restriction for functional languages, which allows saving 5 chars, but because most answers to the previous question can't be adapted (it's a crazily onerous restriction for non-functional languages) I don't think it makes sense to close it as a dupe. [Answer] # Haskell, 118 chars (80 without imports) ``` import Data.List import Control.Monad main=readLn>>=print.flip take(iterate(ap((++).show.length)(take 1)<=<group)"1") ``` [Answer] # Mathematica, 65 chars ``` FromDigits/@NestList[Flatten@Reverse[Tally/@Split@#,3]&,{1},#-1]& ``` ### Example: ``` FromDigits/@NestList[Flatten@Reverse[Tally/@Split@#,3]&,{1},#-1]&[8] ``` > > {1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211} > > > [Answer] ## J, 37 characters ``` 1([:,((1,2&(~:/\))(#,{.);.1]))@[&0~i. ``` Based on my answer to [the Pea Pattern question](https://codegolf.stackexchange.com/a/4644/737). There may be some potential for shortening here. Usage is as for the other J answer: ``` 1([:,((1,2&(~:/\))(#,{.);.1]))@[&0~i. 7 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 2 1 0 0 0 0 0 0 1 2 1 1 0 0 0 0 1 1 1 2 2 1 0 0 3 1 2 2 1 1 0 0 1 3 1 1 2 2 2 1 ``` It also has the extra zeroes problem my pea pattern answer had. [Answer] # Perl 6: 63 53 characters ``` say (1,*.subst(/(\d)$0*/,{.chars~.[0]},:g)...*)[^get] ``` Create a lazy list of the Look and Say sequence (`1,*.subst(/(\d)$0*/,{.chars~.[0]},:g)...*`), and then get as many elements as specified by the user (`[^get]`, which is an array subscript and means `[0..(get-1)]`), and `say` them all. The lazy list works by first taking 1, then to generate each successive number, it takes the last one it found and substitutes all the sequences of the same digit, as matched by `/(\d)$0*/`, and replaces them with {how many}+{what digit}, or `.chars~.[0]`. The only variables in this code are `$0`, the first capture of the match, and the implicit, topical `$_` variable that bare `.method`s call, and neither of these are user-defined. [Answer] # Dyalog APL, 35 characters [`(⊢,⊂∘∊∘((≢,⊃)¨⊃⊂⍨2≢/0,⊃)∘⌽)⍣(⎕-1)⊢1`](http://tryapl.org/?a=%28%u22A2%2C%u2282%u2218%u220A%u2218%28%28%u2262%2C%u2283%29%A8%u2283%u2282%u23682%u2262/0%2C%u2283%29%u2218%u233D%29%u2363%288-1%29%u22A21&run) `⎕` is evaluated input. In the link I've replaced it with 8, as tryapl.org does not allow user input. No named variables (`a←1`), no named functions (`f←{}`), no arguments (`⍺`, `⍵`). Only composition of functions: * monadic operators—each:`f¨`, reduce:`f/`, commute:`f⍨` * dyadic operators—power:`f⍣n`, compose:`f∘g` * forks—`(f g h)B ←→ (f B)g(h B)`; `A(f g h)B ←→ (A f B)g(A h B)` * atops—`(f g)B ←→ f(g B)`; `A(f g)B ←→ f(A g B)` * 4-trains (fork-atops)—`(f g h k) ←→ (f (g h k))` Primitive functions used: * right:`A⊢B ←→ B` * reverse:`⌽B` * first:`⊃B` * concatenate:`A,B` * not match:`A≢B`, count:`≢B` * enclose:`⊂B`, partition:`A⊂B` * flatten:`∊B` In tryapl.org, if you remove the trailing `⊢1`, which is the argument to this massive composed thing, you can see a diagram of how it's parsed: ``` ⍣ ┌─┴─┐ ┌─┼─┐ 7 ⊢ , ∘ ┌┴┐ ∘ ⌽ ┌──┴───┐ ∘ ┌─┴─┐ ┌┴┐ ¨ ┌─┼───┐ ⊂ ∊ ┌─┘ ⊃ ⍨ ┌─┼───┐ ┌─┼─┐ ┌─┘ 2 / ┌─┼─┐ ≢ , ⊃ ⊂ ┌─┘ 0 , ⊃ ≢ ``` [Answer] # GolfScript, ~~57~~ 43 chars My own approach. Ended up longer than the existing one sadly =(. ``` ~[1 9]{.);p[{...1<^0=?.@(\@(>.,(}do 0=]}@*; ``` Sample output for stdin of `8`: ``` [1] [1 1] [2 1] [1 2 1 1] [1 1 1 2 2 1] [3 1 2 2 1 1] [1 3 1 1 2 2 2 1] [1 1 1 3 2 1 3 2 1 1] ``` Alternate version w/out the `9` sentinel, yet it's longer at 47 characters. I suspect it has more potential: ``` ~[1]{.p[{...1<^.{0=?.@(\@(>1}{;,\0=0}if}do]}@*; ``` [Answer] # Scala 178 ``` (0 to Console.in.readLine.toInt).map(i=>Function.chain(List.fill[String=>String](i)(y=>(('0',0,"")/:(y+" ")){case((a,b,c),d)=>if(d==a)(a,b+1,c)else(d,1,c+b+a)}._3.drop(2)))("1")) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ↑¡oṁ§eL←g;1 ``` [Try it online!](https://tio.run/##AR0A4v9odXNr///ihpHCoW/huYHCp2VM4oaQZzsx////Ng "Husk – Try It Online") 1-indexed. [Answer] ## J 66 (with I/O) ``` ".@(_5}&',@((#,&:":{.);.1~1&(0})&(~:_1|.]))^:(<X)":1')@{.&.stdin'' ``` without IO, scores 43: ``` NB. change the 8 for the number of numbers you'd want ,@((#,&:":{.);.1~1&(0})&(~:_1|.]))^:(<8)'1' ``` Funny question to pose yourself, when is the first 9 to show up? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 10 bytes ``` 1ŒrUFƊ’}¡) ``` [Try it online!](https://tio.run/##y0rNyan8/9/w6KSiULdjXY8aZtYeWqj5//9/CwA "Jelly – Try It Online") Jelly doesn't have variables. ## Explanation ``` 1ŒrUFƊ’}¡) ) For each i in 1..n: 1 Begin with 1 ’}¡ i - 1 times Ɗ ( Œr Run-length encode U Reverse each F Flatten Ɗ ) ``` ]
[Question] [ ## Objective Write a program or function (or equivalent) that sorts out and returns the odd letter in the matrix of random size. ## Details You will be passed a matrix (as a string) as input of random dimensions such as this. ``` bbbbbbbbbb bbbbbdbbbb bbbbbbbbbb bbbbbbbbbb bbbbbbbbbb ``` Your job is to find the letter that doesn't match the rest (in this case, it is `d`, found at line 2, col 6) and to return that letter as output. The matrix will consist of letters `A-Z`, `a-z`, newlines (`\n`, only on ends of rows) and have dimensions ranging from 5x5 to 10x10 (25-100 letters). Standard loopholes apply. This is a code golf challenge; entry with code of least bytes wins. ## Input Input will be passed in through standard input as a string if it is a program or as an argument if a function (or similar). ## Output A single character that is the "odd" in the matrix *or* `None`, `nil`, `NUL`, or the string `"None"` if there is no "odd" character. ## More Examples ``` AAAAAAA AAAAAAA AAAAAAA AAAIAAA AAAAAAA ``` Answer: `I` ``` vvqvvvvvvv vvvvvvvvvv vvvvvvvvvv vvvvvvvvvv vvvvvvvvvv ``` Answer: `q` ``` puuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu uuuuuuuuu ``` Answer: `p` ## Generator Here is a random matrix generator written in Python that you can use to test your program. **Note:** There is a slight chance that it could make a mistake and not put in an odd letter. ``` Instructions 1. Copy this code into a file called `matrix_gen.py`. 2. Run it with `python matrix_gen.py`. --- from random import randint rows = randint(5,10) cols = randint(5,10) charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" neg = charset[randint(0,51)] pos = charset[randint(0,51)] p_used = 0 comp = 0 matrix = "" while comp < rows: row = "" while len(row) < cols: if not p_used and not randint(0,10): p_used = 1 row = row + pos else: row = row + neg row = row + "\n" matrix = matrix + row comp += 1 print matrix[:-1] ``` [Answer] # [Python 3](https://docs.python.org/3/), 27 bytes ``` lambda x:min(x,key=x.count) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKjczT6NCJzu10rZCLzm/NK9E839BUWZeiUaahpKSUllZYRkEcJXBAUEmUKOm5n8A "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~12 10~~ 7 bytes ``` -.}./.~ ``` [Try it online!](https://tio.run/##y/r/P81WT0FXr1ZPX6/uf2pyRr5CmkJxSUpmnrr6/1IY4EJhpWIRI5cFAA) ``` /.~ Group identical items together }. Remove one item from each group -. Remove the rest from the input ``` ### 10 byte version ``` -._1 1{\:~ ``` hisss... ``` \:~ Sort down _1 1{ Take the last character (which is a newline) and the second one. -. Remove those from the input ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~8~~ 4 bytes ``` oḅ∋≠ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtZHHd2POhf8/6@UCARJiYlciRCAi1b6HwUA "Brachylog – Try It Online") ## Explanation I haven't used Brachylog before, so this may not be optimal. ``` oḅ∋≠ Input is a string. o Sort the input. ḅ Split it into blocks of equal elements. ∋ There is a block ≠ whose elements are all different. That block is the output. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 2 bytes Saved 2 bytes thanks to *Adnan* ``` .m ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fL/f/fyUlpSQ44AKTKQhmEm4mUCMA "05AB1E – Try It Online") **Explanation** ``` .m # push a list of the least frequent character(s) in input ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~7~~ 6 bytes **Solution** ``` *<#:'= ``` [Try it online!](https://tio.run/##y9bNz/7/X8tG2UrdVqmsrLAMAmLyyuCAGLbS//8A "K (oK) – Try It Online") **Example:** ``` *<#:'="vvqvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv" "q" ``` **Explanation:** Found a slightly shorter approach: Evaluated right-to-left: ``` *<#:'= / the solution = / group matching items together #:' / count (#:) each (') < / sort ascending * / take the first one ``` **Notes:** Whilst I'm expecting the bonus aspect of this challenge to get dropped, this solution will return the newline character `\n` if there is no odd character: ``` *<#:'="vvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv\nvvvvvvvvvv" "\n" ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 46 bytes ``` p(L):-select(X,L,Y),\+member(X,Y),writef([X]). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/v0DDR9NKtzg1JzW5RCNCx0cnUlMnRjs3NTcptQjIB/LKizJLUtM0oiNiNfVA6hOSQCAmD51KgfMSNPUA "Prolog (SWI) – Try It Online") Or if the standard **true** output from prolog queries is not okay: # [Prolog (SWI)](http://www.swi-prolog.org), 48 bytes ``` Z*L:-select(X,L,Y),\+member(X,Y),char_code(Z,X). ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P0rLx0q3ODUnNblEI0LHRydSUydGOzc1Nym1CMgH8pIzEovik/NTUjWidCI09f7/j9BKSAKBmDx0KgXOS9ADAA "Prolog (SWI) – Try It Online") **Explanation** ``` Find the first element X in the input that when removed, results in output that does not contain X then depending on the version above either: print X as a character or return X as an atom ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~93~~ ~~92~~ ~~90~~ ~~66~~ 62 Bytes Much shorter as a function ``` t;f(char*p){for(t=*p;*p;)t^*p++?putchar(*p^*--p?*p:t),*p=0:0;} ``` [Try it online!](https://tio.run/##tUxBCoQwELv3FR5nRgtedRAfIgpStq4HdbDTk/j2rl32CxtCSEiIs4tzKSl7cO/5JMHLHydoR8IPUSeSsuwlaq6BZCJrpSdpFSuSrm5rvtM2rzuguUzxIA@LMDTNyN@c/3h5aYCAjD6ruZPEH0z8l/sA "C (gcc) – Try It Online") test code ``` main() { char s[99]; for(;gets(s);)f(s); } ``` old version is a program # C 86 Bytes ``` char*p;s[9];main(t){for(;p=gets(s);)for(t=*p;*p;)t^*p++?putchar(*p^*--p?*p:t),*p=0:0;} ``` Outputs the odd character, or nothing. run like this; ``` C:\eng\golf>python matrix_gen.py | a.exe X C:\eng\golf>python matrix_gen.py | a.exe G C:\eng\golf>python matrix_gen.py | a.exe x C:\eng\golf>python matrix_gen.py | a.exe C:\eng\golf>python matrix_gen.py | a.exe J ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 13 bytes ``` s(O`. (.)\1+ ``` [Try it online!](https://tio.run/##K0otycxL/P@/WMM/QY9LQ08zxlCb6/9/RwjgwkJ7IvEB "Retina – Try It Online") ### Explanation ``` s(O`. ``` Sort all characters. ``` (.)\1+ ``` Remove any characters that appear at least twice. [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ◄= ``` [Try it online!](https://tio.run/##yygtzv7//9H0Ftv///8nwQEXmExBMJNwMwE "Husk – Try It Online") This is a function taking a string as input and returning a character. It takes the minimum of the input string when comparing characters for equality (i.e. it returns the character that is equal to the least number of other characters). [Answer] # C, 94 bytes Return by pointer. If none, return `\0`. This will cause memory leaks. Assuming `int` is 4 bytes. ``` *t;f(c,p,i)char*c,*p;{t=calloc(64,8);for(*p=-1;*c;c++)t[*c]--;for(i=0;++i<128;)!~t[i]?*p=i:0;} ``` [Try it online!](https://tio.run/##nUxBDoIwELzzirWntpQEiTHGlXDyFcihbII0UWlqPRH4OlbQqybOYWcyOzOUnImmSXpsOCmrjKBWO0lKWux9Tvpy6YhvN2onsOkclzZP1igJKY6FLyVVSTI/TJ5iHJvDOtuhWI2@NFURwmaf4jARn1dBC@jhJaEuswpyYClDaLhWUAsE@/B3PsoaCqhhD@zoHAv2EEVXbW5cRH0EAcsALpozPeN0C8e/WX/jMPmptj@iX6r6j@owPQE "C (gcc) – Try It Online") [Answer] # Mathematica, 27 bytes ``` Last@*Keys@*CharacterCounts ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMRByzu1sthByzkjsSgxuSS1yDm/NK@k@H9AUWZeiUNatFISHHCByRQEMwk3Uyn2PwA "Wolfram Language (Mathematica) – Try It Online") *-1 byte from Martin Ender* [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~15~~ 20 bytes ``` fold -1|sort|uniq -u ``` [Try it online!](https://tio.run/##S0oszvj/Py0/J0VB17CmOL@opKY0L7NQQbf0//88KOAiyPDMAwA) **Explanation:** `fold`s the input to `1` character per line, `sort`s it into groups of matching letters, then prints only lines that are `uniq`ue. *Thanks [@Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul) for catching and helping fix a problem with this approach.* [Answer] # [Pyth](https://github.com/isaacg1/pyth), 4 bytes ``` ho/Q ``` **[Try it here!](https://pyth.herokuapp.com/?code=ho%2FQ&input=%22ggg%5Cnegg%5Cnggg%22&debug=0)** [Answer] # Perl 5, 17 + 3 (-00p) -25% = 15 bytes ``` /(.)\1/;s/ |$1//g ``` [try it online](https://tio.run/##K0gtyjH9/19fQ08zxlDfulhfxbCGS18//f//JDjgApMpCGYSbua//IKSzPy84v@6BgYFAA) [Answer] # Matlab, 25 Bytes ``` a=input('');a(a~=mode(a)) ``` The input "a" where "a" isn't the mode of "a". Outputs empty array for no oddball. [Answer] # Java 8, 85 bytes This is a lambda from `String` to `String` (e.g. `Function<String, String>`). It's essentially a copy of [Luca's solution](https://codegolf.stackexchange.com/a/149371), but I've pared down the string sorting a bit. ``` s->new String(s.chars().sorted().toArray(),0,s.length()).replaceAll("(.)\\1+|\\n","") ``` [Try It Online](https://tio.run/##jVFNT8MwDD2vv8LKKRFdBFfGJk1InEAcOFIOXpttKVlSJe5QBf3tJaUVaB8Si6LYennv2XFK3OPUVcqWxXtX1Sujc8gNhgBPqC18JpMRDIQUw1pbNFBGlaxJG7mubU7aWfkwJncv5LXdpDDERa8onoviUREpD/MuTBdWfYzXPMh8iz5wIYPzpIqYkFt6jw0X6XUapFF2Q1suhPSqMpirpTGccSmy7ObqK8ssSxkT3WSWHLe6d7qAXXwFH2q9vgH6TRD9oya/UI5BBZjDX08R7BkjRZYuOrC@zhGHYb8ifJisThBkrUgvclwd6v7LLrU93@i51gfHdhaPtfMwTg7wPk4JbodhiXE8TSC1k64mWUUSGcsPvlpiVZmG/0iF6B3bJO62@wY) [Answer] ## Haskell, 33 \* 0.75 = 24.75 bytes ``` f s=[c|[c]<-(`filter`s).(==)<$>s] ``` Returns an empty list if there's no odd character. [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2DY6uSY6OdZGVyMhLTOnJLUooVhTT8PWVtNGxa449n9uYmaegq1CSr4Cl4KCQkFRZl6JgopCmoJSIgjE5CGoZBQeiFIipCWRWC2K@LT8BwA "Haskell – Try It Online") For each char `c` in the matrix (given as a string `s`) make a string of all chars in `s` that are equal to `c` and keep those of length 1. [Answer] # JavaScript (ES6), 37 bytes Returns `null` if there's no odd letter. ``` s=>s.match(`[^ ${s.match(/(.)\1/)}]`) ``` ### Test cases ``` let f = s=>s.match(`[^ ${s.match(/(.)\1/)}]`) console.log(f( 'bbbbbbbbbb\n' + 'bbbbbdbbbb\n' + 'bbbbbbbbbb\n' + 'bbbbbbbbbb\n' + 'bbbbbbbbbb' )) console.log(f( 'AAAAAAA\n' + 'AAAAAAA\n' + 'AAAAAAA\n' + 'AAAIAAA\n' + 'AAAAAAA' )) console.log(f( 'vvqvvvvvvv\n' + 'vvvvvvvvvv\n' + 'vvvvvvvvvv\n' + 'vvvvvvvvvv\n' + 'vvvvvvvvvv' )) console.log(f( 'puuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu\n' + 'uuuuuuuuu' )) console.log(f( 'AAAAA\n' + 'AAAAA\n' + 'AAAAA\n' + 'AAAAA\n' + 'AAAAA' )) ``` [Answer] # Common Lisp, 47 bytes ``` (lambda(s)(find-if(lambda(x)(=(count x s)1))s)) ``` [Try it online!](https://tio.run/##S87JLC74r1FQlJmXrKDxXyMnMTcpJVGjWFMjLTMvRTczDSZSoalhq5GcX5pXolChUKxpqKlZrKn5X8nR0ZELjAsdlYB8AA) Returns the odd letter or NIL if it does not exist. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ċ@ÐṂ ``` [Try it online!](https://tio.run/##y0rNyan8//9It8PhCQ93Nv3//z8RArhARBKUBgIA "Jelly – Try It Online") Return `\n` (a single newline) in case there is no odd character. Obviously `\n` is not a printable character. Coincidentally this is exactly the same algorithm as Mr.Xcoder Python answer. (I came up with it independently) Explanation: ``` ÐṂ Ṃinimum value by... ċ@ ċount. (the `@` switch the left and right arguments of `ċ`) ``` That works because in a `m×n` matrix: * If there exists odd character: There are `m-1` newlines, 1 odd characters and `m×n-1` normal character, and `1 < m-1 < m×n-1` because `5 ≤ m, n ≤ 10`. * If there doesn't exist odd character: There are `m-1` newlines and `m×n` normal character, and `m-1 < m×n`. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 54 bytes ``` i=>i.GroupBy(x=>x).FirstOrDefault(g=>g.Count()<2)?.Key ``` [Try it online!](https://tio.run/##tY3BSsRAEETv8xV9nAGdg9dssuCuK4uKooLncdLGwWx37J5ZN8h@ewyi4A9Yl6qioF7U08iCU9FEHTyMmnFXmb/NXyd6r4yJfVCFO@FOwg4@DcBQnvsUQXPIs@05tXATEln3vQKsmJR79E@SMs4vaAk/YFMoLjTLTDiB@Bpk2dgp1U3yl8JlOB/toW4Ozm@SaL6VNb6E0mfb1U3nV1woW7c4c0t/hePk/Jb2/Ib2F7Ulf4@hfeQLaq1zrjoep6H8yJT/Sl8 "C# (.NET Core) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~91~~ ~~86~~ ~~82~~ ~~79~~ 71 bytes ``` f(char*s){for(;*++s==10?s+=2:0,*s;)if(*s^s[-1])return*s^s[1]?*s:s[-1];} ``` [Try it online!](https://tio.run/##pY7BjsIgEEDP5SsmJCYD1aT1KCGe/AqtCWJZmyi7YaqXpt9eKerBi7u6c2BmHvMY7OzL2mFwaA8mSBKd@w6oZJ6T1mWxpFzPF8VUkhKNQ0lbWs/KSoS6PQef2rJaSlokrPphf3sHjIAOWDY2sFvPK9DAC64ianwLF3OMwKERiThMQEMhWJb9nFtCvgqBC8Wy@kj1CEP0HPKJ3Xg@jePxrmfsZBqPgnUMYtyWqVTvkZsUGx@P9p7Nqzyuu6uHX0ZfqA90@lz9U949q6t/f/gdtR@u "C (gcc) – Try It Online") * Thanks to **Gastropner** for the xor and ? tricks (-3 bytes) * Reworked the compare version to fix bugs and used **Gastropner** magic from comments. **Explanation:** Compare current and previous char while skipping newlines. If different, compare to next char. This tells us if we return current or previous char. The function returns the "odd" char value if it exists or 0 if the array is not odd. We get away with the "next" char check because there is always a newline before the `\0` char. If there is no odd char, we intrinsically return the \0 from the for loop. --- **Older, sexier xor code Explanation:** Make a running xor mask of the next 3 string values. If they are all the same, then the value will be equal to any of the three. If they are different, then the 2 identical will cancel each other out leaving the unique. Must factor /n before the xor or it gets messy. Also have to check 2 chars for inequality in case s[0] is the odd value. This costs the extra || check. ``` v;f(char*s){while(s[3]){s[2]==10?s+=3:0;v=*s^s[1]^s[2];if(v^‌​*s++||v^*s)break;}} ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~26~~ 25 bytes *1 byte saved thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)* ``` @(x)x(sum(x(:)==x(:)')<2) ``` Anonymous function that takes a 2D char array as input, and outputs either the odd letter or an empty string if it doesn't exist. [**Try it online!**](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzQqO4NFejQsNK09YWRKpr2hhp/k/TiFZ3hAB1awXcTE800VjN/wA) [Answer] # [Stax](https://github.com/tomtheisen/stax), 2 bytes ``` |! ``` [Run and debug it](https://staxlang.xyz/#c=%7C%21&i=%22%22%22%0AAAAAAAA%0AAAAAAAA%0AAAAAAAA%0AAAAIAAA%0AAAAAAAA%0A%22%22%22) [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ü l1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=/CBsMQ&input=ImJiYmJiYmJiYmIKYmJiYmJkYmJiYgpiYmJiYmJiYmJiCmJiYmJiYmJiYmIKYmJiYmJiYmJiYiI) ``` ü l1 :Implicit input of multiline string ü :Group & sort l1 :Filter elements of length 1 :Implicit output of last element ``` [Answer] # [Alice](https://github.com/m-ender/alice), 16 \* 75% = 12 bytes ``` /-.nDo& \i..*N@/ ``` [Try it online!](https://tio.run/##S8zJTE79/19fVy/PJV@NKyZTT0/Lz0H//39HCODCQnsi8QE "Alice – Try It Online") Outputs `Jabberwocky` if there is no duplicate character. ### Explanation ``` /...@ \.../ ``` This is a framework for linear programs that operate entirely in Ordinal (string processing mode). The actual code is executed in a zigzag manner and unfolds to: ``` i..DN&-o i Read all input. .. Make two copies. D Deduplicate one copy, giving only the two letters and a linefeed. N Multiset difference. Removes one copy of each letter and one linefeed. Therefore it drops the unique letter. &- Fold substring removal over this new string. This essentially removes all copies of the repeated letter and all linefeeds from the input, leaving only the unique letter. . Duplicate. n Logical NOT. Turns empty strings into "Jabberwocky" and everything else into an empty string. * Concatenate to the previous result. o Print the unique letter or "Jabberwocky". ``` Instead of `&-`, we could also use `ey` (transliteration to an empty string). Alternatively, by spending one more character on stack manipulation, we could also deduplicate the input which lets us remove the unwanted characters with `N`, but it's still the same byte count: ``` i.D.QXN.n*o@ ``` ## [Alice](https://github.com/m-ender/alice), 13 bytes ``` /N.-D@ \i&.o/ ``` [Try it online!](https://tio.run/##S8zJTE79/1/fT0/XxYErJlNNL1///39HCODCQnsi8QE "Alice – Try It Online") This is the solution without the bonus, it's simply missing the `.n*`. [Answer] # [Retina](https://github.com/m-ender/retina), 22 bytes ``` !`(.)(?!.*\1)(?<!\1.+) ``` [Try it online!](https://tio.run/##K0otycxL/P9fMUFDT1PDXlFPK8YQSNsoxhjqaWv@/@8IAVxYaE8kPgA "Retina – Try It Online") Only requires height and width of at least 3, rather than 5. [Answer] # APL+WIN, 16 bytes ``` (1=+/a∘.=a)/a←,⎕ ``` Prompts for screen input and either outputs odd letter or nothing if there is no odd letter [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 39 bytes ``` ([char[]]"$args"|group|sort c*)[0].Name ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyM6OSOxKDo2VkklsSi9WKkmvSi/tKCmOL@oRCFZSzPaIFbPLzE39f///@pJcMAFoVIQzCScTHUA "PowerShell – Try It Online") Takes input as a string with newlines (as specified in the challenge), converts it to a `char`-array. We then `Group-Object` the characters, so that characters are grouped together by their names, then `sort` based on the `c`ount. This ensures that the lonely character is first, so we take the `[0]` index and output its `.Name`. If newline is acceptable for "nothing" then this qualifies for the bonus. [Answer] # [Perl 6](https://perl6.org), ~~27~~ 24 -25% = 18 bytes ``` *.comb.Bag.min(*.value).key ``` [Test it](https://tio.run/##tU@7TsQwEOz3K1anCDkhcSSKKwiJgC4NDXSEIg@DrMvDZzs@ouO@jI4fC7kk9ygQVIy09ozXu5oRTJbLvlUMzZLmAVQdXuRNwTDsHZo3VUbv0zda8Zo41KRly2y6Yl0/frzVTGkM0XLiB6rKVgqqJa@oEiXXxMekvsQbkmzsCJ9H8YEWvvguXpuh1IoLj1VCd/bXJ33UMoC9jadhZwCiTOt5v49XAbw2cpZehBavRatdtNi7YLlmBW4BkSvcGydT1z5ru7jYTq9jIuInG98ec6lGauIdkg02hmw7DKPT7AJ2fXYEjGdxotkvtIC7CT/d8bmOwZi1mQDmiL/pGkQ7A9p/Y@Ib "Perl 6 – Try It Online") ``` {%(.comb.Bag.invert){1}} ``` [Test it](https://tio.run/##tY@7TsMwFIb38xRHVUBOSRzB0IGQCNiysMBGGXIxKGourm8lCnkyNl4sNBe1HRBMfJLt//exj/7DmShWvZYMzYqmPpQNnqd1xjDo2zNC07pM6H38RvPKMKHs9rLr@vHVrWJSYYDWMnqgstCCUyXykkpe5Ip4uK4u8Iasd3aIz6P5QAtfPAevzX7JTc5dVnLV2F@f9FEJH4YMT/uePvAirub@Hl758FqL2bohWnnFtXLQYu@cpYpl2AJiLnFITaaqfVJ2cNFOt@MwxFvvPHscSdZCEXdJTVxoNsTYsKbDIDz@XUDXJwdg3LOjTH6RGdxN/HRGpz4CY7ZmAsyBv@UWuJ4B/W@KfwM "Perl 6 – Try It Online") This will [return an undefined value](https://tio.run/##K0gtyjH7X1qcqlBmppdszZVbqaCWnJ@SqmD7v1pVQy85PzdJzykxXS8zryy1qESz2rC29j9YlUpJanGJgq1CoVVJvr6rn4u@NVciGOClgAq5uIoTKxVSUtMy81JTFEB2aYDN0vwPAA "Perl 6 – Try It Online") when given an input that doesn't have an odd character out. ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 %( # coerce into a Hash .comb # split the input into graphemes (implicit method call on 「$_」) .Bag # turn into a weighted Set .invert # invert that (swap keys for values) returns a sequence ){ 1 } # get the character that only occurs once } ``` ]
[Question] [ ## Challenge Suppose you have a list of numbers, and a target value. Find the set of all combinations of your numbers which add up to the target value, returning them as list indices. ## Input and Output The input will take a list of numbers (not necessarily unique) and a target summation number. The output will be a set of non-empty lists, each list containing integer values corresponding to the position of the values in the original input list. ## Examples ``` Input: values = [1, 2, 1, 5], target = 8 Output: [ [0,1,3], [1,2,3] ] Input: values = [4.8, 9.5, 2.7, 11.12, 10], target = 14.8 Output: [ [0,4] ] Input: values = [7, 8, 9, -10, 20, 27], target = 17 Output: [ [1,2], [0,3,4], [3,5] ] Input: values = [1, 2, 3], target = 7 Output: [ ] ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins! [Answer] # JavaScript (ES6), 96 bytes Takes input in currying syntax `(list)(target)`. ``` a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s)) ``` ### Test cases This would fail on the 2nd test case if 4.8 and 10 were swapped because of an IEEE 754 precision error -- i.e. `14.8 - 4.8 - 10 == 0` but `14.8 - 10 - 4.8 != 0`. I think [this is fine](https://codegolf.meta.stackexchange.com/a/14459/58563), although there may be a more relevant reference somewhere in meta. ``` let f = a=>s=>a.reduce((b,_,x)=>[...b,...b.map(y=>[...y,x])],[[]]).filter(b=>!b.reduce((p,i)=>p-a[i],s)) console.log(JSON.stringify(f([1, 2, 1, 5])(8))) console.log(JSON.stringify(f([4.8, 9.5, 2.7, 11.12, 10])(14.8))) console.log(JSON.stringify(f([7, 8, 9, -10, 20, 27])(17))) console.log(JSON.stringify(f([1, 2, 3])(7))) ``` ### Commented ``` a => s => // given an array a[] of length N and an integer s a.reduce((b, _, x) => // step #1: build the powerset of [0, 1, ..., N-1] [ ...b, // by repeatedly adding to the previous list b[] ...b // new arrays made of: .map(y => // all previous entries stored in y[] [...y, x] // followed by the new index x ) // leading to: ], // [[]] -> [[],[0]] -> [[],[0],[1],[0,1]] -> ... [[]] // we start with a list containing an empty array ) // end of reduce() .filter(b => // step #2: filter the powerset !b.reduce((p, i) => // keeping only entries b p - a[i], // for which sum(a[i] for i in b) s // is equal to s ) // end of reduce() ) // end of filter() ``` [Answer] # [Python 2](https://docs.python.org/2/), 110 bytes ``` lambda a,n:[b for b in[[i for i in range(len(a))if j&1<<i]for j in range(2**len(a))]if sum(a[c]for c in b)==n] ``` [Try it online!](https://tio.run/##RcpBCsIwEEDRq8xKkjKbBASR5iRjFpPa6JR2WmJdePrYFsHdh/@Wz/qc1dccbnXkKd0ZGPVKCfJcIIEokRwtW0NhffRm7NWwtZJhOLm2lbj/4f990/xI3MzrPRmm7kDdjpINQWNdiugK2ZBDjw7PES@2fgE "Python 2 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~85~~ 84 bytes ``` function(l,k){N=combn o={} for(i in I<-1:sum(l|1))o=c(o,N(I,i,,F)[N(l,i,sum)==k]) o} ``` [Try it online!](https://tio.run/##FYvBCoMwEETv@Yo97sIajLTYirkWvPgDpZcGAkHNgq0n67en62EYmPdmLRH6qsQth2@SjDNPtI8@yPLORvx@mCgrJkgZhr5y3WdbcP45IvEBhUccODE/6DnqNbFi8n56kZGjRAx4sTeGu70yNLZlcM66RqsmdorInI7up8RQuVq9M63ylsof "R – Try It Online") 1-indexed. `combn` usually returns a `matrix`, but setting `simplify=F` returns a `list` instead, allowing us to `c`oncatenate all the results together. `combn(I,i,,F)` returns all combinations of indices, and we take `N(l,i,sum)==k` as an index into that list to determine those which equal `k`. [Answer] # [J](http://jsoftware.com/), ~~32~~ 31 bytes ``` (=1#.t#])<@I.@#t=.1-[:i.&.#.1"0 ``` [Try it online!](https://tio.run/##y/r/P81WT0HD1lBZr0Q5VtPGwVPPQbnEVs9QN9oqU09NT1nPUMngf2pyRr6ChUKagqGCERCbcoEFDE30QGIg0lLPVMFIz1zB0FDPEKjCQAGqwhwobw7UaakQDxQ0AiJzqJQ51DRjhf8A) ``` 1-[:i.&.#.1"0 Make a list of all masks for the input list. We flip the bits to turn the unnecessary (0...0) into (1...1) that would be missing. Define it as t. (=1#.t#]) Apply the masks, sum and compare with the target <@I.@# Turn the matching masks into lists of indices ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 14 bytes ``` m, à f_x!gU ¥V ``` [Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=bSwg4CBmX3ghZ1UgpVY=&input=WzcsIDgsIDksIC0xMCwgMjAsIDI3XQoxNwoKLVI=) ### How it works ``` m, à f_x!gU ¥V Implicit: U = input array, V = target sum m, Turn U into a range [0, 1, ..., U.length - 1]. à Generate all combinations of this range. f_ Filter to only the combinations where x the sum of !gU the items at these indices in U ¥V equals the target sum. Implicit: output result of last expression ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~104~~ ~~102~~ 98 bytes ``` import StdEnv @n=[[]:[[i:b]\\i<-[0..n-1],b<- @i]] ?l n=[e\\e<-tl(@(length l))|sum(map((!!)l)e)==n] ``` [Try it online!](https://tio.run/##Dc2xCoMwFEDR3a94bgkY0UIXUXRoh0I3xyRD1NQGXp5SY6HQb2/qdJcDd0RrKPpl2tGCN46i8@vyCtCH6UrvpKNGSl1J6apBK@VqIYs8J1HqbKgFdE7rpEU4lFXK1iIg6xhamsMTkPPvtnvmzcpYmnLkljcN6dgHcxwaaEGWGZwyEEfOGor4Gx9o5i2K2z1ePmS8G7c/ "Clean – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` x#t=[i|i<-tail$concat<$>mapM(\z->[[],[z]])[0..length x-1],t==sum[x!!k|k<-i]] ``` [Try it online!](https://tio.run/##bc1LCoMwEIDhfU8xRRctJCFpK1ow3qAnSGcRrNRgfFBTEPHuaaQboV3MLOb/YGo9NpW13k@Rk8osJqdOGxuXfVdql8dFq4fb4T7TQikkakY8Ks6Yrbqnq2GiAomTcny3atrvm6XJqUH0rTYdSHj0O4DhZToHMShB4EQg7ASjbBsuLCNwZUnoLA1CMLFCjpEIaStDXSkBKnjQ66RBpb9vzhj9udLvd@4/ "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ị³S= JŒPçÐf ``` [Try it online!](https://tio.run/##ASQA2/9qZWxsef//4buLwrNTPQpKxZJQw6fDkGb///8xLDIsMSw1/zg "Jelly – Try It Online") 1-indexed. 4 bytes spent on returning indices rather than just the elements themselves. -1 byte thanks to user202729 -1 byte thanks to Jonathan Allan [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` ηλfo=¹ṁ⁰tṖ ``` 1-indexed. [Try it online!](https://tio.run/##AS0A0v9odXNr///Ot867Zm89wrnhuYHigbB04bmW////MP9bMSwxLC01LDMsLTIsMl0 "Husk – Try It Online") ## Explanation ``` ηλfo=¹ṁ⁰tṖ Inputs are a number n (explicit, accessed with ¹) and a list x (implicit). η Act on the incides of x λ using this function: Ṗ Take all subsets, t remove the first one (the empty subset), f and keep those that satisfy this: ṁ⁰ The sum of the corresponding elements of x o=¹ equals n. ``` This uses the latest addition to Husk, `η` (act on indices). The idea is that `η` takes a higher order function `α` (here the inline lambda function) and a list `x`, and calls `α` on the indexing function of `x` (which is `⁰` in the above program) and the indices of `x`. For example, `ṁ⁰` takes a subset of indices, maps indexing to `x` over them and sums the results. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 43 bytes 1-indexed. ``` Pick[s=Subsets;s@Range@Tr[1^#],Tr/@s@#,#2]& ``` [Try it online!](https://tio.run/##Tc3BCsIwDIDhu08RGHiKdZ2OTmTQRxi6W6lQRzeLbIe2nsRnrymC7JAc8n@Q2cSHnU10g0kjtJA6NzxVaK@ve7AxnIO8mGWysveK3wqNvd/LIAssKr1NnXdLlKN6c4QKgXb9QWj05h@OrEE4sZo6EyQ44xmWxDi1laSaKcKOl6TziKzEyvzeHOgsdPoC "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 144 bytes ``` lambda a,t:[[e for e,_ in x]for r in range(len(a))for x in combinations(list(enumerate(a)),r+1)if sum(y for _,y in x)==t] from itertools import* ``` [Try it online!](https://tio.run/##HYxBCsIwEEX3nmKWic6miiBCT1JLSTXRgSRTJlNoTx9Jd/8/Hm/Z9cf5VkP/qtGl@ePAoT6HwUNgAY8TUIZtbEfaFJe/3kSfjbO20a3RN6eZslPiXEykosbnNXlx6puHcuksBShrMvsRnnA/wrbvdTwF4QSkXpQ5FqC0sOi5LkJZTTBDh1fs8D7iw9r6Bw "Python 3 – Try It Online") 0-indexed. 44 bytes spent on returning indices rather than just the elements themselves. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~18~~ 15 bytes ``` hiᶠ⊇Shᵐ+~t?∧Stᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/xmZQM6jrvbgDCBPu67E/lHH8uASkMz/6OhoQx0FIx0FIGkaq6NgAcTR0SZ6FjoKlnqmQBk9c6CcoZ4hSIkBUNIQKAdWAxQHKdJRiDc0AKoDYXOQvDlYFmKoMZBtHhsLAA "Brachylog – Try It Online") *-3 bytes because it now [works as a generator](https://codegolf.meta.stackexchange.com/a/10753/85334).* (It's probably possible to golf more, but working around the need to use indices is awkward.) ``` S The variable S ⊇ is a sublist of ᶠ the list of all i pairs [element, index] from h the first element of the input; hᵐ the first elements of each pair + add up to ~t the last element of ? the input ∧ which isn't necessarily S S, tᵐ from which the last elements of each pair are output. ``` [Answer] # [Perl 6](https://perl6.org), 45 bytes ``` ->\a,\b{grep {a[$_].sum==b},^a .combinations} ``` [Test it](https://tio.run/##bZJLboMwEIb3nOJfRFFQBwvybIWIOECX3REaAXErpPAQdqpGESfrrhejYyfpS7GEGY/n/2Y8diu7/XI4KIm3pShCpzpiXDQ7iWjw1puMNvnptZMtTlky2qZCHaooynt6ziCKpsrLOtNlU6t@YGGspdKIMHGACf6OJCBMCTwvUgLuyfiQ@BTQjB28PWUD6TnaJYtI5oIDH8SCtWLF6kAEBuKzIrB7FjHnZfov3xVhc7PUcAhe4DPKfCuDWF2q4OSmBp9mlpXMaGFK@YW4dRZTNy6IFLcHI9zQUYcc3K2qqRl3F2/h4oR4@/khVNNp/j2WSlvbWugdcyFP3M3QafdZzRptFy9Nd@myt8YkzmiUUyzfW1louWMo11sqbydluz/CXOM5xhXjc3rCd/SP6xrT8lMInX74Ag "Perl 6 – Try It Online") ## Expanded: ``` -> \a, # input list \b, # input target { grep { a[ $_ ].sum # use the list under test as indexes into 「a」 == b }, ^a # Range upto 「a」 (uses 「a」 as a number) .combinations # get all of the combinations } ``` [Answer] # APL(NARS), 49 chars, 98 bytes ``` {∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬} ``` 1-indexed; test: ``` f←{∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬} ⎕fmt 8 f 1 2 1 5 ┌2──────────────┐ │┌3────┐ ┌3────┐│ ││2 3 4│ │1 2 4││ │└~────┘ └~────┘2 └∊──────────────┘ ⎕fmt 14.8 f 4.8 9.5 2.7 11.12 10 ┌1────┐ │┌2──┐│ ││1 5││ │└~──┘2 └∊────┘ ⎕fmt 17 f 7, 8, 9, ¯10, 20, 27 ┌3──────────────────┐ │┌2──┐ ┌2──┐ ┌3────┐│ ││4 6│ │2 3│ │1 4 5││ │└~──┘ └~──┘ └~────┘2 └∊──────────────────┘ ⎕fmt 7 f 1 2 3 ┌0┐ │0│ └~┘ ``` comment: ``` {∨/b←⍺=+/¨{∊⍵⊂w}¨n←{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵:⍸¨b/n⋄⍬} ⍳¯1+2*k←≢w←⍵ copy ⍵ in w, len(⍵) in k, return 1..2^(k-1) n←{⍵⊤⍨k⍴2}¨ traslate in binary each element of 1..2^(k-1) and assign the result to n {∊⍵⊂w}¨ for each binary element of n return the elemets of ⍵ in the place where there are the 1s b←⍺=+/¨ sum them and see if the sum is ⍺, that binary array saved in b ∨/ :⍸¨b/n if or/b, get all the elements of n that are 1s for array b, and calculate each all indexs ⋄⍬ else return Zilde as void set ``` [Answer] # Pyth, 11 bytes ``` fqvzs@LQTyU ``` Try it online [here](https://pyth.herokuapp.com/?code=fqvzs%40LQTyU&input=%5B1%2C2%2C3%2C4%2C5%5D%0A9&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=fqvzs%40LQTyU&test_suite=1&test_suite_input=%5B1%2C%202%2C%201%2C%205%5D%0A8%0A%5B4.8%2C%209.5%2C%202.7%2C%2011.12%2C%2010%5D%0A14.8%0A%5B7%2C%208%2C%209%2C%20-10%2C%2020%2C%2027%5D%0A17%0A%5B1%2C%202%2C%203%5D%0A7&debug=0&input_size=2). ``` fqvzs@LQTyUQ Implicit: Q=input 1 (list of numbers), z=input 2 (target value, as string) Trailing Q inferred UQ Generate range [0-<length of Q>) y Powerset of the above f Keep elements of the above, as T, when the following is truthy: L T Map elements of T... @ Q ... to the indicies in Q s Take the sum q Is the above equal to... vz z as an integer Implicit print of the remaining results ``` ]
[Question] [ Given a positive integer *n* output the *n*-th number of the euro-iginal sequence. ## Calculating the Sequence This sequence is equal to OEIS [A242491](https://oeis.org/A242491). A number is part of said sequence if the number can be made up by using as many different euro coins or notes, but **only one of each**. Note that you don't have to consider cents. **Example:** `6` would be in the sequence, as it can consist of a 1-euro coin and a 5-euro-note. `4` would NOT be in the sequence, as it can't be formed with the given requirements. To give everyone an overview, heres a list with euro values you have to consider: > > 1€, 2€, 5€, 10€, 20€, 50€, 100€, 200€, 500€ > > > Note that this sequence only ranges from 0 (yes, 0 is included!) to 888. --- Here are the first 15 elements of this sequence: 0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, ... ## Test Cases **Input** -> **Output** ``` 2 -> 1 6 -> 6 21 -> 25 33 -> 50 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` b8d4ḅ5Ḍ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//YjhkNOG4hTXhuIz/MHI1MTHCtcW8w4figqxH/w "Jelly – Try It Online") ### How it works ``` b8d4ḅ5Ḍ Main link. Argument: n (integer) b8 Convert n from integer to base 8. d4 Divmod each base-8 digit by 4, mapping the digit d to [d / 4, d % 4]. ḅ5 Convert the quotient-remainder pairs from base 5 to integer, mapping [d / 4, d % 4] to (d / 4 * 5 + d % 4). The last two steps establish the following mapping for octal digits. 0 -> [0, 0] -> 0 1 -> [0, 1] -> 1 2 -> [0, 2] -> 2 3 -> [0, 3] -> 3 4 -> [1, 0] -> 5 5 -> [1, 1] -> 6 6 -> [1, 2] -> 7 7 -> [1, 3] -> 8 Ḍ Convert the resulting array of digits from decimal to integer. ``` [Answer] # [Python 2](https://docs.python.org/2/), 32 bytes ``` lambda n:n+n/4+n/32*10+n/256*100 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk87T98EiI2NtAwNgLSRqRmQYfA/Lb9IIU8hM0@hKDEvPVXD1NBI04qLs6AoM69EIU8nTSNP8z8A "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 34 bytes ``` f=lambda n:n and 10*f(n/8)+n%8*5/4 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIc8qTyExL0XB0EArTSNP30JTO0/VQstU3@R/Wn6RQp5CZp5CUWJeeqqGqaGRphUXZ0FRZl6JQp4OULHmfwA "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~8 7~~ 5 bytes ``` Σ!Ṗİ€ ``` [Try it online!](https://tio.run/##ARoA5f9odXNr///OoyHhuZbihpE5xLDigqz///8yMQ "Husk – Try It Online") **Edit:** -3 bytes thanks to Zgarb! ``` İ€ build-in infinite sequence [1,2,5,10,20,50,100,...] Ṗ power set [[],[1],[2],[1,2],[5],[1,5],[2,5],[1,2,5],...] ! index into the list with given input, e.g. 4 yields [1,2] Σ take the sum of that list ``` --- I heard that it is planned to change `İ€` to the finite sequence `[0.01,0.02,0.05,0.1,0.2,0.5,1,2,5,10,...,500]` in the future. Once that is implemented, the following code should work a byte count of 7: ``` Σ!Ṗ↓6İ€ ``` where `↓6` drops the first six elements of the sequence. [Try it online!](https://tio.run/##ARsA5P9odXNr//8hbc6j4bmW4oaTNsSw4oKs////MjE "Husk – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 29 bytes **28 bytes code + 1 for `-p`.** Uses 0 based indexing. ``` $_=sprintf"%o",$_;y/4-7/5-8/ ``` [Try it online!](https://tio.run/##DcxBCoMwEEDR/T@G2F2DmZnERErP4qoFQUxQN728qdsP79fPvsbW@vl91H3Zzm/3KN2zn1@/Ibg0RJeH1jyCYgQiI4nMhNxREEUMCUhERiQhGZlQj95GUUMDGtERTWhGJ8xjgt1Lu0o9l7IdzdX1Dw "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 0Df9,4Ṇ$$#Ṫ ``` [Try it online!](https://tio.run/##y0rNyan8/9/AJc1Sx@ThzjYVFeWHO1f9///f2BgA "Jelly – Try It Online") Thanks a lot to [@Erik the Outgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) for a lot of help in chat! ## Explanation ``` 0Df9,4Ṇ$$#Ṫ - Monadic link. 0 # - Collect first N matches, starting from 0. D - Digits. f9,4 - Filter-Keep the digits that are either 9 or 4. Yields [] when there are none. Ṇ - Logical NOT. [] -> 1 (truthy), non-empty list -> 0 (falsy). Ṫ - Pop and return the last element. ``` [Answer] # Mathematica, 47 bytes ``` (FromDigits/@0~Range~8~Drop~{5}~Tuples~3)[[#]]& ``` # Mathematica, 48 bytes ``` Sort[Tr/@Subsets@Join[x={1,2,5},10x,100x]][[#]]& ``` -6 bytes from Martin Ender [Answer] # Java 8, ~~28~~ 26 bytes 0-indexed: ``` n->n+n/4+n/32*10+n/256*100 ``` Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/144450/52210) (which used to be deleted, hence the original 1-indexed answer below). [Try it here.](https://tio.run/##hZBND4IwDIbv/ooemQRkQ7wg/gO5cDQeJh9mCIXAIDGG347lwyMxWbuue5r3TXPZS6uqU8yT1xgXsm3hKhV@dgAKddpkMk4hnJ5zA2Jjysh86gwUdFottYohBIQARrQuaOLhSOGKPXfoFt6JCmf0F77uHgXx61hfqQRKkjQi3Sh83u4g2aKXVc2spgLHB3XmUzbN9RMgerc6Le2q03ZNk7pAA23yx2Zzi71NSjg/bANwxR/A45ytaxjGLw) --- Old 1-indexed answer (**28 bytes**): ``` n->--n+n/4+n/32*10+n/256*100 ``` Port of [*@Tfeld*'s Python 2 answer before he made his last edit](https://codegolf.stackexchange.com/revisions/144451/5). Instead of using `~-` a bunch of times, it uses `--n` to decrease `n` by 1 right after entering the lambda function. [Try it here.](https://tio.run/##hVDLDoIwELz7FXsECUhBvCD@gVw4Gg@VhynClkAhMYZvr8vDIzHZR3c7k5lsyQduyybHMnvptOJdB1cu8LMDEKjytuBpDvE0zgtIjamiGdJmpKToFFcihRgQItBoX2wbLTwcKX1vz1zqXnCih6vDhdH0j4oYK3GQIoOaRI1EtQKftztwc1EsZDvriYiFIM4Rc6lZ1voLkLw7ldeO7JXTEFVVaKBDFs3Z3@JwE@WxH2wD4Pt/AAHzzPUSo/4C) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes 0-indexed. Port of [Mr. Xcoder's Jelly answer](https://codegolf.stackexchange.com/a/144473/47066) ``` µN7nÃg_ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0FY/S5PDzenx//8bGwEA "05AB1E – Try It Online") **Explanation** ``` µ # loop over increasing N until input matches are found _ # the logical negation of g # the length of N # N 7nà # with only 4s and 9s kept ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~40~~ ~~38~~ 36 bytes Inspired by [xnor's answer](https://codegolf.stackexchange.com/a/144450/38592), but uses 1-indexing. ``` lambda n:~-n*5/4+~-n/32*10+n/257*100 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPqk43T8tU30QbSOsbG2kZGmjn6RuZmgMZBv8LijLzShTSNAw1uWBMIwTTDEkUSYWxsSYXnGNqaKT5HwA "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), ~~78~~ ~~65~~ ~~62~~ ~~61~~ ~~58~~ 56 bytes ``` lambda i,n=0:f(i+~-('4'in`n`or'9'in`n`),n+1)if i else~-n ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFTJ8/WwCpNI1O7TldD3UQ9My8hLyG/SN0SwtLUydM21MxMU8hUSM0pTq3TzftfUJSZV6KQpmGoyQVjGiGYZkiiSCqMjTW54BxTQyPN/wA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes 0-indexed. ``` 滓£¦®‘ד¢½d‘S+ ``` [Try it online!](https://tio.run/##y0rNyan8///wskO7HzXMObT40LJD6x41zDg8HcRbdGhvCpATrP3//39jIwA "Jelly – Try It Online") ## Explanation This is based off of [xnor's Python solution](https://codegolf.stackexchange.com/a/144450), where the algorithm is **n + n/4 + n/32\*10 + n/256\*100**. ``` lambda n: sum(i * j for i, j in zip([n / i for i in [1, 4, 32, 256]], [1, 1, 10, 100]])) ``` Since the first **n** is unmodified, this is the same as: ``` lambda n: sum(i * j for i, j in zip([n / i for i in [4, 32, 256]], [1, 10, 100]])) + n ``` Since 4, 32, and 256 are all powers of two, they can be translated into bit shifts. ``` lambda n: sum(i * j for i, j in zip([n >> i for i in [2, 5, 8]], [1, 10, 100]])) + n ``` The golfiness doesn't translate well in Python, but turning the lists into Jelly strings of code page indices reduces Jelly's byte count. ``` lambda n: sum(i * j for i, j in zip([n >> i for i in map(jelly_codepage.index, '£¦®')], map(jelly_codepage.index, '¢½d'))) + n ``` ## [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` “¡¿ɼcÞµ³Ṡf2ż’bȷ3ŒPS€Ṣ ị¢ ``` [Try it online!](https://tio.run/##AToAxf9qZWxsef//4oCcwqHCv8m8Y8OewrXCs@G5oGYyxbzigJliyLczxZJQU@KCrOG5ogrhu4vCov///zMz "Jelly – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 59 bytes ``` @(n)unique((dec2bin(0:511)-48)*kron([1 2 5],10.^(0:2))')(n) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0@zNC@zsDRVQyMlNdkoKTNPw8DK1NBQU9fEQlMruyg/TyPaUMFIwTRWx9BALw4oaaSpqa4J1PY/TcNIU0chTcMMTBoZgiljY83/AA "Octave – Try It Online") ### Explanation The code creates the full sequence and then indexes into it. First, the binary expressions of the numbers `0`, `1`, ... `511` are generated as a 512×9 matrix: > > `dec2bin(0:511)-48` > > > (the `-48` part is needed because the result of `dec2bin` is characters, not numbers). This gives ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 ... 1 1 1 1 1 1 1 1 1 ``` Then the Kronecker product of `[1 2 5]` and `[1 10 100]` is computed > > `kron([1 2 5],10.^(0:2))` > > > and transposed > > `'` > > > which gives the nine possible euro values as a 9×1 vector: ``` 1 2 5 10 20 50 100 200 500 ``` Matrix-multiplying the above matrix and vector > > `*` > > > gives a 512×1 vector containing all possible numbers in the sequence, with repetitions and unsorted: ``` 0 500 50 ... 388 888 ``` Deduplicating and sorting > > `unique(...)` > > > gives the full sequence: ``` 0 1 2 ... 887 888 ``` Finally, the input is used to index into this sequence > > `(n)` > > > to produce the output. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~28~~ 27 bytes ``` ->x{("%o"%x).tr"4-7","5-8"} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iWkNJNV9JtUJTr6RIyUTXXElHyVTXQqn2v4aBnp6hgYGmXm5iQXVNRY1CgUJ0hY5CWnRFbGztfwA "Ruby – Try It Online") ### Explanation Output octal string, replace digits 4..7 with 5..8 [Answer] # Bash + GNU utilities, 20 ``` dc -e8o?p|tr 4-7 5-8 ``` Reads a zero-indexed index from STDIN. [Try it online](https://tio.run/##S0oszvifll@kUJJaXJKcWJyqkJmnYKhgqmBkoGBsZK2Qks@loJCanJGvoAJXUaPwPyVZQTfVIt@@oKakSMFE11zBVNfif0p@Xup/AA). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` 9LD3%n>s3/óTsm*æO{sè ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0sfFWDXPrthY//DmkOJcrcPL/KuLD6/4/9/YCAA "05AB1E – Try It Online") --- 1-indexed, using the formula of `[(n%3)^2 + 1]*10^floor(n/3)` to generate the first 10 terms, then using powerset to calculate all possible combinations... Then I sort it and pull `a[b]`. --- See it in action below: ``` Full program: 9LD3%n>s3/óTsm*æO{sè current >> 9 || stack: [] current >> L || stack: ['9'] current >> D || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9]] current >> 3 || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9]] current >> % || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], '3'] current >> n || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 0, 1, 2, 0, 1, 2, 0]] current >> > || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 0, 1, 4, 0, 1, 4, 0]] current >> s || stack: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 5, 1, 2, 5, 1, 2, 5, 1]] current >> 3 || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [1, 2, 3, 4, 5, 6, 7, 8, 9]] current >> / || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [1, 2, 3, 4, 5, 6, 7, 8, 9], '3'] current >> ó || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [0.3333333333333333, 0.6666666666666666, 1.0, 1.3333333333333333, 1.6666666666666667, 2.0, 2.3333333333333335, 2.6666666666666665, 3.0]] current >> T || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [0, 0, 0, 1, 1, 1, 2, 2, 2]] current >> s || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [0, 0, 0, 1, 1, 1, 2, 2, 2], 10] current >> m || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], 10, [0, 0, 0, 1, 1, 1, 2, 2, 2]] current >> * || stack: [[2, 5, 1, 2, 5, 1, 2, 5, 1], [1, 1, 1, 10, 10, 10, 100, 100, 100]] current >> æ || stack: [[2, 5, 1, 20, 50, 10, 200, 500, 100]] current >> O || stack: < OMITTED, THE RESULT OF POWERSET IS HUGE > current >> { || stack: [[0, 2, 5, 1, 20, 50, 10, 200, 500, 100, 7, 3, 22, 52, 12, 202, 502, 102, 6, 25, 55, 15, 205, 505, 105, 21, 51, 11, 201, 501, 101, 70, 30, 220, 520, 120, 60, 250, 550, 150, 210, 510, 110, 700, 300, 600, 8, 27, 57, 17, 207, 507, 107, 23, 53, 13, 203, 503, 103, 72, 32, 222, 522, 122, 62, 252, 552, 152, 212, 512, 112, 702, 302, 602, 26, 56, 16, 206, 506, 106, 75, 35, 225, 525, 125, 65, 255, 555, 155, 215, 515, 115, 705, 305, 605, 71, 31, 221, 521, 121, 61, 251, 551, 151, 211, 511, 111, 701, 301, 601, 80, 270, 570, 170, 230, 530, 130, 720, 320, 620, 260, 560, 160, 750, 350, 650, 710, 310, 610, 800, 28, 58, 18, 208, 508, 108, 77, 37, 227, 527, 127, 67, 257, 557, 157, 217, 517, 117, 707, 307, 607, 73, 33, 223, 523, 123, 63, 253, 553, 153, 213, 513, 113, 703, 303, 603, 82, 272, 572, 172, 232, 532, 132, 722, 322, 622, 262, 562, 162, 752, 352, 652, 712, 312, 612, 802, 76, 36, 226, 526, 126, 66, 256, 556, 156, 216, 516, 116, 706, 306, 606, 85, 275, 575, 175, 235, 535, 135, 725, 325, 625, 265, 565, 165, 755, 355, 655, 715, 315, 615, 805, 81, 271, 571, 171, 231, 531, 131, 721, 321, 621, 261, 561, 161, 751, 351, 651, 711, 311, 611, 801, 280, 580, 180, 770, 370, 670, 730, 330, 630, 820, 760, 360, 660, 850, 810, 78, 38, 228, 528, 128, 68, 258, 558, 158, 218, 518, 118, 708, 308, 608, 87, 277, 577, 177, 237, 537, 137, 727, 327, 627, 267, 567, 167, 757, 357, 657, 717, 317, 617, 807, 83, 273, 573, 173, 233, 533, 133, 723, 323, 623, 263, 563, 163, 753, 353, 653, 713, 313, 613, 803, 282, 582, 182, 772, 372, 672, 732, 332, 632, 822, 762, 362, 662, 852, 812, 86, 276, 576, 176, 236, 536, 136, 726, 326, 626, 266, 566, 166, 756, 356, 656, 716, 316, 616, 806, 285, 585, 185, 775, 375, 675, 735, 335, 635, 825, 765, 365, 665, 855, 815, 281, 581, 181, 771, 371, 671, 731, 331, 631, 821, 761, 361, 661, 851, 811, 780, 380, 680, 870, 830, 860, 88, 278, 578, 178, 238, 538, 138, 728, 328, 628, 268, 568, 168, 758, 358, 658, 718, 318, 618, 808, 287, 587, 187, 777, 377, 677, 737, 337, 637, 827, 767, 367, 667, 857, 817, 283, 583, 183, 773, 373, 673, 733, 333, 633, 823, 763, 363, 663, 853, 813, 782, 382, 682, 872, 832, 862, 286, 586, 186, 776, 376, 676, 736, 336, 636, 826, 766, 366, 666, 856, 816, 785, 385, 685, 875, 835, 865, 781, 381, 681, 871, 831, 861, 880, 288, 588, 188, 778, 378, 678, 738, 338, 638, 828, 768, 368, 668, 858, 818, 787, 387, 687, 877, 837, 867, 783, 383, 683, 873, 833, 863, 882, 786, 386, 686, 876, 836, 866, 885, 881, 788, 388, 688, 878, 838, 868, 887, 883, 886, 888]] current >> s || stack: [[0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21, 22, 23, 25, 26, 27, 28, 30, 31, 32, 33, 35, 36, 37, 38, 50, 51, 52, 53, 55, 56, 57, 58, 60, 61, 62, 63, 65, 66, 67, 68, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81, 82, 83, 85, 86, 87, 88, 100, 101, 102, 103, 105, 106, 107, 108, 110, 111, 112, 113, 115, 116, 117, 118, 120, 121, 122, 123, 125, 126, 127, 128, 130, 131, 132, 133, 135, 136, 137, 138, 150, 151, 152, 153, 155, 156, 157, 158, 160, 161, 162, 163, 165, 166, 167, 168, 170, 171, 172, 173, 175, 176, 177, 178, 180, 181, 182, 183, 185, 186, 187, 188, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, 213, 215, 216, 217, 218, 220, 221, 222, 223, 225, 226, 227, 228, 230, 231, 232, 233, 235, 236, 237, 238, 250, 251, 252, 253, 255, 256, 257, 258, 260, 261, 262, 263, 265, 266, 267, 268, 270, 271, 272, 273, 275, 276, 277, 278, 280, 281, 282, 283, 285, 286, 287, 288, 300, 301, 302, 303, 305, 306, 307, 308, 310, 311, 312, 313, 315, 316, 317, 318, 320, 321, 322, 323, 325, 326, 327, 328, 330, 331, 332, 333, 335, 336, 337, 338, 350, 351, 352, 353, 355, 356, 357, 358, 360, 361, 362, 363, 365, 366, 367, 368, 370, 371, 372, 373, 375, 376, 377, 378, 380, 381, 382, 383, 385, 386, 387, 388, 500, 501, 502, 503, 505, 506, 507, 508, 510, 511, 512, 513, 515, 516, 517, 518, 520, 521, 522, 523, 525, 526, 527, 528, 530, 531, 532, 533, 535, 536, 537, 538, 550, 551, 552, 553, 555, 556, 557, 558, 560, 561, 562, 563, 565, 566, 567, 568, 570, 571, 572, 573, 575, 576, 577, 578, 580, 581, 582, 583, 585, 586, 587, 588, 600, 601, 602, 603, 605, 606, 607, 608, 610, 611, 612, 613, 615, 616, 617, 618, 620, 621, 622, 623, 625, 626, 627, 628, 630, 631, 632, 633, 635, 636, 637, 638, 650, 651, 652, 653, 655, 656, 657, 658, 660, 661, 662, 663, 665, 666, 667, 668, 670, 671, 672, 673, 675, 676, 677, 678, 680, 681, 682, 683, 685, 686, 687, 688, 700, 701, 702, 703, 705, 706, 707, 708, 710, 711, 712, 713, 715, 716, 717, 718, 720, 721, 722, 723, 725, 726, 727, 728, 730, 731, 732, 733, 735, 736, 737, 738, 750, 751, 752, 753, 755, 756, 757, 758, 760, 761, 762, 763, 765, 766, 767, 768, 770, 771, 772, 773, 775, 776, 777, 778, 780, 781, 782, 783, 785, 786, 787, 788, 800, 801, 802, 803, 805, 806, 807, 808, 810, 811, 812, 813, 815, 816, 817, 818, 820, 821, 822, 823, 825, 826, 827, 828, 830, 831, 832, 833, 835, 836, 837, 838, 850, 851, 852, 853, 855, 856, 857, 858, 860, 861, 862, 863, 865, 866, 867, 868, 870, 871, 872, 873, 875, 876, 877, 878, 880, 881, 882, 883, 885, 886, 887, 888]] current >> è || stack: [[0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21, 22, 23, 25, 26, 27, 28, 30, 31, 32, 33, 35, 36, 37, 38, 50, 51, 52, 53, 55, 56, 57, 58, 60, 61, 62, 63, 65, 66, 67, 68, 70, 71, 72, 73, 75, 76, 77, 78, 80, 81, 82, 83, 85, 86, 87, 88, 100, 101, 102, 103, 105, 106, 107, 108, 110, 111, 112, 113, 115, 116, 117, 118, 120, 121, 122, 123, 125, 126, 127, 128, 130, 131, 132, 133, 135, 136, 137, 138, 150, 151, 152, 153, 155, 156, 157, 158, 160, 161, 162, 163, 165, 166, 167, 168, 170, 171, 172, 173, 175, 176, 177, 178, 180, 181, 182, 183, 185, 186, 187, 188, 200, 201, 202, 203, 205, 206, 207, 208, 210, 211, 212, 213, 215, 216, 217, 218, 220, 221, 222, 223, 225, 226, 227, 228, 230, 231, 232, 233, 235, 236, 237, 238, 250, 251, 252, 253, 255, 256, 257, 258, 260, 261, 262, 263, 265, 266, 267, 268, 270, 271, 272, 273, 275, 276, 277, 278, 280, 281, 282, 283, 285, 286, 287, 288, 300, 301, 302, 303, 305, 306, 307, 308, 310, 311, 312, 313, 315, 316, 317, 318, 320, 321, 322, 323, 325, 326, 327, 328, 330, 331, 332, 333, 335, 336, 337, 338, 350, 351, 352, 353, 355, 356, 357, 358, 360, 361, 362, 363, 365, 366, 367, 368, 370, 371, 372, 373, 375, 376, 377, 378, 380, 381, 382, 383, 385, 386, 387, 388, 500, 501, 502, 503, 505, 506, 507, 508, 510, 511, 512, 513, 515, 516, 517, 518, 520, 521, 522, 523, 525, 526, 527, 528, 530, 531, 532, 533, 535, 536, 537, 538, 550, 551, 552, 553, 555, 556, 557, 558, 560, 561, 562, 563, 565, 566, 567, 568, 570, 571, 572, 573, 575, 576, 577, 578, 580, 581, 582, 583, 585, 586, 587, 588, 600, 601, 602, 603, 605, 606, 607, 608, 610, 611, 612, 613, 615, 616, 617, 618, 620, 621, 622, 623, 625, 626, 627, 628, 630, 631, 632, 633, 635, 636, 637, 638, 650, 651, 652, 653, 655, 656, 657, 658, 660, 661, 662, 663, 665, 666, 667, 668, 670, 671, 672, 673, 675, 676, 677, 678, 680, 681, 682, 683, 685, 686, 687, 688, 700, 701, 702, 703, 705, 706, 707, 708, 710, 711, 712, 713, 715, 716, 717, 718, 720, 721, 722, 723, 725, 726, 727, 728, 730, 731, 732, 733, 735, 736, 737, 738, 750, 751, 752, 753, 755, 756, 757, 758, 760, 761, 762, 763, 765, 766, 767, 768, 770, 771, 772, 773, 775, 776, 777, 778, 780, 781, 782, 783, 785, 786, 787, 788, 800, 801, 802, 803, 805, 806, 807, 808, 810, 811, 812, 813, 815, 816, 817, 818, 820, 821, 822, 823, 825, 826, 827, 828, 830, 831, 832, 833, 835, 836, 837, 838, 850, 851, 852, 853, 855, 856, 857, 858, 860, 861, 862, 863, 865, 866, 867, 868, 870, 871, 872, 873, 875, 876, 877, 878, 880, 881, 882, 883, 885, 886, 887, 888], '32'] 50 stack > [50] ``` [Answer] ## JavaScript (ES6), 34 bytes ``` n=>--n+(n>>2)+(n>>5)*10+(n>>8)*100 ``` Or 32 bytes using the correct 0-indexing: ``` f= n=>n+(n>>2)+(n>>5)*10+(n>>8)*100 ``` ``` <input type=number min=0 max=511 value=0 oninput=o.textContent=f(+this.value)><pre id=o>0 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` 53b6×þ“¢½d‘FŒPS€Ṣị@‘ ``` [Try it online!](https://tio.run/##y0rNyan8/9/UOMns8PTD@x41zDm06NDelEcNM9yOTgoIftS05uHORQ93dzsARf4fbgfy//8vSsxLT9Uw1DE01wQA "Jelly – Try It Online") I know this is longer than the existing answer but I think this approach is golfable from here :P -2 bytes thanks to Erik the Outgolfer [Answer] # [Retina](https://github.com/m-ender/retina), 42 bytes ``` .+ $*1; +`(1+)\1{7} $1; 1111 1$& (1*); $.1 ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRcvQmks7QcNQWzPGsNq8lksFyDcEAi5DFTUuDUMtTWsuFT3D//8NuUy5jAy4jI0A "Retina – Try It Online") Link includes test cases. 0-indexed. Explanation: ``` .+ $*1; ``` Convert from decimal to unary, with a `;` suffix. ``` +`(1+)\1{7} $1; ``` Convert to octal, but still using unary representation of the digits with `;` after each unary value. ``` 1111 1$& ``` Add 1 to the values 4-7. ``` (1*); $.1 ``` Convert each value plus its suffix to decimal. [Answer] # [Pyth](https://github.com/isaacg1/pyth), 12 bytes Uses [Dennis' witchcraft](https://codegolf.stackexchange.com/a/144474/59487). ``` jkiR5.DR4jQ8 ``` **[Try it here.](https://pyth.herokuapp.com/?code=jkiR5.DR4jQ8&test_suite=1&test_suite_input=0%0A1%0A5%0A20%0A32&debug=0)** # [Pyth](https://github.com/isaacg1/pyth), ~~16 15~~ 13 bytes ``` e.f!@,9 4jZTt ``` **[Verify all the test cases.](https://pyth.herokuapp.com/?code=e.f%21%40%2C9+4jZTt&test_suite=1&test_suite_input=2%0A6%0A21%0A33&debug=0)** Thanks to [Erik the Outgofer](https://chat.stackexchange.com/transcript/message/40371070#40371070) for some ideas. [Answer] # [C](https://en.wikipedia.org/wiki/C_(programming_language)), 67 bytes ``` main(n){scanf("%d",&n);printf("%d",n+(n>>2)+(n>>5)*10+(n>>8)*100);} ``` A direct port from [Neil's](https://codegolf.stackexchange.com/users/17602/neil) [JavaScript answer](https://codegolf.stackexchange.com/a/144456/66000), but I thought this should be added for completeness. --- Tested on GCC version 6.3.0. It will throw some warnings, but compile anyway. ]
[Question] [ Given three numbers ***m***,***n*** and ***p***, your task is to print a list/array of length ***p*** starting with ***m*** and ***n*** and each element after ***p*** represents the difference of the 2 numbers before it, ***m-n*** (Counter-**[Fibonacci Sequence](https://en.wikipedia.org/wiki/Fibonacci_number)**) For this challenge you can either use a function to return or print the result or a full program. ### Input Three integers, ***m***,***n*** and ***p***, separated by newlines/spaces/commas, whatever your language supports, but you should specify your input format. Code insertion is disallowed. ### Output The numbers contained by the Counter-Fibonacci Sequence, in any of the following formats (this example: `m = 50, n = 40, p = 6`): * `50,40,10,30,-20,50` (or with spacing after commas) * `[50,40,10,30,-20,50]` (or with spacing after commas) * `50 40 10 30 -20 50` (or with `\n`(newlines) instead of spaces) * `{50,40,10,30,-20,50}` (or with spaces instead of commas) --- ### Examples ``` Input => Output 50,40,10 => 50,40,10,30,-20,50,-70,120,-190,310 -100,-90,7 => -100,-90,-10,-80,70,-150,220 250,10,8 => 250,10,240,-230,470,-700,1170,-1870 ``` ### Rules * You are guaranteed that ***p*** is higher than 1 * You should provide a way to test your program, if possible * Take note that [this loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden and code insertion is disallowed, as mentioned above ### Scoring & Leaderboard Your code must be as short as possible, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). **No answer will be accepted**, because this challenge is meant to find the shortest answer by language, avoiding an unfair advantage to golfing languages. ``` var QUESTION_ID=113051,OVERRIDE_USER=59487;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` --- Related Question by ETHproductions: [Monday Mini-Golf #1: Reverse Fibonacci Solver](https://codegolf.stackexchange.com/questions/58419/monday-mini-golf-1-reverse-fibonacci-solver) [Answer] ## Haskell, 29 bytes ``` a#b=a:b#(a-b) (.(#)).(.).take ``` Length `p` is the first parameter. Usage example: `( (.(#)).(.).take ) 10 50 40` -> `[50,40,10,30,-20,50,-70,120,-190,310]`. [Try it online!](https://tio.run/nexus/haskell#@5@onGSbaJWkrJGom6TJlWaroaehrKmpp6GnqVeSmJ36PzcxM0/BVqGgKDOvREFFIU3B0EDB1EDBxOA/AA "Haskell – TIO Nexus"). Shortening the list to `p` elements takes more bytes than producing it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` _@С+Ṗ ``` [Try it online!](https://tio.run/nexus/jelly#@x/vcHjCoYXaD3dO@///v6nBfxOD/2YA "Jelly – TIO Nexus") ### How it works ``` _@С+Ṗ Main link. Left argument: m. Right argument: n. Third argument: p + Yield (m + n), the term that comes before m. С Execute the link to the left p times, starting with left argument m and right argument (m + n). After each execution, replace the right argument with the left one and the left argument with the previous return value. Yield all intermediate values of the left argument, starting with m. _@ Subtract the left argument from the right one. This yields the first (p + 1) terms of the sequence, starting with m. Ṗ Pop; discard the last term. ``` [Answer] # Python 2, 39 bytes *-2 bytes thanks to ETHproductions* -1 byte thanks to Dennis ``` f=lambda m,n,p:p*[0]and[m]+f(n,m-n,p-1) ``` [Try it Online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCrk6dTYFWgFW0Qm5iXEp0bq52mkaeTqwsU1TXU/F9QlJlXopCmYWqgY2KgY6bJhSpgaIAQ0TU0MNDRtTTQMUeIGZmC1OhYaP4HAA) [Answer] # JavaScript (ES6), 33 bytes ``` f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[] ``` Returns a string of the format `1,2,3,` — without using strings! ### Test snippet ``` f=(m,n,p)=>p?m+[,f(n,m-n,p-1)]:[] console.log(f(50,40,10)) console.log(f(-100,-90,7)) console.log(f(250,10,8)) ``` [Answer] # [Perl 6](https://perl6.org), 25 bytes ``` {($^m,$^n,*-*...*)[^$^p]} ``` [Try it](https://tio.run/nexus/perl6#jVDLboMwELz7K@aQlJeNDE1LWgrtB/TYWwhSFFwJCYgVoGqU8kX9i/5YuoYk6rGWVt4Zz856t28VPu79bczqA262u0IhOR3tWV7zWd5wV7i@77vOKp/lej2cSPTSqbZDgqpsVGs7fr3Rjzgy0Kmny5zV7KlsdN@lBiSwYQnrGVnhwVl7mM@xsriFrHXX1xICsJJ0ZP/6qE@ttp0q0n/4DPF4fdnez/fL@QcOxwSvRo7/WrYdG1hP07/RODHT1aaBN84WM/a@25/nFCn1zGqOrKHQFBcXOOPUtJFsr9q@Mjsx@7NBahJrTG3Mj8pWFErp6oBJynFx4WfG12pfseEE3EmOheSBRJIaMOb8VnIRSk5YRERQKoIHogPJRCAJEUBkSq6QEi6WkkcmpcIwlAyhsacHLI3WIALhwrhTi0U0@hMZjFXLSP4C "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with placeholder parameters 「$m」 「$n」 「$p」 ( $^m, $^n, # declare first two params, and use them * - * # WhateverCode lambda which subtracts two values ... # keep using that to generate values * # never stop (instance of type Whatever) )[ ^ $^p ] # declare last param, and use it to grab the wanted values # 「^ $^p」 is short form of range op # 「0 ..^ $^p」 which excludes the 「$p」 } ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 15 bytes ``` q~2-{1$1$-}*]S* ``` 1 extra byte because CJam doesn't naturally use one of the allowed output formats >\_< [Try it online!](https://tio.run/nexus/cjam#@19YZ6RbbahiqKJbqxUbrPX/v66hgYGCrqWBgjkA "CJam – TIO Nexus") **Explanation** ``` q~ e# Read and eval the input 2- e# Subtract 2 from p (to account for m and n being in the list) { e# Run this block p-2 times: 1$1$- e# Copy the top values and subtract }* e# (end of block) ] e# Wrap the stack in an array S* e# Join with spaces ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes ``` ÍFÂ2£¥« ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@41@1wk9GhxYeWHlr9/785V7SuoYGBjq6lQSwA "05AB1E – TIO Nexus") **Explanation** ``` ÍF # p-2 times do  # create a reversed copy of the current list 2£ # take the first 2 elements of the list ¥ # calculate delta « # append to the list ``` [Answer] # [Röda](https://github.com/fergusq/roda), 38 bytes ``` f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_} ``` [Try it online!](https://tio.run/nexus/roda#VYzLDoIwFETX9CsmXWlyIdRoRAlfYkxTDCQ1vCywavvt2OpGF3cWZ87crYUmRbWdmxcEaWeddDd1L@tKpXWpYnrpt@eoBzxgWTLjWoFzZBmmtet2@4iyKpSBSJaYZlnNgJl51o6mVwssPmtOHA6T0cMCCc96FWB42ELkhFO4Yx6E7yjiMyEVeeBpcfkrCsIh@uLH99sb "Röda – TIO Nexus") Explained: ``` f i,a,b{seq 1,i|{|_|[a];b=a-b;a=a-b}_} f i,a,b{ } /* Function declaration */ seq 1,i /* Push numbers 1..i to the stream */ |{|_| }_ /* For each number in the stream: */ [a]; /* Push the current value of a */ b=a-b; /* Set b = the next number */ a=a-b /* Set a = the previous value of b */ ``` [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` (m!n)0=[] (m!n)p=m:(n!(m-n))(p-1) ``` Call using `(m!n)p`. Works by defining `!` as an infix function that takes in `m` and `n` and returns a function that takes `p` and returns the desired result. [Answer] # Ruby, 31 bytes ``` ->m,n,p{p.times{m,n=n,(p m)-n}} ``` The straightforward solution [Answer] # PHP, 76 Bytes ``` [,$a,$b,$c]=$argv;for($r=[$a,$b];$c---2;)$r[]=-end($r)+prev($r);print_r($r); ``` ## PHP, 84 Bytes ``` [,$a,$b,$c]=$argv;for($r=[$a,$b];$c>$d=count($r);)$r[]=$r[$d-2]-end($r);print_r($r); ``` [Answer] # Pyth, 18 bytes ``` JEKEVEJ=N-JK=JK=KN ``` [Try it online!](https://tio.run/nexus/pyth#@@/l6u0a5upl66fr5W0LRN5@//@bmHMZGnBZAAA "Pyth – TIO Nexus") Input and output are both delimited by newlines. How it works: ``` JEKE Read two lines of input to J and K VE Read another line and loop that many times: J Print J =N-JK Set N to J - K (Pyth uses prefix notation) =JK Set J to K =KN Set K to N ``` [Answer] # Mathematica, 26 bytes ``` {-1,1}~LinearRecurrence~## ``` Lovin' the builtin. Takes input in the form `{{m, n}, p}`. `LinearRecurrence` wants the know the coefficients of the linear combination of previous elements to use to generate new elements, which in this case is `{-1,1}`. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~35~~ 33 bytes ``` :::?'a;b;`[c-2|e=a-b?e';`┘a=b┘b=e ``` *Saved 2 bytes by placing the first `PRINT` into one code literal.* Explanation (35 byte version): ``` ::: Get parameters a, b, c from the cmd-line ';` This suppresses a newline when printing ?a b';` PRINT a and b [c-2| FOR x=1; x<=(c-2); x++ e=a-b calculate the next term of the sequence ?e';` Print it, suppressing newline ┘a=b ┘ denotes a syntactic linebreak; shove the numbers one over ┘b=e dito FOR-loop is auto-closed ``` [Answer] # C, 128 bytes ``` m,n,p,z;main(c,v)char**v;{m=atoi(v[1]);n=atoi(v[2]);p=atoi(v[3])-2;printf("%d,%d",m,n);while(p--)z=m,m=n,n=z-m,printf(",%d",n);} ``` This program parses the three arguments `m`, `n` and `p` from the command-line, and prints the output as specified. Modern C compilers allow you to omit basic imports, and thus we can use `printf` and `atoi` without the `#include`s. Global variables are `int` by default when declared without a type - this saves a lot of space. [Answer] # Java, 66 bytes For once, lambdas are the inefficient approach to golfing due to the *very* [roundabout way of applying recursion to them](https://stackoverflow.com/q/19429667/) that requires a lot of extra bytes. Golfed: ``` String f(int m,int n,int p){return""+m+(p>1?","+f(n,m-n,p-1):"");} ``` Ungolfed: ``` public class CounterFibonacciSequences { private static final int[][] INPUTS = new int[][] { // { 50, 40, 10 }, // { -100, -90, 7 }, // { 250, 10, 8 } }; private static final String[] OUTPUTS = new String[] { // "50,40,10,30,-20,50,-70,120,-190,310", // "-100,-90,-10,-80,70,-150,220", // "250,10,240,-230,470,-700,1170,-1870" }; public static void main(String[] args) { for (int i = 0; i < INPUTS.length; ++i) { final int m = INPUTS[i][0]; final int n = INPUTS[i][1]; final int p = INPUTS[i][2]; System.out.println("M: " + m); System.out.println("N: " + n); System.out.println("P: " + p); System.out.println("Expected: " + OUTPUTS[i]); System.out.println("Actual: " + new CounterFibonacciSequences().f(m, n, p)); System.out.println(); } } String f(int m, int n, int p) { return "" + m + (p > 1 ? "," + f(n, m - n, p - 1) : ""); } } ``` [Answer] # AHK, 68 bytes ``` m=%1% n=%2% 3-=2 Send %m%`n%n%`n Loop,%3% { n:=m-n m-=n Send %n%`n } ``` Getting' really tired of not knowing how / being able to use passed arguments (`%1%`, `%2%`, ...) directly in any math functions [Answer] # [Python 2](https://docs.python.org/2/), ~~93~~ 90 bytes ``` u,t=int,input;m,n,p=u(t()),u(t()),u(t());l=[m,n] for i in range(p-2):l.append(l[-2]-l[-1]) ``` [Try it online!](https://tio.run/nexus/python2#VYzLCoAgEADvfoXHXVjDojoUfkl4CHog2LaIfr957TJzGJhaKLvAmQJLyetDTOIKZECkn9botla9ut6kgw6s0873CWIGXGK3i5x8QNzM4E1j77FKamOIWCerRqvmDw "Python 2 – TIO Nexus") Saved 3 bytes thanks to @Mr.Xcoder It works by taking the numbers as input and formatting them correctly, then using a for loop to generate a list based on the inputted numbers. [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ↑¡o→Ẋ`- ``` [Try it online!](https://tio.run/##yygtzv7//1HbxEML8x@1TXq4qytB9////9GmBjomBjqGBrH/zQA "Husk – Try It Online") ## Explanation ``` ↑¡o→Ẋ`- ¡o create an infinite list using the array: the next element is: → the last element of Ẋ`- overlapping pairs reduced by subtraction. ↑ take n elements ``` [Answer] # Swift - 85 bytes ``` func y(x:Int,y:Int,z:Int){var m=x,n=y,p=z,c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}} ``` Usage: `y(x:50,y:40,x:6)` # Swift - 84 bytes ``` func z(l:[Int]){var m=l[0],n=l[1],p=l[2],c=0;for _ in 1...p{print(m);c=m;m=n;n=c-n}} ``` *Usage:* `z(l: [50,40,6])` --- *Output:* ``` 50 40 10 30 -20 50 ``` [Answer] # Python - 55 bytes ``` def s(m,n,p): for i in range(p):print(m);c=m;m=n;n=c-n ``` **[Try it online!](https://tio.run/#WnSRE)** & Usage: `s(50,40,6)` Note: Solution without lambda ]