text
stringlengths
180
608k
[Question] [ Write a program that connects to this site, downloads the very answer in which it is posted, extracts its own source code and prints it out. The output must be identical to the source code. Shortest code (in bytes) wins. Rules: * No URL shorteners allowed. * The answer must have a regular format - a heading with the language name and size, optional description, code block, optional description and explanation. No unnatural delimiters allowed. * The output must originate from the actual code block posted on the site. * The functionality must not depend on the position in the answer list; it should work even if there are multiple pages and the answer it not on the first one. * **New:** special note for answers that are supposed to be run in a browser: it is ok to require running them on the codegolf domain (to obey the same-origin policy) but the domain and path should be included in the solution in order to make it fair. [Answer] # Bash + coreutils + Lynx browser, 61 bytes Thanks to @FDinoff for the tips: ``` lynx -dump codegolf.stackexchange.com/posts/28164/body|grep 2 ``` [Answer] # Ruby, ~~155~~ ~~186~~ ~~195~~ ~~148~~ ~~138~~ ~~110~~ 97 characters ``` require'open-uri';puts open('http://codegolf.stackexchange.com/posts/28159/body').read[/req.+;/]; ``` I had to make it one line, because otherwise it would output newlines as `\n` instead of actual newlines. * ~~+31 characters because I didn't notice some characters were being escaped.~~ * ~~+9 characters to get rid of the annoying backslash.~~ * Thanks to Nathan Osman for saving 2 chars, and Ventero for saving 55 (!!!) by removing the need for most of the fixes listed above. --- ## The explanation Let's beautify this a bit first. However, I'm going to have to use a somewhat... interesting notation in this code. I can't use semicolons at all in this post, for reasons explained later, so I will use `{SEMI}` in place of semicolons instead. ``` require 'open-uri' resp = open('http://codegolf.stackexchange.com/posts/28159/body').read puts resp.match(/req.+{SEMI}/){SEMI} ``` Alright, now let's walk through this. The first two lines are fairly self-explanatory -- they fetch the HTML text of this answer. Now, the last line is the interesting one here. You see that seemingly useless semicolon at the end of the code? It's absolutely required, and here's why. First, `resp.match` extracts the code to be printed. The regexp it uses for this is the trick: `/req.+{SEMI}/`. It grabs the start of the code, `REQuire'net/http'`, by searching for `req` (`re` would grab my `REputation`). Then, it finds the end of the code by searching for a semicolon! Since `+` is greedy by default, it will keep going until it finds the semicolon that signifies the end of the code. See why I can't use semicolons anymore? ~~After that, I don't have to unescape anything thanks to Ventero's fix of not using `\` at all anymore. All I have to do is fix `{AMPERSAND}` changing into `{AMPERSAND}amp{SEMI}`, which can be achieved simply by removing the `amp{SEMI}` part.~~ No need for this anymore because of new URL. After that, the original code has been retrieved! *(Note: I can't use the ampersand either, because that gets HTML-encoded which causes a semicolon to be created.)* [Answer] ## PowerShell - 69 62 ``` (irm codegolf.stackexchange.com/posts/28236/body).div.pre.code ``` [Answer] # JavaScript - 123 122 101 95 92 91 87 86 114 ``` with(new XMLHttpRequest)send(open(0,/\codegolf.stackexchange.com\posts\28175\body/,0)),alert(/w.*/.exec(response)) ``` Runs in the console of your web browser on this page. Tested on the latest Chrome and Firefox. *edit: +28 bytes to add the full domain.* *Firefox doesn't like my Regex URL trick anymore with this update :(* Here's the rule-breaking 86 byte solution: ``` with(new XMLHttpRequest)send(open(0,/posts\28175\body/,0)),alert(/w.*/.exec(response)) ``` [Answer] # Ruby + wget + gunzip, 159 86 82 71 Using tip of @FDinoff to use `http://codegolf.stackexchange.com/posts/28173/body`. ``` puts `wget -qO- codegolf.stackexchange.com/posts/28173/body`[/pu.*\]/] ``` Tested. Thanks to @ace and @Bob for command line optimization. [Answer] # CJam - 53 ``` "codegolf.stackexchange.com/posts/28184/body"g54/1=); ``` I'm making this community wiki since I'm answering my own question and don't really want to compete :p Credits to FDinoff for the URL choice. [Answer] # Rebmu, 91 characters Due to the Catch-22 I have to post to get this answer's URL. :-/ Okay, got it. ``` paTSrd http://codegolf.stackexchange.com/a/28154[th<a name="28154">th<code>cpCto</code>]prC ``` Rebmu is a dialect of Rebol, and [you can read all 'bout it](https://github.com/hostilefork/rebmu). The equivalent Rebol here would be: ``` parse to-string read http://codegolf.stackexchange.com/a/28154 [ thru <a name="28154"> thru <code> copy c to </code> ] print c ``` Rebol's PARSE is a sort of highly-literate answer to RegEx. It starts a parser position of the input *(which can be any series, including structural blocks...binary data...or string types)*. The rules are a language for how the parse position moves. Tags and URLs are really just strings under the hood in the language. But they are "flavored", and as Rebol is dynamically typed you can check that type. READ for instance knows that if you give it a URL-flavored string, then it should dispatch to a scheme handler to do the reading. (In this case, the one registered for HTTP). You get back UTF-8 bytes by default, so we use to-string to decode that and get a series of codepoints in a normal Unicode string. In the case of the parse dialect, encountering a tag type is just matched as if it were a string that looked like the tag. THRU is an instruction meaning "skip until the ensuing rule is matched, and then place the match position at the end of what you just matched." (TO is the analogue that matches, but leaves the parse position before the element). So we zip along past the `<a name="28154">`. Then we zip past the next occurrence of `<code>`, with our parse position now located right after the `>`. PARSE's COPY command then lets us copy data up to another rule, in this case that rule is `[TO </code>]`... so we get into the variable C everything up until right before that `<`. [Cool](http://blog.hostilefork.com/why-rebol-red-parse-cool/), huh? :-) Technically I could shave more off it, for instance by seeking `TO "</"` and that saves three characters--there's no need to match the whole `</code>` end tag when just `</` would do. Similar arguments could me made for the start tag. But Rebmu is about *literate* golfing...even if you might think it looks odd at first! **UPDATE**: the `/body` trick is out of the bag, but I'm similarly going to leave it as-is...because I think it is more educational this way. [Answer] ## Java now 634, 852, was 1004 Code has been updated; thanks for suggestions. Golfed: now replaces &gt with > ``` //bacchus package golf; import java.net.*; import java.util.*; public class G{ public static void main(String[] a) throws Exception { Scanner z; URL u; int x=0; String s; u=new URL("http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself"); z=new Scanner(u.openConnection().getInputStream()); z.useDelimiter("\\s*//bacchus\\s*"); while(z.hasNext()) { s=z.next(); s=s.replace("&gt;", ">"); if(x>0)System.out.println("//bacchus\n"+s); x++; if(x>2)break; } System.out.println("//bacchus\n"); } } //bacchus ``` Submitting for testing, I will edit and try golfing it shortly. Needed to change x>1 to x>2 because test string is also in my code. Note: Code golf replaces > symbol to &gt. ``` //bacchus package golf; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class Golf { public static void main(String[] args) throws IOException { URL u; URLConnection c; InputStream i; InputStreamReader r; BufferedReader b; String s; int x=0; try { u=new URL("http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself"); c=u.openConnection(); i=c.getInputStream(); r=new InputStreamReader(i); b=new BufferedReader(r); while((s=b.readLine())!=null) { if(s.contains("//bacchus")) x++; if(x>0)System.out.println(s); if(x>2) break; } i.close(); b.close(); } catch (MalformedURLException ex) { } } } //bacchus ``` [Answer] # Python, 175 167 bytes This uses two external libraries; I didn't read that it was unauthorized. ``` import bs4,requests print(bs4.BeautifulSoup(requests.get('http://codegolf.stackexchange.com/q/28154').text).select('#answer-28171')[0].select('pre > code')[0].string) ``` Longer, but nicer looking code: ``` import bs4, requests request = requests.get('http://codegolf.stackexchange.com/q/28154') soup = bs4.BeautifulSoup(request.text) answer = soup.select('#answer-28171')[0] code = answer.select('pre > code')[1].string print(code) ``` [Answer] ## w3m 45 characters ``` w3m codegolf.stackexchange.com/a/28336|grep ☻ ``` [Answer] ## JavaScript, 228 ``` r=new XMLHttpRequest() c='code' r.open('GET','//'+c+'golf.stackexchange.com/posts/28157/body') r.onreadystatechange=function(){this.readyState==4&&alert((a=r.responseText).substr(i=a.indexOf(c)+5,a.indexOf('/'+c)-i-1))} r.send() ``` Runs on this page. [Answer] ## Haskell, 563 613 bytes ``` import Control.Monad import Data.List import Network.HTTP m%f=join(fmap f m) q s=(simpleHTTP(getRequest"http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself?answertab=oldest#tab-top"))%getResponseBody%(putStrLn.head.filter((==)(s++show s)).map(take 613).tails) main=q"import Control.Monad\nimport Data.List\nimport Network.HTTP\nm%f=join(fmap f m)\nq s=(simpleHTTP(getRequest\"http://codegolf.stackexchange.com/questions/28154/write-a-program-that-downloads-itself?answertab=oldest#tab-top\"))%getResponseBody%(putStrLn.head.filter((==)(s++show s)).map(take 613).tails)\nmain=q" ``` Tested. Has page support via "oldest posts" feature. Uses quine-line structure to find what to print. The `import Control.Monad` is only because `>>=` generates `&gt;` in HTML. [Answer] # Javascript +jQuery, 87, 67 I'm not sure wether I'm allowed to use jQuery, but: ``` $('body').load('//codegolf.stackexchange.com/posts/28268/body pre') ``` --- ### Javascript + jQuery, if excecuted in this page: 27, 25 For fun, if it would be excecuted here: ``` $('[id$=268] pre').html() ``` `$('[id$=28268] pre').html()` [Answer] # Dart, 164 I thought I'd try this in Dart, is pretty fun to use imo. This can be run in the console in DartEditor, but does require the http package added in pubspec.yaml ``` import"package:http/http.dart"as h;h.read("http://codegolf.stackexchange.com/posts/28215/body").then((s){print(new RegExp(r"im.+(?:})").firstMatch(s).group(0));});} ``` Ungolfed version: ``` import "package:http/http.dart" as h; void main() { h.read("http://codegolf.stackexchange.com/posts/28215/body").then((s) { print(new RegExp(r"im.+(?:})").firstMatch(s).group(0)); }); } ``` [Answer] ## R 114 characters ``` library(XML);cat(xpathSApply(xmlParse("http://codegolf.stackexchange.com/posts/28216/body"),'//code',xmlValue)[1]) ``` No real magic here: it takes the value of the field between the html tags `<code></code>`. Uses library `XML` (as one can see in the code quite obviously). Outputs the result as stdout. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 108 bytes ``` 6 3⌷⎕XML{(⎕SE.SALT.New'HttpCommand'('GET'⍵)).Run.Data}'https://codegolf.stackexchange.com/posts/211205/body' ``` [Don't Try it online, try it locally](https://tio.run/##SyzI0U2pTMzJT///30zB@FHP9kd9UyN8fao1gHSwq16wo0@Inl9qubpHSUmBc35ubmJeirqGurtriPqj3q2amnpBpXl6LoklibXqGUAVxVb6@sn5Kanp@TlpesUlicnZqRXJGYl56al6yfm5@gX5xSXF@kaGhkYGpvpJ@SmV6v//AwA "APL (Dyalog Unicode) – Try It Online") ~~Correct link coming soon.~~ ## Output: [![enter image description here](https://i.stack.imgur.com/Bp2Ih.png)](https://i.stack.imgur.com/Bp2Ih.png) [Answer] # Java, ~~300~~ 294 ``` import java.net.*;import java.util.*;public class G{public static void main (String [] a) throws Exception{Scanner s=new Scanner(new URL("http://codegolf.stackexchange.com/posts/28189/body").openConnection().getInputStream()).useDelimiter("./?[c]ode\\W");s.next();System.out.print(s.next());}} ``` An improved version of bacchusbeale's answer which: * doesn't close resources unnecessarily * doesn't declare unnecessary variables * uses a `Scanner` to avoid having to loop over the input * uses a regexp that doesn't match itself to avoid having to skip over a middle occurrence of the start/end marker. Updated: * Use a direct URL to the post, so we don't need a unique comment to identify the start/end of the code; now uses `<code>[...]</code>` as the delimiters to search for (actually using the regular expression "./?[c]ode\W", so as to avoid having to decode `&lt;` and `&gt;` -- the "\W" is necessary rather than the shorter "." to avoid it matching part of the URL to the post, unfortunately, which costs 2 characters, and the square brackets around c prevent the regex matching itself). [Answer] # w3m 55 bytes ``` w3m codegolf.stackexchange.com/posts/28242/body|grep x ``` Based on @DigitalTrauma [Answer] # Ruby, ~~237~~ ~~215~~ ~~146~~ 132 ``` require'mechanize' a=Mechanize.new puts a.get('http://codegolf.stackexchange.com/a/28159').search('.lang-rb code:nth-child(1)').text ``` [Answer] # Processing, 90 ``` print(loadStrings("http://codegolf.stackexchange.com/posts/28657/body")[2].substring(11)); ``` **Edit:** Finally got it! [Answer] # Python, 164 Works by extracting the text between the code tags. It is quite long but it will always function correctly unless the html page is edited directly or a new code block is added before the one below (having a block of code after should have no effect on the output of the program). ``` import urllib2 print urllib2.urlopen("http://codegolf.stackexchange.com/posts/28617/body").read().split(chr(60)+"code"+chr(62))[1].split(chr(60)+"/code"+chr(62))[0] ``` [Answer] # bash + awk, 71 bytes ``` curl -sL codegolf.stackexchange.com/q/28154 |awk -F\> '/\#/ {print $3}' ``` [Answer] # Javascript, 138 ``` a=window.open("http://codegolf.stackexchange.com/posts/28160/body");setTimeout('alert(a.document.body.innerHTML.match(/a=.*9\\)/)[0])',99) ``` This works assuming that the page loads in under 99 ms. It also has to be run via a console opened on a codegolf.SE page, because of the same origin policy. [Answer] ## Perl 5.10, 155 127 122 117 bytes ``` use XML::LibXML;say XML::LibXML->new->parse_file('http://codegolf.stackexchange.com/posts/28330/body')->find('//pre') ``` Using `XML::LibXML`. [Answer] ## Shell and xmllint, 82 bytes ``` xmllint --xpath 'string(//pre)' http://codegolf.stackexchange.com/posts/28333/body ``` ]
[Question] [ Write a program that will generate a "true" output [iff](http://en.wikipedia.org/wiki/If_and_only_if) the input matches the source code of the program, and which generates a "false" output iff the input does not match the source code of the program. This problem can be described as being related to quines, as the program must be able to somehow compute its own source code in the process. This is code golf: standard rules apply. Your program must not access any special files, such as the file of its own source code. *Edit: If you so choose, true/false can be replaced with True/False or 1/0.* # Example If the source code of your program is `bhiofvewoibh46948732));:/)4`, then here is what your program must do: ## Input (Stdin) ``` bhiofvewoibh46948732));:/)4 ``` ## Output (Stdout) ``` true ``` ## Input ``` (Anything other than your source code) ``` ## Output ``` false ``` [Answer] # JavaScript : 26 ``` function f(s){return s==f} ``` I don't know if a JavaScript file really qualifies as a "program". [Answer] # Haskell, 72 characters ``` main=interact$show.(==s++show s);s="main=interact$show.(==s++show s);s=" ``` Note: there is no end-of-line character at the end of the script. ``` $ runhaskell Self.hs < Self.hs True ``` [Answer] # Perl, ~~Infinity~~ ~~41~~ 38 Characters ``` $_=q(print<>eq"\$_=q($_);eval"|0);eval ``` **Update:** The program no longer ends with a newline, which means it will work correctly on multi-line files. You have to enter input from STDIN without hitting enter. On Windows I was only able to do this by reading from a file. Original solution: ``` print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(print<>==q(... ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 68 bytes Fishes love eating fish poop. Now we know they can distinguish theirs from their friends'. ``` 00v 0+1~$^?)0~\;n0\ >:@@:@gi:0(?\:a=?/=?!/$1+ 0n;n*=f$=2~~/ ``` You can [try it online](https://fishlanguage.com/playground) ! [Answer] ## GolfScript, 11 chars ``` {`".~"+=}.~ ``` Without the `=`, this code would be a quine that generates its own source code as a string. The `=` makes it compare this string to its input and output `1` if they match and `0` if they don't. Note that the comparison is exact — in particular, a trailing newline at the end of the input will cause it to fail. **Explanation:** * `{ }` is a code block literal in GolfScript; * `.` duplicates this code block, and `~` executes the second copy (leaving the first on the stack); * ``` stringifies the code block, and `".~"+` appends `.~` to it; * finally, `=` compares the resulting string with the input (which is pushed on the stack as a string by the GolfScript interpreter before the program starts) and returns `1` if they match and `0` if they don't. [Answer] # Python 2, 55 ``` a='a=%r;print a%%a==raw_input()';print a%a==raw_input() ``` Tested: `a='a=%r;print a%%a==raw_input()';print a%a==raw_input()` -> `True` `(anything else)` -> `False` [Answer] # JavaScript ES6, ~~16~~ 14 bytes ``` $=_=>_==`$=`+$ ``` Minus two bytes thanks to Neil. 31 bytes if we must take input via prompt. ``` $=_=>prompt()==`$=${$};$()`;$() ``` 38 bytes if we must output via alert. ``` $=_=>alert(prompt()==`$=${$};$()`);$() ``` This is the *proper* way to do it, as Optimizer's answer does not accept the entire source code. [Answer] # Node.js : 54 ``` function f(){console.log(f+'f()'==process.argv[2])}f() ``` You test it by saving it into a file `f.js` (the exact name has no importance) and using ``` node f.js "test" ``` (which outputs false) or ``` node f.js "$(< f.js)" ``` (which outputs true) I also made a different version based on eval : ``` eval(f="console.log('eval(f='+JSON.stringify(f)+')'==process.argv[2])") ``` It's now at 72 chars, I'll try to shorten that when I have time. [Answer] # Smalltalk (Pharo 2.0 dialect), 41 bytes Implement this **41** chars method in String (ugly formatting for code-golf): ``` isItMe^self=thisContext method sourceCode ``` Then evaluate this in a Workspace (printIt the traditional Smalltalk way) The input is not read from stdin, it's just a String to which we send the message (what else a program could be in Smalltalk?): ``` 'isItMe^self=thisContext method sourceCode' isItMe. ``` But we are cheating, sourceCode reads some source file... Here is a variant with **51** chars which does not: ``` isItMe ^ self = thisContext method decompileString ``` And test with: ``` 'isItMe ^ self = thisContext method decompileString' isItMe ``` If a String in a Workspace is not considered a valid input, then let's see how to use some Dialog Box in **116** chars Just evaluate this sentence: ``` (UIManager default request: 'type me') = (thisContext method decompileString withSeparatorsCompacted allButFirst: 7) ``` Since decompile format includes CR and TAB, we change that withSeparatorsCompacted. Then we skip the first 7 chars are 'doIt ^ ' Finally a **105** chars variant using stdin, just interpret this sentence from command line, just to feel more mainstream: ``` Pharo -headless Pharo-2.0.image eval "FileStream stdin nextLine = (thisContext method decompileString withSeparatorsCompacted allButFirst: 7)" ``` [Answer] # flex - 312 chars ``` Q \" N \n S " " B \\ P "Q{S}{B}{Q}{N}N{S}{B}n{N}S{S}{Q}{S}{Q}{N}B{S}{B}{B}{N}P{S}{Q}{P}{Q}{N}M{S}{Q}{M}{Q}{N}%%{N}{P}{N}{M}{N} putchar('1');" M "(.|{N})* putchar('0');" %% Q{S}{B}{Q}{N}N{S}{B}n{N}S{S}{Q}{S}{Q}{N}B{S}{B}{B}{N}P{S}{Q}{P}{Q}{N}M{S}{Q}{M}{Q}{N}%%{N}{P}{N}{M}{N} putchar('1'); (.|{N})* putchar('0'); ``` Can probably be made shorter, but it works with multi-line input (necessary since the source code is multiple lines) and even for inputs that contain the program as a substring. It seems many of the answers so far fail on one or both of these. Compile command: `flex id.l && gcc -lfl lex.yy.c` [Answer] ## D (133 chars) ``` enum c=q{import std.stdio;import std.algorithm;void main(){auto i=readln();writeln(equal("auto c=q{"~c~"};mixin(c);",i));}};mixin(c); ``` [Answer] # JavaScript (V8), 35 ``` function i(){alert(prompt()==i+[])} ``` call `i()` and it will prompt for input [Answer] # GolfScript - 26 ``` ":@;[34]@+2*=":@;[34]@+2*= ``` Inspired from <http://esolangs.org/wiki/GolfScript#Examples> Another version: ``` "[34].@@;+2*="[34].@@;+2*= ``` Too bad that `\` is both swap and escape... [Answer] # Python 2, 47 bytes ``` _='_=%r;print _%%_==input()';print _%_==input() ``` A simple quine with the added check. [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` {s"_~"+q=}_~ ``` [Try it online!](https://tio.run/##S85KzP3/v7pYKb5OSbvQtja@DpUHAA "CJam – Try It Online") ### Explanation This just uses the standard CJam quine framework. ``` {s"_~"+q=} e# Push this block (function literal). _~ e# Copy and run it. ``` What the block does: ``` s e# Stringify the top element (this block itself). "_~"+ e# Append "_~". Now the source code is on the stack. q e# Read the input. = e# Check if it equals the source code. ``` [Answer] # Python, 187 bytes ``` import sys;code="import sys;code=!X!;print(sys.stdin.read()==code.replace(chr(33),chr(34)).replace(!X!,code,1))";print(sys.stdin.read()==code.replace(chr(33),chr(34)).replace("X",code,1)) ``` Careful not to add newline at the end. Someone with better Python-fu might be able to shorten it. [Answer] ## Tcl, 111 chars ``` set c {set c {$c};puts [expr {[read stdin] eq [subst -noc \$c]}]};puts [expr {[read stdin] eq [subst -noc $c]}] ``` [Answer] ## Perl, 52 char ``` $_='$/=$\;$_="\$_=\47$_\47;eval";print<>eq$_|0';eval ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` =hS+s"=hS+s ``` [Try it online!](https://tio.run/##yygtzv7/3zYjWLtYCUz@h/JiIFwA "Husk – Try It Online") ### Explanation The explanation uses `¨` to delimit strings (to avoid unreadable escaping): ``` "=hS+s -- string literal: ¨=hS+s¨ S+ -- join itself with s -- | itself "showed": ¨"=hS+s"¨ -- : ¨=hS+s"=hS+s"¨ h -- init: ¨=hS+s"=hS+s¨ = -- is the input equal? ``` By removing the function `=` you can [verify](https://tio.run/##yygtzv7/PyNYu1jJFkT@/w8A "Husk – Try It Online") that it will indeed only match the source itself. [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` s="print's=%r;exec s'%s==input()";exec s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWqaAoM69EvdhWtcg6tSI1WaFYXbXY1jYzr6C0RENTCSr2/7@SkhKxioFKAQ "Python 2 – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), 24 bytes ``` '1rd3*i={*}50l3-?.~i)*n; ``` [Try it online!](https://tio.run/##S8sszvj/X92wKMVYK9O2WqvW1CDHWNdery5TUyvPGrcMAA "><> – Try It Online") Wrapping string literal followed by checking whether the input is identical to the stack, with a final check that there is no more input. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` “Ṿ;$⁼”Ṿ;$⁼ ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZqzxq3POoYS6M@f9w@6OmNf//R6tjl1fX4VJQR4gjK0GTQtWCRymYg64ILBELAA "Jelly – Try It Online") ``` “Ṿ;$⁼”Ṿ;$⁼ “Ṿ;$⁼” String literal: 'Ṿ;$⁼' $ Next two links act on the string literal Ṿ Uneval: '“Ṿ;$⁼”' ; Append string: '“Ṿ;$⁼”Ṿ;$⁼' (source code) ⁼ Is the string above equal to the input? ``` [Answer] # [Zsh](https://www.zsh.org/), 33 bytes ``` f () { [ "`type -f f`" = $1 ] } ``` [Try it online!](https://tio.run/##qyrO@P8/TUFDU6GaizNaQSmhpLIgVUE3TSEtQUnBVkHFUCGWq5YLqEJJRQMupanElZqcka@gYs/FpayQmJKiUFKUmJmTmZeuUFyQmJzKhaZcAbf6vNRyII2hgwtFR1Fqbn5ZKnZN1cjaVO1r4Rr/AwA "Zsh – Try It Online") The extra spaces, tab, and newlines are required. `type -f f` does not print the original source, but the function formatted in a particular way, with indentation and a trailing newline. [Answer] # [R](https://www.r-project.org/), 54 bytes ``` f=function(s)s==paste0("f=function(s)s==", body(f)[3]) ``` [Try it online!](https://tio.run/##K/r/P802rTQvuSQzP0@jWLPY1rYgsbgk1UBDCV1cSUchKT@lUiNNM9o4VvN/moY6eTrVNbmAehOTklPUNf8DAA "R – Try It Online") `body` gets the body of the function (splitting it a bit, so that `body(f)[3]` is everything from `paste0` onwards). Interestingly, `body` reformats the code, adding spaces after commas, etc. This is thus a rare case of an R golf answer with a space after a comma. This works because `body(f)` is an object of type `language`, and there exists an `as.character` method for this type. On the other hand, `f` and `args(f)` are of type `closure`, and cannot be converted to character type as far as I can tell. Please don't ask me what the language type is for… [Answer] # [R](https://www.r-project.org/) (version-dependent), 46 bytes ``` f=function(x)x==paste0('f=',capture.output(f)) ``` `capture.output` - as the function name suggests - retrieves the text string that results from entering the function name `f` directly to [R](https://www.r-project.org/), which should output the body of the function. We manually prepend this with `f=` so that it exactly\* matches the program code, and check whether the function argument `x` is the same as this. \*See below There are a couple of caveats, though, that depend on the [R](https://www.r-project.org/) version used: 1. Early versions of [R](https://www.r-project.org/) (like my own version 3.2.1) return the originally-defined function body as-is when the function name is entered to [R](https://www.r-project.org/). However, later versions add additional formatting, like inserting spaces and newlines, which breaks this code: this unfortunately includes the installation (3.5.2) on 'Try it online'. Later still, much newer [R](https://www.r-project.org/) versions (I tested 4.0.3) return to the as-is output formatting and everything is Ok again... except... 2. The most recent versions of [R](https://www.r-project.org/) compile functions at the first run, and thereafter append a 'byte code' specific for the compiled function to the outputted function body. This means that `capture.output` returns two strings, beginning at the second time the function is run. Luckily, the function body is still the first one (the byte code is the second one), so the result of supplying the program code as input is `TRUE FALSE`, which evaluates to 'truthy' in [R](https://www.r-project.org/) and so counts as a 'true' output for this challenge. Special thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) for helping to uncover the version-dependence of [R](https://www.r-project.org/)'s function outputting. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 12 bytes ``` `:q$+=`:q$+= ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%3Aq%24%2B%3D%60%3Aq%24%2B%3D&inputs=%60%3Aq%24%2B%3D%60%3Aq%24%2B%3D&header=&footer=) I finished making this, and then realized that it is almost identical to the Vyxal quine that @Lyxal wrote, but with the addition of `=` to check if the input is equal. Explanation: ``` # Implicit input `:q$+=` # Push the string ':q$+=' : # Duplicate the string q # Quotify; put backticks around the topmost string $ # Swap the top two values on the stack + # Concatenate the two strings = # Check if the input is equal to the string # Implicit output ``` [Answer] ## C - 186 176 characters One liner: ``` *a="*a=%c%s%c,b[999],c[999];main(){sprintf(b,a,34,a,34);gets(c);putchar(strcmp(b,c)?'0':'1');}",b[999],c[999];main(){sprintf(b,a,34,a,34);gets(c);putchar(strcmp(b,c)?'0':'1');} ``` With whitespace (note that this breaks the program): ``` *a="*a=%c%s%c,b[999],c[999];main(){sprintf(b,a,34,a,34);gets(c);putchar(strcmp(b,c)?'0':'1');}",b[999],c[999]; main() { sprintf(b,a,34,a,34); gets(c); putchar(strcmp(b,c)?'0':'1'); } ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 26 bytes ``` "34bLN26)s:f="34bLN26)s:f= ``` [Run and debug it](https://staxlang.xyz/#c=%2234bLN26%29s%3Af%3D%2234bLN26%29s%3Af%3D&i=%2234bLN26%29s%3Af%3D%2234bLN26%29s%3Af%3D%0A%2234bLN26%29s%3Af%3D%2234bLN26%29s%3Afb%0Aabc%0A34&m=2) [Answer] ## JavaScript ES6, 14 bytes Like the other javascript answer but includes it's entire source code and not just the function ``` a=q=>'a='+a==q ``` Example usage: ``` a("q=>'a='+a==q") // returns false a("a=q=>'a='+a==q") // returns true ``` [Answer] # q, 8 bytes ``` {x~.z.s} ``` Return boolean on input matching the self-referential [.z.s](https://code.kx.com/q/ref/dotz/#zs-self) ]
[Question] [ # Introduction In order to prevent keyloggers from stealing a user's password, a certain bank account system has implemented the following security measure: only certain digits are prompted to be entered each time. For example, say your target's password is `89097`, the system may prompt them to enter the 2nd, 4th and 5th digit: `997` Or it might prompt them to enter the 1st, 3rd and 5th digit: `807` All you know is that your target entered the digits in order, *but you don't know which position they belong to in the actual password*. All you know is there are two 9s, which must come before 7; and that 8 comes before 0, and 0 before 7. Therefore, there are six possible passwords: ``` 80997 89097 89907 98097 98907 99807 ``` The keylogger in your target's computer has been collecting password inputs for months now, so let's hack in! # Challenge Given a list of three-digit inputs, output all the possible passwords that are valid for all inputs. In order to reduce computational complexity and to keep the amount of possible results low, the password is guaranteed to be numerical and have a fixed size of 5. The digits in every input are in order: if it's 123, the target typed 1 first, then 2, then 3. # Input/Output examples ``` |----------------------|--------------------------------------------| | Input | Output | |----------------------|--------------------------------------------| | [320, 723, 730] | [37230, 72320, 73203, 73230] | | [374, 842] | [37842, 38742, 83742] | | [010, 103, 301] | [30103] | | [123, 124, 125, 235] | [12345, 12354, 12435] | | [239, 944] | [23944] | | [111, 120] | [11201, 11120, 11210, 12011, 12110, 12101] | | [456, 789] | [] | | [756, 586] | [07586, 17586, 27586, 37586, 47586, 57586, 57856, 58756, 67586, 70586, 71586, 72586, 73586, 74586, 75086, 75186, 75286, 75386, 75486, 75586, 75686, 75786, 75806, 75816, 75826, 75836, 75846, 75856, 75860, 75861, 75862, 75863, 75864, 75865, 75866, 75867, 75868, 75869, 75876, 75886, 75896, 75986, 76586, 77586, 78586, 79586, 87586, 97586] | | [123] | [00123, 01023, 01123, 01203, 01213, 01223, 01230, 01231, 01232, 01233, 01234, 01235, 01236, 01237, 01238, 01239, 01243, 01253, 01263, 01273, 01283, 01293, 01323, 01423, 01523, 01623, 01723, 01823, 01923, 02123, 03123, 04123, 05123, 06123, 07123, 08123, 09123, 10023, 10123, 10203, 10213, 10223, 10230, 10231, 10232, 10233, 10234, 10235, 10236, 10237, 10238, 10239, 10243, 10253, 10263, 10273, 10283, 10293, 10323, 10423, 10523, 10623, 10723, 10823, 10923, 11023, 11123, 11203, 11213, 11223, 11230, 11231, 11232, 11233, 11234, 11235, 11236, 11237, 11238, 11239, 11243, 11253, 11263, 11273, 11283, 11293, 11323, 11423, 11523, 11623, 11723, 11823, 11923, 12003, 12013, 12023, 12030, 12031, 12032, 12033, 12034, 12035, 12036, 12037, 12038, 12039, 12043, 12053, 12063, 12073, 12083, 12093, 12103, 12113, 12123, 12130, 12131, 12132, 12133, 12134, 12135, 12136, 12137, 12138, 12139, 12143, 12153, 12163, 12173, 12183, 12193, 12203, 12213, 12223, 12230, 12231, 12232, 12233, 12234, 12235, 12236, 12237, 12238, 12239, 12243, 12253, 12263, 12273, 12283, 12293, 12300, 12301, 12302, 12303, 12304, 12305, 12306, 12307, 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317, 12318, 12319, 12320, 12321, 12322, 12323, 12324, 12325, 12326, 12327, 12328, 12329, 12330, 12331, 12332, 12333, 12334, 12335, 12336, 12337, 12338, 12339, 12340, 12341, 12342, 12343, 12344, 12345, 12346, 12347, 12348, 12349, 12350, 12351, 12352, 12353, 12354, 12355, 12356, 12357, 12358, 12359, 12360, 12361, 12362, 12363, 12364, 12365, 12366, 12367, 12368, 12369, 12370, 12371, 12372, 12373, 12374, 12375, 12376, 12377, 12378, 12379, 12380, 12381, 12382, 12383, 12384, 12385, 12386, 12387, 12388, 12389, 12390, 12391, 12392, 12393, 12394, 12395, 12396, 12397, 12398, 12399, 12403, 12413, 12423, 12430, 12431, 12432, 12433, 12434, 12435, 12436, 12437, 12438, 12439, 12443, 12453, 12463, 12473, 12483, 12493, 12503, 12513, 12523, 12530, 12531, 12532, 12533, 12534, 12535, 12536, 12537, 12538, 12539, 12543, 12553, 12563, 12573, 12583, 12593, 12603, 12613, 12623, 12630, 12631, 12632, 12633, 12634, 12635, 12636, 12637, 12638, 12639, 12643, 12653, 12663, 12673, 12683, 12693, 12703, 12713, 12723, 12730, 12731, 12732, 12733, 12734, 12735, 12736, 12737, 12738, 12739, 12743, 12753, 12763, 12773, 12783, 12793, 12803, 12813, 12823, 12830, 12831, 12832, 12833, 12834, 12835, 12836, 12837, 12838, 12839, 12843, 12853, 12863, 12873, 12883, 12893, 12903, 12913, 12923, 12930, 12931, 12932, 12933, 12934, 12935, 12936, 12937, 12938, 12939, 12943, 12953, 12963, 12973, 12983, 12993, 13023, 13123, 13203, 13213, 13223, 13230, 13231, 13232, 13233, 13234, 13235, 13236, 13237, 13238, 13239, 13243, 13253, 13263, 13273, 13283, 13293, 13323, 13423, 13523, 13623, 13723, 13823, 13923, 14023, 14123, 14203, 14213, 14223, 14230, 14231, 14232, 14233, 14234, 14235, 14236, 14237, 14238, 14239, 14243, 14253, 14263, 14273, 14283, 14293, 14323, 14423, 14523, 14623, 14723, 14823, 14923, 15023, 15123, 15203, 15213, 15223, 15230, 15231, 15232, 15233, 15234, 15235, 15236, 15237, 15238, 15239, 15243, 15253, 15263, 15273, 15283, 15293, 15323, 15423, 15523, 15623, 15723, 15823, 15923, 16023, 16123, 16203, 16213, 16223, 16230, 16231, 16232, 16233, 16234, 16235, 16236, 16237, 16238, 16239, 16243, 16253, 16263, 16273, 16283, 16293, 16323, 16423, 16523, 16623, 16723, 16823, 16923, 17023, 17123, 17203, 17213, 17223, 17230, 17231, 17232, 17233, 17234, 17235, 17236, 17237, 17238, 17239, 17243, 17253, 17263, 17273, 17283, 17293, 17323, 17423, 17523, 17623, 17723, 17823, 17923, 18023, 18123, 18203, 18213, 18223, 18230, 18231, 18232, 18233, 18234, 18235, 18236, 18237, 18238, 18239, 18243, 18253, 18263, 18273, 18283, 18293, 18323, 18423, 18523, 18623, 18723, 18823, 18923, 19023, 19123, 19203, 19213, 19223, 19230, 19231, 19232, 19233, 19234, 19235, 19236, 19237, 19238, 19239, 19243, 19253, 19263, 19273, 19283, 19293, 19323, 19423, 19523, 19623, 19723, 19823, 19923, 20123, 21023, 21123, 21203, 21213, 21223, 21230, 21231, 21232, 21233, 21234, 21235, 21236, 21237, 21238, 21239, 21243, 21253, 21263, 21273, 21283, 21293, 21323, 21423, 21523, 21623, 21723, 21823, 21923, 22123, 23123, 24123, 25123, 26123, 27123, 28123, 29123, 30123, 31023, 31123, 31203, 31213, 31223, 31230, 31231, 31232, 31233, 31234, 31235, 31236, 31237, 31238, 31239, 31243, 31253, 31263, 31273, 31283, 31293, 31323, 31423, 31523, 31623, 31723, 31823, 31923, 32123, 33123, 34123, 35123, 36123, 37123, 38123, 39123, 40123, 41023, 41123, 41203, 41213, 41223, 41230, 41231, 41232, 41233, 41234, 41235, 41236, 41237, 41238, 41239, 41243, 41253, 41263, 41273, 41283, 41293, 41323, 41423, 41523, 41623, 41723, 41823, 41923, 42123, 43123, 44123, 45123, 46123, 47123, 48123, 49123, 50123, 51023, 51123, 51203, 51213, 51223, 51230, 51231, 51232, 51233, 51234, 51235, 51236, 51237, 51238, 51239, 51243, 51253, 51263, 51273, 51283, 51293, 51323, 51423, 51523, 51623, 51723, 51823, 51923, 52123, 53123, 54123, 55123, 56123, 57123, 58123, 59123, 60123, 61023, 61123, 61203, 61213, 61223, 61230, 61231, 61232, 61233, 61234, 61235, 61236, 61237, 61238, 61239, 61243, 61253, 61263, 61273, 61283, 61293, 61323, 61423, 61523, 61623, 61723, 61823, 61923, 62123, 63123, 64123, 65123, 66123, 67123, 68123, 69123, 70123, 71023, 71123, 71203, 71213, 71223, 71230, 71231, 71232, 71233, 71234, 71235, 71236, 71237, 71238, 71239, 71243, 71253, 71263, 71273, 71283, 71293, 71323, 71423, 71523, 71623, 71723, 71823, 71923, 72123, 73123, 74123, 75123, 76123, 77123, 78123, 79123, 80123, 81023, 81123, 81203, 81213, 81223, 81230, 81231, 81232, 81233, 81234, 81235, 81236, 81237, 81238, 81239, 81243, 81253, 81263, 81273, 81283, 81293, 81323, 81423, 81523, 81623, 81723, 81823, 81923, 82123, 83123, 84123, 85123, 86123, 87123, 88123, 89123, 90123, 91023, 91123, 91203, 91213, 91223, 91230, 91231, 91232, 91233, 91234, 91235, 91236, 91237, 91238, 91239, 91243, 91253, 91263, 91273, 91283, 91293, 91323, 91423, 91523, 91623, 91723, 91823, 91923, 92123, 93123, 94123, 95123, 96123, 97123, 98123, 99123] | |----------------------|--------------------------------------------| ``` --- # Rules * Input is guaranteed non-empty. * Leading and trailing zeros matter: `01234` is different from `12340`, and `1234` doesn't crack either password. Think of how real passwords work! * [Standard I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply. * No [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. Non-codegolfing languages are welcome! [Answer] # Python, 100 bytes ``` lambda e,d='%05d':[d%i for i in range(10**5)if all(re.search('.*'.join(x),d%i)for x in e)] import re ``` [Try it online!](https://tio.run/##PcuxCoMwEADQvV9xi1wiQaLgIvgl1iFtLvWKJuF0sF@f1qXrg5c/x5JiV8J4L6vbHt4BGT9iZXuPw@QrhpAEGDiCuPgi1dq67jUHcOuqhJqdnDwXhU2NzTtxVKc2v6avdl6N9HzjLSc5QKj8OagJrbVoANvO4qwHyMLxgLN8AQ "Python 2 – Try It Online") Works in Python 2 as well as Python 3. (**97 bytes** in Python 3.8:) ``` lambda e:[p for i in range(10**5)if all(re.search('.*'.join(x),p:='%05d'%i)for x in e)] import re ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 9 bytes ``` žh5ãʒæIåP ``` [Try it online!](https://tio.run/##yy9OTMpM/f//6L4M08OLT006vMzz8NKA//@jzU3NdEwtzGIB "05AB1E – Try It Online") **Explanation** ``` žh # push 0123456789 5ã # 5 times cartesian product ʒ # filter, keep only values are true under: æ # powerset of value Iå # check if each of the input values are in this list P # product ``` [Answer] # JavaScript (ES6), 88 bytes Prints the results with `alert()`. ``` a=>{for(k=n=1e5;n--;)a.every(x=>(s=([k]+n).slice(-5)).match([...x].join`.*`))&&alert(s)} ``` [Try it online!](https://tio.run/##bZLfboIwFMbvfYpeSbtB7V@BEHwRQmLD6qYyWIAYF@Ozs1OaMDVw0V97vu98p2k4mYvpq@74M0RN@2HHQz6afHc7tB0@503Orc6aKMqIofZiu198zXe4z3FxLt8bQvv6WFkcaULotxmqL1xQSq8lPbXHZk/f9oSs16a23YB7ch@nHcpR1TZ9W1tat5/ZarC9qxmU79DtUcJmisFBiAJCMnTABtZHAxzvqykAF4EUzDljISdIFpTIfwRtNqiQoLAQwSocYJUTJCvniFi53kSJufclAqQQySR2SMAu5l7Gp/GcTeMl46/jwSBnN/e35EJ5aAchdVB6N@hKhwiglYOSeu4VMnXuVKnlW4Ku1P8kzv0ItuzmoHAY4egguAPUXFFwf@KMz4FKb6cHTtLlwNkYe6NOtstGFoME6R7w34QodfunR3rpfA5g4AgRPKyDD0ihVI5/ "JavaScript (Node.js) – Try It Online") ### Commented ``` a => { // a[] = input array of 3-character strings for(k = n = 1e5; n--;) // initialize k to 100000; for n = 99999 to 0: a.every(x => // for each string x = 'XYZ' in a[]: ( s = // define s as the concatenation of ([k] + n) // '100000' and n; e.g. '100000' + 1337 -> '1000001337' .slice(-5) // keep the last 5 digits; e.g. '01337' ).match( // test whether this string is matching [...x].join`.*` // the pattern /X.*Y.*Z/ ) // ) && // end of every(); if all tests were successful: alert(s) // output s } // ``` [Answer] ## Haskell, ~~81~~ ~~80~~ ~~78~~ 76 bytes ``` f x=[p|p<-mapM(:['1'..'9'])"00000",all(`elem`(concat.words<$>mapM(:" ")p))x] ``` The obvious brute force approach in Haskell: built a list of all possible passwords and keep those where all elements from the input list are in respective list of subsequences. [Try it online!](https://tio.run/##RY5dCoMwEITfe4olFDRgJX9WLdob9AQSMLRKpVGDCvWhd7dNLLovAzPf7O5Tja9K62WpYc4L8zHZqVXm5l8Kj3ph6KWexIjYQYHS2i8rXbWlf@@7u5rCdz88xux4XSsIEDYYz3JpVdNBDtYG3wxNN0FYYygOAFAgzn7LAMWMO@EEyeCfxMJaiWCbRaiDKXEwJ3RL6NqnTKwSWWE82gDGU2ulQuwdSld4vymis3sjSZGUsHwB "Haskell – Try It Online") Edit: -1 byte thanks to @xnor, ~~-2~~ -4 bytes thanks to @H.PWiz [Answer] # [Python 2](https://docs.python.org/2/), 96 bytes ``` l=input() n=1e5 while n: n-=1;s='%05d'%n;t={''} for c in s:t|={x+c for x in t} if l<t:print s ``` [Try it online!](https://tio.run/##PY3bCoMwEETf8xVBkLS0hWwuXpuvsUoDEkVTarF@u01W6MssZ2aYHT/@OTixv5@2bylU7dI2SZLsvbFufPnTmTgDrSZH7ipC3c1APRuWcv1gqau9WRnbCO2GiTbUOjpX/mvW5dKgtUTLh9x2tL/7apys83Te8ZL4amVScHZluZBRJQ9rwctVoEIJJA6xATw2JAf0APsgFKoOKqTGRMgyUKnU0QPAxrGrdBa/FCVSjqSL7L@4/QA "Python 2 – Try It Online") Takes input as a set of strings. --- # [Python 3](https://docs.python.org/3/), 98 bytes ``` f=lambda l,s='':any(l)or print(s)if s[4:]else[f([x[x[:1]==c:]for x in l],s+c)for c in'0123456789'] ``` [Try it online!](https://tio.run/##LU5da4QwEHw2vyJvm7QW8nlqIL9E8mCtcoE0Jxfb3v16u7FlYZjdGWZ2e@7XW9bHsfo0fb5/TDS1xQO4KT9Z4rc73e4x76zwuNIyGheWVJZxZeMDx8ng/ezCir4HjZmm0JbXmdd9xh2EVNrYS9cPEI6fa0wLlY40yadYdrZ8T4nFvH3tjHNOmhUbSfNXCG/wYvkBWglooVO6ohZAQHcGeW8UciGrKkVVtZB4kadTKnOiRVTa4l3pAflgTPVIeao1Db@ryfggge7ktr/85/wC "Python 3 – Try It Online") Recursively tries building every five-digit number string in `s`, tracking the subsequences in `l` still remaining to be hit. If all are empty by the end, prints the result. [Answer] # [Ruby](https://www.ruby-lang.org/), 54 bytes ``` ->a{(?0*5..?9*5).select{|x|a.all?{|y|x=~/#{y*'.*'}/}}} ``` [Try it online!](https://tio.run/##RY3LCoMwEEX3@QpJobbBpnn6KFg/RFykoriwIGpBSdJft8QIXV3OzJm54@e1bm2@3Z5KXwqCJMZFhuQVT03f1LM2i1FY9X2hzWqW/Hs/6RWFGIX2bq3dSlBCzgiMApgwvgcnsIrcOBGOU8E8E7prlOwaJ9SPqT@jTPiQLhiXfst45jgT4rAp9dpRImS8l6aZ58SzTOP/9wpUuFF1p81shqAtZ/xWQ3B@1J0ap8oCsP0A "Ruby – Try It Online") Takes input as an arrray of character arrays. [Answer] # Pyth, 11 bytes ``` f<QyT^s`MT5 ``` Takes input as a set of strings. [Try it here](http://pyth.herokuapp.com/?code=f%3CQyT%5Es%60MT5&input=%7B%22123%22%2C%20%22124%22%2C%20%22125%22%2C%20%22235%22%7D&debug=0) ### Explanation ``` f<QyT^s`MT5 s`MT Take the digits as a string. ^ 5 Take the Cartesian product with itself 5 times. f T Filter the ones... <Qy ... where the input is a subset of the power set. ``` [Answer] # [R](https://www.r-project.org/), ~~80~~ 81 bytes ``` Reduce(intersect,lapply(gsub("",".*",scan(,"")),grep,substr(1e6:199999,2,6),v=T)) ``` [Try it online!](https://tio.run/##FclZCoQwEEXRrUh9VclDSByghd6EuAGNhTSIhAxCrz7qhfN1QymTbtkp/86kIapLOBbvjz/vMa9MBGpqQnTLySASwR7U43kxBTY6jObzBotBcH1nkWJsWxnbPfrKtn25AQ "R – Try It Online") Here’s a base R solution using regex. Writing this nested series of functions made me realise how much I’ve learned to appreciate the magrittr package! Initially hadn’t read rules on input, so now reads from stdin (thanks @KirillL). Thanks to @RobinRyder for saving a byte! [Try it online!](https://tio.run/##FctRCkBAEIDhq2hKzWiSXfaBcgm5ALtDStp2UU6/@Ot7/ENKg7jLCm7HKSGKPXmfvN8fXOM1IwBDWQBHOx3IAES8BvEcffiGBSGvjAOuuvaP@O5HoqR0nSndfEyma5Ne "R – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` 9Żṗ5ŒPiⱮẠɗƇ ``` [Try it online!](https://tio.run/##y0rNyan8/9/y6O6HO6ebHp0UkPlo47qHuxacnH6s/f///9HRxjoK5joKJrE6CtEWQFpHwSg2FgA "Jelly – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 53 bytes ``` ~(` .$* m`^ G` ^ K`¶5+%`$$¶0"1"2"3"4"5"6"7"8"9¶ " $$" ``` [Try it online!](https://tio.run/##K0otycxLNPz/v04jgUtPRYsrNyGOyz2BK47LO@HQNlNt1QQVlUPbDJQMlYyUjJVMlEyVzJTMlSyULA9t41LiUlFR@v/f2MiAy9zImMvc2AAA "Retina – Try It Online") Explanation: ``` ~(` ``` After executing the script, take the result as a new script, and execute that, too. ``` .$* ``` Insert `.*` everywhere. This results in `.*3.*2.*0.*` although we only need `3.*2.*0`, not that it matters. ``` m`^ G` ``` Insert a `G`` at the start of each line. This turns it into a Retina Grep command. ``` ^ K`¶5+%`$$¶0"1"2"3"4"5"6"7"8"9¶ " $$" ``` Prefix two more Retina commands. The resulting script will therefore look something like this: ``` K` ``` Clear the buffer (which contains the original input). ``` 5+ ``` Repeat 5 times... ``` %`$ ``` ... append to each line... ``` 0$"1$"2$"3$"4$"5$"6$"7$"8$"9 ``` ... the digit `0`, then a copy of the line, then the digit `1`, etc. until `9`. This means that after `n` loops you will have all `n`-digit numbers. ``` G`.*3.*2.*0.* G`.*7.*2.*3.* G`.*7.*3.*0.* ``` Filter out the possible numbers based on the input. [Answer] # [Perl 5](https://www.perl.org/) `-MList::Util=all -a`, 70 bytes ``` map{$t=sprintf'%05d',$_;(all{$t=~/$_/}map s//.*/gr,@F)&&say$t}0..99999 ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saBapcS2uKAoM68kTV3VwDRFXUcl3lojMScHJFGnrxKvXwtUpVCsr6@npZ9epOPgpqmmVpxYqVJSa6CnZwkC//8bGFsqWJqY/MsvKMnMzyv@r@trqmdgaACkfTKLS6ysQksyc2yBZv7XTQQA "Perl 5 – Try It Online") ### Old Approach: [Perl 5](https://www.perl.org/) `-a`, ~~80~~ 77 bytes *Credit to @NahuelFouilleul for -2 bytes* ``` map{s||($t=0)x(5-y///c)|e;for$b(map s//.*/gr,@F){$t+=/$b/}$t-@F||say}0..99999 ``` [Try it online!](https://tio.run/##K0gtyjH9/z83saC6uKZGQ6XE1kCzQsNUt1JfXz9ZsybVOi2/SCVJAyivUKyvr6eln16k4@CmWa1Som2rr5KkX6tSouvgVlNTnFhZa6CnZwkC//8bGVsqWJqY/MsvKMnMzyv@r@trqmdgaPBfNxEA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~79~~ 77 bytes ``` ->x{(0...1e5).map{|i|'%05d'%i}.select{|i|x.all?{|c|i=~/#{c.gsub('','.*')}/}}} ``` [Try it online!](https://tio.run/##Lc/LTsMwEAXQPV9hCUWToOL6/VgEPqR00aYpihSkilJRlJhfD/E1m2PP9Vgef96OP8u5fVueX@5TLTjnsrcN/zhcpnmYqRL2RNWQ@LUf@@4rZ3d@GMfXae7mof3dPk4df7/ejjXRhvgTNWmbUlou7LzbkVaCNoy80li0oP3@oRx563Jmg1sz1ras@q6FX0smoYIaGmj/DXY1rPeZQ@IFlFBBDQ20AkqooIYGlh4HPQwCSqighgZa6ASUUEENDbSwdHoYYMx65OWtmI157zBJ@VGAMRuQxGyz/AE "Ruby – Try It Online") Input is an array of strings. Here's a more readable version of the same code: ``` def f(codes) (0...10**5).map{|i| '%05d'%i}.select do |i| codes.all? do |code| i =~ Regexp.new(code.chars.join('.*')) end end end ``` [Answer] # PHP 128 bytes ``` for(;$i++<1e5;$k>$argc||print$s)for($k=0;$n=$argv[++$k];)preg_match("/$n[0].*$n[1].*$n[2]/",$s=sprintf("%05d ",$i-1))||$k=$argc; ``` or ``` for(;$i<1e5;$i+=$k<$argc||print$s)for($k=0;$n=$argv[++$k];)if(!preg_match("/$n[0].*$n[1].*$n[2]/",$s=sprintf("%05d ",$i)))break; ``` take input from command line arguments. Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/b914abb3a3b0adb98b54e1727d1f03652957c66c). [Answer] # [J](http://jsoftware.com/), 52 bytes ``` (>,{;^:4~i.10)([#~]*/@e."2((#~3=+/"1)#:i.32)#"_ 1[)] ``` [Try it online!](https://tio.run/##jdhPqxzHFYbxvT5FIwXfexP7uqvqnPpzjYMh4FVW2Q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u2AW7YBfsgl2wC3bBLtgFu2AX7IJdsAt2wS7YBbtgF@yCXbALdsEu2CW7ZJflvt52yS7ZJbtkl@ySXbJLdsku2SW7ZJfskl2yS3bJLtklu2SX7JJdskt2yS7ZJbtkl@ySXbJLdsmus@vsermvt11n19l1dp1dZ9fZdXadXWfX2XV2nV1n19l1dp1dZ9fZdXadXWfX2XV2nV1n19l1dp1dZ9fZdXadXWc32A12o9zX/smR3WA32A12g91gN9gNdoPdYDfYDXaD3WA32A12g91gN9gNdoPdYDfYDXaD3WA32A12g91gN9gNdoPdZDfZzXJfb7vJbrKb7Ca7yW6ym@wmu8luspvsJrvJbrKb7Ca7yW6ym@wmu8luspvsJrvJbrKb7Ca7yW6ym@wmu8lusVvsVrmvt91it9gtdovdYrfYLXaL3WK32C12i91it9gtdovdYrfYLXaL3WK32C12i91it9gtdovdYrfYLXaL3drtHz78Bw "J – Try It Online") [Answer] # Japt, 21 bytes ``` 1e5o ù'0 f@e_XèZË+".* ``` [Try it!](https://ethproductions.github.io/japt/?v=1.4.6&code=MWU1byD5JzAgZkBlX1joWssrIi4q&input=WyI3NTYiLCAiNTg2Il0KLVE=) ``` 1e5o ù'0 f@e_XèZË+".* # full program 1e5o # generate numbers under 100k ù'0 # left pad with 0's f@ # filter array e_ # check every element of input array Xè # X is the number to be tested. # test it against a regex. ZË+".* # the regex is an element from the input array # with wildcards injected between each character ``` -2 bytes thanks to @Shaggy! [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 116 bytes ``` x=>{for(int i=0;i<1e5;){var s=$"{i++:D5}";if(x.All(t=>t.Aggregate(-6,(a,c)=>s.IndexOf(c,a<0?a+6:a+1))>0))Print(s);}} ``` [Try it online!](https://tio.run/##fc09a8MwFIXhPb/CiA662DFXdj5KZKkYuhQK7dYhZBCqZC4EBSTRGox/u9t66pTpLA/ntWlrEy29zXQLXcqRwnC@aK@WUenJ3yKnkAtSKKkTbi9h@jKxSOqBTVSWp@f9zCR5Ptb99cqz0rnuhyG6wWTHt4eKm8qC0ql@CZ9ufPPcVqbDJ1MeTqYUABoB3n@bmSeQ87zIjefBfZ8vE2sbZFXBjk27TotsBrn5iJTdKwXH4b897v7Q4665g1CshwLXwxbFPYtrbvkB "C# (Visual C# Interactive Compiler) – Try It Online") ``` // x: input list of strings x=>{ // generate all numbers under 100k for(int i=0;i<1e5;){ // convert the current number to // a 5 digit string padded with 0's var s=$"{i++:D5}"; // test all inputs against the 5 digit // string using an aggregate. // each step of the aggregate gets // the index of the next occurrence // of the current character starting // at the previously found character. // a negative index indicates error. if(x.All(t=>t .Aggregate(-6,(a,c)=> s.IndexOf(c,a<0?a+6:a+1) )>0)) // output to STDOUT Print(s); } } ``` **EDIT:** fixed a bug where the same character was counted more than once. For example, if `000` was logged, the function used to return all passwords containing a single `0`. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 113 bytes ``` import StdEnv,Data.List $l=[s\\s<-iter 5(\p=[[c:e]\\e<-p,c<-['0'..'9']])[[]]|all(flip any(subsequences s)o(==))l] ``` [Try it online!](https://tio.run/##LY2xCsIwFAB3vyKDkBbaIi0iSrPpIHQQHF8yPGMqgZe0Nqkg@O1GQbe7W06TQZ/ccJ3JMIfWJ@vGYYrsHK8H/yj2GLHqbIiLJQkIUoa2tNFMbJ3JUQDonVFSmrYcC92WwFe8qviWK5UDKPVCoqwnOzL0zyzMl2Dus/HaBBbyIRMiz0mlc8TvULAlA@BNveKqYMA3dfOH5ltUeuue8BZSeezS/unRWf2TE2Hsh8l9AA "Clean – Try It Online") [Answer] ## K 67 bytes ``` {n@&{&/y in\:x@/:&:'a@&3=+/'a:(5#2)\:'!32}[;x]'n:{"0"^-5$$x}'!_1e5} ``` K has a (very) primitive regex capability, so i tried a different approach. {...} defines a lambda. Use example: `{...}("320";"723";"730")` returns `("37230";"72320";"73203";"73230")` * `n` is the list of integers in range 0..9999 as 0-padded strings + `_1e5` applies floor to float 1e5 (scientific notation) -> generates integer 100000 + `!_1e5` generates integer-list 0..99999 + `{..}'!_1e5` applies lambda to each value in 0..99999 + `$x` transform argument x (implicit arg) to string + `-5$$x` right adjust string $x to a field of size 5 (ex. `-5$$12` generates `" 12"` + `"0"^string` replaces blanks with "0" char, so `"0"^-5$$12` generates `"00012"` * `a` is the list of integers in the range 0..31 as 5-bit values + `!32` generate values 0..31 + `(5#2)` repeat 2 five times (list 2 2 2 2 2) + `(5#2)\:'!32` generates 5-bit values (2-base five-times) for each value in range 0..31 * we filter the values of a with exactly 3 ones. That values are all the combinations (places) where pattern can be located: `11100 11010 11001 10110 10101 10011 01110 01101 01011 00111`. Ex. for "abc" pattern we have equivalence with regexs `abc?? ab?c? ab??c a?bc? a?b?c a??bc ?abc? ?ab?c ?a?bc ??abc?` + `+\'a` calculates sum of each binary representation (number of ones) + `3=+\'a` generates list of booleans (if each value in a has exactly 3 ones) + `a@&3=+\'a` reads as "a at where 3=+\'a is true" * generate list of indexes for previous places: `(0 1 2; 0 1 3; 0 1 4; 0 2 3; 0 2 4; 0 3 4; 1 2 3; 1 2 4; 1 3 4; 2 3 4)` and the possible entered-values for a password (x) + `&:'` reads as "where each", applies to list of binary-coded integers, and calculates indexes of each 1-bit + `x@/:` applies password x to each elem of the list of indexes (generates all possible entered values) * Determines if all patterns are located in the list of all possible entered values + `y` is the arg that represent list of patterns + `y in\:` reads as each value of y in the list at the right + `&/` is "and over". `&/y in\:..` returns true iff all patterns in y are locates at the list .. * finally, return each string in n at every index that makes lambda true + `n@&{..}` reads as "n at where lambda {..} returns true" [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~119~~ 102 bytes ``` lambda l:['%05d'%n for n in range(10**5)if all(map(lambda x:''in[x:=x[x[:1]==c:]for c in'%05d'%n],l))] ``` [Try it online!](https://tio.run/##NYzLjsIgFIbX9inYGMC44HCxLQlP0umC0XYkQSS1aufpO4fG2fz58t/y73y9J9XkaR3d1xr97fviSbQd3QtzoftExvtEEgmJTD79DAzE4WB4GImPkd18Zp/JYikNqVusW7qls9A7d7Z9GZ9x/P/WHyPn/fq@hjgQsNUuuhgeMxtePrKQ8nNmnPNql6eQZjYybK9USUGPtJaqqBK0oqrWyI2WyAJKCqKkSgA6sDVB6k0NqlQGfala5Fbr0gHY0vKmzak8Ny1yvbFpTp@fPw "Python 3.8 (pre-release) – Try It Online") This was based off of [xnor's Python answer](https://codegolf.stackexchange.com/a/180285/75323) and @Bubbler helped me golf it by 17 bytes ;) [Answer] # [Python 3.8](https://docs.python.org/3.8/), ~~97~~ 96 bytes ``` lambda l:[s for n in range(10**5)if(s:='%05d'%n,t:={''},[t:=t|{x+c for x in t}for c in s])!=t>l] ``` [Try it online!](https://tio.run/##RY3LTsMwEEX3fIVZVLZLFh4/mgcyP1K6CG3SWjJulBgoCvn2YE8l2FzdMz4zHr7j5RpUNYxrb19X376/nVrim/1E@utIAnGBjG04dwzEdmu469nUWLoR5kQ3oYiNnSldin0q8We@PR1x7ZbX4pLrMdfpwB9tfPGH9evifEeg8cSS7rP1zIXhIzLOn8kwuhBZz/w/8HWmSgpa0FKqnErQ5SHNSp2o0hJJQDZAZEMJwBmgD1JjmpRSGXyRqk5Ua333ANC439Vml3@paqQSyVS7v4vLLw "Python 3.8 (pre-release) – Try It Online") -1 byte thanks to @xnor. # [Python 2](https://docs.python.org/2/), 96 bytes ``` lambda l,d='%05d':[d%n for n in range(10**5)if reduce(lambda t,c:t|{x+c for x in t},d%n,{''})>l] ``` [Try it online!](https://tio.run/##PY7LboMwFET3@Yq7iQwpCz/Do6I/0laIgp1YMgZZRk1F@XZqTJXNSGfuzNjTj7@Plm7KjQM0jZr97GTTgB6m0XmYnLY@uLbzerQnVX9sph2@@hZM1tfojEWPqvf@bEGNDixoC661N5kQfLmIVCtwsp87mfy3fNZV/nd5vHSx8NgLfs3CQLYgtKZv5nP7vmsjgVQG6nCeZp@kr8dHEpWY9AnptiBGMcpQTtmuDKP1FLycByo4jYTJniB4TzBMokdinlAeVQSlTMQLZWWgkvMjR0hMHLtcXPdXijJSHkkU1@fi@gc "Python 2 – Try It Online") Alternative forms of [xnor's Python 2 answer](https://codegolf.stackexchange.com/a/180285/78410). [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, ~~54~~ ~~53~~ 51 bytes ``` sed 's/./&.*/g;s/ \|^/|grep /g;s//seq -w 0 99999/e' ``` [Try it online!](https://tio.run/##XY7dCoJAEIXv9ynORRQEtj@zulpP0FUvIEHlkILYzyrd@O62ShF5YAbmO4fDnE@@HF5lVTOefCpQVw0LoLiFBfClvGHf3Lt2i8XH@tBD1454Al3juUUU/dwpjB754LnAysuNXG7W8rrzEnl/lP31yXdMt/T8QPSCQjZK8mr41kyPNDyQUXCG4EgJchapNUJpBa0IpDS@EjqEtLFhYhiKIQxlyKzFn4TWOkTUjNo4gUuzGXWBxmkybzAk3g "Bash – Try It Online") *Thanks to @user41805 for 1 byte off, and now an additional 2 bytes off.* Input: Space-separated integers on stdin. Output: On stdout, one possible password per line. [Answer] # C(GCC) ~~222~~ 214 bytes -8 bytes ceilingcat ``` #define C(p)*f-p||++f; #define I(x,y)x>9&&++y,x%=10; a,b,c,d,e,g,**h,*f;z(int**H){for(a=0;g=a<10;){for(h=H;*h;g&=f>*h+++2){f=*h;C(a)C(b)C(c)C(d)C(e)}g&&printf("%d%d%d%d%d,",a,b,c,d,e);e++;I(e,d)I(d,c)I(c,b)I(b,a)}} ``` [Try it online!](https://tio.run/##XU3LTsMwELznK6yiRmt7IyVFCCLjXnJpvqHi4PiR5ECICoe0ab49LIYihHZnpJ2Z3bVZa@263jkf@sGzCkYuQjZer1IGldzkGiY882lfpqmUZ5y2ushVYrBBiw49tihEhyKoC/TDhxAHPoe3Exidq1abZwp/C50@KNGpNtVhLzop5Y50TUoFhlfQECzBETxf2jQdT3QvwGbrboUb/P3LlZdS1eDR8RocWmKLDXGDhi/LSsvs1fQDcDYnjH2NHVFxfHhhms0llviIWUG9qD/@7sd/wvy/L2Lg/XgfA/EYxhXMY@QC0ecqWdZP "C (gcc) – Try It Online") Calling code ``` int main() { int hint1[5] = {9,9,7,-1,-1}; int hint2[5] = {8,0,7,-1,-1}; int* hints[3] = {hint1,hint2,0}; z(hints); } ``` Output ``` 80997,89097,89907,98097,98907,99807, ``` [Answer] The function takes an array of strings as input and prints each possible code on separate lines. # [PHP](https://php.net/), 122 bytes ``` function a($n){for(;$x++<1e5;){foreach($n as$a)if(!preg_match("/$a[0].*$a[1].*$a[2]/",$x))continue 2;printf("%05d ",$x);}} ``` [Try it online!](https://tio.run/##TZDdioMwFITvfYqzIQVtZZvfqqSwD@KGJbi69aIxWAuF4rPbNKllbzKcbyYZctzJLccv58/uapupHyyYFNvs3g1jqvBttzvSVqowt6Y5eQ/MBZus79IPN7Z/P2czeYz22NREf2690ChM71GOb1nWDHbq7bUFptzY26lL0YbI3yS4ap6X9e06AagRZwTlgArGg3CCdB6NQjxJKdhKCA1RSkKUE7oaNF6mTESRXhiXL5fx6okrId55SmPwXSbkIdSX1UqKSGR5@N@iARLtVwJ@aXD3OHwR0LdFyk9hmSqZlwc "PHP – Try It Online") [Answer] # [sed](https://www.gnu.org/software/sed/) -E, ~~46~~ 44 bytes ``` s/./&.*/g;s/ |^/|grep /g;s//seq -w 0 99999/e ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1hfT19NT0s/3bpYX6EmTr8mvSi1QAHM1S9OLVTQLVcwULAEAf3U//@NjQwUzI2MFcyNDf7lF5Rk5ucV/9d1BQA "sed – Try It Online") Input: Space-separated integers on stdin. Output: On stdout, one possible password per line. This is from my bash answer, which had 3 bytes off thanks to @user41805. ]
[Question] [ Inspired by [George Gibson's Print a Tabula Recta](https://codegolf.stackexchange.com/q/86986/48934). You are to print/output this exact text: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ BBCDEFGHIJKLMNOPQRSTUVWXYZ CCCDEFGHIJKLMNOPQRSTUVWXYZ DDDDEFGHIJKLMNOPQRSTUVWXYZ EEEEEFGHIJKLMNOPQRSTUVWXYZ FFFFFFGHIJKLMNOPQRSTUVWXYZ GGGGGGGHIJKLMNOPQRSTUVWXYZ HHHHHHHHIJKLMNOPQRSTUVWXYZ IIIIIIIIIJKLMNOPQRSTUVWXYZ JJJJJJJJJJKLMNOPQRSTUVWXYZ KKKKKKKKKKKLMNOPQRSTUVWXYZ LLLLLLLLLLLLMNOPQRSTUVWXYZ MMMMMMMMMMMMMNOPQRSTUVWXYZ NNNNNNNNNNNNNNOPQRSTUVWXYZ OOOOOOOOOOOOOOOPQRSTUVWXYZ PPPPPPPPPPPPPPPPQRSTUVWXYZ QQQQQQQQQQQQQQQQQRSTUVWXYZ RRRRRRRRRRRRRRRRRRSTUVWXYZ SSSSSSSSSSSSSSSSSSSTUVWXYZ TTTTTTTTTTTTTTTTTTTTUVWXYZ UUUUUUUUUUUUUUUUUUUUUVWXYZ VVVVVVVVVVVVVVVVVVVVVVWXYZ WWWWWWWWWWWWWWWWWWWWWWWXYZ XXXXXXXXXXXXXXXXXXXXXXXXYZ YYYYYYYYYYYYYYYYYYYYYYYYYZ ZZZZZZZZZZZZZZZZZZZZZZZZZZ ``` (Yes, I typed that by hand) You are allowed to use all lowercase instead of all uppercase. However, your choice of case must be consistent throughout the whole text. ### Rules/Requirements * Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included. * If it is possible, provide a link to a site where your program can be tested. * Your program must not write anything to `STDERR`. * [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Your program can output in any case, but it must be printed (not an array or similar). ### Scoring Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice. Eventually, the answer with the least bytes will win. ## Submissions To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ## Leaderboard Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. ``` /* Configuration */ var QUESTION_ID = 87064; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; if (/<a/.test(lang)) lang = jQuery(lang).text(); languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang > b.lang) return 1; if (a.lang < b.lang) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] # Excel, 19,604 bytes ``` =CHAR(64+MAX(COLUMN(),ROW())) ``` Paste this formula in `A1`, then drag all over `A1:Z26`. Byte count: 1. The formula is 27 bytes. 2. You need to copy it 26^2 times. 27\*26\*26=19604. 3. I and others thought the score should be lower because you don't really need to type the formula again and again. I now think it's irrelevant - we count the size of the program, not the work spent writing it. 4. For comparison - see [this 28,187 chars JS answer](https://codegolf.stackexchange.com/a/22547/3544) - obviously, someone generated it rather than typing all this, but it doesn't change its size. [Answer] # Vim, 43 bytes ``` :h<_↵jjYZZPqqlmaYp`ajyl:norm v0r♥"↵`ajq25@q ``` Here `↵` represents Return (`0x0a`) and `♥` represents Ctrl-R (`0x12`). Not quite as short as my Tabula Recta answer, but… [![enter image description here](https://i.stack.imgur.com/Awe6f.gif)](https://i.stack.imgur.com/Awe6f.gif) [Answer] # Jelly, 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code%20page) ``` ØA»'j⁷ ``` [Try it here.](http://jelly.tryitonline.net/#code=w5hBwrsnauKBtw&input=) If only I hadn’t been lazy yesterday and implemented that one-byte alternative to `j⁷` (join by newlines)… ``` ØA The uppercase alphabet. »' Table of max(x, y). j⁷ Join by newlines. ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 11 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` ⎕A[∘.⌈⍨⍳26] ``` `A[`...`]` pick elements from the uppercase alphabet according to     `∘.⌈⍨` the maximum table of     `⍳26` the first 26 integers [TryAPL online!](http://tryapl.org/?a=%u2395A%5B%u2218.%u2308%u2368%u237326%5D&run) [Answer] # brainfuck, ~~103~~ ~~96~~ ~~95~~ ~~91~~ 87 bytes ``` +++++[>+++++>++<<-]>+[[<<<+>>>-]----[<+>----]<+<<[>+>+>+<<<-]>-]>>[[<.>-]>[.>>]<<[<]>>] ``` This uses Esolangs' brainfuck constant for [64](https://esolangs.org/wiki/Brainfuck_constants#64). [Try it online!](http://brainfuck.tryitonline.net/#code=KysrKytbPisrKysrPisrPDwtXT4rW1s8PDwrPj4-LV0tLS0tWzwrPi0tLS1dPCs8PFs-Kz4rPis8PDwtXT4tXT4-W1s8Lj4tXT5bLj4-XTw8WzxdPj5d&input=) [Answer] # [///](http://esolangs.org/wiki////), ~~141~~ ~~94~~ ~~92~~ 82 bytes ``` /:/\\\\A//#/:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z://:/\/a# \/a\///A/# ``` Try it online: [Demonstration](https://tio.run/##FcunAYAwAAVRzxoZ4Ptz2QNDCYReQl8@wInnLvRZ8C7EKJR@WcmInIISR0WNp6Glo2dgZGJmYSWwsXNwcnHzoP9XZpKPVJKVifEF) Quite a fun language. ### Explanation: Shortend code to only print a 4x4 square: ``` /:/\\\\A//#/:b:c:d://:/\/a# \/a\///A/# ``` The first replacement `/:/\\\\A/` replaces `:` with `\\A`. This gives: ``` /#/\\Ab\\Ac\\Ad\\A//\\A/\/a# \/a\///A/# ``` Then `/#/\\Ab\\Ac\\Ad\\A//\\A/` replaces `#` with `\Ab\Ac\Ad\A`: ``` /\\A/\/a\Ab\Ac\Ad\A \/a\///A/\Ab\Ac\Ad\A ``` Now `/\\A/\/a\Ab\Ac\Ad\A<newline>\/a\//` replaces each `\A` in the subsequent code by `/aAbAcAdA<newline>/a/`, so this results in: ``` /A//aAbAcAdA /a/b/aAbAcAdA /a/c/aAbAcAdA /a/d/aAbAcAdA /a/ ``` Now the first part `/A//` removes all `A`s. ``` abcd /a/b/abcd /a/c/abcd /a/d/abcd /a/ ``` The first five characters `abcd<newline>` get printed. The next command `/a/b/` replaces `a` by `b`, resulting in: ``` bbcd /b/c/bbcd /b/d/bbcd /b/ ``` Again the first five characters `bbcd<newline>` get printed. The next command `/b/c/` replaces `b` by `c`: ``` cccd /c/d/cccd /c/ ``` Again the first five characters `cccd<newline>` get printed. The next command `/c/d/` replaces `c` by `d`: ``` dddd /d/ ``` The first five characters `dddd<newline>` get printed. And the next command `/d/` is incomplete and therefore does nothing. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~69~~ ~~65~~ ~~57~~ 44 bytes *Saved 8 bytes thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478). Saved 13 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203).* ``` Print@@@Array[Alphabet[][[Max@##]]&,{26,26}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/z@gKDOvxMHBwbGoKLEy2jGnICMxKbUkOjY62jexwkFZOTZWTafayEzHyKw29v9/AA "Wolfram Language (Mathematica) – Try It Online") Full program which prints to standard output. [Answer] ## [Retina](https://github.com/m-ender/retina), 41 bytes Byte count assumes ISO 8859-1 encoding. The leading linefeed is significant. ``` 26$*Z {`^[^A].+ $&¶$& }T0-2`L`_L`^(.)\1+ ``` ### Explanation ``` 26$*Z ``` Set the string to 26 copies of `Z`. Then the `{...}` instruct Retina to perform the remaining two instructions in a loop until the string stops changing. ``` {`^[^A].+ $&¶$& ``` Duplicate the first line if it doesn't start with an `A`. ``` }T0-2`L`_L`^(.)\1+ ``` This is a transliteration stage. It is only applied if the string starts with at least two copies of the same character. If so, all but the last of those characters are decremented. The decrementing happens by mapping `L` (upper case alphabet) to `_L` (blank followed by upper case alphabet). The "all but the last" is indicated by the limit `-2` which tells Retina only to transliterate all characters up to the second-to-last in the match. [Try it online!](http://retina.tryitonline.net/#code=CjI2JCpaCntgXlteQV0uKwokJsK2JCYKfVQwLTJgTGBfTGBeKC4pXDEr&input=) [Answer] ## [///](http://esolangs.org/wiki////), 348 bytes ``` /|/\/\///v/NNN|u/MMM|t/LLL|s/WXYZ|r/OOO|q/KLMa|p/RRRR|o/QQQQ|n/PPPP|m/SSS|l/EFGc|k/RSTb|j/UUUU|i/TTTT|h/WWW|g/VVV|f/XXXX|e/ZZZZZ|d/YYYYY|c/HIJq|b/UVs |a/NOPQk/ABCDlBBCDlCCCDlDDDDlEEEElFFFFFFGcGGGGGGGcHHHHHHHcIIIIIIIIIJqJJJJJJJJJJqKKKKKKKKKKqttttMauuuuMavvvvNarrrrrPQknnnnQkooooQkppppRkmmmmmmSTbiiiiibjjjjjbgggggggVs hhhhhhhWs ffffffYZ dddddZ eeeeeZ ``` [Try it online!](http://slashes.tryitonline.net/#code=L3wvXC9cLy8vdi9OTk58dS9NTU18dC9MTEx8cy9XWFlafHIvT09PfHEvS0xNYXxwL1JSUlJ8by9RUVFRfG4vUFBQUHxtL1NTU3xsL0VGR2N8ay9SU1RifGovVVVVVXxpL1RUVFR8aC9XV1d8Zy9WVlZ8Zi9YWFhYfGUvWlpaWlp8ZC9ZWVlZWXxjL0hJSnF8Yi9VVnMKfGEvTk9QUWsvQUJDRGxCQkNEbENDQ0RsRERERGxFRUVFbEZGRkZGRkdjR0dHR0dHR2NISEhISEhIY0lJSUlJSUlJSUpxSkpKSkpKSkpKSnFLS0tLS0tLS0tLcXR0dHRNYXV1dXVNYXZ2dnZOYXJycnJyUFFrbm5ublFrb29vb1FrcHBwcFJrbW1tbW1tU1RiaWlpaWliampqampiZ2dnZ2dnZ1ZzCmhoaGhoaGhXcwpmZmZmZmZZWgpkZGRkZFoKZWVlZWVa&input=) I've used the same technique to build this [as for my /// answer to the challenge this was based on](https://codegolf.stackexchange.com/a/87056/8478). However, I had to fix [the CJam script](http://cjam.tryitonline.net/#code=MjYsMj5xOlhmZXc6fl8me1tfXywoWEAvLCgoKjUtXF19JSRXJVNmKk4q&input=QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoKQkJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoKQ0NDREVGR0hJSktMTU5PUFFSU1RVVldYWVoKREREREVGR0hJSktMTU5PUFFSU1RVVldYWVoKRUVFRUVGR0hJSktMTU5PUFFSU1RVVldYWVoKRkZGRkZGR0hJSktMTU5PUFFSU1RVVldYWVoKR0dHR0dHR0hJSktMTU5PUFFSU1RVVldYWVoKSEhISEhISEhJSktMTU5PUFFSU1RVVldYWVoKSUlJSUlJSUlJSktMTU5PUFFSU1RVVldYWVoKSkpKSkpKSkpKSktMTU5PUFFSU1RVVldYWVoKS0tLS0tLS0tLS0tMTU5PUFFSU1RVVldYWVoKTExMTExMTExMTExMTU5PUFFSU1RVVldYWVoKTU1NTU1NTU1NTU1NTU5PUFFSU1RVVldYWVoKTk5OTk5OTk5OTk5OTk5PUFFSU1RVVldYWVoKT09PT09PT09PT09PT09PUFFSU1RVVldYWVoKUFBQUFBQUFBQUFBQUFBQUFFSU1RVVldYWVoKUVFRUVFRUVFRUVFRUVFRUVFSU1RVVldYWVoKUlJSUlJSUlJSUlJSUlJSUlJSU1RVVldYWVoKU1NTU1NTU1NTU1NTU1NTU1NTU1RVVldYWVoKVFRUVFRUVFRUVFRUVFRUVFRUVFRVVldYWVoKVVVVVVVVVVVVVVVVVVVVVVVVVVVVVldYWVoKVlZWVlZWVlZWVlZWVlZWVlZWVlZWVldYWVoKV1dXV1dXV1dXV1dXV1dXV1dXV1dXV1dYWVoKWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWVoKWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVlZWVoKWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlo) because it didn't correctly handle substrings that can overlap themselves. [Answer] # Haskell, 35 bytes ``` a=['A'..'Z'] unlines$(<$>a).max<$>a ``` [Answer] # Python 2, 59 bytes ``` n=0;exec'print bytearray([n+65]*n+range(n+65,91));n+=1;'*26 ``` Test it on [Ideone](http://ideone.com/Trw1SP). [Answer] # R, 58 bytes ``` l=LETTERS;for(i in 1:26){l[2:i-1]=l[i];cat(l,"\n",sep="")} ``` Thanks to operator precedence, `2:i-1` is equivalent to `1:(i-1)`. Uses the built-in constant `LETTERS` that contains the alphabet in upper case. Everything else is rather self-explanatory. Usage: ``` > l=LETTERS;for(i in 1:26){l[2:i-1]=l[i];cat(l,"\n",sep="")} ABCDEFGHIJKLMNOPQRSTUVWXYZ BBCDEFGHIJKLMNOPQRSTUVWXYZ CCCDEFGHIJKLMNOPQRSTUVWXYZ DDDDEFGHIJKLMNOPQRSTUVWXYZ EEEEEFGHIJKLMNOPQRSTUVWXYZ FFFFFFGHIJKLMNOPQRSTUVWXYZ GGGGGGGHIJKLMNOPQRSTUVWXYZ HHHHHHHHIJKLMNOPQRSTUVWXYZ IIIIIIIIIJKLMNOPQRSTUVWXYZ JJJJJJJJJJKLMNOPQRSTUVWXYZ KKKKKKKKKKKLMNOPQRSTUVWXYZ LLLLLLLLLLLLMNOPQRSTUVWXYZ MMMMMMMMMMMMMNOPQRSTUVWXYZ NNNNNNNNNNNNNNOPQRSTUVWXYZ OOOOOOOOOOOOOOOPQRSTUVWXYZ PPPPPPPPPPPPPPPPQRSTUVWXYZ QQQQQQQQQQQQQQQQQRSTUVWXYZ RRRRRRRRRRRRRRRRRRSTUVWXYZ SSSSSSSSSSSSSSSSSSSTUVWXYZ TTTTTTTTTTTTTTTTTTTTUVWXYZ UUUUUUUUUUUUUUUUUUUUUVWXYZ VVVVVVVVVVVVVVVVVVVVVVWXYZ WWWWWWWWWWWWWWWWWWWWWWWXYZ XXXXXXXXXXXXXXXXXXXXXXXXYZ YYYYYYYYYYYYYYYYYYYYYYYYYZ ZZZZZZZZZZZZZZZZZZZZZZZZZZ ``` [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 25 bytes ``` 0000000: 2829c0 756fc6 aecae2 aecd9c 39e09e 099c63 7d8e3d ().uo.......9....c}.= 0000015: 65a7c0 39 e..9 ``` [Try it online!](http://sesos.tryitonline.net/#code=YWRkIDI2CmptcAogICAgam1wCiAgICAgICAgcndkIDEsIGFkZCAxLCByd2QgMSwgYWRkIDEsIGZ3ZCAyLCBzdWIgMQogICAgam56CiAgICByd2QgMiwgYWRkIDY0CiAgICBqbXAKICAgICAgICBmd2QgMiwgYWRkIDEsIHJ3ZCAyLCBzdWIgMQogICAgam56CiAgICBmd2QgMSwgc3ViIDEKam56CmZ3ZCAxCmptcAogICAgam1wCiAgICAgICAgcndkIDEsIGFkZCAxLCBmd2QgMSwgc3ViIDEKICAgIGpuegogICAgcndkIDEKICAgIGptcAogICAgICAgIHJ3ZCAxCiAgICBqbnoKICAgIGZ3ZCAxCiAgICBqbXAKICAgICAgICBwdXQsIGFkZCAxLCBmd2QgMQogICAgam56CiAgICBmd2QgMQogICAgam1wCiAgICAgICAgcHV0LCBmd2QgMQogICAgam56CiAgICBhZGQgMTAsIHB1dCwgZ2V0LCByd2QgMQogICAgam1wCiAgICAgICAgcndkIDEKICAgIGpuegogICAgZndkIDEKOyBqbnogKGltcGxpY2l0KQ&input=) Check *Debug* to see the generated SBIN code. ### Sesos assembly The binary file above has been generated by assembling the following SASM code. ``` add 26 jmp jmp rwd 1, add 1, rwd 1, add 1, fwd 2, sub 1 jnz rwd 2, add 64 jmp fwd 2, add 1, rwd 2, sub 1 jnz fwd 1, sub 1 jnz fwd 1 jmp jmp rwd 1, add 1, fwd 1, sub 1 jnz nop rwd 1 jnz fwd 1 jmp put, add 1, fwd 1 jnz fwd 1 jmp put, fwd 1 jnz add 10, put, get nop rwd 1 jnz fwd 1 ; jnz (implicit) ``` ### How it works We start by initializing the tape to `ABCDEFGHIJKLMNOPQRSTUVWXYZ`. This is as follows. Write **26** to a cell, leaving the tape in the following state. ``` v 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 26 0 ``` As long as the cell under the data head is non-zero, we do the following. Copy the number to the two cells to the left and add **64** to the leftmost copy. ``` v 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 90 26 0 0 ``` Move the leftmost copy to the original location, then subtract **1** from the rightmost copy. ``` v 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 25 90 0 ``` The process stops after **26** iterations, since the rightmost copy is **0** by then. We move a cell to the right, so the final state of the tape after the initialization is the following. ``` v 0 0 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 0 ``` Now we're ready to generate the output, by repeating the following process until the cell under the data head is zero. First, we move the content of the cell under the data head one unit to the left, then move left until the last cell with a non-zero content. ``` v 0 65 0 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 0 ``` Now, we print all cells, starting with the one under the data head and moving right until we find a **0** cell, incrementing each printed cell after printing it. After printing `A`, the tape looks as follows. ``` v 0 66 0 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 0 ``` Now we move right, again printing all cells until a **0** cell in encountered. After printing `BCDEFGHIJKLMNOPQRSTUVWXYZ`, the tape looks as follows. ``` v 0 66 0 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 0 ``` Now, we write **10** to the current cell, print the corresponding character (linefeed) and zero the cell with a call to `get` on empty input, leaving the tape unchanged. Finally, we move to the last non-zero to the left, preparing the tape for the next iteration. ``` v 0 66 0 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 0 ``` The next iteration is similar. We first move **66** one cell to the left, print both **66** cells (`BB`) and increment them to **67**, then print the remaining non-zero cells to the right (`CDEFGHIJKLMNOPQRSTUVWXYZ`), and finally place the data head on **67**, leaving the tape as follows. ``` v 0 66 66 0 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 0 ``` After **24** more iterations and after printing `ZZZZZZZZZZZZZZZZZZZZZZZZZZ` and a linefeed, the tapes is left in the following state. ``` v 0 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 91 0 0 ``` Moving the data head to the left to the next non-zero cell will leave it in its current position, so the cell under it is **0** and the loop terminates. [Answer] ## C#, 147 bytes ``` void e(){for(int i=0,j=97;i<26;i++,j++)Console.WriteLine(new string((char)j,i)+new string(Enumerable.Range(j,26-i).Select(n=>(char)n).ToArray()));} ``` *sometimes i wonder why im even trying* *edit:* fixed it [Try it online](http://rextester.com/EBCH52681) [Answer] # J, 13 bytes ``` u:65+>./~i.26 ``` [Online interpreter](https://tio.run/##y/r/PzU5I1@h1MrMVNtOT78uU8/I7P9/AA). ### Explanation ``` u:65+>./~i.26 i.26 generate [0 1 ... 25] /~ build a table... >. ...of maximum 65+ add 65 to each element u: convert to unicode ``` [Answer] # Matlab / Octave, ~~43~~ 39 bytes *1 byte removed thanks to [@beaker's](https://codegolf.stackexchange.com/a/87080/36398) idea of using `[...,'']` to convert to char.* ``` @()[91-rot90(gallery('minij',26),2),''] ``` This is an anonymous function that returns a 2D char array. [**Try it on Ideone**](http://ideone.com/yFwVQc). ### Explanation `gallery('minij',...)` gives a matrix in which each entry equals the minimum of its row and column indices: ``` 1 1 1 1 ... 1 2 2 2 1 2 3 3 1 2 3 4 ... ``` This is rotated 180 degrees with `rot90(...,2)`: ``` 26 25 24 23 ... 25 25 24 23 24 24 24 23 23 23 23 23 ... ``` The `91-...` operation gives the ASCII codes of uppercase letters: ``` 65 66 67 68 66 66 67 68 67 67 67 68 68 68 69 68 ... ... ``` Finally `[...,'']` concatenates horizontally with an empty string. This has the effect of converting to char. [Answer] # Python 2, ~~76~~ ~~70~~ 68 bytes ``` a=range(65,91) i=0 for c in a:a[:i]=[c]*i;i+=1;print'%c'*26%tuple(a) ``` Very similar to [my answer to the linked question](https://codegolf.stackexchange.com/a/87001/56755). *Saved 2 bytes thanks to @xnor (again)!* [Answer] ## PowerShell v2+, ~~76~~ ~~52~~ 40 bytes ``` 65..90|%{-join[char[]](,$_*$i+++$_..90)} ``` Loops from `65` to `89`. Each iteration, we're constructing an array using the comma-operator that consists of the current number `$_` multiplied by post-incremented helper variable `$i++`, concatenated with an array of the current number `$_` to `90`. That's encapsulated in a char-array cast, and `-join`ed together into a string. For example, for the first iteration, this array would be equivalent to `65..90`, or the whole alphabet. The second iteration would be `66+66..90`, or the whole alphabet with `B` repeated and no `A`. Those are all left on the pipeline at program end (as an array), and printing to the console is implicit (the default `.ToString()` for an array is separated via newline, so we get that for free). ``` PS C:\Tools\Scripts\golfing> .\print-the-l-phabet.ps1 ABCDEFGHIJKLMNOPQRSTUVWXYZ BBCDEFGHIJKLMNOPQRSTUVWXYZ CCCDEFGHIJKLMNOPQRSTUVWXYZ DDDDEFGHIJKLMNOPQRSTUVWXYZ EEEEEFGHIJKLMNOPQRSTUVWXYZ FFFFFFGHIJKLMNOPQRSTUVWXYZ GGGGGGGHIJKLMNOPQRSTUVWXYZ HHHHHHHHIJKLMNOPQRSTUVWXYZ IIIIIIIIIJKLMNOPQRSTUVWXYZ JJJJJJJJJJKLMNOPQRSTUVWXYZ KKKKKKKKKKKLMNOPQRSTUVWXYZ LLLLLLLLLLLLMNOPQRSTUVWXYZ MMMMMMMMMMMMMNOPQRSTUVWXYZ NNNNNNNNNNNNNNOPQRSTUVWXYZ OOOOOOOOOOOOOOOPQRSTUVWXYZ PPPPPPPPPPPPPPPPQRSTUVWXYZ QQQQQQQQQQQQQQQQQRSTUVWXYZ RRRRRRRRRRRRRRRRRRSTUVWXYZ SSSSSSSSSSSSSSSSSSSTUVWXYZ TTTTTTTTTTTTTTTTTTTTUVWXYZ UUUUUUUUUUUUUUUUUUUUUVWXYZ VVVVVVVVVVVVVVVVVVVVVVWXYZ WWWWWWWWWWWWWWWWWWWWWWWXYZ XXXXXXXXXXXXXXXXXXXXXXXXYZ YYYYYYYYYYYYYYYYYYYYYYYYYZ ZZZZZZZZZZZZZZZZZZZZZZZZZZ ``` [Answer] # [R](https://www.r-project.org/), ~~42~~ 41 bytes ``` write(outer(L<-LETTERS,L,pmax),'',26,,'') ``` [Try it online!](https://tio.run/##K/r/v7wosyRVI7@0JLVIw8dG18c1JMQ1KFjHR6cgN7FCU0ddXcfITAdIaf7/DwA "R – Try It Online") The [next shortest R answer](https://codegolf.stackexchange.com/a/99532/67312) is still a bit too long since it prints out line by line. I was thinking about another question earlier today and realized a much shorter approach was possible for this one: I generate the matrix all at once using `outer` and `pmax` (parallel maximum) and then print it(\*) in one step with `write`. (\*) technically, its transpose, but it's fortunately symmetric across its diagonal. [Answer] # MATL, 10 bytes ``` lY2t!2$X>c ``` [**Online demo**](https://matl.suever.net/?code=lY2t%212%24X%3Ec&inputs=&version=18.6.0) (If you have issues with this interpreter, ping me in the [MATL chat](https://chat.stackexchange.com/rooms/39466/matl-chatl). Also, [here](http://matl.tryitonline.net/#code=bFkydCEyJFg-Yw&input=) is the TIO link in case you have issues) **Explanation** ``` lY2 % Push an array of characters to the stack: 'AB...Z' t! % Duplicate and transpose 2$X> % Take the element-wise maximum between these two (with expansion) c % Explicitly convert back to characters % Implicitly display the result. ``` [Answer] # Octave, 26 bytes ``` disp([max(L=65:90,L'),'']) ``` Sample run on [ideone](http://ideone.com/18fUKi). [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes Code: ``` AAv¬N×?=¦ ``` Explanation: ``` AA # Push the alphabet twice. v # For each in the alphabet. ¬ # Get the first character and N× # multiply by the iteration variable. ? # Pop and print. = # Print the initial alphabet without popping. ¦ # Remove the first character of the initial alphabet and repeat. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=QUF2wqxOw5c_PcKm&input=). [Answer] # Javascript ES6, 81 bytes ``` x=>[...a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'].map((x,y)=>x.repeat(y)+a.slice(y)).join` ` ``` Self-explanatory. [Answer] # R, 56 bytes Don't have the rep to comment, but @plannapus [answer](https://codegolf.stackexchange.com/a/87224/61633) can be golfed-down a bit to: ``` for(i in 1:26)cat({L=LETTERS;L[1:i]=L[i];L},"\n",sep="") ``` resulting in the same output: ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ BBCDEFGHIJKLMNOPQRSTUVWXYZ CCCDEFGHIJKLMNOPQRSTUVWXYZ DDDDEFGHIJKLMNOPQRSTUVWXYZ EEEEEFGHIJKLMNOPQRSTUVWXYZ FFFFFFGHIJKLMNOPQRSTUVWXYZ GGGGGGGHIJKLMNOPQRSTUVWXYZ HHHHHHHHIJKLMNOPQRSTUVWXYZ IIIIIIIIIJKLMNOPQRSTUVWXYZ JJJJJJJJJJKLMNOPQRSTUVWXYZ KKKKKKKKKKKLMNOPQRSTUVWXYZ LLLLLLLLLLLLMNOPQRSTUVWXYZ MMMMMMMMMMMMMNOPQRSTUVWXYZ NNNNNNNNNNNNNNOPQRSTUVWXYZ OOOOOOOOOOOOOOOPQRSTUVWXYZ PPPPPPPPPPPPPPPPQRSTUVWXYZ QQQQQQQQQQQQQQQQQRSTUVWXYZ RRRRRRRRRRRRRRRRRRSTUVWXYZ SSSSSSSSSSSSSSSSSSSTUVWXYZ TTTTTTTTTTTTTTTTTTTTUVWXYZ UUUUUUUUUUUUUUUUUUUUUVWXYZ VVVVVVVVVVVVVVVVVVVVVVWXYZ WWWWWWWWWWWWWWWWWWWWWWWXYZ XXXXXXXXXXXXXXXXXXXXXXXXYZ YYYYYYYYYYYYYYYYYYYYYYYYYZ ZZZZZZZZZZZZZZZZZZZZZZZZZZ ``` Though, if answer as a matrix is allowed ([i.e. like here](https://codegolf.stackexchange.com/a/87302/61633)), we could do 49 bytes: ``` sapply(1:26,function(l){L=LETTERS;L[1:l]=L[l];L}) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 7 bytes ``` ´ṪY…"AZ ``` [Try it online!](https://tio.run/##yygtzv7//9CWhztXRT5qWKbkGPX/PwA "Husk – Try It Online") I'm rather surprised there isn't a Husk answer for this already. In any case, all this does is create a table (`Ṫ`) of the maximum (`Y`) of each pair of letters A to Z. [Answer] ## Haskell, ~~53~~ 46 bytes ``` unlines[(i<$['B'..i])++[i..'Z']|i<-['A'..'Z']] ``` Returns a single string with the L-phabet. go through the chars `i` from `A` to `Z` and make a list of `(length ['B'..i])` copies of `i` followed by `[i..'Z']`. Join elements with newlines in-between. [Answer] # Python 3, ~~71~~ 65 bytes *Thanks to @LeakyNun for -6 bytes* ``` r=range(26) for i in r:print(''.join(chr(max(i,x)+65)for x in r)) ``` A full program that prints to STDOUT. **How it works** We assign character codes to the letters of the alphabet, from `0` for `A` to `25` for `Z`. The program loops over the interval `[0, 25]` with a line counter `i`, which determines the current character to be repeated and the length of the repeated section, and a character index `x`. By calling `max(i,x)`, all characters below the repeated character are clamped to the character code of the same. Adding `65` and calling `chr` converts the resultant character codes to their ASCII equivalents; `''.join` concatenates the characters, and each line is printed to STDOUT. [Try it on Ideone](https://ideone.com/5L08ro) [Answer] # 𝔼𝕊𝕄𝕚𝕟, 12 chars / 15 bytes ``` ᶐⓢ⒨Ċ_+ᶐč_)ü⬬ ``` `[Try it here (Chrome Canary only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=false&input=&code=%E1%B6%90%E2%93%A2%E2%92%A8%C4%8A_%2B%E1%B6%90%C4%8D_)%C3%BC%E2%AC%AC)` Basically a port of my ES6 answer. [Answer] # R, 54 bytes `v=L=LETTERS;for(i in 2:26){L[1:i]=L[i];v=cbind(v,L)};v` This solution uses the **R** built-in constant `LETTERS`, that... well... lists the uppercase letters. There is also the constant `letters` for lowercase letters. [Answer] # Cheddar, 90 bytes ``` (|>26).map(i->String.letters.chars.map((j,k,l)->k<i?l[i]:j).fuse).vfuse.slice(1) ``` That `String.letters` is too long :/ Had to add a `.slice(1)` because leading newline is disallowed ## Explanation ``` (|>26) // Range from [0, 26) .map(i-> // Loop through that range String.letters.chars // Alphabet array .map( // Loop through alphabet (j,k,l) -> // j = letter, j = index, l = alphabet k<i?l[i]:j // Basically `l[max(k,i)]` ).fuse // Collapse the array ).vfuse // Join on newlines ``` # Cheddar, 65 bytes (non-competing) ``` (|>26).map(i->String.letters.map((j,k,l)->k<i?l[i]:j).fuse).vfuse ``` Works with the [nightly branch](https://github.com/cheddar-lang/Cheddar/tree/develop). Non-competing... sad part is that I already had the changes... just never commited ;\_; ]
[Question] [ In as few bytes as possible, write a program or function that outputs the following: ``` Abcdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz abcdefghijKlmnopqrstuvwxyz abcdefghijkLmnopqrstuvwxyz abcdefghijklMnopqrstuvwxyz abcdefghijklmNopqrstuvwxyz abcdefghijklmnOpqrstuvwxyz abcdefghijklmnoPqrstuvwxyz abcdefghijklmnopQrstuvwxyz abcdefghijklmnopqRstuvwxyz abcdefghijklmnopqrStuvwxyz abcdefghijklmnopqrsTuvwxyz abcdefghijklmnopqrstUvwxyz abcdefghijklmnopqrstuVwxyz abcdefghijklmnopqrstuvWxyz abcdefghijklmnopqrstuvwXyz abcdefghijklmnopqrstuvwxYz abcdefghijklmnopqrstuvwxyZ abcdefghijklmnopqrstuvwxYz abcdefghijklmnopqrstuvwXyz abcdefghijklmnopqrstuvWxyz abcdefghijklmnopqrstuVwxyz abcdefghijklmnopqrstUvwxyz abcdefghijklmnopqrsTuvwxyz abcdefghijklmnopqrStuvwxyz abcdefghijklmnopqRstuvwxyz abcdefghijklmnopQrstuvwxyz abcdefghijklmnoPqrstuvwxyz abcdefghijklmnOpqrstuvwxyz abcdefghijklmNopqrstuvwxyz abcdefghijklMnopqrstuvwxyz abcdefghijkLmnopqrstuvwxyz abcdefghijKlmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz Abcdefghijklmnopqrstuvwxyz ``` A trailing newline is permitted. You can find a reference ungolfed Python implementation [here](https://gist.github.com/katyaka/a2a74206d90451952146). [Answer] # Pyth, 12 bytes ``` V+Gt_GXGNrN1 ``` [Demonstration.](https://pyth.herokuapp.com/?code=V%2BGt_GXGNrN1&debug=0) In Pyth, `G` is the lowercase alphabet. `+Gt_G` is `abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba`, the character that needs to be uppercased in each row. `V` sets up a for loop over this string, with `N` as the loop variable. In the body, `XGNrN1` is a string translation function. `X` translates `G`, the alphabet, replacing `N` with `rN1`, the uppercase version of `N`. `r ... 1` is the uppercase function. This gives the desired output. [Answer] # C,73 Sometimes the simplest approach is best: print every character one by one. this beats a lot of languages it really shouldn't. ``` i;f(){for(i=1377;i--;)putchar(i%27?123-i%27-32*!(i/702?i%28-4:i%26):10);} ``` explanation ``` i;f(){ for(i=1377;i--;) putchar(i%27? //if I not divisible by 27 123-i%27- // print lowercase letter from ASCII 122 downards 32*!(i/702?i%28-4:i%26) // subtract 32 to make it uppercase where necessary: above i=702, use i%28-4, below it use i%26 :10); //if I divisible by 27 print a newline (10) } ``` [Answer] # Python 2, 69 bytes ``` i=25 exec"L=range(97,123);L[~abs(i)]^=32;i-=1;print bytearray(L);"*51 ``` Nice and simple, I think. [Answer] # Brainfuck (8bit), 231 bytes ``` ++++++++++>++[>>+++++[-<+++++>]<[>>>>>[-]>[-]--[-----<+>]<----->[-]>----[----<+>]<++<<<+++++[-<<+++++>>]<<+>[>>>.+>+<<<<-<->]>>>+>.+<<<<<-[>>>>.+>+<<<<<-]<<<<[<+>>>>>>>>-<<<<<<<-]<[>+<-]>>>>>>>>+[<+<+>>-]<[>+<-]<<<<<.>>-]+<-<<++>>] ``` Ok, so it's never going to be the shortest, but it's the taking part that counts... right?! Try it [here](http://copy.sh/brainfuck/) (ensure to tick 'Dynamic memory') [Answer] # MS-DOS Binary, 61 This code does not have to be compiled, it will run in MS-DOS if you write it into a file called wave.com . The code in hex: ``` ba3d0189d7b91a00b061aa404975fbb00aaab00daab024aa31f6e8130046 83fe1a75f7be1800e807004e75fae80100c389d3802820b409cd21800020 c3 ``` Or, if you prefer something more readable, here is how to produce it using debug.exe (the empty line after the code is important): ``` debug.exe wave.com a mov dx,13d mov di,dx mov cx,1a mov al,61 stosb inc ax dec cx jnz 10a mov al,a stosb mov al,d stosb mov al,24 stosb xor si,si call 130 inc si cmp si,1a jnz 11a mov si,18 call 130 dec si jnz 126 call 130 ret mov bx,dx sub byte ptr [si+bx],20 mov ah,9 int 21 add byte ptr [si+bx],20 ret rcx 3e w q ``` [Answer] # Ruby: ~~71~~ ~~68~~ ~~65~~ 63 characters ``` puts f=(e=*?a..?z).map{|c|(e*"").tr c,c.upcase},f[0,25].reverse ``` Sample run: ``` bash-4.3$ ruby -e 'puts f=(e=*?a..?z).map{|c|(e*"").tr c,c.upcase},f[0,25].reverse' | head Abcdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz ``` [Answer] ## Matlab, ~~60~~ ~~58~~ 54 bytes ``` I=32*eye(26);[ones(51,1)*(97:122) '']-[I;I(25:-1:1,:)]) ``` With thanks to [Dennis Jaheruddin](https://codegolf.stackexchange.com/users/11159/dennis-jaheruddin) for saving me 4 bytes. [Answer] # SWI-Prolog, 136 bytes ``` a:-(R=0;R=1),between(1,26,I),(I=1,R=0;I\=1,nl),between(1,26,J),(R=0,L=I;R=1,L is 27-I),(J=L,K is J+64,put(K);J\=L,K is J+96,put(K)),\+!. ``` Abusing backtracking to loop... [Answer] # Haskell ~~100~~ ~~89~~ 88 bytes ``` putStr$map toEnum.(\(h,c:t)->h++c-32:t++[10]).(`splitAt`[97..122]).(25-).abs=<<[-25..25] ``` The lambda helper function `\(h,c:t)` takes a pair of lists of ascii values and concatenates both, but with the first value of the second list capitalized. The main function splits the lowercase alphabet (given in ascii, `97..122`) at every position `0,..,24,25,24,..,0` and calls the lambda in every step. Before printing each value is turned into the corresponding character. [Answer] # Scala ~~110~~ 109 characters ``` val a=('a'to'z').map(c⇒('a'to'z').map(v⇒if(v==c)c.toUpper else v).mkString) a++a.init.reverse foreach println ``` [Answer] # [Haskell](https://www.haskell.org/), 70 bytes ``` mapM putStrLn[[toEnum$x+sum[32|x+abs y/=90]|x<-[65..90]]|y<-[-25..25]] ``` I revisited this problem 6 years later and saved a bunch of bytes. Character growth! [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzexwFehoLQkuKTIJy86uiTfNa80V6VCu7g0N9rYqKZCOzGpWKFS39bSILamwkY32sxUTw/Ijq2pBHJ0jYA8I9PYWKAxmXkKtgpp//8lp@Ukphf/100uKAAA "Haskell – Try It Online") # Haskell, 81 bytes Counting bytes the way @nimi did; `f` is an IO action that prints the desired output. ``` x!y|x==min(50-y)y=65|0<1=97 f=mapM putStrLn[[toEnum$x+x!y|x<-[0..25]]|y<-[0..50]] ``` [Answer] # SQL (postgreSQL), ~~107~~ 101 Generate are series from -25 to 25 and use the absolute value to replace characters with their uppercase version. Thanks to manatwork for the tip about the @ operator. ``` select replace('abcdefghijklmnopqrstuvwxyz',chr(122- @i),chr(90- @i))from generate_series(-25,25)a(i) ``` [Answer] # Pyth - 18 17 bytes First pass, probably can be made much shorter. Uses `X` to substitute and `r1` to capitalize. ``` V+KU26t_KXGNr@GN1 ``` [Try it online here](http://pyth.herokuapp.com/?code=V%2BKU26t_KXGNr%40GN1&debug=1). [Answer] # J, ~~31~~ 23 bytes ``` u:|:(97+i.26)-32*=|i:25 ``` 8 bytes saved thanks to @Mauris. [Try it online here.](http://tryj.tk/) [Answer] # MATLAB - 58 bytes ``` char(bsxfun(@minus,97:122,32*[eye(25,26);rot90(eye(26))])) ``` Similar to [Luis Mendo's solution](https://codegolf.stackexchange.com/a/53832/42418), but using the broadcasting abilities of [`bsxfun`](http://www.mathworks.com/help/matlab/ref/bsxfun.html). Taking advantage that in ASCII, the difference between a capital and lower case character is exactly 32 values away from each other, we first generate lower case letters from ASCII codes 97 to 122 which are the ASCII codes from lowercase a to lowercase z respectfully, then create a 51 row matrix that contains the 26 ASCII codes from 97 to 122. Therefore, each row of this matrix contains a numerical sequence of values from 97 to 122. Next, we create another matrix where each ith row of this matrix contains a 32 in the ith column. The first 26 rows of this matrix has this pattern, which is essentially the identity matrix multiplied by 32. The function [`eye`](http://www.mathworks.com/help/matlab/ref/eye.html) creates an identity matrix for you. The last 25 rows of this matrix is the scaled identity matrix rotated 90 degrees. By taking this custom weighted identity matrix and subtracting this with the first matrix, then converting the resulting ASCII codes into characters, the desired "Mexican Hat" sequence is produced. # Example Run ``` >> char(bsxfun(@minus,97:122,32*[eye(25,26);rot90(eye(26))])) ans = Abcdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz abcdefghijKlmnopqrstuvwxyz abcdefghijkLmnopqrstuvwxyz abcdefghijklMnopqrstuvwxyz abcdefghijklmNopqrstuvwxyz abcdefghijklmnOpqrstuvwxyz abcdefghijklmnoPqrstuvwxyz abcdefghijklmnopQrstuvwxyz abcdefghijklmnopqRstuvwxyz abcdefghijklmnopqrStuvwxyz abcdefghijklmnopqrsTuvwxyz abcdefghijklmnopqrstUvwxyz abcdefghijklmnopqrstuVwxyz abcdefghijklmnopqrstuvWxyz abcdefghijklmnopqrstuvwXyz abcdefghijklmnopqrstuvwxYz abcdefghijklmnopqrstuvwxyZ abcdefghijklmnopqrstuvwxYz abcdefghijklmnopqrstuvwXyz abcdefghijklmnopqrstuvWxyz abcdefghijklmnopqrstuVwxyz abcdefghijklmnopqrstUvwxyz abcdefghijklmnopqrsTuvwxyz abcdefghijklmnopqrStuvwxyz abcdefghijklmnopqRstuvwxyz abcdefghijklmnopQrstuvwxyz abcdefghijklmnoPqrstuvwxyz abcdefghijklmnOpqrstuvwxyz abcdefghijklmNopqrstuvwxyz abcdefghijklMnopqrstuvwxyz abcdefghijkLmnopqrstuvwxyz abcdefghijKlmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz Abcdefghijklmnopqrstuvwxyz ``` You can also run this example using IDEone's online Octave environment. Octave is essentially MATLAB but free: <http://ideone.com/PknMe0> [Answer] # Perl, 51 bytes 50 bytes code + 1 byte command line parameter ``` @a=a..z,@a[-1-abs]=uc@a[-1-abs],print@a for-25..25 ``` Can be used as follows: ``` perl -le '@a=a..z,@a[-1-abs]=uc@a[-1-abs],print@a for-25..25' ``` Or online [here](http://ideone.com/ZCJjel) (note I had to add `,"\n"` to this as I couldn't add the -l arg). --- **Much longer method** Before the shortened version above, I tried a different method which ended up being pretty chunky. I've left it below anyway for reference. 86 bytes code + 1 byte command line arg ``` $_=join"",0,a..z,1;print s/1//r while s/(([A-Z])|0)(\D)|(.)((?2))(1)/\L\2\U\3\4\6\L\5/ ``` First Perl I've ever golfed properly so I imagine there's a lot that can be done with it - please do suggest improvements! Can be used as followed: ``` perl -le '$_=join"",0,a..z,1;print s/1//r while s/(([A-Z])|0)(\D)|(.)((?2))(1)/\L\2\U\3\4\6\L\5/' ``` Or online [here](http://ideone.com/mEA5Xm) (note I had to add ."\n" to this as I couldn't add the -l arg). ### Explanation General approach is to use regex substitution to do all the hard work. We start off with: ``` 0abcdefghijklmnopqrstuvwxyz1 ``` This matches `(([A-Z])|0)(\D)` and gets replaced with `\U\3` (\U changes to uppercase) to give: ``` Abcdefghijklmnopqrstuvwxyz1 ``` From this point onwards, we continue to match the same regex and replace with `\L\2\U\3`: ``` aBcdefghijklmnopqrstuvwxyz1 abCdefghijklmnopqrstuvwxyz1 ... abcdefghijklmnopqrstuvwxyZ1 ``` Now the second alternation of the regex matches, `(.)((?2))(1)` (which is the same as `(.)([A-Z])(1)`). We replace with `\U\4\6\L\5` to give: ``` abcdefghijklmnopqrstuvwxY1z ``` This continues to match and replace until we reach: ``` A1bcdefghijklmnopqrstuvwxyz ``` and there are no more regex matches. At each point in the loop we strip off the '1' and print. [Answer] # PHP, ~~87~~ ~~71~~ 69 bytes Not the shortest one, but it works as intended. Thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for a few tips to reduce it's size by a lot. And thanks to [@Blackhole](https://codegolf.stackexchange.com/users/11713/blackhole), the size was reduced by 2 bytes. ``` for(;$L=range(a,z),$L[25-abs($i++-25)]^=' ',$i<52;)echo join($L).' '; ``` Not exactly pretty, but works. [Answer] ## PowerShell 3.0, 82 bytes ``` $(0..25)+$(24..0)|%{$i=$_;[string](@(97..122)|%{[char]@($_,($_-32))[$_-eq$i+97]})} ``` [Answer] # TIS Node Type T21 Architecture - ~~216~~ 215 bytes ![](https://i.stack.imgur.com/m9mit.png) [Watch it in action here!](https://www.youtube.com/watch?v=7jipsgwtRW4) There's a `DOWN` in that video that I later golfed to `ANY`, but it's functionally identical. This language has no concept of strings or characters, so I should point out that I'm using ASCII values, i.e. output begins `97, 66, 67`...`88, 89, 90, 10, 65, 98`... Here's the code in the format of TIS-100's save data, for the purposes of scoring: ``` @5 ADD 25 L:MOV 27 ANY SUB 1 JGZ L MOV 25 ANY JRO -1 @6 JRO 2 S:MOV 10 ANY ADD 65 MOV ACC ANY SUB 90 JEZ S ADD 26 @9 MOV 32 ANY ADD UP L:MOV 0 ANY SUB 1 JGZ L @10 MOV UP ACC ADD ANY SUB 42 D:JEZ D ADD 42 MOV ACC ANY ``` **Explanation** ![](https://i.stack.imgur.com/yMCqU.png) [Answer] # JavaScript ES6, 121 bytes ``` _=>Array(51).fill('abcdefghijklmnopqrstuvwxyz').map((e,i)=>e.replace(/./g,(f,j)=>j==i|i+j==50?f.toUpperCase():f)).join` ` ``` This is really long because it makes more sense to hardcode the alphabet than to use the absurdly long `String.fromCharCode` to generate the characters. Test it out below with the Stack snippet, which uses better-supported ES5 and below. ``` f=function(){ return Array(51).fill('abcdefghijklmnopqrstuvwxyz').map(function(e,i){ return e.replace(/./g,function(f,j){ return j==i|i+j==50?f.toUpperCase():f }) }).join('\n') } // Polyfill for ES6-only fill() Array.prototype.fill = Array.prototype.fill || function(val){ for(i=0;i<this.length;i++){ this[i] = val } return this } document.getElementById('p').innerText=f() ``` ``` <pre id="p"></pre> ``` [Answer] # CJam, 23 bytes ``` 51{25-z~'{,97>'[2$+tN}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=51%7B25-z~'%7B%2C97%3E'%5B2%24%2BtN%7D%2F). ### How it works ``` 51{ }/ e# For I from 0 to 50: 25- e# Compute J := I - 25. e# This maps [0 ... 50] to [-25 ... 25]. z e# Compute K := abs(J). e# This maps [-25 ... 25] to [25 ... 0 ... 25]. ~ e# Compute L := ~K = -(K + 1). e# This maps [25 ... 0 ... 25] to [-26 ... -1 ... -26]. '{, e# Push ['\0' ... 'z']. 97> e# Discard the first 97. Pushes ['a' ... 'z']. '[2$+ e# Add L to '['. Pushes 'A' for -26, 'Z' for -1. t e# Set ['a' ... 'z'][L] to '[' + L. N e# Push a linefeed. ``` [Answer] # R, ~~78~~ 70 ``` M=replicate(26,c(letters,"\n"));diag(M)=LETTERS;cat(M,M[,25:1],sep="") ``` Improved by @MickyT [Answer] # Bash: ~~76~~ 66 characters ``` printf -va %s {a..z} for c in {a..z} {y..a};{ echo ${a/$c/${c^}};} ``` Sample run: ``` bash-4.3$ printf -va %s {a..z};for c in {a..z} {y..a};{ echo ${a/$c/${c^}};} | head Abcdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz ``` [Answer] # Linux Assembly, 289 Unfortunately not competitive with high level languages and probably far from optimal, but pretty straightforward. Run it using `nasm -f elf64 -o a.o wave.S; ld -s -o a a.o; ./a` (the resulting binary is just 568 bytes big): ``` section .data s:db 'abcdefghijklmnopqrstuvwxyz',10 section .text global _start _start: mov esi,0 a:call c inc esi cmp esi,26 jne a mov esi,24 b:call c dec esi jnz b call c mov eax,1 call d c:mov ecx,s sub byte [ecx+esi],32 mov eax,4 mov edx,27 d:mov ebx,1 int 80h add byte [ecx+esi],32 ret ``` [Answer] # x86 assembly for DOS, 41 Bytes compiled Binary: ``` 00000000 b9 e6 ff b3 61 b8 61 02 50 38 d8 75 02 24 df 88 00000010 c2 cd 21 58 40 3c 7b 75 ef b2 0a cd 21 41 79 02 00000020 43 43 4b 80 f9 19 75 dd c3 ``` Source code, save as "wave.asm", compile with "nasm -f bin -o wave.com wave.asm" and run with "dosbox wave.com" ``` org 100h section .text start: mov cx,-26 mov bl,'a' next_line: mov ax, 0261h next_char: push ax cmp al,bl jnz lower_case and al,255-32 lower_case: mov dl,al int 21h pop ax inc ax cmp al,'z'+1 jnz next_char mov dl,0ah int 21h inc cx jns move_left inc bx inc bx move_left: dec bx cmp cl,25 jnz next_line ret ``` [Answer] # C#, 140 139 135 132 ``` void f(){int d=1,i=0;var s="abcdefghijklmnopqrstuvwxyz\n";for(;i>=0;i+=d=i==25?-1:d)Console.Write(s.Replace(s[i],(char)(s[i]-32)));} ``` Expanded ``` void f() { int d = 1, i =0; var s = "abcdefghijklmnopqrstuvwxyz\n"; for (; i >= 0; i += d = i == 25 ? -1 : d) Console.Write(s.Replace(s[i], (char)(s[i] - 32))); } ``` Saved 1 byte thanks to [@Gunther34567](https://codegolf.stackexchange.com/users/37953/gunther34567) using a ternary instead of `if` Saved 4 bytes then nesting that ternary inside the loop and moving the alphabet to the outside of the loop Saved 3 bytes combining integer declarations thanks to [@eatonphil](https://codegolf.stackexchange.com/users/42769/eatonphil) [Answer] # awk, 91 bytes ``` awk 'BEGIN{for(i=0;i<51;i++)for(j=0;j<27;j++)printf("%c",j>25?10:i==j||j==50-i?j+65:j+97)}' ``` [Answer] # Sed: ~~135~~ ~~119~~ ~~116~~ 111 characters (109 character code + 1 character command line option + 1 character input.) ``` s/.*/abcdefghijklmnopqrstuvwxyz/ h;H;G;H;G;H;g;G s/.{,28}/\u&/gp s/$/\t/ :;s/(\w+\n?)\t(.*)/\t\2\1/;t s/.*Z// ``` Sample run: ``` bash-4.3$ sed -rf mexican.sed <<< '' | head Abcdefghijklmnopqrstuvwxyz aBcdefghijklmnopqrstuvwxyz abCdefghijklmnopqrstuvwxyz abcDefghijklmnopqrstuvwxyz abcdEfghijklmnopqrstuvwxyz abcdeFghijklmnopqrstuvwxyz abcdefGhijklmnopqrstuvwxyz abcdefgHijklmnopqrstuvwxyz abcdefghIjklmnopqrstuvwxyz abcdefghiJklmnopqrstuvwxyz ``` [Answer] # Javascript (ES6), 113 bytes ``` c=-1;while(c++<50){console.log('abcdefghijklmnopqrstuvwxyz'.replace(/./g,(x,i)=>i==c|i+c==50?x.toUpperCase():x))} ``` # 110 bytes ``` for(c=-1;c++<50;)console.log('abcdefghijklmnopqrstuvwxyz'.replace(/./g,(x,i)=>i==c|i+c==50?x.toUpperCase():x)) ``` # 102 bytes Old school is unbeatable unless we'll have range operator/function/generator/whatever in js ``` for(c=-1;c++<50;){for(s='',i=-1;i++<25;)s+=String.fromCharCode(i+(i==c|i+c==50?65:97));console.log(s)} ``` # 100 bytes Unluckily Math.abs is too long ``` for(c=51;c--;){for(s='',i=26;i--;)s+=String.fromCharCode(c+i==25|c-i==25?90-i:122-i);console.log(s)} ``` # ~~96~~ 94 bytes Though I've beeing downvoted without explanation I continue my struggle ``` for(c=-26;c++<25;){for(s='',i=26;i--;)s+=String.fromCharCode(c*c-i*i?122-i:90-i);console.log(s)} ``` We can shave off a couple of bytes by rearranging loop instructions: ``` for(c=-26;c++<25;console.log(s))for(s='',i=26;i--;s+=String.fromCharCode(c*c-i*i?122-i:90-i)); ``` [Answer] # Perl - ~~95~~ 64 bytes Takes advantage of the fact `\u` makes the next character printed an uppercase in Perl. ``` for$c(0..50){$n=1;print map{++$n==27-abs$c-25?"\u$_":$_}a..z,$/} ``` Thanks to manatwork for saving 31 bytes and fixing it (my previous code did not work.) ]
[Question] [ I love math. But I can't find a single calculator that can multiply correctly. They seem to get everything right except 6\*9 (It's the question to life, the universe, and everything! How could they get that wrong?!). So I want you all to write a function for me that can multiply 2 numbers correctly (and 6\*9 equals 42 instead of 54. 9\*6 equals 54 still). Oh, and I'm going to have to build the source in Minecraft so... fewest bytes win! Recap * Take 2 numbers as input (type doesn't matter, but only 2 items will be passed, and order must be consistent. So streams, and arrays are ok as long as they preserve the order they where passed in. I.e., a map won't work because it doesn't preserve the order) * Output multiple of both numbers except if they are 6 and 9, then output 42 (order matters!) + PS. I never was really good with counting, so I think only integers from 0 to 99 are real numbers (type used doesn't matter) * Fewest bytes per language wins! **Leaderboard:** ``` var QUESTION_ID=124242,OVERRIDE_USER=61474;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:+r.match(SCORE_REG)[0],language:r.match(LANG_REG)[0].replace(/<\/?[^>]*>/g,"").trim(),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=/\d+((?=$)|(?= Bytes))/i,OVERRIDE_REG=/^Override\s*header:\s*/i;LANG_REG=/^[^,(\n\r]+/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/Sites/codegolf/all.css?v=617d0685f6f3"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{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] ## Mathematica, 15 bytes Byte count assumes Windows ANSI encoding (CP-1252). ``` 6±9=42 ±n__:=1n ``` Defines a binary operator `±` which solves the problem. We simply define `6±9=42` as a special case which takes precedence and then add a fallback definition which makes `±` equal to multiplication. The latter uses a fairly interesting golfing trick. The reason this works is actually quite elaborate and we need to look into *sequences*. A sequence is similar to what's known as a *splat* in other languages. It's basically a "list" without any wrapper around it. E.g. `f[1, Sequence[2, 3, 4], 5]` is really just `f[1, 2, 3, 4, 5]`. The other important concept is that all operators are just syntactic sugar. In particular, `±` can be used as a unary or binary operator and represents the head `PlusMinus`. So `±x` is `PlusMinus[x]` and `a±b` is `PlusMinus[a,b]`. Now we have the definition `±n__`. This is shorthand for defining `PlusMinus[n__]`. But `n__` represents an arbitrary *sequence* of arguments. So this actually adds a definition for binary (and n-ary) usagess of `PlusMinus` as well. The value of this definition is `1n`. How does this multiply the arguments? Well, `1n` uses Mathematica's implicit multiplication by juxtaposition so it's equivalent to `1*n`. But `*` is also just shorthand for `Times[1,n]`. Now, `n` is sequence of arguments. So if we invoke `a±b` then this will actually become `Times[1,a,b]`. And that's just `a*b`. I think it's quite neat how this syntax abuse lets us define a binary operator using unary syntax. We could now even do `PlusMinus[2,3,4]` to compute `24` (which can also be written as `±##&[2,3,4]` or `2±Sequence[3,4]` but it's just getting crazy at that point). [Answer] # [Haskell](https://www.haskell.org/), 14 bytes ``` 6&9=42 a&b=a*b ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/30zN0tbEiCtRLck2USvpf25iZp6CrUJKPpeCQkFRZl6JgoaRgpqCiSaCbwnkmyHxzYB8S83/AA "Haskell – Try It Online") [Answer] # C, ~~32~~ ~~31~~ ~~29~~ 28 bytes -2 thanks to Digital Trauma -1 thanks to musicman523 ``` #define f(a,b)a^6|b^9?a*b:42 ``` Pretty simple. Declares a macro function `f` that takes two arguments, `a` and `b`. If `a` is `6` and `b` is `9`, return `42`. Otherwise return `a` x `b`. [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU0jUSdJMzHOrCYpztI@USvJysTof25iZp6GZnVBUWZeSZqGUlBqcWlOiUJ@mkIukM4syMlMTizJzM@zUlBNUdJJ0zDTsdTUtK79DwA) [Answer] # JavaScript (ES6), 20 bytes ``` x=>y=>x-6|y-9?x*y:42 ``` **Explanation:** Iff x==6 and y==9, `x-6|y-9` will be 0 (falsy), and 42 will be the result. **Snippet:** ``` f= x=>y=>x-6|y-9?x*y:42 console.log(f(6)(9)); console.log(f(9)(6)); ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~30~~ 29 bytes Thanks to *Jonathan Allan* for saving a byte! ``` lambda x,y:x*[y,7][6==x==y-3] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfpmCrEPM/JzE3KSVRoUKn0qpCK7pSxzw22szWtsLWtlLXOPZ/QVFmXolCmoaZjoKlJheMZ6mjYIbgmegomGr@BwA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ ~~11~~ 9 bytes -4 bytes thanks to @Emigna -2 bytes thanks to @Adnan ``` P¹69SQi42 ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/4NBOM8vgwEwTo///o810FCxjAQ "05AB1E – Try It Online") How it works ``` P # multiply input ¹ # push first number 69 # the number 69 S # split per character Q # equality for both inputs i42 # if so, print 42 # otherwise print product ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~24~~ 22 bytes *-2 bytes thanks to @OlivierGrégoire* ``` a->b->a==6&b==9?42:a*b ``` [Try it online!](https://tio.run/##jU2xCsIwFNz7FW@SRmwGEaFq6iY4OHUUh9faltQ0Cc2rINJvrxGii4u33HHv3V2Ld0yMrXR7vU2ys6YnaL3HB5KK14MuSRrND0FsIzsUSpZQKnQOTig1PCPwCL4jJE93I6/Q@WucUy91c74A9o1j4fmNT@XuqKlqqn7xYwTOMqhBwIRJViQZCrGeFUKk@9Vyg/Ni@vRtv835w1HVcTMQt36clI5rjtaqR7xmQaSM/RVI2TcZAmM0Ti8 "Java (OpenJDK 8) – Try It Online") [Answer] # Ruby, 24 bytes ``` ->a,b{a==6&&b==9?42:a*b} ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~158~~ ~~154~~ ~~148~~ ~~140~~ ~~138~~ 126 bytes ``` (({}<>)(((([()()()]<>)){})<({}{}({}))>{(()()()){}(<{}>)}{}))([()]{()(<{}>)}{})(({<{}>{}((<>))}{}){}<{}>{<({}[()])><>({})<>}{}) ``` [Try it online!](https://tio.run/##PYyxCoAwDER3vyQ3uApCyI9IBx0EURxcQ7693iHYQkneXd/2rMc97td69m6W5QHjWQy6jSuy4Eyy@ACR9mXk5lmBEtaPluQ/ok0zWyaLEPUisqmO8JDTQ2Hv0zC/ "Brain-Flak – Try It Online") # Explanation This code is pretty simple. We make copies of the top two items on the stack, we subtract 6 from one and 9 from the other. We then take the `not` of the two values. We `and` those values, multiply the result by 12. Multiply the inputs and subtract the two results. [Answer] # Factorio, 661 bytes, 6 combinators with 9 connections There is one constant combinator set to output A and B. Change these to set the input. Blueprint string (0.15.18): ``` 0eNrNVm2O2jAQvcv8rEKFvSHLRuqPtrfYCkUhGWAkYkfOGDVCOUBv0bP1JLWTLQuB3U0QbfcPYvzxZt68eYr3sNxaLA0phngPlGlVQfxtDxWtVbr1a1yXCDEQYwEBqLTwUY4Z5WgmmS6WpFLWBpoASOX4HWLRBG8C+EScKr6MIJtFAKiYmLCrpw3qRNliicaleK2SAEpduata+fQObiI+zgKo/R+XIyeDWbcrA18IG71NlrhJd+RuuytPmInby1ucyq+uyFScnPHakWHrVg4VdScmnz2fPzQhjnxQlKlpS4zhk7ugLZd2BCTu0NS8IbXusMvalWgVJyuji4SUA4OYjcWmS606nm31wv8YzI+7SS66axbusHxh1zeITGaJ21C4w41XtyeHHCXH9D+o8eVUjYd3qoY47bc86rWPo158/yze2iCqPtxsmHx3r9ry3E6ylU9cTUv0aITDygwPZaaGeFMgUzbM99NBg/aMegPnV+gxRg6oLtFNZFsjfLhiJB+huZn1B87O7Crr/0Pnfz11vug5/9ePn+/E+2Hf++4beNHV8uzgRWWica6ejnDKiraM5oWXwhtC2CcVDo+FxfAWDfwc3Y9jLv4288cj5qG8IXU3Ie2zKj56xgXgZrNqOURhKGfR/GE6nzfNb7OMaxo= ``` The output is signal Z and is to be taken from the top and bottom deciders. [![Screenshot](https://i.stack.imgur.com/MWERB.png)](https://i.stack.imgur.com/MWERB.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes ``` Vf96SạP ``` Input is as an array of two integers: first the right operand, then the left one. [Try it online!](https://tio.run/##y0rNyan8/z8szdIs@OGuhQH/D7c/alqj4K3wcMf2Rw1zFHwTCxTyy1KLFEoyUhUy8wpKS3RAzDyF4tSCxKLEklSFpEqF4oLE5NRivf//o811FMxjdRSiLXUUzGIB "Jelly – Try It Online") ### How it works ``` Vf96SạP Main link. Argument: [b, a] V Cast [b, a] to string, then eval the resulting string. For [b, a] = [9, 6], this yields 96. f96 Filter with 96, yielding [96] if V returned 96, [] otherwise. S Take the sum, yielding either 96 or 0. P Compute the product of [b, a], yielding ba = ab. ạ Compute the absolute difference of the results to both sides. When the sum is 0, this simply yields the product. However, when [b, a] = [9, 6], this yields 96 - 54 = 42. ``` [Answer] ## Factorio, 581 bytes, 3 combinators with 4 connections Blueprint string (0.16.36): ``` 0eNqllNtu4jAQht9lLldmldNCFWkvto/RCkUhGWAkYkfOGDVCefeOnV1Km7ACemPJ9vibf04+webgsLWkGfITUGV0B/nrCTra6fLgz7hvEXIgxgYU6LLxO2/HpeZFZZoN6ZKNhUEB6RrfII+HtQLUTEw44sKmL7RrNmjF4AyqsaIa7SVHQWs6eWq0dy+46OcvBT3ki1hc1GSxGi8T5XWwNYdig/vySPJYXvxFFnJXB0znT7dkOy4mYR3JspOTs6DRYoFHtD3vSe98XP/CFZ9xtsqe0mW29KdNW9qgOYffgjCOW3eHk+eR3fai1WkuttY0BWlhQM7W4TC61mPAIYzYLxbry6yS7FKxJFs54rANFdhZRP3VMBnWQk08ZvZ+ChpExqSCyX9bYVLCRfxRwbmabenAaK+03rX0/RnT5z7VJbroQnUH7HkGlq7OsDFtc8WYzWJ8WxbTs4rSEu8bZKpuGoXopkn4gH5vGEKiO/SMO5vbtCgDEjTCjwcm5AWGO4ZgknX16Tq7OhRfHiZXypU91PTRd6ZYdIjo8PnmF3+1AvmfuuBq+bRKYmnWKM2G4R1hAPnz ``` The bottom left constant combinator should be set to output A and B as input. The output is signal Z from the bottom right arithmetic combinator. [![enter image description here](https://i.stack.imgur.com/dtthF.png)](https://i.stack.imgur.com/dtthF.png) ``` Top left: 2147483640 A, 2147483637 B Top right: If everything = 2147483646 output B, input count Bottom left: (input) A, (input) B Bottom right: A * B -> Z ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 11 bytes ``` [BE]=?42}Gp ``` Input is an array with the two numbers. [Try it online!](https://tio.run/##y00syfn/P9rJNdbW3sSo1r0AyDHTUbCMBQA "MATL – Try It Online") ### Explanation ``` [BE] % Push array [6, 9] = % Implicit input: array of two numbers. Compare with [6, 9] element-wise ? % If the two entries are true 42 % Push 42 } % Else G % Push input p % Product of array % Implicit end. Implicit display ``` [Answer] # [R](https://www.r-project.org/), 33 bytes ``` function(a,b)`if`(a-6|b-9,a*b,42) ``` Returns a function. [Try it online!](https://tio.run/##K/qfoKqlmmD7P600L7kkMz9PI1EnSTMhMy1BI1HXrCZJ11InUStJx8RI87@ZAlClgiWXJZg24zIE08b/AQ "R – Try It Online") [Answer] # [GW-BASIC](//en.wikipedia.org/wiki/GW-BASIC), 55 bytes ``` 1INPUT A:INPUT B 2IF A=6THEN IF B=9THEN ?"42":END 3?A*B ``` Output: [![output](https://i.stack.imgur.com/uRqRY.png)](https://i.stack.imgur.com/uRqRY.png) The first machine at [pcjs](https://pcjs.org) has IBM BASIC, which is practically the same thing. To test this, head over there, hit `Run` on the machine, Press `Enter`-`Enter` and type `BASICA` to get into BASIC mode. Then enter the source code (it will automatically prettyprint for you), type `RUN`, input two integers, and done! [Answer] # JavaScript (ES6), 25 bytes ``` x=>y=>[x*y,42][x==6&y==9] ``` [Answer] ## [Check](https://github.com/ScratchMan544/check-lang), ~~34~~ 33 bytes ``` .:+&>#v #>42#v#9-!\>6-!*? d* ##p ``` Check is my new esolang. It uses a combination of 2D and 1D semantics. Input is two numbers passed through command line arguments. ### Explanation The stack starts with the command line arguments on it. Let's call the arguments `a` and `b`. The first part, `.:+&`, essentially duplicates the stack, leaving it as `a, b, a, b`. `>` pushes 0 to the stack (it is part of a numeric literal completed by `9`). `#` switches to 2D semantics, and `v` redirects the IP downwards. The IP immediately runs into a `#`, which switches back to 1D semantics again. `9-!` checks whether `b` is equal to 9 (by subtracting 9 and taking the logical NOT). `\>6-!` then checks whether `a` is equal to 6. The stack now contains `a, b, 1, 1` if and only if `b==9` and `a==6`. Multiplying with `*` takes the logical AND of these two values, giving `a, b, 1` if the inputs were `6` and `9`, and `a, b, 0` otherwise. After this, the IP runs into a `?`. This will switch to 2D mode if the top stack value is nonzero, and otherwise will continue in 1D mode. If the top stack value was `1`, this means that the other stack values are `6` and `9`, so we push 42 to the stack with `>42` and then move down to the second `#` on the last line. If the top stack value was `0`, then execution moves down to the next line. `d` removes the `0` (as `?` does not do so), and then we multiply the two inputs with `*`. The `##` switches in and out of 2D mode, doing nothing. The branches have now joined again. The stack either contains `6, 9, 1, 42`, or `a*b`. `p` prints the top stack value and then the program ends, discarding the rest of the stack. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~13~~ ~~11~~ 12 bytes ``` ¥6&V¥9?42:N× ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.5&code=pTYmVqU5PzQyOk7X&input=Niw5) * ~~2~~ 1 bytes saved thanks to obarakon. [Answer] # [Python 3](https://docs.python.org/3/), ~~36~~ 33 bytes ``` lambda x,y:42if x==6==y-3else x*y ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9LKxCgzTaHC1tbM1rZS1zg1pzhVoUKr8n9BUWZeiUaahpmOpaYmF4xnqWOmqfkfAA "Python 3 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 10 bytes ``` ×-12×6 9≡, ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v@JR24TD03UNjQ5PN1OwfNS5UOf/fwOFCgVjLiMgacplCSQNDbkMQWKGBlyWIL4RWNSMywxIWgIA "APL (Dyalog Unicode) – Try It Online") `×` the product (of the arguments) `-` minus `12×` twelve times `6 9≡` whether (6,9) is identical to `,` the concatenation (of the arguments) [Answer] **R, 41 I think** I don't know how to count bytes I am new :D ``` function(a,b){ if(a==6&b==9){42} else {a*b} } ``` I define a funtion whose arguments are a and b **in this order**. If a equals to 6 and b equals to 9 it returns 42, otherwise, a times b [Answer] ## [SPL](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00053000000000000000), 356 bytes ``` a.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:Listen to your heart!Puck:Listen to your heart!Are you as big as the sum of a big big big cat and a cat?If so, am I as big as the sum of a big big cat and a big cat?If so, you are as big as the product of I and the sum of I and a cat.If not, you are as big as the product of you and I.Open your heart ``` With newlines and spaces: ``` a. *Title* Ajax,. *Declare variable Ajax* Puck,. *Declare variable Puck* Act I:. Scene I:. [Enter Ajax and Puck] Ajax: Listen to your heart! *Set Puck's value to user input* Puck: Listen to your heart! *Set Ajax's value to user input* Are you as big as the sum of a big big big cat and a cat? *Is Ajax=9?* If so, am I as big as the sum of a big big cat and a big cat? *Is Puck=6?* If so, you are as big as the product of I and the sum of I and a cat. *If so, set Ajax=42* If not, you are as big as the product of you and I. *If not set Ajax=(Ajax)(Puck)* Open your heart *Print Ajax's value* ``` [Answer] # [Standard ML (MLton)](http://www.mlton.org/), ~~22~~ 20 bytes Saved 2 bytes thanks to @Laikoni! ``` fun$6 $9=42| $x y=x*y ``` [Try it online!](https://tio.run/##Jc2xCoMwFEbhV/mRDEmoUlMpFLG7c4cObQeRVAW9CXoFhb57mtLpWw6cZRrTaWRHIbxXEmdcqsJ8IDbs1ab3UMLPAzHkjaNd1jpqG74P3CN5UgI5NR6yJs7Y/RMFqVGTXxmdswt6O1uk6RVaPSAQD4dIAXP8mecwp5dSZfgC "Standard ML (MLton) – Try It Online") This is the kind of thing SML is meant for, which is why it beats shortC and Python. The old version looked much nicer. :P [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` c69∧42|× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1snlP9PNrN81LHcxKjm8PT//6OjjXSMY3WijXWMgKSZjiWQtNQxA7EtdQyAlIGOGVjMTMcQSBnpmMbGAgA "Brachylog – Try It Online") A predicate which takes a pair of numbers as its input variable and outputs their correct product through its output variable. ``` If the input c concatenated 69 is 69, ∧42 then output 42, | otherwise × output the product of all numbers in the input. ``` I have no clue why `[0,69]c69` fails, but I am very glad that it does! (Running `69~cᶠw` confirms that `[6,9]` is the only two-element list that concatenates to `69`.) [Answer] # Python 3, 33 bytes ``` lambda x,y:42*(x==6)*(y==9)or x*y ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9LKxEhLo8LW1kxTS6PS1tZSM79IoUKr8n9BUWZeiUaahpmOpaYmF4xnqWOmqfkfAA "Python 3 – Try It Online") [Answer] ## Pascal, 69 characters ``` function p(x,y:integer):integer;begin p:=x*y-12*ord(x=6)*ord(y=9)end; ``` expanded ``` function product(x, y: integer): integer; begin product := x * y - 12 * ord(x = 6) * ord(y = 9) end; ``` [Answer] # Pyth, 12 bytes ``` -*FQ*12q(6 9 ``` [Try it online](http://pyth.herokuapp.com/?code=-*FQ*12q%286%209&input=6%2C9&debug=0) Explanation ``` -*FQ*12q(6 9 *FQ Take the product q(6 9)Q Check if the (implicit) input is (6, 9) - *12 If so, subtract 12 ``` [Answer] # Bash, 24 ``` echo $[$1$2-69?$1*$2:42] ``` Saves a couple of bytes by just doing one test - checking if the string concatenation of the inputs is 69. [Try it online](https://tio.run/##NcuxCoAgFEbhvaf4kTsFDpoI1tCDRIPpDVsU0vc3l87wbefyNfW7vGhcW/CV8WQIBS0gFpihhRs6WLEhlgmjyg1Sgv6nc0gFdJAiLa3bSc2kV6PPHkvm/gE). [Answer] # [Retina](https://github.com/m-ender/retina), 36 bytes ``` ^6 9$ 6 7 \d+ $* 1(?=1* (1+))|. $1 1 ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP85MwVKFy0zBnCsmRZtLRYvLUMPe1lBLQcNQW1OzRo9LxZDL8P9/SwUzoBpLAA "Retina – Try It Online") Standard unary multiplication, just alters the input to handle the special case. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁼6,9ȧ42ȯ⁸P ``` A monadic link taking a list of the two numbers. **[Try it online!](https://tio.run/##y0rNyan8//9R4x4zHcsTy02MTqx/1Lgj4P///9FAgVgA)** ### How? ``` ⁼6,9ȧ42ȯ⁸P - Link: list of numbers [a,b] 6,9 - 6 paired with 9, [6,9] ⁼ - equals? (non-vectorising) (1 or 0) 42 - literal answer, 42 ȧ - logical and (42 or 0) ⁸ - link's left argument, [a,b] ȯ - logical or (42 or [a,b]) P - product (42 or a*b) ``` ]
[Question] [ Your task is to write program which will draw 800x600 black-and-white image with something resembling a forest. Like this (it is dithered photo): ![](https://i.stack.imgur.com/lbSTC.png) # Rules * You are disallowed to use any existing images - you should generate image purely algorithmically * Use only 2 colors - black and white (no grayscale) * Each time program runs image should be new - random every time * One tree is not a forest (let say 5 trees minumum) * Special libraries for drawing trees/forests are disallowed * Answer with most votes wins [Answer] ## C: 3863 1144 1023 999 942 927 The original solution saves 2 pnm files per run (one with g appended, before dithering). Because the dithering wasn't beautiful for the first few lines, there is a hack in place to render more lines than needed, and crop during output. The golfed solution has a simpler dithering and saves only the dithered image. (no warnings with gcc -std=c11 -pedantic -Wall -Wextra) Example images from 3 original program runs and one run of the golfed version (last image): ![example 1](https://i.stack.imgur.com/SssMP.png) ![example 2](https://i.stack.imgur.com/AEer7.png) ![example 3](https://i.stack.imgur.com/METCC.png) ![example 4](https://i.stack.imgur.com/zDCTR.png) Golfed version ``` #include <math.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #define D float #define R rand()/RAND_MAX #define Z(a,b,c) if(10.*R>a)T(h,s,j+b+c*R,g); #define U a[y][x] #define V e[y+1][x #define F(x) for(i=0;i<x;++i) int i,x,y,W=800,H=600;unsigned char a[600][800],c;D e[601][802],r,b,k,l,m,n,f,w, d,q=.01;void T(D h,D s,D j,D g){r=b=0;do{j+=.04*R-.02;h+=sin(j)*q;s+=cos(j)*q;b +=q;g+=q;f=525/d;r=.25-g/44;m=w*f+s*f+W/2;n=2*f-h*f+H/2;f*=r;for(y=n-f-2;y<n+f+2 ;++y)if(y>=0&&y<H)for(x=m-f-2;x<m+f+2;++x)if(x>=0&&x<W)if(k=m-x,l=n-y,f>sqrt(k*k +l*l))if(U>d*3)U=d*3;}while(b<10*r+12*r*R&&r>q);if(r>q){Z(2,.26,.35)Z(2,-.26,- .35)Z(7,-.05,.1)}}int main(){FILE* o=fopen("i","wb");srand(time(0));F(W*H){y=i/W ;a[y][i%W]=(y<313)?255:6e3/(2*y-H);}F(200)w=1e2*R-60,d=80.*R+5,T(0,0,1.58,0);F(W *H){x=i%W;y=i/W;k=U+e[y][x+1];U=-(k>0);l=(k-U)*.1;e[y][x+2]+=l*4;V]+=l*2;V+1]+=l *3;V+2]+=l;}fprintf(o,"P5 800 600 255 ");fwrite(a,1,W*H,o);} ``` Original version ``` #include <math.h> #include <stdio.h> #include <stdlib.h> #define W 800 #define H 600 #define SPEED 0.01 #define HEIGHT 11.0 #define R(m) ((double)(m) * rand() / RAND_MAX) #define RAD(deg) ((deg) / 180.0 * M_PI) #define LIMIT(x, min, max) ((x) < (min) ? (min) : (x) > (max) ? (max) : (x)) void shade(void); void growTree(double dist, double side, double h, double s, double alpha, double grown); void plot(double dist, double side, double h, double s, double alpha, double diam); void dither(void); void writeImg(int dither); unsigned char img[H+10][W]; double err[H+10+2][W+4]; long tim; int main(void) { int i; tim = time(0); srand(tim); shade(); for(i = 0; i < 200; ++i) { growTree(5 + R(75), -60 + R(120), 0.0, 0.0, RAD(90), 0.0); } writeImg(0); dither(); writeImg(1); } void shade(void) { int y; for(y = -10; y < H; ++y) { double dist = H * 3.5 / (2 * y - H); unsigned char color = dist / 80 * 255; if(y <= H / 2 || dist > 80) color = 255; memset(img[y+10], color, W); } } void growTree(double dist, double side, double h, double s, double alpha, double grown) { double diam, branchLength = 0.0; do { alpha += R(RAD(3)) - RAD(1.5); h += sin(alpha) * SPEED; s += cos(alpha) * SPEED; branchLength += SPEED; grown += SPEED; diam = (1.0 - grown / HEIGHT) * 0.5; plot(dist, side, h, s, alpha, diam); } while(branchLength < 5 * diam + R(6 * diam) && diam > 0.02); if(diam > 0.02) { int br = 0; if(R(10) > 2) br++,growTree(dist, side, h, s, alpha + RAD(15) + R(RAD(20)), grown); if(R(10) > 2) br++,growTree(dist, side, h, s, alpha - RAD(15) - R(RAD(20)), grown); if(R(10) < 2 || br == 0) growTree(dist, side, h, s, alpha - RAD(2.5) + R(RAD(5)), grown); } } void plot(double dist, double side, double h, double s, double alpha, double diam) { int x, y; double scale = H / 4.0 * 3.5 / dist; double x0 = side * scale + s * scale + W / 2.0; double y0 = H / 2.0 + 2.0 * scale - h * scale; diam *= scale; h *= scale; s *= scale; for(y = y0 - diam / 2 - 2; y < y0 + diam / 2 + 2; ++y) { if(y < -10 || y >= H) continue; for(x = x0 - diam / 2 - 2; x < x0 + diam / 2 + 2; ++x) { double dx, dy, d; if(x < 0 || x >= W) continue; dx = x0 - x; dy = y0 - y; d = diam / 2 - sqrt(dx * dx + dy * dy) + 0.5; if(d > 0) { unsigned char color = dist / 80 * 255; if(img[y+10][x] > color) img[y+10][x] = color; } } } } void dither(void) { int x0, x, y; for(y = -10; y < H; ++y) { for(x0 = 0; x0 < W; ++x0) { double error, oldpixel; unsigned char newpixel; if(y%2) x = W - 1 - x0; else x = x0; oldpixel = img[y+10][x] + err[y+10][x+2]; newpixel = oldpixel > 127 ? 255 : 0; img[y+10][x] = newpixel; error = oldpixel - newpixel; err[y+10 ][x+1+2*(1-y%2)] += error * 7 / 48; err[y+10 ][x+4*(1-y%2)] += error * 5 / 48; err[y+10+1][x ] += error * 3 / 48; err[y+10+1][x+1] += error * 5 / 48; err[y+10+1][x+2] += error * 7 / 48; err[y+10+1][x+3] += error * 5 / 48; err[y+10+1][x+4] += error * 3 / 48; err[y+10+2][x ] += error * 1 / 48; err[y+10+2][x+1] += error * 3 / 48; err[y+10+2][x+2] += error * 5 / 48; err[y+10+2][x+3] += error * 3 / 48; err[y+10+2][x+4] += error * 1 / 48; } } } void writeImg(int dither) { FILE* fp; char buffer[32]; sprintf(buffer, "%ld%s.pnm", tim, dither ? "" : "g"); fp = fopen(buffer, "wb"); fprintf(fp, "P5\n%d %d\n255\n", W, H); fwrite(&img[10][0], 1, W * H, fp); fclose(fp); } ``` [Answer] # Java Jungle ### (954 golfed) Full of deep, twisting undergrowth, this is a forest not easily traversed. ![enter image description here](https://i.stack.imgur.com/P5yu6.png) It's basically a fractal random walk with slowly shrinking, twisty vines. I draw 75 of them, gradually changing from white in the back to black up front. Then I dither the whole thing, shamelessly adapting Averroes' code [here](https://codegolf.stackexchange.com/a/26690/14215) for that. Golfed: (Just because others decided to) ``` import java.awt.*;import java.awt.image.*;import java.util.*;class P{static Random rand=new Random();public static void main(String[]a){float c=255;int i,j;Random rand=new Random();final BufferedImage m=new BufferedImage(800,600,BufferedImage.TYPE_INT_RGB);Graphics g=m.getGraphics();for(i=0;i++<75;g.setColor(new Color((int)c,(int)c,(int)c)),b(g,rand.nextInt(800),599,25+(rand.nextInt(21-10)),rand.nextInt(7)-3),c-=3.4);for(i=0;i<800;i++)for(j=0;j<600;j++)if(((m.getRGB(i,j)>>>16)&0xFF)/255d<rand.nextFloat()*.7+.05)m.setRGB(i,j,0);else m.setRGB(i,j,0xFFFFFF);new Frame(){public void paint(Graphics g){setSize(800,600);g.drawImage(m,0,0,null);}}.show();}static void b(Graphics g,float x,float y,float s,float a){if(s>1){g.fillOval((int)(x-s/2),(int)(y-s/2),(int)s,(int)s);s-=0.1;float n,t,u;for(int i=0,c=rand.nextInt(50)<1?2:1;i++<c;n=a+rand.nextFloat()-0.5f,n=n<-15?-15:n>15?15:n,t=x+s/2*(float)Math.cos(n),u=y-s/2*(float)Math.sin(n),b(g,t,u,s,n));}}} ``` Sane original code: ``` import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; import javax.swing.JFrame; public class Paint { static int minSize = 1; static int startSize = 25; static double shrink = 0.1; static int branch = 50; static int treeCount = 75; static Random rand = new Random(); static BufferedImage img; public static void main(String[] args) { img = new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB); forest(img); dither(img); new JFrame() { public void paint(Graphics g) { setSize(800,600); g.drawImage(img,0,0,null); } }.show(); } static void forest(BufferedImage img){ Graphics g = img.getGraphics(); for(int i=0;i<treeCount;i++){ int c = 255-(int)((double)i/treeCount*256); g.setColor(new Color(c,c,c)); tree(g,rand.nextInt(800), 599, startSize+(rand.nextInt(21-10)), rand.nextInt(7)-3); } } static void tree(Graphics g, double x, double y, double scale, double angle){ if(scale < minSize) return; g.fillOval((int)(x-scale/2), (int)(y-scale/2), (int)scale, (int)scale); scale -= shrink; int count = rand.nextInt(branch)==0?2:1; for(int i=0;i<count;i++){ double newAngle = angle + rand.nextDouble()-0.5; if(newAngle < -15) newAngle = -15; if(newAngle > 15) newAngle = 15; double nx = x + (scale/2)*Math.cos(newAngle); double ny = y - (scale/2)*Math.sin(newAngle); tree(g, nx, ny, scale, newAngle); } } static void dither(BufferedImage img) { for (int i=0;i<800;i++) for (int j=0;j<600;j++) { double lum = ((img.getRGB(i, j) >>> 16) & 0xFF) / 255d; if (lum <= threshold[rand.nextInt(threshold.length)]-0.2) img.setRGB(i, j, 0xFF000000); else img.setRGB(i, j, 0xFFFFFFFF); } } static double[] threshold = { 0.25, 0.26, 0.27, 0.28, 0.29, 0.3, 0.31, 0.32, 0.33, 0.34, 0.35, 0.36, 0.37, 0.38, 0.39, 0.4, 0.41, 0.42, 0.43, 0.44, 0.45, 0.46, 0.47, 0.48, 0.49, 0.5, 0.51, 0.52, 0.53, 0.54, 0.55, 0.56, 0.57, 0.58, 0.59, 0.6, 0.61, 0.62, 0.63, 0.64, 0.65, 0.66, 0.67, 0.68, 0.69 }; } ``` One more? Okay! This one has the dithering tuned down a bit, so the blacks in front are much flatter. ![enter image description here](https://i.stack.imgur.com/axswn.png) Unfortunately, the dither doesn't show the fine details of the vine layers. Here's a greyscale version, just for comparison: ![enter image description here](https://i.stack.imgur.com/4A6Go.png) [Answer] # Javascript + HTML - not golfed A javascript porting of the algorithm of @Manuel Kansten - it's amazing how good these trees look. Just to do something different, I draw the image in color, then dither to b/w at the last step. I don't know why, but my forest is less dark and less frightening respect to Manuel's. Test with [JSfiddle](http://jsfiddle.net/xr66ypkr/9/) or run the new **Snippet** below. That's NOT fast. Be patient and watch the forest grow. ![Forest 1](https://i.stack.imgur.com/hhAjo.png) ![Forest 1 color](https://i.stack.imgur.com/97pu1.png) ![Forest 2](https://i.stack.imgur.com/GeguT.png) ![Forest 2 color](https://i.stack.imgur.com/eBgbF.png) ``` W=800 H=600 canvas.width = W; canvas.height = H; var ctx = canvas.getContext("2d"); R=function(m) { return m * Math.random()}; RAD=function(deg) { return deg / 180 * Math.PI}; LIMIT=function(x, min, max) {return x < min ? min : x > max ? max : x}; var SPEED = 0.01, HEIGHT = 11.0; // Ground var grd = ctx.createLinearGradient(0,0,0,H); grd.addColorStop(0,"#88ccff"); grd.addColorStop(0.45,"#ffffee"); grd.addColorStop(0.5,"#80cc80"); grd.addColorStop(1,"#001100"); ctx.fillStyle = grd; ctx.fillRect(0,0, W,H); Plot = function(dist, side, h, s, alpha, diam) { var x, y, a1,a2,scale = H/4 * 3.5 / dist, x0 = side * scale + s * scale + W/2, y0 = H/2 + 2.5*scale - h*scale; k = dist if (diam > 0.05) { red = k*3|0; green = k|0; a1=alpha+1 a2=alpha-1 } else { green= 80+(1-diam)*k*2|0; red = k|0; a1=0; a2=2*Math.PI; } diam *= scale; h *= scale; s *= scale; ctx.beginPath(); ctx.arc(x0,y0,diam/2, a1,a2);//lpha-1, alpha+1);//0,2*Math.PI); ctx.fillStyle = 'rgb('+red+','+green+',0)'; ctx.fill(); } Grow = function(dist, side, h, s, alpha, grown) { var diam, branchLength = 0.0; diam = (1.0 - grown / HEIGHT) * 0.5; do { alpha += R(RAD(3)) - RAD(1.5); h += Math.sin(alpha) * SPEED; s += Math.cos(alpha) * SPEED; branchLength += SPEED; grown += SPEED; diam = (1.0 - grown / HEIGHT) * 0.5; Plot(dist, side, h, s, alpha, diam); } while(branchLength < 5 * diam + R(6 * diam) && diam > 0.02); if (diam > 0.02) { var br = 0; if(R(10) > 2) br++,Grow(dist, side, h, s, alpha + RAD(15) + R(RAD(20)), grown); if(R(10) > 2) br++,Grow(dist, side, h, s, alpha - RAD(15) - R(RAD(20)), grown); if(R(10) < 2 || br == 0) Grow(dist, side, h, s, alpha - RAD(2.5) + R(RAD(5)), grown); } } trees=[] for(i = 0; i < 300; ++i) trees.push({ z: 1+R(70), s:R(120)-60 }); trees.sort( function (a,b) { return a.z - b.z} ); Draw = function() { t = trees.pop(); if (t) { Grow(t.z, t.s, 0, 0, RAD(90), 0); setTimeout(Draw, 100); } else { var e,c,d,p,i,l, img = ctx.getImageData(0,0,W,H); l = img.data.length; for (i = 0; i < l-W*4-4; i+=4) { c = (img.data[i]+img.data[i+1])/2|0 c = img.data[i] d = c > 120 + R(16) ? 255 : 0 e = c - d; img.data[i]=img.data[i+1]=img.data[i+2]=d c = (img.data[i+4]+img.data[i+5])/2|0 c = LIMIT(c + ((e*7)>>4),0,255) img.data[i+4]=img.data[i+5]=img.data[i+6]=c p = i+W*4 c = (img.data[p-4]+img.data[p-3])/2|0 c = LIMIT(c + ((e*3)>>4),0,255) img.data[p-4]=img.data[p-3]=img.data[p-2]=c c = (img.data[p]+img.data[p+1])/2|0 c = LIMIT(c+ ((e*5)>>4),0,255) img.data[p]=img.data[p+1]=img.data[p+2]=c c = (img.data[p+4]+img.data[p+5]*2)/3|0 c = LIMIT(c + (e>>4),0,255) img.data[p+4]=img.data[p+5]=img.data[p+6]=c } bwcanvas.width = W; bwcanvas.height = H; var bwx = bwcanvas.getContext("2d"); bwx.putImageData(img,0,0); } } setTimeout(Draw, 10); ``` ``` <canvas id='bwcanvas' width="2" height="2"></canvas> <canvas id='canvas' width="2" height="2"></canvas> ``` [Answer] # Context Free Art 3 (1133) CF is a vector graphics rendering language, so I cannot avoid anti-alising. I worked that around by drawing square at the same place several (variable `N`) times. Fog is done by drawing small squares on random places. ``` startshape main W = 80*0.6 H = 60*0.6 N = 3 CF::Background = [ b -1 ] CF::Size = [ x 0 y -20 s W H ] CF::Color = 0 CF::ColorDepth = 16 CF::MinimumSize = 0.6 shape main { transform [ z 0 y (H/2) b 1 ] loop 30 [ z -1 y -2 ] { loop 200000 [] SQUARE1 [ s (0.1/3) x -W..W y -H..H z -0.5..0.5 ] } transform [ b -1 z 3 ] loop 14 [[ s 1.1 y -0.8..-1 s 0.6 z -3 ]] { loop 14 [] tree [ x (-30..-20) z (-3..3) ] loop 14 [] tree [ x (20..30) z (-3..3) ] } } shape tree { branch [ ] } shape branch rule 7 { transform [ s (1..2) 1] SQUARE1 [ ] branch [ y (0.2..0.3) x (-0.05..0.05) s 0.994 r (-6..6) z (-0.3..0.3) ] branch1 [ b 0.001 z -2 r -20..20 ] } rule 0.001 { } rule 0.3 { branch [ r 4..20 ] } rule 0.3 { branch [ r -4..-20 ] } shape branch1 rule 90 { } rule { branch [ r -22..22 s 0.8..1 ] } path SQUARE1 { MOVETO( 0.5, 0.5) LINETO(-0.5, 0.5) LINETO(-0.5, -0.5) LINETO( 0.5, -0.5) CLOSEPOLY() loop N [] FILL()[] } shape S { SQUARE [ a -1 ] loop 1000 [ ] SQUARE [ x (-0.5..0.5) y (-0.5..0.5) s 0.01..0.001 ] } ``` ![enter image description here](https://i.stack.imgur.com/YmLqh.jpg) More renders using different numbers ![enter image description here](https://i.stack.imgur.com/qMz8e.jpg) ![enter image description here](https://i.stack.imgur.com/O4oO5.jpg) ![enter image description here](https://i.stack.imgur.com/s9GB9.png) [Answer] ## IFS with JAVA This solution uses an Iterated Function System (IFS) to describe one (proto) tree. The IFS is applied 100 times (=forest). Before each tree is painted (planted into the forest) the IFS is altered slightly in place (random walk style). So each tree looks slightly different. Pictures are from random seeds: * -824737443 * -1220897877 * -644492215 * 1133984583 No dithering is needed. ``` import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random; import javax.swing.*; public class IFS { static Random random=new Random(); static int BLACK = 0xff000000; static int treeCount = 100; static Random rand = new Random(); static int Height = 600; static int Width = 800; static BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_ARGB); static double[][] ifs=new double[][] {//Tree 3 {; Paul Bourke http://ecademy.agnesscott.edu/~lriddle/ifskit/gallery/bourke/bourke.ifs {0.050000, 0.000000, 0.000000, 0.600000, 0.000000, 0.000000, 0.028000}, {0.050000, 0.000000, 0.000000, -0.500000, 0.000000, 1.000000, 0.023256}, {0.459627, -0.321394, 0.385673, 0.383022, 0.000000, 0.600000, 0.279070}, {0.469846, -0.153909, 0.171010, 0.422862, 0.000000, 1.100000, 0.209302}, {0.433013, 0.275000, -0.250000, 0.476314, 0.000000, 1.000000, 0.555814 /*Paul Bourke has: 0.255814*/}, {0.421325, 0.257115, -0.353533, 0.306418, 0.000000, 0.700000, 0.304651 /*Paul Bourke has: 0.204651*/}, }; public static void main(String[] args) { int seed=random.nextInt(); //seed=-1220897877; random=new Random(seed); for (int t = 0; t < treeCount; t++) { for (int i = 0; i < ifs.length; i++) { for (int j = 0; j < ifs[0].length; j++) { ifs[i][j]=R(ifs[i][j]); } } tree(random.nextDouble(), 0.1*random.nextDouble()); } JFrame frame = new JFrame(""+seed) { public void paint(Graphics g) { setSize(800,600); g.drawImage(img,0,0,null); } }; frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setVisible(true); } private static void tree(double x0, double dist) { double y0=Math.atan(dist+0.01); double scale=Math.atan(0.01)/y0; double x=0; double y=0; for (int n = 0; n < 200000/Math.pow(20*dist+1, 8); n++) { int k = select(ifs); double newx=ifs[k][0]*x + ifs[k][1]*y + ifs[k][2]; double newy=ifs[k][3]*x + ifs[k][4]*y + ifs[k][5]; x=newx; y=newy; newx= Width*(0.5*scale*newx+x0); newy= Height*((1-0.5*scale*newy)-y0-0.1); if (0<=newx && newx<Width && 0<=newy && newy<Height) { img.setRGB((int)newx, (int)newy, BLACK); } } } private static double R(double x) { return (1+ 0.01*random.nextGaussian())*x; } private static int select(double[][] ifs) { int k; double sum=0; for(k=0; k<ifs.length; k++) { sum+=ifs[k][6]; } double r=sum*random.nextDouble(); sum=ifs[0][6]; for(k=0; k<ifs.length-1 && r>sum; k++) { sum+=ifs[k+1][6]; } return k; } } ``` ![enter image description here](https://i.stack.imgur.com/ElRzc.png) ![enter image description here](https://i.stack.imgur.com/RX5vt.png) ![enter image description here](https://i.stack.imgur.com/sVkXW.png) ![enter image description here](https://i.stack.imgur.com/cokuk.png) [Answer] ## C: 301 This program creates a simple, abstract image in the [PGM](http://netpbm.sourceforge.net/doc/pgm.html) format. You can open it with GIMP. ``` int x,y,i,d,w;srand(time(NULL));unsigned char p[480000];FILE *f=fopen("a.pgm","w");fprintf(f,"P5\n800 600\n1\n");i=480000;while(i--)p[i]=i>240000|(i%800+i/800&3)!=0;i=100;while(i--){d=(11000-i*i)/99;y=300+1100/d;x=rand()%800;while(y--){w=300/d;while(w--)p[y*800+w+x]=0;}}fwrite(p, 1, 480000, f);fclose(f); ``` Here is an example run:![Generated Image](https://i.stack.imgur.com/1B2MY.png) [Answer] I noticed a distinct lack of conifers here, so I hacked something together in Python. ``` from PIL import Image import random #Generates the seed for a tree def makeSeed(y): random.seed() seed_x = random.randint(10, 590) seed_y = y width = random.randint(5, 10) height = random.randint(width*5, width*30) return (seed_x, seed_y, width, height) #Grows the vertical components def growStems(seed_data, pixel_field): seed_x = seed_data[0] seed_y = seed_data[1] width = seed_data[2] height = seed_data[3] for x in range(seed_x, seed_x+width): for y in range(seed_y-height, seed_y): pixel_field[x][y] = (0, 0, 0) #Dithering if seed_y > 300 and seed_y < 320: if (x+y)%2==0: pixel_field[x][y] = (255, 255, 255) elif seed_y >= 320 and seed_y < 340: if (x+y)%4==0: pixel_field[x][y] = (255, 255, 255) elif seed_y >= 340 and seed_y < 360: if (x+y)%8==0: pixel_field[x][y] = (255, 255, 255) return pixel_field #Grows the horizontal components def growBranches(seed_data, pixel_field): seed_x = seed_data[0] seed_y = seed_data[1] width = seed_data[2] height = seed_data[3] branch_height = seed_y-height branch_width = width branch_length = 2 max_prev = branch_length branches = [] while(branch_height >= seed_y-height and branch_height < seed_y-(3*width) and branch_length < height/3): branches.append((branch_height, branch_width, branch_length)) branch_height+= 4 branch_length+=2 #Gives the conifer unevenness to make it look more organic if random.randint(0,110) > 100 and branch_length > max_prev: max_prev = branch_length branch_length -= branch_length/4 max_length = height/3 for x in range(seed_x-max_length, seed_x+max_length): for y in range(seed_y-height, seed_y): for branch in branches: bh = branch[0] bw = branch[1] bl = branch[2] #Establishing whether a point is "in" a branch if x >= seed_x-bl+(width/2) and x <= seed_x+bl+(width/2): if x > 1 and x < 599: if y >= bh-(bw/2) and y <= bh+(bw/2): if y < 400 and y > 0: pixel_field[x][y] = (0, 0, 0) #Dithering if seed_y > 300 and seed_y < 320: if (x+y)%2==0: pixel_field[x][y] = (255, 255, 255) elif seed_y >= 320 and seed_y < 340: if (x+y)%4==0: pixel_field[x][y] = (255, 255, 255) elif seed_y >= 340 and seed_y < 360: if (x+y)%8==0: pixel_field[x][y] = (255, 255, 255) return pixel_field def growTrees(n): pixel_field = [[(255, 255, 255) for y in range(400)] for x in range(600)] #Create the ground for i in range(600): for j in range(400): if pixel_field[i][j]==(255,255,255) and j > 300: if (i+j)%2 == 0: pixel_field[i][j]=(0,0,0) seed_ys=[] #Generates seeds for the trees and orders them back to front to make the dithering work for t in range(n): seed_ys.append(random.randint(300,390)) seed_ys.sort() for s in range(len(seed_ys)): seed= makeSeed(seed_ys[s]) pixel_field = growStems(seed, pixel_field) pixel_field = growBranches(seed, pixel_field) return pixel_field def makeForest(): forest = growTrees(25) img = Image.new( 'RGB', (600,400), "white") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): if pixels[i,j]==(255,255,255) and j > 300: if (i+j)%2 == 0: pixels[i,j]=(0,0,0) pixels[i,j] = forest[i][j] # set the colour accordingly img.save("Forest25.jpg") if __name__ == '__main__': makeForest() ``` ![Forest with 5 trees](https://i.stack.imgur.com/dgkbU.jpg) ![Forest with 10 trees](https://i.stack.imgur.com/pdasm.jpg) ![Forest with 25 trees](https://i.stack.imgur.com/gxTxI.jpg) This was my first Code Golf, it was a lot of fun! [Answer] This answer isn't as pretty as I hoped, but it's a stepping stone to a more 3D idea I'm working on, and I really like the idea of actually simulating which trees get resources![enter image description here](https://i.stack.imgur.com/S8Ggh.png) ``` package forest; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class Forest extends Canvas{ private int[] heights = new int[800]; private BufferedImage buffered_image; File outputFile = new File("saved.png"); Random r = new Random(); public Forest() { buffered_image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB); for( int j = 0; j < 800; j++){ heights[j] = -10000; for(int k = 0; k < 600; k++){ buffered_image.setRGB(j, k, 0xFFFFFF); } } for(int i = 0; i < 7; i ++){ heights[r.nextInt(800)] = 0; } this.setPreferredSize(new Dimension(800, 600)); this.setSize(new Dimension(800, 600)); for( int i = 0; i < 200000; i++){ int x = r.nextInt(798) + 1; heights[x] = Math.min(599, heights[x - 1] == heights[x + 1] ? heights[x] : Math.max(Math.max(heights[x - 1], heights[x]),heights[x + 1]) + 1); buffered_image.setRGB(x, Math.min(599, 600 - heights[x]), 0); } try { ImageIO.write(buffered_image, "png", outputFile); } catch (IOException e) { } update(); } public void repaint(){ if(this.getGraphics() != null) paint(this.getGraphics()); } public void paint(Graphics g) { g.drawImage(buffered_image, 0, 0, this); } public void update() { repaint(); } public static void main(String[] args) throws IOException { JFrame main_frame = new JFrame(); main_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel top_panel = new JPanel(); top_panel.setLayout(new BorderLayout()); Forest s = new Forest(); top_panel.add(s, BorderLayout.CENTER); main_frame.setContentPane(top_panel); main_frame.pack(); main_frame.setVisible(true); } } ``` ]
[Question] [ For this golf, you will need to use more than one language. # The task A [Rube Goldberg machine](https://en.wikipedia.org/wiki/Rube_Goldberg_machine) is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output `Rube Goldberg`... but not directly. # The machine Your "machine" is the source code that, once executed, will give another source code in another language that will output `Rube Goldberg` upon execution. Got it? I rephrase: your initial code must give another code, that other code must output `Rube Goldberg`. Both codes must be written in different languages. # The bonus which is more like the only fun way to do it There is a bonus if your code outputs a code that will output a code that will ... that will output `Rube Goldberg`. *NOTE:* any sort of output can be used (stdout, stderr, dialog box, ...) # The points The number of points is equal to the number of bytes used in your code, divided by the number of **distinct**, **extra** languages that you used. *NOTE:* different languages use different encodings. The number of bytes is counted in the initial language with its own encoding. ### Examples * `Pyth -> J -> Javascript -> output` in 30 bytes = 30/2 = **15 points** (J and Javascript are the extra languages) * `Java -> C# -> C++ -> PHP -> output` in 36 bytes = 36/3 = **12 points** (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes)) * `C -> output` in 10 bytes = 10/0 = **Infinity points** (No extra languages) * `Python -> Perl -> Ruby -> Python -> Ruby` in 44 bytes = 44/2 = **22 points** (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used) *NOTE:* Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes. # The answer Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language). # The winner Of course, like usual, the lowest score wins. *NOTE:* As usual, standard loopholes and "cheats" are not allowed. [Answer] # [Foo](http://esolangs.org/wiki/Foo) → [gs2](https://github.com/nooodl/gs2) → [M](https://github.com/DennisMitchell/m/) → [Jelly](https://github.com/DennisMitchell/jelly/) → [Retina](https://github.com/m-ender/retina) → [Aeolbonn](https://esolangs.org/wiki/Aeolbonn) → [Par](https://ypnypn.github.io/Par/) → [Actually](http://github.com/Mego/Seriously) → [Sprects](http://dinod123.neocities.org/interpreter.html) → [sed](https://www.gnu.org/software/sed/) → [Universal Lambda](https://esolangs.org/wiki/Universal_Lambda) → [Lines](http://esolangs.org/wiki/Lines) → [///](http://esolangs.org/wiki////) → [m4](https://www.gnu.org/software/m4/m4.html): 19/13 ≈ 1.4615 points ``` "“GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦ ``` All answers are given in the [Jelly code page](https://github.com/DennisMitchell/jelly/wiki/Code-page). ¶ represents a newline. # Mechanism ``` Language Code —————————————————————————————————————— Foo "“GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦ gs2 “GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦ M “GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ Jelly “¶:`".c Rube Goldberg#\/” Retina ¶:`".c Rube Goldberg#\/ Aeolbonn :`".c Rube Goldberg#\/ Par `".c Rube Goldberg#\/ Actually ".c Rube Goldberg#\/ Sprects .c Rube Goldberg#\/ sed c Rube Goldberg#\/ U.Lambda Rube Goldberg#\/ Lines Rube Goldberg#\/ /// Rube Goldberg#/ m4 Rube Goldberg# ``` EDIT: Oops, there was an error in the Pyth program. I replaced Pyth and GolfScript by Par. EDIT 2: Added GNU m4. EDIT 3: Added Foo and M. [Answer] # 33 languages, 40 bytes, 1.25 points ``` 33.Bubblegum : (hexdump) 3f1dbbbc87ebd1594f79fdbfa01c8a8ded64e1796d24d2f23e0115677f3cd9b3cd59c217c75a5c30 32./// : "echo "B*"Rube Goldberg"+````{`]"print(%s)"e%}E*/ 31.CJam : "echo "B*"Rube Goldberg"+````{`]"print(%s)"e%}E* 30.Python : (524,452 bytes) 29.Falcon : (262,301 bytes) 28.Groovy : (131,222 bytes) 27.JavaScript : ( 65,679 bytes) 26.Julia : ( 32,904 bytes) 25.Lua : ( 16,513 bytes) 24.Move : print("print(\"print(\\\"print(\\\\\\\"print(\\\\\\\\\\\\\\\"print(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"print(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"print(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\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\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\")\")") 18.MoonScript : print("print(\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\"\\\"\")") 17.R : print("\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\\\\\\\\\\\\\"\\\\\\\"\\\"\"") 16.Arcyóu : [1] "\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\\\\\\\\\\\\\"\\\\\\\"\\\"\"" 15.Convex : "\"\\\"\\\\\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\\\\\"\\\"\"" 14.GolfScript : "\"\\\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\\\"\"" 13.Pyth : "\"echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg\"" 12.Foo : "echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg" 11.ash : echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg 10.bash : echo echo echo echo echo echo echo echo echo echo Rube Goldberg 09.csh : echo echo echo echo echo echo echo echo echo Rube Goldberg 08.dash : echo echo echo echo echo echo echo echo Rube Goldberg 07.fish : echo echo echo echo echo echo echo Rube Goldberg 06.ksh : echo echo echo echo echo echo Rube Goldberg 05.mksh : echo echo echo echo echo Rube Goldberg 04.pash : echo echo echo echo Rube Goldberg 03.rc : echo echo echo Rube Goldberg 02.tcsh : echo echo Rube Goldberg 01.zsh : echo Rube Goldberg 00.OUTPUT : Rube Goldberg ``` Takes advantage of the fact that many different languages share the same printing syntax, resulting in exponentially longer but highly compressible source code. ### Permalinks (incomplete, to be updated) * [Bubblegum](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogM2YgMWQgYmIgYmMgODcgZWIgZDEgNTkgNGYgNzkgZmQgYmYgYTAgMWMgOGEgOGQgID8uLi4uLi5ZT3kuLi4uLi4KMDAwMDAxMDogZWQgNjQgZTEgNzkgNmQgMjQgZDIgZjIgM2UgMDEgMTUgNjcgN2YgM2MgZDkgYjMgIC5kLnltJC4uPi4uZy48Li4KMDAwMDAyMDogY2QgNTkgYzIgMTcgYzcgNWEgNWMgMzAgICAgICAgICAgICAgICAgICAgICAgICAgIC5ZLi4uWlww&input=) * [///](http://slashes.tryitonline.net/#code=ImVjaG8gIkIqIlJ1YmUgR29sZGJlcmciK2BgYGB7YF0icHJpbnQoJXMpImUlfUUqLw&input=) * [CJam](http://cjam.aditsu.net/#code=%22echo%20%22B*%22Rube%20Goldberg%22%2B%60%60%60%60%7B%60%5D%22print(%25s)%22e%25%7DE*) [Answer] # Jolf -> Actually -> Jelly -> Pyth -> Retina -> /// -> Golfscript: 15 / 6 = 2.5 points 5.4 points thanks to Martin Ender. 0.1 points thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ. Note: both Actually and Jelly have their own code-page, so they could be transfered byte-by-byte, just not in the Online versions. ### Jolf ``` aq"“'ẉ'ɠ@ịQCṁỊ» ``` ### Actually ``` "“'ẉ'ɠ@ịQCṁỊ» ``` [Try it online!](http://actually.tryitonline.net/#code=IuKAnCfhuoknyaBA4buLUUPhuYHhu4rCuw&input=) ### Jelly ``` “'ẉ'ɠ@ịQCṁỊ» ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcJ-G6iSfJoEDhu4tRQ-G5geG7isK7&input=) ### Pyth ``` k"'Rube Goldberg'/ ``` [Try it online!](http://pyth.herokuapp.com/?code=k%22%27Rube+Goldberg%27%2F&debug=0) ### Retina ``` 'Rube Goldberg'/ ``` [Try it online!](http://retina.tryitonline.net/#code=CidSdWJlIEdvbGRiZXJnJy8&input=) ### /// ``` 'Rube Goldberg'/ ``` [Try it online!](http://slashes.tryitonline.net/#code=J1J1YmUgR29sZGJlcmcnLw&input=) ### Golfscript ``` 'Rube Goldberg' ``` [Try it online!](http://golfscript.tryitonline.net/#code=J1J1YmUgR29sZGJlcmcn&input=) [Answer] # Python -> Batch -> Javascript -> Java -> PHP -> C++ -> Foo -> Brainfuck 31.(142857) points ## Python ``` print'@echo alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""`' ``` ## Batch ``` @echo alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""` ``` ## JavaScript ``` alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""` ``` ## Java ``` void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\"" ``` ## PHP ``` echo"void f(){cout<<\"\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\"\"}" ``` ## C++ ``` void f(){cout<<"\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\""} ``` ## Foo ``` "-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------." ``` ## BrainFuck ``` -[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------. ``` [Answer] ## JS -> Cobol -> Python -> IBM 360 BAL 261 bytes/4 languages = 65.25 Points *Was aiming to use difficult languages, with more obfuscation. Javascript converts the string from base64 into Cobol, which produces Python that decodes the BAL code from hex.* **Javascript** ``` console.log(atob(' 1 LH8T88d@05R850T8LT88!Q!R Cek*k{[~&vgm88yx9m4m6y6m8wx9m6}s}6Ovm9m6kg7m4m6x{m69x{6Ovm8wOxxg8Ovm9yOym4m6sv9x{6Ovm8km69Oxs}w}snxv86m69Ox7}m69x{49xyx}wws88wsg88oww}g4Ovkm4Oxyxww}}7g8{9swyyg9wyym6Ovm8Oxwxm6fm6gyxm8sox6m6gyxm6gkm6gLP'); ``` **Cobol** ``` IDENTIFICATION DIVISION. PROGRAM-ID. Rube. ENVIRONMENT DIVISION. DATA DIVISION. PROCEDURE DIVISION. Display ' print bytearray.fromhex("202f2f204558454320415353454d424c5920092020535441525420204d41494e0942414c522020322c30200920205553494e47202a2c32200920204f50454e20205052494e54200920204d5643094255462c485720092020505554095052494e5420092020434c4f5345205052494e5420092020454f4a2020485709444309434c3133325c275255424520474f4c44424552475c27202042554609445309434c31333220205052494e5409445446505220494f41524541313d4255462c444556414444523d5359534c53542c424c4b53495a453d3133322c09092a2009094445564943453d333230332c434f4e54524f4c3d5945532c5052494e544f563d5945532020092020454e44094d41494e20202f2a20202f2f2045584543204c4e4b45445420202f2f204558454320202f2a20202f26").decode()'. STOP RUN. ``` **Python** ``` print bytearray.fromhex("202f2f204558454320415353454d424c5920092020535441525420204d41494e0942414c522020322c30200920205553494e47202a2c32200920204f50454e20205052494e54200920204d5643094255462c485720092020505554095052494e5420092020434c4f5345205052494e5420092020454f4a2020485709444309434c3133325c275255424520474f4c44424552475c27202042554609445309434c31333220205052494e5409445446505220494f41524541313d4255462c444556414444523d5359534c53542c424c4b53495a453d3133322c09092a2009094445564943453d333230332c434f4e54524f4c3d5945532c5052494e544f563d5945532020092020454e44094d41494e20202f2a20202f2f2045584543204c4e4b45445420202f2f204558454320202f2a20202f26").decode() ``` **IBM 360 BAL** ``` // EXEC ASSEMBLY START MAIN BALR 2,0 USING *,2 OPEN PRINT MVC BUF,HW PUT PRINT CLOSE PRINT EOJ HW DC CL132'RUBE GOLDBERG' BUF DS CL132 PRINT DTFPR IOAREA1=BUF,DEVADDR=SYSLST,BLKSIZE=132, * DEVICE=3203,CONTROL=YES,PRINTOV=YES END MAIN /* // EXEC LNKEDT // EXEC /* /& ``` **Output** ``` RUBE GOLDBERG ``` [Answer] # [MATL](https://github.com/lmendo/MATL) -> [CJam](https://sourceforge.net/projects/cjam/) -> [05AB1E](https://github.com/Adriandmen/05AB1E) -> [Golfscript](http://www.golfscript.com/golfscript/) ~~21/2~~ ~~18/2~~ 22/3 *Thanks for Martin for 3 chars off!* ``` '"''Rube Goldberg''"`' ``` executed [in MATL](http://matl.tryitonline.net/#code=JyInJ1J1YmUgR29sZGJlcmcnJyJgJw&input=) gives ``` "''Rube Goldberg''"` ``` which [in CJam](http://cjam.tryitonline.net/#code=IidSdWJlIEdvbGRiZXJnJyJg&input=) gives ``` "'Rube Goldberg'" ``` which [in 05AB1E](http://05ab1e.tryitonline.net/#code=IidSdWJlIEdvbGRiZXJnJyI&input=) gives ``` 'Rube Goldberg' ``` which [in Golfscript](http://golfscript.tryitonline.net/#code=J1J1YmUgR29sZGJlcmcn&input=) gives ``` Rube Goldberg ``` [Answer] # Reng -> ><> -> Vitsy, 32 / 2 = 16 points I wanted to do *only* 2D languages--on a single line! ``` {'Z"Rube Goldberg"'ol?!;f3+0.}n~ ``` ## Explanation ``` Reng sees: {'Z"Rube Goldberg"'ol?!;f3+0.}n~ <----------------------------> code block n~ print that and stop ><> sees: {'Z"Rube Goldberg"'ol?!;f3+0.} { no-op? 'Z"Rube Goldberg"' push that string backwards o output a char l?!; terminate if none are left f3+0. go to (0, 18) in the codebox Vitsy sees: "grebdloG ebuR"Z "............." push that string Z output it ``` [Answer] ## Perl -> JavaScript (ES6) -> Batch -> sh, 39 / 3 = 13 points ## Perl ``` print 'alert`@echo echo Rube Goldberg`' ``` ## JavaScript (ES6) ``` alert`@echo echo Rube Goldberg` ``` ## Batch ``` @echo echo Rube Goldberg ``` ## sh ``` echo Rube Goldberg ``` [Answer] # Java->Thue->Javascript->Batch->Microscript II->Brainf\*\*\*, 236/5=47.2 ``` interface J{static void main(String[]a){System.out.print("a::=~alert`echo \"+++++[>+A<-]>[>++>+++<<-]>++.>---.<++AA.+++.>>++++[>+A<-]>.[>++>+++>+++<<<-]>A.>+AA.---.>++++.--.+++.<<<<<---.>>>>>++.\"`\n::=\na".replaceAll("A","+++++++"));}} ``` --- Generated Thue program: ``` a::=~alert`echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."` ::= a ``` Generated Javascript program: ``` alert`echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++."` ``` Generated Batch program: ``` echo "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++." ``` Generated Microscript II program: ``` "+++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++." ``` Generated Brainf\*\*\* program: ``` +++++[>++++++++<-]>[>++>+++<<-]>++.>---.<++++++++++++++++.+++.>>++++[>++++++++<-]>.[>++>+++>+++<<<-]>+++++++.>+++++++++++++++.---.>++++.--.+++.<<<<<---.>>>>>++. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage) → [4DOS](https://www.4dos.info) → [4OS2](https://www.4dos.info/v4os2.htm) → [Almquist shell](https://www.in-ulm.de/%7Emascheck/various/ash) → [Bourne shell](https://en.wikipedia.org/wiki/Bourne_shell) → [Bourne Again shell](https://www.gnu.org/software/bash) → [COMMAND.COM](https://en.wikipedia.org/wiki/COMMAND.COM) → [C shell](http://bxr.su/NetBSD/bin/csh) → [Debian Almquist shell](http://gondor.apana.org.au/%7Eherbert/dash) → [Desktop Korn shell](https://docs.oracle.com/cd/E19455-01/806-1365/6jalh9ls5/index.html) → [Extensible shell](http://wryun.github.io/es-shell) → [Friendly Interactive shell](http://fishshell.com) → [Hamilton C shell](https://hamiltonlabs.com/Cshell.htm) → [Ion shell](https://gitlab.redox-os.org/redox-os/ion) → [Inferno shell](http://www.vitanuova.com/inferno/papers/sh.html) → [KornShell](http://www.kornshell.org) → [MirBSD Korn shell](http://www.mirbsd.org/mksh.htm) → [MKS Korn shell](https://docs.microsoft.com/en-us/previous-versions/tn-archive/bb463204(v=technet.10)) → [NDOS](https://us.norton.com/products) → [OpenBSD Korn shell](https://github.com/ibara/oksh) → [OS/2 Window](https://en.wikipedia.org/wiki/Cmd.exe#OS/2) → [Pocket CMD](https://en.wikipedia.org/wiki/Cmd.exe#Windows_CE) → [Public Domain Korn shell](http://web.cs.mun.ca/%7Emichael/pdksh) → [ReactOS Command Prompt](https://en.wikipedia.org/wiki/Cmd.exe#ReactOS) → [Run Commands](https://en.wikipedia.org/wiki/Rc) → [Steve Koren shell](http://aminet.net/package/util/shell/SKsh21) → [Thompson shell](https://en.wikipedia.org/wiki/Thompson_shell) → [Take Command Console](https://jpsoft.com/products/tcc-cmd-prompt.html) → [Tool Command Language KornShell](https://web.archive.org/web/20090316024446/http://www.cs.princeton.edu/%7Ejlk/tksh) → [Tool Command Language shell](https://www.tcl-lang.org/man/tcl/UserCmd/tclsh.htm) → [TENEX C shell](https://www.tcsh.org) → [Windows Command Prompt](https://en.wikipedia.org/wiki/Cmd.exe#Windows_NT_family) → [Z shell](https://zsh.sourceforge.io), \$\frac{15}{32}=0.46875\$ Beats all other answers. All it took was a couple centuries of looking for shells with `echo`. 1. **Jelly:** `“¡oġ»ẋ32“,oƝ+Ƈ»` 2. **4DOS:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 3. **4OS2:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 4. **Almquist shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 5. **Bourne shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 6. **Bourne Again shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 7. **COMMAND.COM:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 8. **C shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 9. **Debian Almquist shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 10. **Desktop Korn shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 11. **Extensible shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 12. **Friendly Interactive shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 13. **Hamilton C shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 14. **Inferno shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 15. **Ion shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 16. **KornShell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 17. **MirBSD Korn shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 18. **MKS Korn shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 19. **NDOS:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 20. **OpenBSD Korn shell:** `echo echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 21. **OS/2:** `echo echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 22. **Pocket CMD:** `echo echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 23. **Public Domain Korn shell:** `echo echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 24. **ReactOS Command Prompt:** `echo echo echo echo echo echo echo echo echo echo Rube Goldberg` 25. **Run Commands:** `echo echo echo echo echo echo echo echo echo Rube Goldberg` 26. **Steve Koren shell:** `echo echo echo echo echo echo echo echo Rube Goldberg` 27. **Thompson shell:** `echo echo echo echo echo echo echo Rube Goldberg` 28. **Take Command Console:** `echo echo echo echo echo echo Rube Goldberg` 29. **Tool Command Language KornShell:** `echo echo echo echo echo Rube Goldberg` 30. **Tool Command Language shell:** `echo echo echo echo Rube Goldberg` 31. **TENEX C shell:** `echo echo echo Rube Goldberg` 32. **Windows Command Prompt:** `echo echo Rube Goldberg` 33. **Z shell:** `echo Rube Goldberg` 34. **Output:** `Rube Goldberg` [Answer] # Javascript -> PHP -> Foo 14 points Javascript: ``` alert`echo'"Rube Goldberg"'` ``` PHP: ``` echo'"Rube Goldberg"' ``` Foo: ``` "Rube Goldberg" ``` [Answer] ## /// -> PowerShell -> CJam -> Foo -> BASH, 24 bytes/4 = 6 ``` '"echo Rube Goldberg"p'/ ``` When executed in /// gives ``` '"echo Rube Goldberg"p' ``` which, when executed in PowerShell gives ``` "echo Rube Goldberg"p ``` which, when executed in CJam gives ``` "echo Rube Goldberg" ``` which, when executed in Foo gives ``` echo Rube Goldberg ``` which, when executed in BASH gives ``` Rube Goldberg ``` [Answer] # APL → J → K, 21 [bytes](https://codegolf.meta.stackexchange.com/a/9411/43319)/2 → 10.5 `'''"Rube Goldberg"'''` on Dyalog APL gives `'"Rube Goldberg"'` which in J gives `"Rube Goldberg"` which in K gives `Rube Goldberg` If we allow even closer related languages we can get many more. [Answer] # Python → Ruby → Bash, score: 35 / 2 = 17.5 ``` print"puts'echo \"Rube Goldberg\"'" ``` when executed in Python, gives ``` puts'echo "Rube Goldberg"' ``` with the `\"`s escaped. Next, this, executed Ruby gives ``` echo "Rube Goldberg" ``` and lastly, executing this in Bash gives ``` Rube Goldberg ``` which is the expected string. [Answer] # C → JS → Shell → [><>](https://esolangs.org/wiki/Fish): 68 / 3 = 22.67 ### C ``` main(){puts("console.log(`echo '\"Rube Goldberg\"ar!;ooooooo|'`)");} ``` ### Javascript ``` console.log(`echo '"Rube Goldberg"ar!;ooooooo|'`) ``` ### Shell ``` echo '"Rube Goldberg"ar!;ooooooo|' ``` ### [><>](http://esolangs.org/wiki/Fish) ``` "Rube Goldberg"ar!;ooooooo| ``` Result: ``` Rube Goldberg ``` as required. [Answer] # [Sprects](https://dinod123.neocities.org/interpreter.html) → [///](https://esolangs.org/wiki////) → [itflabtijtslwi](https://esolangs.org/wiki/itflabtijtslwi) → Python 2 → Pyth, 24 / 4 = 6 # Sprects ``` $print'"Rube Goldberg'\/ ``` # /// ``` print'"Rube Goldberg'\/ ``` # itflabtijtslwi ``` print'"Rube Goldberg'/ ``` # Python 2 ``` print'"Rube Goldberg' ``` # Pyth ``` "Rube Goldberg ``` # Output ``` Rube Goldberg ``` [Answer] # /// -> K -> J -> SX -> Golfscript -> Pyke -> Lua -> Moonscript -> C -> Pyth -> Python -> BrainF\*\*\* -> Bash -> Ruby -> Zsh, 554b/16= 34.625 ## /// ``` "'我(\"\\\"print \\\\\"print(\\\\\\\"print \\\\\\\\\"#include<stdio.h>\\\\\\\\\nint main(){printf(\\\\\\\\\"\\\\\\\\\\\"print \\\\\\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\\\\\"\\\\\\\\\\\");}\\\\\\\\\"\\\\\\\")\\\\\"\\\"\")'"/ ``` ## K ``` "'我(\"\\\"print \\\\\"print(\\\\\\\"print \\\\\\\\\"#include<stdio.h>\\\\\\\\\nint main(){printf(\\\\\\\\\"\\\\\\\\\\\"print \\\\\\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\\\\\"\\\\\\\\\\\");}\\\\\\\\\"\\\\\\\")\\\\\"\\\"\")'" ``` ## J ``` '我(\"\\\"print \\\\\"print(\\\\\\\"print \\\\\\\\\"#include<stdio.h>\\\\\\\\\nint main(){printf(\\\\\\\\\"\\\\\\\\\\\"print \\\\\\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\\\\\"\\\\\\\\\\\");}\\\\\\\\\"\\\\\\\")\\\\\"\\\"\")' ``` ## SX ``` 我(\"\\\"print \\\\\"print(\\\\\\\"print \\\\\\\\\"#include<stdio.h>\\\\\\\\\nint main(){printf(\\\\\\\\\"\\\\\\\\\\\"print \\\\\\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\\\\\"\\\\\\\\\\\");}\\\\\\\\\"\\\\\\\")\\\\\"\\\"\") ``` ## Golfscript ``` "\"print \\\"print(\\\\\"print \\\\\\\"#include<stdio.h>\\\\\\\nint main(){printf(\\\\\\\"\\\\\\\\\"print \\\\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\\\"\\\\\\\\\");}\\\\\\\"\\\\\")\\\"\"" ``` ## Pyke ``` "print \"print(\\\"print \\\\\"#include<stdio.h>\\\\\\nint main(){printf(\\\\\"\\\\\\\"print \\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\\\"\\\\\\\");}\\\\\"\\\")\"" ``` ## Perl ``` print "print(\"print \\\"#include<stdio.h>\\\nint main(){printf(\\\\\"\\\\\\\"print \\\\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\\\"\\\\\");}\\\"\")" ``` ## Lua ``` print("print \"#include<stdio.h>\nint main(){printf(\\\"\\\\\"print \\\\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\\\"\\\");}\"") ``` ## Moonscript ``` print "#include<stdio.h>\nint main(){printf(\"\\\"print \\\\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\"\");}" ``` ## C ``` #include<stdio.h> int main(){printf("\"print \\\"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\\\"");} ``` ## Pyth ``` "print \"--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\" ``` ## Python 2 ``` print "--[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>." ``` ## BrainF\*\*\* ``` --[----->+<]>-.--.+++++.+++++++.[--->+<]>-----.--[-->+++<]>.+[-->+++<]>.-[-->+<]>--.[-->+++++++<]>.+++++.-.-.+[---->+<]>+++.-[->+++<]>-.-[->++++++<]>.[->+++<]>-.--.+++++.+++++++.[--->+<]>-----.>-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.-----------.-[->++++++<]>.\ ``` ## Bash ``` echo -E puts \"echo Rube Goldberg\" ``` ## Ruby ``` puts "echo Rube Goldberg" ``` ## Zsh ``` echo Rube Goldberg ``` Obviously I could add a lot of echo's but it feels like it would copy Dennis' answer. [Answer] # sed -> Pyth -> Python -> AWK -> Make -> Bash, 200/4 = 50 ``` s/.*/=Z"echo"p"print(~BEGIN{print\\"r=S\\"Rube GoldbergS\\"Sntrue =;@Y"(){ Y" S\\"${r}S\\"|awk \\\\~$0=S\\"x:SSnSSt@Y" S\\"$0\\\\~;}Sntrue :SnSt@YdpZp" ${r}\\"}~)"p"/ s/S/\\\\\\\\/g;s/~/'/g;s/Y/"pZp/g ``` [Try it online!](https://tio.run/##NU7BCsIwFLv7FeUxcAr6dt4YDEGGFw/2tLGLc6WK0pV2Q2Guv17bMnN44SUhRLNux8Vorcb9FvMa2O3egwSpHmKIzeFYns5TeJoGVE7dvYwtI2X/6lqmuBeoGNTISJ4VFcSbiVRAvBxNavb8vb6fpHEwURIKPimlgtKh@AeT4GbzUpQ615mdrCUQ3@Iys9m4VbjSSLFZgDzTaHAduEJweeTW/gA "sed – Try It Online") Not the shortest, or the most languages, but I enjoyed figuring this out. And the second to the last step in the chain is Make/Bash polyglot. If you run it as a Makefile, it generates a Bash script. If you run it as a Bash script, it generates a Makefile. ### Pyth ``` =Z"echo"p"print('BEGIN{print\"r=\\\\\"Rube Goldberg\\\\\"\\\\ntrue =;@"pZp"(){ "pZp" \\\\\"${r}\\\\\"|awk \\'$0=\\\\\"x:\\\\\\\\n\\\\\\\\t@"pZp" \\\\\"$0\\';}\\\\ntrue :\\\\n\\\\t@"pZpdpZp" ${r}\"}')"p" ``` The `p"` at the end is only necessary since I can't find a way to make `sed` leave off the trailing LF and Pyth really hates blank input source lines... At least the TIO version does. I found adding a print statement follow by an open string squelched the error. ### Python ``` print('BEGIN{print"r=\\"Rube Goldberg\\"\\ntrue =;@echo(){ echo \\"${r}\\"|awk \'$0=\\"x:\\\\n\\\\t@echo \\"$0\';}\\ntrue :\\n\\t@echo echo ${r}"}') ``` ### AWK ``` BEGIN{print"r=\"Rube Goldberg\"\ntrue =;@echo(){ echo \"${r}\"|awk '$0=\"x:\\n\\t@echo \"$0';}\ntrue :\n\t@echo echo ${r}"} ``` ### Make/Bash polyglot ``` r="Rube Goldberg" true =;@echo(){ echo "${r}"|awk '$0="x:\n\t@echo "$0';} true : @echo echo ${r} ``` Since that has to work as a Makefile, there are tabs in the original, which don't cut-n-paste into this page properly... ### Bash (if you treat the Make/Bash step as Make) ``` echo Rube Goldberg ``` ### Make (if you treat the Make/Bash script as Bash) ``` x: @echo Rube Goldberg ``` And again, there's a tab in the original... [Answer] ## Python -> Ruby -> Bash -> JS -> /// -> m4, score: 54 / 5 = 10.8 ``` Original print"puts\"echo \'alert(\\\"Rube Goldberg#/\\\")'\"" Python puts"echo 'alert(Rube Goldberg)'" Ruby echo 'alert("Rube Goldberg#/")' Bash alert("Rube Goldberg#/") JS Rube Goldberg#/ /// Rube Goldberg# m4 Rube Goldberg ``` I've got the /// and m4 trick from the answer <https://codegolf.stackexchange.com/a/83627/53416> [Answer] ## dc -> Fortran -> Basic -> Vim, 59/3 = 19.(6) points With this answer I wanted to contribute to the variety of languages already used in other answers. **dc:** ``` [program P;write(*,*)"PRINT ""echo 'Rube Goldberg'""";end]P ``` **Fortran:** ``` program P;write(*,*)"PRINT ""echo 'Rube Goldberg'""";end ``` **Basic:** ``` PRINT "echo 'Rube Goldberg'" ``` **Vim:** ``` echo 'Rube Goldberg' ``` **Final output:** ``` Rube Goldberg ``` [Answer] # GolfScript -> Python -> Bash -> Ruby -> ///, 49/4 = 12.25 points **GolfScript:** `"print('echo puts \\\\\\'Rube Goldberg/\\\\'')"` **Python:** `print('echo puts \\\'Rube Goldberg/\\\'')` **Bash:** `echo puts \'Rube Goldberg/\'` **Ruby:** `puts 'Rube Goldberg/'` **///:** `Rube Goldberg/` **Output:** Rube Goldberg ]
[Question] [ # [Oreoorererereoo](https://i.redd.it/kqibcu69xm721.jpg) Given an input string that is similar to the word "oreo", give an ASCII representation of the cookie that is as wide as the input string (to ensure cookie stability). ## Rules * The input is lowercase, a non-empty string with no whitespace containing any combination of the strings "o" and "re", and containing only those strings. * The string "o" represents the solid cookie, while the string "re" represents the filling. * The output must be a stacked cookie that is as wide as the input string. * The output may not be an array of strings * The cookie must overlap the filling by one character on each side * The characters used for the output don't have to match the output below (█ and ░), they just have to be different non-whitespace characters for the two parts of the cookie * The whitespace padding on the left side of the filling is required, and any trailing whitespace is optional ## Examples ``` Input: oreo Output: ████ ░░ ████ Input: o Output: █ Input: re Output: (two spaces) Input: rere Output: ░░ ░░ Input: oreoorererereoo Output: ███████████████ ░░░░░░░░░░░░░ ███████████████ ███████████████ ░░░░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░░░░░░ ░░░░░░░░░░░░░ ███████████████ ███████████████ ``` Since this is code golf the shortest answer wins, good luck :) [Answer] # [Pepe](https://esolangs.org/wiki/Pepe), 364 bytes Unfortunately the online interpreter does not take care of compressing comments, hence all `o` characters will be replaced by a space.. Neither the spaces nor the `o` are necessary, so this could be 295 bytes, but I like it more this way: ``` rEeEEeeEeEororEEoreoreeeEeeeeeorEEEEeoREeoreorEeEEeEEEEororEEoreorEEEEEoREeoreorEeEEEeeEeororEEoreoReoREoREEEeoREEEEEoreorEorEEEeorEEEEEoreEoREeoreoREEeoREEEEeEeeoREEEeoREeeEoREEEeoREEEEEEEorEEEeEorEEEeoREoREEEeoREEEEEoREEoReoreorEEEeEoREEEEEEeorEEEeoReEoREoREEEeoREEoReoroReEeoREoREEEeorEEEEeoReeoREEEeoREeeEoREEEeoREEEEEEEoreoReoReoREoREEEeoREEEEEoreeeeeEeEeoRee ``` [Try it online!](https://soaku.github.io/Pepe/#!ca@E$U8-gD$!cu@E$-iD$!d0@E$.&!p-j$_!o-iAD$TRt!p!f!pE7-e!o&!p-jF.$-eE5!oB&!pF.@L&!p-g/!p!f!pE7$..&!p-jT0/ "Pepe – Online interpreter") ## Ungolfed There might be some golfing oppurtunities with *flags* which I missed, but I'm done for now: ``` # "function" for 'e' rEeEEeeEeE rrEE re # remove duplicated argument reeeEeeeee # print space rEEEEe # decrement counter twice REe re # "function" for 'o' rEeEEeEEEE rrEE re # remove duplicated argument rEEEEE # increment counter REe re # "function for 'r' rEeEEEeeEe rrEE re Re # remove duplicated argument & char RE REEEe REEEEE # push 1 re rE rEEEe rEEEEE # replace 1 reE # goto 1 REe re # Main REEe REEEEeEee # read input & reverse REEEe REeeE REEEe REEEEEEE # push length-1 & move to r rEEEeE rEEEe # dummy loop-var (fucking do-whiles...) RE REEEe REEEEE REE # while [label-1] # Call the right procedure depending on current character, # sets stacks up as follows: # R [ .... *currentChar ] # r [ (N-1) *count ] Re re # pop 1 & loop-counter rEEEeE # duplicate counter REEEEEEe rEEEe # copy current char to other stack ReE # jeq to 'o'-label or 'e'-label # Output currentChar count times: RE REEEe REE # while [label-0]: Re # pop 0 rReEe # print character RE REEEe # push 0 rEEEEe # decrement counter Ree REEEe REeeE REEEe REEEEEEE # push length-1 & move to r re Re Re # pop 0, counter and 9((((currentChar RE REEEe REEEEE # push 1 reeeeeEeEe # print new-line Ree ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16 14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 Thanks to Erik the Outgolfer ``` OḂƇẒṁ€aØ.¦€⁶Y ``` Uses `1` for the cream and `0` for the cookie. **[Try it online!](https://tio.run/##y0rNyan8/9//4Y6mY@0Pd016uLPxUdOaxMMz9A4tAzIeNW6L/P//v3p@UWo@EENgfr46AA "Jelly – Try It Online")** ### How? ``` OḂƇẒṁ€aØ.¦€⁶Y - Main Link: list of characters, V e.g. 'orereo' O - ordinal (vectorises) [111,114,101,114,101,111] Ƈ - filter keep those for which: Ḃ - modulo 2 [111, 101, 101,111] Ẓ - is prime? (vectorises) [ 0, 1, 1, 0] ṁ€ - mould each like V [[0,0,0,0,0,0],[1,1,1,1,1,1],[1,1,1,1,1,1],[0,0,0,0,0,0]] € - for each: ¦ - sparse application... Ø. - ...to indices: literal [0,1] (0 is the rightmost index, 1 is the leftmost) a - ...apply: logical AND with: ⁶ - space character [[0,0,0,0,0,0],[' ',1,1,1,1,' '],[' ',1,1,1,1,' '],[0,0,0,0,0,0]] Y - join with newline characters [0,0,0,0,0,0,'\n',' ',1,1,1,1,' ','\n',' ',1,1,1,1,' ','\n',0,0,0,0,0,0] - implicit print ...smashes everything together: - 000000 - 1111 - 1111 - 000000 ``` --- Previous 16 byter: ``` ḟ”eẋ€Ly@Ø.¦€⁾r Y ``` Uses `r` for the c`r`eam and `o` for the c`o`okie. [Try it online!](https://tio.run/##y0rNyan8///hjvmPGuamPtzV/ahpjU@lw@EZeoeWAZmPGvcVKUT@//9fPb8oNR@IITA/Xx0A "Jelly – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~19~~ ~~18~~ 17 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` e ∙╋ :r≠*┤];L×⁸↔⁸ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=ZSUyMCV1MjIxOSV1MjU0QiUwQSV1RkYxQXIldTIyNjAldUZGMEEldTI1MjQldUZGM0QldUZGMUIldUZGMkMlRDcldTIwNzgldTIxOTQldTIwNzg_,i=b3Jlb29yZXJlcmVyZW9v,v=8) Uses the annoyingly long code of `:r≠*┤]` to remove `r`s from the input.. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/58974), ~~16~~ 15 bytes ``` re ¬£çX sX²èrÃû ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=cmUgrKPnWCBzWLLocsP7&input=Im9yZW9vcmVyZXJlcmVvbyIKLVI=) ``` :Implicit input of string U re :Remove all "e"s ¬ :Split to array of characters £ :Map each X çX : Repeat X to the length of U s : Slice from index X² : Duplicate X èr : Count the occurrences of "r" à :End map û :Centre pad each element with spaces to the length of the longest :Implicitly join with newlines and output ``` --- ## Alternatives ``` re ¬ËpUÊaD²èrÃû re ¬£îX rr²i^Ãû ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 'eKεD'rQ2*Igα×}.c ``` -1 byte thanks to *@Emigna* Uses `o` for the cookie and `r` for the filling. [Try it online](https://tio.run/##yy9OTMpM/f9fPdX73FYX9aLAQ9s9089tPDy9Vi/5///8otR8IIbA/HwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF95eEKojpJ/aQmEr/NfPdX73FYX9aLAQ9sj0s9tPDy9Vi/5v86hbfb/84tS87nyuYpSgQhI5IPIfBCVD2aCufkA). **Explanation:** ``` 'eK '# Remove all "e" from the (implicit) input # i.e. "orereo" → "orro" ε } # Map all characters to: D # Duplicate the current character 'rQ '# Check if it's an "r" (1 if truthy; 0 if falsey) # i.e. "r" → 1 # i.e. "o" → 0 · # Double that # i.e. 1 → 2 # i.e. 0 → 0 Ig # Take the length of the input # i.e. "orereo" → 6 α # Take the absolute difference between the two # i.e. 2 and 6 → 4 # i.e. 0 and 6 → 6 × # Repeat the duplicated character that many times # i.e. "r" and 4 → "rrrr" # i.e. "o" and 6 → "oooooo" .c # Then centralize it, which also imlicitly joins by newlines # (and the result is output implicitly) # i.e. ["oooooo","rrrr","rrrr","oooooo"] # → "oooooo\n rrrr\n rrrr\noooooo" ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 95 bytes ``` n=>n.Replace("o",new String('-',n.Length)+"\n").Replace("re"," ".PadRight(n.Length-1,'|')+"\n") ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrgOh7BJt/@fZ2uXpBaUW5CQmp2oo5Svp5KWWKwSDpTXUddV18vR8UvPSSzI0tZVi8pQ0EUqLUpV0lBSU9AISU4Iy0zNKNGAqdQ111GvUoer/W4cXZZakaiSCNWhqWv8HAA "C# (Visual C# Interactive Compiler) – Try It Online") # Alternative using Aggregate, 108 bytes ``` n=>n.Aggregate("",(d,c)=>d+(c<102?"":c<112?new String('-',n.Length)+"\n":" ".PadRight(n.Length-1,'|')+"\n")) ``` [Try it online!](https://tio.run/##NY2xDsIgGIRfpfkXIAUiHdtC4@LkYHRwcSFAKMtvQjEuvjsSG6e7y3eXc5twW6qnF7p5Kzlh5LsYqytqg/IYYw7RlkABOPXcMW18T92sDsMCMDajhgXDu7v9hpQIwlGeA8aysh4eCCN0IC/WX1NcC/0zoTj5kL3BWJ3uObUTS@HZ4lS/ "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [R](https://www.r-project.org/), 106 bytes ``` function(s,N=nchar(s)){m=rep(el(strsplit(gsub('re',0,s),'')),e=N) m[m<1&seq(m)%%N<2]=' ' write(m,1,N,,"")} ``` [Try it online!](https://tio.run/##jc5BCsIwEAXQfU4hgTozMIJ1ba6QC6iLWqZaaJo6SXEhnj2StZv@v33wv5bBlWGd@zzGGRN7N/fPTjERfYJTWVAmTFnTMo0ZH2m9I6gAHzkRAxCxOE8mXMK53Sd5YaCm8efTzcEOzFvHLBi4Zc9sLX3LgDaqREum7zLC4T/XGchUtsGobEKbWL0Vq62Ndb38AA "R – Try It Online") * -12 bytes thanks to @Giuseppe --- Previous version with explanation : # [R](https://www.r-project.org/), 118 bytes ``` function(s,N=nchar(s)){m=t(replicate(N,el(strsplit(gsub('re',0,s),'')))) m[m<1&row(m)%in%c(1,N)]=' ' write(m,1,N,,'')} ``` [Try it online!](https://tio.run/##jc7BCsIwDAbge59CBjMJRHB3@wp7AfUwS6eFtZW0Ywfx2Wt79rI/t5@PJFJmXeY1mOxiwMSjDuY1CSaij9cZxb4XZ6ZscWS7YMqSapHxmdYHgljgMydiAKpR/uovw1Hihp56F3qDA49013AAtYmrWzzXhpv/lhm7KDZ2pOoBhNN/bgFINbbDiN2FdrH2Vmy2TWzXyw8 "R – Try It Online") * -1 byte thanks to @Giuseppe Unrolled code and explanation : ``` function(s){ # s is the input string, e.g. 'oreo' N = nchar(s) # store the length of s into N, e.g. 4 s1 = gsub('re',0,s) # replace 're' with '0' and store in s1, e.g. 'o0o' v = el(strsplit(s1,'')) # split s1 into a vector v of single characters # e.g. 'o','0','o' m = replicate(N,v) # evaluate N times the vector v and arrange # the result into a matrix m (nchar(s1) x N) # e.g. # 'o' 'o' 'o' 'o' # '0' '0' '0' '0' # 'o' 'o' 'o' 'o' m = t(m) # transpose the matrix m[m<1 & row(m)%in%c(1,N)] = ' ' # substitute the zeros (i.e. where < 1) # on the 1st and last row of the matrix with ' ' (space) # e.g. # 'o' ' ' 'o' # 'o' '0' 'o' # 'o' '0' 'o' # 'o' ' ' 'o' write(m,1,N,,'') # write the matrix to stdout (write function transposes it) # e.g. # oooo # 00 # oooo } ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~21~~ 19 bytes ``` L$`. $.=*$& r+¶ee ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9HJUGPS0XPVktFjatI@9C21FQuhf//84tS87m4gKgoFYRBJEgoH8QEwfx8AA "Retina – Try It Online") Link includes test cases. Explanation: ``` L$`. $.=*$& ``` List each letter on its own line repeated to the length of the original input. ``` r+¶ee ``` Remove the lines of `r`s and replace the first two `ee`s on the next line with a space. Edit: Saved 2 bytes thanks to @DomHastings. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 47 bytes ``` s|o|X x($i=y///c).$/|ge;s|re|$".O x($i-2).$/|ge ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4Jr8mQqFCQyXTtlJfXz9ZU09FvyY91bq4pii1RkVJzx8sp2sEFf//P78oNR@IITA//19@QUlmfl7xf90CAA "Perl 5 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~74~~ 73 bytes I feel like I haven't posted an answer in a very long time. Well, here I am. Also, Retina has changed a lot, and I feel like I suck at it now. ``` .+ $0$.0 (\d+) * e o|r $&¶ _$ +(/_/&`o¶ oo¶ _$ )/_/&`r¶ rr¶ ¶$ m`^r ``` [**Try it online!**](https://tio.run/##K0otycxLNPz/X0@bS8VARc@ASyMmRVuTS4srlYsrv6aIS0Xt0DaueBUuLm0N/Xh9tYR8IDc/HyqmCRYqAvKKQMShbUCx3IS4Ii6F///zi1LzgRgC8/MB "Retina – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~135~~ ~~113~~ ~~109~~ 104 bytes * Saved ~~twenty-two~~ twenty-seven bytes thanks to [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob). * Saved four bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` #define $ putchar(33 O(char*r){for(char*e,*o=r,x;*r;$-23))for(x=*r++>111,e=x?$-1),r++,o+2:o;*e++;$+x));} ``` [Try it online!](https://tio.run/##Rc1BCoMwEAXQdT2FpFlkkihEd021R/AIImlsXdQp0xYC4tmtQVqZzePPMN9lN@eW5Xj1/TD6lKfPz9vdOxJlmTQiShJMPdJmryVWpIOVZHlWlABxFSpJStXGGO2rcOGZAb0GGlVxQiu9UparAGDnf1Fr16KXYOe8zWsGNnl0wyhgSg6NYEgeGbSbfyC/a3c8xRjEQYyf5uUL "C (gcc) – Try It Online") [Answer] # JavaScript, ~~72~~ ~~65~~ 64 bytes ``` s=>s.replace(/.e?/g,([x,y])=>(y?` `:` `).padEnd(s.length+!y,x)) ``` [Try it online](https://tio.run/##lc6xCoMwFIXhWZ/CZkpojHtBnXyKWkjQq20JuSGRYp4@xRRKoYue@fvhPNVL@cE97FIaHCFOdfR144UDq9UAtBLQVjOn15WHG6sbGlqZF/Iic8mEVWNnRuqFBjMv9/Mp8JWxOKDxqEFonGk2UYIOkLAs46Q3vSm/Iyz/pUWyG9wlHRygH7zrwIbxgMZUpGrL/qv4Bg) [Answer] # JavaScript ES6, 103 bytes ### Using replace 103 bytes: ``` x=>x.replace(/o/g,"-".repeat(s=x.length)+` `).replace(/re/g," "+"|".repeat(s>1?s-2:0)+` `).slice(0,-1) ``` [Try it online!](https://tio.run/##dcyxCsMgEIDhPU8RnJREk3QsJH2ViL3YFPGCSnHou1ulQ6BYXI7/vvMpX9Irtx@BW7xD2uYU5yUKB4eRCuiAg@4JJyWADNTPURiwOjxYtzYrO6GDIlvSkfepl@nm@eU6ZtwW7c2e7djziSWF1qMBYVDTjRJ0gISx5jdXmoNqxD@9vNrP@QK/2zJlkT4 "JavaScript (Node.js) – Try It Online") ### Using split and map 116 bytes: ``` x=>x.split("re").map(y=>("-"[h='repeat'](r=x.length)+` `)[h](y.length)).join(" "+"|"[h](r>1?r-2:0)+` `).slice(0,-1) ``` [Try it online!](https://tio.run/##dY5BCoMwEEX3PYXMxgk2QbssxB5EBIONGkkzIUpR6N1tpHRTLLMZ3n8z/FE91dQG42fu6K63Tm6LLBcxeWtmhKCBiYfyuMoSgUM1yDRor9Wc1hjkIqx2/TywrDk1rBpqXL@EiZGMQ0gggxfsUSiLW@CXax7tJOpisqbVmJ95wbaW3ERWC0s9dggUNAFjp198wPaKB5D@8H2OPscL@qT7Fo3tDQ "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` lambda x:x.replace("o","-"*len(x)+"\n").replace("re"," "+'.'*(len(x)-2)+"\n") ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCqkKvKLUgJzE5VUMpX0lHSVdJKyc1T6NCU1spJk9JEyFZlAqUVVDSVtdT19KAKNE1gqr6nwbUXJSaD2QBAA "Python 3 – Try It Online") [Answer] # Mathematica, ~~111~~ 91 bytes ``` #~StringReplace~{"o"->"O"~Table~(n=StringLength@#)<>"\n","re"->" "<>Table["R",n-2]<>" \n"}& ``` [Try It Online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/V@5LrgEyEoPSi3ISUxOratWylfStVPyV6oLSUzKSa3TyLOFKPBJzUsvyXBQ1rSxU4rJU9JRKkoFKVRQsrEDq4xWClLSydM1igXKKwAV1Kr9V3BQUMovSgXBfCCdrxT7HwA) This was majorly shortened thanks to [Misha](https://codegolf.stackexchange.com/users/74672/misha-lavrov)'s [edits](https://codegolf.stackexchange.com/questions/178344/oreoorererereoo/178418#comment430012_178418). --- My original code: ``` (z=StringRepeat;n=StringLength@#;#~StringReplace~{"o"->"O"~z~n<>"\n","re"->" "<>If[n>2,z["R",n-2],""]<>" \n"})& ``` This code is not very fancy but it seems too expensive to convert away from strings and then back or to do anything else clever. In particular, with only 3-4 commands that have the name String, my original approach couldn't save bytes at all by trying to abstract that away. For example, the following is 129 bytes: ``` (w=Symbol["String"<>#]&;z=w@"Repeat";n=w["Length"]@#;#~w@"Replace"~{"o"->"O"~z~n<>"\n","re"->" "<>If[n>2,z["R",n-2],""]<>" \n"})& ``` [Answer] # Bash, 87 bytes Without `sed`: ``` f(){ printf %$1s|tr \ $2;} c=${1//o/`f ${#1} B` } echo "${c//re/ `f $[${#1}-2] F` }" ``` Thanks to @manatwork. With `sed` (90 bytes): ``` f(){ printf %$1s|tr \ $2;} echo $1|sed "s/o/`f ${#1} B`\n/g;s/re/ `f $[${#1}-2] F` \n/g" ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 37 bytes ``` {m:g/o|r/>>.&({S/rr/ /.say}o*x.comb)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzrXKl0/v6ZI385OT02jOli/qEhfQV@vOLGyNl@rQi85PzdJs/a/TX5Rar5CvkJRKhABCRA3H8QCwfx8O5DmtP8A "Perl 6 – Try It Online") Anonymous code block that takes a string and prints the oreo, with `o` as the cookie and `r` as the cream. ### Explanation: ``` { } # Anonymous code block m:g/o|r/ # Select all o s and r s >>.&( ) # Map each letter to *x.comb # The letter padded to the width S/rr/ / # Substitute a leading rr with a space .say # And print with a newline ``` [Answer] # [PHP](https://php.net/), ~~100~~ ~~99~~ 93 bytes ``` $l=strlen($i=$argv[1]);$r=str_repeat;echo strtr($i,[o=>$r(X,$l)." ",re=>' '.$r(o,$l-2)." "]); ``` [Try it online!](https://tio.run/##JYzBCsIwEETvfkUoC00gFvUaU39DKCJFlqYQumEM/n7cKsMc5vGYkkq73koqhgHBE1wEdd0We3KhUY7visybpTXSjOUznR8uEHa8uzzXwK8kRneFWn6SOBLs3VN2Q3foPDiOvekHhaLwePlhfWmtCVi0/4h8AQ "PHP – Try It Online") OUCH. PHP's waaaay\_too\_long function names strike again! Output: ``` $php oreo.php oreo XXXX oo XXXX $php oreo.php o X $php oreo.php rere oo oo $ php oreo.php oreoorererereoo XXXXXXXXXXXXXXX ooooooooooooo XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX ooooooooooooo ooooooooooooo ooooooooooooo ooooooooooooo XXXXXXXXXXXXXXX XXXXXXXXXXXXXXX ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` FNzIqN"o"*lzN)IqN"r"+d*-lz2N FNz For each value, N, in input IqN"o" if the character is "o" *lzN return the character times the length of the input ) end if IqN"r" if the character is "r" FNzIqN"o"*lzN)IqN"r"+d*-lz2N *-lz2N return the character times length - 2 +d padded on the left with " " ``` [Try it here!](https://tio.run/##K6gsyfj/382vyrPQTylfSSunyk8TxCxS0k7R0s2pMvL7/z@/KDUfiCEwPx8A) This one uses a loop. # Pyth, 30 bytes (As string replace) ``` ::z"o"+*lz"="b"re"++d*-lz2"~"b :z"o" With the input, replace "o" with *lz"=" "=" times the length of the input + b and a newline added to the end : "re" With the input, replace "re" with * "~" "~" times -lz2 the length of the input minus 2 +d padded on the left with " " + b and a newline added to the end ``` [Try it here!](https://tio.run/##K6gsyfj/38qqSilfSVsrp0rJVilJqShVSVs7RUs3p8pIqU4p6f///KLUfCCGwPx8AA) This one uses string replacement. I really like python (it's what I wrote my original test scripts in), so I thought I'd do a pyth entry for fun :) [Answer] # [PHP](https://php.net/), 96 87 85 bytes Thanks to @gwaugh -9 Bytes Thanks to @manatwork -2 Bytes ``` <?=strtr($i=$argv[1],[o=>($r=str_repeat)(X,$l=strlen($i))." ",re=>" {$r(o,$l-2)} "]); ``` [Try it online!](https://tio.run/##JcvBCoMwEATQu18hIYddSEvbq038DUGkeFhUEDdMQy/Fb08TCnOaNxPXmJ99XGMrgOIFiYq0HQvduOtDMf9OSCC7eTtj@Yz3yY3qA1lUqQeZE9Pg7F6LXY6yZb6axjiID6b9WpAWvjz4bMzEXc5ZIf9Afg "PHP – Try It Online") [Try it online! (87 Bytes)](https://tio.run/##HcvBCoMwEIThe58iyIJZiNL2ahNfoyBSPCwqiBumoa@fJl7/byZuMb/GuEUjgOIDiYq0n6u982DGUNB/ExIs7Z4WrL/pMbtJfbCEKvUhS2L7dnTUcMhZtsx9c2scxIfWtD3BavHueeWZh5yzQvQP "PHP – Try It Online") [Try it online (original 97 bytes submition)!](https://tio.run/##K8go@M/538betrikqKRIQ6XcViWxKL0s2jBWJzrf1k5DJQ0kE1@UWpCaWKKp8Whah45KDkgoJzUPqFpTU0@JS0mnyNZOSUFJTyUNqGAiUIGuEUQ8FSiuFKtp/f////yi1HwghsD8fAA "PHP – Try It Online") --- **And a recursive function** # [PHP](https://php.net/), 135 bytes ``` function f($w,$x=0){$f=str_repeat;echo($x<($l=strlen($w)))?($w[$x]=='o')?$f(█,$l)." ".f($w,$x+1):" ".$f(░,$l-2)." ".f($w,$x+2):"";} ``` [Try it online! (recursive)](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUynVUKmwNNKtV0myLS4rii1ILUhNLrFOTM/I1VCpsNFRyQMI5qXlAlZqamvZAKlqlItbWVj1fXdNeJU3j0bQOHZUcTT0lLiU9qHHahppWSgpKemDZiUBZXSNUeSOgvJJ17f80DaX8otR8JU3r//8B "PHP – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62~~ 60 bytes ``` ->s{s.gsub /./,?r=>" #{(?**z=s.size)[0..-3]} ",?o=>?O*z+?\n} ``` [Try it online!](https://tio.run/##JYlBDsIgFET3noLgRhF@G10a@EfwAMjCGqpuioGyEMrZMbSZ5M2bjI/Dr46yChVygFeIA@mg4@ilomSfD8hYkgHCJ9mj7gHExZQd5eikwhtLJ7xPpWrqvHWUE7rC241bt8u10eIcNWAfz3de5uUb50BGPZsrWRUFO/el/gE "Ruby – Try It Online") Uses `O` for the cookie, `*` for the filling. -1 thanks to @manatwork pointing out a silly mistake and another -1 due to relaxation of the rules about whitespaces. [Answer] # Powershell, ~~71~~ ~~69~~ 66 bytes *-2 bytes thanks @Veskah* *-3 bytes thanks @AdmBorkBork* ``` $l=$args|% le* switch($args|% t*y){'o'{'#'*$l}'r'{" "+'%'*($l-2)}} ``` Less golfed test script: ``` $f = { $l=$args|% length switch($args|% t*y){ 'o'{'#'*$l} 'r'{" "+'%'*($l-2)} } } @( ,( 'oreo', '####', ' %%', '####' ) ,( 'o', '#' ) ,( 're', ' ' ) ,( 'rere', ' %%', ' %%' ) ,( 'oreoorererereoo', '###############', ' %%%%%%%%%%%%%', '###############', '###############', ' %%%%%%%%%%%%%', ' %%%%%%%%%%%%%', ' %%%%%%%%%%%%%', ' %%%%%%%%%%%%%', '###############', '###############' ) ) | % { $s,$expected = $_ $result = &$f $s "$result"-eq"$expected" # $result # uncomment this line to display a result } ``` Output: ``` True True True True True ``` [Answer] # Java 11, ~~110~~ 106 bytes ``` s->{int l=s.length();return s.replace("re"," "+"~".repeat(l-2+1/l)+"\n").replace("o","=".repeat(l)+"\n");} ``` -4 bytes thanks to *@ceilingcat*. Uses `=` for the cookie and `~` for the filling. [Try it online.](https://tio.run/##ZZDBTgMhEIbvfYoJJ8i6GL1u1jewlx7VA9KxUilsYLaJadZXX2cpsVovhPn@n5l/2Jujaffbj9l6kzM8GhdOKwAXCNObsQjrpQTYUHJhB1bWS1Yd82nFRyZDzsIaAvQw5/bhxK/B91l7DDt6l6pLSGMKkHXCwXNXKRKKGwGiEV9igWhI@va@ubv1qhHPQaiLNbKzv7iq3k1zt0wfxlfP02uIY3RbOPASNefTCxh13oAwEzdLGEXJ/kP@lhzsqr4mcUHxH4uFF62Kv3@nBCve@oEuDCPVaJvPTHjQcSQ9sEg@yKCtPFtqq2n@Bg) **Explanation:** ``` s->{ // Method with String as both parameter and return-type int l=s.length(); // Get the length of the input return s // Return the input .replace("re", // After we've replaced all "re" with: " " // A space +"~".repeat(l-2+1/l) // Appended with length-2 amount of "~" // (or length-1 if the input-length was 1) +"\n") // Appended with a newline .replace("o", // And we've also replaced all "o" with: "=".repeat(l) // Length amount of "=" +"\n");} // Appended with a newline ``` --- The above solution uses a replace. The following maps over the characters of the input instead: # Java 11, ~~113~~ 112 bytes ``` s->s.chars().forEach(c->{if(c>101)System.out.println((c>111?" ":"")+(""+(char)c).repeat(s.length()-2*(~c&1)));}) ``` -1 byte thanks to *@Neil*. [Try it online.](https://tio.run/##bZAxT8MwEIX3/oqTB3RHFYswEjVMjHTpiBiM6zQuqR3Zl0qoCn89JE6EoLBYeu9ZT9@9ozqr7Lh/H3SjYoRnZd1lBWAdm1ApbWA7SYCzt3vQuONg3QEiFaPbr8YnsmKrYQsONjDErIxS1ypEJFn58KR0jTorL7ZCXeZ3Oe0@IpuT9B3LduzixuGU5PmjAPEgBK1RiDVOHaRJBtMaxRhlY9yBa6Ts/hY/9U1OREVPQzExtN1bMzIsKAn1NB6y0L68gqL5CjaRUfhgvEgXfDu/ZTDX@trxk@X/eD75KVvCnxslsPR3mdG6tuMFzUmNs547/9lpKeyHLw) **Explanation:** ``` s-> // Method with String parameter and no return-type s.chars().forEach(c->{ // Loop over the characters as codepoint-integers if(c>101) // If it's not an 'e': System.out.println( // Print with trailing newline: (c>111? // If it's an 'r' " " // Start with a space : // Else (it's an 'o' instead) "") // Start with an empty string +(""+(char)c).repeat( // And append the character itself .repeat( // Repeated the following amount of times: s.length() // The input-length -2*(~c&1)));}) // Minus 2 if it's an "r", or 0 if it's an "o" ``` [Answer] # [Brainfuck](https://en.wikipedia.org/wiki/Brainfuck), ~~276~~ ~~268~~ 206 bytes Technically as the brainfuck only has 8 instructions, that means it needs only 3 bits per character instead of 8 (that also means we could encode brainfuck in base64 with exactly 2 instructions per character), but I'll play fair and say it's 268 bytes long. It was a fun challenge, thanks! **Edit**: now featuring the 3rd rule! **Edit**: moving the line feed from the data pool to the display part of the code allowed me to get down to 268 bytes: ``` >>+<,[<++++++++++[>-----------<-]>-[>-<,>>+<<[-]>>>>[>]>++++[<++++++++>-]+>>++++++++++[<+++++++++++>-]<+>>++++[<++++++++>-]<[<]<<<]>[[-]>>>[>]>+++++++[<+++++>-]+>>+++++++[<+++++>-]>+++++++[<+++++>-]<[<]<<]+<,>>+<<]>>--[>>>+<<<-]>>[.>-[>>>>+<<<<->.<]>>.[-]++++++++++.>] ``` Here's a more readable version: The data pool is made like so: [first character, placeholder value used to move the input character count, repeated character, last character] ``` >>+<,[//start of the loop <++++++++++[>-----------<-]>-//"o" [>-<,>>+<<[-]//if it's not a "o", skip one character and: >>>>[>]//go to the data pool and search for the end >++++[<++++++++>-]//put " " in memory +>//put 1 in memory >++++++++++[<+++++++++++>-]<+>//put a "o" in memory >++++[<++++++++>-]<//put another " " in memory [<]<<<//get back to the beginning of the data pool and get back to the program ]>[[-]//else (so if it's a "o"): >>>[>]//go to the data pool and search for the end >+++++++[<+++++>-]//put a "#" in memory +>//put 1 in memory >+++++++[<+++++>-]//put a "#" in memory >+++++++[<+++++>-]<//put a "#" in memory [<]<<//get back to the beginning of the data pool and get back to the program ]+<,>>+<<]//loop until the end of the input line and count the number of characters >>//go to the number of characters variable --//substract 2 to it because the first and last characters take one space each [>>>+<<<-]//copy the value to the next place >>[.>//start of the loop and display of the first character -[>>>>+<<<<->.<]//display of the repeated character while copying the character count to the next line >>.//display of the last character [-]++++++++++.//display a line feed >]//loop until the end of the data pool ``` It works on copy.sh/brainfuck with default settings ([link](https://copy.sh/brainfuck/?c=Pj4rPCxbPCsrKysrKysrKytbPi0tLS0tLS0tLS0tPC1dPi1bPi08LD4-Kzw8Wy1dPj4-Pls-XT4rKysrWzwrKysrKysrKz4tXSs-PisrKysrKysrKytbPCsrKysrKysrKysrPi1dPCs-PisrKytbPCsrKysrKysrPi1dPFs8XTw8PF0-W1stXT4-Pls-XT4rKysrKysrWzwrKysrKz4tXSs-PisrKysrKytbPCsrKysrPi1dPisrKysrKytbPCsrKysrPi1dPFs8XTw8XSs8LD4-Kzw8XT4-LS1bPj4-Kzw8PC1dPj5bLj4tWz4-Pj4rPDw8PC0-LjxdPj4uWy1dKysrKysrKysrKy4-XQ$$)) **Edit**: now down to only 206 Bytes thanks to @RezNesX ``` >>+<,[<-[>++<-------]>-[,[-]>->+>>[>]>+>+>-[<-->-------]>++++[<<<<++++++++>>>++++++++>-]<[<]<<<]>[[-]>>>[>]->+>->->--[<<<<-->>-->-->+++++++]<[<]<<]+>+<<,]>>--[>>>+<<<-]>>[.>-[>>>>+<<<.<-]>>.[-]++++++++++.>] ``` The code is quite similar but a lot of optimisation has been done in the creation of the data pool, very interesting. [Answer] # [Zsh](https://www.zsh.org/), 67 bytes ``` a=$#1 o()<<<${(l/a//=/)} r()<<<\ ${(l/a>1?a-2:0//+/)} eval ${1///;} ``` [Try it online!](https://tio.run/##qyrO@P8/0VZF2ZArX0PTxsZGpVojRz9RX99WX7OWqwgsFKMAEbQztE/UNbIy0NfXBkmmliXmAGUM9fX1rWv///@fX5Sanw8A "Zsh – Try It Online") Explanation: * `$1`: input * `#`: length * `a=`: assign to global variable `$a` * `o()`: define a function called `o`: + `${(l/a//=/)}`: left pad {nothing} with `=` signs to the width `$a` (i.e., print this many equals signs) + `<<<`: print * `r()`: define a function called `r`: + `${(l///+/)}` left pad {nothing} with `+` signs, + `a>1?a-2:0`: to the width of `$a - 2` if `$a > 1` else `0` (because otherwise, if `$a - 2` was negative, zsh would use its absolute value) + `<<<\` : print with a space before * `${1}`: input * `///;`: replace all {empty string}s with `;` (effectively intersperses; `oreo` -> `;o;r;e;o`) * `eval`: evaluate that as zsh code + `o` and `r` call the functions defined above + `e` is a non-existent command, so does nothing + `;` separates the commands [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes ``` Fθ≡ιo⟦⭆θ#⟧e«→P⁻Lθ²↙ ``` [Try it online!](https://tio.run/##LY2xCsMgFEXn@BUPuyikS8d07RihtGPpIGJUCL5ETTKEfLu1tjwud7jn8JSVQaEccx4wAJs5xM0lZYE5DjtRMmqgSDu4B@cTez1TaSPkxOYW6InyN7/@KV2onTQCV826hzM2lakRy5jcVGXh/BJZr71Jtnxq4cIrUYUbbr7Xw9c5yJEzBo0lv0PM53X8AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Fθ ``` Loop through the characters of the input string. ``` ≡ι ``` Switch on each character. ``` o⟦⭆θ#⟧ ``` If it's an `o` then print the input string replaced with `#`s on its own line. ``` e«→P⁻Lθ²↙ ``` If it's an `e` then move right, print a line of `-`s that's two less than the length of the input string, then move down and left. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 71 bytes ``` s=>s.Aggregate("",(a,c)=>a+(c>111?" ":"\n".PadLeft(s.Length+c/5-21,c))) ``` [Try it online!](https://tio.run/##bcqxDgIhEATQ3q8gWy25OwwmNioYGysKOxsbsi4cDSaA34@ndsZmJnkzVCeqqZ@fmQ61lZTj@C0rgjC9GlvVKcbC0TdGgBH9SNJYPyBZrfURBOzglkFd/N1xaFiV4xzbPNB6O2308pay71fXkhq7lBkDwgOk/KXC/3XxT7zH/gI "C# (Visual C# Interactive Compiler) – Try It Online") Borrowed some ideas from on [Embodiment of Ignorance's answer](https://codegolf.stackexchange.com/a/178349/8340) for sure. -6 bytes thanks to @ASCIIOnly! The overall concept is to compute a string aggregate over the input characters following these rules: * If an `r` is encountered, append a single space character for indentation. We know the next character will be an `e`. * If an `o` or an `e` is encountered, generate a string by repeating the current character a specific number of times and prepending it to a newline or some padding and a newline. * The number of times to repeat is determined by length of input string and whether the current line is indented. * The `PadLeft` function is used to generate the repeating character string. The result is the concatenation of all of these strings. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 143 bytes Without LINQ. ``` p=>{var q="";foreach(char c in p){if(c!='e'){for(var j=0;j<p.Length;j++)q+=(j<1|j>p.Length-2)&c>'q'?" ":c<'p'?"█":"░";q+="\n";}}return q;}; ``` [Try it online!](https://tio.run/##NU89T8MwEN3zKw4PxFZoBIx1HAYkJpCQGFhYnMNNHKW2YzuVUMjOysIP5I8EVy26073Te/eJYYPWq3UK2rTw8hGi2vMMBxkCPHvbermfMwA3NYNGCFHGBAer3@FJakPZUQR4mAxWIfo04@oENTQgVifq@SA9jIIQvkt7JHYUu8QgaAOOzXpH8ULkKmdz0umxuBfXvK9c@ahMGzveFwUbC0H76uazr//pzS27xDof8zsCZItV7lL2@/NFtil@E546yJshfFm8ipM3MPKFr6f/yntrgh1U@ep1VLShJF12dsIYz5Zk6x8 "C# (.NET Core) – Try It Online") [Answer] # [Clojure](https://clojure.org/), 137 bytes ``` (fn[f](let[w(count f)r #(apply str(repeat % %2))](clojure.string/join"\n"(replace{\o(r w \#)\e(str \ (r(- w 2)\-) \ )}(remove #{\r}f))))) ``` I'm not using the nice characters in the printout in the golfed version since those are expensive. Returns a string to be printed. [Try it online!](https://tio.run/##JYxRC4MwDIT/SqgIyYMb@HesD6WkQ@maktXJEH97V/GOPNzl43yUdVOumHVJJSbAiiFNYcbIZdrRy5YKBFLo0OUcf/ApisqZXYEe@pFoRn@PPNprSa/nKksyNpkLi87zYQUVdrAdWcYGgQVUHFo1kh2oRTob/JYvQ3dYPQNdqkaUpd1tEUME9Q8 "Clojure – Try It Online") See below for explanation. Pre-golfed: ``` ; Backslashes indicate a character literal (defn oreo [format-str] (let [width (count format-str) ; A helper function since Clojure doesn't have built-in string multiplication str-repeat #(apply str (repeat % %2)) ; Define the layers cookie (str-repeat width \█) cream (str \ (str-repeat (- width 2) \░) \ )] (->> format-str ; Take the input string, (remove #{\r}) ; remove r for simplcity, (replace {\o cookie, \e cream}) ; replace the remaining letters with the layers, (clojure.string/join "\n")))) ; and join the layers together with newlines ``` [Answer] # [Dart](https://www.dartlang.org/), ~~120~~ ~~106~~ 107 bytes ``` f(s)=>s.replaceAll('o',''.padRight(s.length,'#')+'\n').replaceAll('re',' '.padRight(s.length-1,'-')+' \n'); ``` [Try it online!](https://tio.run/##bY1BCsMgEEX3PYXQxTjUCF2HFnqFrLuRZJIIVkXdlZ7dOmSVpszuzX//TyaVWmeZ8XbPOlF0ZqSHcxICKAAdzTTYZS0ya0d@KauCM@AFnh5wF0/U8uKP0F0VdKwIdvr6MtZLfJ@EiMn6Iuc2lSgAYr9jv6ANHMiRcVXgB1/YSj71Cw "Dart – Try It Online") * +1 byte : Added trailing whitespace ]
[Question] [ You are Desmond Hume. For the last 3 years, you and your partner, Kelvin, have been slave to a computer that requires a very specific sequence to be entered into it every 108 minutes to save the world. ``` 4 8 15 16 23 42 ``` Your partner died 40 days ago (due to an unfortunate accident involving Kelvin's head and a big rock), and you have no one to talk to. No one to enter the numbers for you. No one to break the monotony. At first it wasn't too bad, but you can't handle the silence anymore. And if you have to listen to "Make Your Own Kind Of Music" one more time, you're going to scream. You decide that You need to get out. To escape. You decide that you will build a raft and sail off the island. But then you realize the bad news: you're stuck here. You need to keep saving the world. But then you realize the good news: You are a programmer! You can automate saving the world! Excited, you run over to the computer, and, using your trusty python skills, you whip up a quick script to enter the numbers for you. ``` import time while True: print "4 8 15 16 23 42" time.sleep(60 * 107) ``` Quick, simple, reliable, short, and easy. Everything that a good python script should be. But then, when you try to test it, you get an error. ``` Bad command or file name. ``` Huh, strange. Oh well, let's try c++. ``` #include <iostream> #include <unistd.h> int main() { while (true) { std::cout << "4 8 15 16 23 42" << std::endl; sleep(60 * 107); } } ``` No! C++ isn't found either. You try every language you can think of. Javascript, Ruby, Perl, PHP, C#. Nothing. This computer was made before all of the popular languages of the day. ## The Challenge You must write a program that will: 1) Print exactly this: "4 8 15 16 23 42" (without quotes) 2) Wait some time between 104 and 108 minutes. (According to [The Lost Wiki](http://lostpedia.wikia.com/wiki/Pushing_the_button)) 3) Repeat forever. (Or until you realize that this is all an elaborate scam, and that you're stuck in a weird limbo due to lazy writing, and asking questions that you don't have answers for. Thanks JJ Abrams!) However there is a catch: You MUST use a language that the computer in the swan station would actually be capable of running. Assuming that A) The computer was up to date at the time of construction, B) There have been no updates to the computers software, and C) There is no internet connection available (Meaning you can't download Golfscript...), and making our best guess for the construction date of The Swan Station, (Again, [The Lost Wiki.](http://lostpedia.wikia.com/wiki/Swan#The_Incident)) This means you have to use a language that was first released on or before Dec 31, 1977. A few rule clarifications: * Including libraries is OK, but the same rule applies (libraries must be pre-1977). * You do not have to worry about OS compatibility. * If you use `system`, or your languages equivalent, you *must* prove that any system commands you use would have been available before 1978. A wikipedia article is probably the best way to prove this. * It doesn't matter when you start the program, just as long as it ends up in a pattern of alternating printing and sleeping. (print-sleep-print-sleep... and sleep-print-sleep-print... are both acceptable.) This is Code-Golf, so shortest answer in bytes wins. [Answer] # MUMPS - 30 characters, circa 1966 (ANSI standard first in 1977) My first attempt at code golf, here we go! ``` f w "4 8 15 16 23 42" h 6420 ``` MUMPS is still a popular language for EHR software, created by Massachusetts General Hospital in Boston. Most known implementation is Epic Systems in Verona, WI. [Answer] # Bourne shell, ~~47~~ 45 bytes ``` while echo 4 8 15 16 23 42;do sleep 6420;done ``` [Answer] # TECO, 53 bytes TECO (Text [previously Tape] Editor and Corrector) is a text editor originating in 1962. It can also be used to run standalone programs. It's the state-of-the-art editor for PDPs, VAXen, etc. According to the TECO manual, the `^H` command gives the time of day. Make sure to check your operating system and power supply, as the unit of time may vary according to your machine: ``` OS/8: ^H = 0 RT-11: ^H = (seconds since midnight)/2 RSTS/E: ^H = minutes until midnight RSX-11: ^H = (seconds since midnight)/2 VAX/VMS: ^H = (seconds since midnight)/2 TOPS-10: ^H = 60ths of a second since midnight (or 50ths of a second where 50 Hz power is used) ``` The following program works on systems where time of day is measured in seconds/2: ``` I4 8 15 16 23 42 $<HT^HUA<^H-QAUDQD"L43200%D'QD-3180;>> ``` Note that `^H` and `$` should be entered by striking, respectively, CONTROL-H and ESCAPE. The numbers in the program can be adjusted for the following machines: ``` (number) 43200 3180 RSTS/E 1440 106 TOPS-10 60 Hz 5184000 381600 TOPS-10 50 Hz 4320000 318000 OS/8 goodbye, world... ``` [Answer] # C, 54 52 bytes ``` main(){while(1)puts("4 8 15 16 23 42"),sleep(6360);} ``` [Answer] # [APL](https://dyalog.com), ~~28~~ ~~24~~ ~~25~~ 24 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) This worked in STSC's APL\*PLUS and in IPSA's SharpAPL in 1977, and while modern APLs have a ton of new features, this happens to still work on all major APLs today: ``` +\4 4 7 1 7 19 →×⎕DL 6360 ``` The first line prints the cumulative sum of the shown numbers, which are the required numbers. The second line **d**e**l**ays 6360 seconds (106 minutes), then takes the signum of that (1, obviously), and goes to that line (i.e. the previous, number-printing one). However, APL\360 (the APL for [IBM System/360](https://en.wikipedia.org/wiki/IBM_System/360)) from 1966 actually beats it by one byte (tested on the [free IBM/370 emulator](http://lemo.dk/apl/)): ``` +\4 4 7 1 7 19 5⌶19E5 →1 ``` The sleep [I-beam](https://en.wikipedia.org/wiki/I-beam) ("[IBM](https://en.wikipedia.org/wiki/IBM)" – get it?) takes the wait-time in [jiffies](https://en.wikipedia.org/wiki/Jiffy_(time)) of 1⁄300th of a second, so we wait 19×105 jiffies = 105 minutes and 331⁄3 second. [Answer] ## FORTRAN 66 (~~108~~ 98 Bytes) ``` PROGRAM D 2 WRITE (*,*) '4 8 15 16 23 42' CALL SLEEP(6420) GOTO 2 END ``` It is certain that the computer in question had the FORTRAN compiler, as it dominated scientific and engineering fields in the era. I was born 18 years after the eponymous year, but during my math program in university we learned FORTRAN. One fun lecture we learned how to program on punching cards. It's not that easy to format it correctly here, there should be 6 blankspaces before each command and I could only find a reference to the Sleep-function for Fortran 77 but it should have existed already in Fortran IV and 66. PS: We could scrap off one Byte by using label 1 instead of label 42. PPS: If the computer in question uses punching-cards for program input you're all out of luck and the bytes don't matter anymore :D . [Answer] ## MacLisp, ~~47~~ 46 bytes ``` (do()(())(print"4 8 15 16 23 42")(sleep 6360)) ``` All constructions taken from [1974 reference manual (PDF)](http://www.softwarepreservation.org/projects/LISP/MIT/Moon-MACLISP_Reference_Manual-Apr_08_1974.pdf). Not tested though as I don't have a MacLisp interpreter. [Answer] # Altair Basic For sure, Desmond and Kelvin would have had an Altair 8800 (or an emulator) just for fun. Altair Basic (from some guy named Bill Gates, of some little two-man start-up called Micro-Soft) squeaks in with a 1975 release. Desmond would need to fine tune a bit to ensure the inner `FOR` loop lasts one minute. Back then, everybody knew busy loops were wrong, but everybody used them! ``` 1 REM ADJUST "D" AS REQUIRED 2 LET D = 1000 3 PRINT "4 8 15 16 23 42" 4 FOR A = 0 TO 105 * 60 5 REM THIS LOOP SHOULD LAST ONE MINUTE +/- 0.05 SECONDS 6 FOR B = 0 TO D 7 LET C = ATN(0.25) 8 NEXT 9 NEXT 10 GOTO 3 ``` As an alternative, Desmond could install the 88-RTC board (assembled from components!: <http://www.classiccmp.org/altair32/pdf/88-virtc.pdf>) and get access through interrupts to a real time clock running off the power line or internal crystal. He would need to write an interrupt routine to handle the clock input, which in turn could update a port, say every 59 seconds bring to ground for a second, then raise high. Altair Basic had a `WAIT` function, so the code would be simplified to something like the following (I couldn't find a port listing, so I just chose 125 in the hopes it would be unused.): ``` 1 PRINT "4 8 15 16 23 42" 2 FOR A = 0 TO 105 * 60 3 WAIT 125,0 4 WAIT 125,255 5 NEXT 6 GOTO 1 ``` This was actually a fun little question, going back into some really rudimentary computers. The patience those old-timers (including me) must have had! [Answer] # PDP-11 assembler for Unix System 6 - ~~73~~ ~~68~~ 74 characters Talking about the 70s, it's mandatory to honor Unix and the hardware where it all started! ``` s:mov $1,r0 sys write;m;18 mov $6240.,r0 sys 43 br s m:<4 8 15 16 23 42;> ``` You can easily run it [here](http://pdp11.aiju.de/) (but first you have to rediscover the joys of using `ed` to insert the text - in my specific case, I even had to discover how to actually *edit* text in it `:)`). Assembled it becomes 108 bytes. ``` # cat mini.as s:mov $1,r0 sys write;m;18 mov $6240.,r0 sys 43 br s m:<4 8 15 16 23 42;> # as mini.as # ls -l a.out mini.as -rwxrwxrwx 1 root 108 Oct 10 12:36 a.out -rw-rw-rw- 1 root 74 Oct 10 12:36 mini.as # od -h a.out 0000000 0107 0022 0000 0000 0018 0000 0000 0000 0000020 15c0 0001 8904 0012 0010 15c0 0004 8923 0000040 01f7 2034 2038 3531 3120 2036 3332 3420 0000060 3b32 0000 0000 0000 0002 0000 0000 0000 0000100 0000 0000120 0000 0000 0073 0000 0000 0000 0002 0000 0000140 006d 0000 0000 0000 0002 0012 0000154 # ./a.out 4 8 15 16 23 42; ``` [Answer] ## LOGO, 61 bytes (possibly) or 48 bytes (probably not) Unfortunately, I haven't managed to find an online copy of *The LOGO System: Preliminary Manual* (1967) by BBN, or any references by the MIT Logo Group (1960s+). Apple Logo by LCSI is a bit too recent (~1980). However, based on online books, some variation of the following probably worked at the time. Note that WAIT 60 waits for 1 second, not 60. ``` TO a LABEL "l PRINT [4 8 15 16 23 42] WAIT 381600 GO "l END a ``` We can do a bit better with tail call optimization, though this was probably not available at the time. ``` TO a PRINT [4 8 15 16 23 42] WAIT 381600 a END a ``` [Answer] # CBM BASIC 1.0, ~~52~~ 38 characters, tokenized to ~~45~~ 31 bytes ``` 1?"4 8 15 16 23 42":fOa=1to185^3:nE:rU ``` CBM BASIC 1.0 was introduced with the Commodore PET in October 1977. Commands would normally be shown in uppercase and CBM graphics characters, but I've listed them here in lowercase + uppercase for the sake of ease (both mine and yours! :-)). Note also that the ^ would actually be displayed as ↑. Detokenized, after listing this with `LIST` this would result in: ``` 1 PRINT "4 8 15 16 23 42":FOR A=1 TO 185^3:NEXT:RUN ``` The PET's 6502 ran at 1MHz, so this should take around 105 minutes or so to complete. *Edit*: Realized that nested loops weren't really necessary and I'd miscomputed my tokens. Still not enough to win (and too late, to boot), but at least it's better. [Answer] # Pascal - ~~107~~ 95 bytes ``` PROGRAM S;USES CRT;BEGIN WHILE TRUE DO BEGIN WRITELN('4 8 15 16 23 42');DELAY(6300000);END;END. ``` Ungolfed version: ``` PROGRAM S; USES CRT; BEGIN WHILE TRUE DO BEGIN WRITELN('4 8 15 16 23 42'); DELAY(6300000); { 105 minutes * 60 seconds * 1000 milisseconds } END; END. ``` [Answer] # Thompson shell, 1971 (1973 for sleep command) 43 bytes ``` : x echo 4 8 15 16 23 42 sleep 6480 goto x ``` Since the Bourne shell, though it existed in 1977, wasn't in a released version of Unix until v7 in 1979. The original Unix shell didn't have any fancy loop control commands. (If you wanted to end a loop, you could use the `if` command to skip the goto.) [Answer] # [Forth](https://en.wikipedia.org/wiki/Forth_(programming_language)), 50 bytes Though FORTH-79 is the earliest standardized version, the language was in development starting in 1968, and was usable on the IBM 1130. It was used on other systems as well before 1977 came around. I may do a bit more research to ensure these words were all available, but I'm fairly certain this is basic enough to have existed by then. These were all available by FORTH-79, for sure. Loops forever, waiting 6420000 milliseconds between string printing. No newline is printed. ``` : F 0 1 DO 6420000 MS ." 4 8 15 16 23 42" LOOP ; F ``` [Answer] # Smalltalk, 95 (or 68 if loophole is allowed) Been around since 1972 ``` |i|[i:=0.[i<5] whileTrue: [(Delay forSeconds: 6480) wait.Transcript show: '4 8 15 16 23 42'.]]fork ``` No experience with this one, saw it on wikipedia :P Looked it up online how to loop and delay, syntax should be correct but couldn't find a way to run it. ### Possible loophole It should print the sequence every 108 minutes, but it doesn't state that it has to be 108 minutes. This could make the code shorter ``` |i|[i:=0.[i<5] whileTrue: [Transcript show: '4 8 15 16 23 42'.]]fork ``` Code will print the sequence with no interval, so its guaranteed that it will print after 108 mins too. [Answer] ## SAS, ~~82~~ ~~75~~ 69 ``` data; file stdout; a:; put "4 8 15 16 23 42"; a=sleep(6300,1); goto a; run; ``` Not a typical golfing language, but I think it qualifies for this challenge, assuming that `file stdout` was valid in 1977-era SAS. Improvements: * `data _null_;` --> `data;` saves 7 characters (and now produces an empty dataset as well as printing to stdout). * Replaced do-while loop with goto - saves 6 characters [Answer] # C, 50 bytes Shorter than the other C solution, and thus not a duplicate. I actually wrote this before I noticed Digital Trauma's (nearly) identical comment on the other C solution. ``` main(){for(;;sleep(6240))puts("4 8 15 16 23 42");} ``` [Answer] # COBOL, 240 bytes Yes, the leading whitespace is significant. Compile and run like `cobc -x save.cob; ./save`. (The `-x` option produces an executable as opposed to a shared lib and thus I don't think it needs to be counted.) ``` IDENTIFICATION DIVISION. PROGRAM-ID.S. PROCEDURE DIVISION. PERFORM UNTIL 1<>1 DISPLAY"4 8 15 16 23 42" CALL"C$SLEEP"USING BY CONTENT 6402 END-PERFORM. GOBACK. ``` If we want to be boring, we can add the `--free` compilation option for free-format code, then **158 + 6 = 164 bytes** but this would be unlikely to work back in '77. ``` IDENTIFICATION DIVISION. PROGRAM-ID.S. PROCEDURE DIVISION. PERFORM UNTIL 1<>1 DISPLAY"4 8 15 16 23 42" CALL"C$SLEEP"USING BY CONTENT 6402 END-PERFORM. GOBACK. ``` [Answer] # ALGOL 60 / 68 / W, ~~74~~ ~~47~~ 50 bytes Run this full program with `a68g save.a68`, using [`algol68g`](http://algol68.sourceforge.net). ALGOL doesn't have a builtin way to sleep but we can run essentially `/bin/sleep`: ``` DO print("4 8 15 16 23 42");system("sleep 6380")OD ``` --- Old answer: > > ALGOL doesn't have a sleep builtin, so we can abuse `ping` which is surely on a Unix of the time (idea from [here](http://rosettacode.org/wiki/Sleep#ALGOL_68)) for ~~74~~ **69 bytes**. > > > > ``` > DO print("4 8 15 16 23 42");system("ping 1.0 -c1 -w6240>/dev/null")OD > > ``` > > [Answer] # [ABC](https://homepages.cwi.nl/%7Esteven/abc/), 198 bytes ABC: The Python in 1975! ``` WHILE 1=1: PUT now IN(a,b,c,d,e,f) PUT a*518400+b*43200+c*1440+d*60+e IN x WRITE "4 8 15 16 23 42"/ PUT x IN y WHILE y-x<104: PUT now IN(a,b,c,d,e,f) PUT a*518400+b*43200+c*1440+d*60+e IN y ``` [Try it online!](https://tio.run/##S0xK/v8/3MPTx1XB0NbQioszIDREIS@/XMHTTyNRJ0knWSdFJ1UnTRMikahlamhhYmCgnaRlYmwEpJO1DE1MDLRTtMwMtFOBehQquDjDgzxDXBWUTBQsFAxNFQzNFIyMFUyMlPQhRlSAVFUCVYHtrNStsDE0MAHai9tiIm2u/P8fAA "ABC – Try It Online") ]
[Question] [ The purpose of this challenge is to produce an ASCII version of the cover of [this great album](https://en.wikipedia.org/wiki/The_Wall) by the rock band Pink Floyd. The brick junctions are made of characters `_` and `|`. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is: ``` _________ | | | | _________ ``` Each row of bricks is **offset by half a brick width** (4 chars) with respect to the previous row: ``` ________________________________________ | | | | | | | | | | ________________________________________ | | | | | | | | | | ________________________________________ | | | | | | | | | | ``` The wall is **parameterized** as follows. All parameters are measured in chars including junctions: 1. **Horizontal offset** of first row, `F`. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are `0`, `1`, ..., `7`. 2. Total **width**, `W`. This includes junctions. Its value is a positive integer. 3. Total **height**, `H`. This includes junctions. Its value is a positive integer. The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of `3`). For example, here's the output for `6`, `44`, `11`: ``` ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` and a visual explanation of parameters: ``` F=6 ...... . ____________________________________________ . | | | | | . | | | | | . ____________________________________________ . | | | | | | H=11 . | | | | | | . ____________________________________________ . | | | | | . | | | | | . ____________________________________________ . | | | | | | ............................................ W=44 ``` ## Additional rules You may provide a program or a function. Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings. Trailing spaces or newlines are allowed. Shortest code in bytes wins. ## Test cases Inputs are in the order given above, that is: horizontal offset of first row, total width, total height. ``` 6, 44, 11: ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | 2, 20, 10: ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ 1, 1, 1: _ 1, 2, 3: __ | | 3, 80, 21: ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ________________________________________________________________________________ | | | | | | | | | | | | | | | | | | | | ``` [Answer] # C, 86 85 83 82 bytes 3 bytes saved thanks to Lynn. 1 byte saved thanks to charlie. ``` i;f(o,w,h){++w;for(i=0;++i<w*h;)putchar(i%w?i/w%3?i%w+i/w/3*4+~o&7?32:124:95:10);} ``` [Answer] # C, 92 bytes ``` b(f,w,h,y,x){for(y=0;y<h;y++,puts(""))for(x=0;x<w;x++)putchar(y%3?(x+y/3*4-f)%8?32:124:95);} ``` Invoke as `b(F, W, H)`. [Answer] # Pyth, ~~43~~ 27 bytes I ***need*** to golf it heavily... the score is too shameful. ``` AQVE<*H?%N3X*8d+G*4/N3\|\_H ``` [Try it online already.](http://pyth.herokuapp.com/?code=AQVE%3C%2aH%3F%25N3X%2a8d%2BG%2a4%2FN3%5C%7C%5C_H&input=6%2C44%0A11&debug=0) ### Input format ``` 6,44 11 ``` ### Output format ``` ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` ## Explanation ``` AQVE<*H?%N3X*8d+G*4/N3\|\_H First two inputs as list in Q, third input as E. AQ Assign G to the first item in Q and H to the second item in Q. VE For N from 0 to E-1: /N3 N floor-div 3. if N gives a remainder of 3 or 4 or 5 when divided by 6, this will be odd; otherwise, this will be even. *4 Multiply by 4. if the above is odd, this will leave a remainder of 4 when divided by 8; otherwise, the remainder would be 0. +G Add G (as an offset). X*8d \| In the string " " (*8d), replace (X) the character with the index above with "|" (modular indexing, hence the manipulation above). ?%N3 \_ If N%3 is non-zero, use the above; otherwise, use "_". *H The above repeated H times. < H Take the first H characters of above. Implicitly print with newline. ``` [Answer] # Perl, 63 bytes ``` #!perl -nl $y+=print+map$y%3?$_++-$`&7?$":'|':_,($y%6&4)x$&for/ \d+/..$' ``` Counting the shebang as 2, input is taken from stdin, whitespace separated. **Sample Usage** ``` $ echo 2 20 10 | perl bricks.pl ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ ``` [Answer] ## Haskell, 83 bytes ``` q s="_":[s,s] (f!w)h=take h$cycle$take w.drop(7-f).cycle<$>q" |"++q" | " ``` This defines a ternary infix function `!` which returns a list of strings. Usage example: ``` *Main> putStrLn $ unlines $ (3!14) 7 ______________ | | | | ______________ | | ______________ ``` How it works: ``` q" |"++q" | " -- build a list of 6 strings -- 1: "_" -- 2: " |" -- 3: " |" -- 4: "_" -- 5: " | " -- 6: " | " <$> -- for each of the strings take w.drop(7-f).cycle -- repeat infinitely, drop the first 7-f chars -- and take the next w chars cycle -- infinitely repeat the resulting list take h -- and take the first h elements ``` [Answer] ## JavaScript (ES6), ~~96~~ 95 bytes ``` g= (f,w,h)=>[...Array(h)].map((_,i)=>(i%3?` |`:`_`).repeat(w+7).substr(f^7^i%6&4,w)).join` ` ; ``` ``` <div onchange=o.textContent=g(f.value,w.value,+h.value)><input id=f type=number min=0 max=7 placeholder=Offset><input id=w type=number min=0 placeholder=Width><input id=h type=number min=0 placeholder=Height></div><pre id=o> ``` Explanation: Creates a string of either the repeating 7 spaces plus `|` pattern or just repeated `_`s, but at least long enough to be able to extract the `w` characters required for each row. The first three rows start at position `f^7` and then the next three rows start at position `f^3`, so I achieve this by ~~toggling bit 2 of `f` on every third row~~ using the opposite bit 2 on the last two rows of each block of 6 for a saving of 1 byte. [Answer] # Python 2, ~~93~~ 88 bytes ~~2nd indentation level is tab~~ Saving some bytes thanks to Leaky Nun and some own modifications, also now correct offset: ``` def f(F,W,H): for h in range(H):print["_"*W,((("|"+7*" ")*W)[8-F+h%6/3*4:])[:W]][h%3>0] ``` previous code: ``` def f(F,W,H,x="|"+7*" "): for h in range(H): print ["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0] ``` Same length as unnamed lambda: ``` lambda F,W,H,x="|"+7*" ":"\n".join(["_"*W,(x[F+4*(h%6>3):]+x*W)[:W]][h%3>0]for h in range(H)) ``` [Answer] # MATL, ~~42~~ ~~36~~ 33 bytes ``` :-Q'_ | |'[DClCl]Y"8et4YShwi:3$)! ``` Input format is: `nCols`, `offset`, `nRows` [**Try it Online**](http://matl.tryitonline.net/#code=Oi1RJ18gfCB8J1tEQ2xDbF1ZIjhldDRZU2h3aTozJCkh&input=NDQKNgoxMQ) The approach here is that we setup a "template" which we then index into by using the row indices (`[1 2 ... nRows]`) and column indices shifted by the first input (`[1 2 ... nCols] - shift`). Thanks to MATL's modular indexing, it will automatically result in a tiled output. As a side-note, to save some space, technically I work with a transposed version of the template and then just take a transpose (`!`) at the end. The template is this: ``` ________ | | ________ | | ``` [Answer] # QBasic, ~~121~~ 109 bytes ## (Tested on QB64) Thanks to @DLosc for golfing my `IF` statement with a mathematical equivalent. That was worth 12 bytes. ## General Method: Loop through each cell one at a time and determine whether it should be a `_`, , or `|` depending on its location. `MOD` statements and boolean logic are used to determine brick boundaries and how much to stagger the bricks. ## Code: ``` INPUT F,W,H FOR y=0TO H-1:FOR x=0TO W-1 ?CHR$((y MOD 3>0)*(((x-(y MOD 6>3)*4)MOD 8=F)*92+63)+95); NEXT:?:NEXT ``` ## Usage Note: QBasic expects input to be numbers separated by commas. [Answer] # Java, ~~149~~, ~~147~~, ~~146~~, 143 bytes Golfed: ``` String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;} ``` Ungolfed: ``` public class AllInAllItsJustUhAnotherTrickInCodeGolf { public static void main(String[] args) { int offset = 6; int width = 44; int height = 11; System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf() .f(offset, width, height)); } // Begin golf String f(int o, int w, int h) { String s = ""; for (int y = 0, x; y < h; ++y) { for (x = 0; x < w; ++x) { s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_'; } s += '\n'; } return s; } // End golf } ``` [Answer] # Ruby, ~~72~~ 66 bytes ``` ->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}} ``` Thanks @Value Ink for 6 bytes! Simple string multiplication and slicing. Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error). [Answer] # Julia: ~~150~~ ~~128~~ ~~116~~ ~~108~~ 107 bytes ``` # in codegolf.jl r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...) ``` to run with arguments: `julia -e 'o=2;h=18;w=40;include("codegolf.jl")'` If you feel calling from bash is cheating and you want a function inside the interpreter, then the function version is 117 bytes :) ``` f(o,h,w)=(r=repmat;b=r([' '],6,8);b[[1,4],:]='_';b[[2,3,23,24]]='|';b=r(b,h,w)[1:h,o+=1:o+w];b[:,end]=10;print(b'...)) ``` [demo](http://julia.tryitonline.net/#code=ZihvLGgsdyk9KGI9MzIqb25lcyhJbnQzMiw2LDgpO2JbWzEsNF0sOl09OTU7YltbMiwzLDIzLDI0XV09MTI0O2I9cmVwbWF0KGIsaCx3KVsxOmgsbysxOm8rdysxXTtiWzosZW5kXT0xMDtwcmludChyZWludGVycHJldChDaGFyLGInKS4uLikpCmYoMiwgMTgsNDAp&input=) (Thanks, @glen-o for the extra byte-saving tip!) [Answer] ## JavaScript, ~~172~~ ~~168~~ ~~165~~ ~~157~~ ~~147~~ ~~142~~ 137 bytes ``` (O,W,H)=>{t='_'.repeat(W),x='| '.repeat(W),f=t+` `;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+` `;return f} ``` ``` N = (O,W,H)=>{t='_'.repeat(W),x='| '.repeat(W),f=t+` `;for(i=0;++i<H;)f+=(!(i%3)?t:(i%6)>3?x.substr(O,W):x.substr(8-O,W))+` `;return f} let test_data = [[6,44,11], [2,20,10], [1,1,1], [1,2,3], [3,80,21]]; for (test of test_data) console.log(N(...test)); ``` [Answer] # Dyalog APL, 29 bytes `↑⎕⍴⎕⍴¨a,4⌽¨a←'_',2⍴⊂⌽⎕⌽¯8↑'|'` tests: [`6 44 11`](http://tryapl.org/?a=F%20W%20H%u21906%2044%2011%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`2 20 10`](http://tryapl.org/?a=F%20W%20H%u21902%2020%2010%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`1 1 1`](http://tryapl.org/?a=F%20W%20H%u21901%201%201%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`1 2 3`](http://tryapl.org/?a=F%20W%20H%u21901%202%203%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run), [`3 80 21`](http://tryapl.org/?a=F%20W%20H%u21903%2080%2021%20%u22C4%20%u2191H%u2374W%u2374%A8a%2C4%u233D%A8a%u2190%27_%27%2C2%u2374%u2282%u233DF%u233D%AF8%u2191%27%7C%27&run) `⎕` is evaluated input; as the expression executes from right to left, it prompts for `F`, `W`, and `H` in that order `¯8↑'|'` is `' |'` `⎕⌽` is rotate, it chops F chars from the front and puts them at the end of the string the other `⌽` means reverse `'_',2⍴⊂` creates a 3-tuple of '\_' followed by two separate copies of the string so far `a,4⌽¨a←` append the 4-rotation of everything so far, we end up with a 6-tuple `⎕⍴¨` reshape each element to the width `⎕⍴` reshape to the height `↑` mix vector of vectors into a matrix [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '_'|7úD)³∍ε73N3÷è¹-._²∍ ``` -1 byte thanks to *@Grimmy*. Inputs in the order \$\text{offset}, \text{width}, \text{height}\$. Output as a list of string-lines. [Try it online](https://tio.run/##yy9OTMpM/f9fPV69xvzwLhfNQ5sfdfSe22pu7Gd8ePvhFYd26urFH9oEFPtfe2j3fzMuExMuQ0MA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957aaG/sZH95@eEWErl58JFDkf@2h3TqaMYe22f@PjjbTMTHRMTSM1Yk20jEy0DE0ALIMdYAQTBvpGANpYx0LAx0jkIiBjqWOSWwsAA). **Explanation:** ``` '_ '# Push "_" '| '# Push "|" 7ú # Pad 7 leading spaces: " |" D # Duplicate it ) # Wrap all three values on the stack into a list ³∍ # Extend this list to the (third) input-height amount of lines # i.e. height=7 → ["_"," |"," |","_"," |"," |","_"] ε # Map over each line: N # Push the (0-based) map-index 3÷ # Integer-divide it by 3 73 è # Index it into 73 (0-based and with wraparound) # i.e. indices=[0,1,2,3,4,5,6,7,...] → [7,7,7,3,3,3,7,7,...] ¹+ # Subtract the (first) input-offset # i.e. offset=6 → [-3,-3,-3,1,1,1,-3,-3,...] ._ # Rotate the string that many times towards the left # i.e. ["_"," |"," |","_"," |"," |","_"] and # [-3,-3,-3,1,1,1,-3] → ["_"," | "," | ","_"," | "," | ","_"] ²∍ # After this inner loop: push the (second) input-width # Extend/shorten the line to a size equal to the (second) input-width # i.e. width=5 and line=" | " → " | " # i.e. width=20 and line=" | " → " | | |" # i.e. width=5 and line="_" → "_____" # i.e. width=20 and line="_" → "____________________" # (after which the list of string-lines is output implicitly as result) ``` `73N3÷è` could alternatively be `₃€ÐÍNè` for the same byte-count: [Try it online](https://tio.run/##ATsAxP9vc2FiaWX//ydfJ3w3w7pEKcKz4oiNzrXigoPigqzDkMONTsOowrktLl/CsuKIjf99wrv/Ngo0NAoxMQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpSbKWgZF@pw6XkX1oC5AJ5OpUJh1bGhIX@V49XrzE/vMtF89C6Rx2957Y@amp@1LTm8ITDvX6HV0To6sVHAoX/1x7araMZc2ib/f/oaDMdExMdQ8NYnWgjHSMDHUMDIMtQBwjBtJGOMZA21rEw0DECiRjoWOqYxMYCAA). ``` ₃ # Push builtin 95 €Ð # Triplicate each digit: [9,9,9,5,5,5] Í # Decrease each by 2: [7,7,7,3,3,3] Nè # Index the (0-based) map-index into this (0-based and with wraparound) ``` [Answer] # [Actually](https://github.com/Mego/Seriously), ~~44~~ ~~43~~ 40 bytes This is an Actually port of the algorithm in [Neil's JS answer](https://codegolf.stackexchange.com/a/90076/47581). Golfing suggestions welcome. [Try it online!](https://tio.run/##S0wuKU3Myan8///R1OmPps4tetSzwNpMQ9VE7dHUOeZxcY@mzlavMVdSUNLS1ioBchw8QCLxWsYaqpGej3oW@mb@/29oyGViwmUGAA "Actually – Try It Online") ``` ╗╝r⌠;6(%4&╜7^^╛'|7" "*+*t╛@H╛'_*3(%YI⌡Mi ``` **Ungolfing:** ``` Takes implicit input in the order h, w, f. ╗╝ Save f to register 0. Save w to register 1. r⌠...⌡M Map over range [0..h-1]. Call this variable i. ; Duplicate i 6(% i%6... 4& ...&4 ╜7^^ ...^i^7. Call it c. ╛ Push w. '|7" "*+ The string " |" *t╛@H ((" |" * w)[c:])[:w] ╛'_* Push "_" * w 3(% Push 3, move duplicate i to TOS, mod. YI If not i%3, take "_"*w, else ((" |" * w)[c:])[:w] Function ends here. i Flatten the resulting list and print the bricks implicitly. ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~101~~ 88 bytes ``` param($n,$w,$h)0..--$h|%{(('| '*$w|% S*g(8-$n+4*($_%6-gt3))$w),('_'*$w))[!($_%3)]} ``` [Try it online!](https://tio.run/##LY3RCoJAEEXf9ys2GdsZG2NXJSLoK@otRCQsH8xEhX1Iv31zrWG4nDt34HZvW/VDXTWNg8f547qyL18ILYNlqEnv93EM9RR@ENUkf6MisFMoL9ETjzG0uyxCKMJD/BxTIrDEqAr/Q3Tb@CSlfHazEIgHzjI2hlhgwolmoz0aln7/mLBMPaYsj3qxhmipF744uFbDKO/lUJ0kFMF6k1t4LOamc69m1SRfI6XE7L4 "PowerShell – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 30 bytes ``` (n₃[¹\_*,|7\|꘍¹*⁰ǔǔn3ḭ∷[4ǔ]¹Ẏ, ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%28n%E2%82%83%5B%C2%B9%5C_*%2C%7C7%5C%7C%EA%98%8D%C2%B9*%E2%81%B0%C7%94%C7%94n3%E1%B8%AD%E2%88%B7%5B4%C7%94%5D%C2%B9%E1%BA%8E%2C&inputs=10%0A44%0A1&header=&footer=) A big mess. ``` ( # (height) times (to make each row) n₃[ # If the iteration is divisible by 3 (flat row) then... ¹\_*, # (width) underscores | # Else (part of a brick)... 7\|꘍ # Prepend seven spaces to an underscore ¹* # Repeat (width) times ⁰ǔǔ # Cycle by (offset), then cycle once more n3ḭ∷[ ] # If it's an offset row 4ǔ # Cycle once more ¹Ẏ, # Trim to the correct length and print. ``` [Answer] # Octave ~~80~~ 76 bytes ``` % in file codegolf.m c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;char(repmat(c+32,h,w)(1:h,o+1:o+w)) ``` to run from terminal: `octave --eval "o=2;h=18;w=44; codegolf"` (alternatively, if you think the terminal call is cheating :p then an anonymous function implementation takes 86 bytes :) ``` c(6,8)=0;c([1,4],:)=63;c([2,3,23,24])=92;f=@(o,h,w)char(repmat(c+32,h,w)(1:h,o+1:o+w)) ``` Call `f(2,18,44)` at the octave interpreter. [Answer] # Bash + Sed, ~~411~~ ~~395~~ ~~381~~ 370 bytes: ``` F=`printf '_%.s' $(eval echo {1..$2})`;V=" |";(($[($2-$1)/8]>0))&&L=`printf "$V%.s" $(eval echo {1..$[($2-$1)/8]})`||L=;Z=`printf "%$1.s|%s\n" e "$L"`;I=$[($2-(${#Z}-4))/8];(($I>0))&&W=`printf "$V%.s" $(eval echo {1..$I})`||W=;J=${Z:4}$W;for i in `eval echo {1..$[$3/3+1]}`;{ (($[$i%2]<1))&&O+="$F\n$J\n$J\n"||O+="$F\n$Z\n$Z\n";};echo "`echo -e "$O"|sed -n 1,$3p`" ``` Well, here is my very first answer in Bash, or any shell scripting language for that matter. This is also by far the longest answer here. Takes in a sequence of space-separated command line arguments in the format `Offset Width Height`. This can probably be a lot shorter than it currently is, so any tips and/or tricks for golfing this down more are appreciated. [Answer] ## Delphi/Object Pascal, 305, 302, 292 bytes Full console program that reads 3 parameters. ``` uses SySutils,Math;var i,q,o,w,h:byte;begin o:=StrToInt(paramstr(1));w:=StrToInt(paramstr(2));h:=StrToInt(paramstr(3));for q:=0to h-1do begin for i:=1to w do if q mod 3=0then Write('_')else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8))=1then Write('|')else Write(' ');Writeln('');end end. ``` ### ungolfed ``` uses SySutils, Math; var i,q,o,w,h:byte; begin o:=StrToInt(paramstr(1)); w:=StrToInt(paramstr(2)); h:=StrToInt(paramstr(3)); for q := 0 to h-1 do begin for i := 1 to w do if q mod 3 = 0 then Write('_') else if IfThen(Odd(q div 3),((i+o)mod 8),((i-o)mod 8)) = 1 then Write('|') else Write(' '); Writeln(''); end end. ``` Sadly, Delphi does not have a ternary operator and it is quite a verbose language. ### test case ``` D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 2 20 10 ____________________ | | | | | | ____________________ | | | | ____________________ | | | | | | ____________________ D:\Test\CodeGolfWall\Win32\Debug>Project1.exe 6 44 11 ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | | | | | | | ____________________________________________ | | | | | | | | | | ____________________________________________ | | | | | | ``` Edit: Could shave of 3 bytes by using byte as type for all variables. Edit 2: And console applications do not *need* the program declaration, -10 [Answer] # JavaScript (ES6), ~~81 78~~ 77 bytes *Saved 3 bytes thanks to @mypronounismonicareinstate* Takes input as `(F, W)(H)`. ``` (F,W,x=y=0)=>g=H=>y<H?` |_ `[x++<W?y%3?(x+~F^y/3<<2)&7?3:1:2:x=+!++y]+g(H):'' ``` [Try it online!](https://tio.run/##bczBCsIgAIDhe09hh5qi1dRRITpvY2@wQ1QbaxvFmNEiFKJXN6@xzh//f6te1Vg/rvfnajCXxrfKw4wUxCqnYqTSTuUqdTLX5ex9BuXBYiwL7RZcQ4s/2cltuJQMLXeaCyqYsArPMXZH3MEciSjytRlG0zfr3nSwhVsCkgRBShGa/QojgMVB4olQAgBFENC/woLwiXAC9uHGQuO/ "JavaScript (Node.js) – Try It Online") ]
[Question] [ It is well known that a person on a grid under the influence of alcohol has an equal chance of going in any available directions. However, this common-sense statement does not hold in the realm of *very small* drunkards, whose behavior is very much as if they take *every* available path at once, and the possible paths they take can interfere with each other. Your task is to display the possible positions of such a quantum drunkard after `n` steps. ## Specification The drunkard in question occupies a square grid, and may be considered to be a 3-state cellular automaton using a Von Neumann (plus-shaped) neighborhood which follows these simple rules: * `Empty` goes to `Awake` if it is adjacent to exactly one `Awake`, and otherwise goes to `Empty` * `Awake` goes to `Sleeping` * `Sleeping` goes to `Sleeping` The initial state of the board is a single `Awake` surrounded by an infinite field of `Empty`s. ## Challenge Given a nonnegative integer `n`, create an ASCII representation of the drunkard after `n` steps. Each state should be represented by a different character, and solutions should state which character means which state. If you use spaces for `Empty`, you don't need to include a run of them at the end of a line. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, leading and trailing whitespace is allowed, string array/2d char array output is allowed, etc. ## Examples These examples use for `Empty`, `@` for `Awake`, and `#` for `Sleeping`. ``` n=0 @ n = 1 @ @#@ @ n = 2 @ # @###@ # @ n = 3 @ @#@ @ # @ @#####@ @ # @ @#@ @ n=6 @ # @###@ @#@ @ ### @ #@# # #@# @###########@ #@# # #@# @ ### @ @#@ @###@ # @ n=10 @ # @###@ @#@ ### # # # ####### # ### # @ ## ### ## @ #@# ### # ### #@# @###################@ #@# ### # ### #@# @ ## ### ## @ # ### # ####### # # # ### @#@ @###@ # @ ``` ## Interesting Note By looking up the sequence of the number of occupied cells in the OEIS, I found that the quantum drunkard is isomorphic to the much better-studied [toothpick sequence](https://arxiv.org/abs/1004.3036). If you can incorporate that knowledge into a better golf, I will be suitably impressed. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~92~~ 91 bytes ``` Print@@@CellularAutomaton[{7049487784884,{3,{a={0,3,0},3-2a/3,a}},{1,1}},{j={{1}},0},{j#}]& ``` A perfect challenge to use Mathematica's builtin `CellularAutomaton`! [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T@gKDOvxMHBwTk1J6c0J7HIsbQkHyidnxddbW5gYmliYW5uYWJhYaJTbaxTnWhbbaBjrGNQq2Osa5Sob6yTWFurU22oYwiismyrq0EMAxBbuTZW7b@mNVeag5nJfwA "Wolfram Language (Mathematica) – Try It Online") Empty = 0, Awake = 1, Sleeping = 2 Animation of the first 256 iterations (white = empty, gray = awake, black = sleeping): [![enter image description here](https://i.stack.imgur.com/aGX2v.gif)](https://i.stack.imgur.com/aGX2v.gif) ### Explanation ``` CellularAutomaton[ ... ] ``` Run `CellularAutomaton` with specifications... ``` {7049487784884,{3,{a={0,3,0},3-2a/3,a}},{1,1}} ``` Apply the 3-color totalistic rule 7049487784884, with Von Neumann neighborhood... ``` {j={{1}},0} ``` On a board with a single 1 in the middle, with a background of 0s... ``` {j#} ``` Repeat `<input>` times (`{j#}` evaluates to `{{{#}}}`). The array automatically expands if a cell outside of the border is not the same as the background ``` 7049487784884 ``` This rule comes from the base-3 number `220221220221220221220221220`, which means "change all `1` or `2` to `2`, and change `0` to `1` if and only if there is an odd number of `1`s around it." ``` Print@@@ ``` Print the array. ### Semi-proof of "'odd `1`s' is equivalent to 'exactly one `1`'": Consider this 5x5 grid of pixels. White is a `0` or a `2` cell (non-awake pixels), and gray is a `1` cell. [![enter image description here](https://i.stack.imgur.com/KGUWZ.png)](https://i.stack.imgur.com/KGUWZ.png) If a `1` cell was generated around three `0` cells, then the grid must look like this: it has three `1`s arranged in a U-shape (or a rotated version) as follows: [![enter image description here](https://i.stack.imgur.com/FGZWA.png)](https://i.stack.imgur.com/FGZWA.png) Due to the self-similarity of this cellular automaton, any pattern that appears in the cellular automaton must appear on the diagonal (by induction). However, this pattern is not diagonally symmetric. i.e. it cannot occur on the diagonal and cannot appear anywhere on the cellular automaton. ### Awake/Sleeping are equivalent Note that a `0` cell cannot be surrounded by exactly one or three `2` cells and rest `0` cells, since that would imply that some steps prior, the cell had a neighbor of one or three `1` cells -- and must have turned into a `1` already (contradiction). Therefore, it is okay to ignore the distinction between `1` and `2` and state 'change all `1` to `1`, and a `0` to a `1` if and only if it has an odd number of nonzero neighbors.' The resulting cellular automaton is indeed identical to the original, the only difference being there is no distinction between "awake" and "asleep" drunkards. This pattern is described in OEIS [A169707](https://oeis.org/A169707). ``` Print@@@CellularAutomaton[{750,{2,{a={0,2,0},2-a/2,a}},{1,1}},{j={{1}},0},{j#}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T@gKDOvxMHBwTk1J6c0J7HIsbQkHyidnxddbW5qoFNtpFOdaFttoGOkY1CrY6SbqG@kk1hbq1NtqGMIorJsq6tBDAMQW7k2Vu2/pjVXmoOZyX8A "Wolfram Language (Mathematica) – Try It Online") Side-by-side comparison of the first 16 iterations: [![enter image description here](https://i.stack.imgur.com/vmqJL.gif)](https://i.stack.imgur.com/vmqJL.gif) Adding two consecutive iterations gives a result that follows the challenge specs (94 bytes): ``` Print@@@Plus@@CellularAutomaton[{750,{2,{a={0,2,0},2-a/2,a}},{1,1}},{{{1}},0},{Ramp@{#-1,#}}]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T@gKDOvxMHBISCntNjBwTk1J6c0J7HIsbQkH6goPy@62tzUQKfaSKc60bbaQMdIx6BWx0g3Ud9IJ7G2VqfaUMcQRFVXgyigVHVQYm6BQ7WyrqGOcm1trNp/TWuuNAczk/8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 192 bytes ``` x=input() o=c={x+x*1j} R=range(x-~x) exec"n=[C+k for k in-1j,1j,-1,1for C in c];n={k for k in n if(k in o)<2-n.count(k)};o|=c;c=n;"*x print[[`(X+Y*1jin c)+(X+Y*1jin o|c)`for Y in R]for X in R] ``` [Try it online!](https://tio.run/##RY2xCoMwFEX3fEVwStSURuiUZvIPnBQRLEHbKLyIREhR@@upaQfhDedeLudNb/sykHnvpIZpsYQiI5VcXeJiPuyokPMDnh1x7OMo6lynIpB1noy4NzMesQbGh/Q4xlMeqvyosGoEyPXcYMC6Jz8y9J4xuCizgCUj3YXZpBJKgohih6ZZg63rlpRJdfwPKpqcwWyKtkFaBVXRBCz/6P3t@gU "Python 2 – Try It Online") -17 bytes thanks to Mr. Xcoder -9 bytes using Jonathan's output format -11 bytes thanks to Lynn -3 bytes thanks to ovs [Answer] # C, ~~360~~ ~~354~~ ~~343~~ 319 ``` #define A(i,b,e)for(int i=b;i<e;++i) #define B(b,e)A(r,b,e){A(c,b,e) #define W(n)(n<0?-(n):n) #define C(r,c)b[W(r)*s+W(c)] #define D C(r,c) q(n){char N,s=n+2,(*b)[2]=calloc(s,2*s);C(0,0) [1]=1;A(g,0,n+1){B(0,s)*D=D[1];}B(0,g+2){N=(*C (r-1,c)+*C(r+1,c)+*C(r,c-1)+*C(r,c+1))&1;D[1]= *D?2:N;}}}B(2-s,s-1)putchar(*D+32);puts("");}} ``` Newlines after non-`#define` lines are just for presentation here, so they’re not counted. I included a wrapper function, so it’s −6 (313) if the function isn’t counted and you assume `n` comes from elsewhere. `q(10)` outputs: ``` ! " !"""! !"! """ " " " """"""" " """ " ! "" """ "" ! "!" """ " """ "!" !"""""""""""""""""""! "!" """ " """ "!" ! "" """ "" ! " """ " """"""" " " " """ !"! !"""! " ! ``` Using for empty, `"` for sleeping, and `!` for awake. This works like so: * `A(i,b,e)` is “∀i∈[b,e).”, `B(b,e)` is “∀r∈[b,e).∀c∈[b,e).” * Observe that after *n* generations, the board is 2*n* + 1 square. * Because of the symmetry of the board, this only needs to simulate the lower right quadrant, so we allocate an *n* + 1 square matrix with 1 row & column of padding for the later neighbour lookup (so *n* + 2). * Allocating with `calloc` lets us simultaneously multiply the width by the height and clear the board to `0` (empty). * When looking up a cell by its coordinates (`C` and `D`), it uses the absolute value of the row and column (`W`) to automatically mirror the coordinates. * The board is stored as an array of pairs of integers representing the current and previous generations. The integers in question are `char` so we can avoid `sizeof`. * The generation looked up most frequently (by the neighbour test) is the past generation, so it’s placed at index 0 in the pair so it can be accessed with `*`. * At each generation (`g`), the current generation is copied over the previous generation using a `B` loop, then the new generation is generated from the old. * Each cell is represented using `0` for empty, `1` for awake, and `2` for sleeping. Counting neighbours was originally a calculation of the number of bits set in the low 4 bits of the cell when the 4 neighbours are shifted & OR’d together as flags (`N`), using `16` for sleeping. But with the observation that an odd number of neighbours is equivalent to exactly 1 neighbour, we can save several characters just using a mask with 1. * At the end, the board is printed in full by iterating over the lower right quadrant using the same absolute value coordinate trick, minus padding so we don’t print the outer padding on the board. This is also why the `B` loop includes an opening curly bracket, because we have the extra newline statement in the outer loop. * The ASCII codes conveniently map 0+32 (empty) to a space, 2+32 (sleeping) to `"`, and 1+32 (awake) to `!`. All in all I think this is a surprisingly readable golf because of the nice structure of the problem. [Answer] # [MATL](https://github.com/lmendo/MATL), 39 bytes ``` QtE:=&*G:"tt0=w1Y6Z+Xj1=*w|gJ*+]Q|U31+c ``` This displays * `Empty` as (space) * `Awake` as `#` * `Sleeping` as `!`. [**Try it online!**](https://tio.run/##y00syfn/P7DE1cpWTcvdSqmkxMC23DDSLEo7IsvQVqu8Jt1LSzs2sCbU2FA7@f9/QwMA) You can also watch the pattern [**grow**](http://matl.suever.net/?code=QtE%3A%3D%26%2aG%3A%22t2%26XxQ%7CU31%2BcDtt0%3Dw1Y6Z%2BXj1%3D%2aw%7CgJ%2a%2B%5D2%26XxQ%7CU31%2Bc&inputs=14&version=20.4.2) in ASCII art, or [**graphically**](http://matl.suever.net/?code=QtE%3A%3D%26%2aGQ%3A%22t%26ZjwE%2B2%2FXx0YGtt0%3Dw1Y6Z%2BXj1%3D%2aw%7CgJ%2a%2B%5Dx&inputs=100&version=20.4.2) (modified code). ### Explanation The code uses complex numbers `0`, `1`, `j` to represent the three states: empty, wake, sleeping respectively. ``` Q % Implicitly input n. Add 1 tE % Duplicate and multiply by 2 : % Range [1 2 ... 2*n] = % Test for equalty. Gives [0 ... 0 1 0... 0], with 1 at position n &* % Matrix of all pairwise products. Gives square matrix of size 2*n % filled with 0, except a 1 at position (n,n). This is the grid % where the walk will take place, initiallized with an awake cell % (value 1). The grid is 1 column and row too large (which saves a % byte) G:" % Do n times tt % Duplicate current grid state twice 0= % Compare each entry with 0. Gives true for empty cells, false % for the rest w % Swap: moves copy of current grid state to top 1Y6 % Push 3×3 matrix with Von Neumann's neighbourhood Z+ % 2D convolution, maintaining size Xj % Real part 1= % Compare each entry with 1. This gives true for cells that % have exactly 1 awake neighbour * % Multiply, element-wise. This corresponds to logical "and": % cells that are currently empty and have exactly one awake % neighbour. These become 1, that is, awake w % Swap: moves copy of current grid state to top |g % Absolute value, convert to logical: gives true for awake or % sleeping cells, false for empty cells J*+ % Mulltiply by j and add, element-wise. This sets awake and % sleeping cells to sleeping. The grid is now in its new state ] % End Q % Add 1, element-wise. Transforms empty, awake, sleeping % respectively from 0, 1, j into 1, 2, 1+j |U % Abolute value and square, element-wose. Empty, awake, sleeping % respectively give 1, 4, 2 31+c % Add 31 element-wise and convert to char. Empty, awake, sleeping % respectively give characters ' ' (codepoint 32), '#' (codepoint % 35) and '!' (codepoint 33). Implicitly display ``` [Answer] # Befunge, ~~384~~ 304 bytes ``` &:00p->55+,000g->>00g30p:40p\:50p\5>>40g!50g!*vv0g05g04p03-< @,+55_^#`g00:+1$_^>p:4+4g5%2-50g+5#^0#+p#1<v03_>30g:!#v_:1>^ #v_>$99g,1+:00g`^ ^04+g04-2%5g4:\g05\g04\p<>g!45*9+*3+v>p:5- >\50p\40p\30p:#v_>>0\99g48*`!>v >30g:1-30^>>**\!>#v_>v^9 9< $0\\\\0$ >\99g88*-!+\:4->#^_\>1-!48>^ >$3>48*+^ ``` [Try it online!](http://befunge.tryitonline.net/#code=JjowMHAtPjU1KywwMDBnLT4+MDBnMzBwOjQwcFw6NTBwXDU+PjQwZyE1MGchKnZ2MGcwNWcwNHAwMy08CkAsKzU1X14jYGcwMDorMSRfXj5wOjQrNGc1JTItNTBnKzUjXjAjK3AjMTx2MDNfPjMwZzohI3ZfOjE+Xgojdl8+JDk5ZywxKzowMGdgXiBeMDQrZzA0LTIlNWc0OlxnMDVcZzA0XHA8PmchNDUqOSsqMyt2PnA6NS0KID5cNTBwXDQwcFwzMHA6I3ZfPj4wXDk5ZzQ4KmAhPnYgPjMwZzoxLTMwXj4+KipcIT4jdl8+dl45IDk8CiQwXFxcXDAkICAgICAgICA+XDk5Zzg4Ki0hK1w6NC0+I15fXD4xLSE0OD5eICAgICAgID4kMz40OCorXg&input=NQ) The problem with trying to implement this sort of thing in Befunge is the limited memory size (2000 bytes for both data and code). So I've had to use an algorithm that calculates the correct character for any given coordinate without reference to previous calculations. It achieves this by recursively looking back in time across all possible paths the drunkard might have followed to reach that point. Unfortunately this is not a particular efficient solution. It works, but it's incredibly slow, and it becomes exponentially slower the larger the value of *n*. So while it could potentially work for any *n* up to about 127 (Befunge's 7-bit memory cell limit), in practice you'll inevitably lose interest waiting for the result. On TIO, it'll hit the 60 second timeout on anything higher than around 6 (at best). A compiler will do a lot better, but even then you probably wouldn't want to go much higher than 10. Still, I thought it was worth submitting because it's actually quite a nice demonstration of a recursive "function" in Befunge. [Answer] # [Python 2](https://docs.python.org/2/), 214 bytes ``` def f(n):k=n-~n;N=k*k;A=[0]*N;A[N/2]=2;exec"A=[[2*([j%k>0and A[j-1],j%k<k-1and A[j+1],j/k>0and A[j-k],j/k<k-1and A[j+k]].count(2)==1),1,1][v]for j,v in enumerate(A)];"*n;print[map(str,A)[k*x:][:k]for x in range(k)] ``` [Try it online!](https://tio.run/##TcxBboQgGAXgfU9BmDQBio4wOylNuYAXICyIg1PF@TXUmdhNr27VdOHyfXnvjT/T1wByWa6hQQ0BWkYN2S@oSkcWldG2cKxSxlZn6bRUYQ41XtVKRmz3Gj8KD1dkbJcJx9f8HjPxL2@bnA@NuOdjIzqX18MDJiKp1oJywYWzT9cMCXX8iVpAAR73kPwUiKFOYQZqTC1M9u5H8j0lbqiNbC6dLeM@m7dR8nALJFK3nDbrN2vI5ULLfYxx3g0tkJ7mKYy9rwPBBeYY4QOIFU5HkCt8YvqyHy1/ "Python 2 – Try It Online") # Explanation Uses `0` for `empty`, `1` for `sleeping` and `2` for `awake`. Prints out a two-dimensional character (one-length strings) list. Defines a function which takes in a non-negative integer `n`. Successively advances the cellular automaton until the desired state is reached. Finally, a conversion between the internal integer values and actual characters is applied. [Answer] # [Lua](https://www.lua.org), ~~251~~ ~~242~~ ~~239~~ 238 bytes -8 bytes by simplifying the array initializer at the cost of some additional leading whitespace. -1 byte by changing `c=i==2+...and print(s)` into `c=i~=2+...or print(s)`. -3 bytes by building a complete string first and printing once at the end. -1 byte thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech) by rewriting `or(g(...)==1 and` as `or(1==g(...)and`. ``` function g(x,y)return(a[x]or{})[y]or 0 end a={{1}}for i=2,2+...do n={}s=""for x=-i,i do n[x]=n[x]or{}q=a[x]or{}for y=-i,i do n[x][y]=q[y]and 0or(1==g(x+1,y)+g(x,y+1)+g(x-1,y)+g(x,y-1)and 1)s=s..(q[y]or" ")end s=s.."\n"end a=n end print(s) ``` [Try it online!](https://tio.run/##VY5BCsMgEEWvIq4UE4mBLuckbRehSYpQxkYTSBDPbkfbUrqZGR6fP@@xDTnPG95W65Ddxd4c0k/r5lEM5/3qfEzyfNBmHZtwZAPEaFKaCVjom15prUfHEGIKwHnhO7S2saxQagD81CzwLSyh4y9EH2ChMdCHznlhAEhFGZJR1UmZerQ/0hpZ0kYGCFqLpUpyxmWxrIxfkL@Vsao/vcVVBJlzPnUv "Lua – Try It Online") Empty = Space Awake = `1` Sleeping = `0` Takes input from the command line and prints to stdout. By representing the states as `false`/`nil`, `1` and `0` internally, detecting "empty" doesn't need any code and the "exactly one awake" check can be done with just an addition. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 38 [bytes](https://github.com/abrudz/SBCS) ``` ((2∘∧⌈1={2⊃+/1=⍵,⍉⍵}⌺3 3)(⌽0,⍉)⍣4)⍣⎕⍪1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@GhtGjjhmPOpY/6ukwtK02etTVrK1vaPuod6vOo95OIFX7qGeXsYKxpsajnr0GIDHNR72LTUDEo76pj3pXGYLM@Z/GZcClrs6VxmUIoYwglDGEMgEA "APL (Dyalog Unicode) – Try It Online") -4 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m). -8 thanks to [ngn](https://codegolf.stackexchange.com/users/24908/ngn). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~39~~ 29 bytes ``` -,1ṙ@€Sµ+Z ‘ṬŒḄ×þ`µÇ׬Ḃ+Ḃ+µ³¡ ``` [Try it online!](https://tio.run/##AVMArP9qZWxsef//LSwx4bmZQOKCrFPCtStaCuKAmOG5rMWS4biEw5fDvmDCtcOHw5fCrOG4givhuIIrwrXCs8Kh/8OH4buL4oKs4oCcQCMg4oCdWf//Ng "Jelly – Try It Online") Uses `0`,`1` and `2` for empty awake and sleeping. The footer in the link converts this to , `@` and `#`. * -1 byte by using `ṬŒḄ` instead of `ḤḶ=¹`. * -2 bytes by using `-` instead of `1N`. Also makes `¤` unnecessary. * -1 byte by using `S` instead of `+/`. * -6 bytes by using `Ḃ+Ḃ+` instead of `%3=1+=1Ḥ$+`. Now uses `2` for sleeping instead of `3`. Explanation coming... [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 38 bytes ``` ((2∘∧⌈2|⍉∘g∘⍉+g←3+/0,,∘0)(⌽0,⍉)⍣4)⍣⎕⍪1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ooz3tv4aG0aOOGY86lj/q6TCqedTbCeSlg0R6O7XTH7VNMNbWN9DRAQoYaGo86tlroAOU0HzUu9gERDzqm/qod5Xhf3V1LqBh/9O4DLjSuAyB2AiIjUFsAwA "APL (Dyalog Classic) – Try It Online") based on [Erik the Outgolfer's solution](https://codegolf.stackexchange.com/questions/148206/the-quantum-drunkards-walk/#answer-148376) `⍪1` is a 1x1 matrix containing 1 `⎕` eval'ed input `( )⍣⎕` apply that many times * `(⌽0,⍉)⍣4` surround with 0s, that is 4 times do: transpose (`⍉`), add 0s on the left (`0,`), reverse horizontally (`⌽`) * `g←3+/0,,∘0` a function that sums horizontal triples, call it `g` * `⍉∘g∘⍉` a function that sums vertical triples - that's `g` under transposition * `2 | ⍉∘g∘⍉ + g←3+/0,,∘0` sum of the two sums modulo 2 * `⌈` the greater between that and ... * `2∘∧` the LCM of 2 and the original matrix - this turns 1s into 2s, while preserving 0s and 2s [Answer] # [Perl 5](https://www.perl.org/), 192 + 1 (`-n`) = 193 bytes ``` for$i(1..2*$_+1){push@a,[()x$_]}$a[$_][$_]=1;map{@b=();for$i(0..$#a){map$b[$i][$_]=$a[$i][$_]?2:$a[$i-1][$_]+($_&&$a[$i][$_-1])+$a[$i+1][$_]+$a[$i][$_+1]==1?1:0,0..$#a}@a=@b}1..$_;say@$_ for@a ``` [Try it online!](https://tio.run/##PU7RCoMwDPyVwYK0q5Zm4ItS7A/sC2SUCBsTNi26wYb46@uqHT6E5O5y3LnLcM@9v/YDtAylPB7ACuSTe403Q2nN@BvseQaqw1pGY/kgN5lGM15Gm5IS9sSnwENTQxv/Fks8q2OxggxXKBjYJNnkwHKxIvHXNykQWmOFhUpjxmxIm2YOPcGWI30M2F3oYMj7/Nu7Z9t3o89OuVSofNb9AA "Perl 5 – Try It Online") Uses 0 for empty, 1 for awake, and 2 for asleep. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~164~~ 153 bytes ``` ->n{(r=([e=' ']*(l=2*n+1)<<" ")*l)[n+n*l+=1]=a=?@ n.times{r=r.map.with_index{|c,i|c==a ??#:c==e ?r.values_at(i-1,i+1,i-l,i+l).one?{|v|v==a}?a:e:c}} r*""} ``` [Try it online!](https://tio.run/##HYtBbsMgFET3nOKLLGxjjOKk6sLKL72HZUXUJQoSoRHGbivg7C7qYjRvNDN@/fjdb7h3by7WHutRYwXVxGqLJ@bavrlcKKENs83oWsdsi/2ECuU7cSKYh16iRy8e6im@TbhfjfvUPzHN3KQZUYGUh6GABunFpuyql6sKtel6btqizha3jfhyWsa0pa18slSDHuaciWeU5j3oJSyAMB459BxOHM4cXguX/HKcyH8vtJrvEFNI8FzLnDo8xJApv41h4lWVyf4H "Ruby – Try It Online") Uses " " for Empty, "@" for Awake, and "#" for Sleeping (as in the example). I could save 6 bytes by using numbers instead, I suppose, but it looks better like this. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~69~~ 61 bytes 60 bytes of code, +1 for `-l` flag. ``` YZG2*a+1y@a@a:1LaY{y@a@b?2oN(y@(a+_)@(b+B)MP[0o0v0])=1}MC#yy ``` Takes `n` as a command-line argument. Uses `0` for empty, `1` for awake, and `2` for sleeping. (To get nicer ASCII-art as in the challenge's examples, replace the final `y` with `" @#"@y`.) [Try it online!](https://tio.run/##K8gs@P8/MsrdSCtR27DSIdEh0crQJzGyGsRMsjfK99OodNBI1I7XdNBI0nbS9A2INsg3KDOI1bQ1rPV1Vq6s/P//v27OfzMA "Pip – Try It Online") ### Explanation Setup: ``` YZG2*a+1y@a@a:1 Implicit: a is 1st cmdline arg; o is 1; v is -1 ZG2*a+1 Square grid (i.e. nested list) of 0's, with side length 2*a+1 Y Yank into y variable y@a@a:1 Set the element at coordinates (a,a) to 1 ``` Main loop: ``` LaY{...}MC#y La Loop (a) times: #y Len(y) (i.e. 2*a+1) { }MC Map this function to the coordinate pairs in a 2*a+1 by 2*a+1 grid Y and yank the resulting nested list back into y ``` where the function body is: ``` y@a@b?2oN(y@(a+_)@(b+B)MP[0o0v0])=1 The function args, representing the coords of the current cell, are a and b y@a@b? Is the cell at these coords 0 or nonzero? 2 If nonzero (1 or 2), make it 2 Else, if zero, we need to check the neighbors [0o0v0] List of [0; 1; 0; -1; 0] MP Map this function to each adjacent pair of values-- i.e. call it four times with args (0; 1), (1; 0), (0; -1), and (-1; 0) y Index into the grid using @(a+_) a + the 1st item in the pair as the row and @(b+B) b + the 2nd item in the pair as the column The result of MP is a list of the values of the cells in the Von Neumann neighborhood oN( ) Get the number of 1's in that list =1 and test if it equals 1 If so, the new value of this cell is 1; if not, it's 0 ``` After the loop, we simply autoprint `y`. The `-l` flag means that the nested list is printed by concatenating the contents of each row and separating the rows with newlines. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 220 bytes ``` n->{int s=n*2+3,i=0,x,y;char[][]a=new char[s][s],b;for(a[s/2][s--/2]=61;i++<n;a=b)for(b=new char[s+1][s+1],x=0;++x<s;)for(y=0;++y<s;)b[x][y]=a[x][y]>32?'0':(a[x][y-1]+a[x][y+1]+a[x-1][y]+a[x+1][y])%8==5?61:' ';return a;} ``` [Try it online!](https://tio.run/##dVHLbsIwELzzFSukilAnKQEVVTiGW6Ueeuox@OBAANPgRLFDYyG@ndp50FRVJds74514dydHdmZelifiuP285WWc8g1sUiYlvDMu4DIAaG@lYsqEc8a3cDI550MVXOwjCqzYy3EtBTia9/xS8dTflWKjeCb8N6FeWxxuDqyIaESXsANyE97ywoUCScTjFM1cTiZu5WrcqRgRyRfUTFKz3BjvssJhkXyaGu55JpB5gDlCocCMxGObjntfoYDWh1uRCUaoCiWuNbqm2tI4qmikKWFNXM6mq9FktHAa7gUUNQg1yFwYlUWoRuOHF0KeV/NgMYIRLhJVFgIYvt5w7YcpBo6dkQOBCTYhJBBYgFDnGUA3MDCj2vksz1Pt8DFu07kxWjnszj@0VMnJz0rl16lUOMO1WIthq7gO7DZH/581j/xU6qpbO2yDFQkwVBAC89NE7NXBs7zfZafUVqmt0hjTE@u@@G@XraP0Psb1/3F@DXK9fQM "Java (OpenJDK 8) – Try It Online") Note: the array returned contains a border or `'\0'` characters. Since the plane is supposed to be infinite, only non-border is used. Character mapping: * Empty: (space) * Awake: `=` * Sleeping: `0` ## Saves * 29 bytes saved thanks to Jonathan S. * 9 further bytes thanks to Jonathan S. by swapping characters with others and "doing magic with primes and modular arithmetic" [Answer] # Python, ~~199~~ 192 bytes This code runs on both Python 2 and Python 3, but it uses the popular 3rd-party Numpy library to do the array handling. ``` from numpy import* def f(n): m=2*n+1;g=zeros((m+2,)*2,'i');g[n+1,n+1]=1 while n:a=g[1:-1,1:-1];a[:]=(a<1)*(sum(g[r:r+m,c:c+m]&1for r,c in((0,1),(1,0),(1,2),(2,1)))==1)+(a>0)*2;n-=1 return g ``` > > Empty = 0 > > Awake = 1 > > Sleeping = 2 > > > `print(f(6))` outputs ``` [[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 2 0 0 0 0 0 0 0] [0 0 0 0 0 1 2 2 2 1 0 0 0 0 0] [0 0 0 0 0 0 1 2 1 0 0 0 0 0 0] [0 0 0 1 0 0 2 2 2 0 0 1 0 0 0] [0 0 0 2 1 2 0 2 0 2 1 2 0 0 0] [0 1 2 2 2 2 2 2 2 2 2 2 2 1 0] [0 0 0 2 1 2 0 2 0 2 1 2 0 0 0] [0 0 0 1 0 0 2 2 2 0 0 1 0 0 0] [0 0 0 0 0 0 1 2 1 0 0 0 0 0 0] [0 0 0 0 0 1 2 2 2 1 0 0 0 0 0] [0 0 0 0 0 0 0 2 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]] ``` If you want prettier printing, you can call it this way: ``` n=6;print('\n'.join(''.join(' @#'[v]for v in u)for u in f(n))) ``` which prints using the same characters as given in the question. ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. > > Is it possible to write a C program that multiplies two numbers without using the multiplication and addition operators? > > > I found [this on Stack Overflow](https://stackoverflow.com/questions/21064911/how-to-write-a-c-program-for-multiplication-without-using-and-operator). Please help this poor programmer with his problem. And please don't give answers like `c = a/(1/((float)b))`, which is exactly the same as `c = a*b`. (And is already given as an answer.) The answer with the most upvotes on January 19th 2014 wins. Note: This is a [code-trolling](/questions/tagged/code-trolling "show questions tagged 'code-trolling'") question. Please do not take the question and/or answers seriously. More information is in *[code-trolling](https://codegolf.stackexchange.com/tags/code-trolling/info)*. [Answer] ## Always use recursion Recusion is the right way! ``` int inc(int x) { return x&1?inc(x>>1)<<1:x|1; } int dec(int x) { return x&1?x^1:dec(x>>1)<<1|1; } int add(int x, int y) { return x?add(dec(x),inc(y)):y; } int mul(int x, int y) { return x?x^1?add(y,mul(dec(x),y)):y:0; } int main() { int a, b; scanf("%i\n%i", &a, &b); printf("%i", mul(a,b)); } ``` [Answer] You'll have to compile the program each time, but it does do multiplication of any positive integers exactly in any version of C or C++. ``` #define A 45 // first number #define B 315 // second number typedef char buffer[A][B]; main() { printf("%d\n",sizeof(buffer)); } ``` [Answer] If you are OK with a little imprecision, you can use the [Monte Carlo method](http://en.wikipedia.org/wiki/Monte_Carlo_method): ``` #include <stdlib.h> #include <stdio.h> unsigned int mul(unsigned short a, unsigned short b) { const int totalBits = 24; const int total = (1 << totalBits); const int maxNumBits = 10; const int mask = (1 << maxNumBits) - 1; int count = 0, i; unsigned short x, y; for(i = 0; i < total; i++) { x = random() & mask; y = random() & mask; if ((x < a) && (y < b)) count++; } return ((long)count) >> (totalBits - (maxNumBits << 1)); } void main(int argc, char *argv[]) { unsigned short a = atoi(argv[1]); unsigned short b = atoi(argv[2]); printf("%hd * %hd = %d\n", a, b, mul(a, b)); } ``` Example: ``` $ ./mul 300 250 300 * 250 = 74954 ``` I guess this could be good enough ;) [Answer] Since you didn't specify what size of number, I assume that you mean two one-bit numbers. ``` #include <stdbool.h> bool mul(bool a, bool b) { if (a && b) { return true; } else { return false; } } ``` If you want a maximally-efficient implementation, use the following tiny implementation: ``` m(a,b){return a&b;} ``` Note that it still only accepts bits even though the types are implicit ints - it takes less code, and is therefore more efficient. (And yes, it does compile.) [Answer] Here's a simple shell script to do it: ``` curl "http://www.bing.com/search?q=$1%2A$2&go=&qs=n&form=QBLH&pq=$1%2A$2" -s \ | sed -e "s/[<>]/\n/g" \ | grep "^[0-9 *]*=[0-9 ]*$" ``` UPDATE: Of course, to do it in C, just wrap it in `exec("bash", "-c", ...)`. (Thanks, AmeliaBR) [Answer] Why, let's do a recursive halving search between INT64\_MIN and INT64\_MAX! ``` #include <stdio.h> #include <stdint.h> int64_t mul_finder(int32_t a, int32_t b, int64_t low, int64_t high) { int64_t result = (low - (0 - high)) / 2; if (result / a == b && result % a == 0) return result; else return result / a < b ? mul_finder(a, b, result, high) : mul_finder(a, b, low, result); } int64_t mul(int32_t a, int32_t b) { return a == 0 ? 0 : mul_finder(a, b, INT64_MIN, INT64_MAX); } void main(int argc, char* argv[]) { int32_t a, b; sscanf(argv[1], "%d", &a); sscanf(argv[2], "%d", &b); printf("%d * %d = %ld\n", a, b, mul(a, b)); } ``` P.S. It will happily sigsegv with some values. ;) [Answer] Unfortunately, this only works for integers. Since addition is disallowed, let's build an increment operator first: ``` int plusOne(int arg){ int onMask = 1; int offMask = -1; while (arg & onMask){ onMask <<= 1; offMask <<= 1; } return(arg & offMask | onMask); } ``` Next, we have to handle the sign. First, find the sign bit: ``` int signBit = -1; while(signBit << 1) signBit <<=1; ``` Then take the sign and magnitude of each argument. To negate a number in a two's complement, invert all bits, and add one. ``` int signA = a & signBit; if(signA) a = plusOne(-1 ^ a); int signB = b & signBit; if(signB) b = plusOne(-1 ^ b); int signRes = signA ^ signB; ``` To multiply two positive integers, we can use the geometrical meaning of multiplication: ``` // 3x4 // // ooo // ooo // ooo // ooo int res = 0; for(int i = 0; i < a; i = plusOne(i)) for(int j = 1; j < b; j = plusOne(j)) res = plusOne(res); if(signRes) res = plusOne(-1 ^ res); ``` --- trolls: * Addition is disallowed, but does `a++` really count as addition? I bet the teacher intended to allow it. * Relies on two's complement, but that's an implementation-defined behavior and the target platform wasn't specified. * Similarly, assumes subtraction and division are disallowed just as well. * `<<` is actually multiplication by a power of two, so it should technically be disallowed. * unneccesary diagram is unneccesary. Also, it could have been transposed to save one line. * repeated shifting of `-1` is not the nicest way of finding the sign bit. Even if there was no built-in constant, you could do a logical shift right of -1, then invert all bits. * XOR -1 is a not the best way to invert all bits. * The whole charade with sign-magnitude representation is unneccesary. Just cast to unsigned and modular arithmetic will do the rest. * since the absolute value of `MIN_INT` (AKA `signBit`) is negative, this breaks for that value. Luckily, it still works in half the cases, because `MIN_INT * [even number]` *should* be zero. ~~Also, `plusOne` breaks for `-1`, causing infinite loops anytime the result overflows.~~ `plusOne` works just fine for any value. Sorry for the confusion. [Answer] Works for floating point numbers as well: ``` float mul(float a, float b){ return std::exp(std::log(a) - std::log(1.0 / b)); } ``` [Answer] Everyone knows that Python is easier to use than C. And Python has functions corresponding to every operator, for cases where you can't use the operator. Which is exactly our problem definition, right? So: ``` #include <Python.h> void multiply(int a, int b) { PyObject *operator_name, *operator, *mul, *pa, *pb, *args, *result; int result; operator_name = PyString_FromString("operator"); operator = PyImport_Import(operator_name); Py_DECREF(operator_name); mul = PyObject_GetAttrString(operator, "__mul__"); pa = PyLong_FromLong((long)a); pb = PyLong_FromLong((long)b); args = PyTuple_New(2); PyTuple_SetItem(args, 0, pa); PyTuple_SetItem(args, 1, pb); presult = PyObject_CallObject(mul, args); Py_DECREF(args); Py_DECREF(mul); Py_DECREF(operator); result = (int)PyLong_AsLong(presult); Py_DECREF(presult); return result; } int main(int argc, char *argv[]) { int c; Py_Initialize(); c = multiply(2, 3); printf("2 * 3 = %d\n", c); Py_Finalize(); } ``` [Answer] None of the other answers are theoretically sound. As the very first comment on the question says: > > Please be more specific about "numbers" > > > We need to define multiplication, and numbers, before an answer is even possible. Once we do, the problem becomes trivial. The most popular way to do this in beginning mathematical logic is to [build von Neumann ordinals on top of ZF set theory](http://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers#The_contemporary_standard), and then use the [Peano axioms](http://en.wikipedia.org/wiki/Peano_axioms). This translates naturally to C, assuming you have a set type that can contain other sets. It doesn't have to contain anything *but* sets, which makes it trivial (none of that casting `void*` nonsense in most set libraries), so I'll leave the implementation as an exercise for the reader. So, first: ``` /* The empty set is 0. */ set_t zero() { return set_new(); } /* The successor of n is n U {n}. */ set_t successor(set_t n) { set_t result = set_copy(n); set_t set_of_n = set_new(); set_add(set_of_n, n); set_union(result, set_of_n); set_free(set_of_n); return result; } /* It is an error to call this on 0, which will be reported by running out of memory. */ set_t predecessor(set_t n) { set_t pred = zero(); while (1) { set_t next = successor(pred); if (set_equal(next, n)) { set_free(next); return pred; } set_free(pred); } } set_t add(set_t a, set_t b) { if (set_empty(b)) { /* a + 0 = a */ return a; } else { /* a + successor(b) = successor(a+b) */ set_t pred_b = predecessor(b) set_t pred_ab = add(a, pred_b); set_t result = successor(pred_ab); set_free(pred_b); set_free(pred_ab); return result; } } set_t multiply(set_t a, set_t b) { if (set_empty(b)) { /* a * 0 = 0 */ return b; } else { /* a * successor(b) = a + (a * b) */ set_t pred_b = predecessor(b) set_t pred_ab = mul(a, pred_b); set_t result = successor(pred_ab); set_free(pred_b); set_free(pred_ab); return result; } } ``` If you want to expand this to integers, rationals, reals, surreals, etc., you can—with infinite precision (assuming you have infinite memory and CPU), to boot. But as Kroenecker famously said, God made the natural numbers; all else is the work of man, so really, why bother? [Answer] ``` unsigned add( unsigned a, unsigned b ) { return (unsigned)&((char*)a)[b]; // ignore compiler warnings // (if pointers are bigger than unsigned). it still works. } unsigned umul( unsigned a, unsigned b ) { unsigned res = 0; while( a != 0 ){ if( a & 1) res = add( res, b ); b <<= 1; a >>= 1; } return res; } int mul( int a, int b ){ return (int)umul( (unsigned)a, (unsigned)b ); } ``` If you consider the a[b] hack to be cheating (since it's really an add) then this works instead. But table lookups involve pointer adds too. See <http://en.wikipedia.org/wiki/IBM_1620> - a conputer that actually did addition using lookup tables... Something satisfying about using a table mechanism to 'speed up' an operation that could actually be done in one instruction. ``` static unsigned sumtab[17][16]= { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15}, { 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16}, { 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17}, { 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18}, { 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19}, { 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20}, { 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21}, { 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22}, { 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23}, { 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}, {10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, {11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26}, {12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27}, {13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28}, {14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29}, {15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30}, {16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31} }; unsigned add( unsigned a, unsigned b ) { static const int add4hack[8] = {4,8,12,16,20,24,28,32}; unsigned carry = 0; unsigned (*sumtab0)[16] = &sumtab[0]; unsigned (*sumtab1)[16] = &sumtab[1]; unsigned result = 0; int nshift = 0; while( (a|b) != 0 ){ unsigned psum = (carry?sumtab1:sumtab0)[ a & 0xF ][ b & 0xF ]; result = result | ((psum & 0xF)<<nshift); carry = psum >> 4; a = a >> 4 b = b >> 4; nshift= add4hack[nshift>>2]; // add 4 to nshift. } return result; } ``` [Answer] I'm not sure what constitutes "cheating" in these "code troll" posts, but this multiplies 2 arbitrary integers, at run time, with no `*` or `+` operator using standard libraries (C99). ``` #include <math.h> main() { int a = 6; int b = 7; return fma(a,b,0); } ``` [Answer] My troll solution for `unsigned int`: ``` #include<stdio.h> unsigned int add(unsigned int x, unsigned int y) { /* An addition of one bit corresponds to the both following logical operations for bit result and carry: r = x xor y xor c_in c_out = (x and y) or (x and c_in) or (y and c_in) However, since we dealing not with bits but words, we have to loop till the carry word is stable */ unsigned int t,c=0; do { t = c; c = (x & y) | (x & c) | (y & c); c <<= 1; } while (c!=t); return x^y^c; } unsigned int mult(unsigned int x,unsigned int y) { /* Paper and pencil method for binary positional notation: multiply a factor by one (=copy) or zero depending on others factor actual digit at position, and shift through each position; adding up */ unsigned int r=0; while (y != 0) { if (y & 1) r = add(r,x); y>>=1; x<<=1; } return r; } int main(int c, char** param) { unsigned int x,y; if (c!=3) { printf("Fuck!\n"); return 1; } sscanf(param[1],"%ud",&x); sscanf(param[2],"%ud",&y); printf("%d\n", mult(x,y)); return 0; } ``` [Answer] There are a lot of good answers here, but it doesn't look like many of them take advantage of the fact that modern computers are really powerful. There are multiple processing units in most CPUs, so why use just one? We can exploit this to get great performance results. ``` #include <stdio.h> #include <limits.h> #include "omp.h" int mult(int a, int b); void main(){ int first; int second; scanf("%i %i", &first, &second); printf("%i x %i = %i\n", first, second, mult(first,second)); } int mult(int second, int first){ int answer = INT_MAX; omp_set_num_threads(second); #pragma omp parallel for(second = first; second > 0; second--) answer--; return INT_MAX - answer; } ``` Here's an example of its usage: ``` $ ./multiply 5 6 5 x 6 = 30 ``` The `#pragma omp parallel` directive makes OpenMP divide each part of the for loop to a different execution unit, so we're multiplying in parallel! Note that you have to use the `-fopenmp` flag to tell the compiler to use OpenMP. --- Troll parts: 1. Misleading about the use of parallel programming. 2. Doesn't work on negative (or large) numbers. 3. Doesn't actually divide the parts of the `for` loop - each thread runs the loop. 4. Annoying variable names and variable reuse. 5. There's a subtle race condition on `answer--`; most of the time, it won't show up, but occasionally it will cause inaccurate results. [Answer] Unfortunately, multiplication is a very difficult problem in computer science. The best solution is to use division instead: ``` #include <stdio.h> #include <limits.h> int multiply(int x, int y) { int a; for (a=INT_MAX; a>1; a--) { if (a/x == y) { return a; } } for (a=-1; a>INT_MIN; a--) { if (a/x == y) { return a; } } return 0; } main (int argc, char **argv) { int a, b; if (argc > 1) a = atoi(argv[1]); else a = 42; if (argc > 2) b = atoi(argv[2]); else b = 13; printf("%d * %d is %d\n", a, b, multiply(a,b)); } ``` [Answer] In real life I usually respond to trolling with knowledge, so here's an answer that doesn't troll at all. It works for all `int` values as far as I can see. ``` int multiply (int a, int b) { int r = 0; if (a < 0) { a = -a; b = -b } while (a) { if (a&1) { int x = b; do { int y = x&r; r ^= x; x = y<<1 } while (x); } a>>=1; b<<=1; } return r; } ``` This is, to the best of my understanding, very much like how a CPU might actually do integer multiplication. First, we make sure that at least one of the arguments (`a`) is positive by flipping the sign on both if `a` is negative (and no, I refuse to count negation as a kind of either addition or multiplication). Then the `while (a)` loop adds a shifted copy of `b` to the result for every set bit in `a`. The `do` loop implements `r += x` using and, xor, and shifting in what's clearly a set of half-adders, with the carry bits fed back into `x` until there are no more (a real CPU would use full adders, which is more efficient, but C doesn't have the operators we need for this, unless you count the `+` operator). [Answer] ``` int bogomul(int A, int B) { int C = 0; while(C/A != B) { print("Answer isn't: %d", C); C = rand(); } return C; } ``` [Answer] Throwing this into the mix: ``` #include <stdio.h> #include <stdlib.h> int mul(int a, int b) { asm ("mul %2" : "=a" (a) : "%0" (a), "r" (b) : "cc" ); return a; } int main(int argc, char *argv[]) { int a, b; a = (argc > 1) ? atoi(argv[1]) : 0; b = (argc > 2) ? atoi(argv[2]) : 0; return printf("%d x %d = %d\n", a, b, mul(a, b)) < 1; } ``` --- [From info page](https://codegolf.stackexchange.com/tags/code-trolling/info). *– Introducing something extremely unacceptable or unreasonable in the code that cannot be removed without throwing everything away, rendering the answer utterly useless for the OP.* *– […] The intention is to do the homework in a language that the lazy OP might think acceptable, but still frustrate him.* [Answer] ``` #include <stdio.h> #include <stdlib.h> int mult (int n1, int n2); int add (int n1, int n2 ); int main (int argc, char** argv) { int a,b; a = atoi(argv[1]); b = atoi(argv[2]); printf ("\n%i times %i is %i\n",a,b,mult(a,b)); return 0; } int add (int n1, int n2 ) { return n1 - -n2; } int mult (int n1, int n2) { int sum = 0; char s1='p', s2='p'; if ( n1 == 0 || n2 == 0 ) return 0; if( n1 < 0 ) { s1 = 'n'; n1 = -n1; } if( n2 < 0 ) { s2 = 'n'; n2 = -n2; } for (int i = 1; i <= n2; i = add( i, 1 )) { sum = add(sum, n1); } if ( s1 != s2 ) sum = -sum; return sum; } ``` [Answer] > > Is it possible to write a C program that multiplies two numbers without using the multiplication and addition operators? > > > Sure: ``` void multiply() { printf("6 times 7 is 42\n"); } ``` But of course that's cheating; obviously he wants to be able to \_supply) two numbers, right? ``` void multiply(int a, int b) { int answer = 42; if (answer / b != a || answer % b) { printf("The answer is 42, so that's the wrong question.\n"); } else { printf("The answer is 42, but that's probably not the right question anyway.\n"); } } ``` [Answer] There's no arithmetic like pointer arithmetic: ``` int f(int a, int b) { char x[1][b]; return x[a] - x[0]; } int main(int ac, char **av) { printf("%d\n", f(atoi(av[1]),atoi(av[2]))); return 0; } ``` The function `f` implements multiplication. `main` simply calls it with two arguments. Works for negative numbers as well. [Answer] # C# I think subtraction and negation are not allowed... Anyway: ``` int mul(int a, int b) { int t = 0; for (int i = b; i >= 1; i--) t -= -a; return t; } ``` [Answer] C with SSE intrinsics (because everything's better with SIMD): ``` #include <stdio.h> #include <stdlib.h> #include <xmmintrin.h> static float mul(float a, float b) { float c; __m128 va = _mm_set1_ps(a); __m128 vb = _mm_set1_ps(b); __m128 vc = _mm_mul_ps(va, vb); _mm_store_ss(&c, vc); return c; } int main(int argc, char *argv[]) { if (argc > 2) { float a = atof(argv[1]); float b = atof(argv[2]); float c = mul(a, b); printf("%g * %g = %g\n", a, b, c); } return 0; } ``` The big advantage of this implementation is that it can easily be adapted to perform 4 parallel multiplications without `*` or `+` if required. [Answer] ``` #include <stdio.h> #include <string.h> #include <stdlib.h> #define INF 1000000 char cg[INF]; int main() { int a, b; char bg[INF]; memset(bg, '*', INF); scanf("%d%d", &a, &b); bg[b] = 0; while(a--) strcat(cg, bg); int result; printf("%s%n",cg,&result); printf("%d\n", result); return 0; } ``` * work only for multiplication result < 1 000 000 * So far can't get rid out of -- operator, possibly enhancing here * using %n format specifier in printf to count the number printed characters(I posting this mainly to remind of existence %n in C, instead of %n could of course be strlen etc.) * Prints a\*b characters of '\*' [Answer] Probably too fast :-( ``` unsigned int add(unsigned int a, unsigned int b) { unsigned int carry; for (; b != 0; b = carry << 1) { carry = a & b; a ^= b; } return a; } unsigned int mul(unsigned int a, unsigned int b) { unsigned int prod = 0; for (; b != 0; a <<= 1, b >>= 1) { if (b & 1) prod = add(prod, a); } return prod; } ``` [Answer] This Haskell version only works with nonnegative integers, but it does the multiplication the way children first learn it. I.e., 3x4 is 3 groups of 4 things. In this case, the "things" being counted are notches ('|') on a stick. ``` mult n m = length . concat . replicate n . replicate m $ '|' ``` [Answer] ``` int multiply(int a, int b) { return sizeof(char[a][b]); } ``` This may work in C99, if the weather is right, and your compiler supports undefined nonsense. [Answer] Since [the OP didn't ask for C](https://codegolf.stackexchange.com/a/18366/14150), here's one in (Oracle) SQL! ``` WITH aa AS ( SELECT LEVEL AS lvl FROM dual CONNECT BY LEVEL <= &a ), bb AS ( SELECT LEVEL AS lvl FROM dual CONNECT BY LEVEL <= &b ) SELECT COUNT(*) AS addition FROM (SELECT * FROM aa UNION ALL SELECT * FROM bb); WITH aa AS ( SELECT LEVEL AS lvl FROM dual CONNECT BY LEVEL <= &a ), bb AS ( SELECT LEVEL AS lvl FROM dual CONNECT BY LEVEL <= &b ) SELECT COUNT(*) AS multiplication FROM aa CROSS JOIN bb; ``` [Answer] ``` int add(int a, int b) { return 0 - ((0 - a) - b); } int mul(int a, int b) { int m = 0; for (int count = b; count > 0; m = add(m, a), count = add(count, 0 - 1)) { } return m; } ``` May contain traces of UD. [Answer] ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { int x = atoi(argv[1]); int y = atoi(argv[2]); FILE *f = fopen("m","wb"); char *b = calloc(x, y); if (!f || !b || fwrite(b, x, y, f) != y) { puts("503 multiplication service is down for maintenance"); return EXIT_FAILURE; } printf("%ld\n", ftell(f)); fclose(f); remove("m"); return 0; } ``` Test run: ``` $ ./a.out 1 0 0 $ ./a.out 1 1 1 $ ./a.out 2 2 4 $ ./a.out 3 2 6 $ ./a.out 12 12 144 $ ./a.out 1234 1234 1522756 ``` ]
[Question] [ **In:** Enough memory and a positive integer N **Out:** N-dimensional N^N array filled with N, where N^N means N terms of N-by-N-by-N-by... **Examples:** 1: `[1]` which is a 1D array (a list) of length 1, containing a single 1 2: `[[2,2],[2,2]]` which is a 2D array (a table) with 2 rows and 2 columns, filled with 2s 3: `[[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]]` which is a 3D array (a cube) with 3 layers, 3 rows, and 3 columns, filled with 3s 4: `[[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]],[[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]],[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]]]` 5 and 6: Please see one of the answers. [Answer] # [Python](https://docs.python.org/2/), 32 bytes ``` lambda n:eval('['*n+'n'+']*n'*n) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQZ5ValpijoR6trpWnrZ6nrq0eq5UHZGv@T8svUkhWyMxTMNQx0jG24uIsKMrMK1FI00jW/A8A "Python 2 – TIO Nexus") Makes a string like `"[[[n]*n]*n]*n"` with `n` multiplcations, and evaluates it as Python code. Since the evaluation happens within the function scope, the variable name `n` evaluates to the function input. [Answer] # J, 4 bytes ``` $~#~ ``` [Try it online!](https://tio.run/nexus/j#@5@mYGuloFKnXMfFlZqcka@QpmD8/z8A "J – TIO Nexus") ## Explanation ``` $~#~ Input: integer n #~ Create n copies of n $~ Shape n into an array with dimensions n copies of n ``` [Answer] # [APL (Dyalog APL)](https://www.dyalog.com/), 4 bytes ``` ⍴⍨⍴⊢ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@5@m8KhtgsKj3i2PeleAyK5FXFyP@qaCRdMUDJHYRkhsYyS2yf//AA "APL (Dyalog APL) – TIO Nexus") [Answer] # Mathematica, ~~22~~ 20 bytes ``` (t=Table)@@t[#,#+1]& (* or *) Table@@Table[#,#+1]& ``` [Answer] ## JavaScript (ES6), ~~44~~ 40 bytes ``` f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k ``` ### Demo ``` f=(n,k=i=n)=>i--?f(n,Array(n).fill(k)):k console.log(JSON.stringify(f(1))) console.log(JSON.stringify(f(2))) console.log(JSON.stringify(f(3))) console.log(JSON.stringify(f(4))) ``` [Answer] # Octave, ~~35~~ ~~33~~ ~~25~~ ~~23~~ 20 bytes ``` @(N)ones(N+!(1:N))*N ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aeZn5darOGnrahhaOWnqanl9z8xr1jDWPM/AA "Octave – TIO Nexus") ``` @(N)ones(N*ones(1,N))*N @(N)repmat(N,N*ones(1,N)) ``` Thanks to @LuisMendo saved 8 bytes ``` @(N)ones(num2cell(!(1:N)+N){:})*N ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aeZn5darJFXmmuUnJqTo6GoYWjlp6ntp1ltVaup5fc/Ma9Yw1jzPwA "Octave – TIO Nexus") Previous answer: ``` @(N)repmat(N,num2cell(!(1:N)+N){:}) ``` [Try it online!](https://tio.run/nexus/octave#@@@g4adZlFqQm1ii4aeTV5prlJyak6OhqGFo5aep7adZbVWr@T8xr1jDWPM/AA "Octave – TIO Nexus") [Answer] # R, 26 This is the obvious answer but perhaps there is something cleverer? ``` n=scan();array(n,rep(n,n)) ``` [Answer] # [Haskell](https://www.haskell.org/), 52 bytes ``` f n=iterate(filter(>'"').show.(<$[1..n]))(show n)!!n ``` [Try it online!](https://tio.run/nexus/haskell#FchBCoAgEAXQq3xDcGYzEG2zi0QLKSWhJiih41vuHu8MWeGRtcQ7rAUWCYI7hq0mqM@tS6SUj180uc6xPPv1Co127kV0YaYWUDZGax0@ "Haskell – TIO Nexus") Inspired by [@nimi's answer](https://codegolf.stackexchange.com/a/111700), but using more predefined functions. * Uses `iterate` and `!!` instead of a recursive help function. * Instead of constructing list delimiters "by hand", uses `filter(>'"').show` to format a list of strings, then stripping away the extra `"` characters. [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~6~~ 5 bytes -1 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` F¹.D) ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f7dBOPRfN//@NAQ "05AB1E (legacy) – Try It Online") ``` F # For 0 .. input ¹.D) # Push <input> copies of the result of the last step as an array ``` [Answer] ## Haskell, 62 bytes ``` n#0=show n n#l='[':tail((',':)=<<n#(l-1)<$[1..n])++"]" f n=n#n ``` Usage example: `f 2` -> `"[[2,2],[2,2]]"`. [Try it online!](https://tio.run/nexus/haskell#FcqxDkAwFAXQ3Ve8qKRt0BCb9P0Bk1E6dBGSuoSKz68480kQDd/r8RIyiMByln30W1BKVrLXbC2ECnWrbTG3xsDpssxdni0EhkDa/QZi2v05kjqfOMVrgFk0/btzlD4 "Haskell – TIO Nexus"). Haskell's strict type system prevents a function that returns nested lists of different depths, so I construct the result as a string. How it works: ``` n#l= n with the current level l is '[': a literal [ followed by n#(l-1)<$[1..n] n copies of n # (l-1) (',':)=<< each prepended by a , and flattened into a single list tail and the first , removed ++"]" followed by a literal ] n#0=show n the base case is n as a string f n=n#n main function, start with level n ``` [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes -2 bytes thanks to @CalculatorFeline ``` a=n=input() exec"a=[a]*n;"*n print a ``` [Try it online!](https://tio.run/nexus/python2#@59om2ebmVdQWqKhyZVakZqslGgbnRirlWetpJX3v6AoM69EI1HzvwkA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁾Wẋẋv ``` **[Try it online!](https://tio.run/nexus/jelly#@/@ocV/4w13dQFT2//9/EwA "Jelly – TIO Nexus")** ### How? ``` ⁾Wẋẋv - Main link: n e.g. 3 ⁾Wẋ - character pair literal ['W','ẋ'] "Wẋ" ẋ - repeat list n times "WẋWẋWẋ" v - evaluate as Jelly code with input n eval("WẋWẋWẋ", 3) - ... WẋWẋ... - toEval: n e.g. 3 W - wrap [3] ẋ - repeat list n times [3,3,3] Wẋ - wrap and repeat [[3,3,3],[3,3,3],[3,3,3]] ... - n times total [[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]],[[3,3,3],[3,3,3],[3,3,3]]] ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` R»µ¡ ``` [Try it online!](https://tio.run/##y0rNyan8/z/o0O5DWw8t/P//vzEA "Jelly – Try It Online") ``` R»µ¡ R Range. 2 -> [1, 2] » Max between left arg and right arg. Vectorizes. -> [2, 2] µ Separates into a new chain. ¡ Repeat 2 times. After another iteration this yields [[2, 2], [2, 2]]. ``` Same thing but with a single monad and no need for the chain separator: [**4 bytes**](https://tio.run/##y0rNyan8///Q7kdNaxIOLfz//78xAA) ``` »€`¡ ``` [Answer] # MATL, 8 bytes ``` ttY"l$l* ``` Try it at [**MATL Online**](https://matl.io/?code=ttY%222%24X%22%0A%0A%27Actual+Size%27yZy++++%25+Display+the+actual+size&inputs=4&version=19.8.0) (I have added some code showing the *actual* size of the output since all n-dimensional outputs in MATL are shown as 2D matrices where all dimensions > 2 are flattened into the second dimension). **Explanation** ``` % Implicitly grab the input (N) tt % Make two copies of N Y" % Perform run-length decoding to create N copies of N l$1 % Create a matrix of ones that is this size * % Multiply this matrix of ones by N % Implicitly display the result ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` ri:X{aX*}X*p ``` [Try it online!](https://tio.run/nexus/cjam#@1@UaRVRnRihVRuhVfD/vzEA "CJam – TIO Nexus") **Explanation** ``` ri:X Read an integer from input, store it in X (leaves it on the stack) { }X* Execute this block X times: a Wrap the top of stack in an array X* Repeat the array X times p Print nicely ``` [Answer] # Java ~~97~~ ~~96~~ 95 bytes ``` Object c(int n,int i){Object[]a=new Object[n];for(int j=0;j<n;)a[j++]=i<2?n:c(n,i-1);return a;} ``` --- Ungolfed: ``` public class N_Dim { public static Object create(int n) { return create(n, n); } public static Object create(int n, int i) { Object[] array = new Object[n]; for(int j=0;j<n;j++) { array[j] = i<2?n:create(n, i - 1); } return array; } public static void main(String[] args) { System.out.println(Arrays.deepToString((Object[]) create(3))); } } ``` [Answer] ## JavaScript (ES6), 38 bytes ``` f=(n,m=n)=>m?Array(n).fill(f(n,m-1)):n ``` The memory-hungry version of this is 45 bytes: ``` f=(n,m=n)=>m?[...Array(n)].map(_=>f(n,m-1)):n ``` [Answer] ## Batch, 141 bytes ``` @set t=. @for /l %%i in (2,1,%1)do @call set t=%%t%%,. @set s=%1 @for /l %%i in (1,1,%1)do @call call set s=[%%%%t:.=%%s%%%%%%] @echo %s% ``` Batch doesn't actually have arrays so this just prints the string representation of an array. Explanation: The first two lines build up a repeated pattern of `N` `.`s separated by `N-1` `,`s in the variable `t`. The fourth line then uses this as a substitution pattern `N` times to create the `N`-dimensional array. The double `call` is necessary because of how the `for` and `set` statements work. First, the `for` command substitutes variables. As it happens, all of my `%` signs are doubled, so this does nothing except to unquote them all, resulting in `call call set s=[%%t:.=%s%%%]`. It then repeats the resulting statement `N` times. Each time, the `call` command substitutes variables. At this point, the `s` variable only has a single set of `%`s, so it gets substituted, resulting in (e.g.) `call set s=[%t:.=[2,2]%]`. The inner call then substitutes the `t` variable, resulting in (e.g.) `set s=[[2,2],[2,2]]`, performing the desired assignment. The final value of `s` is then printed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Wẋ³µ¡ ``` [Try it online!](https://tio.run/nexus/jelly#@x/@cFf3oc2Hth5a@P//fxMA "Jelly – TIO Nexus") ## Explanation ``` Implicit input: N µ¡ Apply N times to input: Wẋ³ “N copies of” ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~57~~ ~~53~~ ~~50~~ 38 bytes ``` f=lambda n,c=0:n-c and[f(n,c+1)*n]or 1 ``` [Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCnk2xrYJWnm6yQmJcSnaYB5GsbamrlxeYXKRj@z7PNzCvRyMwrKC3R0NTkKigCcYGKNDX/mwAA "Python 3 – TIO Nexus") --- -4 bytes thanks to @CalculatorFeline --- **34 bytes:** ``` f=lambda c,n:c and[f(c-1,n)*n]or 1 ``` Needs to be called as `f(4,4)` [Answer] # Ruby, 28 26 bytes *Thanks to [Cyoce](https://codegolf.stackexchange.com/users/41042/cyoce) for saving 2 bytes!* ``` ->n{eval'['*n+'n'+']*n'*n} ``` Stolen shamelessly from [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [excellent answer](https://codegolf.stackexchange.com/a/111696/58437). [Answer] ## Ruby, 27 bytes ``` ->a{(z=a).times{z=[z]*a};z} ``` Only 1 byte more but using a different approach instead of the 'eval' trick from xnor's wonderful Python answer. [Answer] # [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 117 bytes ``` n=$[$1**$1] seq -f$1o%.fd$n+1-p $n|dc|rev|sed -r "s/(0+|$[$1-1]*).*$/\1/;s/^(0*)/\1$1/;s/^1/[1]/"|tr \\n0$[$1-1] \ [] ``` [Try it online!](https://tio.run/nexus/bash#LcsxDoMwDEDRvaewkJHAKDiWulU9SZIuTRhDm6BOvnsKgu3/4bX8RIdChBJuNX3BLChrPy8R8yTmA5g1vrWkn9YUwRToKg920kMZCTTOhOyFH5Vfg6VxbzxP2EngTrcC3md7AfDgQmvt/gc "Bash – TIO Nexus") --- The program essentially counts from 0 to (n^n)-1 in base n, where n is the input. For each base-n number k in the count, it does the following: 1. If k ends with at least one digit 0, print a '[' for each digit 0 at the end of k. 2. Print n. 3. If k ends with at least one digit n-1, print a ']' for each digit n-1 at the end of k. (The value n=1 needs to have brackets added as a special case. This input value also generates some output to stderr, which can be ignored under standard PPCG rules.) Maybe there's a shorter way to implement this idea. --- Sample run: ``` ./array 3 [[[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]] [[3 3 3] [3 3 3] [3 3 3]]] ``` [Answer] # [Haskell](https://www.haskell.org/), 51 bytes Other than the existing Haskell solutions this constructs a usable data type not just a string representation thereof (and is shorter): ``` data L=N[L]|E Int f n=iterate(N.(<$[1..n]))(E n)!!n ``` [Try it online!](https://tio.run/##PYyxCoNAEET7@4oRUniFQiClVsEiIDZJJxZHXHNHzBruNmgg/24UQZiBea8Ya8KT@n6eWyMGZV7VZfMrcGFRHTh3Qt4IxVUaZ4f6mKbcaB0XYB1FPCcJbtYFLBm4/4KJWmrhOoyE0bBABry9W4cleAqfXpTjIIbvhKsdRpQYLXlSQFhx@Z40kG807brCFPSug1Iv43jh7T1Ft9STaZFnGR4k54GFWMJ8@gM "Haskell – Try It Online") ### Explanation / Ungolfed The reason why this is an interesting challenge in Haskell is that a solution to this challenge needs to return different deeply nested lists and Haskell (without importing external modules) does not support this. One workaround which turned out to be the golfiest, is to define our own data type: ``` data NestedList = Nest [NestedList] | Entry Int ``` Now we can just define a function `f :: Int -> NestedList` which is able to represent all the required data types: ``` pow n = iterate (Nest . replicate n) (Entry n) !! n ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~5~~ 4 bytes ``` _{a* ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z@@OlHr/39DLiMuYy6T/wA "MathGolf – Try It Online") ## Explanation using `n = 2` (note that the outermost `[]` are not arrays, but are just there to show the stack) ``` _ duplicate TOS (stack is [2, 2]) { loop 2 times (stack is [2]) a wrap in array ([2] => [[2]], [[2, 2]] => [[[2, 2]]]) * pop a, b : push(a*b) ([[2]] => [[2, 2]], [[[2, 2]]] => [[[2, 2], [2, 2]]]) ``` [Answer] # [Raku](https://raku.org), 21 bytes [try it online!](https://tio.run/##K0gtyjH7/786OrqiIlYBTKjEK1RUKBjH1mqkp5Zo6hUnVv7/bwQA) ``` {[[xx] [xx] $_ xx 3]} ``` [Answer] # [Julia 0.6](http://julialang.org/), ~~23~~ 21 bytes ``` n->n>(n>n)... > =fill ``` [Try it online!](https://tio.run/##yyrNyUw0@59m@z9P1y7PTiPPLk9TT0@Py07BNi0zJ@d/bmKBBlBGIyWzuCAnsVIjTSNPU9O6oCgzryQnT0NTU0dBw1DHWMdUU/M/AA "Julia 0.6 – Try It Online") (Thanks to @MarcMush for -2 bytes.) In Julia, binary operators are parsed as function calls, so `a>b` is `>(a, b)`, which here is `fill(a, b)`. So the above is really saying: ``` n->fill(n,fill(n,n)...) ``` The first argument to `fill` is the value to fill the new array with. The following arguments to that are the dimensions of the new array. Here we create those dimensions themselves using another `fill` call: we create an array of `n` `n`s, then splat that with `...` so that the first `fill` call gets n number of dimension arguments, each with value n - so it creates an n-dimensional array where each dimension length is n, and filled with the value n. [Answer] # [Perl 6](https://perl6.org), 25 bytes ``` {($^n,{$_ xx$n}...*)[$n]} ``` Starts with `n`, and iteratively applies the "repeat n times" transformation `n` times, each time creating an additional level of `List` nesting. [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fraESl6dTrRKvUFGhklerp6enpRmtkhdb@784sVIhTcHQmgvCMIIxjGEME@v/AA "Perl 6 – TIO Nexus") [Answer] # PHP, ~~70~~ 62 bytes This is the simplest I can come up with. ``` for(;$i++<$n=$argv[1];)$F=array_fill(0,$n,$F?:$n);print_r($F); ``` Takes the input as the first argument and prints the resulting array on the screen. --- Thanks to [@user59178](https://codegolf.stackexchange.com/users/59178/user59178) for saving me **8 bytes**! [Answer] # Clojure, 36 bytes ``` #(nth(iterate(fn[a](repeat % a))%)%) ``` Iterates function which repeats its argument `n` times, it produces infinite sequence of such elements and then takes its `n`th element. [See it online](https://ideone.com/l9pMOD) ]
[Question] [ [Dropsort](http://www.dangermouse.net/esoteric/dropsort.html), designed by David Morgan-Mar, is an example of a linear-time "sorting algorithm" that produces a list that is, in fact, sorted, but contains only *some* of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is simply removed from the list and discarded. In this task, you will be given a list of integers as input (STDIN or function argument, you are required to support at least the range of 8-bit signed integers.) Your task is to dropsort them and then output the remaining elements in order. You may assume that the list is non-empty. This is code-golf, so the shortest program wins. **Test Cases** ``` Input Output 1 2 5 4 3 7 1 2 5 7 10 -1 12 10 12 -7 -8 -5 0 -1 1 -7 -5 0 1 9 8 7 6 5 9 10 13 17 21 10 13 17 21 10 10 10 9 10 10 10 10 10 ``` **Leaderboard** ``` var QUESTION_ID=61808,OVERRIDE_USER=39022;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # APL, 9 bytes ``` ⊢(/⍨)⊢=⌈\ ``` This is a monadic function train with diagram: ``` ┌─┼───┐ ⊢ ⍨ ┌─┼─┐ ┌─┘ ⊢ = \ / ┌─┘ ⌈ ``` The non-train version is ``` {⍵/⍨⍵=⌈\⍵} ``` This basically checks if each element is equal to the running maximum. *Note that **[Martin Büttner's J solution](https://codegolf.stackexchange.com/a/61818/39328)** is the same length as this and was posted first.* [Answer] # J, ~~10~~ 9 bytes ``` #~(=>./\) ``` Working version of my CJam idea (in fewer bytes). E.g.: ``` f =: #~(=>./\) f 10 10 10 9 10 10 10 10 10 f 1 2 5 4 3 7 1 2 5 7 ``` ## Explanation First, we get the maximum of each prefix, with: ``` >./\ ``` (Here, `>.` is the maximum operator, `/` folds that operator onto a list, and `\` gets all the prefixes of the input.) Then we compare the initial list with those maxima for equality: ``` (=>./\) ``` And finally, we select all elements where this list of boolean results gave a `1`: ``` #~(=>./\) ``` [Answer] ## Haskell, 28 ``` foldr(\x l->x:filter(x<)l)[] ``` An anonymous function. Call it like ``` foldr(\x l->x:filter(x<)l)[] [-7, -8, -5, 0, -1, 1] [-7,-5,0,1] ``` Equivalent to the recursion ``` f[]=[] f(x:l)=x:filter(x<)(f l) ``` Translated iteratively, we iterate over the elements, and for each one we see, we remove the ones smaller than it from the remainder of the list that we're iterating over. Thanks to Antisthenes for a byte saved with `(x<)`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ⊇ᶠ↔ᵒt ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NtCx61TXm4dVLJ///RRjqGOsY6JkAMJGP/RwEA "Brachylog – Try It Online") # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` ŒPUÞṪ ``` [Try it online!](https://tio.run/##y0rNyan8///opIDQw/Me7lz1////aCMdQx1jHRMgBpKxAA "Jelly – Try It Online") ## Explanation ``` ⊇ᶠ↔ᵒt ŒPUÞṪ ⊇ᶠ ŒP On all subsequences of {the input} ᵒ Þ sort by ↔ U their reverse t Ṫ then take the last element (i.e. the maximum as given by the sort) ``` This is a rare situation: I get to use an algorithm which (as far as I could tell with a quick skim) nobody is using so far, and it somehow ends up the same length in two very different golfing languages with very different syntax and builtin sets, with a 1-to-1 correspondence between the programs (the commands are even in the same order!). So it seemed to make more sense to combine them – in a way, these are the same program, and I wrote it in both languages to see which was shorter – than to submit them separately. The basic idea here is that the dropsort of a list is its subsequence with the lexicographically maximum reverse. Oddly, neither Brachylog nor Jelly has a builtin to find the maximum by a particular function (Jelly has a builtin to return *all the maxima* by a particular function, but that'd return a singleton list containing the result rather than the result itself, and also isn't even shorter than doing it this way). So instead, we generate all possible subsequences, sort by reverse, take the last. The reason why "lexicographically maximum reverse" works is that the chosen output must end (thus its reverse must start) with the highest number in the input list (it's easy to see that the dropsort output will always end with that), and thus can't contain anything after that (because taking subsequences preserves order). Repeat inductively and we end up with the definition of dropsort. [Answer] # Octave, ~~27~~ 19 bytes ``` @(a)a(cummax(a)==a) ``` [Answer] # JavaScript (ES6), 29 Abusing of the standard type conversion in javascript, array to number: * array of just 1 number => that number * any other array => NaN ``` d=l=>l.filter(v=>l>v?0:[l=v]) // TEST console.log=x=>O.innerHTML+=x+'\n' ;[ [[1,2,5,4,3,7], [1,2,5,7]] , [[10,-1,12], [10,12]] , [[-7,-8,-5,0,-1,1], [-7,-5,0,1]] , [[9,8,7,6,5], [9]] , [[10,13,17,21], [10,13,17,21]] , [[10,10,10,9,10], [10,10,10,10]] ].forEach(t=>( i=t[0],r=d(i),x=t[1], console.log('Test '+i+' -> '+r+(r+''==x+''?' OK':' Fail (expected '+x+')'))) ) ``` ``` <pre id=O></pre> ``` [Answer] # Python 2, 49 ``` f=lambda a:a and f(a[:-1])+a[-1:]*(a[-1]==max(a)) ``` [Answer] # Pyth, 12 bytes ``` eMfqeTeST._Q ``` [Verify all test cases at once.](https://pyth.herokuapp.com/?code=eMfqeTeST._Q&test_suite=1&test_suite_input=%5B1%2C+2%2C+5%2C+4%2C+3%2C+7%5D%0A%5B10%2C+-1%2C+12%5D%0A%5B-7%2C+-8%2C+-5%2C+0%2C+-1%2C+1%5D%0A%5B9%2C+8%2C+7%2C+6%2C+5%5D%0A%5B10%2C+13%2C+17%2C+21%5D%0A%5B10%2C+10%2C+10%2C+9%2C+10%5D) ### How it works ``` ._Q Compute all prefixes of the input. f Filter; for each T in the prefixes: eT Retrieve the last element of T. eST Sort T and retrieve its last element. q Check for equality. Keep T if q returned True. eM Select the last element of each kept T. ``` [Answer] # Mathematica, 26 Bytes ``` DeleteDuplicates[#,#>#2&]& ``` [Answer] # R, ~~29~~ 26 bytes ``` function(x)x[x>=cummax(x)] ``` This creates a function object that accepts a vector `x` and returns `x` after removing all elements not at least as large as the cumulative maximum of `x`. Saved 3 bytes thanks to flodel! [Answer] # K, 11 bytes ``` {x@&~x<|\x} ``` In action: ``` f: {x@&~x<|\x} f'(1 2 5 4 3 7 10 -1 12 -7 -8 -5 0 -1 1 9 8 7 6 5 10 13 17 21 10 10 10 9 10) (1 2 5 7 10 12 -7 -5 0 1 ,9 10 13 17 21 10 10 10 10) ``` [Answer] # Java, 82 bytes ``` void f(int[]a){int m=a[0];for(int n:a){System.out.print(m>n?"":n+" ");m=n>m?n:m;}} ``` Here's a simple output loop. It just keeps the max in `m` and compares each element. [Answer] ## Perl, 33 bytes **32 bytes code + `-p`** ``` $p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge ``` If additional spaces are acceptable in the output, can be 31 bytes by removing and `?`. Accepts a string (or number of newline separated) strings via `STDIN`: ``` perl -pe'$p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge' <<< '-7 -8 -5 0 -1 1' -7 -5 0 1 ``` ``` perl -pe'$p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge' <<< '10 10 10 9 10' 10 10 10 10 ``` [Answer] # Python 3, 67 Pretty brute force. Changed it to a function, because I missed that it was a valid answer. ``` def f(i): s=[i[0]] for n in i[1:]: if s[-1]<=n:s+=[n] return s ``` Ungolfed version: ``` input_numbers = input().split() sorted_numbers = [] previous_number = int(input_numbers[0]) for number in map(int, input_numbers): if previous_number <= number: sorted_numbers.append(number) previous_number = number print(sorted_numbers) ``` [Answer] # Haskell, ~~38~~ 37 bytes Saved 1 byte thanks to [JArkinstall](https://codegolf.stackexchange.com/users/45300/jarkinstall). ``` f(x:y:s)|x>y=f$x:s|1>0=x:f(y:s) f s=s ``` [Answer] # C# - ~~68~~64 or ~~132~~127 Characters ``` int[]f(int[]b){return b.Where((v,i)=>i<1||b[i-1]<=v).ToArray();} ``` `Where` in this case is iterating through the list, and for each element `v` at index `i` in the list, evaluates the boolean expression. If the expression evaluates to true, then the item is added to the result. The only real trick to the boolean expression is that C# short circuits or evaluation as soon as a condition evaluates to true. This prevents the `IndexOutOfRangeException` exception, and keeps the first element in the list. If the input and output have to be strings (I couldn't tell for sure, so I'll leave it to the OP and the rest of you to decide.) ``` string t(string b){var c=b.Split(' ').Select(d=>int.Parse(d)).ToList();return String.Join(" ",c.Where((v,i)=>i<1||c[i-1]<=v));} ``` Decompressing that a bit gives: ``` string t(string b) { var c=b.Split(' ').Select(d=>int.Parse(d)).ToList(); return String.Join(" ",c.Where((v, i)=>i<1||c[i-1]<=v)); } ``` In this case the second line of the function is using the exact same logic as above. The `Select` grabs the elements of the list and converts them to `int`. The call to `ToList`1 forces the select to be evaluated, and turns the `var` into a `List<int>` at compile time, so that the `Where` is operating on a collection of integers. [Try it on C# Pad](http://csharppad.com/gist/57d00bb5cc690cd0185d) **Thanks to [VisualMelon](https://codegolf.stackexchange.com/users/26981/visualmelon) for helping trim 4 bytes and 5 bytes respectively. :)** 1 tutu list? [Answer] # CJam, 15 bytes ``` q~{_2$<{;}&}*]p ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q~%7B_2%24%3C%7B%3B%7D%26%7D*%5Dp&input=%5B1%202%205%204%203%207%5D). ### How it works ``` q~ Read an evaluate all input. { }* Reduce; push the first element; or each remaining element: _2$ Copy the topmost and second topmost element from the stack. < Check if the topmost is smaller than the second topmost. {;}& If it is, remove it from the stack. ] Wrap the stack i an array. p Print. ``` [Answer] # [><>](https://esolangs.org/wiki/Fish) with -v flag, ~~36~~ 31 + 2 = 33 bytes ``` :&\o " "&n:~& < ~ >l?!;:&:&(?!^ ``` Input the list on the stack with -v so that the first element of the list is at the top of the stack. It will print the dropsorted list with a trailing space. Test run : ``` $ for input in "1 2 5 4 3 7" "10 -1 12" "-7 -8 -5 0 -1 1" "9 8 7 6 5" "10 13 17 21" "10 10 10 9 10"; do echo $input '-> ' $(python fish.py dropsort.fsh -v $(echo $input | tac -s ' ')); done 1 2 5 4 3 7 -> 1 2 5 7 10 -1 12 -> 10 12 -7 -8 -5 0 -1 1 -> -7 -5 0 1 9 8 7 6 5 -> 9 10 13 17 21 -> 10 13 17 21 10 10 10 9 10 -> 10 10 10 10 ``` Edit : saved 5 bytes thanks to Fongoid [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 32 bytes ``` $args|?{$e-eq$p-or$_-ge$p;$p=$_} ``` [Try it online!](https://tio.run/##XZD9aoNAEMT/9ykGsy0GTsjZtKmU0LyJSLI1gtGrd6Etxme3G7@a9GC5Y@Y3u8ea6otre@Si6OgDWzQdpXVmL@8NccifZMKqpiTMmMwbmS0lbdd63i7wICcItEKk8KywVnhS2CwVhjMbIk3sSiEUXUczNbKrQRy5cCPcq5Skp0if6I1B1DMdKwgrzouMu2sc303W8j0tWKRvoP/GLT9WfL2myK0hqrfEBQ9o@hilivjb8N7xQRZJyaDWbM@FE@FR9rtLsYA1RepcXmY94I@EL9v25wZ@7y3@XHmfy311OnHp4I65RZGXDFfhkF8b/mAArdd2vw "PowerShell – Try It Online") Less golfed: ``` $args|?{ $empty -eq $previous -or $_ -ge $previous $previous = $_ } ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 2 bytes ``` ü< ``` [Try it online!](https://tio.run/##yygtzv6fm1/8qKnx/@E9Nv///4@ONtQx0jHVMdEx1jGP1Yk2NNDRNdQxNAIydc11dC10dE11IEJAEUsdCx1zHTMd09hYAA "Husk – Try It Online") nub sieve using lesser than. [Answer] # C: 73 bytes ``` int i,j;i=j=INT_MIN;while(scanf("%d",&j)!=EOF)if(j>=i)printf("%d",j),i=j; ``` or # C: 49 bytes **(If [customs header](https://github.com/Darelbi/codegolf/blob/master/c) made for codegolf competitions is allowed)** ``` I z,y;z=y=INT_MIN;w(s(D,&y)!=E)i(y>z)p(D,y),z=y;} ``` Still can't beat CJam, but at least this allow to beat few other languages. [Answer] ## Burlesque, 13 bytes 11 byte solution that passes test-cases: ``` -.2CO:so)[~ ``` [Try online here](http://104.167.104.168/~burlesque/burlesque.cgi?q=%7B1%202%205%204%203%207%7D-.2CO%3Aso%29[~). Explanation: ``` -. -- prepend head of list to list 2CO -- n-grams (sliding window) of size 2 :so -- filter sorted lists )[~ -- map last ``` However, this version only works by using the fact, that no two smaller numbers are in between two numbers. Otherwise use the version below (which is 13B): **Older versions:** ``` J-]{cm-1.>}LO ``` [Try online here.](http://104.167.104.168/~burlesque/burlesque.cgi?q=%7B1%202%205%204%203%207%200%200%209%7DJ-]%7Bcm-1.%3E%7DLO) Explanation: ``` J -- duplicate -] -- head { cm -- compare (returning -1,0 or 1) -1.> -- greater than -1 }LO -- Loop ``` If you'd drop equal numbers as well you could go with just `.>` instead of using `cm`. Also, if lists only contain positive numbers you can use either `0` or `-1` instead of `J-]`. [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), 18 bytes ``` ndN(nd1R`2&dN$I$). ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=ndN%28nd1R%602%26dN%24I%24%29%2E&input=10%2010%2010%209%2010) ### Explanation ``` ndN Take first integer from input ( $I$). Repeat until the input is empty and then stop. nd1R` Is the next integer less than the previous one? 2&dN If not (i.e., it's greater than or equal to), print it. ``` [Answer] # NARS2000 APL, 13 bytes NARS2000 is a free APL interpreter for Windows; it includes [multiset features](http://wiki.nars2000.org/index.php/Multisets) accessed with the `⍦` operator. ``` (+⍦∩⌈\) ``` This is a monadic fork that takes the multiset intersection (`⍦∩`) of the input (`+`)\* and the list of running maximums (`⌈\`). Since `⍦` is not a standard APL character in the one-byte APL legacy encodings, we must use UTF-8, making the `⍦∩⌈` characters three bytes each. I chose `+` instead of `⊢` to save two bytes. NARS2000 supports forks, which can be built into trains without parentheses, but unlike Dyalog it doesn't allow assignment to a function without wrapping the function in parentheses. \*`+` is technically complex conjugate, but the input is real. [Answer] # Python, 102 99 94 + 5 6 non-file-final newlines = 107 105 100 bytes (I used tabs for indentation) ``` def d(l): j=b=0;m=l[j];r=[] for i in l: (m,b)=[(m,0),(i,1)][i>=m] if b>0:r+=[i] j+=1 l[:]=r ``` Not the best out there, but this is my first shot at code golf. Couldn't figure out a way to sort the list inline without running into removal-related bugs, so I moved the ordered elements to a temporary list. EDIT: list.append() is shorter than doing it the ugly way r+=[i] was shorter than list.append(); thanks [njzk2](https://codegolf.stackexchange.com/users/14736/njzk2)! [Answer] # Scala: 232 126 120 bytes ``` def f(x:Int*)=(Seq[Int]()/:x)((r,y)=>r.headOption.filter(y>=).map(_=>y+:r).getOrElse(if(r.isEmpty) y+:r else r)).reverse ``` [Answer] # Scala, 54 bytes ``` def f(x:Int*)=(x:\Seq[Int]())((y,r)=>y+:r.filter(y<=)) ``` Ungolfed: ``` def dropSort(xs: Seq[Int]): Seq[Int] = xs.foldRight(Seq.empty[Int]) { (x, result) => x +: result.filter(r => r >= x) } ``` [Answer] ## Tiny Lisp, 107 bytes ([This language was only published](https://codegolf.stackexchange.com/q/62886/2338) after this question, so this answer runs out of competition. Not that it had any chance to win. *The [language](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) later evolved further to have more buildins than the ones I used here, but I'm staying with the version I originally implemented in 2015. [This answer still works with the newer official interpreter](https://tio.run/##ZY/BCoMwEETvfsUcZw@C0drYzzEV2oBKTbz06@0mFsE2hNnd2Zddsvr5Pfr42jYOCFzICb3Qo6fnyKcWkzBg4qqp8J4thj1kT13JOmCIaYJL711G3Y66hLqDTLt06QouYB8eEUm0UWijLABtEJwlpekwosK3FGgUFMpGMI8xqNHiggY2zzj8CixhBKY@@WpaSdplbQUHeOJu6GBxVeBnqmlgLGrz5@d7U9FPfgA), though it gives some warnings because I define a parameter `a` which shadows the new buildin `a` (for adding).*Thanks to DLosc for the TIO link.) `(d r(q((m a)(i a(i(l(h a)m)(r m(t a))(c(h a)(r(h a)(t a))))()))))(d ds(q((b)(i b(c(h b)(r(h b)(t b)))()))))` This defines a function `ds` (and its recursive helper function `r`) which sorts its argument, which must be a list of integers. `r` is not a tail-recursive function, so for very long lists this might run into a stack overflow. Ungolfed: ``` (d r (q((m a) (i a (i (l (h a) m) (r m (t a)) (c (h a) (r (h a) (t a)) ) ) () ) ) ) ) (d ds (q( (b) (i b (c (h b) (r (h b) (t b)) ) () ) ) ) ) ``` Here are some examples how to use this (with the test cases from the question): ``` (d list (q (args args))) (d - (q( (n) (s 0 n) ) ) ) (ds (list 1 2 5 4 3 7)) (ds (list 10 (- 1) 12)) (ds (list (- 7) (- 8) (- 5) 0 (- 1) 1)) (ds (list 9 8 7 6 5)) (ds (list 10 13 17 21)) (ds (list 10 10 10 9 10)) ``` (Yeah, `-7` is not an integer literal, so we have to define a function to represent them.) Output: ``` list - (1 2 5 7) (10 12) (-7 -5 0 1) (9) (10 13 17 21) (10 10 10 10) ``` [Answer] # Jelly, 5 bytes ``` =»\Tị ``` Note that the challenge predates the creation of Jelly. [Try it online!](http://jelly.tryitonline.net/#code=PcK7XFThu4s&input=&args=WzEsIDIsIDUsIDQsIDMsIDdd) ### How it works ``` =»\Tị Main link. Argument: A (list) »\ Yield the cumulative maxima of A. = Perform element-by-element comparison. Yields 1 iff A[n] = max(A[1], ..., A[n]). T Get all indices of truthy elements. ị Retrieve the items of A at those indices. ``` [Answer] # SWI-Prolog, 55 bytes ``` A/B:-append(C,[D,E|F],A),E<D,append(C,[D|F],G),G/B;A=B. ``` Usage: Call "*List*/X" where *List* is a bracket-enclosed, comma-separated list e.g. [1,4,5,1,11,6,7]. ]
[Question] [ > > This is a repost [of an old challenge](https://codegolf.stackexchange.com/q/8369/8478), in order to adjust the I/O requirements to our recent standards. This is done in an effort to allow more languages to participate in a challenge about this popular sequence. See [this meta post](https://codegolf.meta.stackexchange.com/q/14871/8478) for a discussion of the repost. > > > The Kolakoski sequence is a fun self-referential sequence, which has the honour of being OEIS sequence [A000002](http://oeis.org/A000002) (and it's much easier to understand and implement than A000001). The sequence starts with **1**, consists only of **1**s and **2**s and the sequence element **a(n)** describes the length of the **n**th run of **1**s or **2**s in the sequence. This uniquely defines the sequence to be (with a visualisation of the runs underneath): ``` 1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1,2,1,1,2,1,2,2,1,1,2,1,1,2,... = === === = = === = === === = === === = = === = = === === = === = 1, 2, 2, 1,1, 2, 1, 2, 2, 1, 2, 2, 1,1, 2, 1,1, 2, 2, 1, 2, 1,... ``` Your task is, of course, to implement this sequence. You may choose one of three formats to do so: 1. Take an input **n** and output the **n**th term of the sequence, where **n** starts either from **0** or **1**. 2. Take an input **n** and output the terms *up to and including* the **n**th term of the sequence, where **n** starts either from **0** or **1** (i.e. either print the first **n** or the first **n+1** terms). 3. Output values from the sequence indefinitely. In the second and third case, you may choose any reasonable, unambiguous list format. It's fine if there is no separator between the elements, since they're always a single digit by definition. In the third case, if your submission is a function, you can also return an infinite list or a generator in languages that support them. You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. Note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` 2Rṁxṁµ¡ ``` This is a full program that prints the first **n** terms. [Try it online!](https://tio.run/##y0rNyan8/98o6OHOxgogPrT10ML///8bGwMA "Jelly – Try It Online") ### How it works ``` 2Rṁxṁµ¡ Main link. Argument: n (integer) µ Combine the preceding links into a monadic chain. ¡ Set t = n. Call the chain n times, updating t with the return value after each call. Yield the last value of t. 2R Set the return value to 2 and take its range. Yields [1, 2]. ṁ Mold; cyclically repeat 1 and 2 to match t's length. In the first run, ṁ promotes t = n to [1, ..., n]. x Repeat the k-th element of the result t[k] times. In the first run, x repeats each element t = n times. ṁ Mold; truncate the result to match the length of t. In the first run, ṁ promotes t = n to [1, ..., n]. ``` ### Example run Let **n = 5**. The first invocation of the chain repeats **1, 2** cyclically to reach length **5**, then each element **5** times, and finally truncates the result to length **5**. ``` 1 2 1 2 1 x 5 5 5 5 5 --------------------------------------------------- 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 ``` This yields a list of length **5**. The first element is the first element of the Kolakoski sequence. The second invocation of the chain repeats **1, 2** cyclically to reach length **5**, then repeats the **k**th element **j** times, where **j** is the **k**th element of the previous list, and finally truncates the result to length **5**. ``` 1 2 1 2 1 x 1 1 1 1 1 ------------ 1 2 1 2 1 1 2 1 2 1 ``` This yields another list of length **5**. The first two elements are the first two elements of the Kolakoski sequence. The process continues for three more iterations. ``` 1 2 1 2 1 x 1 2 1 2 1 ---------------- 1 2 2 1 2 2 1 1 2 2 1 2 ``` ``` 1 2 1 2 1 x 1 2 2 1 2 ------------------ 1 2 2 1 1 2 1 1 1 2 2 1 1 ``` ``` 1 2 1 2 1 x 1 2 2 1 1 ---------------- 1 2 2 1 1 2 1 1 2 2 1 1 ``` These are the first five elements of the Kolakoski sequence. [Answer] # [Python 2](https://docs.python.org/2/), 42 bytes ``` x=y=-1 while 1:x=x/2^y;y<<=x%2;print x%2+1 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8K20lbXkKs8IzMnVcHQqsK2Qt8ortK60sbGtkLVyLqgKDOvRAHI0jb8/x8A "Python 2 – Try It Online") Full disclosure - I didn't find the solution myself. I let my brute forcer do the heavy lifting for me and just watched the results roll in. At first, I didn't even try to understand the solution. I just assumed it was too complicated for me to wrap my head around. But then I realized that It's actually pretty simple. [Answer] # [Python 2](https://docs.python.org/2/), 51 bytes ``` l=[2] print 1,2, for x in l:print x,;l+=x*[l[-1]^3] ``` Prints indefinitely. Builds the list `l` as it's being iterated through. For each entry `x` of `l`, appends `x` copies of `1` or `2`, whichever is opposite the current last element. The main difficulty is dealing with the initial self-referential fragment `[1,2,2]`. This code just prints the initial `1,2` and proceeds from there. The extra printing costs 12 bytes. Without that: [**39 bytes**](https://tio.run/##K6gsycjPM/r/P8c22iiWKy2/SKFCITNPIceqoCgzr0ShwjpH27ZCKzonWtcwNs449v9/AA "Python 2 – Try It Online"), missing first two entries: ``` l=[2] for x in l:print x;l+=x*[l[-1]^3] ``` Another approach is to specially initialize the first two entries. We initialize `l` as `[0,0,2]` so that the first two entries don't cause appending, but `print x or n` makes them be printed as `n`. [**51 bytes**](https://tio.run/##K6gsycjPM/r/P8c22kDHQMcolivP1pArLb9IoUIhM08hx6qgKDOvBMgBiuRZ52jbVmhF58Va58XZGv//DwA "Python 2 – Try It Online") ``` l=[0,0,2] n=1 for x in l:print x or n;l+=x*[n];n^=3 ``` Another fix is to initialize `l=[1]`, track the alternation manually in `n`, and correct the printing: [**51 bytes**](https://tio.run/##K6gsycjPM/r/P0/HNsc22jCWKy2/SKFCITNPIceqoCgzr0QjxxYormMYq6ldYZ2jbVuhFZ0Xa50XZ2v8/z8A "Python 2 – Try It Online") ``` n,=l=[1] for x in l:print(l==[1,1])+x;l+=x*[n];n^=3 ``` Without the `(l==[1,1])+`, everything works except the printed sequences starts `1,1,2` instead of `1,2,2`. There has to be a better way to recognize we're at this second step. And another weird fix, also somehow the same byte count: [**51 bytes**](https://tio.run/##K6gsycjPM/r/P8c22jDWutDWiCstv0ihQiEzTyHHqqAoM69EocI6R9u2Qis6J1rXMDbOOFarEKiu0AaoCQA "Python 2 – Try It Online") ``` l=[1];q=2 for x in l:print x;l+=x*[l[-1]^3]*q;q=q<2 ``` [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), ~~13~~ 11 bytes ``` =[=)O?=!00. ``` [Try it online!](https://tio.run/##Ky/NLSgt/v/fNtpW09/eVtHAQO//fwA "Wumpus – Try It Online") Prints the sequence indefinitely without separators. I am genuinely surprised by how short this is. ### Explanation The basic idea is to keep the sequence on the stack and repeatedly use the bottom-most element to generate another run and then print it. We're effectively abusing the stack as a queue here. We can also save a couple of bytes by working `0` and `1` (incrementing only for output) instead of `1` and `2`, because this way we don't need to explicitly initialise the stack with a `1` and we can use logical negation to toggle between the two values. ``` The entire program is run in a loop. At the beginning of loop iteration i, a(i)-1 will be at the bottom of the stack and the first element of the ith run of values will be on top. The caveat is that on the first iteration, the stack is empty, but popping from an empty stack produces an implicit zero. = Duplicate the top of the stack. Since this is defined as "pop x, push x, push x" this will result in 2 zeros when the stack is empty. After this we've got two copies of the ith run's value on top of the stack. [ Pull up a(i)-1 from the bottom of the stack. =)O Duplicate, increment to a(i) and print it. ?= If a(i)-1 is 1 (as opposed to 0), make another copy of the top of the stack. We've now got a(i)+1 copies, so one more than the run should be long, but that's great because we can use the additional copy to get the start of the next run. ! Logical negation which swaps 0 and 1. 00. Jump back to the beginning of the program. ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~30 26 25 23 17~~ 16 bytes ``` ~l{1|2}ᵐ.~lᵐ~ḅa₀ ``` Outputs the first **n** values. [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy6n2rDGqPbh1gl6dTlAsu7hjtbER00N//@b/Y8CAA "Brachylog – Try It Online") This is *extremely* slow: **n = 6** takes over 30 seconds on TIO. [Answer] # [Husk](https://github.com/barbuz/Husk), 10 bytes ``` Ṡωo↑⁰`Ṙ¢ḣ2 ``` Returns the first **n** values. [Try it online!](https://tio.run/##ASEA3v9odXNr///huaDPiW/ihpHigbBg4bmYwqLhuKMy////MzA "Husk – Try It Online") ## Explanation ``` Ṡωo↑⁰`Ṙ¢ḣ2 Input is an integer N. ḣ2 The range [1,2] ¢ Cycle: C = [1,2,1,2,1,2... ω Iterate until fixed point is found: Ṡ `Ṙ Replicate the list C element-wise according to the current list, o↑⁰ then take first N elements. ``` For input 20, the process goes like this: ``` [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2... [1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2] [1,2,2,1,1,2,1,1,2,2,1,2,2,1,1,2,1,1,2,2] [1,2,2,1,1,2,1,2,2,1,2,1,1,2,2,1,2,2,1,1] [1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,1,2] [1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1] [1,2,2,1,1,2,1,2,2,1,2,2,1,1,2,1,1,2,2,1] ``` [Answer] # Java 10, ~~155~~ ~~108~~ ~~105~~ ~~100~~ ~~97~~ 94 bytes ``` v->{var s="122";for(int i=1;;s+=(s.charAt(i)>49?11:1)<<i%2)System.out.print(s.charAt(++i-2));} ``` Prints indefinitely without delimiter. -3 bytes after an indirect tip from *@Neil*. -5 bytes thanks to *@MartinEnder*. -3 bytes converting Java 8 to Java 10. -3 bytes thanks to *@ceilingcat* with the binary left-shift trick. **Explanation:** [Try it online](https://tio.run/##RY5NCsIwEIX3nmIQhITSQIobja14ALsR3IiLMbYaTdOSpAGRnr3GHxBmGGaY9953w4Dp7XwfpUbnYIvKPCcAyvjK1igrKN8rQGjVGSTZv0egIt6G2LGcR68klGAghzGkxTOgBZdPeZZNRd1aEr1A5VwIl@TEMXlFu/FE0WK@WHO@5HS1UrOM7h7OVw1re886GzX/1yRRaUapGEbxzez6k46Zv@gPWhPByc5H4eVwRPqFNkwS02v94x3GFw) (times out after 60 sec on TIO). ``` v->{ // Method with empty unused parameter and no return-type var s="122"; // String, starting at "122" for(int i=1;; // Loop `i` from 1 upwards indefinitely s+= // After every iteration: Append the String with: (s.charAt(i)>49?11:1) // Either once or twice depending on the digit at index `i` <<i%2) // With digits 2 or 1 by left-shifting with `i` modulo-2 System.out.print(s.charAt(++i-2));} // Print the character at index `i-2` of the String // After we've first increased `i` by 1 with `++i` ``` The binary for 1 and 11 are `1` and `1011`. If we left-shift with `0` they'll remain the same, but if we left-shift with `1` they'll become `10` (binary for 2) and `10110` (binary for 22) respectively. [Answer] # [Python 2](https://docs.python.org/2/), 45 bytes ``` x=y=0 while 1:print 1+x%2;x^=~y&~-y;y=~-y&x/2 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v8K20taAqzwjMydVwdCqoCgzr0TBULtC1ci6Is62rlKtTrfSutIWSKpV6AOVAwA "Python 2 – Try It Online") Based on [this blog post](https://11011110.github.io/blog/2016/10/14/kolakoski-sequence-via.html), but golfed better. Has the bonus advantage of only using logarithmic space. -1 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) who realised we can invert and use `~x` and `~y` instead of `x` and `y` to avoid writing `x=y=-1` for the initial condition. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ’߀+\<¹SḂ‘ ``` Returns the **n**th term. [Try it online!](https://tio.run/##y0rNyan8//9Rw8zD8x81rdGOsTm0M/jhjqZHDTP@G5odbgeK/QcA "Jelly – Try It Online") ### How it works ``` ’߀+\<¹SḂ‘ Main link. Argument: n (positive integer) ’ Decrement; yield n-1. ߀ Recursively map the main link over [1, ..., n-1]. +\ Take the cumulative sum. The k-th sum is the combined length of the first k runs. <¹ Compare each sum with n. S Sum the Booleans. This counts the number of runs that occur before the n-th term. If there's an even number (including 0) of runs, the n-th term is 1. If there's an odd number of runs, the n-th term is 2. Ḃ Extract the least significant bit of the count. ‘ Increment. ``` [Answer] # [J](http://jsoftware.com/), 12 bytes Single-argument function taking *n* and producing the first *n* terms. [Try it online!](https://tio.run/##y/qvpKeeZmulrlNrZaBgZfBfRcNQ26jGU08zzir2vyZXcUlKfmmJg5KVQpqCscF/AA "J – Try It Online") ``` $(1+2|I.)^:] ``` Just sprucing up my [old answer](https://codegolf.stackexchange.com/a/26560/5138) to the old question. `I.` is a verb which takes an array of numbers and spits out a list of indices, so that if the *k*-th item in the array is *n*, then the index *k* appears *n* times. We'll use it to bootstrap the Kolakowski sequence up from an initial seed. Each step will proceed as follows: ``` 1 2 2 1 1 2 1 2 2 1 (some prefix) 0 1 1 2 2 3 4 5 5 6 7 7 8 8 9 (use I.) 0 1 1 0 0 1 0 1 1 0 1 1 0 0 1 (mod 2) 1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 (add 1) ``` If we perform this operation (`1+2|I.`) over and over starting from 10, it looks something like this: ``` 10 1 1 1 1 1 1 1 1 1 1 1 2 1 2 1 2 1 2 1 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 1 2 1 1 2 2 1 2 2 1 1 ... 1 2 2 1 1 2 1 2 2 1 2 1 1 2 2 ... 1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 ... ``` Notice how we get more and more correct terms each time, and after a while the first *n* terms are fixed. The number of iterations it takes to settle down is hard to describe precisely, but it looks to be roughly logarithmic in *n*, so if we just run it *n* times (`^:]`) it should be fine. (Check out these other OEIS sequences for more info: [generation lengths](http://oeis.org/A054352), [partial sums](http://oeis.org/A054353).) Once we're done that, all we have to do is take the first *n* terms using `$`. The construction `$v` for any verb `v` is an example of a hook, and giving it `n` as argument will execute `n $ (v n)`. Here is the old 13-byte version which is far less wasteful of time and space: `($1+2|I.)^:_~`. It truncates the input at every step, so we can run exactly as many times as is needed to settle, instead of linearly many times. [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` r=r%1 ~(x:t)%n=n:[n|x>1]++t%(3-n) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v8i2SNWQq06jwqpEUzXPNs8qOq@mws4wVlu7RFXDWDdP839uYmaegq1CQVFmXomCikJJYnaqgqGBgULRfwA "Haskell – Try It Online") Ørjan Johansen saved 7 bytes using an irrefutable pattern to force the prefix. [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~594 583~~ 572 bytes *Thanks to Ed Wynn for -10 bytes!* ``` ,.Ford,.Puck,.Act I:.Scene I:.[Enter Ford and Puck]Ford:You cat!Open heart!You big cat!Open heart!Puck:Remember you!Remember me!Scene V:.Ford:You is the sum ofI a cat!Puck:Recall!Open heart!Ford:Remember a pig!Is I nicer a cat?If notyou be the sum ofyou a big pig!Scene X:.Puck:Recall!Ford:Is I nicer zero?If soremember I!If solet usScene X!Puck:Is I nicer zero?You is the sum ofI a big cat!If soyou is I!Remember zero!Remember I!Remember you!You be the difference betweena big cat you!Scene L:.Ford:Recall!Is you worse I?If so,let usScene V!Puck:Remember I!Let usScene L! ``` [Try it online!](https://tio.run/##bZHLasMwEEV/ZbQ3@gBvShcNCAwtLYSEkoUijxNTWzJ6ENyfdz2SYwvTneZxz9wZuaGbpoIfjK0L/hHUT8FflQdR8i@FGunx/aY9WqAWkLoG6rpQVJ5NACU9ex9Qwx2l9YxS1/a2T5Om/MQe@@uMGk1ga9AjS6OOJV@prQN/R3ChB9MIkJG3QJTsupwdRStOwtDemHAgQLcqJmbti2hAGz@SO8zQlJDRMKmSj1PJ80kRn/F@0RrCOWOfMwWLcYceglsgye1e9@9uz3tFyJg6xHYgEm5RVqAznreN6rZp0KJWOGf8A1Gv6NiajFXLlZftZoM08WGsmz877VXkixx3fydYlVUrNk1/ "Shakespeare Programming Language – Try It Online") This is a golfed version of [Ed Wynn's ungolfed solution](https://codegolf.stackexchange.com/a/164267/76162), starting from the [828 byte solution](https://tio.run/##hVLLaoQwFP2V637IB7gZytCC0KGlhWGG0kWM10cnJpJExK@3ifEV29KNqDmPe8@JbvgwUPIkVXYgry27H8gDM5DE5J2hQPfy8SgMKnAQoCIDh/p0j/gNa6xTe0aho4rcZAsp2g8tRbQ5U5iBvvfkpUEBJVJlIicWO3ylLSCtCviSAcC7n2OyIGkNSTTZMsq519jY8Ar9@UYm0dA7rh496GzGqDmO9CS3wx56P4gpEXRbg8w9aYZOUZxisrVfpXNqvHQpi6NX5Gig1XZz0yoBRoKXuJJw6CR6/h14mjyvk6cLwKXqh16cJc/CpUbwutTYxrzFjhsE4oSY7PZ8m7mvz/F3US@fFhjMZfUK@9uUVEzqtvytstow50vzI3t3H25rL1mV56hQMLRo0yGKcPJRy2d2ieeUdz0tGzfVPz2dSXi//@zpQobhGw) he linked in the [comments](https://codegolf.stackexchange.com/questions/157403/compute-the-kolakoski-sequence#comment397761_164267) and going a little nuts from there. ### Explanation: ``` ,.Ford,.Puck,.Act I:.Scene I:.[Enter Ford and Puck] Boilerplate, introducing the characters Ford:You cat!Open heart!You big cat!Open heart! Print 1,2 as the first two terms of the sequence Puck:Remember you!Remember me! Initialise stack as 0, 2 Ford's value is currently 0, representing the value to be pushed to the stack Scene V:. Start infinite loop Ford:You is the sum ofI a cat! Puck:Recall!Open heart! Pop the next value in the stack and print it Ford:Remember a pig! Push -1 as the end of the stack Is I nicer a cat? If Ford's value is 2 If notyou be the sum ofyou a big pig! Subtract 2 from Puck's value to represent making 2 only one copy #Reverse the stack until it reaches the terminator value 0 or -1 Scene X:.Puck:Recall!Ford:Is I nicer zero?If soremember I!If solet usScene X! Puck:Is I nicer zero? Check if the Puck's value is bigger than 0 (only making one copy) You is the sum of Ia big cat! Set Ford's value to Puck+2 to counter the change If soyou is I! But undo it if making one copies Remember zero! Push 0 as the stack terminator Remember I! Push Ford's value, which is 0 or -1 if this is a single copy, or 1 or 2 for a double copy Remember you! Push one copy of Puck's value You be the difference betweena big cat you! Map Ford's value from 1,2 to 1,0 Scene L:. #Reverse the stack until it reaches the terminator 0 Ford:Recall!Is you worse I?If solet us Scene V! Puck:Remember I!Let usScene L! ``` [Answer] ## [Gol><>](https://github.com/Sp3000/Golfish), ~~8~~ 7 bytes ``` :{:PnKz ``` [Try it online!](https://tio.run/##S8/PScsszvj/36raKiDPu@r/fwA "Gol><> – Try It Online") ### Explanation This is a port of [my Wumpus answer](https://codegolf.stackexchange.com/a/157469/8478). Gol><> is basically *the* language that has all the necessary features to port the Wumpus answer (specifically, implicit zeros at the bottom of stack, "duplicate" implemented "pop, push, push", and a stack rotation command), but: * It has a toroidal grid, which means we don't need the explicit `00.` to jump back to the beginning. * It has `K`, which is "pop N, then duplicate the next element N times", which can replace `?=`, saving another byte. So the mapping from Wumpus to Gol><> becomes: ``` Wumpus Gol><> = : [ { = : ) P O n ?= K ! z 00. ``` [Answer] # JavaScript, ~~67~~ ~~66~~ ~~60~~ ~~58~~ ~~52~~ ~~51~~ 50 bytes Well, that made my brain itch more than it should have! Retruns the `n`th term, 0-indexed. ``` s=`122` x=1 f=n=>s[n]||f(n,s+=s[++x%2]*(s[x]+0-9)) ``` 5+1 bytes saved thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) scratching my itchy brain! --- ## Test it The snippet below will output the first 50 terms. ``` s=`122` x=1 f=n=>s[n]||f(n,s+=s[++x%2]*(s[x]+0-9)) o.innerText=[...Array(50).keys()].map(f).join`, ` ``` ``` <pre id=o></pre> ``` --- ## Explanation This is one of those rare occasions when we can declare some variables outside the scope of our function, modify them within the function and still be able to reuse them on subsequent calls of the function. ``` s=`122` :Initialise variable s as the string "122" x=1 :Initialise variable x as integer 1 f=n=> :Named function f taking input as an argument through parameter n s[n] :If s has a character at index n, return it and exit || :Or f(n :Call f with n again ,s+= :At the same time, append to s s[++x%2] : Increment x, modulo by 2 and get the character at that index in s * : Multiplied by (the above gets cast to an integer) (s[x]+0-9) : Append a 0 to the xth character of s and subtract 9 ) : (The above gives "1"+0-9="10"-9=1 or "2"+0-9="20"-9=11) ``` [Answer] # [Haskell](https://www.haskell.org/), 48 bytes *-1 byte thanks to nimi. -2 bytes thanks to Lynn.* ``` c=1:2:c l=1:2:drop 2(id=<<zipWith replicate l c) ``` [Try it online!](https://tio.run/##HcUxDoAgDAXQ3VP8wUE3ZSRwDmdSm9BQkSCTl6@Jb3k5PYVVzSju3nma9P/sd4Nb5IwhvNIOGRmdmwqlwVDQaleSiojWpQ7MGKkw3Aa1Dw "Haskell – Try It Online") Repeat every element its position mod 2 + 1 times. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~13~~ 12 bytes ``` 0:{:1+n?:0=! ``` [Try it online!](https://tio.run/##S8sszvj/38Cq2spQO8/eysBW8f9/AA "><> – Try It Online") A port of Martin Ender's [Wumpus answer](https://codegolf.stackexchange.com/a/157469/8478). Unfortunately, `><>` doesn't have an increment or an invert command nor does it have implicit 0s on the bottom of the stack, so this ends up being a bit longer. [Answer] # [Fueue](https://github.com/TryItOnline/fueue), 30 bytes Fueue is a queue-based esolang in which the running program and its data are both in the same queue, the execution goes around the queue in cycles, and programming requires lots of synchronizing to keep anything from executing at the wrong time. ``` 1)2:[[2:])~)~:~[[1]:~))~:~~]~] ``` [Try it online!](https://tio.run/##SytNLU39/99Q08gqOtrIKlazTrPOqi462jDWqk4TxKyLrYv9/x8A "Fueue – Try It Online") The above prints an unending list of digits as control codes. For 34 bytes it can print actual digits: ``` 49)50:[[50:])~)~:~[[49]:~))~:~~]~] ``` [Try it online!](https://tio.run/##SytNLU39/9/EUtPUwCo6GkjEatZp1lnVRUebWMZa1WmC2HWxdbH//wMA "Fueue – Try It Online") The rest of the explanation uses the latter version. # Summary of Fueue elements The Fueue queue can contain the following kind of elements: * Integers, which print their Unicode codepoint when executed, * Square-bracket delimited subprogram blocks, which are mercifully inactive (just moving to the end of the queue) unless the `)` function *deblocks* them, and * Single-character functions, which execute if they are followed by the right type of arguments and remain inactive otherwise. + The only functions used in this program are `~` (swap two following elements), `:` (duplicate next element), and `)` (deblock following block). # High level overview During the main loop of the program, the queue consists of: * a chain of blocks representing digits to be iterated through; + A digit 1 or 2 is represented by the blocks `[49]` and `[50:]`, respectively. * a self-replicating main loop section that traverses the digit blocks and puts alternating 1s and 2s after them, then deblocks them. + An deblocked digit block prints its own digit *d*, and then creates *d* copies of the following block, thus creating the digits for the run it describes. # Low level trace of first 10 commands ``` Cmds Explanation Queue 49 Print '1'. )50:[[50:])~)~:~[[49]:~))~:~~]~] ) Inactive, move to end. 50:[[50:])~)~:~[[49]:~))~:~~]~]) 50 Print '2'. :[[50:])~)~:~[[49]:~))~:~~]~]) :[...] Duplicate block. )[[50:])~)~:~[[49]:~))~:~~]~][[50:])~)~:~[[49]:~))~:~~]~] )[...] Deblock (rmv. brackets). [[50:])~)~:~[[49]:~))~:~~]~][50:])~)~:~[[49]:~))~:~~]~ [...] Inactive. [50:])~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~] [50:] Inactive. )~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:] ) Inactive. ~)~:~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:]) ~)~ Swap ) and ~. :~[[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:])~) :~ Duplicate ~. [[49]:~))~:~~]~[[50:])~)~:~[[49]:~))~:~~]~][50:])~)~~ ``` # Walkthrough of a full main loop iteration Optional whitespace has been inserted to separate commands. ``` 49 ) 50 :[[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 1: `49` prints `1`. `)` is inactive, waiting to be brought together with the main loop block. `50` prints `2`. `:` duplicates the main loop block (which needs a copy for self-replication.) ``` ) [[50:])~)~:~[[49]:~))~:~~]~] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 2: `)` deblocks the first main loop block, making it start executing next cycle. ``` [50:] ) ~)~ :~ [[49]:~))~:~~] ~[[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 3: `[50:]` represents the first digit produced in the chain, a `2` not yet deblocked. The following `)` will eventually do so after the rest of the main loop has traversed it. `~)~:~` is a golfed (using a swap and a copy) one-cycle delay of `~)~~`. `[[49]:~))~:~~]` is inactive. `~` swaps the following main loop block past the `[50:]` digit block. ``` ) ~)~ ~[[49]:~))~:~~][50:] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 4: `)` still waits, `~)~` produces `~)`, `~` swaps `[[49]:~))~:~~]` past the `[50:]` digit block. ``` ) ~)[50:] [[49]:~))~:~~] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 5: `~` swaps `)` past the `[50:]` digit block. ``` )[50:] )[[49]:~))~:~~] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 6: The first `)` now deblocks the `[50:]` digit block, the next `)` deblocks the subprogram `[[49]:~))~:~~]`. ``` 50 :[49] :~ ) ) ~:~ ~[[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 7: `50` prints `2`, `:` duplicates the just produced `[49]` digit block, creating a run of two `1`s. `:~))~:~` is a one-cycle delay of `~~))~:`. `~` swaps the remaining main loop block past the first `[49]`. ``` [49] ~~) ) ~:[49] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 8: `~~))` is a one-cycle delay of `)~)`. `~` swaps `:` past the currently traversed `[49]`. ``` [49] ) ~)[49] :[[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 9: `~` swaps `)` past `[49]`. `:` duplicates the main loop block. ``` [49] )[49] )[[50:])~)~:~[[49]:~))~:~~]~] [[50:])~)~:~[[49]:~))~:~~]~] ``` Cycle 10: The first `)` deblocks the `[49]` digit block just traversed, the second `)` restarts the main loop to traverse the next one (above shown at the beginning of the queue.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 9 bytes Saved 3 bytes thanks to *Grimy* Prints the first **n** items. ``` Δ2LÞsÅΓI∍ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//3BQjn8Pzig@3npvs@aij9/9/IwMA "05AB1E – Try It Online") **Explanation** ``` Δ # repeat until ToS doesn't change 2LÞ # push [1,2,1,2 ...] sÅΓ # run-length encode with previous value (initially input) I∍ # extend/shorten to the length specified by input ``` [Answer] # Python (2 and 3), ~~65~~ 60 bytes ``` f=lambda n:sum([f(i)*[i%2+1]for i in range(2,n)],[1,2,2])[n] ``` Returns the **n**th entry, 0-indexed. Alternative (65 bytes): ``` f=lambda n:n>1and sum([f(i)*[i%2+1]for i in range(n)],[])[n]or-~n ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 61 bytes ``` +.+.[.[>]>+++>+++<<<[->+>->-<<<]<[[->+<]<]>>--[[>]<,<[<]>+]>] ``` [Try it online!](https://tio.run/##FYpBCoBADAMfFLsvCPlI6EEFQQQPC76/dg9hZiDH3O/3@s6nCgPDw0oBWCPpEBSK1qRXNVOKcB@50V1IZdUP "brainfuck – Try It Online") Prints numbers as char codes indefinitely. For clarity, [here's a version](https://tio.run/##lYxBCoBADAPP7VfW7gtCPlJ6UEEQwYPg@2v3sncDgQkk2Z71vI93vzJbb11dpU39Y1HpKjb1j1WcwboZBuDGRqMVhgp8ZMRg0syrjAWOmgQ1Mj8) that prints in numbers (except for the first two elements, which are easy enough to verify). ### How It Works: ``` +.+. Prints the first two elements. These are the self-referential elements This also intitialises the tape with the third element, 2 [ Start infinite loop . Print current lowest element [>]>+++>+++ Move to end of tape and create two 3s <<<[->+>->-<<<] Subtract the last element of the tape from these 3s <[[->+<]<]>> Move to the beginning of the tape -- Subtract two from the first element This leaves 2 as 0 and 1 as -1 [ If the number was 1 [>]<, Delete the excess element from the end of the tape <[<]>+ Remove the -1 ] > Move to the next element of the list ] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` ƵLS[DNÌ©èF®É>¸« ``` [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8a1TFNbRE7DjMKpw6hGwq7DiT7CuMKr//8 "05AB1E – Try It Online") or [with an iteration limit](https://tio.run/##ASoA1f8wNWFiMWX//8a1TFNbw69JTlEjRE7DjMKpw6hGwq7DiT7CuMKr//8xMDA) **Explanation** ``` ƵLS # push our initial list [1,2,2] [ # for every N in [0 ... D # duplicate current list of numbers NÌ©è # get the N+2'th element from the list F # that many times do ®É> # push ((N+2)%2==1)+1 ¸« # append to current list ``` [Answer] # [Perl 5](https://www.perl.org/), 36 bytes Still a trivial modification of the classic TPR(0,3) solution: Outputs the series from `0` to `n` ``` #!/usr/bin/perl use 5.10.0; say$_=($n+=!--$_[$n])%2+1for@_=0..<> ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIl3lZDJU/bVlFXVyU@WiUvVlPVSNswLb/IId7WQE/Pxu7/f4t/@QUlmfl5xf91fU31DA30DAA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~55~~ 54 bytes ``` n=h=1;l=[] while n:print(h);n^=3;h,*l=l+[n]*(l+[2])[0] ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P882w9bQOsc2OparPCMzJ1Uhz6qgKDOvRCND0zovztbYOkNHK8c2Rzs6L1ZLA0gZxWpGG8T@/w8A "Python 3 – Try It Online") [Answer] # R, 63 bytes or 61 bytes **Implementation 1:** prints out the *n*th term of the sequence. ``` x=scan() a=c(1,2,2) for(n in 3:x)a=c(a,rep(2-n%%2,a[n])) a[x] ``` **Implementation 2:** prints out the first *n* terms of the sequence. ``` x=scan() a=c(1,2,2) for(n in 3:x)a=c(a,rep(2-n%%2,a[n])) a[1:x] ``` *(The difference is only in the last line.)* Yes, yes, you may complain that my solution is inefficient, that it computes really more terms than needed, but still... **Update:** Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) for shaving off 9 bytes. [Answer] # x86, ~~41~~ ~~37~~ ~~35~~ ~~33~~ 28 bytes I had a lot of fun messing around with different x86 instructions, as this is my first "non-trivial" x86 answer. I actually learned x86-64 first, and I saved many bytes just by converting my program to 32-bit. It turns out the algorithm I used from OEIS pushes values to an array, which makes it amenable to x86 and storing values on the stack (note MIPS doesn't have stack instructions). Currently the program takes `N` values as input in `ecx` and returns an address in `ebp` of an array with the nth element representing the nth value in the sequence. I assume returning on the stack and computing extra values is valid (we consider what's beyond the array as garbage anyway). **Changelog** * -4 bytes by computing `x = 2 - n%2` with `xor` every iteration * -2 bytes by using do-while instead of while loop. * -2 bytes by pushing initial values 1, 2, 2 using `eax` * -5 bytes by not storing `n` explicitly and instead running loop `N` times ``` .section .text .globl main main: mov $10, %ecx # N = 10 start: mov %esp, %ebp # Save sp push $1 push $2 # x = 2 pop %eax push %eax # push 2 push %eax # push 2 mov %esp, %esi # sn = stack+3 addr loop: xor $3, %al # flip x between 1 <-> 2 push %eax # push x # maybe use jump by parity? cmp $2, (%esi) # if *sn == 2 jne loop1 push %eax # push x loop1: sub $4, %esi # sn += 1 loop loop # --N, do while (N) end: mov %ebp, %esp # Restore sp ret ``` Objdump: ``` 00000005 <start>: 5: 89 e5 mov %esp,%ebp 7: 6a 01 push $0x1 9: 6a 02 push $0x2 b: 58 pop %eax c: 50 push %eax d: 50 push %eax e: 89 e6 mov %esp,%esi 00000010 <loop>: 10: 34 03 xor $0x3,%al 12: 50 push %eax 13: 83 3e 02 cmpl $0x2,(%esi) 16: 75 01 jne 19 <loop1> 18: 50 push %eax 00000019 <loop1>: 19: 83 ee 04 sub $0x4,%esi 1c: e2 f2 loop 10 <loop> 0000001e <end>: 1e: 89 ec mov %ebp,%esp 20: c3 ret ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 72 71 65 64 62 bytes -9 bytes thanks to @ceilingcat ``` x,y;f(z){for(x=y=-1;putchar(49-~x%2);y=-~y|z&x/2)x^=z=y&~-~y;} ``` [Try it online!](https://tio.run/##S9ZNT07@/79Cp9I6TaNKszotv0ijwrbSVtfQuqC0JDkjsUjDxFK3rkLVSNMaKFpXWVOlVqFvpFkRZ1tlW6lWBxSxrv2fm5iZpwHUrKEJ5AAA "C (gcc) – Try It Online") Generates values of the sequence indefinitely (option 3 from the challenge) [Answer] # Javascript ES6 - ~~71~~ ~~70~~ 68 bytes ``` (_="122")=>{for(x=1;;_+=(1+x%2)*(_[x]>1?11:1))console.log(_[++x-2])} ``` 1 bit saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) Tanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for correcting my mistake, also for saving 1 bit. ``` f = (_="122") => { for(x=1;x<20;_+=(1+x%2)*(_[x]>1?11:1)) document.getElementById('content').innerHTML += ' ' + _[++x-2] } f() ``` ``` <div id="content"></div> ``` [Answer] # [Appleseed](https://github.com/dloscutoff/appleseed), 89 bytes ``` (def K(lambda()(concat(q(1 2))(drop 2(flatten(zip-with repeat-val(cycle(q(1 2)))(K))))))) ``` Defines a function `K` that takes no arguments and returns the Kolakoski sequence as an infinite list. [Try it online!](https://tio.run/##NY1BDsIwDATvfYV7Wx8qQSVe0VeYxBURITWpVQSfD4fA3GdGzLLuqrE1RF1pQZbHNQoYYStBHE@caWZGrJvRjDWLuxZ8kk2v5Deqaio@HZIR3iHrX2As3Onl3aX6ONBvQNBDi/NABKup@EhwuStdTtTN9gU "Appleseed – Try It Online") This approach was inspired by [totallyhuman's Haskell answer](https://codegolf.stackexchange.com/a/157442/16766). My [original approach](https://tio.run/##VY9BEoIwDEX3nuKzSxfOIB7As0QI2qG2TBtceHksFhjMKsn8/37C4@gkiXTzTJ30GILjIaTBnkCOX/eOQRQnf/bTC7UBdfZhFRdjTgDZHvSRGG5YJcsW1AbfsmaATVmKBk027uQ8F/smXFpQlFFYz292KBnk9blxD3ZTvEcgWd/uF4DSdMe1QMyvymtJOWq1nL09Jm/xutLGaL1WIOVBcK3/AzPiCw "Appleseed – Try It Online") was longer *and* was probably O(2^n). :^P ### Ungolfed ``` (def kolakoski (lambda () (concat (list 1 2) (drop 2 (flatten (zip-with repeat-val (cycle (list 1 2)) (kolakoski))))))) ``` The return list begins with `(1 2)`. After that, to generate the rest of it (reading from the inside out): * Recursively call `(kolakoski)` to get the Kolakoski sequence list (due to lazy evaluation, it doesn't matter that the list hasn't been fully generated yet) * `(cycle (list 1 2))` creates an infinite list `(1 2 1 2 1 2 ...)` * Zip the two infinite lists together using the function `repeat-val`. This will repeat the `1` or `2` from the `cycle` list either one or two times depending on the associated value in the Kolakoski list. Result: `((1) (2 2) (1 1) ...)` * `flatten` that list into `(1 2 2 1 1 ...)` * We've already got the first two terms from `(concat (list 1 2)`, so we `drop` the first two from the generated list to avoid duplication. [Answer] # [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╦╥2Bïß▄n»-[╒ ``` [Run and debug it](https://staxlang.xyz/#p=cbd232428be1dc6eaf2d5bd5&i=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&a=1&m=2) This is the ascii representation of the same program. ``` G@}2R;D{|;^]*m$ ``` It expands the sequence x times where x is the input. Then it outputs the xth element, 0-indexed. ``` G } G jumps to trailing } and returns when done @ get xth element in array 2R [1, 2] ;D repeat the rest x times { m map array using block |;^] produces [1] and [2] alternately * repeat array specified number of times $ flatten array ``` [Here's](https://staxlang.xyz/#p=81d7d96043d2e2cdf028a23a&i=) a bonus 12-byte solution that produces output as an infinite stream. Press Run to start. [Answer] # Shakespeare Programming Language, 575 bytes (but defective), or 653 or 623 bytes ``` ,.Puck,.Ford,.Act I:.Scene X:.[Enter Puck and Ford]Ford:You big cat!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you nicer zero?If not,let us Scene X.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L. ``` In the hotly contested SPL category, this would beat Jo King's current entry (583 bytes), except that it is defective: First, it does not run in the TIO version (implementing the SPL website) -- but it does run in the [Perl version](http://search.cpan.org/dist/Lingua-Shakespeare/lib/Lingua/Shakespeare.pod "perl version"), so maybe that is not a serious defect. Second, though, it does not print the first two digits. If we allowed that defect in Jo King's solution, then that defective solution would be 553 bytes, beating my defective solution. My solution fails on TIO for two reasons: we try to rely on an empty stack returning zero when popped; and we goto the first scene, with "[Enter Ford and Puck]" even though nobody has left the stage. These are merely warnings in the Perl version. If I fix these errors *and* put in the first two digits, I reach 653 bytes: ``` ,.Puck,.Ford,.Act I:.Scene I:.[Enter Puck and Ford]Ford:You cat!Open heart!You big cat!Open heart!You zero!Scene X:.Ford:Remember you!You big cat!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you nicer zero?If not,let us Scene X.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L. ``` [Try it online!](https://tio.run/##hZHLasMwEEV/Zbw3@gBtShctCBxaWigJIQtFmTSmshT0ICQ/7@jlxG5Mu7Gt0Zm5947tUfZ9Td69@KnJqza7mjwLB4yST4EK48f6RTk0EBHgageR2sQHXWkPgrvq7YgKDsiNq2Jp237PlS9odJWnLmnSoh/YYbcNw8/aT1oz1hSMWWCgWhHAOOSJ7cHqWqIDbyGjXyRAYUrB@DCpsPGmteAOCNZ3oPeJzZRskWRK3w2PvGeBBU1LmloeGeNJbZSB3JXjqeQVXMpqYnVIpLSbRlr@EekBXpDVPxHLnuY2X3RO2lgsHb@00v0tWMa5TZXwerB2Lr97xhSLvcMq0zaacY6G9P0V "Shakespeare Programming Language – Try It Online") I can generate the full sequence in the Perl implementation using 623 bytes: ``` ,.Puck,.Ford,.Act I:.Scene I:.[Enter Puck and Ford]Ford:You cat!Open heart!You big cat!Open heart!Scene L:.Ford:Is I nicer zero?If so,let us Scene V.Is you nicer a big cat?If so,you is the sum of you a big lie.If so,open heart!Open heart!Scene M:.Puck:Remember you!Is I nicer a cat?You big cat.If so,you cat.Ford:Recall!Is you worse a cat?If so,you big cat!If so,let us Scene L.Is you nicer a big cat?If not,let us Scene M.You is the sum of you a big lie.Scene V:.Ford:Remember you!Is you worse a big big cat?If not, you big cat.Is you as big as a big cat?If not,you zero.You is the sum of I you.Puck:Recall!Let us Scene L. ``` However, I would point out that this solution is *fast* compared to many other solutions, and uses logarithmic amounts of memory rather than storing the whole list. (This is similar to vazt's C solution, to which it is distantly related.) This makes no difference for golf, but I'm pleased with it even so. You can generate a million digits in about a minute in Perl (for example if you pipe to sed and wc to get a digit count), where the other solution might give you a few thousand digits. ## Explanation We store a sequence of variables in order: Puck's stack (bottom to top), Puck's value, Ford's value, Ford's stack (top to bottom). Apart from zero values at the ends (with the zero on the left maybe from popping an empty stack), each value is the digit generated next at that generation, with 2 added if the next generation needs to have another child from that parent. When we have N non-zero values in the sequence, we generate all the children up to and including the N-th generation, in a kind of depth-first tree traversal. We print values only from the N-th generation. When the N-th generation has been completely generated, the stored values are in fact the starting values for generations 2 to (N+1), so we append a 2 at the left and start again, this time generating the (N+1)-th generation. So, an outline: Scene X: When we reach here, this the start of a new traversal. Puck==0. We optionally push that zero onto Puck's stack, and set Puck=2. Scene L: If Ford==0, we have reached the printing generation. If not, goto V. For printing, if the value in Puck has had 2 added, remove the 2 and print it twice; if not, print it once. Scene M: This is a loop where we repeatedly toggle the value of Puck and go back through the sequence. We repeat until either we reach the end (Puck==0), in which case goto X, or we reach a value that needs another child (Puck>2), in which case subtract the extra 2 and go forwards in V. Scene V: Here we go forwards. If Puck is 2 or 4, the next generation will contain two children from the current parent, so Ford+=2. Step forwards through the sequence. Goto L to check for termination. ]
[Question] [ Doing code review, I stumbled upon the following code, that tests the status of a checkbox: ``` if (!isNotUnchecked()) { ... } ``` I had to brainstorm for 30 minutes to find out what actual checkbox status the code was expecting. Please write me a program that can simplify these silly expressions! --- The program should accept as input a string representing the expression to simplify (for example: `!isNotUnchecked()`). The program should output a logically equivalent simplified expression, either `isChecked()` or `!isChecked()`. The method name in the input expression always starts with `is`, contains 0..n `Not`, and ends with `Checked()` or `Unchecked()`. The method can be prefixed by any number of `!`. ## Examples ``` isChecked() => isChecked() isUnchecked() => !isChecked() isNotChecked() => !isChecked() !isNotChecked() => isChecked() !!!isNotNotUnchecked() => isChecked() ``` [Answer] # [Python](https://docs.python.org/2/), 51 bytes ``` lambda s:sum(map(s.count,'!NU'))%2*'!'+'isC'+s[-8:] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQbFVcmquRm1igUayXnF@aV6KjrugXqq6pqWqkpa6orq2eWeysrl0crWthFfu/PCMzJ1XB0KqgKDOvRCFNIzOvoLREQ1PzvxJQVUZqcnZqioamEheQF5qXjML3yy9BVqCIKaIIEQMiZL0A "Python 2 – TIO Nexus") [Answer] ## [Retina](https://github.com/m-ender/retina), 23 bytes ``` Unc !C Not ! O`is|! !! ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/gfmpfMpejM5ZdfwqXI5Z@QWVyjyKWoyPX/f2axc0ZqcnZqioYmV2YxUBkSD6gaIamIzleEiAARki4A "Retina – TIO Nexus") ### Explanation ``` Unc !C ``` Turn `Unchecked` into `!Checked`. ``` Not ! ``` Turn all `Not`s into `!`. We now get something like `!!!is!!!!Checked()`. ``` O`is|! ``` Sort all matches of either `is` or `!`. Since `! < is`, this moves all the `!` to the beginning of the string, so the above example would become `!!!!!!!isChecked()`. ``` !! ``` Remove pairs of `!` to cancel repeated negation. [Answer] # [///](https://esolangs.org/wiki////), 26 bytes ``` /Unc/NotC//isNot/!is//!!// ``` [Try it online!](https://tio.run/nexus/slashes#@68fmpes75df4qyvn1kMpPUVM4v19RUV9fX/ZxY7Z6QmZ6emaGhyZRYD1SHxQDrgXEV0viJEBIiQdP0HAA "/// – TIO Nexus") Port of my [Retina answer](https://codegolf.stackexchange.com/a/120010/48934). [Answer] # [Python](https://docs.python.org/), 43 bytes ``` lambda s:sum(map(ord,s))%2*'!'+'isC'+s[-8:] ``` An unnamed function taking the string, `s` and returning a string. **[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQbFVcmquRm1igkV@UolOsqalqpKWuqK6tnlnsrK5dHK1rYRX7vyS1uKRYwVZBAySakZqcnZqioamuA@SF5iWj8P3yS5AVKGKKKELEgAhZryZXWn6RAsgehcw8MF1sxcVZUJSZV6IB4ukoqNvaqesopIF5mpr/AQ "Python 3 – TIO Nexus")** No need to check for existence of characters when `!`, `Not`, and `Un` all have exactly one odd ordinal (and `c` and `C` are both odd), so just sum up the ordinals and use the value modulo 2 to decide if we want a `!` or not. Other than that the form is the same as [xnor's answer](https://codegolf.stackexchange.com/a/120014/53748), as I didn't find anything better. The following is also 43: ``` lambda s:'!isC'[~sum(map(ord,s))%2:]+s[-8:] ``` [Answer] ## JavaScript (ES6), ~~51~~ 50 bytes ``` f= s=>(s.split(/!|n/i).length%2?'':'!')+'isChecked()' ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` Works by looking for `!`, `N`, and `n` characters, which invert the checked state. `split` returns an odd array length by default, so we add the `!` when the `split` length is even. Edit: Saved 1 byte thanks to @ETHproductions. Alternative version, also for 50 bytes: ``` s=>`${s.split(/!|n/i).length%2?``:`!`}isChecked()` ``` [Answer] # [Retina](https://github.com/m-ender/retina), 24 bytes ``` Unc NotC +`isNot !is !! ``` [Try it online!](https://tio.run/nexus/retina#@x@al8zll1/izKWdkFkMZHApZhZzKSpy/f@fWeyckZqcnZqiocmVWQxUh8QD6YBzFdH5ihARIELSBQA "Retina – TIO Nexus") [Answer] # Java 7, ~~100~~ 77 bytes ``` String c(String s){return(s.split("[!NU]").length%2<1?"!":"")+"isChecked()";} ``` **Expanation:** ``` String c(String s){ // Method with String parameter and String return-type return(s.split("[!NU]").length // Count the amount of '!', 'N' and 'U' in the input String (+ 1) %2<1? // and if they are an even number: "!" // Start with an examination mark : // Else: "") // Start with nothing +"isChecked()"; // And append "isChecked()" to that } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#lY5BC4JAEIXv/opxINglWKhjBh0650U8iYdtXXRpXcUdgxB/uxl5iSAM5vDgfXxvlJXew2UIADxJMgqmhDrjSlBsCZ4Pnaa@c8wL31pDDLMwTnPkwmpXUrXZH3cnDPGAyLdo/LnS6qYLxjEaJ4C2v9rZu@jvjSmglsYt@iwHyV/zAMnDk65F05No54qsY4p9@DiPfpKpU6vZuKG14vA/Onzz833/Mwbj9AQ) ``` class M{ static String c(String s){return(s.split("[!NU]").length%2<1?"!":"")+"isChecked()";} public static void main(String[] a){ System.out.println(c("isChecked()")); System.out.println(c("isUnchecked()")); System.out.println(c("isNotChecked()")); System.out.println(c("!isNotChecked()")); System.out.println(c("!!!isNotNotUnchecked()")); } } ``` **Output:** ``` isChecked() !isChecked() !isChecked() isChecked() isChecked() ``` [Answer] # [Aceto](https://github.com/L3viathan/Aceto), 49 bytes ``` &M"pp" L!)(de &c;`Che" `!d!sick !',@p"!' 'N'U`!Lu ``` yadda yadda Hilbert curve. First of all, we push the three important characters on the stack: ``` !' 'N'U ``` Then we set a catch mark and start by reading a single character. We `d`uplicate it and negate it, and if the result of this is truthy (so if the string was empty; so the input ended), we jump to the end: ``` ;` d! ,@ ``` With the remaining copy of the input character, we check whether it is contained in the rest of the stack (i.e. if its one of !, N, U). If it's not, we raise an error, throwing us back to our catch mark where we read another character: ``` &c `! ``` Otherwise, we load what's on quick storage (essentially a register that's initially an empty string; falsy), negate it and send it back to quick storage, then raise the error too (going back to reading characters): ``` &M L! ``` When the input stopped, we are sent to the end. There, we reverse the direction, push an exclamation mark, and load quick storage and negate it. If that is truthy (i.e. we've had an odd number of negation things), we print the exclamation mark we've pushed: ``` p !' `!Lu ``` Finally, we push the string in two parts and print them (for space saving reasons): ``` "pp" )(de Che" sick " ``` Afterwards, the program still runs back to the original beginning, but since none of the commands output anything or have loopy behaviour, that doesn't matter. Actually, the first non-nopping command we reach raises an exception, skipping a majority of the code because we jump to the catch mark, meaning all Aceto sees in that part is: ``` & !' @ 'N'U ``` Since `U` is now not preceeded by a single-quote character and is therefore not seen as a character literal, it gets interpreted as a command: `U` reverses all the elements on the stack (now it's `!`, `N`, `U`, from the top), and `'N` and `'!` push more characters, meaning we end with the stack `[U, N, !, N, !]`. *Side note: This is the first Aceto program written (in part) with the help of [Aceto's new editor](https://asciinema.org/a/57a0wa44k6lowek7amt4fu649).* [Answer] ## C, ~~78~~ ~~70~~ 68 Bytes Thank you Christoph! ``` c;f(char*s){for(c=1;*s;)c^=!!strchr("!NU",*s++);s="!isChecked()"+c;} ``` [Try it online](https://tio.run/nexus/c-gcc#bY8xa8NADIVn36/QHQTuzi60s7gu2bNlalIwio1N6bmcRBbjn93ZUdIMpSlIGh7S0/dWwt7T0JbIYe6n4im9YGQM9J6sZSk0FO/sbu@ayHUdkJOzI2@Hjj66kw@uJlzWMQt8tmP2cJ7GEwQzm@pmCtKxvB0hwQymqtzvy@au7DM9aLtJ/i7a/1X7o2s9@DzrWNDcUZQFTaURwYvyXMEQorZorOv6V9EYvXcbhvQKGz5ktYnSQO@jhIBmWb/z9EStvrkA) Output: ``` isChecked() => isChecked() isUnchecked() => !isChecked() isNotChecked() => !isChecked() !isNotChecked() => isChecked() !!!isNotNotUnchecked() => isChecked() ``` [Answer] # [Perl 5](https://www.perl.org/), 31 bytes *-2 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings).* 30 bytes of code + `-p` flag. ``` /c/i;$_="!"x(y/UN!//%2).isC.$' ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K@frJ9prRJvq6SoVKFRqR/qp6ivr2qkqZdZ7Kynov7/P5DOSE3OTk3R0OTKLA7NS0bi@eWXICQV0fkQASBC1qSIVRgA "Perl 5 – TIO Nexus") `y/UN!//` counts the number of occurrences of `Un`, `Not`, and `!`. The result is that many `!` modulo 2, followed by `isChecked()`. --- Another attempt, based on regex, for 38 bytes (Dom Hastings saved 1 byte on that one): ``` s/isNot|isUn(c)/!is\u$1/?redo:s/!!//g ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@F@sn1nsl19Sk1kcmqeRrKmvmFkcU6piqG9flJqSb1Wsr6ior5/@/39msXNGanJ2aoqGJhdIaTISD6gdIamIzocIABGyJkWswgA "Perl 5 – TIO Nexus") [Answer] # [Scala](http://www.scala-lang.org/), ~~39~~ 30 bytes ``` s=>"!"*(s.sum%2)+"isChecked()" ``` [Try it online!](https://tio.run/nexus/scala#dUxNC4IwGL73K94Ngq1gh46FQnStLtIPWPNVZ7oNNyMQf7uNgkgieA7Pt73WqAKcpDaAj4Am97B3Dga4ywaKLWSh06aEJP0wGCafpJTQFfPC9@1yw9dU@0OF6oY543Qad68147Gsrchs3ykUPuTaiBLDURv0opWOFVwUtkOpKubieWgMh3GanS2iuhg102cbvgvk1yFvL2K@JX@SJw "Scala – TIO Nexus") Unfortunately I couldn't get it to deduce the type of s. Edit: Moved the type declaration to the header (I think this is allowed, if not I'll put it back). [Answer] # [Ruby](https://www.ruby-lang.org/), 40 bytes ``` ->x{?!*(x.count('!UN')%2)+'isChecked()'} ``` [Try it online!](https://tio.run/nexus/ruby#S7T9r2tXUW2vqKVRoZecX5pXoqGuGOqnrqlqpKmtnlnsnJGanJ2aoqGpXvu/KDUxJSczL7VYLzexoLqmoqagtKRYITG6Irb2vxKSUiUuIC80LxmF75dfgqxAEVNEESIGRMh6AQ "Ruby – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes ``` …Unc„!C:'€–™'!:'!†„!!K ``` [Try it online!](https://tio.run/nexus/05ab1e#qymr/P@oYVloXvKjhnmKzlbqj5rWPGqY/Khlkbqilbrio4YFIHFF7/@VSof3K9jaKRzer6TzP7PYOSM1OTs1RUOTK7MYqBmJ55dfgpBUROcrQkSACFmXInZxAA "05AB1E – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes ``` ÇOÉ'!×…isCyR8£RJ ``` [Try it online!](https://tio.run/nexus/05ab1e#qymr/H@43f9wp7ri4emPGpZlFjtXBlkcWhzk9b9S6fB@BVs7hcP7lXT@A8UzUpOzU1M0NLkyi0PzkpF4fvklCElFdL4iRASIkHUpYhcHAA "05AB1E – TIO Nexus") Uses the trick of summing the ordinals from [Jonathan Allan's python answer](https://codegolf.stackexchange.com/a/120046/47066). **Explanation** ``` ÇO # sum of ascii values of input É # is odd '!× # repeat "!" that many times …isC # push the string "isC" IR8£R # push the last 8 chars of input J # join everything to string ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~24~~ 23 bytes ``` o"!N" l u)ç'! +`‰C”×B() ``` # Explanation ``` o"!N" l u)ç'! +`‰C”×B() Uo"!N" l u)ç'! +`‰C”×B()` Uo"!N" # Only keep "!", "n" and "N" from the input ç'! # Repeat the string "!" by l u) # the parity of the length of the newly formed string +`‰C”×B()` # and concatenate with the string "isChecked()" ``` [Try it online!](https://tio.run/nexus/japt#@5@vpOinpJCjUKp5eLm6ooJ2wqFO50NTDk930tD8/19JMbPYL7/EOSM1OTs1RUNTCQA "Japt – TIO Nexus") [Answer] ## PHP (5.5 - 5.6), ~~52~~ ~~50~~ 49 Bytes ``` <?='!'[count(spliti('!|N',$argn))%2]?>isChecked() ``` Try it [here](http://sandbox.onlinephpfunctions.com/code/12de9387b5efbc4d90f85439f33dfd291dd19ada). ``` -2 Bytes by @Titus. Ty :) -1 Byte by @ETHproductions. Ty :) ``` ## PHP (>=5.5), ~~66~~ ~~65~~ 61 ``` for($b=b;$a=$argn[$i++];)$b^=$a;echo$b&"!"|" ","isChecked()"; ``` Without regex it gets a bit more compex :) Try it [here](http://sandbox.onlinephpfunctions.com/code/1c1f850c8bf8ded4d60361c8f95ffd90d7df4b28). ``` -4 Bytes by @Titus. Ty :) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` OSḂ⁾!iṫ⁾sCø³ṫ-7 ``` A full program that takes the string as a command line argument and prints the result **[Try it online!](https://tio.run/##y0rNyan8/98/@OGOpkeN@xQzH@5cDaSLnQ/vOLQZyNY1////v6KiYmaxX34JEIXmJWekJmenpmhoAgA)** `OSḂ⁾!iṫ-7³ṫṭ⁾sC` or `OSḂ⁾!iṫ-7³ṫ⁾sC;` would both also work for 15. ### How? Uses the same idea as [my Python answer](https://codegolf.stackexchange.com/a/120046/53748), but saves bytes using a different construction of `!isC` or `isC` and some implicit printing in Jelly... ``` OSḂ⁾!iṫ⁾sCø³ṫ-7 - Main link: s O - cast to ordinals S - sum Ḃ - mod 2 ⁾!i - literal ['!','i'] ṫ - tail -> ['i'] if OSḂ was 0; ['!','i'] if OSḂ was 1 - this is printed due to the following starting a new leading - constant chain. Printing smashes so either "i" or "!i" is printed. ⁾sC - literal ['s','C'] - this is printed (as "sC") due to the following niladic chain. ø - start a new niladic chain ³ - program's first input (3rd command line argument), s ṫ-7 - tail from index -7 = ['h','e','c','k','e','d','(',')'] - implicit print (of "hecked()") ``` previous @ 16 bytes 9 (using concatenation and pairing with the same underlying idea): ``` OSḂ⁾!iṫ;⁾sC,ṫ€-7 ``` [Answer] # [Perl 6](https://perl6.org), ~~35~~ 31 bytes ``` {'!'x m:g/<[!NU]>/%2~'isChecked()'} ``` [Try it](https://tio.run/nexus/perl6#dc7LTsMwEAXQvb/iegG205BIILEgTYTUfTfQFWFRnKG1aB7CDiqqmh9jx48FNzyUgpAsS55zPTOtJbxcRjph5StOdV0Q0n4nuNiivFrF0zs@X9xn8cl5J4ydrUk/USGV2Pc@fu3IOqTYmIqsVO9vka7LBxkjv0EQ4CKKAsQqYa2fceujCWs2ywqT4V/CHuvnrxZnGWRuqqZ1YU7bhrSjQmHHAGNx2EkOqEJ8a4ihgg4Caeav7ofYvh9tetDRkxm7qPQY@bHOazf7l/lfP2L@GfDn15BR6gM "Perl 6 – TIO Nexus") ``` {'!'x tr/!NU//%2~'isChecked()'} ``` [Try it](https://tio.run/nexus/perl6#dY7BasJAEIbv@xT/gu3upmkWWuglRATvXqy3XOpmSpdqEtxNsYh5MW99sXTVKrEiLAM73zfzT@MIXy@JSdnyG/emKghZtxFcrOFXmk9mWt89tcK68QeZTyqkEtsuqCNPziPDwpbkpPrZJaZazqVGPkUU4TlJImiVsibsfw1qyurFW4mHw1zK3qvV34rHIWRuy7rxcU7rmoynQmHDAOuwv0eGtEFIOjgqxkmKjx20EMiGobRnxLZd7@A97X2ZdbPS9CG/pJPKj29ifs0vMD8K4f0L6Vm/ "Perl 6 – TIO Nexus") (requires mutable input string which will be mutilated) ## Expanded: ``` { #( '!' x # string repeat # m:g/<[!NU]>/ tr/!NU// # find the number of negatives % 2 # modulus 2 #) ~ # string concat 'isChecked()' } ``` [Answer] # Sed, 36 Bytes Same idea as all the other direct substitution answers. ``` : s/Unc/NotC/ s/isNot/!is/ s/!!// t ``` [Answer] # sed, ~~37~~ 38 bytes ``` :;s/is(Not|Un)/!is/;s/!!//;t;s/ch/Ch/ ``` 37 + 1 for `-r` switch: ``` sed -r ':;s/is(Not|Un)/!is/;s/!!//;t;s/ch/Ch/' ``` [Answer] ## Mathematica, ~~82~~ ~~61~~ 60 Bytes Small tweak, added one more infix operator: ``` "!"~Table~Mod[#~StringCount~{"o","n","!"},2]<>"isChecked()"& ``` Previously: ``` "!"~Table~Mod[StringCount[#,{"o","n","!"}],2]<>"isChecked()"& ``` Count up all the o's, n's and !'s then mod 2 and put that many ! in front. Old version: ``` "!"~Table~Mod[StringCount[StringReplace[#,{{"o","n"}->"!"}],"!"],2]<>"isChecked()"& ``` [Answer] # Excel, 90 bytes ``` =IF(ISODD(SEARCH("C",SUBSTITUTE(SUBSTITUTE(A1,"Un","!"),"Not","!"))),"","!")&"isChecked()" ``` [Answer] # Windows Batch, 120 bytes Previously 268 257 253 245 239 221 182 176 169 123 bytes ``` @set a=%1 @set s=#%a:~,-2% @set s=%s:!=N#% @for %%a in (%s:N= %)do @set/ac+=5 @if %c:~-1%==0 cd|set/p=! @echo isC%a:~-8% ``` The programs replaces all the `!` into `N#`. Because now all negation signs, !(Now it is `N#`), `Not`, and `Un` contains `N`, the program can counts the number of appearance of `N` and determines if an leading `!` is required. Each time the program counts an `N`, the counter is added by 5. The reason for adding 5 is because each alternating values when adding 5 ends in either 0 or 5. This can be used to determine whether the value is odd or even and the leading `!` us added if required. In addition, xnor's last-eight-character trick is utilized. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~29~~ ~~28~~ ~~25~~ 21 bytes ``` f“NU!”LḂ”!x;“µịÆẹṠƊẹ» ``` [Try it online!](https://tio.run/nexus/jelly#@5/2qGGOX6jio4a5Pg93NAEpxQproNChrQ93dx9ue7hr58OdC451AelDu/8f3XO4/VHTmiwgBipRsLVTAKqP/P8/Wj2z2DkjNTk7NUVDU10HyAvNS0bh@@WXICtQxBRRhIgBEbLeWAA "Jelly – TIO Nexus") ``` f“NU!”LḂ”!x;“µịÆẹṠƊẹ» Main link, argument is z f“NU!” Filter to only keep "NU!" LḂ”!x Repeat exclamation mark by the parity of the length ;“µịÆẹṠƊẹ» Concatenate to "isChecked()" ``` -4 bytes thanks to Jonathan Allan! -4 bytes thanks to Jonathan Allan! (by using compressed strings) [Answer] # PHP, 55 Bytes ``` <?=preg_match_all("#!|N#i",$argn)&1?"!":""?>isChecked() ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVJUzCz2yy8BotA854zU5OzUFA1NJWsue7v/Nva2BUWp6fG5iSXJGfGJOTkaSsqKNX7KmUo6YM2aaob2SopKVkpK9naZxXDN//8DAA "PHP – TIO Nexus") # PHP, 58 Bytes ``` <?=preg_match_all("#[!NU]#",$argn)%2?"!":"","isChecked()"; ``` instead `"#[!NU]#"` you can use `"#[!N]#i"` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVJUzCz2yy8BotA854zU5OzUFA1NJWsue7v/Nva2BUWp6fG5iSXJGfGJOTkaSsrRin6hscpKOmDdmqpG9kqKSlZKSjpKmcVIuv//BwA "PHP – TIO Nexus") # PHP, 68 Bytes Version without Regex ``` for(;$c=$argn[$i++];)$d^=!trim($c,"UN!");echo"!"[!$d],"isChecked()"; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVVJUzCz2yy8BotA854zU5OzUFA1NJev/aflFGtYqybZgZdEqmdrasdaaKilxtoolRZm5GirJOkqhfopKmtapyRn5SopK0YoqKbE6SpnFyIb8BwA "PHP – TIO Nexus") [Answer] # [Japt](https://github.com/ETHproductions/japt), 19 bytes ``` `‰C”×B()`i'!pU¬xc u ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=YIlDlNdCKClgaSchcFWseGMgdQ==&input=LW1SIFsKImlzQ2hlY2tlZCgpIiwKImlzVW5jaGVja2VkKCkiLAoiaXNOb3RDaGVja2VkKCkiLAoiIWlzTm90Q2hlY2tlZCgpIiwKIiEhIWlzTm90Tm90VW5jaGVja2VkKCkiCl0=) ### Unpacked & How it works ``` `‰C”×B()`i'!pUq xc u `‰C”×B()` Compressed string for "isChecked()" i Insert the following string at the beginning... '!p "!" repeated the following number of times... Uq Split the input into chars xc Sum the charcodes u Modulo 2 ``` Using the charcode-sum trick from [Jonathan Allan's Python solution](https://codegolf.stackexchange.com/a/120046/78410). [Answer] # [Pascal (FPC)](https://www.freepascal.org/), 119 bytes ``` var s:string;j:word;c:char;begin read(s);for c in s do j:=j+ord(c);if 1=j mod 2then write('!');write('isChecked()')end. ``` [Try it online!](https://tio.run/##NYoxDgIhEEWvMlRAjCZaQrayt/MAOMwuoMJmhrjHxy00@cXLe38NguF1nFcc4xMYxEnnXBdf3NY4enSYAvsHLbkCU4hGrJ8bA8IuBGKD4qZy2L8Grc8znKcC7xbh0hNV2Dh3Mlpp63@Y5ZoInxSN1ZZqPI2hlMpya33fveK/fgE "Pascal (FPC) – Try It Online") Using method that almost every answer does, summing codepoints of characters in the input, then checking parity of the sum. [Answer] # [ReRegex](https://github.com/TehFlaminTaco/ReRegex), 32 bytes ``` /!!//Not/!/Unc/!C/is!/!is/#input ``` ## Explained Works like the Retina answer ``` /!!// #Remove all !! pairs Not/!/ #Replace all Nots with !s Unc/!C/ #Replace any Unc's with !C (Turning Unchecked into !Checked) is!/!is/ #Float all !'s past the is to the left #input #Take the stdin as input ``` [Try it online!](https://tio.run/##K0otSk1Prfj/X19RUV/fL79EX1E/NC9ZX9FZP7NYUV8xs1hfOTOvoLTk/39FIAeoAIiACjJSk7NTUzQ0/wMA "ReRegex – Try It Online") ]
[Question] [ Randall Munroe's book "xkcd, volume 0" uses a rather odd number system for the page numbers. The first few page numbers are ``` 1, 2, 10, 11, 12, 20, 100, 101, 102, 110, 111, 112, 120, 200, 1000, 1001, ... ``` This looks a bit like ternary, but notice that he skips from `20` straight to `100`, from `120` to `200` and from `200` to `1000`. One way to define this sequence is to say that it enumerates all ternary numbers that contain at most one `2` and no `1` after that `2`. You can find this on OEIS in entry [A169683](https://oeis.org/A169683). This number system is known as [skew binary](http://en.wikipedia.org/wiki/Skew_binary_number_system). Your task is to find the representation of a given positive integer `N` in this number system. You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. Output may be a string, a number with a decimal representation equal to the skew binary representation, or a list of digits (as integers or characters/strings). You must not return leading zeroes. This is code golf, so the shortest answer (in bytes) wins. **Fun fact:** There is actually some merit to this number system. When incrementing a number, you will always change at most two adjacent digits - you'll never have to carry the change through the entire number. With the right representation that allows incrementing in O(1). ## Test Cases ``` 1 => 1 2 => 2 3 => 10 6 => 20 7 => 100 50 => 11011 100 => 110020 200 => 1100110 1000 => 111110120 10000 => 1001110001012 100000 => 1100001101010020 1000000 => 1111010000100100100 1048576 => 10000000000000000001 1000000000000000000 => 11011110000010110110101100111010011101100100000000000001102 ``` I will give a bounty to the shortest answer which can solve the last test case (and any other input of similar magnitude, so don't think about hardcoding it) in less than a second. ## Leaderboards Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` <script>site = 'meta.codegolf'; postID = 5314; isAnswer = true; QUESTION_ID = 51517</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # CJam, ~~24~~ ~~23~~ ~~22~~ ~~21~~ 19 bytes ``` ri_)2b,,W%{2\#(md}/ ``` This is an **O(log n)** approach, where **n** is the input, that completes the last test case instantly. It converts **n** directly to skew binary, using modular division by the values of the digit **1**. This code finishes with an error that goes to STDERR with the Java interpreter, which is allowed according to the [consensus on Meta](https://codegolf.meta.stackexchange.com/a/4781). If you try this code in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_)2b%2C%2CW%25%7B2%5C%23(md%7D%2F&input=1000000000000000000), just ignore everything but the last line of output. The error can be eliminated, at the cost of 2 bytes, by prepending `2>` to `W%`. *Thanks to @MartinBüttner for golfing off one byte.* ### Background The skew binary representation **ak...a0** corresponds to the integer **n = (2k+1-1)ak+...+(21-1)a0**. Since both **(2k-1) + ... + (21-1) = 2k+1 - (k + 2)** and **(2k-1) + ... + 2(2j-1) = 2k+1 - (2j+1 - 2j + k + 1)** are less than **2k+1-1**, the values of **ak** to **a0** can be recovered by successive modular division by **2k+1-1**, **2k-1**, etc. To begin, we have to find the value of **2k+1-1** first. Since **n** is at most **2(2k+1-1)**, the integer **n + 1** must be strictly smaller than **2k+2**. Thus, taking the integer part of the binary logarithm of **n + 1** yields **k + 1**. Finally, we observe that the integer **n + 1** has **⌊log2(n + 1)⌋** digits in base 2. ### How it works ``` ri e# Read an integer N from STDIN. 2b, e# Push the number of binary digits of N + 1, i.e, K + 2 = log(N + 1) + 1. ,W% e# Push the range [K+1 ... 0]. { e# For each J in the range: 2\# e# J -> 2**J ( e# -> 2**J - 1 md e# Perform modular division of the integer on the stack (initially N) e# by 2**J - 1: N, 2**J - 1 -> N/(2**J - 1), N%(2**J - 1) }/ e# ``` In the last two iterations, we perform modular division by **1** and **0**. The first pushes an unwanted **0** on the stack. The last attempts to execute `0 0 md`, which pops both unwanted **0**s from the stack, exits immediately instead of pushing anything and dumps the stack to STDOUT. [Answer] # Python 2, 67 bytes ``` def f(n):x=len(bin(n+1))-3;y=2**x-1;return n and n/y*10**~-x+f(n%y) ``` Seems to work for the given test cases. If I've got this right, this should be about `O(place values set in output)`, so it does the last case with ease. Call like `f(100)`. Returns a decimal representation equal to the skew binary. # Python 3, 65 bytes ``` def g(n,x=1):*a,b=n>x*2and g(n,x-~x)or[n];return a+[b//x,b%x][:x] ``` Slightly less efficient but still logarithmic, so the last case is near-instant. Call like `g(100)`. Returns a list of digits. [Answer] # Pyth, 17 bytes ``` Ljb3ye.f!-P-yZ01Q ``` This is somewhat ridiculously slow - `O(output^log_2(3))`. It's exponential in the length of the input, but not doubly exponential, like some of the answers on the page. Some ideas taken from @Dennis's answer, [here](https://codegolf.stackexchange.com/a/51529/20080). [Demonstration.](https://pyth.herokuapp.com/?code=Ljb3ye.f!-P-yZ01Q&input=100&debug=0) It makes use of `.f`, Pyth's "loop until n matches have been found" function. [Answer] # CJam, ~~22~~ ~~21~~ 20 bytes ``` ri_me,3fb{0-W<1-!},= ``` This is an **O(enn)** approach, where **n** is the input. It lists the first **⌊en⌋** non-negative integers in base 3, eliminates those that have **2**s or **1**s after the first **2** (if any) and selects the **n+1**th. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=ri_2%23)%2C3fb%7B0-W%3C1-!%7D%2C%3D&input=10). ### How it works ``` ri e# Read an integer N from STDIN. _me, e# Push [0 ... floor(exp(N))-1]. 3fb e# Replace each integer in the range by the array of its digits in base 3. { e# Filter; for each array A: 0- e# Remove all 0's. W< e# Remove the last element. 1- e# Remove all 1's. ! e# Logical NOT. Pushes 1 iff the array is empty. }, e# If ! pushed 1, keep the array. = e# Select the (N+1)th element of the filtered array. ``` [Answer] # Pyth, 20 bytes ``` Jt^2hslhQ#p/=%QJ=/J2 ``` Runs in O(log(input())), well under a second for the final test case. Based around a run until error loop. No trailing newline. [Demonstration.](https://pyth.herokuapp.com/?code=Jt%5E2hslhQ%23p%2F%3D%25QJ%3D%2FJ2&input=1000000000000000000&debug=0) Explanation: ``` Jt^2hslhQ#p/=%QJ=/J2 Implicit: Q is the input. lhQ log(Q+1,2) slhQ floor(log(Q+1,2)) hslhQ floor(log(Q+1,2))+1 ^2hslhQ 2^(floor(log(Q+1,2))+1) t^2hslhQ 2^(floor(log(Q+1,2))+1)-1 Jt^2hslhQ J=2^(floor(log(Q+1,2))+1)-1 # until an error is thrown: =%QJ Q=Q%J =/J2 J=J/2 / The value Q/J, with the new values of Q and J. p print that charcter, with no trailing newline. ``` J is initialized to the value of the smallest skew binary digit position that is larger than the input. Then, each time through the loop, we do the following: * Remove each digit of value `J` from `Q` with `=%QJ`. For instance, if `Q=10` and `J=7`, `Q` becomes `3`, which corresponds to the skew binary changing from `110` to `10`. This has no effect in the first iteration. * Change `J` to the next smaller skew binary base value with `=/J2`. This is floored division by 2, changing `J=7` to `J=3`, for instance. Because this happens before the first digit is output, `J` is intialized one digit position higher than needed. * Find the actual digit value with `/QJ` (effectively). * Print that value with `p`, instead of Pyth`s default printing, to avoid the trailing newline. This loop will repeat until `J` becomes zero, at which point a divide by zero error will be thrown, and the loop will end. [Answer] # ES6, 105 bytes ``` f=n=>{for(o=0;n--;c?o+=Math.pow(3,s.length-c):o++)s=t(o),c=s.search(2)+1;return t(o);},t=a=>a.toString(3) ``` Usage is: `f(1048576)` => `"10000000000000000001" Test the last argument at your own peril. I gave up after 5 seconds. And pretty print with comments! ``` f=n=>{ //define function f with input of n (iteration) for(o=0; //define o (output value in decimal) n--; //decrement n (goes towards falsy 0) each loop until 0 c?o+=Math.pow(3,s.length-c):o++) //if search finds a 2, increment output by 3^place (basically moves the 2 to the left and sets the place to 0), else ++ s=t(o), //convert output to base 3 c=s.search(2)+1; //find the location of 2, +1, so a not-found becomes falsy 0. return t(o); //return the output in base 3 }, t=a=>a.toString(3); //convert input a to base 3 ``` [Answer] # Retina, 55 bytes ``` ^ 0a (+`12(.*a)1 20$1 0?2(.*a)1 10$1 0a1 1a )`1a1 2a a <empty line> ``` Takes input in unary. Each line should go to its own file but you can run the code as one file with the `-s` flag. E.g.: ``` > echo 11111|retina -s skew 12 ``` Method: Executes incrementation on a string input number times starting from the string `0`. We use the following incrementation rules: * if contains `2`: `^2 -> ^12`; `02 -> 12`; `12 -> 20` * if doesn't contain `2`: `0$ -> 1$`; `1$ -> 2$` (There can be at most one `2` in the string; `^` and `$` marks the start and end of the string in the rules.) [More information about Retina.](https://github.com/mbuettner/retina) [Answer] # Java, ~~154~~ 148 ``` n->{String s="0";for(;n-->0;)s=s.contains("2")?s.replaceAll("(^|0)2","10").replace("12","20"):s.replaceAll("1$","2").replaceAll("0$","1");return s;} ``` This answer take the form of a single anonymous function that takes an integer argument and returns the answer as a String. Below is a complete class for testing this solution. ``` import java.util.function.Function; public class Skew { public static void main(String[] args){ Function<Integer,String> skew = n->{String s="0";for(;n-->0;)s=s.contains("2")?s.replaceAll("(^|0)2","10").replace("12","20"):s.replaceAll("1$","2").replaceAll("0$","1");return s;}; for(String s:args){ System.out.println(skew.apply(Integer.parseInt(s))); } } } ``` [Answer] # Bash + coreutils, 52 ``` dc -e3o0[r1+prdx]dx|grep -v 2.\*[12]|sed -n $1{p\;q} ``` This is a brute-forcer, so its rather slow for larger numbers. ### Output: ``` $ ./xkcdnum.sh 1000 111110120 $ ``` [Answer] # Java, ~~337~~ ~~335~~ ~~253~~ ~~246~~ 244 bytes A method that takes in the index as a `long` and returns the result as a string Uses a `long` for the index so can *theoretically* handle the last test case, but I *really* wouldn't suggest it. ``` String f(long i){List<Long>l=new ArrayList<>();l.add(0L);for(;i-->0;){int j=l.indexOf(2);if(j!=-1){l.set(j,0L);if(j==0){l.add(0,1L);}else{l.set(j-1,l.get(j-1)+1);}}else{j=l.size()-1;l.set(j,l.get(j)+1);}}String s="";for(long q:l)s+=q;return s;} ``` [Answer] # Haskell, ~~73~~ 72 Thanks to @nimi for 1 byte! This solution won't be winning any bounty, the last couple tests take an inordinate amount of time to run, but, I think I've golfed it fairly well. ``` i(2:b)=1:0:b i[b]=[b+1] i(b:2:c)=b+1:0:c i(b:c)=b:i c s=(iterate i[0]!!) ``` This solution is a rather naïve approach that calculates the skew binary number `n` by incrementing 0 `n` times. [Answer] # CJam, 24 bytes ``` Q{0\+2a/())+a\+0a*}ri*si ``` This is an **O(n log n)** approach, where **n** is the input. It starts with the skew binary representation of **0** and increments the corresponding integer **n** times. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=Q%7B0%5C%2B2a%2F())%2Ba%5C%2B0a*%7Dri*si&input=1000). ### Background Incrementing a number in skew binary can be done by following two easy steps: 1. Replace an eventual **2** by a **0**. 2. If a **2** has been replaced, increment the digit to its left. Otherwise, increment the last digit. ### How it works ``` Q e# Push an empty array. { e# Define an anonymous function: 0\+ e# Prepend a 0 to the array. 2a/ e# Split the array at 2's. ( e# Shift out the first chunk of this array. ) e# Pop the last digit. )+ e# Increment it and append it to the array. a\+ e# Prepend the chunk to the array of chunks. 0a* e# Join the chunks, using [0] as separator. e# If there was a 2, it will get replaced with a 0. Otherewise, there's e# only one chunk and joining the array dumps the chunk on the stack. } e# ri* e# Call the function int(input()) times. si e# Cast to string, then to integer. This eliminates leading 0's. ``` [Answer] # VBA, ~~209~~ ~~147~~ 142 bytes ``` Sub p(k) For i=1To k a=StrReverse(q) If Left(Replace(a,"0",""),1)=2Then:q=q-2*10^(InStr(a,2)-1)+10^InStr(a,2):Else:q=q+1 Next msgbox q End Sub ``` My math is inefficient and my golfing could use work. But it's my first attempt at PoG and thought I'd give this one a try. Sort of a Brute Force way though. It's just counting by 1 unless the last digit is a 2 then steps back by 2 and jumps forward 10. Plus the trailing 0's. This stops working at 65534 because VBA insists on giving output in scientific notation, but the logic should work fine for even higher numbers Looking forward to golfing suggestions, VBA is not very golf-friendly but it's not often represented, and I think it can beat Java for length. Edit1: Thanks **Manu** for helping shave off 62 bytes Edit2: Swapped `debug.print` for `msgbox` as output. Saved 5 bytes [Answer] # Javascript ES6, ~~99~~ ~~86~~ ~~78~~ ~~76~~ 72 chars ``` f=n=>{for(s="1";--n;s=s.replace(/.?2|.$/,m=>[1,2,10][+m]||20));return s} // Old version, 76 chars: f=n=>{for(s="1";--n;s=s.replace(/02|12|2|.$/,m=>[1,2,10][+m]||20));return s} // Old version, 86 chars: f=n=>{for(s="1";--n;s=s.replace(/(02|12|2|.$)/,m=>[1,2,10,,,,,,,,,,20][+m]));return s} // Old version, 99 chars: f=n=>{for(s="1";--n;s=s.replace(/(^2|02|12|20|.$)/,m=>({0:1,1:2,2:10,12:20,20:100}[+m])));return s} ``` Test: ``` ;[1,2,3,6,7,50,100,200,1000,10000,100000,1000000,1048576].map(f) == "1,2,10,20,100,11011,110020,1100110,111110120,1001110001012,1100001101010020,1111010000100100100,10000000000000000001" ``` > > **Fun fact:** There is actually some merit to this number system. When incrementing a number, you will always change at most two adjacent digits - you'll never have to carry the change through the entire number. With the right representation that allows incrementing in O(1). > > > Thank you for the fact - it is the base of my solution :) [Answer] # Octave, ~~107~~ 101 bytes Should be **O(log n)** if I'm figuring this right... ``` function r=s(n)r="";for(a=2.^(uint64(fix(log2(n+1))):-1:1)-1)x=idivide(n,a);r=[r x+48];n-=x*a;end;end ``` Pretty-print: ``` function r=s(n) r=""; for(a=2.^(uint64(fix(log2(n+1))):-1:1)-1) x=idivide(n,a); r=[r x+48]; n-=x*a; end end ``` I was somewhat stymied addressing the final challenge, since Octave by default treats everything as floating point numbers and I didn't have the necessary precision to calculate the last one. I got around that by spending precious bytes to force everything to be an unsigned integer. The result of the last one was too big to treat as a number, so the result is a string. Output (I'm including `1e18 - 1` to show I can do that accurately, and the last set of outputs shows how long it takes to calculate that value): ``` octave:83> s(uint64(1e18)) ans = 11011110000010110110101100111010011101100100000000000001102 octave:84> s(uint64(1e18)-1) ans = 11011110000010110110101100111010011101100100000000000001101 octave:85> tic();s(uint64(1e18)-1);toc() Elapsed time is 0.0270021 seconds. ``` [Answer] ## T-SQL, ~~221~~ ~~189~~ 177 bytes EDIT: The original versions of this code would produce incorrect output for some numbers, this has been corrected. With every query here, just add the number to calculate before the first comma. Everyone know that T-SQL is the best golfing language. Here is a version that will calculate even the last test case. On the machine I tested it on, it ran in under a second, I'd be interested to see how it runs for everyone else. ``` DECLARE @ BIGINT=,@T VARCHAR(MAX)='';WITH M AS(SELECT CAST(2AS BIGINT)I UNION ALL SELECT I*2FROM M WHERE I<@)SELECT @T += STR(@/(I-1),1),@%=(I-1)FROM M ORDER BY I DESC SELECT @T ``` And here it is again, but readable: ``` DECLARE @ BIGINT=, @T VARCHAR(MAX)=''; WITH M AS ( SELECT CAST(2 AS BIGINT) I UNION ALL SELECT I * 2 FROM M WHERE I < @ ) SELECT @T+=STR(@/(I-1),1), @%=(I-1) FROM M ORDER BY I DESC SELECT @T ``` --- If I only use ints, this can be a bit shorter, coming out at 157 bytes: ``` DECLARE @ INT=,@T VARCHAR(MAX)='';WITH M AS(SELECT 2I UNION ALL SELECT I*2FROM M WHERE I<@)SELECT @T+=STR(@/(I-1),1),@%=(I-1)FROM M ORDER BY I DESC SELECT @T ``` And once more again, more readable: ``` DECLARE @ INT=, @T VARCHAR(MAX)=''; WITH M AS ( SELECT 2I UNION ALL SELECT I * 2 FROM M WHERE I < @ ) SELECT @T+=STR(@/(I-1),1), @%=(I-1) FROM M ORDER BY I DESC SELECT @T ``` [Answer] # Turing Machine Code, ~~333~~ 293 bytes I'm using an encoding as used [here](http://morphett.info/turing/turing.html). This machine uses 9 states and 11 colors. If binary input is permissible, this can be reduced to a mere 4 colors, saving a few tens of bytes in the process. ``` 0 _ _ l 1 0 * * r 0 1 9 8 l 2 1 8 7 l 2 1 7 6 l 2 1 6 5 l 2 1 5 4 l 2 1 4 3 l 2 1 3 2 l 2 1 2 1 l 2 1 1 0 l 2 1 0 9 l 1 1 _ _ r 8 2 _ _ l 3 2 * * l 2 3 _ 1 r 4 3 * * l 5 4 _ _ r 0 4 * * r 4 5 * * l 5 5 _ _ r 6 6 _ _ l 7 6 2 0 l 7 6 * * r 6 7 _ 1 r 4 7 0 1 r 4 7 1 2 r 4 8 _ _ * halt 8 * _ r 8 ``` If the above link isn't working (sometimes it works for me, other times the page refuses to load) you may also test this using [this java implementation.](http://pastebin.com/fQz6DBRU) [Answer] # Perl, 66 bytes Number is to be input through STDIN. ``` $_=1;$c=<>;s/(.*)(.?)2(.*)/$1.$2+1 .$3.0/e||$_++while(--$c);print; ``` [Answer] # Pyth, 19 bytes ``` m/=%Qtydtd^L2_SslhQ ``` Logarithmic complexity. Easily finishes in the necessary amount of time. Output in the form of a list of digits. [Demonstration](https://pyth.herokuapp.com/?code=m%2F%3D%25Qtydtd%5EL2_SslhQ&input=1000000000000000000&debug=0). [Answer] # Perl, ~~84~~ ~~70~~ 67 bytes ``` $n=<>;$d*=2while($d++<$n);$_.=int($n/$d)while($n%=$d--,$d/=2);print ``` ~~Not very golfy,~~ Getting better but it does work very quickly! Dennis's suggestion gets it down to 51 (50 bytes + -p switch) ``` $d*=2while$d++<$_;$\.=$_/$d|0while$_%=$d--,$d/=2}{ ``` It *must* be called like `perl -p skew_binary.pl num_list.txt` where `num_list.txt` contains a single line with the number to encode on it. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 40 bytes ``` v=>(g=n=>n>v?'':g(n-~n)+(v-(v%=n))/n)(1) ``` [Try it online!](https://tio.run/##XY/LTsMwEEX3/opskGdUYuxAW0TlsOIrAKmR6wQj14liE3XFrwc7D4rw@9w7dyR/VkPlVW@6kLv2pMdajoMsoZFOlq4cnil9asDl3w43MOQw3EiHeOcQBI4HErQPqvLaZzI7EpHJMhOkSFdB7ifiZDchJ/uZOdny6SW4ECTyAjyWFFeKO5kLi1RdzApf@iQtnlGf5d/oFE6Tr4lrGz7764r2w@N2v1ta/h@CHP/8kfnOmgD0zVFktbFB93BJyQszTtmvk/ZAZUkR2bnqwCbLrqFZr9v@pVIfAK/mNtPvmEpU63xrNbNtAzVsDEaHhd6cAREP4w8 "JavaScript (Node.js) – Try It Online") This solution does not work on last testcase. It just cause stack overflow on it. [Answer] ## Mathematica, 65 Should be quite fast enough, although I have to admit I peeked at the other submissions before making this. ``` f = (n = #; l = 0; While[n > 0, m = Floor[Log2[1 + n]]; l += 10^(m - 1); n -= 2^m - 1 ]; l)& ``` Usage: ``` f[1000000000000000000] ``` Output: ``` 11011110000010110110101100111010011101100100000000000001102 ``` Starts giving MaxExtraPrecision error messages somewhere past 10^228 (for which it calculates the result in .03 seconds on my machine) After removing the MaxExtraPrecision limit, it will handle numbers up to around 10^8000 in a second. Input: ``` Timing[Block[{$MaxExtraPrecision = Infinity}, f[10^8000]];] ``` Output: ``` {1.060807, Null} ``` [Answer] # C, 95 bytes ``` void f(unsigned long i,int*b){for(unsigned long a=~0,m=0;a;a/=2,b+=!!m)m|=*b=i/a,i-=a**b;*b=3;} ``` This accepts an integer and a buffer in which to return the digits. The results are stored in `b`, terminated with value `3` (which can't occur in the output). We don't have to handle input of `0` (as the question specified only positive integers), so there's no special-casing to avoid empty output. ### Expanded code ``` void f(unsigned long i,int*b) { for (unsigned long a=~0, m=0; a; a/=2, b+=(m!=0)) { *b = i/a; /* rounds down */ i -= *b * a; m = m | *b; /* m != 0 after leading zeros */ } *b=3; /* add terminator */ } ``` We operate by successive subtraction, starting with the most significant digit. The only complication is that we use the variable `m` to avoid printing leading zeros. A natural extension to `unsigned long long` may be made if desired, at the cost of 10 bytes. ### Test program Pass numbers to be converted as command arguments. It converts the `int` array buffer to a printable digit string. Runtime is less than one millisecond for input `1000000000000000000`. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char**argv) { while (*++argv) { unsigned long i = strtoul(*argv, NULL, 10); int result[1024]; f(i,result); /* convert to string */ char s[1024]; {char*d=s;int*p=result;while(*p!=3)*d++=*p+++'0';*d=0;} printf("%lu = %s\n", i, s); } return EXIT_SUCCESS; } ``` ### Test results ``` $ ./51517 $(seq 20) 1 = 1 2 = 2 3 = 10 4 = 11 5 = 12 6 = 20 7 = 100 8 = 101 9 = 102 10 = 110 11 = 111 12 = 112 13 = 120 14 = 200 15 = 1000 16 = 1001 17 = 1002 18 = 1010 19 = 1011 20 = 1012 ``` [Answer] ## CoffeeScript, ~~92~~ 69 bytes Based of [Qwertiy's answer](https://codegolf.stackexchange.com/a/51599/22867) and updates: ``` f=(n)->s='1';(s=s.replace /(.?2|.$)/,(m)->[1,2,10][+m]||20)while--n;s # older version, 92 bytes f=(n)->s='1';(s=s.replace /(^2|02|12|20|.$)/,(m)->{0:1,1:2,2:10,12:20,20:100}[+m])while--n;s ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 31 bytes ``` _r/?2|.$/g_÷C ç20 ª°Zs3}}gU['0] ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=X3IvPzJ8LiQvZ1/3QyDnMjAgqrBaczN9fWdVWycwXQ==&input=LW1SIFsxLDIsMyw2LDcsNTAsMTAwLDIwMCwxMDAwLDEwMDAwXQ==) Almost direct port of [this JS solution](https://codegolf.stackexchange.com/a/51599/78410). No idea if there's better way. ### Unpacked & How it works ``` X{Xr/?2|.$/gZ{Z÷C ç20 ||++Zs3}}gU['0] X{ Declare a function... Xr Accept a string, replace the regex... /?2|.$/g /.?2|.$/ (g is needed to match *only once*, opposite of JS) Z{ ...with the function... (matched string will be 0,1,2,02 or 12) Z÷C Implicitly cast the matched string into number, divide by 12 ç20 Repeat "20" that many times (discard fractions) || If the above results in "", use the next one instead ++Z Increment the value s3 Convert to base-3 string (so 0,1,2 becomes 1,2,10) }} gU['0] Repeatedly apply the function on "0", U (input) times ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` üxëàè£öΦGΩ│Je5█ò ``` [Run and debug it](https://staxlang.xyz/#p=817889858a9c94e847eab34a6535db95&i=1%0A2%0A3%0A6%0A7%0A50%0A100%0A200%0A1000%0A10000%0A100000%0A1000000%0A1048576%0A1000000000000000000&a=1&m=2) I'm not sure exactly what the formal complexity class is, but it's fast enough to do all the test cases in a tenth of a second on this machine. Unpacked, ungolfed, and commented, it looks like this. In this program, the x register originally contains the input. ``` z push [] { start block for while loop |X:2N -log2(++x) {^}& increment array at index (pad with 0s if necessary) xc:G-X unset high bit of x; write back to x register w while; loop until x is falsy (0) $ convert to string ``` [Run this one](https://staxlang.xyz/#c=z%09push+[]%0A%7B%09start+block+for+while+loop%0A+%7CX%3A2N%09-log2%28%2B%2Bx%29%0A+%7B%5E%7D%26%09increment+array+at+index+%28pad+with+0s+if+necessary%29%0A+xc%3AG-X%09unset+high+bit+of+x%3B+write+back+to+x+register%0Aw%09while%3B+loop+until+x+is+falsy+%280%29%0A%24%09convert+to+string&i=1%0A2%0A3%0A6%0A7%0A50%0A100%0A200%0A1000%0A10000%0A100000%0A1000000%0A1048576%0A1000000000000000000&a=1&m=2) [Answer] # [Husk](https://github.com/barbuz/Husk), 16 bytes ``` !mdfö¬f≠1hfImB3N ``` [Try it online!](https://tio.run/##yygtzv7/XzE3Je3wtkNr0h51LjDMSPPMdTL2@///v6GBAQA "Husk – Try It Online") or [Verify first 100 values](https://tio.run/##ATYAyf9odXNr/23CpytzKCsiIOKGkiAic@KCgSnhuKP/IW1kZsO2wqxm4omgMWhmSW1CM07///8xMDA "Husk – Try It Online") Same method as Dennis' CJam answer. ]
[Question] [ [Richard Dawkins](http://en.wikipedia.org/wiki/Richard_Dawkins) in his book The [Blind Watchmaker](http://en.wikipedia.org/wiki/The_Blind_Watchmaker), describes a [Weasel program](http://en.wikipedia.org/wiki/Weasel_program). The algorithm can be described as follows: > > 1. Start with a random string of 28 characters. Valid characters are all upppercase letters, and space. > 2. Make 100 copies of that string, with a 5% chance per character of that character being replaced with a random character. > 3. Compare each new string with the target "METHINKS IT IS LIKE A WEASEL", and give each a score according to the number of letters in the string which are correct and in the correct position. > 4. If any of the new strings has a perfect score (28), halt. > 5. Choose the highest-scoring string from step 3. How you work out a tie is up to you, but only one string may be chosen. Take the chosen string and go to step 2. > > > The winner will be the shortest code snippet to get to the correct answer while printing the highest-scoring string of each generation in the following format: ![answers in this format please](https://i.stack.imgur.com/JhRcM.png) If people could help by checking other peoples answers would be very helpful! [Answer] ## APL (143) ``` 0{⍵≢T←'METHINKS IT IS LIKE A WEASEL':c∇⍨1+⍺⊣⎕←(⍕⍺),':'c'-- score:',s⊣c←⊃c/⍨G=s←⌈/G←{+/⍵=T}¨c←{⍵{⍵:⍺⋄C[?27]}¨9≠?28/20}¨100⍴⊂⍵}⊃∘(C←27↑⎕A)¨?28/27 ``` Explanation: * `0{`...`}⊃∘(C←27↑⎕A)¨?28/27`: set `C` to the first 27 capital letters. There are only 26, so the 27th element will be a space. Select 28 random items from `C`. This will be the first `⍵`. The first `⍺` (generation) will be `0`. * `⍵≢T←'METHINKS IT IS LIKE A WEASEL`: set `T` to the string `'METHINKS IT IS LIKE A WEASEL'`. As long as `⍵` is not equal to `T`: + `{`...`}¨100⍴⊂⍵`: Make 100 copies of `⍵`. For each of these... - `9≠?28/20`: select 28 random numbers from 1 to 20. Make a bitmask where each `1` means that the random number was not equal to `9`. (This means 5% chance of a `0`). - `⍵{⍵:⍺⋄C[?27]}¨`: for each letter in `⍵`, if the corresponding bit was `1`, keep that letter, otherwise replace it with a randomly chosen element from `C`. + `c←`: store the 100 mutated strings in `c`. + `G←{+/⍵=T}¨c`: for each element in `c`, calculate the score (amount of characters that match `T`) and store the scores in `G`. + `s←⌈/G`: find the maximum score and store that in `s`. + `c←⊃c/⍨G=s`: select the first item from `c` whose score is equal to `s` (the maximum), and store it in `c` again. + `⎕←(⍕⍺),':'c'-- score:',s`: print the generation in the given format (`⍺` is current generation, `c` is current best string, `s` is score) + `c∇⍨1+⍺`: Increment the generation and run the mutation again using the current best string (`c`) as input. [Answer] # Mathematica - ~~238~~ ~~236~~ 225 ``` c:="@"~CharacterRange~"Z"~RandomChoice~28/."@"->" " For[s=""<>c;i=0,{d,s}=Sort[{#~HammingDistance~"METHINKS IT IS LIKE A WEASEL",#}&@ StringReplace[s,_/;20Random[]<1:>c〚1〛]&~Array~100]〚1〛; d>0Print[i++,":"s," -- score: ",28-d],] ``` Example output ``` 0: CYPMEIHADXRXVTFHERYOZNRVFCSQ -- score: 0 1: CYPMEIHADIRXVTFBERYOZNRVFCSQ -- score: 1 2: CYPMEIHA IRXVTFBIRYOZNRVFCSQ -- score: 3 ... 50: METHINKS IT IS LIKE A WEASEL -- score: 28 ``` [Answer] # Python (273) ``` from random import choice as c n=range a=map(chr,n(65,91)+[32]) s=map(c,[a]*28) p=x=0 while p<28: p,s=max((sum(g==r for g,r in zip(y,'METHINKS IT IS LIKE A WEASEL')),y)for y in ([c(a+[x]*513)for x in s]for _ in n(100)));print '%d: %s -- score: %d' % (x,''.join(s),p);x+=1 ``` [Answer] # K, 173 167 ``` o:"METHINKS IT IS LIKE A WEASEL" i:0;{~x~o}{-1($i),": ",(r:a@*&b=c)," -- score: ",$c:max@b:+/'o=/:a:{x{if[0~*1?20;x[y]:*1?s];x}/!#x}'100#,x;i+:1;r}/28?s:"c"$32,65+!26; ``` / ``` 0: FQRZPHACDIBHZOUUCYKKFBJWVNVI -- score: 1 1: FQRZP ACDITHCOUUCYKKFBJWVNVI -- score: 2 2: FQRZP AFDIT COUUCYKKFBJWVNVI -- score: 3 ... 51: METHINKS IT IS LIKECA WEASEL -- score: 27 52: METHINKS IT IS LIKECA WEASEL -- score: 27 53: METHINKS IT IS LIKE A WEASEL -- score: 28 ``` [Answer] ## R (~~245~~ ~~239~~ 238 characters) ``` t=strsplit("METHINKS IT IS LIKE A WEASEL","")[[1]] h=sample s=h(f<-c(LETTERS," "),28,T) c=0 while(!all(s==t)){for(i in 1:100){z=ifelse(runif(28)<.05,h(f,1),s) y=sum(s==t) if(sum(z==t)>y)s=z} cat(c<-c+1,": ",s," -- score: ",y,"\n",sep="")} ``` Gives: ``` 1: HSSSIMJM ETJISGBSCIELUYPLSED -- score: 7 2: HSSSIMJM ETJISGBSKIELUYPLSED -- score: 8 3: EETLITLM ETJISTBSKIELUYLLSEL -- score: 11 ``` ... ``` 78: METHINKS IT IS LIKEEA WEASEL -- score: 27 79: METHINKS IT IS LIKEEA WEASEL -- score: 27 80: METHINKS IT IS LIKEEA WEASEL -- score: 27 81: METHINKS IT IS LIKE A WEASEL -- score: 28 ``` [Answer] # Python: 282 characters no semi colons ``` from random import* g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice k=map(c,[l]*28) while(r!=28): r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100]) print`g`+":","".join(k),"-- score:",`r` g+=1 ``` # 278 with: ``` from random import*;g,r,l,c=0,0,"ABCDEFGHIJKLMNOPQRSTUVWXYZ ",choice;k=map(c,[l]*28) while(r!=28):r,k=max((sum(i==j for i,j in zip(t,"METHINKS IT IS LIKE A WEASEL")),t)for t in[[c(l)if random()<.05 else i for i in k]for i in[1]*100]);print`g`+":","".join(k),"-- score:",`r`;g+=1 ``` [Answer] # JavaScript, ~~277~~ 246 ``` c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m];for(s=[k=28];e=k;s[--k]=c(27));for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t)for(z=100;f=0,z--;f>e&&(t=n,e=f))n=s.map((h,p)=>(h=c(540)||h,f+=h=="METHINKS IT IS LIKE A WEASEL"[p],h)) ``` (requires arrow function support; indentation added only for readability) ``` // c() returns a random char using `m` as an index max c=m=>" ABCDEFGHIJKLMNOPQRSTUVWXYZ"[0|Math.random()*m]; // generate base string `s` for(s=[k=28];e=k;s[--k]=c(27)); // while score `e` is < 28 for(;alert(k+++": "+s.join("")+" -- score: "+e),e<28;s=t) for(z=100;f=0,z--;f>e&&(t=n,e=f)) // do 100 mutations; keep best score n=s.map((h,p)=>( // map `s` to `n` with 5% mutation h=c(540)||h, // change the char in 5% of cases f+=h=="METHINKS IT IS LIKE A WEASEL"[p], // score++ if char matches h // arrow function return character )) ``` Feel free to change `alert` to `console.log` if you want a more pleasant execution experience. There are some nifty golfy bits in here: * The function `c` returns a random character from the alphabet string `" ABC..."`. The function takes an argument to use as an upper bound for the random index selection. When generating the base string, we use `27`, so the function behaves normally. However, we abuse this behavior by asking for a random upper bound of 540 in `h = c(540) || h`. Only 5% of the time will `c` actually return a string (because 540 \* .05 = 27); the other 95% of the time, the randomly-chosen index falls beyond the length of the string, so the function returns `undefined`. This falsey value causes a logical-OR cascade in `c(540) || h`, so the original `map` value `h` is used (i.e., no replacement occurs). * The score-summing operation does `f+=h=="METHINKS IT IS LIKE A WEASEL"[p]`, which says "add `true` to `f` if the current `map` character `h` matches the `p`th character of the WEASEL string". The number-plus-boolean addition coerces the boolean result to either `0` or `1`, which means that `f` is incremented only when there is a match against the target WEASEL string. [Answer] # C 256 ``` char c[101][29],s,n,z,b,j,i,w;g;main(){for(;w<28;printf("%d: %s -- score: %d\n",g++,c[b=n],w))for(i=w=0;i<101;i++)for(s=j=0;j<28&&!(i==b&&g);j++)(s+=(c[i][j]=g&&rand()%20?c[b][j]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[j])>w?n=i,w=s:0;} ``` Simple three loops, initialization, generation of new strings from parent and score calculated by the same statement. It's not very readable even with indentation. # C 252 ``` i,g,n,b,o,s,w,z;char c[2929];main(){for(;(o=i%29)|i|w<28;(i=(i+1)%2929)||printf("%d: %s -- score: %d\n",g++,&c[b=n],w))(s+=o>27?-s:((i-o!=b||!g)&&(c[i]=g&&rand()%20?c[b+o]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[o]))>w?n=i-o,w=s:0;} ``` One loop, with one array holding all 101 strings. This second version breaks the rules because it prints the string from (the equivalent of) step 1, but it was either that or not print the last string. I'm stumped how to fix it without exploding in size. I'm posting it anyway for inspiration. # C 256 ``` struct{char d[29];}p,t,n;i,j=-1,z,s,w,g;main(){for(;w<28;j>1&&printf("%d: %s -- score: %d\n",g++,(p=n).d,w))for(;j++%100;p=j?p:t)for(s=0,i=28;i--;)(s+=(t.d[i]=j&&rand()%20?p.d[i]:(z=rand()%27)?'A'+z-1:' ')=="METHINKS IT IS LIKE A WEASEL"[i])>w?n=t,w=s:0;} ``` Different approach, instead of making an array to hold 101 strings just regenerate the string 100 times and use struct assignment for easy copying. Initialization is done by starting the "repeat 100 times" counter at -1 and handling it carefully by strategically chosen post-increment. Despite a very different approach it ends up exactly the same as the first attempt - 256 characters. [Answer] ## C# - 436 ``` namespace System.Linq{class W{static void Main(){var r=new Random(); Func<char>c=()=>(char)(r.Next(33,60)%59+32);var s=""; while(s.Length<28)s+=c();var a="METHINKS IT IS LIKE A WEASEL";int b=0; while (s!=a){int m=-1;var f=s;for(int i=0;i<100;i++){ var l=string.Join("",s.Select(j=>(r.Next(20)!=0?j:c()).ToString())); int o=Enumerable.Range(0,28).Sum(j=>l[j]==a[j]?1:0);if(o>m){f=l;m=o;}} Console.WriteLine(b+++": "+(s=f)+" -- score: "+m);}}}} ``` [Answer] **Lua 5.1 (502)** The minimised version: ``` s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28 while q~=f do r,p={},{} for x=1,d do i(r,s) i(p,0) e="" for o=1,f do if c(1,20)==1 then if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end else e=e..a(r[x],o,o) end end r[x]=e for y=1,f do if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end end if p[x]==f then s=r[x] end end for x=1,d do if p[x]>=q then s,q=r[x],p[x] end end print(b..":",s,"-- score: "..q) b=b+1 end ``` and the easier to read version (with comments!): ``` s,t,b,c,i,q,a,d,f="ABCDFGHJYUEGKSHNCOLPQIEJUSNC","METHINKS IT IS LIKE A WEASEL",1,math.random,table.insert,1,string.sub,100,28 --s=random string, t=target, b=counter, c=reference to math.random, i=reference to table.insert, q=top score,a=reference to string.sub, d=constant (100), f=constant (28) while q~=f do r,p={},{} for x=1,d do --add 100 copies to the table of strings i(r,s) i(p,0) e="" for o=1,f do --for each character in string if c(1,20)==1 then -- 5% chance if c(1,27)==1 then e=e.." " else e=e..string.char(c(65,90)) end --set it to an ASCII char between 65 and 90 (A-Z) or a space character else e=e..a(r[x],o,o) end end r[x]=e --current string = mutations for y=1,f do if a(r[x],y,y)==a(t,y,y) then p[x]=p[x]+1 end end --for each char increment score if it is correct if p[x]==f then s=r[x] end --if 28 then final string is this! end for x=1,d do if p[x]>=q then s,q=r[x],p[x] end --if this is the highest score so far, then make the string equal to this end print(b..":",s,"-- score: "..q) --print it! b=b+1 --add one to the counter! end ``` To be honest even though this definitely won't win, I was just glad to find and minimise a *reasonably* short solution for this problem! (emphasis on reasonably) :p [Answer] ## SAS - 374 ``` %macro r;ranuni(7)%mend;%macro s;r=int(%r*27);substr(x,t,1)=byte(ifn(r,64+r,32));%mend;%macro y;char(y,t)=char(x,t)%mend;options nonotes nosource;data x;length x$28;do t=1to 28;%s;end;y="METHINKS IT IS LIKE A WEASEL";do z=1by 1;o=x;do i=1to 100;c=0;x=o;do t=1to 28;if %r<=.05then do;%s;end;c+%y;end;if c>m then do;m=c;v=x;end;end;x=v;put z":" x"-- score:" m;if m<28;end;run; ``` -> ``` 1 :GUUVLNUSILSRZLRBXVVCWXX HXKC -- score:2 2 :MUUVLNUSILSRZLRBXVMCWXX HXKC -- score:3 3 :MUUVLNESILSRILRBXVMCWXX HXKC -- score:4 4 :MEUVLNESILSRIRRBXVMCWXX HXKC -- score:5 .... 95 :METHINKS IT IS LIKE A XEASEL -- score:27 96 :METHINKS IT IS LIKE A XEASEL -- score:27 97 :METHINKS IT IS LIKE A XEASEL -- score:27 98 :METHINKS IT IS LIKE A WEASEL -- score:28 ``` With linebreaks/indent/comments: ``` %macro r; ranuni(7) /* seed 0 will make new each time (seed=clock), otherwise fixed results */ %mend; %macro s; /* does the rand char, used both to initialize and replace; */ r=int(%r*27); substr(x,t,1)=byte(ifn(r,64+r,32)); *r=0 becomes space otherwise upper char; %mend; %macro y; /*compares using new to 9.2 CHAR function which is equivalent to substr(str,start,1) */ char(y,t)=char(x,t) %mend; options nonotes nosource; /*cheapest way to get clean log */ data x; length x$28; /*annoyingly necessary*/ do t=1to 28;%s;end; /*initialize string*/ y="METHINKS IT IS LIKE A WEASEL"; /*compare string */ do z=1by 1; /*start iterating */ o=x; /*save this iteration's string */ do i=1to 100; c=0; /*score for this iteration*/ x=o; /*string to fudge about start out clean, reusing x so no params to macro*/ do t=1to 28; if %r<=.05then do;%s;end; /*if 5% then change the char out */ c+%y; /*score that character*/ end; if c>m then do; /*if on better scoring line, save it */ m=c; v=x; end; end; x=v; *for next iter - this is cheaper than other options involving o=v due to first iter; put z":" x"-- score:" m; if m<28; *quit at 28; end; run; ``` [Answer] ## C ~~361~~ 331 Not as good as Art's solution, but here's my (newbie) attempt at a C solution. 361 characters if you remove newlines and tabs. ``` char*w="METHINKS IT IS LIKE A WEASEL";char b[101][29];t,s,n,i,j,x,a;main(){for(;i<28;i++)b[0][i]=w[rand()%28];while(s<28){for(j=1;j<101;j++){x=0;for(i=0;i<28;i++){if(!(rand()%20))b[j][i]=w[rand()%28];else b[j][i]=b[0][i];if(b[j][i]==w[i])x++;}if(x>s){s=x;t=j;}}printf("%d: %s -- score %d\n",n++,b[t],s);for(;i>=0;--i){a=b[0][i];b[0][i]=b[t][i];b[t][i]=a;}t=0;}} ``` Edit: Got rid of the nested loop and used a 1D array. Was hoping it would make a bigger difference, but it only saved me 30 characters. Here's the code: ``` char*w="METHINKS IT IS LIKE A WEASEL";char b[2929];t,s,n,i,x;main(){for(;i<28;i++)b[i]=w[rand()%28];while(s<28){for(;i<2929;i++){if((i+1)%29){if(!(i%29))x=0;b[i]=rand()%20?b[i%29]:w[rand()%28]; x+=b[i]==w[i%29];if(x>s){s=x;t=i/29;}}}for(i=0;i<29;i++){x=b[i+t*29];b[i+t*29]=b[i];b[i]=x;}printf("%d: %s -- score %d\n",n++,b,s);t=0;}} ``` Edit: This is the original, ungolfed code, for those who are interested in knowing how the "golfing" was done. The code produces no warnings when compiled with GCC with -Wall and C99 enabled. Maybe you're a golfing newbie like me, or a C newbie like me, or maybe you're just curious. :) <https://gist.github.com/cpx/97edbce4db3cb30c306a> [Answer] ## Scala, ~~347~~ ~~341~~ 337 chars: ``` import util.Random.{nextInt=>r} val t="METHINKS IT IS LIKE A WEASEL" def c="ABCDEFGHIJKLMNOPQRSTUVWXYZ "(r(27)) def s(a:String)=t.zip(a).map{x=>if(x._1==x._2) 1 else 0}.sum def w(a:String,i:Int=0){println(f"$i%2d: $a -- score: ${s(a)}") if(s(a)!=28){w((0 to 99).map{_=>a.map(o=>if(r(20)<1) c else o)}.sortBy(s).last,i+1)}} w(t.map(_=>c)) ``` => ``` 0: PGSHWAEPALQFTCORUKANPNUTRVXH -- score: 2 1: PGSHWAEPALQ TCOQUKANPNUTRVXH -- score: 3 ... 47: METHINKS WT IS LIKE A WEASEL -- score: 27 48: METHINKS IT IS LIKE A WEASEL -- score: 28 ``` [Answer] ## PHP 442 ``` <? function r(){$n=rand(65,91);if($n==91) return ' ';else return chr($n);}function s($s){$c=0;$t='METHINKS IT IS LIKE A WEASEL';for($i=0;$i<28;$i++) if($s[$i]==$t[$i]) $c++;return $c;}function m($s){for($i=0;$i<28;$i++) if(rand(0,99)<5) $s[$i]=r();return $s;}$s='';for($i=0;$i<28;$i++) $s.=r();for($i=0;;$i++){$l=s($s);printf("%2d: %s -- score: %d\n",$i,$s,$l);if($l==28) break;$x=$s;for($j=0;$j<100;$j++){$t=m($s);if(s($t)>$l) $x=$t;}$s=$x;} ``` Readbly: ``` <? //random char function r(){ $n=rand(65,91); if($n==91) return ' '; else return chr($n); } //score function s($s){ $c=0; $t='METHINKS IT IS LIKE A WEASEL'; for($i=0;$i<28;$i++) if($s[$i]==$t[$i]) $c++; return $c; } //mutate function m($s){ for($i=0;$i<28;$i++) if(rand(0,99)<5) $s[$i]=r(); return $s; } $s=''; for($i=0;$i<28;$i++) $s.=r(); for($i=0;;$i++){ $l=s($s); printf("%2d: %s -- score: %d\n",$i,$s,$l); if($l==28) break; $x=$s; for($j=0;$j<100;$j++){ $t=m($s); if(s($t)>$l) $x=$t; } $s=$x; } ``` [Answer] # Java (632) ``` class C {public static void main(String[] a){String b="AAAAAAAAAAAAAAAAAAAAAAAAAAAA";for(int i=1;;i++){String c=w(b);int s=s(c);if(s==28)break;if(s(b)<s){b=c;System.out.println(i+": "+c+" -- score: "+s);}}}public static String w(String b) {StringBuffer c = new StringBuffer(b);int max = 0;for (int i=0;i<100;i++){for(int j=0;j<28;j++)if(Math.random()<.06){double d=Math.random();c.setCharAt(j,(char)(d==1?32:d*26+65));}String d=c.toString();int s=s(d);if(s>max){max=s;b=d;}}return b;}public static int s(String s){String b="METHINKS IT IS LIKE A WEASEL";int sum=0;for(int j=0;j<28;j++)sum+=s.charAt(j)==b.charAt(j)?1:0;return sum;}} ``` Java is such a verbose language.. :( [Answer] # Python (~~330~~ 321) ``` def b(i,s):print i,':',''.join(s),'-- score:',p(s) from random import*;a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ";i,s,t=0,choice(a)*28,"METHINKS IT IS LIKE A WEASEL";p=lambda n:sum(n[c]==t[c]for c in range(28)) while p(s)<28:b(i,s);s=sorted([[(c,choice(a))[random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1 b(i,s) ``` Readable version: ``` def b(i,s): print i,':',''.join(s),'-- score:',p(s) import random as r a=" ABCDEFGHIJKLMNOPQRSTUVWXYZ" i,s,t=0,r.choice(a)*28,"METHINKS IT IS LIKE A WEASEL" p=lambda n:sum(1for c in range(28)if n[c]==t[c]) while p(s)<28: b(i,s) s=sorted([[(c,r.choice(a))[r.random()<.05]for c in s]for k in[1]*100],key=lambda n:p(n))[-1];i+=1 b(i,s) ``` Example output: ``` 0 : SSSSSSSSSSSSSSSSSSSSSSSSSSSS -- score: 3 1 : SSSQSSSSSSSSSSSSISSSSSSSSSSS -- score: 4 2 : SSSQISSSSSSSSSSSISSSSSSSSSSS -- score: 5 3 : SSSQISSSSSSSSSSSIKSSSSSSSSSS -- score: 6 4 : SMSQISSSSSSSISSSIKSSSSGSSSSS -- score: 7 ... 53 : METHINKS IT IS UIKE A WEASEL -- score: 27 54 : METHINKS IT IS UIKE A WEASEL -- score: 27 55 : METHINKS IT IS LIKE A WEASEL -- score: 28 ``` edit: removed a few characters based on AMKs and Timtechs answer [Answer] **PHP (381 397 323 319 312):** ``` <? function s(&$s,&$i=0){$t='METHINKS IT IS LIKE A WEASEL';$i=0;$c=$s;$f=28;while($f--){$n=rand(0,26);$i+=($s[$f]=($c=='_'||!rand(0,19)?chr($n?$n+64:32):$s[$f]))==$t[$f];}}$s='_';s($s);$x=$y=0;do{$f=100;while($f--){$m=$s;s($m,$i);if($i>$y){$y=$i;$l=$m;}}printf("%2d: %s -- score: $y\n",$x++,$s=$l);}while($y<28); ``` Readable version: ``` <? function s(&$s, &$i = 0) { $t = 'METHINKS IT IS LIKE A WEASEL'; $i = 0; $c = $s; $f = 28; while ($f--) { $n = rand(0, 26); $i += ($s[$f] = ($c == '_' || !rand(0, 19) ? chr($n ? $n + 64 : 32) : $s[$f])) == $t[$f]; } } $s = '_'; s($s); $x = $y = 0; do { $f = 100; while ($f--) { $m = $s; s($m, $i); if ($i > $y) { $y = $i; $l = $m; } } printf("%2d: %s -- score: $y\n", $x++, $s = $l); } while ($y < 28); ``` Optimization credits (319): * @GigaWatt [in this comment](https://codegolf.stackexchange.com/questions/17294/golfing-a-weasel-program#comment34957_17358) * @Einacio for !rand(0,19) [taken from here](https://codegolf.stackexchange.com/questions/17294/golfing-a-weasel-program#17906) Optimization credits (312): * @Einacio's comments [Answer] ## Ruby, 218 ``` g,s,p,t=-1,'',1;while t!=28;t,b=-1;100.times{|i|m,n='',0 28.times{|j|n+=1if(m[j]=(rand<p ?[*?A..?Z,' '].sample: s[j]))=="METHINKS IT IS LIKE A WEASEL"[j]} b,t=m,n if n>t};puts"#{g+=1}: #{s=b} -- score: #{t}";p=0.05;end ``` example run ``` 0: LRAZZMKL IKUOGEHLKPWEVNEAZWX -- score: 6 1: LRAZZMKL IKUIGEALKMWEVNEAZWX -- score: 7 2: HRAGZMKL IKUIGEALKMWEVNEAZWX -- score: 7 3: HVAGZMKL IKUISAALKYWEVNEAZWX -- score: 8 ... 48: METHIUKS IT IS LIKEIA WEASEL -- score: 26 49: METHINKS IT IS LIKEIA WEASEL -- score: 27 50: METHINKS IT IS LIKEIA WEASEL -- score: 27 51: METHINKS IT IS LIKE A WEASEL -- score: 28 ``` [Answer] ## Ruby - ~~225~~ ~~202~~ ~~203~~ 198 chars Ruby seems under-represented in this challenge so far so I thought I would give it a try! Improvements welcome. ``` g=-1 s=[] puts"#{g+=1}: #{$.,s=(0..99).map{n=(r=0..27).map{|i|x=[' ',*?A..?Z].sample;rand<0.05?x:s[i]||=x};[r.count{|i|n[i]=='METHINKS IT IS LIKE A WEASEL'[i]},n*'']}.max;s} -- score: #$."until$.>27 ``` [Answer] # Ruby, ~~206~~ ~~200~~ 199 ``` q,i,*R=*-2..27 puts"#{i+=1}: #{$.,s=(-2..q).map{x=R.map{|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]};[R.count{|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]},x]}.max;q=97;s.join} -- score: #$."until$.>27 ``` The first line is simply a fancy way to define `q=-2`, `i=-1`, and `R=(0..27).to_a`. All the work is done in the 2nd line: ``` puts"..."until$.>27 # Prints the string in quotes until we reach the desired score ^ | +---+ | "#{i+=1}: #{...} -- score: #$." ^ ^ ^ +--------|---------------|-- Generation counter +----------+---------------|-- Current string | +-- Score of current string (interpolates the `$.` variable) | #{$.,s=(-2..q).map{...}.max;q=97;s.join} # Generate the score & string ^ ^ ^ ^ ^ ^ ^ +---------|--|---|----|---|----|------ Store the score; this variable makes | | | | | | string interpolation shorter. +--|---|----|---+----|------ `q` automatically takes care of generating | | | | the string vs randomizing the string. +---|----|--------|------ Make 100 (or 1 the first time) strings, | | | and compute their score. | +--------|------- Take the string with the max score. +------------------+ +------- `s` is stored as an array | x=R.map{...};[R.count{...},x] # Compute string and its score, store in array ^ ^ ^^ ^ +-----|----|+-------|------ `R` is 0..27, we use the constant to save chars. | +--------|------ `max` orders by first element, then second. We clearly want | | the highest score, so make the score first. +-------+-------------|------ Generate the string, store in `x`. | +------ Count the number of chars that overlap with 'METHINKS...' | | | {|i|x[i]=='METHINKS IT IS LIKE A WEASEL'[i]} {|j|!s||rand<0.05?[*?A..?Z,' '].sample: s[j]} ^ ^ ^ ^ ^ +---+---------|-------------|-------|---- 5% chance of randomizing, or 100% for | | | first string. +-------------+-------|---- Sample from alphabet + ' '. +---- Don't alter the string 95% of the time ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~112~~ 108 bytes ``` ª(T=Si26õdI q¹ö28 _¬í¥`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x (OpW+`: {U} -- sÖ: `+(K=[U]xV¹WÄ K<28©ßLÆ®p513 iT ö}ÃñV o ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=qihUPVNpMjb1ZEkgcbn2MjgKX6ztYNowiGtzIIogiSCma2UgYSDY4mVsYHUgrCI9PSIgeAooT3BXK2A6IHtVfSAtLSBz1hA6IGArKEs9K1tVXW1WuVfECks8Mjip30zGrnA1MTMgaVQg9n3D8VYgbw==&input=) -4 bytes thanks to @ETHproductions. ### Unpacked & How it works ``` U||(T=Si26õdI q) ö28 Initialize primary input U|| If U is not initialized... 26õdI Generate uppercase alphabets q Convert to string Si Add space (T= ) Assign to variable T ö28 Sample 28 random chars from T and form a string Implicitly assign to U _q í==`Ú0ˆks Š ‰ ¦ke a Øâel`u q)x Match counting function _ Declare a function... q í== ) Convert to array of chars and pair with the next, and map with equality... `Ú0ˆks Š ‰ ¦ke a Øâel`u q "methinks it is like a weasel" to uppercase split into chars x Sum (true == 1, false == 0) Implicitly assign to V (OpW+`: {U} -- sÖ: `+(K=[U]xV) W+1 Output and increment counter (Op ) Output with newline... W+`: {U} -- sÖ: `+ `{W}: {U} -- score: ` [U]xV Call V on [U] and force cast to number (K= ) Assign to K W+1 Add 1 to W and implicitly assign to W K<28&&ßLo@Um_p513 iT ö}} ñV o Termination check and recursion K<28&& If the match count is less than 28... ß Recurse the program with... Um_ Map over chars of U... p513 iT The char repeated 513 times plus T ö} Sample a char from it Lo@ } Generate array of 100 of the above ñV o Sort by V, pop the largest, pass it as U ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, 94 bytes A different approach to but with a little inspiration from [Bubbler's solution](https://codegolf.stackexchange.com/a/165790/58974). ``` ;C±S ö28 ȶ`Ú0ks ¦ke a Øâel`gY @=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)ʶG}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸ ``` [Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=O0OxUyD2MjgKyLZg2jCIa3MgiiCJIKZrZSBhINjiZWxgZ1kKQD0jZMajMjD2ID9YOkP2w8PxX6x4VsNvKcq2R31hQE5wW1grJzpVdSAnLbJgc9YQOmBHPVWseFZduA==&input=LVI=) (or [Try It Online](https://tio.run/##AYIAff9qYXB0//87Q8KxUyDDtjI4CsOIwrZgw5owwohrcyDCiiDCiSDCpmtlIGEgw5jDomVsYGdZCkA9I2TDhsKjMjDDtiA/WDpDw7bDg8ODw7Ffwqx4VsODbynDisK2R31hQE5wW1grJzpVdSAnLcKyYHPDlhA6YEc9VcKseFZdwrj//y1S)) --- ## Explanation ### Line 1 Result gets assigned to variable `U`. ``` ;C±S ö28 ;C :The lower case alphabet ±S :Append a space and reassign result to C ö28 :Generate a string of 28 random characters ``` ### Line 2 Result gets assigned to variable `V`. ``` ȶ`Ú...l`gY È :A function that takes 2 arguments; a string (X) and an integer (Y) `Ú...l` : The compressed string "methinks it is like a weasel" gY : Get the character at index Y ¶ : Test for equality with X ``` ### Line 3 The result of this line is implicitly joined with newlines and output. ``` @=#dÆ£20ö ?X:CöÃÃñ_¬xVÃo)Ê¥G}a@Np[X+':Uu '-²`sÖ:`G=U¬xV]¸ @ }a@ :Repeat until true [ ] :Build an array containing ... X+': : A colon appended to the number of the current iteration Uu : The current value of U uppercased '-² : A hyphen repeated twice `sÖ:` : The compressed string "score: " U¬ : Split U to an array of characters V : Pass each character X at index Y through function V x : Reduce by addition G= : Assign the result to variable G ¸ :Join with spaces Np :Push to N (initially an empty array) #d :100 Æ :Generate the range [0,100) and pass each through a function £ : Map over each character X in U 20ö : Generate a random number in the range [0,20), which has a 5% chance of being 0 (falsey) ?X : If thruthy, return X :Cö : Else return a random character from C à : End mapping à :End function ñ_ :Sort by passing each through a function ¬ : Split to an array of characters V : Pass each character X at index Y through function V x : Reduce by addition à :End sorting o :Pop the last element = ) :Reassign to U Ê :Length ¶G :Equal to G ``` [Answer] ## [Perl 5](https://www.perl.org/), 219 bytes ``` $_="METHINKS IT IS LIKE A WEASEL";sub r{(A..Z,$")[rand 27]};sub t{~~grep/$t[$-++%28]/,pop=~/./g}$}.=r for@t=/./g;printf"%3d: %s -- score: %d ",$i++,(($})=sort{t($b)<=>t$a}map s/./rand>.05?$&:r/ger,($})x100),t$}until/$}/ ``` [Try it online!](https://tio.run/##HY5Ra4MwFIXf9ysu4ToUY@I6yka7dPNBmLTbi4VCSxl2WhE6DTcpDCT@dVf3eM53@Di6ost8HPFLsY90@559rnPItpDlsMnWKSSwS5M83bCluZ6Aej8RYs@RBQcq2hJmT0f3T2w/DDVVWqI9YBSG3uz5KLnutBqkkLVDJxTBuaM3q6Ziqalp7Zl5j@UCPANRBOa7o@oWyjvGsQlD7vvoAmU6sr318RS8qJXFwv0UGszNMR1YiXj@ivcLknVFfNr/PsRxwC26a2ubi0Qnx/EP "Perl 5 – Try It Online") [Answer] # Ruby - 410 ``` #!/usr/bin/env ruby C,RC=[32]+(65..90).to_a,->{C[rand(27)].chr} T,CO,CH,OU,s,sc,a,aa,z,TR="METHINKS IT IS LIKE A WEASEL",->x{a=0;(0...28).each{|z|a+=1 if x[z]==T[z]};a},->{a[aa.rindex(sc)]},->x,y{print x;print " Score: ";puts y},(0...28).map{RC[]}.join,0,[0],[0],0,->{rand(20)==0} until sc==28 a=[s]*100;aa=[0]*100;(0...100).each{|x|(0...28).each{|y|a[x][y]=RC[] if TR[]};z=CO[a[x]];aa[x]=CO[a[x]];OU[a[x],z]};sc=aa.max;s=CH[] end ``` Edit\* It's currently failing (for some reason a[any] is being set to 0 (type=>fixnum)). However, the actual design is right, I just need to find the bug causing this to happen (it's very mysterious) [Answer] ## Python 284 ``` from random import* C=choice A=map(chr,range(65,91)+[32]) s=[C(A)for i in[0]*28] N=x=0 while N!=28:N,s=max((len([i for i,j in zip(X,"METHINKS IT IS LIKE A WEASEL")if i==j]),X)for X in[[c if random()<.95 else C(A)for c in s]for i in[0]*100]);print`x`+":",''.join(s),"-- score:",N;x+=1 ``` [Answer] ## GolfScript 207 ``` {91,{64>},32+''+27rand=}:g;'METHINKS IT IS LIKE A WEASEL':s;{`{\.@\=s@==}+s,,\%{+}*}:c;0:k;{k):k\.': '@@c' -- score: '\++++n+}:f;[{g}]28*{~}%{s=!}{{`100,\{\;{100rand 5>{ }{;g}if}%''+}+}~%{c}$)\;{ }%}/{f}/s f ``` Below is a slightly unpacked version of the above GolfScript with explanation. Since I don't think it could beat the APL or some other answers, I didn't bother to truly minify it. I think that with inlining variable declarations, eliminating unnecessary variables, and other such tricks, this code could achieve approximately 190 characters without really changing the algorithm. I think about about 10-15 characters could be removed if I better sorted out the conversion between arrays of ASCII values and strings. ``` #g is a function that returns the ASCII value of a random character or space. #The ASCII values for capital letters are 65-90, and 32 is space. {91,{64>},32+''+27rand=}:g; #s is the string of interest. 'METHINKS IT IS LIKE A WEASEL':s; #c is a function that returns the 'score' of a given string #(the number of correct characters in the correct place). {`{\.@\=s@==}+s,,\%{+}*}:c; #t is a function that transforms a given string according to #the specification (by replacing characters with a random character 5% of the times). {{100rand 5>{ }{;g}if}%''+}:t; #i is the initial random string. [{g}]28*{~}%:i; #Use '/' to unfold the initial value until the string is equal to the string of interest. #Every loop, do the transformation 100 times, then sort by score c, and then take the top scoring string. #Aggregate the results into an array a. i{s=!}{{`100,\{\;t}+}~%{c}$)\;{ }%}/:a; #Instantiate a counter variable k 0:k; #f is the formatting function, that takes a string and formats it according to the spec. {k):k\.': '@@c' -- score: '\++++n+}:f; #Format every string in the array, and then format the string of interest a{f}/ s f ``` [Answer] # JavaScript - 312 There is already a shorter JS solution above but it is using experimental pointer functions, so I thought I'd throw in another solution that is running in any JS environment: ``` for(r=Math.random,R=function(){return'METHINKS CODZAWFLBUGYQRXVJP'[~~(r()*27)]},_=[],_.$=n=0,D=function(s){for(c=[],c.$=i=0;i<28;){c[i]=s&&r()<.95?s[i]:R();_=(c.$+=c[i]=='METHINKS IT IS LIKE A WEASEL'[i++])>_.$?c:_};return c},D();_.$<28;){for(j=0;j++<1e2;)D(_);console.log(n+++': '+_.join('')+' -- score: '+_.$)} ``` [Answer] ## Java: ~~557~~ 534 ``` enum W{W;public static void main(String[]a){char[]c=new char[28],h,d[];int i,k,e,s=W.s(c);for(i=0;i<28;i++)c[i]=W.r();for(i=0;;){W.p(i++,h=c,s);if(s>27)break;d=new char[100][28];for(char[]b:d){for(k=0;k<28;k++)b[k]=Math.random()<.05?W.r():h[k];if((e=W.s(b))>s){s=e;c=b;}}}}int s(char[]c){int s=0,k;for(k=0;k<28;k++)if(c[k]=="METHINKS IT IS LIKE A WEASEL".charAt(k))s++;return s;}void p(int i,char[]c,int s){System.out.println(i+": "+new String(c)+" -- score: "+s);}char r(){int i=(int)(Math.random()*27);return(char)(i==26?32:i+65);}} ``` Unwrapped: ``` enum W { W; public static void main(String[] a) { char[] c = new char[28], h, d[]; int i, k, e, s = W.s(c); for(i = 0; i < 28; i++) c[i] = W.r(); for(i = 0;;) { W.p(i++, h = c, s); if(s > 27) break; d = new char[100][28]; for(char[] b : d) { for(k = 0; k < 28; k++) b[k] = Math.random() < .05 ? W.r() : h[k]; if((e = W.s(b)) > s) { s = e; c = b; } } } } int s(char[] c) { int s = 0, k; for(k = 0; k < 28; k++) if(c[k] == "METHINKS IT IS LIKE A WEASEL".charAt(k)) s++; return s; } void p(int i, char[] c, int s) { System.out.println(i + ": " + new String(c) + " -- score: " + s); } char r() { int i = (int)(Math.random() * 27); return (char)(i == 26 ? 32 : i + 65); } } ``` [Answer] **PHP ~~429~~ ~~426~~ ~~421~~ 415** ``` <? function t(){$a="ABCDEFGHIJKLMNOPQRSTUVWXYZ ";return $a{rand(0,26)};}$c='';$j=$g=0;$i=28;while($i--)$c.=t();function r($s){$i=28;while($i--)!rand(0,19)&&$s{$i}=t();return $s;}function s($s,&$r){$c="METHINKS IT IS LIKE A WEASEL";$i=28;$r=0;while($i--)$r+=$s{$i}==$c{$i};}while($g<28){$n='';$v=0;$i=100;while($i--){s($t=r($c),$a);($a>$v)&&($v=$a)&($n=$t);}($v>$g)&&($g=$v)&($c=$n);echo $j++.": $c -- score: $g\n";} ``` pretty print ``` <?php function t(){ $a="ABCDEFGHIJKLMNOPQRSTUVWXYZ "; return $a{rand(0,26)}; } $c=''; $j=$g=0; $i=28; while($i--) $c.=t(); function r($s){ $i=28; while($i--) !rand(0,19)&&$s{$i}=t(); return $s; } function s($s,&$r){ $c="METHINKS IT IS LIKE A WEASEL"; $i=28; $r=0; while($i--) $r+=+($s{$i}==$c{$i}); } while($g<28){ $n=''; $v=0; $i=100; while($i--){ s($t=r($c),$a); ($a>$v)&&($v=$a)&($n=$t); } ($v>$g)&&($g=$v)&($c=$n); echo $j++.": $c -- score: $g\n"; } ``` I'll need a less verbose language next time [Answer] **Golfscript (**168** 167)** ``` :x;0['METHINKS IT IS LIKE A WEASEL'{}/]:o{;{27rand.!96*+64^}:r~}%{o=!}{100,{;.{20rand{}{;r}if}%}%{{[o\]zip{~=},,}:s~}$)@;\;x 2$+': '+1$+' -- score: '+1$s+n+:x;\)\}/;;x ``` Sadly, I can't seem to compress it quite to APL's level, but it's afaict currently a shared second place. This is what it does; ``` # Grab the empty parameter string as initially empty output string. :x; # Start count at row #0 0 # Store the target string as an array in 'o' ['METHINKS IT IS LIKE A WEASEL'{}/]:o # Create a random starting string, and define 'r' as a function generating a random char. {;{27rand.!96*+64^}:r~}% # Unfold as long as the latest string is different from the target string. {o=!} { // Generate 100 strings, sort by score and keep the highest. 100,{;.{20rand{}{;r}if}%}%{{[o\]zip{~=},,}:s~}$)@;\; // Append the row to the output string, and increase the row number x 2$+': '+1$+' -- score: '+1$s+n+:x;\)\ }/ // Clean some junk on the stack ;; // Output string x ``` ]
[Question] [ Write a regex which matches any valid [sudoku](https://en.wikipedia.org/wiki/Sudoku) solution and doesn't match any invalid sudoku solution. The input is an *unrolled* version of the sudoku, i.e. there are no line delimiters. E.g. the following board: ``` 7 2 5 8 9 3 4 6 1 8 4 1 6 5 7 3 9 2 3 9 6 1 4 2 7 5 8 4 7 3 5 1 6 8 2 9 1 6 8 4 2 9 5 3 7 9 5 2 3 7 8 1 4 6 2 3 4 7 6 1 9 8 5 6 8 7 9 3 5 2 1 4 5 1 9 2 8 4 6 7 3 ``` would be given as: ``` 725893461841657392396142758473516829168429537952378146234761985687935214519284673 ``` The rules are probably common knowledge by now, but just in case... a sudoku board is valid if and only if: * Each row contains the digits from `1` to `9` exactly once. * Each column contains the digits from `1` to `9` exactly once. * Each of the nine 3x3 subgrids contains the digits from `1` to `9` exactly once. ## Rules Your answer should consist of a single regex, without any additional code (except, optionally, a list of regex modifiers required to make your solution work). You must not use features of your language's regex flavour that allow you to invoke code in the hosting language (e.g. Perl's `e` modifier). You can use any regex flavour which existed before this challenge, but please specify the flavour. Do not assume that the regex is anchored implicitly. E.g. if you're using Python, assume that your regex is used with `re.search` and not with `re.match`. Your regex does not need to match the entire string. It just needs to match at least one substring (which may be empty) for valid solutions and yield no matches for invalid solutions. You may assume that the input will always be a string of 81 positive digits. This is regex golf, so the shortest regex in bytes wins. If your language requires delimiters (usually `/.../`) to denote regular expressions, don't count the delimiters themselves. If your solution requires modifiers, add one byte per modifier. ## Test Cases Valid boards: ``` 123456789456789123789123456231564897564897231897231564312645978645978312978312645 725893461841657392396142758473516829168429537952378146234761985687935214519284673 395412678824376591671589243156928437249735186738641925983164752412857369567293814 679543182158926473432817659567381294914265738283479561345792816896154327721638945 867539142324167859159482736275398614936241587481756923592873461743615298618924375 954217683861453729372968145516832497249675318783149256437581962695324871128796534 271459386435168927986273541518734269769821435342596178194387652657942813823615794 237541896186927345495386721743269158569178432812435679378652914924813567651794283 168279435459863271273415986821354769734692518596781342615947823387526194942138657 863459712415273869279168354526387941947615238138942576781596423354821697692734185 768593142423176859951428736184765923572389614639214587816942375295837461347651298 243561789819327456657489132374192865926845317581673294162758943735914628498236571 243156789519847326687392145361475892724918653895263471152684937436729518978531264 498236571735914628162758943581673294926845317374192865657489132819327456243561789 978531264436729518152684937895263471724918653361475892687392145519847326243156789 341572689257698143986413275862341957495726831173985426519234768734869512628157394 ``` Invalid boards: ``` 519284673725893461841657392396142758473516829168429537952378146234761985687935214 839541267182437659367158924715692843624973518573864192298316475941285736456729381 679543182158926473432817659567381294914256738283479561345792816896154327721638945 867539142324167859159482736275398684936241517481756923592873461743615298618924375 754219683861453729372968145516832497249675318983147256437581962695324871128796534 271459386435168927986273541518734269769828435342596178194387652657942813823615794 237541896186927345378652914743269158569178432812435679495386721924813567651794283 168759432459613278273165984821594763734982516596821347615437829387246195942378651 869887283619214453457338664548525781275424668379969727517385163319223917621449519 894158578962859187461322315913849812241742157275462973384219294849882291119423759 123456789456789123564897231231564897789123456897231564312645978645978312978312645 145278369256389147364197258478512693589623471697431582712845936823956714931764825 243561789829317456657489132374192865916845327581673294162758943735924618498236571 243156789529847316687392145361475892714928653895263471152684937436719528978531264 498236571735924618162758943581673294916845327374192865657489132829317456243561789 978531264436719528152684937895263471714928653361475892687392145529847316243156789 342571689257698143986413275861342957495726831173985426519234768734869512628157394 345678192627319458892451673468793521713524986951862347179246835534187269286935714 341572689257698143986413275862341957495726831173985426519234768734869512628517394 ``` For further test cases, [you can use this CJam script](http://cjam.aditsu.net/#code=3e!1%3E%7BI9%2C3%3E%2B3%2CI3f%2B9%2C6%3E%2B%2B6%2CI6f%2B%2BI9%2C3%2Ff%3De_%7DfI%5D%7B%60'%7B%5C%2B%22%5Cf%3D%7D%22%2B%7D%25s~%0A%7BW%25%7D%7Bz%7D%5D%3AP%3B%0A%0Aq%3A~9%2F%7BPmR~%7D1000*&input=7%202%205%208%209%203%204%206%201%0A8%204%201%206%205%207%203%209%202%0A3%209%206%201%204%202%207%205%208%0A4%207%203%205%201%206%208%202%209%0A1%206%208%204%202%209%205%203%207%0A9%205%202%203%207%208%201%204%206%0A2%203%204%207%206%201%209%208%205%0A6%208%207%209%203%205%202%201%204%0A5%201%209%202%208%204%206%207%203) which takes a valid board as input and randomly shuffles it to give a new valid board (input format irrelevant as long as it contains only digits and optionally whitespace). If your regex is compatible with the .NET flavour, [you can test it online](http://retina.tryitonline.net/) using Retina. A valid solution should print `0` for invalid boards and some positive integer for valid boards. To run all test cases at once, [use this template](http://retina.tryitonline.net/#code=JShHYAo&input=MTIzNDU2Nzg5NDU2Nzg5MTIzNzg5MTIzNDU2MjMxNTY0ODk3NTY0ODk3MjMxODk3MjM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1NzQ4OTEzMjM3NDE5Mjg2NTkxNjg0NTMyNzU4MTY3MzI5NDE2Mjc1ODk0MzczNTkyNDYxODQ5ODIzNjU3MQoyNDMxNTY3ODk1Mjk4NDczMTY2ODczOTIxNDUzNjE0NzU4OTI3MTQ5Mjg2NTM4OTUyNjM0NzExNTI2ODQ5Mzc0MzY3MTk1Mjg5Nzg1MzEyNjQKNDk4MjM2NTcxNzM1OTI0NjE4MTYyNzU4OTQzNTgxNjczMjk0OTE2ODQ1MzI3Mzc0MTkyODY1NjU3NDg5MTMyODI5MzE3NDU2MjQzNTYxNzg5Cjk3ODUzMTI2NDQzNjcxOTUyODE1MjY4NDkzNzg5NTI2MzQ3MTcxNDkyODY1MzM2MTQ3NTg5MjY4NzM5MjE0NTUyOTg0NzMxNjI0MzE1Njc4OQozNDI1NzE2ODkyNTc2OTgxNDM5ODY0MTMyNzU4NjEzNDI5NTc0OTU3MjY4MzExNzM5ODU0MjY1MTkyMzQ3Njg3MzQ4Njk1MTI2MjgxNTczOTQ) and insert the regex on the second line. If you need regex modifiers, prepend a ``` to the regex and put the standard modifier letters in front of it. [Answer] # Ruby regex, 71 78 73 bytes ``` ^(?!.*(?=(.))(.{9}+|(.(?!.{9}*$))+|(?>.(?!.{3}*$)|(.(?!.{27}*$)){7})+)\1) ``` I don't really know Ruby but apparently it doesn't complain about cascaded quantifiers. [Try it here.](http://rubular.com/r/5WSa21XJwQ) # .NET regex, 79 78 75 or 77 bytes Because Martin thinks this is possible... But I guess he will just incorporate these changes too. ``` ^(?!(.)+((.{9})+|(?>(.{9})+ |.)+|(?((...)* )(?>(.{27})+ |.){7}|.)+)(?<=\1)) ``` Requires a trailing newline in the input to work. I'm not sure whether I'm allowed to do this (probably not). [Try it here.](http://retina.tryitonline.net/#code=bWAkCk4KJShHYApeKD8hKC4pKygoLns5fSkrfCg_Piguezl9KStOfC4pK3woPygoLi4uKSpOKSg_PiguezI3fSkrTnwuKXs3fXwuKSspKD88PVwxKSk&input=MTIzND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I0NjE4NDk4MjM2NTcxCjI0MzE1Njc4OTUyOTg0NzMxNjY4NzM5MjE0NTM2MTQ3NTg5MjcxNDkyODY1Mzg5NTI2MzQ3MTE1MjY4NDkzNzQzNjcxOTUyODk3ODUzMTI2NAo0OTgyMzY1NzE3MzU5MjQ2MTgxNjI3NTg5NDM1ODE2NzMyOTQ5MTY4NDUzMjczNzQxOTI4NjU2NTc0ODkxMzI4MjkzMTc0NTYyNDM1NjE3ODkKOTc4NTMxMjY0NDM2NzE5NTI4MTUyNjg0OTM3ODk1MjYzNDcxNzE0OTI4NjUzMzYxNDc1ODkyNjg3MzkyMTQ1NTI5ODQ3MzE2MjQzMTU2Nzg5CjM0MjU3MTY4OTI1NzY5ODE0Mzk4NjQxMzI3NTg2MTM0Mjk1NzQ5NTcyNjgzMTE3Mzk4NTQyNjUxOTIzNDc2ODczNDg2OTUxMjYyODE1NzM5NAoxMjM0NTY3ODkyMzQ1Njc4OTEzNDU2Nzg5MTI0NTY3ODkxMjM1Njc4OTEyMzQ2Nzg5MTIzNDU3ODkxMjM0NTY4OTEyMzQ1Njc5MTIzNDU2Nzg) The 77 byte sane version: ``` ^(?!(.)+((.{9})+|((?!(.{9})*$).)+|(?((...)*$)((?!(.{27})*$).){7}|.)+)(?<=\1)) ``` Thanks Neil for pointing out the error in my previous version and golfing off 1 byte (for the `(...)*`). [Try it here.](http://retina.tryitonline.net/#code=JShHYApeKD8hKC4pKygoLns5fSkrfCgoPyEoLns5fSkqJCkuKSt8KD8oKC4uLikqJCkoKD8hKC57Mjd9KSokKS4pezd9fC4pKykoPzw9XDEpKQ&input=MTIzNDU2Nzg5NDU2Nzg5MTIzNzg5MTIzNDU2MjMxNTY0ODk3NTY0ODk3MjMxODk3MjMxNTY0MzEyNjQ1OTc4NjQ1OTc4MzEyOTc4MzEyNjQ1CjcyNTg5MzQ2MTg0MTY1NzM5MjM5NjE0Mjc1ODQ3MzUxNjgyOTE2ODQyOTUzNzk1MjM3ODE0NjIzNDc2MT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czNzQxOTI4NjU2NTc0ODkxMzI4MjkzMTc0NTYyNDM1NjE3ODkKOTc4NTMxMjY0NDM2NzE5NTI4MTUyNjg0OTM3ODk1MjYzNDcxNzE0OTI4NjUzMzYxNDc1ODkyNjg3MzkyMTQ1NTI5ODQ3MzE2MjQzMTU2Nzg5CjM0MjU3MTY4OTI1NzY5ODE0Mzk4NjQxMzI3NTg2MTM0Mjk1NzQ5NTcyNjgzMTE3Mzk4NTQyNjUxOTIzNDc2ODczNDg2OTUxMjYyODE1NzM5NAoxMjM0NTY3ODkyMzQ1Njc4OTEzNDU2Nzg5MTI0NTY3ODkxMjM1Njc4OTEyMzQ2Nzg5MTIzNDU3ODkxMjM0NTY4OTEyMzQ1Njc5MTIzNDU2Nzg) # PCRE, 77 78 bytes ``` ^(?!.*(?=(.))((.{9})+|(.(?!(?3)*$))+|(?(?=.(...)*$)(.(?!(.{27})*$)){7}|.)+)\1) ``` Just for completeness. [Try it here.](https://regex101.com/r/mN5wA8/2) Another version, also 78 bytes: ``` ^(?!.*(?=(.))((.{9})+|(.(?!(?3)*$))+|(?>.(?!(...)*$)|(.(?!(.{27})*$)){7})+)\1) ``` [Try it here.](https://regex101.com/r/mN5wA8/3) ### Explanation ``` ^(?!.* # Match a string that doesn't contain the pattern, # at any position. (?=(.)) # Capture the next character. ( (.{9})+ # Any 9*n characters. The next character is in # the same column as the captured one. | (.(?!(.{9})*$))+ # Any n characters not followed by a positions 9*m # to the end. The next character is in the same row # as the captured one. | ( # Any n occasions of... ?(.(...)*$) # If it is at a position 3*k+1 to the end: (.(?!(.{27})*$)){7} # Then count 7*m characters that are not followed # by a position 27*j to the end, | . # Else count any character. )+ # The next character is in the same block as the # captured one. ) \1 # Fail if the next character is the captured character. ) ``` [Answer] # PCRE, 117 ~~119 130 133 147~~ bytes ``` ^(?!(.{27})*(...){0,2}(.{9})?.?.?(.).?.?(?=(?2)*$).{6,8}(?3)?\4.{0,17}(?1)*$|.*(.)(.{8}(?3)*|((?!(?3)*$)(|.(?7))))\5) ``` ~~Should also work in Python, Java, etc. flavors.~~ Now with recursion! And the "recursion" feature used non-recursively for "subroutines", which I totally forgot about until I had to use actual recursion. [Answer] # .NET regex, 8339 bytes Yes, I know my solution is very naive, since Martin told me he did it in like 130 bytes. In fact, the URL to try it online is so long that I couldn't find a URL shortener that would accept it. ``` (code removed, since it's so long nobody will read it here, and it made the post take forever to load. Just use the "Try it online" link.) ``` *The below link does not work in IE, but does work in Chrome and Firefox.* [**Try it online**](http://retina.tryitonline.net/#code=IWAoPz0uezAsOH0xKSg_PS57MCw4fTIpKD89LnswLDh9MykoPz0uezAsOH00KSg_PS57MCw4fTUpKD89LnswLDh9NikoPz0uezAsOH03KSg_PS57MCw4fTgpKD89LnswLDh9OSkoPz0uezksMTd9MSkoPz0uezksMTd9MikoPz0uezksMTd9MykoPz0uezksMTd9NCkoPz0uezksMTd9NSkoPz0uezksMTd9NikoPz0uezksMTd9NykoPz0uezksMTd9OCkoPz0uezksMTd9OSkoPz0uezE4LDI2fTEpKD89LnsxOCwyNn0yKSg_PS57MTgsMjZ9MykoPz0uezE4LDI2fTQpKD89LnsxOCwyNn01KSg_PS57MTgsMjZ9NikoPz0uezE4LDI2fTcpKD89LnsxOCwyNn04KSg_PS57MTgsMjZ9OSkoPz0uezI3LDM1fTEpKD89LnsyNywzNX0yKSg_PS57MjcsMzV9MykoPz0uezI3LDM1fTQpKD89LnsyNywzNX01KSg_PS57MjcsMzV9NikoPz0uezI3LDM1fTcpKD89LnsyNywzNX04KSg_PS57MjcsMzV9OSkoPz0uezM2LDQ0fTEpKD89LnszNiw0NH0yKSg_PS57MzYsNDR9MykoPz0uezM2LDQ0fTQpKD89LnszNiw0NH01KSg_PS57MzYsNDR9NikoPz0uezM2LDQ0fTcpKD89LnszNiw0NH04KSg_PS57MzYsNDR9OSkoPz0uezQ1LDUzfTEpKD89Lns0NSw1M30yKSg_PS57NDUsNTN9MykoPz0uezQ1LDUzfTQpKD89Lns0NSw1M301KSg_PS57NDUsNTN9NikoPz0uezQ1LDUzfTcpKD89Lns0NSw1M304KSg_PS57NDUsNTN9OSkoPz0uezU0LDYyfTEpKD89Lns1NCw2Mn0yKSg_PS57NTQsNjJ9MykoPz0uezU0LDYyfTQpKD89Lns1NCw2Mn01KSg_PS57NTQsNjJ9NikoPz0uezU0LDYyfTcpKD89Lns1NCw2Mn04KSg_PS57NTQsNjJ9OSkoPz0uezYzLDcxfTEpKD89Lns2Myw3MX0yKSg_PS57NjMsNzF9MykoPz0uezYzLDcxfTQpKD89Lns2Myw3MX01KSg_PS57NjMsNzF9NikoPz0uezYzLDcxfTcpKD89Lns2Myw3MX04KSg_PS57NjMsNzF9OSkoPz0uezcyLH0xKSg_PS57NzIsfTIpKD89Lns3Mix9MykoPz0uezcyLH00KSg_PS57NzIsfTUpKD89Lns3Mix9NikoPz0uezcyLH03KSg_PS57NzIsfTgpKD89Lns3Mix9OSkoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pMSkoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pMikoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pMykoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pNCkoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pNSkoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pNikoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pNykoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pOCkoPz0ofC57OX18LnsxOH18LnsyN318LnszNn18Lns0NX18Lns1NH18Lns2M318Lns3Mn0pOSkoPz0oLnsxfXwuezEwfXwuezE5fXwuezI4fXwuezM3fXwuezQ2fXwuezU1fXwuezY0fXwuezczfSkxKSg_PSguezF9fC57MTB9fC57MTl9fC57Mjh9fC57Mzd9fC57NDZ9fC57NTV9fC57NjR9fC57NzN9KTIpKD89KC57MX18LnsxMH18LnsxOX18LnsyOH18LnszN318Lns0Nn18Lns1NX18Lns2NH18Lns3M30pMykoPz0oLnsxfXwuezEwfXwuezE5fXwuezI4fXwuezM3fXwuezQ2fXwuezU1fXwuezY0fXwuezczfSk0KSg_PSguezF9fC57MTB9fC57MTl9fC57Mjh9fC57Mzd9fC57NDZ9fC57NTV9fC57NjR9fC57NzN9KTUpKD89KC57MX18LnsxMH18LnsxOX18LnsyOH18LnszN318Lns0Nn18Lns1NX18Lns2NH18Lns3M30pNikoPz0oLnsxfXwuezEwfXwuezE5fXwuezI4fXwuezM3fXwuezQ2fXwuezU1fXwuezY0fXwuezczfSk3KSg_PSguezF9fC57MTB9fC57MTl9fC57Mjh9fC57Mzd9fC57NDZ9fC57NTV9fC57NjR9fC57NzN9KTgpKD89KC57MX18LnsxMH18LnsxOX18LnsyOH18LnszN318Lns0Nn18Lns1NX18Lns2NH18Lns3M30pOSkoPz0oLnsyfXwuezExfXwuezIwfXwuezI5fXwuezM4fXwuezQ3fXwuezU2fXwuezY1fXwuezc0fSkxKSg_PSguezJ9fC57MTF9fC57MjB9fC57Mjl9fC57Mzh9fC57NDd9fC57NTZ9fC57NjV9fC57NzR9KTIpKD89KC57Mn18LnsxMX18LnsyMH18LnsyOX18LnszOH18Lns0N318Lns1Nn18Lns2NX18Lns3NH0pMykoPz0oLnsyfXwuezExfXwuezIwfXwuezI5fXwuezM4fXwuezQ3fXwuezU2fXwuezY1fXwuezc0fSk0KSg_PSguezJ9fC57MTF9fC57MjB9fC57Mjl9fC57Mzh9fC57NDd9fC57NTZ9fC57NjV9fC57NzR9KTUpKD89KC57Mn18LnsxMX18LnsyMH18LnsyOX18LnszOH18Lns0N318Lns1Nn18Lns2NX18Lns3NH0pNikoPz0oLnsyfXwuezExfXwuezIwfXwuezI5fXwuezM4fXwuezQ3fXwuezU2fXwuezY1fXwuezc0fSk3KSg_PSguezJ9fC57MTF9fC57MjB9fC57Mjl9fC57Mzh9fC57NDd9fC57NTZ9fC57NjV9fC57NzR9KTgpKD89KC57Mn18LnsxMX18LnsyMH18LnsyOX18LnszOH18Lns0N318Lns1Nn18Lns2NX18Lns3NH0pOSkoPz0oLnszfXwuezEyfXwuezIxfXwuezMwfXwuezM5fXwuezQ4fXwuezU3fXwuezY2fXwuezc1fSkxKSg_PSguezN9fC57MTJ9fC57MjF9fC57MzB9fC57Mzl9fC57NDh9fC57NTd9fC57NjZ9fC57NzV9KTIpKD89KC57M318LnsxMn18LnsyMX18LnszMH18LnszOX18Lns0OH18Lns1N318Lns2Nn18Lns3NX0pMykoPz0oLnszfXwuezEyfXwuezIxfXwuezMwfXwuezM5fXwuezQ4fXwuezU3fXwuezY2fXwuezc1fSk0KSg_PSguezN9fC57MTJ9fC57MjF9fC57MzB9fC57Mzl9fC57NDh9fC57NTd9fC57NjZ9fC57NzV9KTUpKD89KC57M318LnsxMn18LnsyMX18LnszMH18LnszOX18Lns0OH18Lns1N318Lns2Nn18Lns3NX0pNikoPz0oLnszfXwuezEyfXwuezIxfXwuezMwfXwuezM5fXwuezQ4fXwuezU3fXwuezY2fXwuezc1fSk3KSg_PSguezN9fC57MTJ9fC57MjF9fC57MzB9fC57Mzl9fC57NDh9fC57NTd9fC57NjZ9fC57NzV9KTgpKD89KC57M318LnsxMn18LnsyMX18LnszMH18LnszOX18Lns0OH18Lns1N318Lns2Nn18Lns3NX0pOSkoPz0oLns0fXwuezEzfXwuezIyfXwuezMxfXwuezQwfXwuezQ5fXwuezU4fXwuezY3fXwuezc2fSkxKSg_PSguezR9fC57MTN9fC57MjJ9fC57MzF9fC57NDB9fC57NDl9fC57NTh9fC57Njd9fC57NzZ9KTIpKD89KC57NH18LnsxM318LnsyMn18LnszMX18Lns0MH18Lns0OX18Lns1OH18Lns2N318Lns3Nn0pMykoPz0oLns0fXwuezEzfXwuezIyfXwuezMxfXwuezQwfXwuezQ5fXwuezU4fXwuezY3fXwuezc2fSk0KSg_PSguezR9fC57MTN9fC57MjJ9fC57MzF9fC57NDB9fC57NDl9fC57NTh9fC57Njd9fC57NzZ9KTUpKD89KC57NH18LnsxM318LnsyMn18LnszMX18Lns0MH18Lns0OX18Lns1OH18Lns2N318Lns3Nn0pNikoPz0oLns0fXwuezEzfXwuezIyfXwuezMxfXwuezQwfXwuezQ5fXwuezU4fXwuezY3fXwuezc2fSk3KSg_PSguezR9fC57MTN9fC57MjJ9fC57MzF9fC57NDB9fC57NDl9fC57NTh9fC57Njd9fC57NzZ9KTgpKD89KC57NH18LnsxM318LnsyMn18LnszMX18Lns0MH18Lns0OX18Lns1OH18Lns2N318Lns3Nn0pOSkoPz0oLns1fXwuezE0fXwuezIzfXwuezMyfXwuezQxfXwuezUwfXwuezU5fXwuezY4fXwuezc3fSkxKSg_PSguezV9fC57MTR9fC57MjN9fC57MzJ9fC57NDF9fC57NTB9fC57NTl9fC57Njh9fC57Nzd9KTIpKD89KC57NX18LnsxNH18LnsyM318LnszMn18Lns0MX18Lns1MH18Lns1OX18Lns2OH18Lns3N30pMykoPz0oLns1fXwuezE0fXwuezIzfXwuezMyfXwuezQxfXwuezUwfXwuezU5fXwuezY4fXwuezc3fSk0KSg_PSguezV9fC57MTR9fC57MjN9fC57MzJ9fC57NDF9fC57NTB9fC57NTl9fC57Njh9fC57Nzd9KTUpKD89KC57NX18LnsxNH18LnsyM318LnszMn18Lns0MX18Lns1MH18Lns1OX18Lns2OH18Lns3N30pNikoPz0oLns1fXwuezE0fXwuezIzfXwuezMyfXwuezQxfXwuezUwfXwuezU5fXwuezY4fXwuezc3fSk3KSg_PSguezV9fC57MTR9fC57MjN9fC57MzJ9fC57NDF9fC57NTB9fC57NTl9fC57Njh9fC57Nzd9KTgpKD89KC57NX18LnsxNH18LnsyM318LnszMn18Lns0MX18Lns1MH18Lns1OX18Lns2OH18Lns3N30pOSkoPz0oLns2fXwuezE1fXwuezI0fXwuezMzfXwuezQyfXwuezUxfXwuezYwfXwuezY5fXwuezc4fSkxKSg_PSguezZ9fC57MTV9fC57MjR9fC57MzN9fC57NDJ9fC57NTF9fC57NjB9fC57Njl9fC57Nzh9KTIpKD89KC57Nn18LnsxNX18LnsyNH18LnszM318Lns0Mn18Lns1MX18Lns2MH18Lns2OX18Lns3OH0pMykoPz0oLns2fXwuezE1fXwuezI0fXwuezMzfXwuezQyfXwuezUxfXwuezYwfXwuezY5fXwuezc4fSk0KSg_PSguezZ9fC57MTV9fC57MjR9fC57MzN9fC57NDJ9fC57NTF9fC57NjB9fC57Njl9fC57Nzh9KTUpKD89KC57Nn18LnsxNX18LnsyNH18LnszM318Lns0Mn18Lns1MX18Lns2MH18Lns2OX18Lns3OH0pNikoPz0oLns2fXwuezE1fXwuezI0fXwuezMzfXwuezQyfXwuezUxfXwuezYwfXwuezY5fXwuezc4fSk3KSg_PSguezZ9fC57MTV9fC57MjR9fC57MzN9fC57NDJ9fC57NTF9fC57NjB9fC57Njl9fC57Nzh9KTgpKD89KC57Nn18LnsxNX18LnsyNH18LnszM318Lns0Mn18Lns1MX18Lns2MH18Lns2OX18Lns3OH0pOSkoPz0oLns3fXwuezE2fXwuezI1fXwuezM0fXwuezQzfXwuezUyfXwuezYxfXwuezcwfXwuezc5fSkxKSg_PSguezd9fC57MTZ9fC57MjV9fC57MzR9fC57NDN9fC57NTJ9fC57NjF9fC57NzB9fC57Nzl9KTIpKD89KC57N318LnsxNn18LnsyNX18LnszNH18Lns0M318Lns1Mn18Lns2MX18Lns3MH18Lns3OX0pMykoPz0oLns3fXwuezE2fXwuezI1fXwuezM0fXwuezQzfXwuezUyfXwuezYxfXwuezcwfXwuezc5fSk0KSg_PSguezd9fC57MTZ9fC57MjV9fC57MzR9fC57NDN9fC57NTJ9fC57NjF9fC57NzB9fC57Nzl9KTUpKD89KC57N318LnsxNn18LnsyNX18LnszNH18Lns0M318Lns1Mn18Lns2MX18Lns3MH18Lns3OX0pNikoPz0oLns3fXwuezE2fXwuezI1fXwuezM0fXwuezQzfXwuezUyfXwuezYxfXwuezcwfXwuezc5fSk3KSg_PSguezd9fC57MTZ9fC57MjV9fC57MzR9fC57NDN9fC57NTJ9fC57NjF9fC57NzB9fC57Nzl9KTgpKD89KC57N318LnsxNn18LnsyNX18LnszNH18Lns0M318Lns1Mn18Lns2MX18Lns3MH18Lns3OX0pOSkoPz0oLns4fXwuezE3fXwuezI2fXwuezM1fXwuezQ0fXwuezUzfXwuezYyfXwuezcxfXwuezgwfSkxKSg_PSguezh9fC57MTd9fC57MjZ9fC57MzV9fC57NDR9fC57NTN9fC57NjJ9fC57NzF9fC57ODB9KTIpKD89KC57OH18LnsxN318LnsyNn18LnszNX18Lns0NH18Lns1M318Lns2Mn18Lns3MX18Lns4MH0pMykoPz0oLns4fXwuezE3fXwuezI2fXwuezM1fXwuezQ0fXwuezUzfXwuezYyfXwuezcxfXwuezgwfSk0KSg_PSguezh9fC57MTd9fC57MjZ9fC57MzV9fC57NDR9fC57NTN9fC57NjJ9fC57NzF9fC57ODB9KTUpKD89KC57OH18LnsxN318LnsyNn18LnszNX18Lns0NH18Lns1M318Lns2Mn18Lns3MX18Lns4MH0pNikoPz0oLns4fXwuezE3fXwuezI2fXwuezM1fXwuezQ0fXwuezUzfXwuezYyfXwuezcxfXwuezgwfSk3KSg_PSguezh9fC57MTd9fC57MjZ9fC57MzV9fC57NDR9fC57NTN9fC57NjJ9fC57NzF9fC57ODB9KTgpKD89KC57OH18LnsxN318LnsyNn18LnszNX18Lns0NH18Lns1M318Lns2Mn18Lns3MX18Lns4MH0pOSkoPz0uezAsMn0xfC57OSwxMX0xfC57MTgsMjB9MSkoPz0uezMsNX0xfC57MTIsMTR9MXwuezIxLDIzfTEpKD89Lns2LDh9MXwuezE1LDE3fTF8LnsyNCwyNn0xKSg_PS57MjcsMjl9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MjQ1OTYxMzI3ODI3MzE2NTk4NDgyMTU5NDc2MzczNDk4MjUxNjU5NjgyMTM0NzYxNTQzNzgyOTM4NzI0NjE5NTk0MjM3ODY1MQo4Njk4ODcyODM2MTkyMTQ0NTM0NTczMzg2NjQ1NDg1MjU3ODEyNzU0MjQ2NjgzNzk5Njk3Mjc1MTczODUxNjMzMTkyMjM5MTc2MjE0NDk1MTkKODk0MTU4NTc4OTYyODU5MTg3NDYxMzIyMzE1OTEzODQ5ODEyMjQxNzQyMTU3Mjc1NDYyOTczMzg0MjE5Mjk0ODQ5ODgyMjkxMTE5NDIzNzU5CjEyMzQ1Njc4OTQ1Njc4OTEyMzU2NDg5NzIzMTIzMTU2NDg5Nzc4OTEyMzQ1Njg5NzIzMTU2NDMxMjY0NTk3ODY0NTk3ODMxMjk3ODMxMjY0NQoxNDUyNzgzNjkyNTYzODkxNDczNjQxOTcyNTg0Nzg1MTI2OTM1ODk2MjM0NzE2OTc0MzE1ODI3MTI4NDU5MzY4MjM5NTY3MTQ5MzE3NjQ4MjU) - All test cases at once, with the help of `!`` at the beginning, not included in byte count. --- Here's the [Python script](http://ideone.com/nUcnlc) I used to generate it (code below): ``` R=range(0,9) S=range(1,10) o = "" # validate rows T = "(?=.{%s,%s}%s)" for j in R: for i in S: o += T % (9*j,9*(j+1)-1, i) # validate columns # "(?=(.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s}|.{%s})%s)" T = "(?=("+"|".join([".{%s}"]*9)+")%s)" for j in R: for i in S: o += T % (j,j+9,j+18,j+27,j+36,j+45,j+54,j+63,j+72, i) # validate boxes # (?=.{0,2}1|.{9,11}1|.{18,20}1)(?=.{3,5}1|.{12,14}1|.{21,23}1) # (?=.{27,29}1|.{36,38}1|.{45,47}1) T = ".{%s,%s}%s" for i in S: for x in (0,27,54): for y in (0,3,6): o += "(?="+"|".join(T % (x+y+z,x+y+z+2, i) for z in (0,9,18))+")" o += ".{81}" o = o.replace(".{0}","").replace(",80}",",}") print(o) ``` [Answer] ## .NET regex, 121 bytes ``` ^(?!(.{27})*(.{9})?(...){0,2}.?.?(.).?.?(?=(...)*$)(.{9})?.{6,8}\4.{0,17}(.{27})*$|.*(?=(.))((.{9})+|(.(?!(.{9})*$))+)\8) ``` Explanation: ``` ^(?! Invert match (because we're excluding duplicates) (.{27})* Skip 0, 3 or 6 rows (.{9})? Optionally skip another row (...){0,2} Skip 0, 3 or 6 columns .?.?(.).?.?(?=(...)*$) Choose any of the next three cells (.{9})? Optionally skip another row .{6,8}\4 Match any of the three cells below .{0,17}(.{27})*$ As long as they're from the same square | OR .*(?=(.))( Choose any cell (.{9})+ Skip at least one row | or (. Skip cells (?!(.{9})*$) Without reaching the end of the row )+ For at least one cell (i.e. the cell chosen above) )\8) Match the chosen cell to the next cell ) ``` [Answer] # PCRE, 3579 bytes An absolutely terrible brute force solution. Negative lookbehinds ahoy! I spent way too much time on this to abandon it, so here it is, for posterity's sake. On the bright side, if Sudoku suddenly starts using a different set of 9 characters, this'll still work, I guess... <http://pastebin.com/raw/CwtviGkC> I don't know how to operate Retina, but you can also paste it into <https://regex101.com> or similar and it'll match. Ruby code used to generate the regex: ``` # Calculate the block you're in def block(x) x /= 3 x + x%3 - x%9 end 81.times do |i| row, col = i.divmod(9) neg = [] neg += (0...col).map {|e| 9*row + e + 1} neg += (0...row).map {|e| 9*e + col + 1} neg += (0...i).map {|e| e + 1 if block(e) == block(i)}.compact neg = neg.uniq.sort.map {|e| "\\#{e}"} if neg.size > 0 print "(?!#{neg.join '|'})" end print "(.)" end ``` [Answer] ## Ruby flavour, ~~75~~ 74 bytes *Thanks to jimmy23013 for saving 1 byte.* ``` ^(?!(.{9}*(.|(.)){,8}|.*(\g<2>.{8})*|.{27}?.{3}?(\g<2>{3}.{6}){,2}.?.?)\3). ``` [Test it here.](http://rubular.com/r/zAedzia7ds) Now that it's finally beaten, I can share my own solution. :) I discovered an interesting (maybe new?) regex technique in the process (the `(.|(.)){,8}\3` part), which would probably be unbeatable in cases where this can't be combined with other parts of the regex (as was the case in jimmy23013's answer). ### Explanation Like the other short answers I'm using a negative lookahead which searches for duplicates in rows, columns or blocks. The basic building block of the solution is this: ``` (.|(.))...\3 ``` Note that the `\3` is reused between three different alternatives (which all use group `3` for duplicate detection). That group on the left (which is group `2`, containing group `3`) is used for any position that can contain the first half of a duplicate digit (within a group that must not contain duplicate digits). Then `...` is something that gets us the the next position where such a digit might occur (if necessary) and `\3` tries to find the second half of the duplicate via backreference. The reason this works is backtracking. When the engine first matches `(.|(.))` it will simply use `.` every time and not capture anything. Now the `\3` at the end fails. But now the engine will gradually try using `(.)` instead of `.` for individual matches. Ultimately, if there's a duplicate, it will find the combination where `(.)` was last used on the first digit of the duplicate (such that the capture isn't overwritten later), and then uses some more `.` to bridge the gap to the backreference. If there is a duplicate, backtracking will always find it. Let's look at the three different parts where this is used: ``` .{9}*(.|(.)){,8} ``` This checks for duplicates in some row. First we skip to any row with `.{9}*`. Then we match up to 8 characters (i.e. anything in that row except the last digit) using the optional duplicate capture and try to find the `\3` after it. ``` .*(\g<2>.{8})* ``` This looks for duplicates in some column. First, note that `\g<2>` is a subroutine call, so this is the same as: ``` .*((.|(.)).{8})* ``` where the two groups we've just inserted are still referred to as `2` and `3`. Here, the `.*` simply skips as far as necessary (it would be sufficient to match up to 8 characters here, but that costs more bytes). Then the outer group matches one complete row (which may wrap across two physical rows) at a time, optionally capturing the first character. The `\3` will be looked for right after this, which ensures vertical alignment between the capture and the backreference. Finally, checking the blocks: ``` .{27}?.{3}?(\g<2>{3}.{6}){,2}.?.? ``` Again, the `\g<2>` is a subroutine call, so this is the same as: ``` .{27}?.{3}?((.|(.)){3}.{6}){,2}.?.? ``` To verify the blocks, note that since we've already checked all the rows and columns, we only need to check four of the 3x3 blocks. When we know that all rows and columns as well as these 3x3 blocks are correct: ``` XX. XX. ... ``` Then we know that there can't possibly be duplicates in the remaining blocks. Hence I'm only checking these four blocks. Furthermore, note that we don't have to look for duplicates within the same row of a 3x3 block. It's enough to find the first half of the duplicate in one row and search for the second half in a row further down. Now for the code itself, we first skip to the beginning of one of the four blocks with `.{27}?.{3}?` (optionally skip three rows, optionally skip three columns). Then we try to match up to two of the rows of the 3x3 block with the same trick we used for the rows earlier: ``` (.|(.)){3}.{6} ``` We allow but don't require capturing of any of the 3 cells in the current row of the 3x3 block and then skip to the next row with `.{6}`. Finally, we try to find a duplicate in either of the 3 cells of the row we end up on: ``` .?.? ``` And that's it. [Answer] # Javascript regex, ~~532~~ ~~530~~ ~~481~~ 463 chars Validate rows: ``` /^((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$/ ``` Validate columns: ``` /^((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9}/ ``` Validate square from its first char: ``` /(?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)/ ``` Set preview to start of the square: ``` /^(((?=)...){3}.{18})+$/ ``` And the whole expression: ``` /^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/ ``` Matches the whole string. --- Test in Javascript ES6: ``` r = /^(?=((?=.{0,8}1)(?=.{0,8}2)(?=.{0,8}3)(?=.{0,8}4)(?=.{0,8}5)(?=.{0,8}6)(?=.{0,8}7)(?=.{0,8}8)(?=.{0,8}9).{9})+$)(?=((?=(.{9}){0,8}1)(?=(.{9}){0,8}2)(?=(.{9}){0,8}3)(?=(.{9}){0,8}4)(?=(.{9}){0,8}5)(?=(.{9}){0,8}6)(?=(.{9}){0,8}7)(?=(.{9}){0,8}8)(?=(.{9}){0,8}9).){9})(((?=.?.?(.{9}){0,2}1)(?=.?.?(.{9}){0,2}2)(?=.?.?(.{9}){0,2}3)(?=.?.?(.{9}){0,2}4)(?=.?.?(.{9}){0,2}5)(?=.?.?(.{9}){0,2}6)(?=.?.?(.{9}){0,2}7)(?=.?.?(.{9}){0,2}8)(?=.?.?(.{9}){0,2}9)...){3}.{18})+$/ ;`123456789456789123789123456231564897564897231897231564312645978645978312978312645 725893461841657392396142758473516829168429537952378146234761985687935214519284673 395412678824376591671589243156928437249735186738641925983164752412857369567293814 679543182158926473432817659567381294914265738283479561345792816896154327721638945 867539142324167859159482736275398614936241587481756923592873461743615298618924375 954217683861453729372968145516832497249675318783149256437581962695324871128796534 271459386435168927986273541518734269769821435342596178194387652657942813823615794 237541896186927345495386721743269158569178432812435679378652914924813567651794283 168279435459863271273415986821354769734692518596781342615947823387526194942138657 863459712415273869279168354526387941947615238138942576781596423354821697692734185 768593142423176859951428736184765923572389614639214587816942375295837461347651298` .split` `.every(r.test.bind(r)) && `519284673725893461841657392396142758473516829168429537952378146234761985687935214 839541267182437659367158924715692843624973518573864192298316475941285736456729381 679543182158926473432817659567381294914256738283479561345792816896154327721638945 867539142324167859159482736275398684936241517481756923592873461743615298618924375 754219683861453729372968145516832497249675318983147256437581962695324871128796534 271459386435168927986273541518734269769828435342596178194387652657942813823615794 237541896186927345378652914743269158569178432812435679495386721924813567651794283 168759432459613278273165984821594763734982516596821347615437829387246195942378651 869887283619214453457338664548525781275424668379969727517385163319223917621449519 894158578962859187461322315913849812241742157275462973384219294849882291119423759 123456789456789123564897231231564897789123456897231564312645978645978312978312645 145278369256389147364197258478512693589623471697431582712845936823956714931764825` .split` `.every(s => !r.test(s)) ``` ]
[Question] [ > > **The results are in, the contest is over.** > > The winner is [arshajii's](https://codegolf.stackexchange.com/users/6611/arshajii) [EvilBot](https://codegolf.stackexchange.com/a/23902/737) with 14 wins ahead of Neo-Bot with 13 wins and CentreBot and LastStand with 11 wins each. > > > **Scores from the final run** ``` Results: java Rifter: 9 match wins (45 total bout wins) java EvadeBot: 10 match wins (44 total bout wins) java EvilBot: 14 match wins (59 total bout wins) java LastStand: 11 match wins (43 total bout wins) java UltraBot: 9 match wins (40 total bout wins) python ReadyAimShoot.py: 8 match wins (36 total bout wins) ./SpiralBot: 0 match wins (1 total bout wins) python DodgingTurret.py: 8 match wins (43 total bout wins) ruby1.9 TroubleAndStrafe.rb: 8 match wins (41 total bout wins) ./RandomBot: 1 match wins (6 total bout wins) python StraightShooter.py: 8 match wins (41 total bout wins) python mineminemine.py: 3 match wins (14 total bout wins) ./CamperBot: 5 match wins (20 total bout wins) python3.3 CunningPlanBot.py: 3 match wins (15 total bout wins) node CentreBot.js: 11 match wins (44 total bout wins) node Neo-Bot.js: 13 match wins (59 total bout wins) python NinjaPy.py: 3 match wins (19 total bout wins) ``` This is a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge. The aim is to write a bot that will beat more of the other bots than any other. # The Game The bots will all be pitted against each other 2 at a time in a 10x10 arena with the task of reducing the opponent's energy down from 10 to 0 before its own energy is reduced to 0. Each match will consist of 5 bouts. The winner of the match is the winner of the most bouts. The total number of match wins and bout wins will be stored by the control program and will be used to determine the overall winner of the contest. The winner receives the big green tick and the adulation of the masses. Each bout will proceed in a number of rounds. At the beginning of each round the current state of the arena will be given to each bot and the bot will then respond with a command to determine what it wants to do next. Once both commands have been received by the control program both commands are executed at the same time and the arena and bot energy levels are updated to reflect the new state. If both bots still have enough energy to continue the game goes onto the next round. There will be a limit of 1000 rounds per bout to ensure no bout goes on forever, and in the event that this limit is reached the winner will be the bot with the most energy. If both bots have equal energy the bout is a draw and neither bot will get a point for the win (it would be as if they had both lost). ## The Weapons Each bot will have at its disposal a number of weapons: * Armour-piercing bullets. These travel 3 squares at a time and cause 1 energy point of damage. * Missiles. These travel 2 squares at a time and cause 3 energy points of damage at the point of impact, and 1 point of damage in all the immediately surrounding squares. * Landmines. These are dropped in one of the squares immediately surrounding the bot and cause 2 energy points of damage when stepped on, and 1 energy point of damage to anything standing in one of the immediately surrounding squares. * Electro-magnetic pulse. Causes both bots' movement circuits to malfunction for 2 turns, meaning they cannot move. They can, however, still deploy weapons (yes I know that's not realistic, but it's a game. It's not supposed to be real life). **Edit: Each EMP deployment will cost one energy point to the bot that uses it.** Bullets/missiles can only impact with bots, or walls. They will hit any bot that is in any of the squares that they travel through. They disappear once they have hit something. In all cases `immediately surrounding squares` means the 8 squares that the bot could move to on its next move - the Moore neighbourhood. ## The commands * `0` do nothing. * `N`, `NE`, `E`, `SE`, `S`, `SW`, `W`, `NW` are all direction commands and move the bot one square in the given direction. If the bot is unable to move in that direction because there is a wall or another bot in the square, the bot remains where it is. Moving into a square that already contains a bullet or missile is safe since the bullet/missile will be considered to already be on its way out of that square. * `B` followed by a space and then one of the direction commands fires an armour piercing bullet in that direction. * `M` followed by a space and then one of the direction commands fires a missile in that direction. * `L` followed by a space and then one of the direction commands drops a land mine on that square next to the bot. If the square is already occupied by a wall or a bot, the command is ignored. If a landmine is dropped onto another landmine, it detonates it. This will damage the bot doing the dropping, and any other bot within range of the original landmine. * `P` fires the EMP. Since only one command may be given per round, a bot can only move or fire/deploy a weapon, not do both at the same time. **Order of commands** The movement of either bot will always come first, and all movements will be attempted twice to account for another bot being in the way but moving out of the way. *Example* * Bot1 tries to move `E` but Bot2 is already in that square * Control program moves on to Bot2. * Bot2 tries to move `S` and succeeds because nothing is in the way. * Bot1 gets a second attempt at doing its move. This time it succeeds and Bot1 moves `E`. Once the bots have made any movements they want to make, the weapons will be fired and all projectiles (new and previously fired) will move their predefined number of squares. ## The arena At the beginning of each round the bot will receive the current state of play as the program's only command line argument: ``` X.....LLL. .......... .......... .......... M......... .......... .......... .......... .......... ...B.....Y Y 10 X 7 B 3 9 W M 0 4 S L 6 0 B 3 9 S L 7 0 L 8 0 ``` The arena comes first consisting of 10 lines of 10 characters. It is surrounded with walls which are not shown. The characters' meanings are as follows: * `.` represents an empty square * `Y` represents your bot. * `X` represents the opponent bot. * `L` represents a landmine. * `B` represents a bullet in flight. * `M` represents a missile in flight. This is followed by the remaining energy of the bots, one bot per line. Only one space will separate the bot identifier from its energy level. As in the arena, `Y` represents your bot and `X` represents your opponent. Finally comes a list of the projectiles and landmines, their positions and (if appropriate) headings, again one per line. # The control program ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define NUMBOTS 2 #define BOUTSPERMATCH 5 #define ROUNDSPERBOUT 1000 #define MAXFILENAMESIZE 100 #define MAXWEAPONS 100 #define DISPLAYBOUTS true typedef struct { int x, y, energy; char cmd[5]; } Bot; int getxmove(char cmd[5]); int getymove(char cmd[5]); int newposinbounds(int oldx, int oldy, int dx, int dy); int directhit(Bot bot, int landmine[2]); int landminecollision(int landmine1[2], int landmine2[2]); int inshrapnelrange(Bot bot, int landmine[2]); int directiontoint(char direction[5], char directions[8][3]); void deployweapons(Bot *bot, Bot *enemy, int bullets[MAXWEAPONS][3], int missiles[MAXWEAPONS][3], int landmines[MAXWEAPONS][2], char directions[8][3]); void cleararena(char arena[10][11]); int main() { FILE *fp; Bot b1, b2; int bot1, bot2, bot1bouts, bot2bouts; int bout, round, loop, totalprojectiles, dx, dy; char bots[NUMBOTS][MAXFILENAMESIZE]= { "./donowt ", "php -f huggybot.php " }; char directions[8][3]={"N", "NE", "E", "SE", "S", "SW", "W", "NW"}; char openstring[5000], argumentstring[4000], bot1string[6], bot2string[6]; int matcheswon[NUMBOTS],boutswon[NUMBOTS]; int missiles[MAXWEAPONS][3]; int bullets[MAXWEAPONS][3]; int landmines[MAXWEAPONS][2]; int paralyzedturnsremaining=0; bool bot1moved; char arena[10][11]; char projectiles[300][10]; for(loop=0;loop<NUMBOTS;loop++) { matcheswon[loop]=0; boutswon[loop]=0; } srand(time(NULL)); for(bot1=0;bot1<NUMBOTS-1;bot1++) { for(bot2=bot1+1;bot2<NUMBOTS;bot2++) { bot1bouts=bot2bouts=0; printf("%s vs %s ",bots[bot1],bots[bot2]); for(bout=0;bout<BOUTSPERMATCH;bout++) { printf("%d ",bout); //setup the arena for the bout b1.x=1;b1.y=1; b2.x=9; //b1.y=rand()%10; b2.y=rand()%10; b1.energy=b2.energy=10; //clear the previous stuff memset(missiles, -1, sizeof(missiles)); memset(bullets, -1, sizeof(bullets)); memset(landmines, -1, sizeof(landmines)); for(round=0;round<ROUNDSPERBOUT;round++) { //draw the arena based on current state cleararena(arena); totalprojectiles=0; for(loop=0;loop<MAXWEAPONS;loop++) { if(bullets[loop][0]!= -1) { arena[bullets[loop][1]][bullets[loop][0]]='B'; sprintf(projectiles[totalprojectiles], "%c %d %d %s\n", 'B', bullets[loop][0], bullets[loop][1], directions[bullets[loop][2]]); totalprojectiles+=1; } if(missiles[loop][0]!= -1) { arena[missiles[loop][1]][missiles[loop][0]]='M'; sprintf(projectiles[totalprojectiles], "%c %d %d %s\n", 'M', missiles[loop][0], missiles[loop][1], directions[missiles[loop][2]]); totalprojectiles+=1; } if(landmines[loop][0]!= -1) { arena[landmines[loop][1]][landmines[loop][0]]='L'; sprintf(projectiles[totalprojectiles], "%c %d %d\n", 'L', landmines[loop][0], landmines[loop][1]); totalprojectiles+=1; } } //send the arena to both bots to get the commands // create bot1's input arena[b1.y][b1.x]='Y'; arena[b2.y][b2.x]='X'; sprintf(bot1string, "Y %d\n", b1.energy); sprintf(bot2string, "X %d\n", b2.energy); strcpy(argumentstring, "'"); strncat(argumentstring, *arena, 10*11); strcat(argumentstring, bot1string); strcat(argumentstring, bot2string); for(loop=0;loop<totalprojectiles;loop++) { strcat(argumentstring, projectiles[loop]); } strcat(argumentstring, "'"); sprintf(openstring, "%s %s", bots[bot1], argumentstring); // send it and get the command back fp=popen(openstring, "r"); fgets(b1.cmd, 5, fp); fflush(NULL); pclose(fp); // create bot2's input arena[b2.y][b2.x]='Y'; arena[b1.y][b1.x]='X'; sprintf(bot2string, "Y %d\n", b2.energy); sprintf(bot1string, "X %d\n", b1.energy); strcpy(argumentstring, "'"); strncat(argumentstring, *arena, 10*11); strcat(argumentstring, bot2string); strcat(argumentstring, bot1string); for(loop=0;loop<totalprojectiles;loop++) { strcat(argumentstring, projectiles[loop]); } strcat(argumentstring, "'"); sprintf(openstring, "%s %s", bots[bot2], argumentstring); // send it and get the command back fp=popen(openstring, "r"); fgets(b2.cmd, 5, fp); fflush(NULL); pclose(fp); if(DISPLAYBOUTS) { arena[b1.y][b1.x]='A'; arena[b2.y][b2.x]='B'; printf("\033c"); printf("Round: %d\n", round); printf("%s", arena); sprintf(bot1string, "A %d\n", b1.energy); sprintf(bot2string, "B %d\n", b2.energy); printf("%s%s", bot1string, bot2string); } //do bot movement phase if(paralyzedturnsremaining==0) { // move bot 1 first bot1moved=false; dx=dy=0; dx=getxmove(b1.cmd); dy=getymove(b1.cmd); if(newposinbounds(b1.x, b1.y, dx, dy)) { if(!(b1.x+dx==b2.x) || !(b1.y+dy==b2.y)) { bot1moved=true; b1.x=b1.x+dx; b1.y=b1.y+dy; } } // move bot 2 next dx=dy=0; dx=getxmove(b2.cmd); dy=getymove(b2.cmd); if(newposinbounds(b2.x, b2.y, dx, dy)) { if(!(b2.x+dx==b1.x) || !(b2.y+dy==b1.y)) { b2.x=b2.x+dx; b2.y=b2.y+dy; } } if(!bot1moved) // if bot2 was in the way first time, try again { dx=dy=0; dx=getxmove(b1.cmd); dy=getymove(b1.cmd); if(newposinbounds(b1.x, b1.y, dx, dy)) { if(!(b1.x+dx==b2.x) || !(b1.y+dy==b2.y)) { b1.x=b1.x+dx; b1.y=b1.y+dy; } } } //check for landmine hits for(loop=0;loop<MAXWEAPONS;loop++) { if(landmines[loop][0]!= -1) { if(directhit(b1, landmines[loop])) { b1.energy-=2; if(inshrapnelrange(b2, landmines[loop])) { b2.energy-=1; } landmines[loop][0]= -1; landmines[loop][1]= -1; } if(directhit(b2, landmines[loop])) { b2.energy-=2; if(inshrapnelrange(b1, landmines[loop])) { b1.energy-=1; } landmines[loop][0]= -1; landmines[loop][1]= -1; } } } } else { paralyzedturnsremaining-=1; } //do weapons firing phase if(strcmp(b1.cmd, "P")==0) { paralyzedturnsremaining=2; b1.energy--; } else if(strcmp(b2.cmd, "P")==0) { paralyzedturnsremaining=2; b2.energy--; } deployweapons(&b1, &b2, bullets, missiles, landmines, directions); deployweapons(&b2, &b1, bullets, missiles, landmines, directions); //do weapons movement phase int moves; for(loop=0;loop<MAXWEAPONS;loop++) { dx=dy=0; if(bullets[loop][0]!= -1) { dx=getxmove(directions[bullets[loop][2]]); dy=getymove(directions[bullets[loop][2]]); for(moves=0;moves<3;moves++) { if(newposinbounds(bullets[loop][0], bullets[loop][1], dx, dy)) { bullets[loop][0]+=dx; bullets[loop][1]+=dy; if(directhit(b1, bullets[loop])) { b1.energy-=1; bullets[loop][0]= -1; bullets[loop][1]= -1; bullets[loop][2]= -1; } if(directhit(b2, bullets[loop])) { b2.energy-=1; bullets[loop][0]= -1; bullets[loop][1]= -1; bullets[loop][2]= -1; } } else { bullets[loop][0]= -1; bullets[loop][1]= -1; bullets[loop][2]= -1; dx=dy=0; } } } }; for(loop=0;loop<MAXWEAPONS;loop++) { dx=dy=0; if(missiles[loop][0]!= -1) { dx=getxmove(directions[missiles[loop][2]]); dy=getymove(directions[missiles[loop][2]]); for(moves=0;moves<2;moves++) { if(newposinbounds(missiles[loop][0], missiles[loop][1], dx, dy)) { missiles[loop][0]+=dx; missiles[loop][1]+=dy; if(directhit(b1, missiles[loop])) { b1.energy-=3; if(inshrapnelrange(b2, missiles[loop])) { b2.energy-=1; } missiles[loop][0]= -1; missiles[loop][1]= -1; missiles[loop][2]= -1; } if(directhit(b2, missiles[loop])) { b2.energy-=3; if(inshrapnelrange(b1, missiles[loop])) { b1.energy-=1; } missiles[loop][0]= -1; missiles[loop][1]= -1; missiles[loop][2]= -1; } } else { if(inshrapnelrange(b1, missiles[loop])) { b1.energy-=1; } if(inshrapnelrange(b2, missiles[loop])) { b2.energy-=1; } missiles[loop][0]= -1; missiles[loop][1]= -1; missiles[loop][2]= -1; dx=dy=0; } } } } //check if there's a winner if(b1.energy<1 || b2.energy<1) { round=ROUNDSPERBOUT; } } // who has won the bout if(b1.energy<b2.energy) { bot2bouts+=1; boutswon[bot2]+=1; } else if(b2.energy<b1.energy) { bot1bouts+=1; boutswon[bot1]+=1; } } if(bot1bouts>bot2bouts) { matcheswon[bot1]+=1; } else if(bot2bouts>bot1bouts) { matcheswon[bot2]+=1; } printf("\n"); } } // output final scores printf("\nResults:\n"); printf("Bot\t\t\tMatches\tBouts\n"); for(loop=0;loop<NUMBOTS;loop++) { printf("%s\t%d\t%d\n", bots[loop], matcheswon[loop], boutswon[loop]); } } int getxmove(char cmd[5]) { int dx=0; if(strcmp(cmd, "NE")==0) dx= 1; else if(strcmp(cmd, "E")==0) dx= 1; else if(strcmp(cmd, "SE")==0) dx= 1; else if(strcmp(cmd, "SW")==0) dx= -1; else if(strcmp(cmd, "W")==0) dx= -1; else if(strcmp(cmd, "NW")==0) dx= -1; return dx; } int getymove(char cmd[5]) { int dy=0; if(strcmp(cmd, "N")==0) dy= -1; else if(strcmp(cmd, "NE")==0) dy= -1; else if(strcmp(cmd, "SE")==0) dy= 1; else if(strcmp(cmd, "S")==0) dy= 1; else if(strcmp(cmd, "SW")==0) dy= 1; else if(strcmp(cmd, "NW")==0) dy= -1; return dy; } int newposinbounds(int oldx, int oldy, int dx, int dy) { return (oldx+dx>=0 && oldx+dx<10 && oldy+dy>=0 && oldy+dy<10); } int directhit(Bot bot, int landmine[2]) { return (bot.x==landmine[0] && bot.y==landmine[1]); } int landminecollision(int landmine1[2], int landmine2[2]) { return ((landmine1[1]==landmine2[1]) && abs(landmine1[0]==landmine2[0])); } int inshrapnelrange(Bot bot, int landmine[2]) { return (abs(bot.x-landmine[0])<2 && abs(bot.y-landmine[1])<2); } int directiontoint(char direction[5], char directions[8][3]) { int loop,returnval=8; for(loop=0;loop<8;loop++) { if(strcmp(directions[loop], direction)==0) returnval=loop; } return returnval; } void deployweapons(Bot *bot, Bot *enemy, int bullets[MAXWEAPONS][3], int missiles[MAXWEAPONS][3], int landmines[MAXWEAPONS][2], char directions[8][3]) { int loop; if(strlen(bot->cmd)>2) { if(bot->cmd[0]=='B') { int weaponslot=0; while(bullets[weaponslot][0]!= -1) weaponslot+=1; bullets[weaponslot][0]=bot->x; bullets[weaponslot][1]=bot->y; bullets[weaponslot][2]=directiontoint(bot->cmd+2, directions); if(bullets[weaponslot][2]>7) { // direction wasn't recognized so clear the weapon bullets[weaponslot][0]= -1; bullets[weaponslot][1]= -1; bullets[weaponslot][2]= -1; } } if(bot->cmd[0]=='M') { int weaponslot=0; while(missiles[weaponslot][0]!= -1) weaponslot+=1; missiles[weaponslot][0]=bot->x; missiles[weaponslot][1]=bot->y; missiles[weaponslot][2]=directiontoint(bot->cmd+2, directions); if(missiles[weaponslot][2]>7) { // direction wasn't recognized so clear the weapon missiles[weaponslot][0]= -1; missiles[weaponslot][1]= -1; missiles[weaponslot][2]= -1; } } if(bot->cmd[0]=='L') { int weaponslot=0; while(landmines[weaponslot][0]!= -1) weaponslot+=1; if(newposinbounds(bot->x, bot->y, getxmove(bot->cmd+2), getymove(bot->cmd+2))) { landmines[weaponslot][0]=bot->x+getxmove(bot->cmd+2); landmines[weaponslot][1]=bot->y+getymove(bot->cmd+2); //check for landmine hits for(loop=0;loop<MAXWEAPONS;loop++) { if(landmines[loop][0]!= -1) { if(landminecollision(landmines[weaponslot], landmines[loop]) && weaponslot!=loop) { if(inshrapnelrange(*bot, landmines[loop])) { bot->energy-=1; } if(inshrapnelrange(*enemy, landmines[loop])) { enemy->energy-=1; } landmines[loop][0]= -1; landmines[loop][1]= -1; landmines[weaponslot][0]= -1; landmines[weaponslot][1]= -1; } } } } } } } void cleararena(char arena[10][11]) { int loop; memset(arena, '.', 110); for(loop=0;loop<10;loop++) { arena[loop][10]='\n'; } } ``` The control program will call your bot from the command line. For this reason, **programs which cannot be called from the command line will be considered invalid**. I apologise to those whose language of choice doesn't work that way, but doing each match manually would be impractical. [intx13](https://codegolf.stackexchange.com/users/18280/intx13) has kindly written a more robust version of the control program with some bugfixes which you can find [here](https://github.com/gazrogers/CodegolfBattlebotsScorer/blob/master/scorernew.c). Suggestions for improvements or bug-fixes to the control program are welcome. # Test bots *None* of the test bots will be included in the scoring runs. They're just for testing purposes. **Dudley DoNowt (C)** ``` int main(int argc, char *argv) { printf("0"); } ``` Does nothing regardless of the situation. Not expected to win much. **HuggyBot (PHP)** ``` <?php $arena=$argv[1]; list($meX, $meY)=findMe($arena); list($oppX, $oppY)=findOpp($arena); if($meY<$oppY) { if($meX<$oppX) echo "SE"; elseif($meX==$oppX) echo "S"; else echo "SW"; } elseif($meY==$oppY) { if($meX<$oppX) echo "E"; else echo "W"; } else { if($meX<$oppX) echo "NE"; elseif($meX==$oppX) echo "N"; else echo "NW"; } function findMe($arena) { return find("Y", explode("\n", $arena)); } function findOpp($arena) { return find("X", explode("\n", $arena)); } function find($char, $array) { $x=0; $y=0; for($loop=0;$loop<10;$loop++) { if(strpos($array[$loop], $char)!==FALSE) { $x=strpos($array[$loop], $char); $y=$loop; } } return array($x, $y); } ?> ``` Tries to get right next to the opponent. Vulnerable to landmines since it doesn't look for them. Makes firing missiles a less effective tactic for the opponent when it achieves its goal. # The results The final scoring run will be done after **23:59 on the 24th March 2014**. I will run test runs regularly so that entrants can see how their bots are stacking up against the current opposition. # Entries Entries should include your bot's source, and the command line argument I'll need to use to run it. You're welcome to post as many different entries as you like, but each answer should contain **only one** bot. # Important It seems that some entries want to write to disk to retain some state between runs. These are new rules regarding writing to disk. * You may modify the source of your own bot. Modifying any other bot is cheating and will result in the offending bot being disqualified. * You may write to a file created for the purpose of storing state. This file must be stored in a subdirectory of the directory where your bot is located. The subdirectory will be named `state`. Writing to any other part of the filesystem (other than your own source) is disallowed. [Answer] ## Rifter This bot takes different actions based on what bot it's fighting. To determine the opponent, it flips its own state and feeds it into the other bots to see what they would do, and compares that to what they actually do. Once they hit a threshold of 'correct' moves, it stops testing the others. Once it knows what bot it's fighting, it *generally* knows where it will be on the next turn, so it can fire *there* instead of their current position. Of course, there are some drawbacks. One is that bots that have "random" activity aren't detected so well. This is balanced by using the King's Last Stand logic when the opponent isn't known. However, if a bot is purely deterministic, this has *no* trouble figuring out who it is. It can then be easily adapted to the situation by adding more cases into its logic for each opponent. For example, fighting Last Stand, it will corner him, stand 2x1 away so that the he can't move or fire directly, and shoot missiles into the wall behind, killing it with splash damage. Like my others, it extends BattleBot.java: ``` import java.awt.Point; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Rifter extends BattleBot{ String output="0"; String state; String oldState = null; List<Rift> rifts; Rift chosen; List<Point> safe; Point probable; int round; final int testCount = 100; Rifter(String[] args) { super(args.length>0?args:testState); state = args.length>0?args[0]:testState[0]; round = 0; } public static void main(String[] args) { debug = false; System.out.print(new Rifter(args).execute()); } @Override String execute() { if(!valid) return "0"; init(); probable = getLikelyPosition(); if(!safe.contains(yPosition) && evade()) return output; if(riftShift()) return output; return fallback(); } boolean riftShift(){ if(chosen==null) return false; if("P".equals(chosen.nextAction)) return fireAt(xPosition, true); switch(getChosenIndex()){ case 1: output = fightStand(); break; case 2: output = fightEvil(); break; default: output = fallback(); } return output.equals("0")?false:true; } int getChosenIndex(){ for(int i=0;i<baseBots.length;i++) if(chosen.bot.equals(baseBots[i])) return i; return -1; } int distanceToWall(Point pos){ int min = Math.min(pos.x, pos.y); min = Math.min(min, (arenaSize - 1) - pos.x); return Math.min(min, (arenaSize - 1) - pos.y); } String fightStand(){ int wall = distanceToWall(xPosition); if(wall > 0 || distance(yPosition, probable) > 2){ if(moveToward(probable, NONE)) return output; if(fireAt(probable, false)) return output; } if(probable.x==0 && probable.y==0) return "M NW"; if(probable.x==arenaSize-1 && probable.y==0) return "M NE"; if(probable.x==arenaSize-1 && probable.y == arenaSize-1) return "M SE"; if(probable.x==0 && probable.y == arenaSize-1) return "M SW"; if(probable.x==0) return "M W"; if(probable.x==arenaSize-1) return "M E"; if(probable.y==0) return "M N"; if(probable.y==arenaSize-1) return "M S"; return "M " + headings[headingToPoint(probable)]; } String fightEvil(){ if(areAligned(yPosition,xPosition)){ if(distance(yPosition,xPosition)>3) if(moveToward(probable,UNALIGN)) return output; if(fireAt(probable, false)) return output; } if(fireAt(probable, false)) return output; if(moveToward(center, ALIGN)) return output; return "0"; } String fallback(){ output = getOutputFrom(fallbackBots[rand.nextInt(fallbackBots.length)]); if(output==null) output="0"; return output; } int NONE = 0; int ALIGN = 1; int UNALIGN = 2; boolean moveToward(Point target, int align){ Point closest = new Point(-99,-99); for(Point pos : safe){ if(pos.equals(yPosition)) continue; if(distance(pos,target) < distance(closest,target)){ if(areAligned(pos,target) && align == UNALIGN) continue; if(!areAligned(pos,target) && align == ALIGN) continue; closest = pos; } } if(isOutside(closest)) for(Point pos : safe) if(distance(pos,target) < distance(closest,target)) closest = pos; if(distance(closest,target) > distance(yPosition,target)) return false; output = headings[headingToPoint(closest)]; return true; } boolean fireAt(Point target, boolean override){ if(!override && !areAligned(yPosition, target)) return false; int dist = distance(yPosition, target); if(!override && dist>3) return false; int heading = headingToPoint(target); output = "M "; if(dist > 3 || dist == 1) output = "B "; output += headings[heading]; return true; } String getOutputFrom(String bot){ return new Rift(bot,0).foretell(state); } boolean evade(){ if(safe.isEmpty()) return false; Point dest = null; for(Point pos : safe) if(areAligned(pos,probable)) dest = pos; if(dest==null){ output = getOutputFrom("java LastStand"); return true; } output = headings[headingToPoint(dest)]; return true; } Point getLikelyPosition(){ if(chosen!=null) return chosen.getNextPosition(null); if(round > testCount) return xPosition; int[] arena = new int[arenaSize*arenaSize]; for(Rift rift : rifts){ Point next = rift.getNextPosition(null); if(!isOutside(next)) arena[next.y*arenaSize+next.x]++; } int max = 0, index = -1; for(int i=0;i<arena.length;i++){ if(arena[i] > max){ max = arena[i]; index = i; } } Point dest = new Point(index%arenaSize, index/arenaSize); return isOutside(dest)?xPosition:dest; } boolean areAligned(Point a, Point b){ int x = Math.abs(a.x - b.x); int y = Math.abs(a.y - b.y); if(x==0 || y==0 || x==y) return true; return false; } void init(){ safe = new ArrayList<Point>(); if(spotCollision(yPosition)==null) safe.add(yPosition); for(int heading=0;heading<8;heading++){ Point pos = nextPosition(heading, yPosition); if(isOutside(pos)) continue; if(spotCollision(pos)==null) safe.add(pos); } loadBots(readState()); updateRifts(); writeState(); } void updateRifts(){ if(chosen == null && round < testCount) for(Rift rift : rifts) if(rift.validate(oldState)) rift.correct++; } Rift chooseBot(){ double avg = 0.0; int highest = 0; Rift choice = null; for(Rift rift : rifts){ avg += rift.correct; if(rift.correct >= highest){ highest = rift.correct; choice = rift; } } avg /= rifts.size(); if(choice!= null && (choice.correct > 8) && choice.correct > avg*2) return choice; else return null; } boolean writeState(){ File dir = new File("state"); dir.mkdirs(); File file = new File("state/rifter.state"); try { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(">" + round + "\n"); for(Rift rift : rifts) writer.write(":" + rift.correct + "|" + rift.bot + "\n"); writer.write(state); writer.flush(); writer.close(); } catch (IOException e) { log(e.getMessage()); return false; } return true; } List<String> readState(){ List<String> bots = new ArrayList<String>(); File file = new File("state/rifter.state"); if(file.exists()){ try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line; String oldState = ""; line = reader.readLine(); if(line != null && line.startsWith(">")) round = Integer.valueOf(line.substring(1)) + 1; while((line = reader.readLine()) != null){ if(line.startsWith(":")) bots.add(line.substring(1)); else oldState += line + "\n"; } reader.close(); BattleBot bot = new Rifter(new String[]{oldState}); if(isStateInvalid(bot)){ bots.clear(); oldState = ""; round = 0; } this.oldState = oldState; } catch(Exception e){ log(e.getMessage()); bots.clear(); this.oldState = ""; } } return bots.isEmpty()?Arrays.asList(baseBots):bots; } boolean isStateInvalid(BattleBot bot){ if(!bot.valid) return true; if(distance(bot.xPosition, xPosition) > 1) return true; if(distance(bot.yPosition, yPosition) > 1) return true; if(xEnergy > bot.xEnergy || yEnergy > bot.yEnergy) return true; return false; } List<Rift> loadBots(List<String> bots){ rifts = new ArrayList<Rift>(); String flipped = flipState(state); for(String bot : bots){ String[] tokens = bot.split("\\|"); Rift rift; if(tokens.length < 2) rift = new Rift(bot, 0); else rift = new Rift(tokens[1], Integer.valueOf(tokens[0])); rifts.add(rift); } if((chosen = chooseBot()) == null) if(round < testCount) for(Rift rift : rifts) rift.nextAction = rift.foretell(flipped); else chosen.nextAction = chosen.foretell(flipped); return rifts; } String flipState(String in){ String tmp = in.replaceAll("X", "Q"); tmp = tmp.replaceAll("Y", "X"); tmp = tmp.replaceAll("Q", "Y"); String[] lines = tmp.split("\\r?\\n"); tmp = lines[arenaSize]; lines[arenaSize] = lines[arenaSize+1]; lines[arenaSize+1] = tmp; String out = ""; for(int i=0;i<lines.length;i++) out += lines[i] + "\n"; return out.trim(); } class Rift{ String bot; String nextAction; String state; String nextState; int correct; Rift(String name, int count){ bot = name; correct = count; } Point getNextPosition(String action){ if(action==null) action = nextAction; if(action==null || action.length()<1) return xPosition; int heading = getHeading(action.split(" ")[0]); return nextPosition(heading, xPosition); } boolean validate(String oldState){ boolean valid = true; if(oldState == null) return valid; if(oldState.split("\\r?\\n").length < 12) return valid; String action = foretell(flipState(oldState)); if(action==null || action.length() < 1){ log(this.bot + " : " + "invalid action"); return valid; } BattleBot bot = new Rifter(new String[]{oldState}); switch(action.charAt(0)){ case 'B': case 'M': case 'L': valid = testShot(action, bot); break; case 'P': case '0': valid = testNothing(bot); break; default: valid = testMovement(action, bot); break; } log(this.bot + " : " + action + " : " + valid); return valid; } boolean testNothing(BattleBot bot){ if(!xPosition.equals(bot.xPosition)) return false; for(Weapon weapon : weapons){ int dist = weapon.type==LANDMINE?1:weapon.speed; log(dist); if(distance(weapon.position, bot.xPosition) != dist) continue; int dir = weapon.heading; if(isHeadingExact(dir,bot.xPosition,weapon.position)) return false; } return true; } boolean testShot(String act, BattleBot bot){ if(!xPosition.equals(bot.xPosition)) return false; if(weapons == null) return false; String[] tokens = act.split(" "); char which = tokens[0].charAt(0); int type = which=='B'?BULLET: which=='M'?MISSILE: LANDMINE; for(Weapon weapon : weapons){ if(weapon.type != type) continue; int dist = weapon.type==LANDMINE?1:weapon.speed; log(dist); if(distance(weapon.position, bot.xPosition) != dist) continue; int dir; if(act==null) dir = weapon.heading; else if(tokens.length < 2) return false; else dir = getHeading(tokens[1]); if(isHeadingExact(dir,bot.xPosition,weapon.position)) return true; } return false; } boolean testMovement(String act, BattleBot bot){ return xPosition.equals(nextPosition(getHeading(act), bot.xPosition)); } String foretell(String state){ this.state = state; String[] cmdRaw = bot.split(" "); String[] cmd = new String[cmdRaw.length+1]; for(int i=0;i<cmdRaw.length;i++) cmd[i] = cmdRaw[i]; cmd[cmd.length-1]=state; String out = null; try { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; while((line = err.readLine()) != null){ out = line; } err.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); while((line = reader.readLine()) != null){ out = line; } reader.close(); } catch (Exception e) { log(e.getMessage()); } return out!=null&&out.length()<6&&out.length()>0?out:null; } } String fallbackBots[] = {"node Neo-Bot.js"}; String[] baseBots = { "java EvadeBot", "java LastStand", "java EvilBot", "python ReadyAimShoot.py", "python DodgingTurret.py", "python mineminemine.py", "python StraightShooter.py", "./RandomBot", "./SpiralBot", "ruby1.9 TroubleAndStrafe.rb", "python3 CunningPlanBot.py", "./CamperBot", "node CentreBot.js", "node Neo-Bot.js", "java UltraBot", "python NinjaPy.py" }; static String[] testState = {".X....LLL.\n..........\n.M........\n..........\nM.........\n..........\n..........\n..........\n.Y........\n...B......\nY 10\nX 7\nM 1 2 S"}; } ``` [Answer] # EvilBot **a bot that tries to be as evil as possible** Well here's what I've got: a Java bot that tries to get as close to the opponent a circular strip of radius 2.5 around the center of the arena as possible and then do as much damage as it can when it can. Its movement pattern is based on assigning a "danger" value to each of its neighboring squares, and deciding to move based on these values *and* based on a tendency to be as close to a circular region of radius 2.5 about the center of the arena. I used some of the nuts and bolts from @Geobits's answer (e.g. having an abstract `BattleBot` class and the parsing technique), so thanks! I'm probably going to modify/expand what I have so far, although it does fare quite well as is with the other bots posted so far. The code is below. (if anyone else is using Java, feel free to use my abstract/helper classes.) (`EvilBot.java`) ``` import java.io.File; // debugging import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; // debugging class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } public int distTo(Point other) { return Math.max(Math.abs(x - other.x), Math.abs(y - other.y)); } public double conventionalDistTo(Point other) { return Math.hypot(x - other.x, y - other.y); } @Override public boolean equals(Object other) { if (!(other instanceof Point)) return false; Point otherPoint = (Point) other; return x == otherPoint.x && y == otherPoint.y; } @Override public int hashCode() { return x * (1 << Arena.ARENA_SIZE) + y; } @Override public String toString() { return "(" + x + "," + y + ")"; } } interface ArenaElement { char getSymbol(); } enum Projectile implements ArenaElement { BULLET('B', 3, 1) { }, MISSILE('M', 2, 3) { }, LANDMINE('L', 0, 2) { @Override public int timeUntilImpact(Point current, Point target, Direction dir) { return current.equals(target) ? 0 : -1; } }; private final char symbol; private final int speed; private final int damage; private Projectile(char symbol, int speed, int damage) { this.symbol = symbol; this.speed = speed; this.damage = damage; } @Override public char getSymbol() { return symbol; } public int getSpeed() { return speed; } public int getDamage() { return damage; } public static Projectile fromSymbol(char symbol) { for (Projectile p : values()) { if (p.getSymbol() == symbol) return p; } return null; } public int timeUntilImpact(Point current, Point target, Direction dir) { final int dx = target.getX() - current.getX(); final int dy = target.getY() - current.getY(); if (!(dx == 0 || dy == 0 || dx == dy || dx == -dy)) return -1; if (dx == 0) { if (dy > 0 && dir != Direction.N) return -1; if (dy < 0 && dir != Direction.S) return -1; } if (dy == 0) { if (dx > 0 && dir != Direction.E) return -1; if (dx < 0 && dir != Direction.W) return -1; } if (dx == dy) { if (dx > 0 && dir != Direction.NE) return -1; if (dx < 0 && dir != Direction.SW) return -1; } if (dx == -dy) { if (dx > 0 && dir != Direction.SE) return -1; if (dx < 0 && dir != Direction.NW) return -1; } int dist = target.distTo(current); return (dist / speed) + (dist % speed == 0 ? 0 : 1); } } enum BotType implements ArenaElement { ME('Y'), ENEMY('X'); private final char symbol; private BotType(char symbol) { this.symbol = symbol; } @Override public char getSymbol() { return symbol; } public static BotType fromSymbol(char symbol) { for (BotType bt : values()) { if (bt.getSymbol() == symbol) return bt; } return null; } } enum EmptySpot implements ArenaElement { EMPTY; @Override public char getSymbol() { return '.'; } public static EmptySpot fromSymbol(char symbol) { for (EmptySpot es : values()) { if (es.getSymbol() == symbol) return es; } return null; } } enum Direction { N, NE, E, SE, S, SW, W, NW } class Arena { public static final int ARENA_SIZE = 10; public static final Point center = new Point(ARENA_SIZE / 2, ARENA_SIZE / 2); private ArenaElement[][] arena; private Arena(boolean fill) { arena = new ArenaElement[ARENA_SIZE][ARENA_SIZE]; if (!fill) return; for (int i = 0; i < ARENA_SIZE; i++) { for (int j = 0; j < ARENA_SIZE; j++) { arena[i][j] = EmptySpot.EMPTY; } } } public boolean inBounds(int x, int y) { return x >= 0 && x < ARENA_SIZE && y >= 0 && y < ARENA_SIZE; } public boolean inBounds(Point p) { final int x = p.getX(), y = p.getY(); return inBounds(x, y); } public ArenaElement get(int x, int y) { if (!inBounds(x, y)) { return null; // be cautious of this } return arena[ARENA_SIZE - 1 - y][x]; } public ArenaElement get(Point p) { return get(p.getX(), p.getY()); } // note: a point is considered its own neighbor public List<Point> neighbors(Point p) { List<Point> neighbors = new ArrayList<Point>(9); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { Point p1 = new Point(p.getX() + i, p.getY() + j); if (get(p1) != null) neighbors.add(p1); } } return neighbors; } public Point findMe() { for (int i = 0; i < ARENA_SIZE; i++) { for (int j = 0; j < ARENA_SIZE; j++) { if (get(i, j) == BotType.ME) return new Point(i, j); } } return null; } public Point findEnemy() { for (int i = 0; i < ARENA_SIZE; i++) { for (int j = 0; j < ARENA_SIZE; j++) { if (get(i, j) == BotType.ENEMY) return new Point(i, j); } } return null; } public Point impactOfRayFromPointInDirection(Point p, Direction dir) { int x = p.getX(), y = p.getY(); switch (dir) { case N: y += (Arena.ARENA_SIZE - 1 - y); break; case NE: { int dx = (Arena.ARENA_SIZE - 1 - x); int dy = (Arena.ARENA_SIZE - 1 - y); int off = Math.max(dx, dy); x += off; y += off; break; } case E: x += (Arena.ARENA_SIZE - 1 - x); break; case SE: { int dx = (Arena.ARENA_SIZE - 1 - x); int dy = y; int off = Math.max(dx, dy); x += off; y -= off; break; } case S: y = 0; break; case SW: { int dx = x; int dy = y; int off = Math.max(dx, dy); x -= off; y -= off; break; } case W: x = 0; break; case NW: { int dx = x; int dy = (Arena.ARENA_SIZE - 1 - y); int off = Math.max(dx, dy); x -= off; y += off; break; } } return new Point(x, y); } private static ArenaElement fromSymbol(char symbol) { ArenaElement e = EmptySpot.fromSymbol(symbol); if (e != null) return e; e = Projectile.fromSymbol(symbol); if (e != null) return e; return BotType.fromSymbol(symbol); } public static Arena parse(String[] input) { Arena arena = new Arena(false); for (int i = 0; i < ARENA_SIZE; i++) { for (int j = 0; j < ARENA_SIZE; j++) { char symbol = input[i].charAt(j); arena.arena[i][j] = fromSymbol(symbol); } } return arena; } } abstract class BaseBot { protected static class ProjectileInfo { Projectile projectile; Point position; Direction direction; @Override public String toString() { return projectile.toString() + " " + position + " " + direction; } } protected Arena arena; protected Point myPos; protected int energy; protected Point enemyPos; protected int enemyEnergy; public List<ProjectileInfo> projectiles; public BaseBot(String[] args) { if (args.length < 1) return; String[] lines = args[0].split("\r?\n"); projectiles = new ArrayList<ProjectileInfo>(lines.length - Arena.ARENA_SIZE - 2); arena = Arena.parse(lines); myPos = arena.findMe(); enemyPos = arena.findEnemy(); for (int i = Arena.ARENA_SIZE; i < lines.length; i++) { parseInputLine(lines[i]); } } private void parseInputLine(String line) { String[] split = line.split(" "); char c0 = line.charAt(0); if (c0 == 'Y') { energy = Integer.parseInt(split[1]); } else if (c0 == 'X') { enemyEnergy = Integer.parseInt(split[1]); } else { ProjectileInfo pinfo = new ProjectileInfo(); pinfo.projectile = Projectile.fromSymbol(split[0].charAt(0)); pinfo.position = new Point(Integer.parseInt(split[1]), Arena.ARENA_SIZE - 1 - Integer.parseInt(split[2])); if (split.length > 3) pinfo.direction = Direction.valueOf(split[3]); projectiles.add(pinfo); } } abstract String getMove(); } public class EvilBot extends BaseBot { public static final boolean DEBUG = false; public static void main(String... args) throws Exception { if (DEBUG) { StringBuffer input = new StringBuffer(); Scanner scan = new Scanner(new File("a.txt")); while (scan.hasNextLine()) { input.append(scan.nextLine()); input.append('\n'); } scan.close(); args = new String[] { input.toString() }; } System.out.print(new EvilBot(args).getMove()); } public EvilBot(String[] args) { super(args); } /* * Direction to p if perfectly aligned, null otherwise */ private Direction getDirTo(Point p) { final int dx = p.getX() - myPos.getX(); final int dy = p.getY() - myPos.getY(); if (dx == 0) { return (dy > 0) ? Direction.N : Direction.S; } if (dy == 0) { return (dx > 0) ? Direction.E : Direction.W; } if (dx == dy) { return (dy > 0) ? Direction.NE : Direction.SW; } if (dx == -dy) { return (dy > 0) ? Direction.NW : Direction.SE; } return null; } /* * Direction towards p (best approximation) */ private Direction getDirTowards(Point p) { Direction minDir = null; double minDist = 0; for (Direction dir : Direction.values()) { double dist = arena.impactOfRayFromPointInDirection(myPos, dir) .conventionalDistTo(p); if (minDir == null || dist < minDist) { minDir = dir; minDist = dist; } } return minDir; } private boolean isEnemyCloseToWall() { return (enemyPos.getX() < 2 || enemyPos.getY() < 2 || enemyPos.getX() > Arena.ARENA_SIZE - 3 || enemyPos.getY() > Arena.ARENA_SIZE - 3); } private String missileAttack() { return "M " + getDirTowards(enemyPos); } @Override public String getMove() { List<Point> neighbors = arena.neighbors(myPos); Map<Point, Double> dangerFactors = new HashMap<Point, Double>(); for (Point neighbor : neighbors) { double dangerFactor = 0; if (arena.get(neighbor) == Projectile.LANDMINE) { dangerFactor += 2; } for (ProjectileInfo pi : projectiles) { int time = pi.projectile.timeUntilImpact(pi.position, neighbor, pi.direction); if (time > 0) { dangerFactor += ((double) pi.projectile.getDamage()) / time; } } dangerFactors.put(neighbor, dangerFactor); } if (dangerFactors.get(myPos) == 0) { // we are safe for now... Direction dir = getDirTo(enemyPos); boolean closeToWall = isEnemyCloseToWall(); if (dir != null) { int dist = myPos.distTo(enemyPos); if (dist < Projectile.MISSILE.getSpeed() * 2) { return "M " + dir; } else { return "B " + dir; } } else if (closeToWall) { if (Math.random() > 0.5) // so we don't get caught in loops return missileAttack(); } } // move! double leastDanger = Double.POSITIVE_INFINITY; for (Entry<Point, Double> entry : dangerFactors.entrySet()) { if (entry.getValue() < leastDanger) leastDanger = entry.getValue(); } Point moveTo = null; for (Entry<Point, Double> entry : dangerFactors.entrySet()) { if (entry.getKey().equals(myPos)) continue; if (entry.getValue() == leastDanger) { double d1 = entry.getKey().conventionalDistTo(Arena.center); double d2 = moveTo == null ? 0 : moveTo .conventionalDistTo(Arena.center); if (moveTo == null || Math.abs(d1 - 2.5) < Math.abs(d2 - 2.5)) { moveTo = entry.getKey(); } } } if (moveTo == null) { return missileAttack(); } return getDirTo(moveTo).toString(); } } ``` Usage: ``` javac EvilBot.java java EvilBot <input> ``` --- **Notes:** * Currently, land mines are not being used, only dodged. I'm probably not going to change this, since using land mines appears to do more harm than good (at least for EvilBot) judging by a few tests I ran. * Currently, EMP is not being used. I tried the strategy of aligning with the opponent and firing the EMP followed by missiles, but there are a few counter-strategies to this that would win almost 100% of the time, so I decided to abandon that route. I might explore using the EMP in different ways later on. [Answer] ### ReadyAimShoot **a [R](http://cran.r-project.org/) Bot** ``` input <- strsplit(commandArgs(TRUE),split="\\\\n")[[1]] arena <- do.call(rbind,strsplit(input[1:10],"")) #Parse arena life <- as.integer(strsplit(input[11:12]," ")[[1]][2]) #Parse stats stuff <- strsplit(input[13:length(input)]," ") #Parse elements if(length(input)>12){ #What are they stuff <- strsplit(input[13:length(input)]," ") whatstuff <- sapply(stuff,`[`,1) }else{whatstuff<-""} if(sum(whatstuff=="L")>1){ #Where are the mines mines <- t(apply(do.call(rbind,stuff[whatstuff=="L"])[,3:2],1,as.integer))+1 }else if(sum(whatstuff=="L")==1){ mines <- as.integer(stuff[whatstuff=="L"][[1]][3:2])+1 }else{mines <- c()} me <- which(arena=="Y",arr.ind=T) #Where am I other <- which(arena=="X",arr.ind=T) #Where is the target direction <- other-me #Direction of the other bot in term of indices if(length(mines)>2){ #Direction of mines in term of indices dirmines <- mines-matrix(rep(me,nrow(mines)),nc=2,byrow=T) }else if(length(mines)==1){ dirmines <- mines-me }else{dirmines<-c()} file <- normalizePath(gsub("^--file=","",grep("^--file=",commandArgs(FALSE),v=TRUE))) #Path to this very file f1 <- readLines(file) #Read-in this source file where <- function(D){ #Computes direction of something in term of NSWE d <- "" if(D[2]<0) d <- paste(d,"W",sep="") if(D[2]>0) d <- paste(d,"E",sep="") if(D[1]<0) d <- paste(d,"N",sep="") if(D[1]>0) d <- paste(d,"S",sep="") d } d <- where(direction) #Direction of the other bot in term of NSWE M <- dirmines[dirmines[,1]%in%(-1:1) & dirmines[,2]%in%(-1:1),] #Which mines are next to me if(length(M)>2){m<-apply(M,1,where)}else if(length(M)==1){m<-where(M)}else{m<-""} #Direction of close-by mines in term of NSWE if(any(direction==0) & life >1 & !grepl("#p_fired", tail(f1,1))){ # If aligned with target, if life is more than one # and if this source file doesn't end with a comment saying the EMP was already fired # Fire the EMP, and leave comment on this file saying so action <- "P" f2 <- c(f1,"#p_fired2") cat(f2, file=file, sep="\n") }else if(tail(f1,1)=="#p_fired2"){ # If EMP have been fired last turn # Send missile in direction of target # Change comment on file. action <- paste("M", d) f2 <- c(f1[-length(f1)], "#p_fired1") cat(f2, file=file, sep="\n") }else if(tail(f1,1)=="#p_fired1"){ # If EMP was fired two turns ago # Send bullet and erase comment line. action <- paste("B", d) f2 <- f1[-length(f1)] cat(f2, file=file, sep="\n") } if (any(direction==0) & life<2){ # If aligned but life is 1 don't fire the EMP, but send missile instead action <- paste("M",d) } if (!any(direction==0)){ # If not aligned, try to align using shortest, landmine-free direction if(direction[2]<direction[1]){ if(grepl('W',d) & !'W'%in%m){action <- 'W'} if(grepl('E',d) & !'E'%in%m){action <- 'E'} }else if(direction[2]>=direction[1]){ if(grepl('N',d) & !'N'%in%m){action <- 'N'} if(grepl('S',d) & !'S'%in%m){action <- 'S'} }else{ #If no landmine-free direction, don't move action <- 0 } } cat(action,"\n") ``` This bot tries to place itself in the same row or column as the target, when it is aligned with the target it fires the EMP, then on the following turn it fires a missile toward the target, and then a bullet. It should also be aware of the surrounding mine and avoid them but is completely oblivious of bullets and missiles. If life is already at 1 it skips the EMP. To keep track of when it triggers the EMP, it modifies its source code by adding a comment at the end of the file (`#p_fired2` at first, then modifies it to `#p_fired1` and then erase it). I hope that keeping track of when it triggers the EMP this way is not too borderline. Command line should be `Rscript ReadyAimShoot.R`, followed by the argument as in the example, at least on UNIX systems but probably as well on windows (I'll check that when I ll actually test it against the other bots). **Edit**: Since the R version seems to have problem parsing the input, here is a python version of the same bot with, I hope, works. If any other R programmer see the post and see what's wrong with this bot, feel free to debug! ``` import sys, os def Position(arena, element): y = [i for i,j in enumerate(arena) if element in arena[i]][0] x = arena[y].index(element) return (x,y) def Direction(coord1, coord2): d0 = coord1[0]-coord2[0] d1 = coord1[1]-coord2[1] if d1!=0: a = ['N','S'][d1<0] else: a = "" if d0!=0: b = ['W','E'][d0<0] else: b = "" return a+b def Shortest(coord1,coord2): d = abs(coord1[0]-coord2[0])-abs(coord1[1]-coord2[1]) if d>0: a = 'EW' if d<=0: a = 'NS' return a input = sys.argv[1].splitlines() arena = input[0:10] life = input[10].split(" ") stuff = input[12:] path = os.path.dirname(__file__) f1 = os.path.join(path,'state','RAS') try: with open(f1, 'r') as f: fired = int(f.read()) except: fired = 0 me = Position(arena, "Y") other = Position(arena, "X") target = Direction(me,other) m = [] if len(stuff): s = [i.split(" ") for i in stuff] for i in s: if i[0]=='L': m += [(int(i[1]),int(i[2]))] near = [(me[0]+i,me[1]) for i in range(-1,2,2)]+[(me[0],me[1]+i) for i in range(-1,2,2)]+[(5+me[0],5+me[1]) for i in range(-1,2,2)] closeMines = [i for i in m if i in near] dirmines = [] for j in closeMines: dirmines += Direction(me, j) if target in ['N','S','E','W']: if int(life[1])>1 and fired==0: action = "P" with open(f1,'w') as f: f.write('2') else: if fired==2: action = "M "+target with open(f1,'w') as f: f.write('1') if fired==1: action = "B "+target with open(f1,'w') as f: f.write('0') if int(life[1])==1: action = "M "+target else: s = Shortest(me,other) d1 = Direction((me[0],other[1]), other) d2 = Direction((other[0],me[1]), other) if s=='EW' and d1 not in dirmines: action = d1 if s=='NS' and d2 not in dirmines: action = d2 else: if d2 not in dirmines: action = d2 if d1 not in dirmines: action = d1 else: action = 0 sys.stdout.write(action) ``` [Answer] ## King's Last Stand An extension to my `BattleBot`, this is designed to combat EMP-blasters. The only sensible way (IMO) to use EMP is by firing it while you're on the same axis as the opponent, then shooting missiles/weapons toward the stuck opponent. So, I stay off the axis :) If you've ever had a chess game go down to a king against a king+queen, you know that a queen alone *can't checkmate*, you have to get the king involved. If you don't, the lone king's strategy is easy: try to stay off-axis and toward the center to maximize mobility. If you get stuck, go for a stalemate. Of course, there is no great way to force a stalemate here, so *eventually* you get stuck on a side or corner if the queen is playing at any level of competence. If this bot is ever in that situation, it shoots. Assuming the opponent is going to EMP, this gives a one-turn damage advantage, so the king's last stand should turn out alright unless he's already low on life. Oh, and if it's already off-axis and safe from projectiles, it'll just take a potshot in the general direction of the enemy. **LastStand.java** ``` import java.awt.Point; import java.util.ArrayList; public class LastStand extends BattleBot{ String output = "0"; ArrayList<Point> safeFromEnemy; ArrayList<Point> safeFromWeapons; ArrayList<Point> safeFromBoth; public static void main(String[] args){ System.out.print(new LastStand(args).execute()); } LastStand(String[] args){ super(args); debug = false; } @Override String execute() { findSafeSpots(); if(attack()) return output; if(evade(safeFromBoth)) return output; if(evade(safeFromEnemy)) return output; return output; } boolean evade(ArrayList<Point> points){ Point dest = closestToCenter(points); if(dest==null) return false; int heading = headingToPoint(dest); output = headings[heading]; return true; } boolean attack(){ if(safeFromEnemy.isEmpty() || safeFromBoth.contains(yPosition)) return fire(); return false; } Point closestToCenter(ArrayList<Point> points){ Point closest = null; int dist = 15; for(Point pos : points){ if(distance(center, pos) < dist){ closest = pos; dist = distance(center, pos); } } return closest; } boolean isOnEnemyAxis(Point pos){ int x = Math.abs(pos.x - xPosition.x); int y = Math.abs(pos.y - xPosition.y); if(x==0 || y==0 || x==y) return true; return false; } void findSafeSpots(){ safeFromEnemy = new ArrayList<Point>(); safeFromWeapons = new ArrayList<Point>(); safeFromBoth = new ArrayList<Point>(); if(!isOnEnemyAxis(yPosition)) safeFromEnemy.add(yPosition); if(spotCollision(yPosition)==null) safeFromWeapons.add(yPosition); for(int heading=0;heading<8;heading++){ Point pos = nextPosition(heading, yPosition); if(isOutside(pos)) continue; if(!isOnEnemyAxis(pos)) safeFromEnemy.add(pos); if(spotCollision(pos)==null) safeFromWeapons.add(pos); } for(Point pos : safeFromEnemy){ if(safeFromWeapons.contains(pos)) safeFromBoth.add(pos); } } boolean fire(){ int heading = headingToPoint(xPosition); int dist = distance(xPosition, yPosition); if(dist>1 || yEnergy>4) output = "M " + headings[heading]; else output = "B " + headings[heading]; return true; } } ``` To compile run, place in a folder with [`BattleBot.java`](https://codegolf.stackexchange.com/a/23771/14215) and run: ``` javac LastStand.java java LastStand <arena-argument> ``` [Answer] ## EvadeBot This bot prioritizes staying alive. If it detects incoming collisions, it tries to move to a safe spot by checking *that* spot for collisions. If there are no surrounding "safe" spots, it stays put and goes to the next step. If there were no collisions (or safe spots in case of collision), it does an attack check. If the opponent is 8-axis aligned, it fires 80% of the time. If it's not aligned, it fires 50% of the time in the nearest heading. It chooses a weapon based on distance. If it's close, a landmine or bullet(depending on exact distance and relative health), missiles from afar. If it decided not to fire, it takes a random walk(again checking for safe spots). If none of the above worked out, it just sits there until the next turn. It doesn't use EMP, and I have a bad feeling about squaring up against `ReadyAimShoot`, but we'll see how it goes. --- The code is in two pieces. Since I may make more than one bot, I created an abstract `BattleBot` class. It includes helper functions like reading the arena, collision checking, heading management, etc. There's also a log function to help track what's going on while debugging. If `debug==false`, it will only print the actual output. If anyone wants to use/extend it, feel free. It's not *pretty* code, but it beats writing boilerplate. **BattleBot.java** ``` import java.awt.Point; import java.util.Random; abstract class BattleBot { static boolean debug; Random rand; final String[] headings = {"N","NE","E","SE","S","SW","W","NW"}; final int BULLET = 0, MISSILE = 1, LANDMINE = 2; final int arenaSize = 10; final Point center = new Point(arenaSize/2, arenaSize/2); boolean valid = false; Weapon[] weapons; Point xPosition, yPosition; int xEnergy, yEnergy; abstract String execute(); Point nextPosition(int heading, Point from){ if(from == null) from = yPosition; Point next = new Point(from); if(heading<0||heading>7) return next; if(heading<2 || heading>6) next.y--; if(heading<6 && heading>2) next.y++; if(heading>4) next.x--; if(heading<4 && heading>0) next.x++; return next; } boolean isHeadingExact(int heading, Point from, Point to){ Point next = new Point(from); while(!isOutside(next)){ next = nextPosition(heading, next); if(next.equals(to)) return true; } return false; } int headingToPoint(Point to){ int x = yPosition.x - to.x; int y = yPosition.y - to.y; if(x<0){ if(y<0) return 3; if(y>0) return 1; return 2; }else if(x>0){ if(y<0) return 5; if(y>0) return 7; return 6; }else{ if(y<0) return 4; return 0; } } BattleBot(String[] args){ rand = new Random(); if(args.length < 1 || args[0].length() < arenaSize*arenaSize) return; String[] lines = args[0].split("\\r?\\n"); if(lines.length<12) return; weapons = new Weapon[lines.length - 12]; int wIndex = 0; for(int i=0;i<lines.length;i++){ String line = lines[i]; if(i<arenaSize){ if(line.contains("X")) xPosition = new Point(line.indexOf("X"),i); if(line.contains("Y")) yPosition = new Point(line.indexOf("Y"),i); } else { String[] tokens = line.split(" "); switch(tokens[0].charAt(0)){ case 'X': xEnergy = Integer.parseInt(tokens[1]); break; case 'Y': yEnergy = Integer.parseInt(tokens[1]); break; case 'B': case 'M': case 'L': weapons[wIndex++] = new Weapon(tokens); break; } } } valid = true; } int distance(Point a, Point b){ return Math.max(Math.abs(a.x-b.x), Math.abs(a.y-b.y)); } Point spotCollision(Point pos){ for(int i=0;i<weapons.length;i++){ Point collision = weapons[i].collisionPoint(pos); if(collision != null){ log("Collision at " + collision.x + "," + collision.y + " with weapon type " + weapons[i].type); if(collision.equals(pos)) return collision; else if(weapons[i].type==MISSILE && distance(collision,pos) < 2) return collision; log("Collision disregarded"); } } return null; } boolean isOutside(Point pos){ if(pos.x<0||pos.y<0||pos.x>=arenaSize||pos.y>=arenaSize) return true; return false; } static <T> void log(T msg){ if(debug) System.out.println(msg); } int getHeading(String in){ for(int i=0;i<headings.length;i++){ if(in.equalsIgnoreCase(headings[i])) return i; } return -1; } class Weapon{ final int[] speeds = {3,2,0}; Point position; int type; int heading; int speed; Weapon(String[] tokens){ char which = tokens[0].charAt(0); type = which=='B'?BULLET: which=='M'?MISSILE: LANDMINE; speed = speeds[type]; position = new Point(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); if(type==BULLET || type == MISSILE) heading = getHeading(tokens[3]); else heading = -1; } Point collisionPoint(Point pos){ Point next = new Point(position); if(type==LANDMINE) return next; for(int i=0;i<speed;i++){ next = nextPosition(heading, next); if(isOutside(next)) return next; if(next.equals(xPosition) || next.equals(yPosition)) return next; if(next.equals(pos)) return next; } return null; } } } ``` This *particular* bot is `EvadeBot`. To compile/run, put it in a folder with `BattleBot.java` and run: ``` javac EvadeBot.java java EvadeBot <arena-argument> ``` If you omit the argument or it can't parse it correctly, it defaults to `"0"` output. **EvadeBot.java** ``` import java.awt.Point; public class EvadeBot extends BattleBot{ String output = "0"; public static void main(String[] args){ System.out.print(new EvadeBot(args).execute()); } EvadeBot(String[] args) { super(args); debug = false; } @Override String execute() { if(!valid) return output; if(evade()) return output; if(attack()) return output; if(walk()) return output; return output; } boolean evade(){ Point collision = spotCollision(yPosition); if(collision!=null){ log("Incoming! " + collision.x + "," + collision.y); return moveAwayFrom(collision); } return false; } boolean attack(){ int dist = distance(yPosition, xPosition); int heading = headingToPoint(xPosition); int odds = rand.nextInt(100); if(isHeadingExact(heading, yPosition, xPosition)){ if(odds<20) return false; } else { if(odds<50) return false; } log("Odds of firing " + headings[heading] + " to " + xPosition.x + "," + xPosition.y + " checked, preparing to attack."); if(dist==2){ if(yEnergy > 3 || (xEnergy < 2 && yEnergy > 1)){ output = "L " + headings[heading]; return true; } }else if(dist<4){ output = "B " + headings[heading]; return true; }else{ output = "M " + headings[heading]; return true; } return false; } boolean walk(){ log("Trying to random walk..."); int heading = rand.nextInt(8); for(int i=0;i<8;i++,heading=(heading+1)%8){ Point next = nextPosition(heading, yPosition); if(!isOutside(next) && spotCollision(next)==null){ output = headings[heading]; return true; } } return false; } boolean moveAwayFrom(Point from){ int heading; if(from.equals(yPosition)) heading = rand.nextInt(8); else heading = (headingToPoint(from) + (rand.nextBoolean()?2:6)) % 8; Point next = nextPosition(heading, yPosition); for(int i=0;i<8;i++){ log("Checking move " + headings[heading] + " to " + next.x + "," + next.y); if(!isOutside(next) && spotCollision(next)==null){ output = headings[heading]; return true; } heading = (heading + 1) % 8; next = nextPosition(heading, yPosition); } return false; } } ``` [Answer] ## Spiral Bot Literate Haskell In literate haskell, comments are default, so this entire post is the program. This bot will shoot missiles in spirals around it, ignoring input. It stores state in a file (which hopefully isn't being posioned by the competer.) ``` > import System.Directory (doesFileExist, createDirectoryIfMissing, setCurrentDirectory) > import Control.Monad (unless) ``` First we list the missile actions. ``` > missiles = map ("M "++) $ cycle ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] ``` Next we go straight into the IO monad. If "spiral.txt" doesn't exist, we write "0" to it. We also check for the directory. ``` > main = do > createDirectoryIfMissing True "state" > setCurrentDirectory "state" > exists <- doesFileExist "spiral.txt" > unless exists $ writeFile "spiral.txt" "0" ``` Then we read it and print the action. ``` > actPos <- fmap read $ readFile "spiral.txt" :: IO Int > putStr $ missiles !! actPos ``` And finally we write to the file the now position. ``` > writeFile "spiral.txt" (show $ actPos + 1) ``` [Answer] ### DodgingTurret **a Python Bot** Here's another attempt. Since ReadyAimShoot is in the repair shop for a while :) I figured I'll try something else in the meantime, using Python this time. ``` import sys def Position(arena, element): y = [i for i,j in enumerate(arena) if element in arena[i]][0] x = arena[y].index(element) return (x,y) def Direction(coord1, coord2): d0 = coord1[0]-coord2[0] d1 = coord1[1]-coord2[1] if d1!=0: a = ['N','S'][d1<0] else: a = "" if d0!=0: b = ['W','E'][d0<0] else: b = "" return a+b def GetPath(coord, direction): if direction=='N': path = [(coord[0],coord[1]-i) for i in xrange(3)] if direction=='S': path = [(coord[0],coord[1]+i) for i in xrange(3)] if direction=='E': path = [(coord[0]+i,coord[1]) for i in xrange(3)] if direction=='W': path = [(coord[0]-i,coord[1]) for i in xrange(3)] if direction=='NE': path = [(coord[0]+i,coord[1]-i) for i in xrange(3)] if direction=='NW': path = [(coord[0]-i,coord[1]-i) for i in xrange(3)] if direction=='SE': path = [(coord[0]+i,coord[1]+i) for i in xrange(3)] if direction=='SW': path = [(coord[0]-i,coord[1]+i) for i in xrange(3)] return path def Danger(coord, stuff): if len(stuff): s = [i.split(" ") for i in stuff] for i in s: if i[0] in ['M','B']: path = GetPath((int(i[1]),int(i[2])),i[3]) if coord in path: return ['unsafe',path] return ['safe',()] else: return ['safe',()] input = sys.argv[1].splitlines() arena = input[0:10] stuff = input[12:] me = Position(arena, "Y") center = Direction(me, (5,5)) if center != "": action = center else: d = Danger(me,stuff) if d[0]=='safe': other = Position(arena,"X") target = Direction(me, other) action = 'M '+target if d[0]=='unsafe': escape = [(me[0]+i,me[1]) for i in range(-1,2,2)]+[(me[0],me[1]+i) for i in range(-1,2,2)]+[(5+me[0],5+me[1]) for i in range(-1,2,2)] esc_choice = [i for i in escape if i not in d[1]][0] action = Direction(me,esc_choice) sys.stdout.write(action) ``` I shamelessly stole the line `sys.argv[1].splitlines()` from @Gareth but at least this time that means I won't have a problem parsing the input. This bot runs at the center at the start of the bout, then stays there and shoots missiles in the direction of the opponent. He also tries to dodge nearby bullets and missiles if it's on their path but then goes back to the center before starting shooting again. [Answer] # Straight shooter This is another simple bot you can use for testing. If it has a direct line of sight to the opponent it shoots, otherwise it steps randomly. ``` import sys try: map = sys.argv[1][0:110].split() except: sys.exit(1) # Locate us and the opponent. # for y in range(0,10): for x in range(0, 10): if 'Y' == map[y][x]: me_y = y me_x = x elif 'X' == map[y][x]: him_y = y him_x = x # If we're on a direct line with the opponent, fire a missile. # if me_y == him_y or me_x == him_x or abs(me_y - him_y) == abs(me_x - him_x): if him_y < me_y and him_x < me_x: sys.stdout.write('M NW') elif him_y < me_y and him_x == me_x: sys.stdout.write('M N') elif him_y < me_y and him_x > me_x: sys.stdout.write('M NE') elif him_y == me_y and him_x < me_x: sys.stdout.write('M W') elif him_y == me_y and him_x > me_x: sys.stdout.write('M E') elif him_y > me_y and him_x < me_x: sys.stdout.write('M SW') elif him_y > me_y and him_x == me_x: sys.stdout.write('M S') elif him_y > me_y and him_x > me_x: sys.stdout.write('M SE') # Otherwise, move randomly. # else: import random sys.stdout.write(random.choice(['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])) ``` [Answer] # neo-bot ### coffeescript Another JavaScript bot to add to the mix. This one targets Node.js and is written in CoffeeScript. The architecture follows from the Java crowd with a base class handling general bottiness and another file with specialization for the bot at hand. The main strategy of this bot is to not get hit by your projectiles. If you aren't an immediate threat neo-bot will just start shooting. The base file `shared.coffee` ``` # entry point deserializeBoard = (board) -> me = no you = no rows = board.split '\n' all = for i in [0...rows.length] row = rows[i] me = row: i, col: row.indexOf 'Y' if /Y/.test row you = row: i, col: row.indexOf 'X' if /X/.test row row.split '' throw new Error "missing player" unless me and you all.me = me all.you = you all deserializeState = (state) -> board = deserializeBoard state[0...110] rest = state[110...] .split '\n' .filter (d) -> d if rest[0][0] is 'Y' board.me.health = +rest[0][2...] board.you.health = +rest[1][2...] else board.you.health = +rest[0][2...] board.me.health = +rest[1][2...] board.mines = [] board.projectiles = [] for weapon in rest[2...] parts = weapon[2...].split ' ' if weapon[0] is 'L' board.mines.push row: +parts[1] col: +parts[0] else board.projectiles.push type: weapon[0] row: +parts[1] col: +parts[0] dir: parts[2] board module.exports = bot = (handle) -> state = process.argv[-1...][0] board = deserializeState state move = handle board process.stdout.write move ``` And `neo-bot.coffee`, the bot code. ``` # i know kung fu bot = require "./shared" board_rows = [0...10] board_cols = [0...10] directions = [ 'NW', 'N', 'NE' 'W', 'E' 'SW', 'S', 'SE' ] direction = (a, b) -> if a.row < b.row if a.col < b.col "SE" else if a.col is b.col "S" else "SW" else if a.row is b.row if a.col < b.col "E" else "W" else if a.col < b.col "NE" else if a.col is b.col "N" else "NW" move = (me, dir) -> row = me.row col = me.col if /N/.test dir row-- if /S/.test dir row++ if /W/.test dir col-- if /E/.test dir col++ {row, col} clamp = (v) -> Math.max 0, Math.min 9, v legal = (pos) -> clamp(pos.row) is pos.row and clamp(pos.col) is pos.col randOf = (choices) -> i = Math.floor Math.rand * choices.length choices[i] moves = B: 3 M: 2 damage = B: 1 M: 3 danger = (board) -> n = ((0 for i in [0...10]) for j in [0...10]) for projectile in board.projectiles next = projectile for i in [0...moves[projectile.type]] next = move next, projectile.dir if projectile.type is 'M' and not legal next for d in directions schrapnel = move next, d if legal schrapnel n[schrapnel.row][schrapnel.col] += 1 continue unless legal next n[next.row][next.col] += damage[projectile.type] for mine in board.mines n[mine.row][mine.col] += 2 n warning = (board) -> n = ((0 for i in [0...10]) for j in [0...10]) for dir in directions p = board.you p = move p, dir continue unless legal p n[p.row][p.col] = damage.M - 1 # relative damage p = move p, dir continue unless legal p n[p.row][p.col] = damage.M p = move p, dir continue unless legal p n[p.row][p.col] = damage.B for mine in board.mines for dir in directions p = move mine, dir continue unless legal p n[p.row][p.col] += 1 n board_map = (map) -> (a) -> ((map a[i][j] for j in board_cols) for i in board_rows) board_pair = (join) -> (a, b) -> ((join a[i][j], b[i][j] for j in board_cols) for i in board_rows) boards = sum: board_pair (a, b) -> a + b scale: (n) -> board_map (a) -> a * n chooseSafeDir = ({me, you}, lava) -> dirs = [] min = +Infinity for dir in directions guess = move me, dir continue unless legal guess guess.dir = dir guess.damage = lava[guess.row][guess.col] min = guess.damage if guess.damage < min dirs.push guess dirs.sort (a, b) -> if a.damage < b.damage -1 else if b.damage < a.damage 1 else 0 choice = randOf dirs.filter (d) -> d.damage < min + 1 choice = choice or dirs[0] choice.dir neo = (WARNING_FACTOR, MISSILE_FACTOR, MOVE_FACTOR) -> WARNING_FACTOR ?= 0.8 MISSILE_FACTOR ?= 0.2 MOVE_FACTOR ?= 0.1 combine = (d, w) -> boards.sum d, boards.scale(WARNING_FACTOR)(w) shoot = ({me, you}) -> weapon = if Math.random() < MISSILE_FACTOR then 'M' else 'B' dir = direction me, you "#{weapon} #{dir}" (board) -> lava = combine danger(board), warning(board) if lava[board.me.row][board.me.col] or Math.random() < MOVE_FACTOR chooseSafeDir board, lava else shoot board bot neo() ``` I'd highly recommend compiling the coffee files to javascript before running; it's quite a bit faster. Basically you want to do this: ``` > coffee -c *.coffee > ./bb "java EvilBot" "node ./neo-bot.js" ``` [Answer] # CamperBot This bot just stays where he is and shoots. I only implemented bullets, as the other weapons would harm the bot. Please forgive me my awful C-skills ;) ``` #include <stdio.h> #include <time.h> int main(int argc, char *argv[]) { int direction = 0; char directions[][3] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}; srand(time(NULL)); direction = rand() % 8; printf("B %s", directions[direction]); return 0; } ``` Not really expected to win much. [Answer] Since there are no entries yet I'll put one out there so you have something to beat up. I give to you: # Mine! Mine! Mine! ``` import sys import random from itertools import product def getMyPos(arena): x=0 y=0 for idx, line in enumerate(arena): if(line.find('Y')!= -1): x=line.find('Y') y=idx return [x, y] def isNearMine(pos, badstuff): returnval=False for badthing in badstuff: thinglist=badthing.split(" ") if(thinglist[0]=='L'): returnval=returnval or isNear(pos, map(int, thinglist[1:3])) return returnval def isNear(pos1, pos2): return ((abs(pos1[0]-pos2[0])<2) and (abs(pos1[1]-pos2[1])<2)) def newpos(mypos, move): return [mypos[0]+move[0], mypos[1]+move[1]] def inBounds(pos): return pos[0]<10 and pos[0]>=0 and pos[1]<10 and pos[1]>=0 def randomSafeMove(arena, badstuff): mypos=getMyPos(arena) badsquares=[mypos] #don't want to stay still for badthing in badstuff: thinglist=badthing.split(" ") if(thinglist[0]=='L'): badsquares.append(map(int, thinglist[1:3])) possiblemoves=list(product(range(-1, 2), repeat=2)) possiblemoves=[list(x) for x in possiblemoves] safemoves=[x for x in possiblemoves if newpos(mypos, x) not in badsquares] safemoves=[x for x in safemoves if inBounds(newpos(mypos, x))] move=random.choice(safemoves) return (("N S"[move[1]+1])+("W E"[move[0]+1])).strip() def randomDropMine(arena): mypos=getMyPos(arena) badsquares=[mypos] #don't want to drop a mine under myself possiblemoves=list(product(range(-1, 2), repeat=2)) possiblemoves=[list(x) for x in possiblemoves] possiblemoves=[x for x in possiblemoves if newpos(mypos, x) not in badsquares] possiblemoves=[x for x in possiblemoves if inBounds(newpos(mypos, x))] move=random.choice(possiblemoves) return "L "+(("N S"[move[1]+1])+("W E"[move[0]+1])).strip() input=sys.argv[1].splitlines() arena=input[0:10] energy=input[10:12] badstuff=input[12:] if(isNearMine(getMyPos(arena), badstuff)): sys.stdout.write(randomSafeMove(arena, badstuff)) else: sys.stdout.write(randomDropMine(arena)) ``` Doesn't do anything particularly clever. Drops a mine if there are none in any of the surrounding squares otherwise moves into one of the safe surrounding squares. Can only barely beat the HuggyBot. Please excuse the naff Python coding. [Answer] # Random bot This bot just makes a random action on each move. It doesn't fire the EMP and it doesn't look at the map at all. Half the time it's just firing into the wall! ``` #include <stdio.h> #include <sys/time.h> void main(int argc, char **argv) { char dirs[][3] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}; struct timeval tv; gettimeofday(&tv, NULL); srand(tv.tv_usec); int action = rand()%11; int dir = rand()%7; switch(action) { case 8: printf("B %s", dirs[dir]); break; case 9: printf("M %s", dirs[dir]); break; case 10: printf("L %s", dirs[dir]); break; default: printf(dirs[action]); break; } } ``` Test it (against itself) as below. ``` $ gcc random.c -o random $ ./bb random ``` [Answer] ## Trouble and Strafe Some Ruby representation in the fight. Moves up and down the randomly assigned wall firing missiles at the opposite wall. Slightly glitchy at the top and bottom. ``` def getInput() inputlines=ARGV[0].split(/\n/) return [inputlines[0, 10], inputlines[10, 2], inputlines[12..-1]] end def getMyPos(arena) pos=[] arena.each_with_index{|str, index| pos=[str.index('Y'), index] if(!str.index('Y').nil?)} return pos end def parseProjectiles(projectiles) projectiles.map!{|prj| prj.split(' ')} missiles=projectiles.select{|prj| prj[0]=='M'} bullets=projectiles.select{|prj| prj[0]=='B'} landmines=projectiles.select{|prj| prj[0]=='L'} return [missiles, bullets, landmines] end def haveFired?(ypos, direction, projectiles) return projectiles.select{|prj| prj[2]==ypos.to_s && prj[3]==direction}.size>0 end arena, botenergy, projectiles=getInput() missiles, bullets, landmines=parseProjectiles(projectiles) myposX=getMyPos(arena)[0] myposY=getMyPos(arena)[1] direction="WE"[myposX!=0 ? 0 : 1] if haveFired?(myposY, direction, missiles) if myposY==0 print "S" elsif myposY==9 print "N" else if haveFired?(myposY-1, direction, missiles) print "S" elsif haveFired?(myposY+1, direction, missiles) print "N" else if(Random.rand(2)==0) print "N" else print "S" end end end else print "M "+direction end ``` [Answer] # A JavaScript core I thought I'd be kind and give you my core JS bot. It's got all the functions necessary for making a bot, all you need is some actions to do based on the data that this gives you. Not finished yet, as I can't really test it (can't get the arena code to compile). Feel free to use this, I'm looking forward to seeing some JS bots in the mix. **To Do:** * Add functions to calculate weapon locations ``` var stdi = WScript.StdIn; var stdo = WScript.StdOut; function botLog(toLog){ var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.CreateTextFile("./botLog.txt", 8, true); fh.WriteLine(toLog); fh.Close(); } var directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; // READ ARGUMENTS AND CREATE THE ARENA var arena = {}; arena.map = WScript.Arguments.Item(0); // Get the arena from arguments arena.rows = arena.map.split('\\n'); arena.find = function(toFind){ //Find a character in the arena. for(var i = 0; i < 10; i++){ if(arena.rows[i].indexOf(toFind) !== -1){ return [arena.rows[i].search(toFind), i]; } } }; arena.findAtPos = function(x, y){ return arena.rows[y].charAt(x); }; me = {}; me.pos = arena.find('Y'); me.x = me.pos[0]; me.y = me.pos[1]; me.energy = parseInt(arena.rows[10].replace("Y ", "")); me.nearby = { N : arena.findAtPos(me.x, me.y - 1), NE : arena.findAtPos(me.x + 1, me.y - 1), E : arena.findAtPos(me.x + 1, me.y), SE : arena.findAtPos(me.x + 1, me.y + 1), S : arena.findAtPos(me.x, me.y + 1), SW : arena.findAtPos(me.x - 1, me.y + 1), W : arena.findAtPos(me.x - 1, me.y), NW : arena.findAtPos(me.x -1, me.y - 1), contains : function(checkFor){ for(var j = 0; j < 8; j++){ if(me.nearby[j] === checkFor){ return true; } } } } foe = {}; foe.pos = arena.find('X'); foe.x = foe.pos[0]; foe.y = foe.pos[1]; foe.energy = parseInt(arena.rows[11].replace("X ", "")); ``` **Please note** that some things here may have to be modified for other OS (this works only on Windows). Rhino version here: <http://pastebin.com/FHvmHCB8> [Answer] # Centre-Bot **A JavaScript Bot** This bot aims to get into the middle of the arena, before it shoots bullets or missiles at it's target each turn depending on how close it is. If the enemy is in the middle, it'll just keep shooting bullets in the vague direction. I don't expect it to do very well, but it's more of a testing one, and I'm interested to see how well it really does. ``` var arena = {}; var sys = require("sys"); var fs = require("fs"); arena.map = process.argv[2]; arena.rows = arena.map.split('\n'); arena.find = function(toFind){ for(var i = 0; i < 10; i++){ if(arena.rows[i].indexOf(toFind) !== -1){ return [arena.rows[i].search(toFind), i]; } } }; arena.findAtPos = function(x, y){ return arena.rows[y].charAt(x); }; me = {}; me.pos = arena.find('Y'); me.x = me.pos[0]; me.y = me.pos[1]; me.energy = parseInt(arena.rows[10].replace("Y ", "")); foe = {}; foe.pos = arena.find('X'); foe.x = foe.pos[0]; foe.y = foe.pos[1]; foe.energy = parseInt(arena.rows[11].replace("X ", "")); function findFoe(){ if(me.x < foe.x){ if(me.y < foe.y){ foe.direction = 'SE'; } else if(me. y === foe.y){ foe.direction = 'E'; } else{ foe.direction = 'NE'; } } if(me.x === foe.x){ if(me.y < foe.y){ foe.direction = 'S'; } else{ foe.direction = 'N'; } } if(me.x > foe.x){ if(me.y < foe.y){ foe.direction = 'SW'; } else if(me. y === foe.y){ foe.direction = 'W'; } else{ foe.direction = 'NW' } } } function findCentre(){ if(me.x < 5){ if(me.y < 5){ centreDirection = 'SE'; } else if(me.y === 5){ centreDirection = 'E'; } else{ centreDirection = 'NE' } } if(me.x === 5){ if(me.y < 5){ centreDirection = 'S'; } else{ centreDirection = 'N' } } if(me.x > 5){ if(me.y < 5){ centreDirection = 'SW'; } else if(me. y === 5){ centreDirection = 'W'; } else{ centreDirection = 'NW' } } } findCentre(); findFoe(); if(me.x !== 5 && me.y !== 5){ process.stdout.write(centreDirection); }else{ if(foe.x >= me.x + 2 || foe.x <= me.x - 2 || foe.y >= me.y + 2 || foe.y <= me.y - 2){ process.stdout.write('M ' + foe.direction); }else process.stdout.write('B ' + foe.direction); } ``` save as .js file and execute with `node centrebot.js`. This will work with Node.js, but you may have to modify it for another program, sorry! **In my tests:** * Thrashed ReadyAimShoot without a scratch. * MOSTLY wins against DodgingTurret * Won all with a few scratches from lucky landmines from Randombot * Beat Straight shooter 9 times out of 9, but each bout was close, even though I won all of them. Haven't tested any of the top java bots, and I'm not too confident either... [Answer] ## CunningPlanBot (Python 3.3) This is completely untested under the actual interface... It does work correctly with the maps at least! It's written for Python 3.3 What it does: If in Phase 1 - If at wall and direction moves into wall or moving into a landmine, randomly change direction to a non wall or landmine direction - Move in current direction - Go to Phase 2 If in Phase 2 - Shoot bullet in closest direction to enemy - Go to Phase 3 If in Phase 3 - If no land mine, drop land mine - Go to phase 1 Still needs to figure out whether to shoot a missile. Also I've got no clue whatsoever about whether the landmine avoiding stuff works. Needs more testing tomorrow evening. ``` #!/usr/bin/python import sys import os.path import random import math def iround(x): return int(round(x) - .5) + (x > 0) currentphase = 0 currentdir = 0 # # 4 # 5 3 # 6 DIR 2 # 7 1 # 0 if os.path.isfile('state/cpb'): statein = open('state/cpb', 'r') currentdir = int(statein.read(1)) currentphase = int(statein.read(1)) statein.close() Landmines = [] #Loads the map bit. The bits we care about anyway. line=sys.argv[1].splitlines() for y in range(0, 10): for x in range(0, 10): if line[x][y] == "X": hisloc = (x, y) elif line[x][y] == "Y": myloc = (x, y) elif line[x][y] == "L": Landmines.append((x,y)) #print(myloc[0]) #print(myloc[1]) newdir = False if (currentphase == 0): if (currentdir == 7) or (currentdir == 0) or (currentdir == 1) and (myloc[1] == 9): newdir = True if (currentdir == 5) or (currentdir == 4) or (currentdir == 3) and (myloc[1] == 0): newdir = True if (currentdir == 3) or (currentdir == 2) or (currentdir == 1) and (myloc[0] == 9): newdir = True if (currentdir == 5) or (currentdir == 6) or (currentdir == 7) and (myloc[0] == 0): newdir = True if newdir: newdirs = [] #Test 0 if (myloc[1] < 9) and not (myloc[0], myloc[1] + 1) in Landmines: newdirs.append(0) #Test 1 if (myloc[0] < 9) and (myloc[1] < 9) and not (myloc[0] + 1, myloc[1] + 1) in Landmines: newdirs.append(1) #Test 2 if (myloc[0] < 9) and not (myloc[0] + 1, myloc[1]) in Landmines: newdirs.append(2) #Test 3 if (myloc[0] < 9) and (myloc[1] > 0) and not (myloc[0] + 1, myloc[1] - 1) in Landmines: newdirs.append(3) #Test 4 if (myloc[1] > 0) and not (myloc[0], myloc[1] - 1) in Landmines: newdirs.append(4) #Test 5 if (myloc[0] > 0) and (myloc[1] > 0) and not (myloc[0] - 1, myloc[1] - 1) in Landmines: newdirs.append(5) #Test 6 if (myloc[0] > 0) and not (myloc[0] - 1, myloc[1] ) in Landmines: newdirs.append(6) #Test 7 if (myloc[0] > 0) and (myloc[1] > 9) and not (myloc[0] - 1, myloc[1] + 1) in Landmines: newdirs.append(7) if len(newdirs) == 0: if currendir == 0: currentdir = 4 elif currendir == 1: currentdir = 5 elif currendir == 2: currentdir = 6 elif currendir == 3: currentdir = 7 elif currendir == 4: currentdir = 0 elif currendir == 5: currentdir = 1 elif currendir == 6: currentdir = 2 elif currendir == 7: currentdir = 3 else: currentdir = random.SystemRandom().choice(newdirs) if currentdir == 0: print ("S", end="") elif currentdir == 1: print ("SE", end="") elif currentdir == 2: print ("E", end="") elif currentdir == 3: print ("NE", end="") elif currentdir == 4: print ("N", end="") elif currentdir == 5: print ("NW", end="") elif currentdir == 6: print ("W", end="") elif currentdir == 7: print ("SW", end="") elif (currentphase == 1): dx = (myloc[0] - hisloc[0]) dy = (myloc[1] - hisloc[1]) distance = math.pow(dx*dx+dy*dy, 0.5) angle = int(iround(math.degrees(math.atan2(dx, -dy)) / 45) ) % 8 if angle == 5: print ("B S", end="") elif angle == 1: print ("B SE", end="") elif angle == 2: print ("B E", end="") elif angle == 3: print ("B NE", end="") elif angle == 4: print ("B N", end="") elif angle == 5: print ("B NW", end="") elif angle == 6: print ("B W", end="") elif angle == 7: print ("B SW", end="") elif (currentphase == 2): if not (myloc in Landmines): print ("L", end="") currentphase = (currentphase + 1) % 3 stateout = open ('state/cpb', 'w') stateout.write(str(currentdir)) stateout.write(str(currentphase)) stateout.close() ``` [Answer] # UltraBot A Java bot that calculates the danger for each surrounding field. If a surrounding field is less dangerous than the current one, the bot moves there (or another, equally dangerous field). If there is no less dangerous field, the bot shoots (missiles if enemy bot is far away, bullets if enemy bot is close). I took some code from the BattleBot (thanks!). ``` import java.awt.Point; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Random; public class UltraBot { private static final int arenaSize = 10; private static ArrayList<Weapon> weapons = new ArrayList<Weapon>(); private static Bot me; private static Bot enemy; public static void main(String args[]) { Direction suggestedMove; readInput(args[0]); suggestedMove = suggestedMove(); if (suggestedMove != Direction.STAY) { System.out.print(suggestedMove.name()); return; } System.out.print(shootCmd()); } public static void readInput(String args) { String[] lines = args.split("\\r?\\n"); for(int i=0;i<lines.length;i++){ String line = lines[i]; if(i<arenaSize){ if(line.contains("X")) enemy = new Bot(new Field(line.indexOf("X"),i)); if(line.contains("Y")) me = new Bot(new Field(line.indexOf("Y"),i)); } else { String[] tokens = line.split(" "); switch(tokens[0].charAt(0)){ case 'X': enemy.setLife(Integer.parseInt(tokens[1])); break; case 'Y': me.setLife(Integer.parseInt(tokens[1])); break; default: weapons.add(new Weapon(tokens)); break; } } } } public static Direction suggestedMove() { Map<Direction, Integer> surrFields = new HashMap<Direction, Integer>(); Random rand = new Random(); //calculate danger for all surrounding fields for(Direction direction : Direction.values()) { Field currField = me.getPos().incPos(direction, 1); surrFields.put(direction, currField.calcDanger(weapons, enemy)); } int currDanger = surrFields.get(Direction.STAY); Direction currDirection = Direction.STAY; for (Entry<Direction, Integer> e : surrFields.entrySet()) { //always move if better field found if (e.getValue() < currDanger) { currDanger = e.getValue(); currDirection = e.getKey(); } //move sometimes if equal danger field found else if(e.getValue() == currDanger && rand.nextInt(3) == 1) { if (currDanger != 0 || rand.nextInt(15) == 1) { currDanger = e.getValue(); currDirection = e.getKey(); } } } return currDirection; } public static String shootCmd() { WeaponType type = WeaponType.M; if(me.getPos().isNear(enemy.getPos(), 3)) { type = WeaponType.B; } return type.name() + " " + me.shootDirection(enemy); } } class Bot { private Field pos; private int life; public Bot(Field pos) { this.pos = pos; } public void setLife(int life) { this.life = life; } public Field getPos() { return pos; } public int getLife() { return life; } public String shootDirection(Bot other) { Random rand = new Random(); Direction direction = Direction.S; if (getPos().getX() >= other.getPos().getX() && getPos().getY() >= other.getPos().getY()) { switch(rand.nextInt(5)) { case 0: direction = Direction.N; break; case 1: direction = Direction.W; break; default: direction = Direction.NW; break; } } else if (getPos().getX() <= other.getPos().getX() && getPos().getY() >= other.getPos().getY()) { switch(rand.nextInt(3)) { case 0: direction = Direction.N; break; case 1: direction = Direction.E; break; default: direction = Direction.NE; break; } } if (getPos().getX() >= other.getPos().getX() && getPos().getY() <= other.getPos().getY()) { switch(rand.nextInt(3)) { case 0: direction = Direction.S; break; case 1: direction = Direction.W;break; default: direction = Direction.SW;break; } } if (getPos().getX() <= other.getPos().getX() && getPos().y <= other.getPos().y) { switch(rand.nextInt(3)) { case 0: direction = Direction.S; break; case 1: direction = Direction.E; break; default: direction = Direction.SE; break; } } return direction.name(); } } enum Direction { N(0, -1), NE(1, -1), E(1, 0), SE(1, 1), S(0, 1), SW(-1, 1), W(-1, 0), NW(-1,-1), STAY(0,0); public final int offsetX; public final int offsetY; Direction(int offsetX, int offsetY) { this.offsetX = offsetX; this.offsetY = offsetY; } } enum WeaponType { B(1, 3), M(3, 2), L(2, 0); public final int dmg; public final int speed; WeaponType(int dmg, int speed) { this.dmg = dmg; this.speed = speed; } } class Weapon { private WeaponType type; private Direction direction; private Field pos; public Weapon(String[] tokens) { this.type = WeaponType.valueOf(tokens[0]); this.pos = new Field(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); if(type != WeaponType.L) { this.direction = Direction.valueOf(tokens[3]); } } public int getDanger(Field dest) { if (dest.isOutside()) { return 99; } if (type == WeaponType.L) { return dest.equals(pos) ? type.dmg * 3 : 0; // stepped on landmine } for (int i = 1; i <= type.speed; i++) { Field newPos = pos.incPos(direction, i); if (dest.equals(newPos)) { return type.dmg * 3; // direct hit with missile or bullet } } return 0; } } class Field extends Point{ public Field(int x, int y) { super(x,y); } // as it tries to stay off walls and enemy, it doesn't need to calc splash dmg public int calcDanger(ArrayList<Weapon> weapons, Bot enemy) { int danger = 0; // is near wall if (this.getX() == 0 || this.getX() == 9) danger++; if (this.getY() == 0 || this.getY() == 9) danger++; for (Weapon weapon : weapons) { danger += weapon.getDanger(this); } // near bot if (this.isNear(enemy.getPos(), 2)) { danger++; } return danger; } public Boolean isOutside() { if (this.getX() > 9 || this.getY() > 9 || this.getX() < 0 || this.getY() < 0) { return true; } return false; } public Boolean isNear(Field dest, int distance) { int dx = (int)Math.abs(dest.getX() - this.getX()); int dy = (int)Math.abs(dest.getY() - this.getY()); if (dx <= distance || dy <= distance) { return true; } return false; } public Field incPos(Direction direction, int step) { return new Field((int)this.getX() + (direction.offsetX * step), (int)this.getY() + (direction.offsetY * step)); } } ``` This bot is extremely hard to hit, but not very good at shooting the enemy… I still expect it to be better than my previous CamperBot. [Answer] ## NinjaPy A last minute submission in python (untested but hopefully will work). The idea is that it advances toward the opponent while staying in its blind spot. When it is close enough (3 cells away) it places itself in the diagonal of the opponent and shoots a missile. ``` import sys def position(arena, element): y = [i for i,j in enumerate(arena) if element in arena[i]][0] x = arena[y].index(element) return (x,y) def distance(other): dM = [[0 for x in range(10)] for y in range(10)] for i in range(len(dM)): for j in range(len(dM[0])): dM[i][j] = max([abs(other[0]-i),abs(other[1]-j)]) return dM def direction(coord1, coord2): d0 = coord1[0]-coord2[0] d1 = coord1[1]-coord2[1] if d1!=0: a = ['N','S'][d1<0] else: a = "" if d0!=0: b = ['W','E'][d0<0] else: b = "" return a+b def getPath(coord, aim, speed): d = {'N': (0,-1), 'S':(0,1), 'E':(1,0), 'W':(-1,0), 'NW':(-1,-1), 'NE':(1,-1), 'SW':(-1,1), 'SE':(1,1)} D = d[aim] path = [(coord[0]+D[0]*i, coord[1]+D[1]*i) for i in range(speed+1)] return path def dangerMap(stuff,other): dM = [[0 for x in range(10)] for y in range(10)] surroundings = [(other[0]+i,other[1]+j) for i in range(-2,3) for j in range(-2,3)] for i in range(len(dM)): for j in range(len(dM[0])): if i == other[0] : dM[i][j] = 1 if j == other[1] : dM[i][j] = 1 if (i,j) in [(other[0]+k, other[1]+k) for k in range(-10,11)]: dM[i][j] = 1 if (i,j) in [(other[0]-k, other[1]+k) for k in range(-10,11)]: dM[i][j] = 1 for j in surroundings: dM[j[0]][j[1]] = 2 if len(stuff): s = [i.split(" ") for i in stuff] for i in s: if i[0]=='L': g = [(int(i[1]),int(i[2]))] if i[0]=='M': g = getPath((int(i[1]),int(i[2])),i[3],2) if i[0]=='B': g = getPath((int(i[1]),int(i[2])),i[3],3) for j in g: dM[j[0]][j[1]] = 2 return dM input = sys.argv[1].splitlines() arena = input[0:10] stuff = input[12:] me = position(arena, "Y") other = position(arena,"X") distOther = distance(other) distMe = distance(me) dangM = dangerMap(stuff,other) if distOther[me[0]][me[1]] > 3: surroundings = [(i,j) for i in range(10) for j in range(10) if distMe[i][j]==1] choice = [k for k in surroundings if dangM[k[0]][k[1]] == 0] if len(choice)==0: choice = [k for k in surroundings if dangM[k[0]][k[1]] == 1] if len(choice)>1: K = [] for i in choice: K += [distOther[i[0]][i[1]]] choice = [choice[k] for k in range(len(choice)) if K[k] == min(K)] action = direction(me,choice[0]) else: diag = [(other[0]+i, other[1]+i) for i in [-2,2]]+[(other[0]-i, other[1]+i) for i in [-2,2]] if me in diag: action = 'M '+direction(me,other) else: distDiag = [] for i in diag: distDiag += [distMe[i[0]][i[1]]] choice = [diag[k] for k in range(len(diag)) if distDiag[k] == min(distDiag)] action = direction(me,choice[0]) sys.stdout.write(action) ``` ]
[Question] [ Trump needs the wall constructed and you are going to do it! To most efficiently build his wall I have created a simple, repeatable pattern for you to use: ``` __ __ | |_| | ___| |___ - - - - - - - - - - - - - - - - - - - ——————————————— ``` Trump will tell you how many wall segments he needs and you will build them to look just like this. Here is the pattern: ``` __ __ <-- 4-2-3-2-4 ' _ _ ' | |_| | <-- 3-1-2-1-1-1-2-1-3 ' | |_| | ' ___| |___ <-- 3-1-7-1-3 '_| |_' - - - - <-- 1-3-1-3-1-3-1-1 '- - - - ' - - - - - - - <-- 1-1-...-1-1 ' - -...- - ' - - - - - - - - <-- 1-1-...-1-1 '- - ... - -' ——————————————— <-- 15 Unicode U+2014 ``` Input will always be an integer >0. Test cases: ``` 1 __ __ | |_| | ___| |___ - - - - - - - - - - - - - - - - - - - ——————————————— 2 __ __ __ __ | |_| | | |_| | ___| |______| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - - —————————————————————————————— 5 __ __ __ __ __ __ __ __ __ __ | |_| | | |_| | | |_| | | |_| | | |_| | ___| |______| |______| |______| |______| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - - ——————————————————————————————————————————————————————————————————————————— ``` Since you need to do this fast, write the shortest program possible! If it helps, I wrote the challenge first, title last ;) [Answer] # CJam, 52 bytes ``` F,ri*"s@;b6(MBZF,fu"128b6b"_ |-—"f=N/ff=zN* ``` Includes a bunch of unprintable ASCII characters. The hexdump of the first string literal pushed is: ``` 01 73 06 40 3B 62 36 28 1E 4D 07 42 5A 14 1B 46 2C 66 75 ``` [Try it here!](http://cjam.aditsu.net/#code=%22%01s%06%40%3Bb6(%1EM%07BZ%14%1BF%2Cfu%22128b6b%22_%20%0A%7C-%E2%80%94%22f%3DN%2FFf*Ff%3Crif*N*&input=5) ## Explanation The above hexdump is interpreted as a base-128 number, then converted to base 6, to get this list: ``` [1 1 1 1 0 0 1 1 1 0 0 2 1 1 1 3 1 1 3 0 3 1 1 3 2 0 0 0 3 1 1 1 1 1 1 1 3 2 4 1 1 1 2 1 4 2 4 1 2 5] ``` To this, we apply the mapping `0 → _`, `1 → space`, `2 → \n`, `3 → |`, `4 → -`, `5 → —`. This gets us the string: ``` __ __ | |_| | ___| | - - - — ``` It consists of the "period" of each line; i.e. we can cycle the fifth line `" -"` to get `" - - - - - - - "`. Then, we execute this subprogram: ``` N/ Split into lines. Ff* Repeat each line 15 times (to cycle it). Ff< Take the first 15 chars of each line. rif* Repeat these chars input() times. N* Join lines. ``` (The new version does this in a slightly different way that I actually can't wrap my head around myself very well, because it uses `ff=`.) [Answer] # JavaScript (ES6), ~~116~~ 115 bytes ``` n=>"__ __ n| |_| | n| |___n - n- n -n—".split`n`.map(l=>l.repeat(15).slice(-15).repeat(n)).join` ` ``` *Saved a byte thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)!* ## Explanation Pretty much the same as [@Mauris' CJam method](https://codegolf.stackexchange.com/a/67463/46855), but without the character mapping. The wall parts are in the format: ``` __ __ | |_| | | |___ - - - — ``` because if you repeat each line 15 times you get: ``` ... __ __ __ __ __ __ ... | |_| | | |_| | | |_| | ... | |___| |___| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ——————————————— ``` and after slicing to just the last 15 characters you get: ``` __ __ | |_| | ___| |___ - - - - - - - - - - - - - - - - - - - ——————————————— ``` ### Ungolfed ``` n=> // array of wall line parts "__ __ n| |_| | n| |___n - n- n -n—".split`n` .map(l=> // for each wall line l.repeat(15) // repeat the line 15 times to create a complete wall line .slice(-15) // each wall piece is only 15 characters long .repeat(n) // repeat the wall n times ) .join` ` // output the resulting wall ``` ## Test ``` var solution = n=>"__ __ n| |_| | n| |___n - n- n -n—".split`n`.map(l=>l.repeat(15).slice(-15).repeat(n)).join` ` ``` ``` <input type="number" oninput="result.textContent=solution(+this.value)" /> <pre id="result"></pre> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes ``` •4H’*»È%f·ù„áÅ'4•4B3ÝJ"_ -|"‡8ô€ûvy¹×» ``` [Try it online!](https://tio.run/nexus/05ab1e#AUIAvf//4oCiNEjigJkqwrvDiCVmwrfDueKAnsOhw4UnNOKAojRCM8OdSiJfIC18IuKAoTjDtOKCrMO7dnnCucOXwrv//zM "05AB1E – TIO Nexus") ``` •4H’*»È%f·ù„áÅ'4• # Push '1724427993555739020619095486300160' 4B # Convert to base 4 (turns it into an 8x8 bitmap). 3ÝJ"_ -|"‡ # Replace digits 0-3 with _, , -, or |. 8ô # Split into pieces of 8. €û # Palindromize each piece. vy¹×» # For each row, dupe it n times (hori) and print it. ``` ***1724427993555739020619095486300160 converted to base-4:*** `11110011111311300003111121112111121212122121212100000000` ***11110011111311300003111121112111121212122121212100000000 with characters replaced:*** `__ | |____| - - - - - -- - - - ________` ***Previous pattern split into 8 pieces:*** ``` __ | |_ ___| - - - - - - - - - - ________ ``` ***Then you palindromize, and make it as long as needed through repetition.*** [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 135 bytes ~~Considerable golfing can be done.~~ Turn off pretty print and clear the output for a better result. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=b0hwQXRvUysqIiAtIjcnIG9uKyByUyIgLSIrKysrKysrKysrKysqIiAgICBfXyAgIF9fICAgICJqSCoiICAgfCAgfF98ICB8ICAgImpIKiJfX198ICAgICAgIHxfX18iakgqaiItICAgLSAgIC0gICAtICAiSCpTakgqbmpIKk0zNWon4oCU&input=MQoKMgoKMw). Also, use [this](http://conorobrien-foxx.github.io/Jolf/#code=b0hwQXRvUysqIiAtIjcnIG9uKyByUyIgLSIKb2pQIllPVVIgTlVNQkVSIEhFUkUhIgorKysrKysrKysrKysqIiAgICBfXyAgIF9fICAgICJqSCoiICAgfCAgfF98ICB8ICAgImpIKiJfX198ICAgICAgIHxfX18iakgqaiItICAgLSAgIC0gICAtICAiSCpTakgqbmpIKk0zNWon4oCU) to test an arbitrary number with more ease. ``` oHpAt++++++++++++*" __ __ "jH*" | |_| | "jH*"___| |___"jH*j"- - - - "H*+*" -"7' jH*"- - - - - - - -"jH*M35j'— ``` I will add an explanation later. [Answer] ## Haskell, ~~116~~ ~~118~~ 108 bytes ``` h n=take(n*15).cycle f n=unlines$h n.h 1<$>lines" __ __\n | |_| |\n___| |\n- \n -\n- \n—" ``` Usage example: ``` *Main> putStr $ f 3 __ __ __ __ __ __ | |_| | | |_| | | |_| | ___| |______| |______| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -- - - - - - - - ————————————————————————————————————————————— ``` This uses the same strategy as other answers here: each line of the wall is one cycle of the pattern, e.g. "- " (dash + space) for the second last line. Repeat each pattern, take 15 chars to get one wall segment, repeat again and take `15*n` chars for `n` segments. Edit: @Mauris found 10 bytes. Thanks! [Answer] # Bash + Linux utilities (~~247~~ ~~186~~ 180 bytes) ``` read x for i in {1..7} do tail -n +7 $0|gzip -dc|sed -nr "$i s/(.*)/$(printf '\\1%.0s' $(seq 1 $x))/p" done exit ˈ ELzVSPPPȏǑ \@\D񵠚k>ĄÚ ܋ɀÜ@r²uٞ5L! 󰰹͠ ``` Since unprintable characters have been generously used in the construction of the above script, here's a hexdump: ``` 00000000 72 65 61 64 20 78 0a 66 6f 72 20 69 20 69 6e 20 |read x.for i in | 00000010 7b 31 2e 2e 37 7d 0a 64 6f 0a 74 61 69 6c 20 2d |{1..7}.do.tail -| 00000020 6e 20 2b 37 20 24 30 7c 67 7a 69 70 20 2d 64 63 |n +7 $0|gzip -dc| 00000030 7c 73 65 64 20 2d 6e 72 20 22 24 69 20 73 2f 28 ||sed -nr "$i s/(| 00000040 2e 2a 29 2f 24 28 70 72 69 6e 74 66 20 27 5c 5c |.*)/$(printf '\\| 00000050 31 25 2e 30 73 27 20 24 28 73 65 71 20 31 20 24 |1%.0s' $(seq 1 $| 00000060 78 29 29 2f 70 22 0a 64 6f 6e 65 0a 65 78 69 74 |x))/p".done.exit| 00000070 0a 1f 8b 08 00 45 4c 7a 56 02 03 53 50 50 50 88 |.....ELzV..SPPP.| 00000080 8f 87 11 0a 5c 40 5c 03 44 f1 35 60 5a 81 2b 3e |....\@\.D.5`Z.+>| 00000090 1e c4 04 83 1a 20 9b 4b 17 c8 40 c2 5c 40 02 19 |..... .K..@.\@..| 000000a0 72 a1 72 75 b9 1e 35 4c 21 1e 01 00 f3 30 f0 f9 |r.ru..5L!....0..| 000000b0 8d 00 00 00 |....| 000000b4 ``` [Answer] # PowerShell, ~~103~~ 100 characters (105 bytes on disk, 102 w/o BOM) Pretty much the same as [@user81655 method](https://codegolf.stackexchange.com/a/67467/48455). ``` Param($c)' __ __n | |_| |n___| |n- n -n- n—'-split'n'|%{($_*15).Substring(0,15)*$c} ``` ### Ungolfed version ``` # Assign input to variable, Param($c) # Split array of wall parts and send them down the pipeline ' __ __n | |_| |n___| |n- n -n- n—' -split 'n' | ForEach-Object { # For each piece of wall ($_*15) # Repeat the line 15 times to create a complete wall line .Substring(0,15) # Each wall piece is only 15 characters long *$c # Repeat the wall n times } ``` ### Usage example ``` PS> .\TrumpWall.ps1 3 __ __ __ __ __ __ | |_| | | |_| | | |_| | ___| |______| |______| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -- - - - - - - - ————————————————————————————————————————————— ``` [Answer] # PHP 5.4, ( ~~182~~ 175 characters ) ``` foreach([' __ __ ',' | |_| | ','___| |___','- - - - ', ' - - - - - - - ','- - - - - - - -','———————————————'] as$d)echo str_repeat($d,$argv[1])."\n"; ``` Ungolfed Version ``` $s=[' __ __ ', ' | |_| | ', '___| |___', '- - - - ', ' - - - - - - - ', '- - - - - - - -', '———————————————' ]; foreach($s as $d) { echo str_repeat($d,$argv[1])."\n"; } ``` [ 7 characters saved by follow Blackhole suggestion. ] Another version with less bytes but more characters # PHP 5.4, ( 176 characters, 178 bytes ) ``` foreach([' __ __ ',' | |_| | ','___| |___','- - - - ',' - - - - - - - ','- - - - - - - -',str_repeat('—',15)] as$d)echo str_repeat($d,$argv[1])."\n"; ``` Just replace 15 instances of m-dash with one dash with str\_repeat function [Answer] # C, 148 bytes ``` #define q 16843009 i;p[]={-1,q*17,q*68,q*16,-8388417,8577152,3936000}; f(n){for(i=n*105;i--;i%(15*n)||puts(""))putchar(" -|_"[p[i/15/n]>>i%15*2&3]);} ``` Score excludes the unnecessary newline before `f(n)` which is included for clarity. the magic numbers in `p` encode the characters for the wall in base 4, which are reconstructed from the string `" -|_"` *0,1,2,3 respectively* `16843009` in hex is `0x1010101`. this is used for the lines with `-` in them. Because `_` is encoded by `3`, the bottom line can be encoded simply as `-1`, which is the number with all the bits set to `1`. [Answer] # [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), 121 bytes How I do this is by accessing each line one at a time input times, giving me stacks with the contents of each line. Then, I output a line at a time. If anyone wants me to give a more in-depth explanation, just ask (I'm currently opening presents, so...). ``` V0v7\[v1+v&V\[vDvm]a]y\[?Z] " __ __ " " | |_| | " "___| |___" 4\["- "]Xr 6mXr" " 8\["- "]X "—"e\D ``` [Try it online!](http://vitsy.tryitonline.net/#code=VjB2N1xbdjErdiZWXFt2RHZtXWFdeVxbP1pdCiIgICAgX18gICBfXyAgICAiCiIgICB8ICB8X3wgIHwgICAiCiJfX198ICAgICAgIHxfX18iCjRcWyItICAgIl1Ycgo2bVhyIiAiCjhcWyItICJdWAoi4oCUImVcRA&input=&args=NQ) [Answer] # PHP5.5, ~~182~~ ~~172 bytes~~ 168 bytes based on @kuldeep.kamboj's answer, which is actually 212 bytes the moment I write this but 182 characters. I wish the wall was a bit higher, then I could do some more optimisation ;-) this one is 168 bytes, thanks to @JörgHülsermann ``` $r='str_repeat';$d=$r(' -',7);$x=' ';foreach(["$x __ __ $x","$x| |_| |$x","___|$x$x |___","-$x-$x-$x- ","$d ","-$d",$r('—',15)] as$z){echo$r($z,$argv[1])." ";} ``` This one is 172 bytes ``` $r='str_repeat';$d=$r(' -',7);$x=$r(' ',3);foreach(["$x __ __ $x","$x| |_| |$x","___|$x$x |___","-$x-$x-$x- ","$d ","-$d",$r('—',15)] as$z){echo$r($z,$argv[1])." ";} ``` This one is 182 bytes :-) ``` $r='str_repeat';$d=$r(' -',7);$x=$r(' ',4);foreach([$x.'__ __'.$x,' | |_| | ','___| |___','- - - - ',$d.' ','-'.$d,$r('—',15)] as$z){echo $r($z,$argv[1]).' ';} ``` ungolfed version ``` $r='str_repeat'; $d=$r(' -',7); $x=$r(' ',3); $s=["$x __ __ $x", "$x| |_| |$x", "___|$x$x |___", "-$x-$x-$x- ", "$d ", "-$d", $r('—',15) ]; foreach($s as $z) { echo$r($z,$argv[1])." "; } ``` [Answer] ## Python 3, 132 122 120 bytes ``` def f(n):[print((s*15*n)[:15*n])for s in[' __ __ ',' | |_| | ','___| |___','- ', ' -', '- ', '—']] ``` Ungolfed: ``` def f(n): [print((s*15*n)[:15*n])for s in[' __ __ ', ' | |_| | ', '___| |___', '- ', ' -', '- ', '—']] ``` [Answer] # Python 2, (161 characters, 191 bytes) ``` x=input();a=[' __ __ ',' | |_| | ','___| |___','- - - - ',' - - - - - - - ','- - - - - - - -','———————————————'] for i in a:print i*x ``` [Answer] # Vim, 90 keys Assuming the input is in a buffer by itself the following will do the job (newline only for readability) ``` "aDi __ __ ^M | |_| | ^M___| |___^M^[ 4i- ^[xo-^[Y7P8JY2PxA ^[GVr^K-M^Vgg$d@aP ``` where `^M` is a `return`, `^[` is `escape`, `^K` is `ctrl+k` and `^V` is `ctrl+v`. This can very likely be golfed down quite a bit, as there might be much better ways of generating the pattern. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 32 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` →↔\ιδ»►℮⁰}▒║ΙOģΠp~⁵‘ ¾“ζ'¹*+'¹n* ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkyJXUyMTk0JTVDJXUwM0I5JXUwM0I0JUJCJXUyNUJBJXUyMTJFJXUyMDcwJTdEJXUyNTkyJXUyNTUxJXUwMzk5TyV1MDEyMyV1MDNBMHAlN0UldTIwNzUldTIwMTglMjAlQkUldTIwMUMldTAzQjYlMjclQjkqKyUyNyVCOW4q,inputs=Mg__,v=0.12) Explanation: ``` ...‘ ¾“ζ'¹*+'¹n* ...‘ push a string of the top 6 lines of 1 wall piece (no newlines) ¾“ push 8212 ζ convert to char from unicode codepoint '¹* repeat 15 times + add that to the previous compressed string '¹n split into lines with length 15 * repeat horizontally input times ``` [Answer] # Java 11, ~~236~~ ~~235~~ ~~231~~ 229 bytes ``` n->{String w[]={"","","","","","",""},t="- ".repeat(7);for(;n-->0;w[0]+="x __x__x ",w[1]+="x| |_| |x",w[2]+="___|xx |___",w[3]+="-x-x-x- ",w[4]+=" "+t,w[5]+=t+"-")w[6]+="_".repeat(15);return"".join("\n",w).replace("x"," ");} ``` [Try it online.](https://tio.run/##hVHBboMwDL3vKyyfEpWgdl3XA6J/sF52pCjKKN3oaKhCKEwt384cyLRJ0zTFQc57Nsl7PqqLEsf9@5CVqq7hSRX6egdQaJubg8py2LojwLM1hX6FjBEDmkcE9rQpaqtskcEWNMQwaLG5@to2SeMrYvAr@sDGJj/nyjIUgMGaR4fKsEgLsZlHbTJPZzF2IGVHQXybLEbkBnCT7tM57N5hUspb1xEspcOWDhPduGDsfHAI4MxSvqLczlAgb5NHyr/eQK2LFY9MbhujEcNjVWiGO039PKSiknxgSJciGYE86odokn5uXkqS7h24VMUeTmQgmwxIUlDcu/dR2/wUVo0Nz0TZUjMdZmzBRyP/5Jf/8GvuB/E9Bu@9l@ZPtTWBGymoU9Vo6x816QWdt76LuTR7UyaZ6tIf6ndzDOg3/r5@@AQ) NOTE: Java 11 isn't on TIO yet, so `String.repeat(int)` has been emulated with `repeat(String,int)` (for the same byte-count). **Explanation:** ``` n->{ // Method with integer parameter and String return-type String w[]={"","","","","","",""},// Start with seven empty rows t="- ".repeat(7); // Temp String to reduce bytes for(;n-->0; // Loop `n` amount of times: w[0]+="x __x__x ", // Append to the first row w[1]+="x| |_| |x", // Append to the second row w[2]+="___|xx |___", // Append to the third row w[3]+="-x-x-x- ", // Append to the fourth row w[4]+=" "+t, // Append to the fifth row w[5]+=t+"-") // Append to the sixth row w[6]+="_".repeat(15); // Append to the seventh row return"".join("\n",w) // Join all rows by new-lines .replace("x"," ");} // Then replace all "x" with three spaces, // and return the result ``` [Answer] # Powershell + file, 92 bytes save powershell to `get-trumpwall.ps1` (40 bytes) ``` param($c);gc f|%{-join($_*15)[0..14]*$c} ``` save data file with name `f` and data contains Unicode symbol and Linux LF only (52 bytes): ``` __ __ | |_| | ___| | - - - — ``` hex dump: ``` 0000000000: 20 20 20 20 5F 5F 20 20 │ 20 5F 5F 0A 20 20 20 7C __ __◙ | 0000000010: 20 20 7C 5F 7C 20 20 7C │ 0A 5F 5F 5F 7C 20 20 20 |_| |◙___| 0000000020: 20 20 20 20 7C 0A 2D 20 │ 20 20 0A 20 2D 0A 2D 20 |◙- ◙ -◙- 0000000030: 0A E2 80 94 │ ◙—›› ``` ## Usage example ``` PS> .\get-trumpwall.ps1 5 __ __ __ __ __ __ __ __ __ __ | |_| | | |_| | | |_| | | |_| | | |_| | ___| |______| |______| |______| |______| |___ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - -- - - - - - - - ——————————————————————————————————————————————————————————————————————————— ``` ]
[Question] [ Write a program or function which will provably **print all integers exactly once** given infinite time and memory. Possible outputs could be: ``` 0, 1, -1, 2, -2, 3, -3, 4, -4, … 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, … ``` This is not a valid output, as this would never enumerate negative numbers: ~~``` 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … ```~~ * The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses). * Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language. * Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language. * The separator must not change at any point. * The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. `,` is as valid as just `,`). * Any supported integer must eventually be printed after a finite amount of time. ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins ### Leaderboard ``` var QUESTION_ID=93441,OVERRIDE_USER=41723;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Haskell, 19 bytes ``` do n<-[1..];[1-n,n] ``` Produces the infinite list `[0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7...` Haskell allows infinite lists natively. Printing such a list will prints its elements one a time forever. [Answer] # Brainfuck, 6 bytes This makes use of the cell wrapping and prints all possible values. In Brainfuck, the native integer representation is by [byte value](https://codegolf.meta.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719). ``` .+[.+] ``` [Try it online!](http://brainfuck.tryitonline.net/#code=LitbLitd&input=&args=&debug=on) [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~14~~ 12 bytes ``` .(.\OSo;?.>~ ``` [Test it online!](http://ethproductions.github.io/cubix/?code=LiguXE9Tbzs/Lj5+&input=&speed=20) You can now adjust the speed if you want it to run faster or slower. ### How it works The first thing the interpreter does is remove all whitespace and pad the code with no-ops `.` until it fits perfectly on a cube. That means that the above code can also be written like this: ``` . ( . \ O S o ; ? . > ~ . . . . . . . . . . . . ``` Now the code is run. The IP (instruction pointer) starts out at the top left corner of the far left face, pointed east. Here's the paths it takes throughout the course of running the program: [![enter image description here](https://i.stack.imgur.com/XcEPV.png)](https://i.stack.imgur.com/XcEPV.png) The IP starts on the red trail at the far left of the image. It then runs `OSo;`, which does the following: * `O` Print the TOS (top-of-stack) as an integer. At the beginning of the program, the stack contains infinite zeroes, so this prints `0`. * `S` Push `32`, the char code for the space character. * `o` Print the TOS as a character. This prints a space. * `;` Pop the TOS. Removes the `32` from the stack. Now the IP hits the `?`, which directs it left, right, or straight depending on the sign of the TOS. Right now, the TOS is `0`, so it goes straight. This is the blue path; `.` does nothing, and the IP hits the arrow `>`, which directs it east along the red path again. `~` takes the bitwise NOT of the TOS, changing it to `-1`. Here the IP reaches the right edge of the net, which wraps it back around to the left; this again prints the TOS (this time `-1`) and a space. Now the IP hits the `?` again. This time, the TOS is `-1`; since this is negative, the IP turns left, taking the green path. The mirror `\` deflects the IP to the `(`, which decrements the TOS, changing it to `-2`. It comes back around and hits the arrow; `~` takes bitwise NOT again, turning the `-2` to `1`. Again the TOS is outputted and a space printed. This time when the IP hits the `?`, the TOS is `1`; since this is positive, the IP turns right, taking the yellow path. The first operator it encounters is `S`, pushing an extra `32`; the `;` pops it before it can cause any trouble. Now the IP comes back around to the arrow and performs its routine, `~` changing the TOS to `-2` and `O` printing it. Since the TOS is negative again, the IP takes the green path once more. And it just keeps cycling like that forever\*: red, green, red, yellow, red, green, red, yellow..., printing in the following cycle: ``` 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 ... ``` ## TL;DR This program repeatedly goes through these 3 easy steps: 1. Output the current number and a space. 2. If the current number is negative, decrement it by 1. 3. Take bitwise NOT of the current number. ### Non-separated version, 6 bytes ``` nO?~>~ ``` Removing the separation simplifies the program so much that it can fit onto a unit cube: ``` n O ? ~ > ~ ``` \* **Note**: Neither program is truly infinite, as they only count up to 252 (where JavaScript starts to lose integer precision). [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), ~~113~~ 3 bytes ``` 0000000: c4ceb9 ... ``` [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bW91dAoKam1wCiAgICBwdXQsICAgZndkIDEKICAgIHN1YiAxLCBwdXQKICAgIHJ3ZCAxLCBhZGQgMQ&input=) Check *Debug* to see the generated SBIN code. ### Sesos assembly The binary file above has been generated by assembling the following SASM code. ``` set numout jmp ; implicitly promoted to nop put, fwd 1 sub 1, put rwd 1, add 1 ; jnz (implicit) ``` [Answer] ## Python 2, 27 bytes ``` n=0 while 1:print~n,n,;n+=1 ``` Prints `-1 0 -2 1 -3 2 -4 3 ...` [Answer] # [MATL](http://github.com/lmendo/MATL), 8 bytes ``` 0`@_@XDT ``` This uses MATL's default data type, which is `double`, so it works up to `2^53` in absolute value. The output is ``` 0 -1 1 -2 2 ··· ``` [**Try it online!**](http://matl.tryitonline.net/#code=MGBAX0BYRFQ&input=) ### Explanation ``` 0 % Push 0 ` T % Do...while true: infinite loop @_ % Push iteration index and negate @ % Push iteration index XD % Display the whole stack ``` [Answer] # [Shakespeare Programming Language](http://shakespearelang.sourceforge.net/report/shakespeare/), 227 bytes ``` . Ajax,. Puck,. Act I: Scene I: [Enter Ajax,Puck] Puck:You ox! Ajax:Be me without myself.Open thy heart. Scene II: Ajax:Be thyself and ash.Open thy heart.Be me times you.Open thy heart.Be me times you.Let us return to scene II. ``` Obviously, this answer is nowhere near winning, but I liked that this is a use case that the SPL is comparatively well suited to. Explained: ``` // Everything before the first dot is the play's title, the parser treats it as a comment. . // Dramatis personae. Must be characters from Shakespeare's plays, again with a comment. Ajax,. Puck,. // Acts and scenes serve as labels. Like the whole play, they can have titles too, // but for the sake of golfing I didn't give them any. Act I: // This scene would've been named "You are nothing" Scene I: // Characters can talk to each other when on stage [Enter Ajax,Puck] // Characters can assign each other values by talking. Nice nouns = 1, ugly nouns = -1. Puck: You ox! // Assignment: $ajax = -1; Ajax: Be me without myself. // Arithmetic: $puck = $ajax - $ajax; Open thy heart. // Standard output in numerical form: echo $puck; // Working title "The circle of life" Scene II: // Poor Ajax always doing all the work for us Ajax: Be thyself and ash. // $puck = $puck + (-1); Open thy heart. // echo $puck; Be me times you. // $puck *= $ajax; (remember $ajax==-1 from scene I) Open thy heart. // echo $puck; Be me times you. // negate again Let us return to scene II. // infinite goto loop ``` As you can see when comparing this code to [my answer to the related challenge to count up forever](https://codegolf.stackexchange.com/questions/63834/count-up-forever/74426#74426) (i.e. print all natural numbers), SPL code length grows rather badly when problem size increases... [Answer] ## GNU sed, 189 + 2(rn flags) = 191 bytes This is most likely the longest solution, since sed has no integer type or arithmetic operations. As such, I had to emulate an **arbitrary size** increment operator using regular expressions only. ``` s/^/0/p : :i;s/9(@*)$/@\1/;ti s/8(@*)$/9\1/ s/7(@*)$/8\1/ s/6(@*)$/7\1/ s/5(@*)$/6\1/ s/4(@*)$/5\1/ s/3(@*)$/4\1/ s/2(@*)$/3\1/ s/1(@*)$/2\1/ s/0(@*)$/1\1/ s/^@+/1&/;y/@/0/ s/^/-/p;s/-//p t ``` **Run:** ``` echo | sed -rnf all_integers.sed ``` **Output:** ``` 0 -1 1 -2 2 -3 3 etc. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~9~~ 6 bytes Saved 3 bytes thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) ``` [ND,±, ``` [Try it online!](http://05ab1e.tryitonline.net/#code=W05ELMKxLA&input=) Prints `0, -1, 1, -2, 2 ...` separated by newlines. [Answer] # Brainfuck, 127 bytes ``` +[-->+>+[<]>-]>-->+[[.<<<]>>-.>>+<[[-]>[->+<]++++++++[-<++++++>>-<]>--[++++++++++>->-<<[-<+<+>>]]>+>+<]<<<[.<<<]>>.+.>[>>>]<<<] ``` [Try it online!](http://brainfuck.tryitonline.net/#code=K1stLT4rPitbPF0-LV0-LS0-K1tbLjw8PF0-Pi0uPj4rPFtbLV0-Wy0-KzxdKysrKysrKytbLTwrKysrKys-Pi08XT4tLVsrKysrKysrKysrPi0-LTw8Wy08KzwrPj5dXT4rPis8XTw8PFsuPDw8XT4-LisuPls-Pj5dPDw8XQ) Given an infinite tape would theoretically run forever. ``` 0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,-10,11,-11,12,-12,13,-13,14,-14,15,-15,16,-16,17,-17,18,-18,19,-19,20,-20,21,-21,22,-22,23,-23,24,-24,25,-25,26,-26,27,-27,28,-28,29,-29,30,-30,31,-31,32,-32,33,-33,34,-34,35,-35,36,-36,37,-37,38,-38,39,-39,40,-40,41,-41,42,-42,43,-43,44,-44,45,-45,46,-46,47,-47,48,-48,49,-49,50,-50,51,-51,52,-52,53,-53,54,-54,55,-55,56,-56,57,-57,58,-58,59,-59,60,-60,61,-61,62,-62,63,-63,64,-64,65,-65,66,-66,67,-67,68,-68,69,-69,70,-70,71,-71,72,-72,73,-73,74,-74,75,-75,76,-76,77,-77,78,-78,79,-79,80,-80,81,-81,82,-82,83,-83,84,-84,85,-85,86,-86,87,-87,88,-88,89,-89,90,-90,91,-91,92,-92,93,-93,94,-94,95,-95,96,-96,97,-97,98,-98,99,-99,... ``` **Uncompressed** ``` +[-->+>+[<]>-]>-->+ [ [.<<<]>>-.>>+< [[-]>[->+<] ++++++++[-<++++++>>-<]>-- [++++++++++>->-<<[-<+<+>>]]>+>+< ]<<< [.<<<]>>.+.> [>>>]<<< ] ``` [Answer] # R, ~~25~~ 24 bytes Golfed one byte thanks to @JDL. ``` repeat cat(-F,F<-F+1,'') ``` [Try it online!](https://tio.run/##K/r/vyi1IDWxRCE5sURD103HzUbXTdtQR11d8/9/AA "R – Try It Online") Example output: ``` 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 ``` [Answer] # [ShadyAsFuck](https://esolangs.org/wiki/ShadyAsFuck), 3 bytes ``` FVd ``` Explanation: ``` F prints the current cell value (0) and increases it by 1 V starts a loop and prints the current value d increases the current value and ends the loop ``` This makes use of the cell wrapping and prints all possible values. In SAF, the native integer representation is by [byte value](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values/4719#4719). [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/index.html), 565 bytes ``` even as a child, i had a dream i was a person in the movies it makes a lot of sense,i did think o,a million people was an image in mind i inspire folks to see a comedy o-m-g,how i am funny o,i mean i laugh,i cry,i scream,i am the funniest i made a comedy i was pretty proud of like a galaxy,i am given a star on a big California byway i make a movie,i make a sequel to a film i edited i had a vision i was a celeb;as in,an actor i had a dream i had a legacy i am asleep now i quietly awaken was it truth,or nothing but a fantasy world?o,a whole lot of doubts for me ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?XVFLdoQwDNtzCh@AOUEXXfQkhhjww4lpPkNz@qnNTNv3ugErcWRZojslwAII88YSRmDYMBgMmTAaOq/Lg3LRBJygbgRR70xl4AoRd/J70Qq6QKFUaGQIHKyR0z7oiBBZhO31QXoIPRmNK@JKzhg5hYGtKgdngkVlL1DVyMhlaaTQB73F2zpuepok07W0lOzQRkVyLhBs62Zwzt2@ZXb149Xqgr3dFFcbEzH80b72OzLV2u2nLdgag/DuPSsKfvUny8qXUVAqZlCvJl7hA4UXzYkN9hP7xX@9vSwaf2Ghz0biWyEsLG4sBa7kiz/9vnNxj34Mn0loerOS02gL4lw1D/@zeSKhFWcfbWdYhOiApKfhz8ZUpQOeJiINTmyR1dzqNmq2Jo9ohalVV4WpYulwapbw7rGdm1par2SDtqkWCyeb44/HhOEb) Outputs the following forever: `0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,-10,11,-11,`... [Answer] ## Batch, 56 bytes ``` @set n=0 :l @echo %n% @set/an+=1 @echo -%n% @goto l ``` Output: ``` 0 -1 1 -2 2 -3 ``` etc. Works up to 2147483647; 58 bytes if you want (-)2147483648 in the output: ``` @set n=0 :l @echo %n:-=% @set/an-=1 @echo %n% @goto l ``` 44 bytes if printing all supported positive integers, then all supported negative integers, then repeating endlessly, is acceptable: ``` @set n=0 :l @echo %n% @set/an+=1 @goto l ``` [Answer] # Bash + GNU utilities, 26 ``` seq NaN|sed '1i0 p;s/^/-/' ``` [Answer] ## bc, ~~17~~ 16 bytes **Edit:** 1 byte less thanks to [Digital Trauma](/users/11259/digital-trauma). Adding to the diversity of languages used so far, I present a bc solution that works with integers of **arbitrary size**. A newline is required after the code and it is counted in the bytes total. ``` for(;;){i;-++i} ``` In the first iteration `i` is not defined, but printing it gives 0 to my surprise. [Answer] # Java 7, ~~151~~ ~~134~~ ~~122~~ 118 bytes ``` import java.math.*;void c(){for(BigInteger i=BigInteger.ONE,y=i;;i=i.add(y))System.out.println(y.subtract(i)+"\n"+i);} ``` 12 bytes saved thanks to *@flawr* (and *@xnor* indirectly) # After rule change.. (~~59~~ ~~56~~ 63 bytes) ``` void c(){for(int i=0;i>1<<31;)System.out.println(~--i+"\n"+i);} ``` Since in Java `2147483647 + 1 = -2147483648`, we can't simply do `i++` and continue infinitely, since the challenge was to print all numbers once. With the above code with added range, it will instead print all integers from `-2147483648` to `2147483647` once each, in the following sequence: `0, -1, 1, -2, 2, -3, 3, -4, ..., 2147483646, -2147483647, 2147483647, -2147483648`. Thanks to *@OlivierGrégoire* for pointing out Java's behavior regarding `MIN_VALUE-1`/`MAX_VALUE+1`. [Try it here.](https://ideone.com/iz5mKG) **Ungolfed & test code:** [Try it here - resulting in runtime error](https://ideone.com/hDicLq) ``` import java.math.*; class M{ static void c() { for(BigInteger i = BigInteger.ONE, y = i; ; i = i.add(y)){ System.out.println(y.subtract(i) + "\n" + i); } } public static void main(String[] a){ c(); } } ``` **Output:** ``` 0 1 -1 2 -2 3 -3 4 -4 5 -5 ... ``` [Answer] # Powershell, ~~20~~ ~~19~~ 18 bytes Improved by stealing shamelessly from TimmyD's answer ``` 0;for(){-++$i;$i} ``` Output: ``` 0 -1 1 -2 2 -3 3 -4 4 ``` Old version: ``` for(){-$i;$i++;$i} ``` Not sure why tbh, but -*undeclared variable* (or -$null) is evaluted as 0, which saved us 2 bytes in this version... [Answer] # [DC (GNU or OpenBSD flavour)](https://rosettacode.org/wiki/Category:Dc) - 16 bytes This version is not shorter than the version below but should be able to run without the stack exploding in your PC. Nevertheless infinite large numbers will take up infinite amounts of memory... somewhen... Because of the `r` command it needs [GNU-DC or OpenBSD-DC](https://rosettacode.org/wiki/Category:Dc). ``` 0[rp1+45Pprdx]dx ``` Test: ``` $ dc -e '0[rp1+45Pprdx]dx' | head 0 -1 1 -2 2 -3 3 -4 4 -5 ``` --- # [DC](https://rosettacode.org/wiki/Category:Dc) - 16 bytes A little bit mean now. ;-) This version is abusing the stack length as counter while letting the stack grow. ``` z[pz45Ppllx]dslx ``` Test: ``` $ dc -e 'z[pz45Ppllx]dslx' | head 0 -1 1 -2 2 -3 3 -4 4 -5 ``` --- # [DC](https://rosettacode.org/wiki/Category:Dc) - 17 bytes Without dirty tricks. ``` 0[p1+45Ppllx]dslx ``` Test: ``` $ dc -e '0[p1+45Ppllx]dslx' | head 0 -1 1 -2 2 -3 3 -4 4 -5 ``` [Answer] # C# 74 bytes ``` class P{void Main(){for(var x=0m;;System.Console.Write(x+++","+-x+","));}} ``` --- ``` class P { void Main() { for(var x = 0m; ; System.Console.Write(x++ + "," + -x + ",")); } } ``` Output: ``` 0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6,-7,7,-8,8,-9,9,-10,10,... ``` Try it: [`dotnetfiddle.net`](https://dotnetfiddle.net/wwbWhi) (limited to 1000) [Answer] ## [Labyrinth](http://github.com/mbuettner/labyrinth), 9 bytes ``` !` \:" ( ``` [Try it online!](http://labyrinth.tryitonline.net/#code=IWAKXDoiCiAo&input=) This also works and is essentially the same: ``` " `:( \! ``` ### Explanation The control flow in this code is rather funny. Remember that the instruction pointer (IP) in a Labyrinth program follows the path of non-space characters and examines the top of the stack at any junction to decide which path to take: * If the top of the stack is positive, turn right. * If the top of the stack is zero, keep moving straight ahead. * If the top of the stack is negative, turn left. When the IP hits a dead end, it turns around (executing the command at the end only once). And the IP starts in the top left corner moving east. Also note that the stack is implicitly filled with an infinite amount of zeros to begin with. The program starts with this short bit: ``` ! Print top of stack (0). ` Multiply by -1 (still 0). : Duplicate. ``` Now the IP is at the relevant junction and moves straight ahead onto the `(` which decrements the top of the stack to `-1`. The IP hits a dead end and turns around. `:` duplicates the top of the stack once more. Now the top of the stack is negative and the IP turns left (west). We now execute one more iteration of the main loop: ``` \ Print linefeed. ! Print top of stack (-1). ` Multiply by -1 (1). : Duplicate. ``` This time, the top of the stack is positive, so IP turns right (west) and immediately executes another iteration of the main loop, which prints the `1`. Then after it is negated again, we hit the `:` with `-1` on the stack. This time the IP turns left (east). The `"` is just a no-op and the IP turns around in the dead end. `:` makes another copy and this time the IP turns south. `(` decrements the value to `-2`, the IP turns around again. With the top of the stack *still* negative, the IP now turns west on the `:` and does the next iteration of the main loop. In this way, the IP will now iterate between a tight loop iteration, printing a positive number, and an iteration that goes through both dead ends to decrement the value before printing a negative number. You might ask yourself why there's the `"` on the second line if it doesn't actually do anything: without it, when the IP reaches `:` on a negative value, it *can't* turn left (east) so it would turn right (west) instead (as a rule of thumb, if the usual direction at a junction isn't available, the IP will take the opposite direction). That means the IP would also never reach the `(` at the bottom and we couldn't distinguish positive from negative iterations. [Answer] # JavaScript (ES5), 32 31 30 29 bytes ``` for(i=0;;)[i++,-i].map(alert) ``` Prints `0 -1 1 -2 2 -3 3 -4 4 -5 5 ...` Saved 1 byte thanks to Patrick Roberts! Saved 2 bytes thanks to Conor O'Brien! [Answer] ## JavaScript, ~~29~~ 26 bytes ### Non-infinite version, 26 bytes *Saved 3 bytes thanks to ETHproductions* ``` for(n=1;;)alert([1-n,n++]) ``` will display all integers between -9007199254740991 and 9007199254740992. ### Infinite version (ES6), ~~114~~ 112 bytes *Saved 2 bytes thanks to ETHproductions* ``` for(n=[-1];1;alert(n[a||n.unshift(1),0]?(x=n.join``)+' -'+x:0))for(i=n.length,a=0;i--;a=(n[i]+=1-a)>9?n[i]=0:1); ``` will display all integers, given infinite time and memory. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~26~~ ~~22~~ ~~19~~ ~~16~~ 15 bytes Prints numbers separated by newlines. -3 bytes from @manatwork. -3 bytes from @m-chrzan. -1 bytes from @CGOneHanded via upgrading to Ruby 2.7+. ``` 0.step{p~_1,_1} ``` [Attempt This Online! (with a 5 ms timeout)](https://ato.pxeger.com/run?1=m72kqDSpcsFN3aLUwtLMolQF9ZLM3NT80hJ1rhAIw8oKKqJhoGdgYGCqqZCSv7S0JE3XYr2BXnFJakF1QV28oU68YS1EdHFqXgqEtWABhAYA) [Answer] # Java, ~~65~~ 54 bytes ``` i->{for(;;)System.out.print(i+++" "+(-i<i?-i+" ":"")); ``` # Ungolfed test code ``` public static void main(String[] args) { Consumer<Integer> r = i -> { for (;;) { System.out.print(i++ + " " + (-i < i ? -i + " " : "")); } }; r.accept(0); } ``` [Answer] **C#, 83 bytes** ``` void f(){for(decimal n=0;;n++){Console.Write(n+",");if(n>0)Console.Write(-n+",");}} ``` Ungolfed: ``` void f() { for (decimal n=0;;n++) { Console.Write(n + ","); if (n > 0) Console.Write(-n + ","); } } ``` Outputs: ``` 0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6....... ``` [Answer] # C# ~~86~~ 66 bytes New answer: ``` void b(){for(var i=0;;i++)Console.Write(i==0?","+i:","+i+",-"+i);} ``` Clear: ``` void b() { for(var i=0;;i++) Console.Write(i == 0 ? "," + i : "," + i + ",-" + i); } ``` Old answer (86 bytes): ``` void a(){Console.Write(String.Join(",",Enumerable.Range(int.MinValue,int.MaxValue)));} ``` Ungolfed: ``` void a() { Console.Write(String.Join(",", Enumerable.Range(int.MinValue, int.MaxValue))); } ``` [Answer] # J, 25 bytes ``` ([:$:1:`-`(1+-)@.*[echo)0 ``` Works on [the online site](http://tryj.tk/), but I can't verify it on computer yet. Prints numbers like: ``` 0 1 _1 2 _2 3 _3 4 ``` etc. [Answer] # Vim, 19 keystrokes ``` i0<cr>1<esc>qqYpi-<esc>p<C-a>@qq@q ``` Creates a recursive macro that duplicates a number, makes it negative, prints the original number again and increments it. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~19~~ 15 bytes ``` 1::1$-naonao1+! ``` This prints the following: ``` 0 1 -1 2 -2 3 -3 ``` ... and so on. The separator is a newline. Re-written after reading @xnor's answer to use a version of that algorithm. Starting at `n=1`, the program prints `1-n` and `n`, each followed by a newline, before incrementing `n`. After overflowing the maximum value the program will end with an error of `something smells fishy...`. Exactly when this will happen depends on the interpreter implementation. --- Previous version: ``` 0:nao0$-:10{0(?$~+! ``` Starting at 0, the program loops indefinitely. On each loop, the current value is printed along with a newline. It is then negated, and incremented if positive. ]
[Question] [ **Requirements:** * Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.) * Output the reverse of the input on stdout. **Example:** Input: ``` Quick brown fox He jumped over the lazy dog ``` Output: ``` god yzal eht revo depmuj eH xof nworb kciuQ ``` Shortest wins. Leaderboard: ``` var QUESTION_ID=242,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Bash - 7 ``` tac|rev ``` `tac` reverses line order, while `rev` reverses character order. [Answer] ## BrainFuck, 10 characters ``` ,[>,]<[.<] ``` Beats a good amount of answers for such a simple language. [Answer] ## Golfscript - 3 chars ``` -1% ``` obfuscated version is also 3 chars ``` 0(% ``` [here](http://www.golfscript.com/golfscript/builtin.html#%) is an explanation of how [%](http://www.golfscript.com/golfscript/builtin.html#%) works [Answer] ## C, 37 bytes ``` main(_){write(read(0,&_,1)&&main());} ``` [Answer] # Haskell - 21 ``` main=interact reverse ``` [Answer] # [Pancake Stack](http://esolangs.org/wiki/Pancake_Stack), ~~342~~ 316 bytes ``` Put this nice pancake on top! [] Put this pancake on top! How about a hotcake? If the pancake is tasty, go over to "". Put this delightful pancake on top! [#] Eat the pancake on top! Eat the pancake on top! Show me a pancake! Eat the pancake on top! If the pancake is tasty, go over to "#". Eat all of the pancakes! ``` It assumes that the input is terminated by a null character (`^@` on commandline). Example run, using the [interpreter](http://ideone.com/7sFFo0): ``` Put this nice pancake on top! [] Put this pancake on top! How about a hotcake? If the pancake is tasty, go over to "". Put this delightful pancake on top! [#] Eat the pancake on top! Eat the pancake on top! Show me a pancake! Eat the pancake on top! If the pancake is tasty, go over to "#". Eat all of the pancakes! ~~~~~~~~~~~~~~~~~~~~~~~~ Hello, World!^@ !dlroW ,olleH ``` [Answer] # Python, 41 40 bytes ``` import sys;print sys.stdin.read()[::-1] ``` 41 -> 40 - removed semicolon at end of program. Probably could be optimised! [Answer] ## APL, 2 ``` ⊖⍞ ``` Or CircleBar QuoteQuad if the characters don't come through, simply meaning: reverse keyboard character input. [Answer] ## Perl - 23 ``` print scalar reverse <> ``` [Answer] # C - 47 characters ``` main(c){if(c=getchar(),c>=0)main(),putchar(c);} ``` Note that this uses O(n) stack space. [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mzOjNNI9k2PbUkOSOxSENTJ9nO1kATLKepU1AKEU3WtK79/x8A) [Answer] ## Ruby - 19 characters ``` puts$<.read.reverse ``` [Answer] ### Windows PowerShell, 53 ~~54~~ ``` -join($x=[char[]]($($input)-join' '))[($x.count)..0] ``` **2011-01-30** (54) – First attempt **2011-01-30** (53) – Inline line breaks are fun. **2011-01-3-** (52) – Inlined variable assignments too. [Answer] # Binary Lambda Calculus - 9 bytes ``` 16 46 80 17 3E F0 B7 B0 40 ``` Source: <http://ioccc.org/2012/tromp/hint.html> [Answer] ## Perl 5.1, 14 ``` say~~reverse<> ``` [Answer] ## Befunge-93 - 11x2 (22 characters) ``` >~:0`v >:v ^ _$^,_@ ``` Tested using [this interpreter](http://www.quirkster.com/iano/js/befunge.html). [Answer] ## ><>, ~~16~~ 14 bytes ### -2 bytes by @JoKing two years (!) later, removes the extra -1 from reading input by shifting around the logic for halting. ``` i:0(7$. 0=?;ol ``` [Try it online!](https://tio.run/##S8sszvj/P9PKQMNcRY/LwNbeOj/n///yxKKknFQurqzivJTsxOKsFAA) Similar to the other ><> answer, this doesn't need to reverse the stack because of the way input is read in the first line. I'm actually not too sure whether or not this should be a suggestion for the other ><> answer, as it is quite different in appearance but similar in concept. The main difference is that my answer compares the input to 0, and if it is less (i.e. there is no input -- `i` returns -1 if there is no input) it jumps to (1,7), if not, (0,7). If it jumps to the former, it pops the top value (-1) and starts a print loop. If it jumps to the latter, it continues the input loop. # 11 bytes, exits with an error ### Courtesy of @JoKing ``` i:0(7$. ~o! ``` [Try it online!](https://tio.run/##S8sszvj/P9PKQMNcRY@rLl/x///yxKKknFQurqzivJTsxOKsFAA) I believe this is valid now via meta consensus. # Previous answer (14 bytes) ``` i:0(7$. ~ol0=?;! ``` [Answer] # [Fission](http://esolangs.org/wiki/Fission), ~~16~~ ~~14~~ 12 bytes ``` DY$\ ? [Z~K! ``` ## Explanation Control flow starts at `D` with a down-going `(1,0)` atom. The `?` reads from STDIN, one character at a time, setting the mass to the read character code and the energy to `0`. Once we hit EOF, `?` will instead set the energy to `1`. The `[` redirects the atom onto a `Z` switch. As long as we're reading characters, the energy will be `0`, so the atom is deflected to the upwards by the `Z`. We clone the atom, looping one copy back into the `?` to keep reading input. We increment the other copy's energy to `1` with `$` and push it onto the stack `K`. So the input loop is this: ``` DY$\ ? [Z K ``` When the energy is `1` due to EOF, the `Z` will instead let the atom pass straight through and decrement the energy to `0` again. `~` decrements the energy further to `-1`. Atoms with negative energy *pop* from the stack, so we can retrieve the characters in opposite order and print them with `!`. Now note that the grid is toroidal, so the atom reappears on the left edge of the same row. Remember that we incremented the energy of the pushed atoms earlier with `$`, so the atoms now have energy `1` just like the last output from `?` and will again pass straight through the `Z`. The path after EOF is therefore ``` ? [Z~K! ``` This loop on the bottom row continues until the stack is empty. When that happens, the atom is reflected back from the `K` and its energy becomes positive (`+1`). The `~` decrements it once more (moving to the left), so that we now hit the `Z` with non-positive energy. This deflects the atom downward, such that it ends up in the wedge of `Y` where it's stored, and because there are no more moving atoms, the program terminates. [Answer] ## [Stack Cats](https://github.com/mbuettner/stackcats), 7 bytes ``` <!]T[!> ``` [Try it online!](http://stackcats.tryitonline.net/#code=PCFdVFshPg&input=YWJjCmRlZgowMTI) There's a bunch of alternatives for the same byte count, most of which are essentially equivalent in how they work: ### Explanation A short Stack Cats primer: * Every program has to have mirror symmetry, and by mirroring any piece of code we obtain new code which computes the inverse function. Therefore the last three characters of the program above undo the first three, if it wasn't for the command in the centre. * The memory model is an infinite tape of stacks, which hold an implicit, infinite amount of zeros at the bottom. The initial stack has a `-1` on top of those zeros and then the input bytes on top of that (with the first byte at the very top and the last byte above the `-1`). * For output, we simply take the final stack, discard a `-1` at the bottom if there is one, and then print all the values as bytes to STDOUT. Now for the actual program: ``` < Move the tape head one stack left (onto an empty stack). ! Bitwise NOT of the implicit zero on top, giving -1. ] Move back to the original stack, taking the -1 with the tape head. We're now back to the original situation, except that we have a -1 on top. T Reverse the stack down to the -1 at the bottom. One of the reasons we needed to move a -1 on top is that T only works when the top of the stack is nonzero. Since the first byte of the input could have been a null-byte we need the -1 to make sure this does anything at all. [ Push the -1 to the stack on the left. ! Bitwise NOT, turning it back into 0 (this is irrelevant). > Move the tape head back onto the original stack. ``` Sp3000 set his brute force search to find all other 7-byte solutions, so here are some alternatives: ``` <]!T![> >![T]!< >[!T!]< ``` These three variants are essentially the same, except that they differ in when the bitwise NOT is computed and whether we use the empty stack on the left or on the right. ``` <]T!T[> >[T!T]< ``` Like I said in the explanation above, `T` doesn't do anything when the top of the stack is zero. That means we can actually put the `!` in the middle instead. That means the first `T` is a no-op, then we turn the zero on top into a `-1` and *then* then second `T` performs the reversal. Of course, this means that the final memory state has a `-1` on the stack next to the original one, but that doesn't matter since only the stack at the current tape head position affects the output. ``` <*ITI*> ``` This variant uses `*` (XOR 1) instead of `!`, so that it turns the zero into `+1`, and the `I` is a conditional push which pushes positive values and right, negative values left, and negates them in either case (such that we still end up with a `-1` on top of the original stack when we encounter `T`), so this ultimately works the same as the original `<!]T[!>` solution. [Answer] # PHP - ~~38~~ 17 characters ``` <?=strrev(`cat`); ``` [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 2 bytes (non-competing, FOG is newer than the challenge) ``` ^z ``` `^` gets input, `z` reverses, and implicit output. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 16 bytes ``` \{\{:}($.,.=;)$\ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/z@mOqbaqlZDRU9Hz9ZaUyXm/3/FlJyi/HCF/JycVA8A "Hexagony – Try It Online") Expanded: (Made with [Hexagony Colorer](https://github.com/Timwi/HexagonyColorer)) [![Reverse Cat in Hexagony](https://i.stack.imgur.com/R9eRu.png)](https://i.stack.imgur.com/R9eRu.png) Explanation: * Blue path moves IP to the red path * Red path moves "forward" in memory, reads a byte from STDIN, and increments it by 1, then checks if it's positive. The increment is so that the check will pass for all values including null bytes, and only fail for EOF (which Hexagony reads as negative 1) * Orange path is reached when the check fails, it reverses memory and then puts the IP on the green path * Green path goes back through the memory, attempting to divide 0 by each byte in memory. If the byte is empty, the end of the string has been reached, and the program crashes attempting to divide by zero. Otherwise it decrements the byte by 1 (to undo the increment from before) and prints it as a character. Alternative 21 byte solutions that properly terminate instead of crashing: `\{}\(//,;./')"<$|/$/@` and `},)<>'"<{\@..(_$.>.$;` [Answer] ## PHP, ~~82~~ ~~29~~ ~~24~~ ~~29~~ 28 characters ``` <?=strrev(fread(STDIN,2e9)); ``` 82 -> 29: The new line character is preserved when reversed with `strrev`. 29 -> 24: Uses the shortcut syntax now 24 -> 29: Now reads all lines instead of a single line [Answer] ## Befunge-98 - ~~11~~ 10 ``` #v~ :<,_@# ``` (Tested with cfunge) The variant below breaks the requirement slightly: it performs the task but outputs an infinite stream of null bytes afterwards (and doesn't terminate). ``` ~#, ``` The way it works is that it repeatedly reads input to the stack (`~`) one character at a time, jumping over (`#`) the comma. When EOF is reached, `~` acts as a reflector and the PC flips over, repeatedly popping and outputting a character (`,`) while jumping over (`#`) the tilde. [Answer] # Pyth - 3 ~~5~~ 4 bytes So, the original 3-char version didn't reverse the line order, just the lines. I then came up with this 5-char version: ``` _jb.z ``` I saved 1 byte thanks to @FryAmTheEggman to result it: ``` _j.z ``` [Live demo.](https://pyth.herokuapp.com/?code=_j.z&input=Quick+brown+fox%0AHe+jumped+over+the+lazy+dog&debug=1) ## Explanation: ``` .w read all the input into a list of strings j join (j) by using a newline character _ reverse the result Pyth implicitly prints the result on an expression ``` # Original (incorrect) solution: This technically doesn't count because Pyth was created in 2014, but it's still neat that it's tied with GolfScript. ``` #_w ``` ## Explanation: ``` # loop while no errors w read a line of input (throws an error on end-of-file or Control-C) _ reverse the input line Pyth implicitly prints the result on an expression ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix/), ~~9~~ 8 bytes Many thanks to Martin Ender for this golf: ``` w;o@i.?\ ``` [**See it work online!**](http://ethproductions.github.io/cubix/?code=dztvQGkuP1w=&input=T09QIDop&speed=1) This becomes the following cube (`>` indicates initial instruction pointer): ``` w ; o @ > i . ? \ . . . . . . . . . . . . . . . . ``` The first step of the program is to take all input. `i` puts 1 byte of input onto the stack. Unless the input is finished, `?` makes the IP turn right, wrapping around the cube until it reaches `w`, which sends it back to `i`. When input finishes, the `?` makes the IP head north, entering the output loop: * `o`: print the character at the top of the stack * `w`: 'sidestep' the pointer to the right * `;`: pop the character that was just printed * `\`: reflect the IP, sending it East * `?`: if there are chars left to print, turn right, back into the loop. The final time `?` is hit, when nothing is left on the stack, the IP continues forward instead: * `i`: take a byte of input. This will be `-1` as input has finished. * `\`: reflect the IP, sending it North, into: * `@`: terminate the program. --- # 9 byte solution ``` ..o;i?@!/ ``` [**See it work online!**](http://ethproductions.github.io/cubix/?code=Li5vO2k/QCEv&input=T09QIDop&speed=20) In cube form: ``` . . o ; > i ? @ ! / . . . . . . . . . . . . . . . ``` The first character encoutered is `i`, which takes a charcode of input. If there is no input left, this is `-1`. The next character is `?` - a decision. If the top of stack is positive, it turns right, wrapping around the cube until it hits `/` which sends it back to the `i`, creating an input loop. However, if the TOS is negative, input has finished, and so it turns left into the output loop. The output loop is simple. `o;` outputs and pops the TOS. The first time this is run, `-1` is the top of stack, but does not map to a character and is therefore ignored. `/` reflects the IP to move left, where it encounters `!@` - which terminates the program if the stack is empty. Otherwise, the IP continues, hitting `?` again - because the stack is not empty, the TOS must be a charcode, all of which are positive1, so this makes the IP turn right and continue the output loop. --- *1 Both solutions assume that the input will not contain null bytes.* [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), 12 bytes ``` i=)!4*0.l&o@ ``` [Try it online!](https://tio.run/##Ky/NLSgt/v8/01ZT0UTLQC9HLd/h///A0szkbIWkovzyPIW0/Aouj1SFLKDC1BSF/LLUIoWSjFSFnMSqSoWU/HQA "Wumpus – Try It Online") --- [Martin's answer](https://codegolf.stackexchange.com/a/155862/21487) showcases Wumpus' triangular grid control flow well, but I thought I'd give this challenge a try with a one-liner. The easier to understand version (one byte longer) is: ``` i=)!8*0.;l&o@ ``` which works like so: ``` [Input loop] i Read a byte of input (gives -1 on EOF) =)! Duplicate, increment then logical not (i.e. push 1 if EOF, else 0) 8* Multiply by 8 (= x) 0 Push 0 (= y) . Jump to (x, y), i.e. (8, 0) if EOF else (0, 0) to continue input loop [Output] ; Pop the extraneous -1 at the top from EOF l&o Output <length of stack> times @ Terminate the program ``` Now let's take a look at the golfed version, which differs in the middle: ``` i=)!4*0.l&o@ ``` The golfed version saves a byte by not needing an explicit command `;` to pop the extraneous -1. On EOF, this program jumps to `(4, 0)` instead of `(8, 0)` where it executes `4*0.` again — except this time the extraneous -1 is on top! This causes us to jump to `(-4, 0)`, which due to wrapping is the same as `(8, 0)` for this grid, getting us where we want whilst consuming the extraneous value at the same time. [Answer] ## [Wumpus](https://github.com/m-ender/wumpus), ~~13~~ 11 bytes ``` )?\;l&o@ =i ``` [Try it online!](https://tio.run/##Ky/NLSgt/v9f0z7GOkct34HLNvP//8DSzORshaSi/PI8hbT8Ci6PVIUsoLrUFIX8stQihZKMVIWcxKpKhZT8dAA "Wumpus – Try It Online") ### Explanation Since Wumpus is a stack-based language, the basic idea is to read all STDIN to the stack and then just print the entire stack from top to bottom. The interesting part here is the control flow through the grid. To understand the control flow, we need to look at the actual triangular grid layout: [![enter image description here](https://i.stack.imgur.com/H9yh1.png)](https://i.stack.imgur.com/H9yh1.png) The IP starts in the top left corner going east. We can see that there's a loop through the group of six cells on the left, and a branch off of the `\`. As you might expect, the loop reads all input, and the linear section at the end writes the result back to STDOUT. Let's look at the loop first. It makes more sense to think of the first `)?\` as not being part of the loop, with the actual loop beginning at the `i`. So here's the initial bit: ``` ) Increment an implicit zero to get a 1. ?\ Pop the 1 (which is truthy) and execute the \, which reflects the IP to move southwest. ``` Then the loop starts: ``` i Read one byte from STDIN and push it to the stack (or -1 at EOF). Note that Wumpus's grid doesn't wrap around, instead the IP reflects off the bottom edge. = Duplicate the byte we've read, so that we can use it for the condition later without losing it. ) Increment. EOF becomes zero (falsy) and everything else positive (truthy). ?\ If the incremented value is non-zero, execute the \ again, which continues the loop. Otherwise (at EOF), the \ is skipped and the IP keeps moving east. ``` That leaves the linear section at the end: ``` ; Get rid of the -1 we read at EOF. l Push the stack depth, i.e. the number of bytes we've read. &o Print that many bytes. ``` [Answer] # [Wren](https://github.com/munificent/wren), ~~40~~ 33 bytes After I discovered a really clever trick... ``` Fn.new{|a|System.write(a[-1..0])} ``` [Try it online!](https://tio.run/##Ky9KzftfllikkKhg@98tTy8vtby6JrEmuLK4JDVXr7wosyRVIzFa11BPzyBWs/Z/ol5yYk6OhpKhkbGJkuZ/AA) ## [Wren](https://github.com/munificent/wren), 53 bytes Wren has no STDIN functions... I guess I will just be using a function instead of hard-coding the value and using a snippet (which is a bit risky). ``` Fn.new{|a|[-1..-a.count].each{|w|System.print(a[w])}} ``` [TIO](https://tio.run/##Ky9KzftfllikkFaal6xg@98tTy8vtby6JrEmWtdQT083US85vzSvJFYvNTE5o7qmvCa4srgkNVevoCgzr0QjMbo8VrO29j9Is15yYk6OhpJnXkFpiZLmfwA) ## Explanation ``` Fn.new{ Create a new anonymous function (because Wren has no input functions) |a| With the parameter a [-1..-a.count] Generate the range [-1,-2,...,len(a-1),len(a)] .each Pass this range to the given function: {|w| Take one parameter a System.print(a[w])}} And output it to STDOUT ``` ## Wren, 54 bytes ``` Fn.new{|a| for(i in-1..-a.count)System.write(a[i]) } ``` [TIO](https://tio.run/##Ky9KzftfllikkFaal6xg@98tTy8vtby6JrGGKy2/SCNTITNP11BPTzdRLzm/NK9EM7iyuCQ1V6@8KLMkVSMxOjNWk6v2P0ivXnJiTo6GkmdeQWmJkuZ/AA) [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 31 bytes ``` a:-get0(C),C>0,a,put(C);!. :-a. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/P9FKNz21xEDDWVPH2c5AJ1GnoLQEyLFW1OOy0k3U@/8/sDQzOVshqSi/PE8hLb@CyyNVIas0tyA1RSG/LLVIoSQjVSEnsapSISU/HQA "Prolog (SWI) – Try It Online") [Answer] ## PHP - 44 characters ``` <?=strrev(file_get_contents('php://stdin')); ``` ]
[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 7 years ago. [Improve this question](/posts/51109/edit) I have noticed that there are a disproportionate number of computer languages based on English. I propose to fix this by translating existing computer languages into foreign languages! * Pick a computer language that uses English keywords/functions * Pick any natural\* language other than English * Write a program that translates its own source code or any other program written using the same subset of keywords/functions into the other language * Post the source code and the output (the translated code) Start your post with something like: ## BASIC, French or ## BASIC, French - FONDAMENTAL You don't have to translate the language name if you don't want to, it's just for fun! You don't have to translate all the keywords/functions in your chosen language, just the ones you actually use in your source code. For instance, PHP has thousands so you definitely don't need to translate them all! Also, if you use any comments please do your best to translate them too! After your program has finished there should be no recognisable English words, unless they are appropriate for the foreign language. Words in strings should be translated too (meaning your translated program won't work on English source code anymore, even if it could be run!). Hopefully your program will make some sort of sense to a programmer who speaks the other language! For example, `if () {} elseif () {} else {}` might become `si () {} sinonsi () {} sinon {}` in French! If you were translating Perl's `elsif` into French, maybe you'd drop the second `n` the way the second `e` is dropped in English: `sinosi`. In French *else* would more likely be *autre* but the alternative *sinon* (*or else*, *otherwise*) feels nicer to me! Be creative! Try to capture the feel of both the computer and natural languages! Languages like Brainfuck, CJam, etc. that don't have English tokens can't be used. Languages like BASIC or COBOL are much more suitable. Use meaningful variable names and translate them too unless your language doesn't support variable names that can be English words. You may post multiple answers, one for each combination of computer/natural language. You may not use a library or an external tool to do the translation! Your code should do the translation itself, not call something else that does translation! This is not Code Golf! If your program takes any input it must only be its own source code, if it reads from the disc it can only be the source file, etc. \* For the purposes of this challenge I will consider Esperanto, Lojban, Volapük, Interlingua, etc. as natural languages. You may not invent your own language for this challenge! I have added a rule to prevent explicit quines. You may pick any subset of keywords/functions - even all of them - to translate. Your program must be able to translate itself as a minimum, i.e. if your original source includes the word `print` then adding `print(42)` anywhere to the input code (not your program itself) should still produce the correct results. For example: ``` function translate() { ... } print(translate()); ``` might become ``` fonction traduire() { ... } imprimer(traduire()); ``` If the *input* is changed to ``` print(42); function translate() { ... } print(translate()); print(42); ``` the *output* should then become ``` imprimer(42); fonction traduire() { ... } imprimer(traduire()); imprimer(42); ``` [Answer] # Python, [Koine Greek](http://en.wikipedia.org/wiki/Koine_Greek) - Πύθων My favorite programming language, in my favorite foreign language--perfect! And it doesn't hurt that [the name is already Greek](http://en.wikipedia.org/wiki/Python_(mythology)). The translator program in Python 3 (thank goodness for native Unicode support): ``` with open(__file__, encoding="utf-8") as f: code = f.read() replacements = [ ("print", "γραψάτω"), ("input", "λαβέτω"), ("read", "ἀναγνώτω"), ("open", "ἀνεῳξάτω"), ("file", "βιβλίον"), ("import", "εἰσενεγκάτω"), ("encoding", "τύπος"), ("code", "λόγοι"), ("replacements", "νεόλογοι"), ("location", "τόπος"), ("old", "παλαιόν"), ("new", "νέον"), ("find", "εὑρέτω"), ("replace", "ἀλλαξάτω"), ("for", "ἕκαστον"), ("while", "ἐν τῷ"), ("elif", "εἰ δὲ"), ("if", "εἰ"), ("else", "εἰ δὲ μή"), ("is not", "οὐκ ἔστιν"), ("is", "ἔστιν"), ("not in", "οὐκ ἐν"), ("in", "ἐν"), ("and", "καὶ"), ("or", "ἢ"), ("not", "οὐ"), ("with", "μετὰ"), ("as", "ὡς"), ("re", "ῥλ"), ("sys", "σύς"), (":", "·"), ("ph", "φ"), ("th", "θ"), ("ch", "χ"), ("ps", "ψ"), ("a", "α"), ("b", "β"), ("c", "κ"), ("d", "δ"), ("e", "ε"), ("f", "φ"), ("g", "γ"), ("h", ""), ("i", "ι"), ("j", "ι"), ("k", "κ"), ("l", "λ"), ("m", "μ"), ("n", "ν"), ("o", "ο"), ("p", "π"), ("r", "ρ"), ("s ", "ς "), ("s.", "ς."), ("s,", "ς,"), ("s·", "ς·"), ("s", "σ"), ("t", "τ"), ("u", "ου"), ("v", "ου"), ("w", "ου"), ("x", "ξ"), ("y", "υ"), ("z", "ζ") ] for old, new in replacements: if old == "for": location = 0 while old in code[location:]: location = code.find(old, location) if code[location+3] != '"': location = code.find("in", location) code = code[:location] + "ἐκ" + code[location+2:] else: location += 1 code = code.replace(old, new) print(code) ``` Results of running the code on itself (with the big translation list redacted): ``` μετὰ ἀνεῳξάτω(__βιβλίον__, τύπος="ουτφ-8") ὡς φ· λόγοι = φ.ἀναγνώτω() νεόλογοι = [ ("γραψάτω", "γραψάτω"), ("λαβέτω", "λαβέτω"), ("ἀναγνώτω", "ἀναγνώτω"), ... ] ἕκαστον παλαιόν, νέον ἐκ νεόλογοι· εἰ παλαιόν == "ἕκαστον"· τόπος = 0 ἐν τῷ παλαιόν ἐν λόγοι[τόπος·]· τόπος = λόγοι.εὑρέτω(παλαιόν, τόπος) εἰ λόγοι[τόπος+3] != '"'· τόπος = λόγοι.εὑρέτω("ἐν", τόπος) λόγοι = λόγοι[·τόπος] + "ἐκ" + λόγοι[τόπος+2·] εἰ δὲ μή· τόπος += 1 λόγοι = λόγοι.ἀλλαξάτω(παλαιόν, νέον) γραψάτω(λόγοι) ``` Koine Greek is 2000 years old, so it was fun translating programming terms. Here's a few of my favorites: * *βιβλίον* = "scroll" (`file`) * *γραψάτω* = "write" (`print`) * *λαβέτω* = "take" (`input`) * *εἰσενεγκάτω* = "bring in" (`import`) * *τύπος* = "pattern, type" (`encoding`) * *λόγοι*/*νεόλογοι* = "words"/"new words" (`code`/`replacements`) * *ἕκαστον... ἐκ* = "each... from" (`for ... in`) * *εἰ... εἰ δὲ... εἰ δὲ μή* = "if... but if... but if not" (`if ... elif ... else`) * *ἐν τῷ* literally means "in the," but in certain contexts it can be an idiom for "when, while" * "Regular expression" became *ῥήμα λογικόν*, "rational/reasonable saying"; thus, the abbreviation `re` is *ῥλ* Most of the words can be also found by searching on [Wiktionary](http://wiktionary.org). Some other salient features: * English programming uses a bunch of imperative verbs (`print`, `read`, `replace`). I suspect the ancient Greeks would feel a bit foolish talking to the computer like this, so I made them all *third-person imperatives*: "it must print," "it must read," "it must replace." * Greek punctuation is a bit different from English. I didn't go overboard with this, because I'm not sure what to replace the square brackets and underscores with, but I did swap out colons for *ano teleia* or "high period" (`·`). * For words that aren't in the list, I made sure to transliterate all the lowercase letters too. There isn't always a straight one-to-one correspondence; so for example, `utf` turns into `ουτφ`--which sounds about like "ootf" if you try to pronounce it. This still leaves a lot to be desired grammar-wise. Greek is a much more highly inflected language than English, and my code isn't nearly sophisticated enough to get all the cases and numbers right. For example, *ἕκαστον παλαιόν, νέον ἐκ νεόλογοι* ought to read *ἐκ νεολόγ**ων***, with the object of the preposition in the genitive case. However, I'm not about to put *that* much time into this! The look is sufficiently Greek (at least to the untrained eye) and the high periods add a nice touch. All in all, I'm pretty satisfied with the results. [Answer] # [Chicken](http://esolangs.org/wiki/chicken), Chinese - 鸡 Chicken is much harder to use than I thought. There isn't a trailing newline. But the final `chicken` is just for marking the end of this program, which can be replaced with an empty line. I'm using [this interpreter](https://github.com/igorw/chicken-php), which prints an extra newline and cannot be suppressed. So the output have one more line than the original, and that can make a Chicken program broken. I hope this won't make it invalid. It used some tricks like getting an empty strings from index -1 of the input, and detecting EOF by comparing with empty strings. I also used the `compare` command to discard unused items in the stack, without caring about the type. They may not work in other interpreters. And it prints the string as UTF-8 bytes, where other interpreters may support printing Unicode characters directly. ``` chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken ``` Use this command to run this code: ``` bin/chicken "`<file`" <file ``` where weirdly enough, the first `file` is for input, and the second is for the code. The output (Chinese don't use spaces between words): ``` 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡 鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡鸡 鸡鸡鸡鸡鸡鸡 鸡 ``` This program replaces `h` with `鸡`, leaves newlines unaffected, and ignores everything else. And as you see, it can translate every valid Chicken program. [Answer] # C++, Latin - C Plus Plus Yes, that is an actual translation of the language name. They didn't have the plus sign, but they gave us the word plus. ``` #include <iostream> #include <fstream> using namespace std; static const char *reposita[][2] = { // Miscellanea {"iostream", "flumineie"}, // flumine inducto/educto {"ofstream", "fluminele"}, // flumine limae educto {"ifstream", "flumineli"}, // flumine limae inducto {"fstream", "fluminel"}, // flumine limae {"std", "cmn"}, // commune {"string", "chorda"}, {"empty", "vacuum"}, {"size_t", "t·amplitudinis"}, // typus amplitudinis {"find", "inveni"}, {"npos", "posn"}, // positio nulla {"replace", "repone"}, {"main", "primor"}, {"getline", "sumelinea"}, // Verba gravia {"alignas", "ordinasicut"}, {"alignof", "ordinatio"}, {"asm", "cns"}, // construere {"auto", "modic"}, // modicum {"bool", "bic"}, // bicolore {"break", "erumpe"}, {"case", "res"}, {"catch", "capta"}, {"char16_t", "t·littxvi"}, // typus litterae {"char32_t", "t·littxxxii"}, {"wchar_t", "t·littv"}, // typus litterae vadae {"char", "litt"}, // littera {"class", "genus"}, {"constexpr", "dictconst"}, // dictum constante {"const_cast", "funde·const"}, // funde constanter {"continue", "procede"}, {"decltype", "typusdecl"}, // typus declaratus {"default", "ultima"}, {"delete", "abole"}, {"for", "cum"}, {"if", "si"}, {"struct", "aedif"}, // aedificium {"double", "biforme"}, {"do", "fac"}, {"dynamic_cast", "funde·impigre"}, {"else", "alter"}, {"explicit", "directum"}, {"export", "expone"}, {"false", "falsum"}, {"float", "nante"}, {"friend", "amicus"}, {"goto", "iad"}, {"inline", "inlinea"}, {"long", "longum"}, {"mutable", "mutabilis"}, {"namespace", "plaganominis"}, {"new", "novum"}, {"noexcept", "sineexim"}, // sine eximibus {"nullptr", "sgnnullum"}, // signum nullum {"private", "privata"}, {"protected", "protecta"}, {"public", "publica"}, {"register", "arca"}, {"reinterpret_cast", "funde·revertendo"}, {"return", "redde"}, {"short", "breve"}, {"unsigned", "sine·signo"}, {"signed", "signo"}, {"sizeof", "amplitudo"}, {"static_assert", "autuma·stant"}, // autuma stantiter {"static_cast", "funde·stant"}, // funde stantiter {"static", "stante"}, {"switch", "furca"}, {"template", "exemplar"}, {"this", "hoc"}, {"thread_local", "ligamen·loci"}, {"throw", "iaci"}, {"true", "verum"}, {"try", "tempta"}, {"typedef", "typumdes"}, // typum designa {"typeid", "signumtypi"}, {"typename", "nomentypi"}, {"union", "iugum"}, {"using", "utente"}, {"virtual", "virtuale"}, {"void", "inane"}, {"volatile", "volatilis"}, {"while", "dum"}, // Numeri {"0", "nihil"}, {"1", "i"}, {"2", "ii"}, // Miscellanea {"length", "longitudo"} }; static void omnesRepone(string& chorda, const string& de, const string& ad) { if (de.empty()) { return; } size_t index = 0; while ((index = chorda.find(de, index)) != string::npos) { chorda.replace(index, de.length(), ad); index += ad.length(); } } int main(int narg, const char * varg[]) { ifstream limaArchetypa(varg[1]); ofstream limaTransferenda(varg[2]); int elementa = sizeof(reposita) / sizeof(reposita[0]); string linea; while (getline(limaArchetypa, linea)) { for (int index = 0; index < elementa; ++index) { omnesRepone(linea, reposita[index][0], reposita[index][1]); } limaTransferenda << linea << "\n"; } return 0; } ``` Notes: * Takes an input and output file on the command line * Translates all keywords * I did not write a full Roman numeral parser but I thought it would be nice to at least translate the numbers present in the source (*nihil*, *i*, and *ii*) * I did not go down the road of translating symbols used in C++, which seemed like a huge can of worms * The keywords `const`, `enum`, `int`, and `operator` do not change. They now stand for *constante*, *enumeratum*, *integrum*, and *operator*. * I didn't think the Romans would be into `_` as a word divider, so I used [interpuncts](http://en.wikipedia.org/wiki/Interpunct). * The translation is very dumb and inefficient, ignoring word boundaries etc. Output: ``` #include <flumineie> #include <fluminel> utente plaganominis cmn; stante const litt *reposita[][ii] = { // (redacta) }; stante inane omnesRepone(chorda& chorda, const chorda& de, const chorda& ad) { si (de.vacuum()) { redde; } t·amplitudinis index = nihil; dum ((index = chorda.inveni(de, index)) != chorda::posn) { chorda.repone(index, de.longitudo(), ad); index += ad.longitudo(); } } int primor(int narg, const litt * varg[]) { flumineli limaArchetypa(varg[i]); fluminele limaTransferenda(varg[ii]); int elementa = amplitudo(reposita) / amplitudo(reposita[nihil]); chorda linea; dum (sumelinea(limaArchetypa, linea)) { cum (int index = nihil; index < elementa; ++index) { omnesRepone(linea, reposita[index][nihil], reposita[index][i]); } limaTransferenda << linea << "\n"; } redde nihil; } ``` [Answer] ## JavaScript (NodeJS) - Hebrew My method for encoding is pretty similar to [DLosc's Python program](https://codegolf.stackexchange.com/a/51112/32376): It reads the source code, has a list of tokens, and runs find-and-replace. ``` var file_system = require('fs'); file_system.readFile(__filename, function(error,code){ if (error) {throw error;} code = code.toString(); var words = { 'var': 'מש׳', 'file_system': 'מערכת_קבצים', 'require': 'דרוש', 'fs': 'מ״ק', 'readFile': 'קראקובץ', 'filename': 'שםקובץ', 'function': 'תפקיד', 'error': 'שבוש', 'code': 'צופן', 'if': 'אם', 'throw': 'זרוק', 'toString': 'למחרוזת', 'words': 'מילים', 'word': 'מילה', 'for': 'לכל', 'in ': 'ב', 'replace': 'החלף', 'RegExp': 'ביטס״ד', 'console': 'מסוף', 'log': 'רשום', 'new (.+)\\(': '$1 חדש(', 'g': 'ע׳', '\'': '', ';': '׃' }, word; for (word in words) { code = code.replace(new RegExp(word,'g'), words[word]); } console.log(code); }); ``` This gives the following output: ``` מש׳ מערכת_קבצים = דרוש(מ״ק)׃ מערכת_קבצים.קראקובץ(__שםקובץ, תפקיד(שבוש,צופן){ אם (שבוש) {זרוק שבוש׃} צופן = צופן.למחרוזת()׃ מש׳ מילים = { מש׳: מש׳, מערכת_קבצים: מערכת_קבצים, דרוש: דרוש, מ״ק: מ״ק, קראקובץ: קראקובץ, שםקובץ: שםקובץ, תפקיד: תפקיד, שבוש: שבוש, צופן: צופן, אם: אם, זרוק: זרוק, למחרוזת: למחרוזת, מילים: מילים, מילה: מילה, לכל: לכל, ב: ב, החלף: החלף, ביטס״ד: ביטס״ד, מסוף: מסוף, רשום: רשום, (.+)\\(: $1 חדש חדש(, ע׳: ע׳, \: , ׃: ׃ }, מילה׃ לכל (מילה במילים) { צופן = צופן.החלף(ביטס״ד חדש(מילה,ע׳), מילים[מילה])׃ } מסוף.רשום(צופן)׃ })׃ ``` Unfortunately, SE doesn't seem to like RTL text. I tried to manually wrap the above code block in `<pre dir="rtl">`, but it just got stripped. :( The code is actually supposed to look like this: (screenshot of gedit) ![code properly displayed with RTL formatting](https://i.stack.imgur.com/vaPK1.png) Some things to note about the Hebrew text: * The Hebrew method for abbreviations (which is used multiple times in this code) is to use a single quote mark at the end for abbreviating a single word, and double quotes before the last letter if it is multiple words. For a single word, we have `var`, which i translated as `מש'`, short for "משתנה" (variable). `fs`, an acronym of "file system", got translated as `מ"ק`, the first letters of "מערכת קבצים", seen above. * Hebrew doesn't have capital/lowercase letters. A few letters have normal/final forms (כמנפצ and ךםןףץ, respectively), but that's it. So in mashup words like "readFile" and "filename", i also mashed together the Hebrew "קרא קובץ" and "שם קובץ", despite the second one ending up with a final letter in the middle of the word. * The above does not apply to `toString`. In Hebrew, prepositions are single letters which get prepended to the word. So, if "string" is "מחרוזת", "to string" is "למחרוזת". That's also why in the `for..in` block, the `in` token includes the space, so that it gets attached to the next word (`word in words` becomes `מילה במילים`). * I am unable to reproduce this from my computer, but when i went to [translate.google.com](https://translate.google.com/) from my iPad and put in `regex`, it gave me back ביטוי סדיר, which literally means "ordered expression". Wow! I abbreviated it down to ביטס"ד, as JS's `RegExp` is. * The `g` regex flag i translated as ע', which stands for עולמי, global. * Note the complicated regex form for replacing `new`. That's because in Hebrew, adjectives (such as "new" - "חדש") come after the noun (such as regex). So, instead of `new RegExp()`, it would be "RegExp [that is] new()`. * I removed the quote marks, as they don't exist in classic Hebrew. It certainly makes the grammar a lot harder! I'm still not sure whether or not it was a good decision. * It looks like i'm replacing all the terminating semicolons with colons. It's actually a [U+05C3](https://codepoints.net/U+05C3) [SOF PASUQ](https://en.wikipedia.org/wiki/Sof_passuk), a punctuation mark which ends a verse in the Bible. This code certainly does not translate every valid JS program. In fact, it probably only translates this one. But that's good enough for this challenge. ;) By the way, if you're interested in Hebrew, come follow the Hebrew.SE proposal (and vote on questions with a score of <10)! [![Stack Exchange Q&A site proposal: Hebrew Language](https://i.stack.imgur.com/oyTLL.png)](https://area51.stackexchange.com/proposals/75348/hebrew-language?referrer=wuY59ZBbDdHCzDHh3-zT9w2) (source: [stackexchange.com](http://area51.stackexchange.com/ads/proposal/75348.png)) [Answer] # Perl, PigLatin - erlPay First, the actual program is very short, so to demonstrate how it behaves for longer sections of text I included some Perl Poetry as a further example of the input/output. Since the poetry is included after the **END** line it doesn't actually get executed. The actual algorithm is pretty straight forward: * Split input into tokens on word boundaries * For any word with at least two alpha characters translate into Pig Latin + Find the leading consonants in the word + move them to the end and put the 'ay' suffix on them * Print everything. Non alpha input (and single-characters) are not translated --- ``` #!/usr/bin/perl while (<>) { print map { s/^([bcdfghjklmnpqrstvwxyz]*)([a-z]+)/$2$1ay/i if /[a-z][a-z]/i; $_ } split(/\b/); } __END__ # listen (a perl poem) # Sharon Hopkins # rev. June 19, 1995 # Found in the "Perl Poetry" section of the Camel book APPEAL: listen(please, please); open yourself, wide; join (you, me), connect (us, together), tell me. do something if distressed; @dawn, dance; @evening, sing; read (books, $poems, stories) until peaceful; study if able; write me if-you-please; sort your feelings, reset goals, seek (friends, family, anyone); do*not*die (like this) if sin abounds; keys (hidden), open (locks, doors), tell secrets; do not, I-beg-you, close them, yet. accept (yourself, changes), bind (grief, despair); require truth, goodness if-you-will, each moment; select (always), length (of-days) ``` --- Output from running the program on itself: ``` #!/usray/inbay/erlpay ilewhay (<>) { intpray apmay { s/^([zbcdfghjklmnpqrstvwxyay]*)([a-z]+)/$2$1ay/i ifay /[a-z][a-z]/i; $_ } itsplay(/\b/); } __END__ # istenlay (a erlpay oempay) # aronShay opkinsHay # evray. uneJay 19, 1995 # oundFay inay ethay "erlPay oetryPay" ectionsay ofay ethay amelCay ookbay APPEALay: istenlay(easeplay, easeplay); openay ourselfyay, ideway; oinjay (ouyay, emay), onnectcay (usay, ogethertay), elltay emay. oday omethingsay ifay istressedday; @awnday, anceday; @eveningay, ingsay; eadray (ooksbay, $oemspay, oriesstay) untilay eacefulpay; udystay ifay ableay; itewray emay ifay-ouyay-easeplay; ortsay ouryay eelingsfay, esetray oalsgay, eeksay (iendsfray, amilyfay, anyoneay); oday*otnay*ieday (ikelay isthay) ifay insay aboundsay; eyskay (iddenhay), openay (ockslay, oorsday), elltay ecretssay; oday otnay, I-egbay-ouyay, oseclay emthay, etyay. acceptay (ourselfyay, angeschay), indbay (iefgray, espairday); equireray uthtray, oodnessgay ifay-ouyay-illway, eachay omentmay; electsay (alwaysay), engthlay (ofay-aysday) ``` [Answer] # Visual Basic .Net, Persian I chose a verbose language so it would be harder. Turns out, I didn't have to change the grammar. The Persian form of the code is just as verbose. ``` Imports System.Collections.Generic Module Translator Sub Main() Dim translation As New Dictionary(Of String, String) With translation .Add("imports", "وارد‌کردن") .Add("system", "دستگاه") .Add("collections", "مجموعه") .Add("generic", "عمومی") .Add("module", "واحد") .Add("translator", "مترجم") .Add("sub", "زیرروال") .Add("main", "اصلی") .Add("dim", "بعد") .Add("translation", "ترجمه") .Add("new", "نو") .Add("dictionary", "دیکشنری") .Add("string", "رشته") .Add("with", "با") .Add("add", "افزودن") .Add("end", "پایان") .Add("file", "فایل") .Add("create", "درست‌کردن") .Add("readalltext", "خواندن‌کل‌متن") .Add("writealltext", "نوشتن‌کل‌متن") .Add("io", "ورودی‌خروجی") .Add("for", "برای") .Add("each", "هر") .Add("next", "بعدی") .Add("tolower", "به‌کوچک") .Add("key", "کلید") .Add("value", "مقدار") .Add("replace", "جایگزین‌کردن") .Add("code", "کد") .Add("dispose", "رها‌کردن") .Add("and", "و") .Add("andalso", "و‌همچنین") .Add("byte", "بیت") .Add("call", "صدا‌کردن") .Add("case", "صورت") .Add("catch", "گرفتن") .Add("object", "شئ") .Add("integer", "عدد") .Add("if", "اگر") .Add("then", "سپس") .Add("goto", "برو‌به") .Add("true", "درست") .Add("false", "نادرست") .Add("exit", "خارج‌شدن") .Add("loop", "حلقه") .Add("function", "تابع") .Add("nothing", "هیچی") .Add("else", "در‌غیر‌این‌صورت") .Add("try", "سعی‌کردن") .Add("or", "یا") .Add("orelse", "یا") .Add("as", "به‌عنوان") .Add("of", "از") .Add("in", "در") End With Dim code As String = System.IO.File.ReadAllText("Code.txt").ToLower() For Each k In translation code = code.Replace(k.Key, k.Value) Next System.IO.File.Create("Persian.txt").Dispose() System.IO.File.WriteAllText("Persian.txt", code) End Sub End Module ``` The result requires a right-to-left text editor. I couldn't get it to display properly here. But if I **have** to display it, here it is. Here's a picture: ![code](https://i.stack.imgur.com/eVmIk.png) Note: It reads from a file named Persian.txt and outputs to code.txt. I couldn't get the console window to write or read Persian without it turning into question marks. (e.g. a four letter word would turn into ????) Note: If you connect words with each other in Persian, it will be almost unreadable, because letters connect to each other and get a different form. So I had to separate them with spaces which resulted in words having spaces. A word like Imports turned into وارد کردن which is two words. [Answer] # Java, German - Java This program is really straight forward. It just reads the file given as the first argument and replaces all occurrences of an English word with the respective German translation. I am using a regular expression with two groups (`([^a-zA-Z\\d:])*`) to match individual items prepended/followed by a non-alphanumeric character. This solved the issue with overlapping translations (eng. `List` -> ger. `Liste` but then `Liste` would become `Listee`). Using `$1`/`$2` adds those characters back and leaves us with a translated source code. ## Update 1: Use abbreviations like `ea`, `nbea` etc. to follow naming conventions of Java in German. ## Update 2: Now uses a third component in the array to break after their first replacement. This is necessary for my cheaty declination/conjugation approach. `class`/`Klasse` is female in German and `void`/`nichts` is neutral, so I just skipped replacing the latter and replaced later. Another edit is `new`'s translation turned to `neue` because I only use it on `String`, which is female. ## Update 3: Properly deal with capitalization by adding case sensitive regular expressions. ``` import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.regex.Pattern; public class Main { public static void main(String[] args) throws IOException { String[][] array = new String[][]{ {"import", "importiere", ""}, {"public", "öffentliche", "break"}, {"public", "öffentliches", ""}, {"class", "klasse", ""}, {"Main", "Haupt", ""}, {"main", "haupt", ""}, {"static", "statisches", ""}, {"void", "nichts", ""}, {"String", "Zeichenkette", ""}, {"args", "argumente", ""}, {"throws", "wirft", ""}, {"IOException", "EAAusnahme", ""}, {"FileSystems", "Dateisysteme", ""}, {"new", "neue", ""}, {"Files", "Dateien", ""}, {"readAllBytes", "leseAlleBytes", ""}, {"getDefault", "holeStandard", ""}, {"getPath", "holePfad", ""}, {"array", "ansammlung", ""}, {"replaceFirst", "ersetzeErstes", ""}, {"find", "finde", ""}, {"out", "ausgabe", ""}, {"println", "druckeZeile", ""}, {"pattern", "muster", ""}, {"Pattern", "Muster", ""}, {"compile", "zusammenstellen", ""}, {"matcher", "abgleicher", ""}, {"util", "werkzeug", ""}, {"regex", "regaus", ""}, {"while", "solange", ""}, {"nio", "nbea", ""}, {"io", "ea", ""}, {"for", "für", ""}, {"if", "wenn", ""}, {"equals", "gleicht", ""}, {"break", "unterbrechen", ""} }; String str = new String(Files.readAllBytes(FileSystems.getDefault().getPath(args[0]))); for (String[] s : array) { Pattern pattern = Pattern.compile("(^|[^a-zA-Z\\d]+)" + s[0] + "([^a-zA-Z\\d]+)"); while(pattern.matcher(str).find(0)) { str = pattern.matcher(str).replaceFirst("$1" + s[1] + "$2"); if(s[2].equals("break")) { break; } } } System.out.println(str); } } ``` This outputs the following to `System.out`: ``` importiere java.ea.EAAusnahme; importiere java.nbea.file.Dateisysteme; importiere java.nbea.file.Dateien; importiere java.werkzeug.regaus.Muster; öffentliche klasse Haupt { öffentliches statisches nichts haupt(Zeichenkette[] argumente) wirft EAAusnahme { Zeichenkette[][] ansammlung = neue Zeichenkette[][]{ {"importiere", "importiere", ""}, {"öffentliches", "öffentliche", "unterbrechen"}, {"öffentliches", "öffentliches", ""}, {"klasse", "klasse", ""}, {"Haupt", "Haupt", ""}, {"haupt", "haupt", ""}, {"statisches", "statisches", ""}, {"nichts", "nichts", ""}, {"Zeichenkette", "Zeichenkette", ""}, {"argumente", "argumente", ""}, {"wirft", "wirft", ""}, {"EAAusnahme", "EAAusnahme", ""}, {"Dateisysteme", "Dateisysteme", ""}, {"neue", "neue", ""}, {"Dateien", "Dateien", ""}, {"leseAlleBytes", "leseAlleBytes", ""}, {"holeStandard", "holeStandard", ""}, {"holePfad", "holePfad", ""}, {"ansammlung", "ansammlung", ""}, {"ersetzeErstes", "ersetzeErstes", ""}, {"finde", "finde", ""}, {"ausgabe", "ausgabe", ""}, {"druckeZeile", "druckeZeile", ""}, {"muster", "muster", ""}, {"Muster", "Muster", ""}, {"zusammenstellen", "zusammenstellen", ""}, {"abgleicher", "abgleicher", ""}, {"werkzeug", "werkzeug", ""}, {"regaus", "regaus", ""}, {"solange", "solange", ""}, {"nbea", "nbea", ""}, {"ea", "ea", ""}, {"für", "für", ""}, {"wenn", "wenn", ""}, {"gleicht", "gleicht", ""}, {"unterbrechen", "unterbrechen", ""} }; Zeichenkette str = neue Zeichenkette(Dateien.leseAlleBytes(Dateisysteme.holeStandard().holePfad(argumente[0]))); für (Zeichenkette[] s : ansammlung) { Muster muster = Muster.zusammenstellen("(^|[^a-zA-Z\\d]+)" + s[0] + "([^a-zA-Z\\d]+)"); solange(muster.abgleicher(str).finde(0)) { str = muster.abgleicher(str).ersetzeErstes("$1" + s[1] + "$2"); wenn(s[2].gleicht("unterbrechen")) { unterbrechen; } } } System.ausgabe.druckeZeile(str); } } ``` If you have any improvements on the code or the translation, let me know and I see if I can implement them. [Answer] # Julia, [Tatar](http://en.wikipedia.org/wiki/Tatar_language) - Julia This uses the unofficial Latin-based Zamanälif alphabet for İdel-Ural Tatar, established in 2001. However, in 2002, the Russian Federation struck down [Tatarstan](http://en.wikipedia.org/wiki/Tatarstan)'s motion to make Zamanälif the official alphabet for the Tatar language, criminalizing the official use of any alphabet other than Cyrillic. In the past century, there have been 5 alphabets for the Tatar language: * İske imlâ, a variant of the Arabic alphabet, 1870s-1920s * Yaña imlâ, another Arabic variant, 1920s and 30s * Jaᶇalif, a variant of the Latin alphabet, 1930s * Cyrillic, conversion mandated by Joseph Stalin, 1940s-present * Zamanälif, unofficial, 2001-present I've opted for Zamanälif because I think my grandpa would be disappointed if I used Cyrillic. His first language is Tatar and and having been born in the 1920s, he learned to read and write in the iske imlâ alphabet. English: ``` function translate(source) words = Dict([("function", "funktsiya"), ("if", "ägär"), ("else", "başkaça"), ("elif", "başägär"), ("end", "axır"), ("for", "saen"), ("print", "bastırırga"), ("english", "ingliz"), ("tatar", "tatarça"), ("translate", "tärcemä"), ("words", "süzlär"), ("replace", "alıştıru"), ("Dict", "Süzlek"), ("keys", "açkıçlär"), ("get", "alırga"), ("readall", "ukırgaböten"), ("source", "çıganak")]) tatar = readall(source) for english = keys(words) tatar = replace(tatar, english, get(words, english, "")) end tatar end print(translate("tatar.jl")) ``` Tatar: ``` funktsiya tärcemä(çıganak) süzlär = Süzlek([("funktsiya", "funktsiya"), ("ägär", "ägär"), ("başkaça", "başkaça"), ("başägär", "başägär"), ("axır", "axır"), ("saen", "saen"), ("bastırırga", "bastırırga"), ("ingliz", "ingliz"), ("tatarça", "tatarça"), ("tärcemä", "tärcemä"), ("süzlär", "süzlär"), ("alıştıru", "alıştıru"), ("Süzlek", "Süzlek"), ("açkıçlär", "açkıçlär"), ("alırga", "alırga"), ("ukırgaböten", "ukırgaböten"), ("çıganak", "çıganak")]) tatarça = ukırgaböten(çıganak) saen ingliz = açkıçlär(süzlär) tatarça = alıştıru(tatarça, ingliz, alırga(süzlär, ingliz, "")) axır tatarça axır bastırırga(tärcemä("~/tatarça.jl")) ``` I took a couple liberties to make the translation a little cleaner. For example, `for` became `saen`, which translates more literally to "each." I also didn't abbreviate `Süzlek`, which means "dictionary." `ukırgaböten`, my translation for `readall`, is `ukırga` (read) + `böten` (all/every). `başägär`, my translation for `elseif`, is `baş` (an abbreviation of `başkaça`, meaning "else/otherwise") + `ägär` (if). If anyone on PPCG knows Tatar, you likely know more than I do. Any suggestions would be welcome. [Answer] ## [Rust](http://rust-lang.org/), [Belarusian](http://en.wikipedia.org/wiki/Belarusian_language) (Ржа) Program: ``` #![feature(non_ascii_idents)] use std::io::stdin; use std::io::Read; static ЗАМЕНЫ: &'static [(&'static str, &'static str)] = &[ ("match", "супастаўленьне"), (" if ", " калі "), ("else", "інакш"), (" as ", " як "), ("panic!", "паніка!"), ("assert!", "праверыць!"), ("box ", "пак "), ("break", "перапыніць"), ("continue", "працягнуць"), ("fn ", "фн "), ("extern", "знешняе"), (" for ", " кожная "), (" in ", " ў "), ("impl ", " увасобіць "), ("let ", "хай "), ("loop ", "цыкл "), ("once", "аднойчы"), ("pub ", "адкр"), ("return", "выйсці"), ("super", "бацькоўскі_модуль"), ("unsafe ", "непяспечнае "), (" where", " дзе"), ("while", "пакуль"), ("use ", "вык "), ("mod ", "модуль "), ("trait ", "рыса "), ("struct ", "структура "), ("enum ", "пералік"), ("type ", "тып "), ("move ", "перанесьці"), ("mut ", "зьмян "), ("ref ", "спасыл "), ("static ", "статычнае "), ("const ", "нязменнае "), ("crate ", "скрыня "), ("Copy", "МожнаКапіяваць"), ("Send", "МожнаПерадаваць"), ("Sized", "МаеПамер"), ("Sync", "БяспечнаНаПатокі"), ("Drop", "МаеЗавяршальнік"), ("FnMut", "ЯкЗьмяняемаяФункцыя"), ("FnOnce", "ЯкАднаразоваяФункцыя"), ("Fn", "ЯкФункцыя"), ("macro_rules!", "новы_макрас!"), ("alignof", "выраўненьеяку"), ("become", "стала"), ("do ", "рабі"), ("offsetof", "пазіцыяяку"), ("priv", "прыватнае"), ("pure", "чыстае"), ("sizeof", "памер_ад"), ("typeof", "тып_ад"), ("unsized", "безпамеравы"), ("yield", "вырабіць"), ("abstract", "абстрактны"), ("virtual", "віртуальны"), ("final", "канчатковае"), ("override", "перавызначыць"), ("macro", "макрас"), ("Box", "Каробка"), ("ToOwned", "МожнаНабыцьУладара"), ("Clone", "МожнаКланаваць"), ("PartialOrd", "МаеЧастковыПарадак"), ("PartialEq", "ЧастковаПараўнальны"), ("Eq", "Параўнальны"), ("Ord", "МаеПарадак"), ("AsRef", "МожнаЯкСпасылку"), ("AsMut", "МожнаЯкЗьмяняемые"), ("Into", "МожнаУ"), ("From", "МожнаЗ"), ("Default", "МаеЗначеньнеПаЗмаўчаньні"), ("Extend", "Пашырыць"), ("IntoIterator", "МожнаУПаўторнік"), ("DoubleEndedIterator", "ДвубаковыПаўторнік"), ("ExactSizeIterator", "ПаўторнікЗДакладнымПамерам"), ("Iterator", "Паўторнік"), ("Option", "Недакладна"), ("Some", "Ёсць"), ("None", "Нічога"), ("Result", "Вынік"), ("Ok", "Ок"), ("Err", "Збой"), ("SliceConcatExt", "АбянднальнікЛустаў"), ("ToString", "УРадок"), ("String", "Радок"), ("Vec", "Вэктар"), ("vec!", "вэкрар!"), ("self", "сам"), ("true", "так"), ("false", "не"), ("feature", "магчымасьць"), ("main", "галоўная"), ("replace", "замяніць"), ("iter","пераліч"), ("print!","друк!"), ("println!","друкрад!"), ("stdin","звыч_уваход"), ("stdout","звыч_выхад"), ("stderr","звыч_павед"), ("Read", "Чытальнік"), ("Write", "Пісальнік"), ("read_to_string", "чытаць_у_радок"), ("to_string", "у_радок"), ("std", "стд"), ("io", "ув"), ("non_ascii_idents", "ідентыфікатары_з_юнікоду"), ("str", "радок"), ]; fn main() { let mut зьмест : String = "".to_string(); match stdin().read_to_string(&mut зьмест) { Ok(_) => (), Err(памылка) => panic!(памылка), } for замена in ЗАМЕНЫ.iter() { зьмест = зьмест.replace(замена.0, замена.1); } println!("{}", зьмест); } ``` Output: ``` #![магчымасьць(ідентыфікатары_з_юнікоду)] вык стд::ув::звыч_уваход; вык стд::ув::Чытальнік; статычнае ЗАМЕНЫ: &'статычнае [(&'статычнае радок, &'статычнае радок)] = &[ ("супастаўленьне", "супастаўленьне"), (" калі ", " калі "), ("інакш", "інакш"), (" як ", " як "), ("паніка!", "паніка!"), ("праверыць!", "праверыць!"), ("пак ", "пак "), ("перапыніць", "перапыніць"), ("працягнуць", "працягнуць"), ("фн ", "фн "), ("знешняе", "знешняе"), (" кожная ", " кожная "), (" ў ", " ў "), (" увасобіць ", " увасобіць "), ("хай ", "хай "), ("цыкл ", "цыкл "), ("аднойчы", "аднойчы"), ("адкр", "адкр"), ("выйсці", "выйсці"), ("бацькоўскі_модуль", "бацькоўскі_модуль"), ("непяспечнае ", "непяспечнае "), (" дзе", " дзе"), ("пакуль", "пакуль"), ("вык ", "вык "), ("модуль ", "модуль "), ("рыса ", "рыса "), ("структура ", "структура "), ("пералік", "пералік"), ("тып ", "тып "), ("перанесьці", "перанесьці"), ("зьмян ", "зьмян "), ("спасыл ", "спасыл "), ("статычнае ", "статычнае "), ("нязменнае ", "нязменнае "), ("скрыня ", "скрыня "), ("МожнаКапіяваць", "МожнаКапіяваць"), ("МожнаПерадаваць", "МожнаПерадаваць"), ("МаеПамер", "МаеПамер"), ("БяспечнаНаПатокі", "БяспечнаНаПатокі"), ("МаеЗавяршальнік", "МаеЗавяршальнік"), ("ЯкЗьмяняемаяФункцыя", "ЯкЗьмяняемаяФункцыя"), ("ЯкАднаразоваяФункцыя", "ЯкАднаразоваяФункцыя"), ("ЯкФункцыя", "ЯкФункцыя"), ("новы_макрас!", "новы_макрас!"), ("выраўненьеяку", "выраўненьеяку"), ("стала", "стала"), ("рабі", "рабі"), ("пазіцыяяку", "пазіцыяяку"), ("прыватнае", "прыватнае"), ("чыстае", "чыстае"), ("памер_ад", "памер_ад"), ("тып_ад", "тып_ад"), ("безпамеравы", "безпамеравы"), ("вырабіць", "вырабіць"), ("абстрактны", "абстрактны"), ("віртуальны", "віртуальны"), ("канчатковае", "канчатковае"), ("перавызначыць", "перавызначыць"), ("макрас", "макрас"), ("Каробка", "Каробка"), ("МожнаНабыцьУладара", "МожнаНабыцьУладара"), ("МожнаКланаваць", "МожнаКланаваць"), ("МаеЧастковыПарадак", "МаеЧастковыПарадак"), ("ЧастковаПараўнальны", "ЧастковаПараўнальны"), ("Параўнальны", "Параўнальны"), ("МаеПарадак", "МаеПарадак"), ("МожнаЯкСпасылку", "МожнаЯкСпасылку"), ("МожнаЯкЗьмяняемые", "МожнаЯкЗьмяняемые"), ("МожнаУ", "МожнаУ"), ("МожнаЗ", "МожнаЗ"), ("МаеЗначеньнеПаЗмаўчаньні", "МаеЗначеньнеПаЗмаўчаньні"), ("Пашырыць", "Пашырыць"), ("МожнаУПаўторнік", "МожнаУПаўторнік"), ("ДвубаковыПаўторнік", "ДвубаковыПаўторнік"), ("ПаўторнікЗДакладнымПамерам", "ПаўторнікЗДакладнымПамерам"), ("Паўторнік", "Паўторнік"), ("Недакладна", "Недакладна"), ("Ёсць", "Ёсць"), ("Нічога", "Нічога"), ("Вынік", "Вынік"), ("Ок", "Ок"), ("Збой", "Збой"), ("АбянднальнікЛустаў", "АбянднальнікЛустаў"), ("УРадок", "УРадок"), ("Радок", "Радок"), ("Вэктар", "Вэктар"), ("вэкрар!", "вэкрар!"), ("сам", "сам"), ("так", "так"), ("не", "не"), ("магчымасьць", "магчымасьць"), ("галоўная", "галоўная"), ("замяніць", "замяніць"), ("пераліч","пераліч"), ("друк!","друк!"), ("друкрад!","друкрад!"), ("звыч_уваход","звыч_уваход"), ("звыч_выхад","звыч_выхад"), ("звыч_павед","звыч_павед"), ("Чытальнік", "Чытальнік"), ("Пісальнік", "Пісальнік"), ("чытаць_у_радок", "чытаць_у_радок"), ("у_радок", "у_радок"), ("стд", "стд"), ("ув", "ув"), ("ідентыфікатары_з_юнікоду", "ідентыфікатары_з_юнікоду"), ("радок", "радок"), ]; фн галоўная() { хай зьмян зьмест : Радок = "".у_радок(); супастаўленьне звыч_уваход().чытаць_у_радок(&зьмян зьмест) { Ок(_) => (), Збой(памылка) => паніка!(памылка), } кожная замена ў ЗАМЕНЫ.пераліч() { зьмест = зьмест.замяніць(замена.0, замена.1); } друкрад!("{}", зьмест); } ``` [Answer] # [DogeScript](https://dogescript.com), Spanish - El Código del Perro DogeScript is interpreted to JavaScript, so any valid JS is valid DogeScript. The translation I've given here actually encompasses the entire [keyword specification](https://github.com/dogescript/dogescript/blob/master/LANGUAGE.md) (plus some more to cover the words used in the program). "English": ``` trained very speak is prompt() very doge is { 'console': 'consola', 'doge': 'perro', 'very': 'muy', 'concern': 'preocupación', 'word': 'palabra', 'much': 'mucho', 'trained': 'entrenado', 'with': 'con', 'doge': 'perro', 'very': 'muy', 'much': 'mucho', 'with': 'con', 'is': 'es', 'trained': 'entrenado', 'such': 'tan', 'wow': 'guau', 'plz': 'porFavor', 'but': 'pero', 'maybe': 'quizás', 'rly': 'enserio', 'many': 'muchos', 'so': 'tanto', 'not': 'no', 'and': 'y', 'or': 'o', 'next': 'siguiente', 'as': 'como', 'more': 'más', 'less': 'menos', 'lots': 'montones', 'few': 'pocos', 'bigger': 'másGrande', 'smaller': 'menor', 'biggerish': 'unPocoMásGrande', 'smallerish': 'unPocoMásPequeño', 'prompt': 'preguntar', 'in': 'en', 'replace': 'reemplazar', 'new': 'nuevo', 'RegExp': 'ExpReg', 'loge': 'registro', 'dose': 'punta', 'speak': 'habla' } much very word in doge very concern is new RegExp with word 'g' doge is speak dose replace with concern doge[word] wow console dose loge with speak ``` Spanish: ``` entrenado muy habla es preguntar() muy perro es {...} mucho muy palabra en perro muy preocupación es nuevo ExpReg con palabra 'g' perro es habla punta reemplazar con preocupación perro[palabra] guau consola punta registro con habla ``` You may notice that I've taken a few liberties in the translation. This is partially because my Spanish is rather poor and partially because my knowledge of Spanish language memes is lacking. ![enter image description here](https://i.stack.imgur.com/RIAZ3.png) [Answer] # C#, Latin - C Acutus ``` using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ToLatin { class Program { static void Main(string[] args) { Dictionary<string, string> dx = new Dictionary<string, string>(); dx.Add("using", "usura"); dx.Add("System", "Ratio"); dx.Add("Collections", "Comprensio"); dx.Add("Text", "Scriptum"); dx.Add("txt", "scrptm"); dx.Add("output", "scribo"); dx.Add("namespace", "nomenspatium"); dx.Add("class", "classis"); dx.Add("Program", "Libellus"); dx.Add("static", "immotus"); dx.Add("void", "inane"); dx.Add("Main", "Paelagus"); dx.Add("string", "chorda"); dx.Add("args", "argumenta"); dx.Add("Dictionary", "Lexicon"); dx.Add("new", "novus"); dx.Add("Add", "Adaugeo"); dx.Add("IO", "LecticoScribo"); dx.Add("abstract", "abstracto"); dx.Add("break", "confractus"); dx.Add("Math", "Mathematica"); dx.Add("File", "Ordo"); dx.Add("file", "ordo"); dx.Add("foreach", "prosingulus"); dx.Add("Read", "Lectico"); dx.Add("Write", "Scribo"); dx.Add("All", "Omnes"); dx.Add("translation", "interpretatio"); dx.Add("bool", "verumfalsus"); dx.Add("true", "verum"); dx.Add("false", "falsus"); dx.Add("0", "nil"); dx.Add("||", "aut"); dx.Add("&&", "et"); dx.Add("Key", "Clavis"); dx.Add("Value", "Pretium"); dx.Add("Replace", "Restituo"); dx.Add("Generic", "Ordinarius"); dx.Add("ToLatin", "AdLatinam"); string file = File.ReadAllText(args[0]); foreach (var translation in dx ) { file = file.Replace(translation.Key, translation.Value); } File.WriteAllText("output.txt", file); } } } ``` Reads file from command-line args, writes to output.txt. Example: ``` usura Ratio; usura Ratio.Comprensio.Ordinarius; usura Ratio.Scriptum; usura Ratio.LecticoScribo; nomenspatium AdLatinam { classis Libellus { immotus inane Paelagus(chorda[] argumenta) { Lexicon<chorda, chorda> dx = novus Lexicon<chorda, chorda>(); dx.Adaugeo("usura", "usura"); dx.Adaugeo("Ratio", "Ratio"); dx.Adaugeo("Comprensio", "Comprensio"); dx.Adaugeo("Scriptum", "Scriptum"); dx.Adaugeo("scrptm", "scrptm"); dx.Adaugeo("scribo", "scribo"); dx.Adaugeo("nomenspatium", "nomenspatium"); dx.Adaugeo("classis", "classisis"); dx.Adaugeo("Libellus", "Libellus"); dx.Adaugeo("immotus", "immotus"); dx.Adaugeo("inane", "inane"); dx.Adaugeo("Paelagus", "Paelagus"); dx.Adaugeo("chorda", "chorda"); dx.Adaugeo("argumenta", "argumenta"); dx.Adaugeo("Lexicon", "Lexicon"); dx.Adaugeo("novus", "novus"); dx.Adaugeo("Adaugeo", "Adaugeo"); dx.Adaugeo("LecticoScribo", "LecticoScribo"); dx.Adaugeo("abstracto", "abstractoo"); dx.Adaugeo("confractus", "confractus"); dx.Adaugeo("Mathematica", "Mathematicaematica"); dx.Adaugeo("Ordo", "Ordo"); dx.Adaugeo("ordo", "ordo"); dx.Adaugeo("prosingulus", "prosingulus"); dx.Adaugeo("Lectico", "Lectico"); dx.Adaugeo("Scribo", "Scribo"); dx.Adaugeo("Omnes", "Omnes"); dx.Adaugeo("interpretatio", "interpretatio"); dx.Adaugeo("verumfalsus", "verumfalsus"); dx.Adaugeo("verum", "verum"); dx.Adaugeo("falsus", "falsus"); dx.Adaugeo("nil", "nil"); dx.Adaugeo("aut", "aut"); dx.Adaugeo("et", "et"); dx.Adaugeo("Clavis", "Clavis"); dx.Adaugeo("Pretium", "Pretium"); dx.Adaugeo("Restituo", "Restituo"); dx.Adaugeo("Ordinarius", "Ordinarius"); dx.Adaugeo("ToLatin", "AdLatinam"); chorda ordo = Ordo.LecticoOmnesScriptum(argumenta[nil]); prosingulus (var interpretatio in dx ) { ordo = ordo.Restituo(interpretatio.Clavis, interpretatio.Pretium); } Ordo.ScriboOmnesScriptum("scribo.scrptm", ordo); } } } ``` --- Darn, just saw the C++ Latin version.. [Answer] # Ruby, Japanese - AkaDama Ruby in Japanese is *rubii* (ルビー), which is boring, so I named it literally *red gem*. In ruby, variables and methods are not restricted to ASCII, so something like ``` def フロートの文字化(フロート) 甲 = フロート.to_s.split(?.) 甲[0] = 整数の文字化(甲[0]) 甲[1] = 甲[1].chars.map{|乙|R数字行列[乙]}.join 甲.join(?点) end ``` is valid ruby. I'm using this as much as possible ~~for obfuscation~~ for all your bases. I hope it's okay to use the gems for parsing ruby, it still required some ugly monkey-patching. You can expand on the `TRANS_TABLE` to add translation for more methods. Everything that's not in the table is "translated" into Japanese loosely based upon its pronunciation (or more like spelling), so *eat* becomes えあと ("a-ah-toe"). Converts integers to a ["very" practical notation](http://ja.wikipedia.org/wiki/%E5%91%BD%E6%95%B0%E6%B3%95#.E4.BB.8F.E5.85.B8.E3.81.AE.E6.95.B0.E8.A9.9E). ``` # encoding:utf-8 require 'parser/current' # super hack, don't try this at home!! class Array def freeze self end end class Hash def freeze self end end class Parser::AST::Node def freeze self end end require 'unparser' class Parser::Source::Comment def freeze self end end # translation memory R翻訳メモリー = {} # keyword translation R鍵文字 = { :BEGIN => [:K_PREEXE, :"コンパイル時に最初に登録"], :END => [:K_POSTEXE, :"コンパイル時に最後に登録"], :__ENCODING__ => [:K_ENCODING, :"__エンコーディング__"], :__END__ => [:K_EEND, :"__終__"], :__FILE__ => [:K_FILE, :"__ソースファイル名__"], :alias => [:K_ALIAS, :"別名"], :and => [:K_AND, :"且つ"], :begin => [:K_BEGIN, :"開始"], :break => [:K_BREAK, :"抜ける"], :case => [:K_CASE, :"条件分岐"], :class => [:K_CLASS, :"クラス"], :def => [:K_DEF, :"定義"], :define => [:K_DEFINE, :""], :defined? => [:K_DEFINED, :"若し定義されたら"], :do => [:K_DO, :"実行"], :else => [:K_ELSE, :"違えば"], :elsif => [:K_ELSIF, :"それとも"], :end => [:K_END, :"此処迄"], :ensure => [:K_ENSURE, :"必ず実行"], :false => [:K_FALSE, :"偽"], :for => [:K_FOR, :"変数"], :if => [:K_IF, :"若し"], :in => [:K_IN, :"の次の値ごとに"], :module => [:K_MODULE, :"モジュール"], :next => [:K_NEXT, :"次"], :nil => [:K_NIL, :"無"], :not => [:K_NOT, :"ノット"], :or => [:K_OR, :"又は"], :redo => [:K_REDO, :"遣り直す"], :rescue => [:K_RESCUE, :"救出"], :retry => [:K_RETRY, :"再び試みる"], :return => [:K_RETURN, :"戻る"], :self => [:K_SELF, :"自身"], :super => [:K_SUPER, :"スーパー"], :then => [:K_THEN, :"成らば"], :true => [:K_TRUE, :"真"], :undef => [:K_UNDEF, :"定義を取消す"], :unless => [:K_UNLESS, :"若し違えば"], :until => [:K_UNTIL, :"次の通りである限り"], :when => [:K_WHEN, :"場合"], :while => [:K_WHILE, :"次の通りで無い限り"], :yield => [:K_YIELD, :"ブロックを呼び出す"], } R数字行列 = { "0" => "零", "1" => "壹", "2" => "貮", "3" => "參", "4" => "肆", "5" => "伍", "6" => "陸", "7" => "漆", "8" => "捌", "9" => "玖", } R翻訳行列 = { # Symbols :+ => :+, :- => :-, :/ => :/, :* => :*, :** => :**, :! => :!, :^ => :^, :& => :&, :| => :|, :~ => :~, :> => :>, :< => :<, :<< => :<<, :% => :%, :"!=" => :"!=", :"=~" => :"=~", :"~=" => :"~=", :">=" => :">=", :"<=" => :"<=", :"=" => :"=", :"==" => :"==", :"===" => :"===", :"<=>" => :"<=>", :"[]" => :"[]", :"[]=" => :"[]=", :"!~" => :"!~", # Errors :ArgumentError => :引数エラー, :EncodingError => :文字コードエラー, :FiberError => :ファイバーエラー, :IOError => :入出エラー, :IndexError => :添字エラー, :LoadError => :読込エラー, :LocalJumpError => :エラー, :NameError => :未定義エラー, :NoMemoryError => :メモリー不足エラー, :NotImplementedError => :未実装エラー, :RangeError => :範囲エラー, :RegexpError => :正規表現エラー, :RuntimeError => :実行時エラー, :ScriptError => :スクリプトエラー, :SecurityError => :セキュリティエラー, :StandardError => :通常エラー, :SyntaxError => :シンタクスエラー, :ThreadError => :スレッドエラー, :TypeError => :タイプエラー, :ZeroDivisionError => :零除算エラー, # Constants :Array => :配列, :BasicObject => :基本オブジェクト, :Bignum => :多倍長整数, :Class => :クラス, :Complex => :複素数, :Exception => :例外, :FalseClass => :偽クラス, :File => :ファイル, :Fiber => :ファイバー, :Fixnum => :固定長整数, :Float => :浮動小数点数, :Hash => :ハッシュ表, :Integer => :整数, :IO => :入出, :Kernel => :中核, :Marshal => :元帥, :Math => :数学, :Module => :モジュール, :NilClass => :無クラス, :Numeric => :数値, :Object => :オブジェクト, :Prime => :素数, :Proc => :プロック, :Process => :プロセス, :Random => :乱数, :Range => :範囲, :Rational => :有理数, :Regexp => :正規表現, :Set => :集合, :Socket => :ソケット, :String => :文字列, :Symbol => :シンボル, :Time => :時刻, :Thread => :スレッド, :TrueClass => :真クラス, # Kernel :inspect => :検査, :p => :表示, :print => :書く, :puts => :言う, :require => :取り込む, # Object :freeze => :凍結, # String :gsub => :全文字列置換, :gsub! => :全文字列置換せよ, } INT_TABLE = [ [7, "倶胝"], [14, "阿庾多"], [28, "那由他"], [56, "頻波羅"], [112, "矜羯羅"], [224, "阿伽羅"], [448, "最勝"], [896, "摩婆羅"], [1792, "阿婆羅"], [3584, "多婆羅"], [7168, "界分"], [14336, "普摩"], [28672, "禰摩"], [57344, "阿婆鈐"], [114688, "弥伽婆"], [229376, "毘攞伽"], [458752, "毘伽婆"], [917504, "僧羯邏摩"], [1835008, "毘薩羅"], [3670016, "毘贍婆"], [7340032, "毘盛伽"], [14680064, "毘素陀"], [29360128, "毘婆訶"], [58720256, "毘薄底"], [117440512, "毘佉擔"], [234881024, "称量"], [469762048, "一持"], [939524096, "異路"], [1879048192, "顛倒"], [3758096384, "三末耶"], [7516192768, "毘睹羅"], [15032385536, "奚婆羅"], [30064771072, "伺察"], [60129542144, "周広"], [120259084288, "高出"], [240518168576, "最妙"], [481036337152, "泥羅婆"], [962072674304, "訶理婆"], [1924145348608, "一動"], [3848290697216, "訶理蒲"], [7696581394432, "訶理三"], [15393162788864, "奚魯伽"], [30786325577728, "達攞歩陀"], [61572651155456, "訶魯那"], [123145302310912, "摩魯陀"], [246290604621824, "懺慕陀"], [492581209243648, "瑿攞陀"], [985162418487296, "摩魯摩"], [1970324836974592, "調伏"], [3940649673949184, "離憍慢"], [7881299347898368, "不動"], [15762598695796736, "極量"], [31525197391593472, "阿麼怛羅"], [63050394783186944, "勃麼怛羅"], [126100789566373888, "伽麼怛羅"], [252201579132747776, "那麼怛羅"], [504403158265495552, "奚麼怛羅"], [1008806316530991104, "鞞麼怛羅"], [2017612633061982208, "鉢羅麼怛羅"], [4035225266123964416, "尸婆麼怛羅"], [8070450532247928832, "翳羅"], [16140901064495857664, "薜羅"], [32281802128991715328, "諦羅"], [64563604257983430656, "偈羅"], [129127208515966861312, "窣歩羅"], [258254417031933722624, "泥羅"], [516508834063867445248, "計羅"], [1033017668127734890496, "細羅"], [2066035336255469780992, "睥羅"], [4132070672510939561984, "謎羅"], [8264141345021879123968, "娑攞荼"], [16528282690043758247936, "謎魯陀"], [33056565380087516495872, "契魯陀"], [66113130760175032991744, "摩睹羅"], [132226261520350065983488, "娑母羅"], [264452523040700131966976, "阿野娑"], [528905046081400263933952, "迦麼羅"], [1057810092162800527867904, "摩伽婆"], [2115620184325601055735808, "阿怛羅"], [4231240368651202111471616, "醯魯耶"], [8462480737302404222943232, "薜魯婆"], [16924961474604808445886464, "羯羅波"], [33849922949209616891772928, "訶婆婆"], [67699845898419233783545856, "毘婆羅"], [135399691796838467567091712, "那婆羅"], [270799383593676935134183424, "摩攞羅"], [541598767187353870268366848, "娑婆羅"], [1083197534374707740536733696, "迷攞普"], [2166395068749415481073467392, "者麼羅"], [4332790137498830962146934784, "駄麼羅"], [8665580274997661924293869568, "鉢攞麼陀"], [17331160549995323848587739136, "毘迦摩"], [34662321099990647697175478272, "烏波跋多"], [69324642199981295394350956544, "演説"], [138649284399962590788701913088, "無尽"], [277298568799925181577403826176, "出生"], [554597137599850363154807652352, "無我"], [1109194275199700726309615304704, "阿畔多"], [2218388550399401452619230609408, "青蓮華"], [4436777100798802905238461218816, "鉢頭摩"], [8873554201597605810476922437632, "僧祇"], [17747108403195211620953844875264, "趣"], [35494216806390423241907689750528, "至"], [70988433612780846483815379501056, "阿僧祇"], [141976867225561692967630759002112, "阿僧祇転"], [283953734451123385935261518004224, "無量"], [567907468902246771870523036008448, "無量転"], [1135814937804493543741046072016896, "無辺"], [2271629875608987087482092144033792, "無辺転"], [4543259751217974174964184288067584, "無等"], [9086519502435948349928368576135168, "無等転"], [18173039004871896699856737152270336, "不可数"], [36346078009743793399713474304540672, "不可数転"], [72692156019487586799426948609081344, "不可称"], [145384312038975173598853897218162688, "不可称転"], [290768624077950347197707794436325376, "不可思"], [581537248155900694395415588872650752, "不可思転"], [1163074496311801388790831177745301504, "不可量"], [2326148992623602777581662355490603008, "不可量転"], [4652297985247205555163324710981206016, "不可説"], [9304595970494411110326649421962412032, "不可説転"], [18609191940988822220653298843924824064, "不可説不可説"], [37218383881977644441306597687849648128, "不可説不可説転"], ].reverse Rしヴぁう = { :b => :u, :c => :u, :d => :o, :f => :u, :g => :u, :h => :u, :j => :u, :k => :u, :l => :u, :m => :u, :n => :u, :p => :u, :q => :u, :r => :u, :s => :u, :t => :o, :v => :u, :w => :u, :x => :u, :y => :u, :z => :u, } R平 = { :a => :あ, :i => :い, :u => :う, :e => :え, :o => :お, :ba => :ば, :bi => :び, :bu => :ぶ, :be => :べ, :bo => :ぼ, :ca => :か, :ci => :き, :cu => :く, :ce => :け, :co => :こ, :da => :だ, :di => :どぃ, :du => :どぅ, :de => :で, :do => :ど, :fa => :ふぁ, :fi => :ふぃ, :fu => :ふ, :fe => :ふぇ, :fo => :ふぉ, :ga => :が, :gi => :ぎ, :gu => :ぐ, :ge => :げ, :go => :ご, :ha => :は, :hi => :ひ, :hu => :ふ, :he => :へ, :ho => :ほ, :ja => :じぁ, :ji => :じ, :ju => :じぅ, :je => :じぇ, :jo => :じぉ, :ka => :か, :ki => :き, :ku => :く, :ke => :け, :ko => :こ, :la => :ら, :li => :り, :lu => :る, :le => :れ, :lo => :ろ, :ma => :ま, :mi => :み, :mu => :む, :me => :め, :mo => :も, :na => :な, :ni => :に, :nu => :ぬ, :ne => :ね, :no => :の, :pa => :ぱ, :pi => :ぴ, :pu => :ぷ, :pe => :ぺ, :po => :ぽ, :qa => :か, :qi => :き, :qu => :く, :qe => :け, :qo => :こ, :ra => :ら, :ri => :り, :ru => :る, :re => :れ, :ro => :ろ, :sa => :さ, :si => :すぃ, :su => :す, :se => :せ, :so => :そ, :ta => :た, :ti => :てぃ, :tu => :とぅ, :te => :て, :to => :と, :va => :ヴぁ, :vi => :ヴぃ, :vu => :ヴぅ, :ve => :ヴぇ, :vo => :ヴぉ, :wa => :わ, :wi => :ゐ, :wu => :ゐぅ, :we => :ゑ, :wo => :を, :xa => :くさ, :xi => :くすぃ, :xu => :くす, :xe => :くせ, :xo => :くそ, :ya => :いぁ, :yi => :いぃ, :yu => :いぅ, :ye => :いぇ, :yo => :いぉ, :za => :ざ, :zi => :ずぃ, :zu => :ず, :ze => :ぜ, :zo => :ぞ, } R片 = { :が => :ガ,:ぎ => :ギ,:ぐ => :グ,:げ => :ゲ,:ご => :ゴ, :ざ => :ザ,:じ => :ジ,:ず => :ズ,:ぜ => :ゼ,:ぞ => :ゾ, :だ => :ダ,:ぢ => :ヂ,:づ => :ヅ,:で => :デ,:ど => :ド, :ば => :バ,:び => :ビ,:ぶ => :ブ,:べ => :ベ,:ぼ => :ボ, :ぱ => :パ,:ぴ => :ピ,:ぷ => :プ,:ぺ => :ペ,:ぽ => :ポ, :あ => :ア,:い => :イ,:う => :ウ,:え => :エ,:お => :オ, :か => :カ,:き => :キ,:く => :ク,:け => :ケ,:こ => :コ, :さ => :サ,:し => :シ,:す => :ス,:せ => :セ,:そ => :ソ, :た => :タ,:ち => :チ,:つ => :ツ,:て => :テ,:と => :ト, :な => :ナ,:に => :ニ,:ぬ => :ヌ,:ね => :ネ,:の => :ノ, :は => :ハ,:ひ => :ヒ,:ふ => :フ,:へ => :ヘ,:ほ => :ホ, :ま => :マ,:み => :ミ,:む => :ム,:め => :メ,:も => :モ, :ら => :ラ,:り => :リ,:る => :ル,:れ => :レ,:ろ => :ロ, :わ => :ワ,:を => :ヲ,:ゑ => :ヱ,:ゐ => :ヰ,:ヴ => :ヴ, :ぁ => :ァ,:ぃ => :ィ,:ぅ => :ゥ,:ぇ => :ェ,:ぉ => :ォ, :ゃ => :ャ,:ゅ => :ュ,:ょ => :ョ, :や => :ヤ,:ゆ => :ユ,:よ => :ヨ, :ん => :ン,:っ => :ッ,:ゎ => :ヮ, } def 鍵文字を登録 R鍵文字.each_pair do |甲,乙| Unparser::Constants.const_set 乙[0], 乙[1].to_s Unparser::Emitter::REGISTRY[乙[1].to_sym] = Unparser::Emitter::REGISTRY[甲.to_sym] end Unparser::Emitter::Repetition::MAP[:while] = R鍵文字[:while][1].to_s Unparser::Emitter::Repetition::MAP[:until] = R鍵文字[:until][1].to_s Unparser::Emitter::FlowModifier::MAP[:return] = R鍵文字[:return][1].to_s Unparser::Emitter::FlowModifier::MAP[:next] = R鍵文字[:next][1].to_s Unparser::Emitter::FlowModifier::MAP[:break] = R鍵文字[:break][1].to_s Unparser::Emitter::FlowModifier::MAP[:or] = R鍵文字[:or][1].to_s Unparser::Emitter::FlowModifier::MAP[:and] = R鍵文字[:and][1].to_s Unparser::Emitter::FlowModifier::MAP[:BEGIN] = R鍵文字[:BEGIN][1].to_s Unparser::Emitter::FlowModifier::MAP[:END] = R鍵文字[:END][1].to_s end class Float def inspect フロートの文字化(self) end end class BigDecimal def inspect フロートの文字化(self.to_s('F')) end end class Integer def inspect 整数の文字化(self) end end class Fixnum def inspect 整数の文字化(self) end end class Bignum def inspect 整数の文字化(self) end end def 整数の文字化(整数) 数字 = 整数.to_s if 数字.size <= 7 return 数字.chars.map{|甲|R数字行列[甲]}.join else 乙 = INT_TABLE.find{|甲|甲[0] < 数字.size} 整数の文字化(数字[0...-乙[0]]) + 乙[1] + 整数の文字化(数字[(-乙[0])..-1]) end end def フロートの文字化(フロート) 甲 = フロート.to_s.split(?.) 甲[0] = 整数の文字化(甲[0]) 甲[1] = 甲[1].chars.map{|乙|R数字行列[乙]}.join 甲.join(?点) end def 文字を翻訳(文字) 平片 = :hira 文字.scan(/([^aeiou])?(\1)?([yj])?([aeiou])?/i).map do |子音甲,子音乙,子音丙,母音| 母音 = 母音.to_s if 子音甲.nil? && 母音.empty? nil else 平片 = :kata if (子音甲||母音).downcase!=(子音甲||母音) 子音甲,子音乙,子音丙,母音 = [子音甲,子音乙,子音丙,母音].map{|x| x ? x.downcase : x } if 母音.empty? 母音 = Rしヴぁう[子音甲.to_sym].to_s end # hu => ひゅ, qu => きゅ if 母音=="u" && (子音甲=="h"||子音甲=="q") 子音丙 = "y" end # ja,ju,jo => じゃ、じゅ,じょ if (母音=="a"||母音=="u"||母音=="o") && 子音甲 == "j" 子音丙 = "y" end # 拗音 if 子音丙 if [:a,:u,:o].include?(母音) 子音丙 = case 母音 when :a ; :ゃ when :u ; :ゅ when :o ; :ょ end 母音 = :i else 子音丙 = nil end end # basic syllable 仮名 = R平[(子音甲.to_s+母音).to_sym].to_s # 促音 if 子音乙 if %w[ま み む め も な に ぬ ね の].include?(子音乙) 仮名 = "ん" + 仮名 else 仮名 = "っ" + 仮名 end end # 拗音 if 子音丙 仮名 = 仮名 + 子音丙 end # lowercase => hiragana, uppercase => katakana if 平片==:kata 仮名 = 仮名.gsub(/./){|丁|R片[丁.to_sym]}.to_s end 仮名 end end.compact.join end def 文を翻訳(文) 文.scan(/(([a-z]+|[0-9]+|[^a-z0-9]+))/i).map do |文字,_| if 文字.index(/[a-z]/i) 文字を翻訳(文字) elsif 文字.index(/[0-9]/) 整数の文字化(文字) else 文字 end end.compact.join end def 翻訳(文章=nil) if 文章.empty? || 文章.nil? 文章 else if 甲 = R翻訳行列[文章.to_sym] 甲 elsif 甲 = R翻訳メモリー[文章] 甲 else 甲 = 文を翻訳(文章.to_s) R翻訳メモリー[文章] = 甲 end end end def ノード毎に(幹,&塊) if 幹.is_a? Parser::AST::Node 子供 = 幹.children yield 幹.type,子供 幹.children.each{|甲|ノード毎に(甲,&塊)} if 甲 = R鍵文字[幹.type] 幹.instance_variable_set(:@type,甲[1]) if [:self,:true,:false,:nil].include?(幹.type) end end end def 幹を翻訳(幹) ノード毎に(幹) do |類,子| case 類 when :arg 子[0] = 翻訳(子[0]).to_sym when :blockarg 子[0] = 翻訳(子[0]).to_sym when :casgn 子[1] = ('C_'+翻訳(子[1]).to_s).to_sym when :const 子[1] = 翻訳(子[1]).to_sym when :def 子[0] = 翻訳(子[0]).to_sym when :int when :kwoptarg 子[0] = 翻訳(子[0]).to_sym when :lvar 子[0] = 翻訳(子[0]).to_sym when :lvasgn 子[0] = 翻訳(子[0]).to_sym when :optarg 子[0] = 翻訳(子[0]).to_sym when :restarg 子[0] = 翻訳(子[0]).to_sym when :send 子[1] = 翻訳(子[1]).to_sym when :str 子[0] = 翻訳(子[0]).to_s when :sym 子[0] = 翻訳(子[0]).to_sym end end end def ノートを翻訳(ノート) ノート.each do |子| テキスト = 子.text if テキスト[0] == '#' 子.instance_variable_set(:@text,"#" + 翻訳(テキスト[1..-1])) else 子.instance_variable_set(:@text,"=開始\n" + 翻訳(テキスト[6..-6]) + "\n=此処迄\n") end end end ######## # main # ######## # register keywords 鍵文字を登録 # read input, translate, and print result コード = STDIN.read コード.encode(Encoding::UTF_8) コード = "#encoding:utf-8\n" + コード 幹, ノート = Parser::CurrentRuby.parse_with_comments(コード) 幹を翻訳(幹) ノートを翻訳(ノート) STDOUT.write Unparser.unparse(幹,ノート) ``` Run on itself, omitting some translation tables etc: ``` #えぬこどぃぬぐ:うとふ-捌 # えぬこどぃぬぐ:うとふ-捌 取り込む("ぱるせる/くっれぬと") # すぺる はくく, どぬ'と とる とひす あと ほめ!! クラス 配列 定義 凍結 自身 此処迄 此処迄 クラス ハッシュ表 定義 凍結 自身 此処迄 此処迄 クラス パルセル::アスト::ノデ 定義 凍結 自身 此処迄 此処迄 取り込む("うぬぱるせる") クラス パルセル::ソウルケ::コッメヌト 定義 凍結 自身 此処迄 此処迄 定義 鍵文字を登録 ル鍵文字.えあくふ_ぱいる 実行 |甲, 乙| ウヌパルセル::コヌスタヌトス.こぬすと_せと(乙[零], 乙[壹].と_す) ウヌパルセル::エミッテル::レギストル[乙[壹].と_すむ] = ウヌパルセル::エミッテル::レギストル[甲.と_すむ] 此処迄 ウヌパルセル::エミッテル::レペティティオヌ::マプ[:ゐぅひれ] = ル鍵文字[:ゐぅひれ][壹].と_す ウヌパルセル::エミッテル::レペティティオヌ::マプ[:うぬてぃる] = ル鍵文字[:うぬてぃる][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:れとぅるぬ] = ル鍵文字[:れとぅるぬ][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:ねくすと] = ル鍵文字[:ねくすと][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:ぶれあく] = ル鍵文字[:ぶれあく][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:おる] = ル鍵文字[:おる][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:あぬど] = ル鍵文字[:あぬど][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:ベギヌ] = ル鍵文字[:ベギヌ][壹].と_す ウヌパルセル::エミッテル::フロヰゥモドィフィエル::マプ[:エヌド] = ル鍵文字[:エヌド][壹].と_す 此処迄 クラス 浮動小数点数 定義 検査 フロートの文字化(自身) 此処迄 此処迄 クラス ビグデキマル 定義 検査 フロートの文字化(自身.と_す("フ")) 此処迄 此処迄 クラス 整数 定義 検査 整数の文字化(自身) 此処迄 此処迄 クラス 固定長整数 定義 検査 整数の文字化(自身) 此処迄 此処迄 クラス 多倍長整数 定義 検査 整数の文字化(自身) 此処迄 此処迄 定義 整数の文字化(整数) 数字 = 整数.と_す 若し (数字.すぃぜ <= 漆) 戻る 数字.くはるす.まぷ 実行 |甲| ル数字行列[甲] 此処迄.じぉいぬ 違えば 乙 = イヌト_タブレ.ふぃぬど 実行 |甲| 甲[零] < 数字.すぃぜ 此処迄 (整数の文字化(数字[零...(-乙[零])]) + 乙[壹]) + 整数の文字化(数字[(-乙[零])..壹]) 此処迄 此処迄 定義 フロートの文字化(フロート) 甲 = フロート.と_す.すぷりと(".") 甲[零] = 整数の文字化(甲[零]) 甲[壹] = 甲[壹].くはるす.まぷ 実行 |乙| ル数字行列[乙] 此処迄.じぉいぬ 甲.じぉいぬ("点") 此処迄 定義 文字を翻訳(文字) 平片 = :ひら 文字.すかぬ(/([^あえいおう])?(\壹)?([いぅ])?([あえいおう])?/i).まぷ 実行 |子音甲, 子音乙, 子音丙, 母音| 母音 = 母音.と_す 若し (子音甲.にる? && 母音.えむぷと?) 無 違えば 若し ((子音甲 || 母音).どゐぅぬかせ != (子音甲 || 母音)) 平片 = :かた 此処迄 子音甲, 子音乙, 子音丙, 母音 = [子音甲, 子音乙, 子音丙, 母音].まぷ 実行 |くす| 若し くす くす.どゐぅぬかせ 違えば くす 此処迄 此処迄 若し 母音.えむぷと? 母音 = ルしヴぁう[子音甲.と_すむ].と_す 此処迄 # ふ => ひゅ, く => きゅ 若し ((母音 == "う") && ((子音甲 == "ふ") || (子音甲 == "く"))) 子音丙 = "いぅ" 此処迄 # じぁ,じぅ,じぉ => じゃ、じゅ,じょ 若し ((((母音 == "あ") || (母音 == "う")) || (母音 == "お")) && (子音甲 == "じぅ")) 子音丙 = "いぅ" 此処迄 # 拗音 若し 子音丙 若し [:あ, :う, :お].いぬくるで?(母音) 子音丙 = 条件分岐 母音 場合 :あ :ゃ 場合 :う :ゅ 場合 :お :ょ 此処迄 母音 = :い 違えば 子音丙 = 無 此処迄 此処迄 # ばすぃく すっらぶれ 仮名 = ル平[(子音甲.と_す + 母音).と_すむ].と_す # 促音 若し 子音乙 若し ["ま", "み", "む", "め", "も", "な", "に", "ぬ", "ね", "の"].いぬくるで?(子音乙) 仮名 = ("ん" + 仮名) 違えば 仮名 = ("っ" + 仮名) 此処迄 此処迄 # 拗音 若し 子音丙 仮名 = (仮名 + 子音丙) 此処迄 # ろゑるかせ => ひらがな, うっぺるかせ => かたかな 若し (平片 == :かた) 仮名 = 仮名.全文字列置換(/./) 実行 |丁| ル片[丁.と_すむ] 此処迄.と_す 此処迄 仮名 此処迄 此処迄.こむぱくと.じぉいぬ 此処迄 定義 文を翻訳(文) 文.すかぬ(/(([あ-ず]+|[零-玖]+|[^あ-ず零-玖]+))/i).まぷ 実行 |文字, _| 若し 文字.いぬでくす(/[あ-ず]/i) 文字を翻訳(文字) 違えば 若し 文字.いぬでくす(/[零-玖]/) 整数の文字化(文字) 違えば 文字 此処迄 此処迄 此処迄.こむぱくと.じぉいぬ 此処迄 定義 翻訳(文章 = 無) 若し (文章.えむぷと? || 文章.にる?) 文章 違えば 若し (甲 = ル翻訳行列[文章.と_すむ]) 甲 違えば 若し (甲 = ル翻訳メモリー[文章]) 甲 違えば 甲 = 文を翻訳(文章.と_す) ル翻訳メモリー[文章] = 甲 此処迄 此処迄 此処迄 此処迄 定義 ノード毎に(幹, &塊) 若し 幹.いす_あ?(パルセル::アスト::ノデ) 子供 = 幹.くひるどれぬ ブロックを呼び出す(幹.とぺ, 子供) 幹.くひるどれぬ.えあくふ 実行 |甲| ノード毎に(甲, &塊) 此処迄 若し (甲 = ル鍵文字[幹.とぺ]) 若し [:せるふ, :とるえ, :ふぁるせ, :にる].いぬくるで?(幹.とぺ) 幹.いぬすたぬけ_ヴぁりあぶれ_せと(:@とぺ, 甲[壹]) 此処迄 此処迄 此処迄 此処迄 定義 幹を翻訳(幹) ノード毎に(幹) 実行 |類, 子| 条件分岐 類 場合 :あるぐ 子[零] = 翻訳(子[零]).と_すむ 場合 :ぶろくかるぐ 子[零] = 翻訳(子[零]).と_すむ 場合 :かすぐぬ 子[壹] = ("ク_" + 翻訳(子[壹]).と_す).と_すむ 場合 :こぬすと 子[壹] = 翻訳(子[壹]).と_すむ 場合 :でふ 子[零] = 翻訳(子[零]).と_すむ 場合 :いぬと 場合 :くをぷたるぐ 子[零] = 翻訳(子[零]).と_すむ 場合 :るヴぁる 子[零] = 翻訳(子[零]).と_すむ 場合 :るヴぁすぐぬ 子[零] = 翻訳(子[零]).と_すむ 場合 :おぷたるぐ 子[零] = 翻訳(子[零]).と_すむ 場合 :れすたるぐ 子[零] = 翻訳(子[零]).と_すむ 場合 :せぬど 子[壹] = 翻訳(子[壹]).と_すむ 場合 :すとる 子[零] = 翻訳(子[零]).と_す 場合 :すむ 子[零] = 翻訳(子[零]).と_すむ 此処迄 此処迄 此処迄 定義 ノートを翻訳(ノート) ノート.えあくふ 実行 |子| テキスト = 子.てくすと 若し (テキスト[零] == "#") 子.いぬすたぬけ_ヴぁりあぶれ_せと(:@てくすと, "#" + 翻訳(テキスト[壹..壹])) 違えば 子.いぬすたぬけ_ヴぁりあぶれ_せと(:@てくすと, ("=開始\n" + 翻訳(テキスト[陸..陸])) + "\n=此処迄\n") 此処迄 此処迄 此処迄 ######## # まいぬ # ######## # れぎすてる けいぅをるどす 鍵文字を登録 # れあど いぬぷと, とらぬすらて, あぬど ぷりぬと れすると コード = ストドィヌ.れあど コード.えぬこで(エヌコドィヌグ::ウトフ_捌) コード = ("#えぬこどぃぬぐ:うとふ-捌\n" + コード) 幹, ノート = パルセル::クッレヌトルブ.ぱるせ_ゐとふ_こっめぬとす(コード) 幹を翻訳(幹) ノートを翻訳(ノート) ストドウト.ゐぅりて(ウヌパルセル.うぬぱるせ(幹, ノート)) ``` or ``` # Output "I love Ruby" say = "I love Ruby" puts say # Output "I *LOVE* RUBY" say['love'] = "*love*" puts say.upcase # Output "I *love* Ruby" # five times 5.times { puts say } ``` becomes ``` #えぬこどぃぬぐ:うとふ-捌 # オウトプト "イ ろヴぇ ルブ" さいぅ = "イ ろヴぇ ルブ" 言う(さいぅ) # オウトプト "イ *ロヴェ* ルブ" さいぅ["ろヴぇ"] = "*ろヴぇ*" 言う(さいぅ.うぷかせ) # オウトプト "イ *ろヴぇ* ルブ" # ふぃヴぇ てぃめす 伍.てぃめす 実行 言う(さいぅ) 此処迄 ``` [Answer] # HTML5/ Javascript to French (HTML5 avec le Script au Caoua) ``` <script> var a=document.currentScript.outerHTML; alert(a.replace(/var a/g,"la variable «a»") .replace(/alert\(/g,"alerter(") .replace(/=/g," est ") .replace(/outerHTML/g,"HTMLExtérieur") .replace(/\.replace\((.+)\,(.+)\)/g," avec $1 remplacé par $2") .replace(/\/\*and\*\//g," et") .replace(/"(.+?)"/g,"«$1»") /*and*/.replace(/currentScript/g,"scriptCourant") ); </script> ``` Output: ``` <script> la variable «a» est document.scriptCourant.HTMLExtérieur; alerter(a avec /la variable «a»/g remplacé par «la variable «a»» avec /alert\(/g remplacé par «alerter(» avec / est /g remplacé par « est » avec /HTMLExtérieur/g remplacé par «HTMLExtérieur» avec /\.replace\((.+)\,(.+)\)/g remplacé par « avec $1 remplacé par $2» avec /\/\*and\*\//g remplacé par « et» avec /«(.+?)»/g remplacé par ««$1»» et avec /scriptCourant/g remplacé par «scriptCourant» ); </script> ``` [Answer] # JavaScript, French – CauoaScript ``` var input = prompt('Enter code'); var translations = { 'alert': 'informe', 'code': 'le code', 'else': 'sinon', 'Enter': 'Entrez', 'if': 'si', 'input': 'donnée', 'function': 'fonction', 'output': 'résultat', 'prompt': 'soulève', 'replace': 'remplace', 'replacement': 'pièceDeReplacement', 'return': 'remet', 'translate': 'traduit', 'translations': 'traductions', 'typeof': 'typede', 'undefined': 'indéterminé', 'var': 'var', 'w': 'm', // word 'word': 'mot' }; var output = input.replace(/(["'])(.*?[^\\])?\1/g, '« $2 »') .replace(/\w+/g, function(word) { var replacement = translations[word]; if (typeof replacement != 'undefined') { return replacement; } else { return word; } }); alert(output); ``` I know there is already a JavaScript + French answer, but mine uses different translations and coding methods. The code is quite straightforward: it iterates through all words in the input code, and replaces them with their corresponding French word from the `translations` object. If the word is not listed, it is not changed. French uses « [Guillemets](https://en.wikipedia.org/wiki/Guillemet) » instead of quotation marks, so it first makes strings uses those. (Yes, it uses regu͘͜l̴͝a͘͜͠r͏͏ ̶̸͢e̵͜x̸͝pr̵͞͞e͘͘s̵ś̸̷i͝o̴ns̴͜ to parse strings, so it doesn't always work perfectly.) Here is the output when run on itself: ``` var donnée = soulève(« Entrez le code »); var traductions = { « informe »: « informe », « le code »: « le le code », ... « mot »: « mot » }; var résultat = donnée.remplace(/(["« ])(.*?[^\\])?\1/g, »« $2 »') .remplace(/\m+/g, fonction(mot) { var pièceDeReplacement = traductions[mot]; si (typede pièceDeReplacement != « indéterminé ») { remet pièceDeReplacement; } sinon { remet mot; } }); informe(résultat); ``` You can use the Stack Snippet below to easily run the code. ``` // CaouaScript var translate = function(input) { var input = document.getElementById('input').value; var translations = { 'alert': 'informe', 'code': 'le code', 'else': 'sinon', 'Enter': 'Entrez', 'if': 'si', 'input': 'donnée', 'function': 'fonction', 'output': 'résultat', 'prompt': 'soulève', 'replace': 'remplace', 'replacement': 'pièceDeReplacement', 'return': 'remet', 'translate': 'traduit', 'translations': 'traductions', 'typeof': 'typede', 'undefined': 'indéterminé', 'var': 'var', 'w': 'm', // word 'word': 'mot' }; var output = input.replace(/(["'])(.*?[^\\])?\1/g, '« $2 »') .replace(/\w+/g, function(word) { var replacement = translations[word]; if (typeof replacement != 'undefined') { return replacement; } else { return word; } }); return output; } document.getElementById('go').onclick = function(){ var input = document.getElementById('input').value; var output = translate(input); document.getElementById('output').innerHTML = output; }; ``` ``` <textarea id="input" rows="20" cols="70"> var input = prompt('Enter code'); var translations = { 'alert': 'informe', 'code': 'le code', 'else': 'sinon', 'Enter': 'Entrez', 'if': 'si', 'input': 'donnée', 'function': 'fonction', 'output': 'résultat', 'prompt': 'soulève', 'replace': 'remplace', 'replacement': 'pièceDeReplacement', 'return': 'remet', 'translate': 'traduit', 'translations': 'traductions', 'typeof': 'typede', 'undefined': 'indéterminé', 'var': 'var', 'w': 'm', // word 'word': 'mot' }; var output = input.replace(/(["'])(.*?[^\\])?\1/g, '« $2 »') .replace(/\w+/g, function(word) { var replacement = translations[word]; if (typeof replacement != 'undefined') { return replacement; } else { return word; } }); alert(output);</textarea> <button id="go">Go</button> <pre><samp id="output"></samp></pre> ``` [Answer] # Commodore 64 BASIC - Bosnian/Croatian/Serbian ``` 10 FOR I=40960 TO 49151:POKE I,PEEK(I):NEXT 20 DATA "KRAJ","ZA","OPET","PODACI","UZM#","UZMI","DIM","CITAJ","DE" 30 DATA "HAJD","TRCI","AKO","VRATI","IDIU","NAZAD","KOM","STOJ","NA" 40 DATA "CEKAJ","UCITAJ","SPASI","VIDI","DEF","GURNI","PIS#","PISI" 50 DATA "NAST","POPIS","BRIS","KOM","SIS","OTVORI","ZATVORI","UZMI" 60 DATA "NOV","TAB(","DO","FU","RAZ(","ONDA","NE","KORAK","+","-" 70 DATA "*","/","↑","I","ILI",">","=","<","ZN","C","ABS","KOR" 80 DATA "SLO","POZ","KOR","SLU","LOG","EKS","KOS","SIN","TAN","ATN" 90 DATA "VIRI","DUZ","NIZ$","VRI","ASK","KAR$","LEVO$","DESNO$","SRE$" 100 DATA "ID","" 110 D=41118 120 READ A$ 130 IF A$="" THEN 210 140 L=LEN(A$) 150 IF L=1 THEN 190 160 FOR I=1 TO L-1 170 POKE D,ASC(MID$(A$,I,1)):D=D+1 180 NEXT 190 POKE D,ASC(MID$(A$,L,1))+128:D=D+1 200 GOTO 120 210 POKE 1, PEEK(1) AND 254 ``` This actually replaces BASIC keywords with the translated ones, so you ~~can~~ *must* use them when you write new code. ![Bosnian BASIC](https://i.stack.imgur.com/fzbku.png) How it works? `FOR I=40960 TO 49151:POKE I,PEEK(I):NEXT` Though it appears that this line does not do much, it in fact copies bytes from BASIC ROM to RAM. Data written to a ROM location is stored in the RAM at the same address. The last line in the program switches to the RAM copy of BASIC: `POKE 1,PEEK(1) AND 254` Memory adresses 41118-41373 contain a complete list of the reserved BASIC keywords. The ASCII characters of these words are stored in token number order. Bit #7 of the last letter of each word is set to indicate the end of the word (ASCII value + 128). Lines 20-100 contain the translated keywords. Lines 110-200 read the keywords in the memory as described above. [Answer] # PHP - Portuguese (pt-PT/semi pt-BR) This turned out quite complex, and giant! ``` <? echo preg_replace_callback( '@\b([\wâêçãáú]+)\b|(?:[\$\>]|[=\.]=|=\>?|&&)@i', function($match){ $word = $match[0]; if($word == '_') { return '_'; } $list = array( 'echo' => 'ecoar', 'match' => 'equivalência', 'array' => 'conjunto', 'file' => 'ficheiro', 'replace' => 'substitui', 'callback' => 'executável', 'function' => 'função', 'list' => 'lista', 'if' => 'se', 'else' => 'senão', 'word' => 'palavra', 'piece' => 'pedaço', 'pieces' => 'pedaços', 'explode' => 'explosão', 'implode' => 'implosão', 'count' => 'conta', 'tmp' => 'temporário', 'k' => 'chave', 'get' => 'busca', 'contents' => 'conteúdos', 'preg' => 'expressão_regular', 'as' => 'como', 'return' => 'retorna', 'use' => 'utiliza', 'strtoupper' => 'corda_para_maiúscula', 'strtolower' => 'corda_para_minúscula', 'unset' => 'remover_definição', 'isset' => 'está_definido', 'str' => 'corda', '$' => '€', '.=' => '.=', '=>' => 'recebe', '==' => 'igual', '=' => 'atribuí', '>' => 'maior_que', '&&' => 'e' ); if($word[0] == '_' && $word[1] == '_') { return preg_replace_callback( '@([A-Z]+)@', function($word) use (&$list){ return strtoupper($list[strtolower($word[1])]); }, $word ); } else { $word = explode('_', $word); $pieces = count($word); if( $pieces > 1 ) { $tmp = $word[0]; $word[0] = $word[1]; $word[1] = $tmp; unset($tmp); } foreach($word as $k => $piece) { $word[$k] = isset($list[$piece])?$list[$piece]:$piece; if( $k == 0 && $pieces > 1 ) { $word[$k] .= 'r'; } } return implode('_', $word); } }, file_get_contents(__FILE__) ); ``` Remember that this code was made to match with itself! It may work partially with other codes. --- ## Output, translated: ``` <? ecoar substituir_expressão_regular_executável( '@\b([\wâêçãáú]+)\b|(?:[\€\maior_que]|[atribuí\.]atribuí|atribuí\maior_que?|e)@i', função(€equivalência){ €palavra atribuí €equivalência[0]; se(€palavra igual '_') { retorna '_'; } €lista atribuí conjunto( 'ecoar' recebe 'ecoar', 'equivalência' recebe 'equivalência', 'conjunto' recebe 'conjunto', 'ficheiro' recebe 'ficheiro', 'substitui' recebe 'substitui', 'executável' recebe 'executável', 'função' recebe 'função', 'lista' recebe 'lista', 'se' recebe 'se', 'senão' recebe 'senão', 'palavra' recebe 'palavra', 'pedaço' recebe 'pedaço', 'pedaços' recebe 'pedaços', 'explosão' recebe 'explosão', 'implosão' recebe 'implosão', 'conta' recebe 'conta', 'temporário' recebe 'temporário', 'chave' recebe 'chave', 'busca' recebe 'busca', 'conteúdos' recebe 'conteúdos', 'expressão_regular' recebe 'regularr_expressão', 'como' recebe 'como', 'retorna' recebe 'retorna', 'utiliza' recebe 'utiliza', 'corda_para_maiúscula' recebe 'parar_corda_maiúscula', 'corda_para_minúscula' recebe 'parar_corda_minúscula', 'remover_definição' recebe 'definiçãor_remover', 'está_definido' recebe 'definidor_está', 'corda' recebe 'corda', '€' recebe '€', '.=' recebe '.=', 'recebe' recebe 'recebe', 'igual' recebe 'igual', 'atribuí' recebe 'atribuí', 'maior_que' recebe 'quer_maior', 'e' recebe 'e' ); se(€palavra[0] igual '_' e €palavra[1] igual '_') { retorna substituir_expressão_regular_executável( '@([A-Z]+)@', função(€palavra) utiliza (&€lista){ retorna corda_para_maiúscula(€lista[corda_para_minúscula(€palavra[1])]); }, €palavra ); } senão { €palavra atribuí explosão('_', €palavra); €pedaços atribuí conta(€palavra); se( €pedaços maior_que 1 ) { €temporário atribuí €palavra[0]; €palavra[0] atribuí €palavra[1]; €palavra[1] atribuí €temporário; remover_definição(€temporário); } foreach(€palavra como €chave recebe €pedaço) { €palavra[€chave] atribuí está_definido(€lista[€pedaço])?€lista[€pedaço]:€pedaço; se( €chave igual 0 e €pedaços maior_que 1 ) { €palavra[€chave] .= 'r'; } } retorna implosão('_', €palavra); } }, buscar_ficheiro_conteúdos(__FICHEIRO__) ); ``` --- I've tried to respect the grammar as much as possible. An example is right in the first line: ``` echo preg_replace_callback ``` Echo is an action, and actions are verbs. All verbs in portuguese end with `r`. Translating `echo` without context would be `eco`, while in the context it has to be `ecoar` ('making an echo'). Also, the function `preg_replace_callback` has a unique thing. The action must be the first word. Translated literally, it would be `expressão_regular_substitui_executável`, which is terribly translated!(It means `replace the callback using a regular expression`) Therefore, special care must be taken and swap the first and second words, so it is `substituir_expressão_regular_executável`, which is a little better. Other functions, like `count`, are left without `r` to detonate an order (like if you were being bossy). Some words turned out weird... `string` means `corda`, but if I translated it correctly, it would be `cadeia contínua/ininterrupta de caracteres`. To add on all that, I've also translated some symbols and operators (`$`, `=`, `=>`). Thank you [@DLosc](https://codegolf.stackexchange.com/users/16766/dlosc) for the idea of translating `$` into `€`. [Answer] ## Fondamentale Visuale .RETE - *Visual Basic .NET, translated to ITALIAN* The program is much simple (aimed at translating itself). Some points: * I/O : this is a module with a obvious function to be called * grammar is mostly correct (feels almost natural) * english and italian word position is different so i could not (easily) write some function to fix that, and preferred static translation pairs * i have conjugated imperative verbs to the 2nd person, as in a literal italian translation they would sound and feel wrong (as wrong as windows 8+ talking in 1d person) * ~~the translation pairs are obfuscated so the english ones don't get also translated. thus, if there was an interpreter, the translated program would work~~ **i only left some `"+"` to avoid overtranslation** (many english words are contained in italian ones, so it would end up translating italian to italian with duplication of suffixes) ``` Module Italian Dim Tokens As New List(Of Tuple(Of String, String)) Sub AddPair(a As String, b As String) Tokens.Add(Tuple.Create(a, b)) End Sub Sub init() AddPair(" Italian", " Italia" + "no") : AddPair("Module", "Modulo") AddPair("lacks", "non ha") : AddPair("AddPair", "AggiungiCoppia") AddPair(" italian", " l'italiano") AddPair("Next", "Appresso") : AddPair("Tokens", "Frammenti") AddPair("init", "iniz") : AddPair(" As ", " Come ") AddPair("Tuple", "Coppia") : AddPair("For Each", "Per Ogni") AddPair("Of", "Di") : AddPair(" only", " e basta") AddPair("Sub", "Proc") : AddPair("so i will add", "quindi aggiungerò") AddPair("Function", "Funzione") : AddPair("Dim", "Def") AddPair(" a ", " una ") : AddPair("support", "il s" + "upporto") AddPair("used types", "i tipi utilizzati") REM italian lacks a gender-indipendent form for adjectives REM so i will add support for used types only AddPair(" New List", " una Nuova Lista") AddPair("Create", "Crea") : AddPair("End", "Fine") AddPair("REM", "RIC") : AddPair(" for ", " per ") AddPair("gender-indipendent form", "forma indipendente dal genere") AddPair("String", "Sequenza") : AddPair("adjectives", "gli aggettivi") AddPair(" TranslateToItalian", " TraduciInItaliano") End Sub Function TranslateToItalian(o As String) As String Dim ret As String = o : init() For Each t As Tuple(Of String, String) In Tokens ret = ret.Replace(t.Item1, t.Item2) Next Return ret End Function End Module ``` **Italian, here we go!** The result on itself: ``` Modulo Italiano Def Frammenti Come una Nuova Lista(Di Coppia(Di Sequenza, Sequenza)) Proc AggiungiCoppia(a Come Sequenza, b Come Sequenza) Frammenti.Add(Coppia.Crea(a, b)) Fine Proc Proc iniz() AggiungiCoppia(" Italiano", " Italia" + "no") : AggiungiCoppia("Modulo", "Modulo") AggiungiCoppia("non ha", "non ha") : AggiungiCoppia("AggiungiCoppia", "AggiungiCoppia") AggiungiCoppia(" l'italiano", " l'italiano") AggiungiCoppia("Appresso", "Appresso") : AggiungiCoppia("Frammenti", "Frammenti") AggiungiCoppia("iniz", "iniz") : AggiungiCoppia(" Come ", " Come ") AggiungiCoppia("Coppia", "Coppia") : AggiungiCoppia("Per Ogni", "Per Ogni") AggiungiCoppia("Di", "Di") : AggiungiCoppia(" e basta", " e basta") AggiungiCoppia("Proc", "Proc") : AggiungiCoppia("quindi aggiungerò", "quindi aggiungerò") AggiungiCoppia("Funzione", "Funzione") : AggiungiCoppia("Def", "Def") AggiungiCoppia(" una ", " una ") : AggiungiCoppia("il supporto", "il s" + "upporto") AggiungiCoppia("i tipi utilizzati", "i tipi utilizzati") RIC l'italiano non ha una forma indipendente dal genere per gli aggettivi RIC quindi aggiungerò il supporto per i tipi utilizzati e basta AggiungiCoppia(" una Nuova Lista", " una Nuova Lista") AggiungiCoppia("Crea", "Crea") : AggiungiCoppia("Fine", "Fine") AggiungiCoppia("RIC", "RIC") : AggiungiCoppia(" per ", " per ") AggiungiCoppia("forma indipendente dal genere", "forma indipendente dal genere") AggiungiCoppia("Sequenza", "Sequenza") : AggiungiCoppia("gli aggettivi", "gli aggettivi") AggiungiCoppia(" TraduciInItaliano", " TraduciInItaliano") Fine Proc Funzione TraduciInItaliano(o Come Sequenza) Come Sequenza Def ret Come Sequenza = o : iniz() Per Ogni t Come Coppia(Di Sequenza, Sequenza) In Frammenti ret = ret.Replace(t.Item1, t.Item2) Appresso Return ret Fine Funzione Fine Modulo ``` [Answer] # C, Spanish - C Input/Output via STDIN/STDOUT (use `./c-spanish < c-spanish.c`). If `extra = 0` is changed to `extra = 1`, then the output of this program is essentially a mutual quine. Otherwise, the output is a compilable C program that works like `cat`. Extra spaces in the source are necessary (as they are replaced with characters in the Spanish version). ``` #define B(_, __) __ ## _ #define C(_, __) B(_,__) #define char C(C(r, ha), c) #define gets C(ets, g) #define if C(f, i) #define int C(C(ed, n), s##ig) #define is == #define main C(C(n, ai), m) #define puts C(C(s, t), C(u, p)) #define void C(id, C(o, v)) #define while(x) C(r, C(o, f))(;x;) int x, y, extra = 0; void count (char *sheep); void try_replace (char *cake , char *bacon , char *sheep); void translate(char *sheep){ char *array [] = { "array ", "matriz", "bacon ", "tocino", "cake ", "pastel", "char", "car ", "count ", "cuenta", "gets ", "traec", "if", "si", "int ", "ent ", "is", "es", "main ", "principal", "peace", "paz ", "puts", "ponc", "sheep", "oveja", "translate", "traduce ", "truth ", "verdad", "try_replace ", "trata_de_reemplazar", "void", "nada", "war ", "guerra", " while", "mientras", }; int war = 19, peace = -1; while(!(--war is peace)){ count (sheep); int truth = x, cake = 0; while(!(cake is truth )){ try_replace (&sheep[cake ], array [2 * war ], array [1 + 2 * war ]); if(extra && !y) try_replace (&sheep[cake ], array [1 + 2 * war ], array [2 * war ]); ++cake ; } } } int main (){ char bacon [9999]; while(gets (bacon )){ translate(bacon ); puts(bacon ); } } void count (char *sheep){ x = 0; while(*sheep++ && ++x); } void try_replace (char *cake , char *bacon , char *sheep){ y = 0; char *truth = bacon ; while(*cake && *truth && *sheep && *cake is *truth ) ++cake , ++truth , ++sheep; if(!*truth ){ while(!(bacon is truth )) *--cake = *(--truth , --sheep); y = 1; } } ``` Words translated: ``` array -> matriz bacon -> tocino cake -> pastel char -> car (short for carácter) count -> cuenta gets -> traec (TRAE la Cadena) if -> si int -> ent (short for entero) is -> es main -> principal peace -> paz puts -> ponc (PON la Cadena) sheep -> oveja translate -> traduce truth -> verdad try_replace -> trata_de_reemplazar void -> nada war -> guerra while -> mientras ``` ## Output **With `extra = 0`:** ``` #define B(_, __) __ ## _ #define C(_, __) B(_,__) #define car C(C(r, ha), c) #define traec C(ets, g) #define si C(f, i) #define ent C(C(ed, n), s##ig) #define es == #define principal C(C(n, ai), m) #define ponc C(C(s, t), C(u, p)) #define nada C(id, C(o, v)) #define mientras(x) C(r, C(o, f))(;x;) ent x, y, extra = 0; nada cuenta(car *oveja); nada trata_de_reemplazar(car *pastel, car *tocino, car *oveja); nada traduce (car *oveja){ car *matriz[] = { "matriz", "matriz", "tocino", "tocino", "pastel", "pastel", "car ", "car ", "cuenta", "cuenta", "traec", "traec", "si", "si", "ent ", "ent ", "es", "es", "principal", "principal", "paz ", "paz ", "ponc", "ponc", "oveja", "oveja", "traduce ", "traduce ", "verdad", "verdad", "trata_de_reemplazar", "trata_de_reemplazar", "nada", "nada", "guerra", "guerra", "mientras", "mientras", }; ent guerra = 19, paz = -1; mientras(!(--guerra es paz )){ cuenta(oveja); ent verdad = x, pastel = 0; mientras(!(pastel es verdad)){ trata_de_reemplazar(&oveja[pastel], matriz[2 * guerra], matriz[1 + 2 * guerra]); si(extra && !y) trata_de_reemplazar(&oveja[pastel], matriz[1 + 2 * guerra], matriz[2 * guerra]); ++pastel; } } } ent principal(){ car tocino[9999]; mientras(traec(tocino)){ traduce (tocino); ponc(tocino); } } nada cuenta(car *oveja){ x = 0; mientras(*oveja++ && ++x); } nada trata_de_reemplazar(car *pastel, car *tocino, car *oveja){ y = 0; car *verdad = tocino; mientras(*pastel && *verdad && *oveja && *pastel es *verdad) ++pastel, ++verdad, ++oveja; si(!*verdad){ mientras(!(tocino es verdad)) *--pastel = *(--verdad, --oveja); y = 1; } } ``` **With `extra = 1`:** ``` #define B(_, __) __ ## _ #define C(_, __) B(_,__) #define car C(C(r, ha), c) #define traec C(ets, g) #define si C(f, i) #define ent C(C(ed, n), s##ig) #define es == #define principal C(C(n, ai), m) #define ponc C(C(s, t), C(u, p)) #define nada C(id, C(o, v)) #define mientras(x) C(r, C(o, f))(;x;) ent x, y, extra = 1; nada cuenta(car *oveja); nada trata_de_reemplazar(car *pastel, car *tocino, car *oveja); nada traduce (car *oveja){ car *matriz[] = { "matriz", "array ", "tocino", "bacon ", "pastel", "cake ", "car ", "char", "cuenta", "count ", "traec", "gets ", "si", "if", "ent ", "int ", "es", "is", "principal", "main ", "paz ", "peace", "ponc", "puts", "oveja", "sheep", "traduce ", "translate", "verdad", "truth ", "trata_de_reemplazar", "try_replace ", "nada", "void", "guerra", "war ", "mientras", " while", }; ent guerra = 19, paz = -1; mientras(!(--guerra es paz )){ cuenta(oveja); ent verdad = x, pastel = 0; mientras(!(pastel es verdad)){ trata_de_reemplazar(&oveja[pastel], matriz[2 * guerra], matriz[1 + 2 * guerra]); si(extra && !y) trata_de_reemplazar(&oveja[pastel], matriz[1 + 2 * guerra], matriz[2 * guerra]); ++pastel; } } } ent principal(){ car tocino[9999]; mientras(traec(tocino)){ traduce (tocino); ponc(tocino); } } nada cuenta(car *oveja){ x = 0; mientras(*oveja++ && ++x); } nada trata_de_reemplazar(car *pastel, car *tocino, car *oveja){ y = 0; car *verdad = tocino; mientras(*pastel && *verdad && *oveja && *pastel es *verdad) ++pastel, ++verdad, ++oveja; si(!*verdad){ mientras(!(tocino es verdad)) *--pastel = *(--verdad, --oveja); y = 1; } } ``` [Answer] # Ruby, Catalan - Rubí It's quite a short code in ruby, so it's not that representative, but I've been a bit more verbose in the function names to show a bit more. This exercise remembered me too much of university classes where we used similar pseudocode to "program". ``` words = { while: "mentre", words: "paraules", end: "fi", nil: "res", gets: "obtingues_cadena", line: "línia", each: "per_cada_una", do: "fes", original: "original", replacement: "intercanvi", gsub: "substitueix_globalment", puts: "posa_cadena" } while (line = gets) != nil words.each do |original,replacement| line.gsub! original.to_s,replacement end puts line end ``` Applied to itself becomes: ``` paraules = { # Eliminat per simplificar codi } mentre (línia = obtingues_cadena) != res paraules.per_cada_una fes |original,intercanvi| línia.substitueix_globalment! original.to_s,intercanvi fi posa_cadena línia fi ``` [Answer] # Python 3, Lojban Where I needed to reorder sumti places, I enclosed the words in brackets, e.g (te tcidu fe) Code: ``` dictionary = [ ('basti fa', 'with'), ('ro', 'for'), ("vidnyja'o", 'print'), ('nenri', 'in'), ('lujvo', 'word'), ('jbovlaste', 'dictionary'), ('basygau', 'replace'), ('(te tcidu fe)', 'read'), ('datnyvei','file'), ('vlamei', 'text'), ('kargau', 'open'), ('la .lojban.', 'lojban'), ('no', '0'), ('pa', '1'), ('as', ''), ('with', 'basti fa'), ('for', 'ro'), ('print', "vidnyja'o"), ('in', 'nenri'), ('word', 'lujvo'), ('dictionary', 'jbovlaste'), ('replace', 'basygau'), ('read', '(te tcidu fe)'), ('file', 'datnyvei'), ('text', 'vlamei'), ('open', 'kargau'), ('lojban', 'la .lojban.'), ('0', 'no'), ('1', 'pa') ] with open('lojban.py', 'r') as file: text = file.read() for word in dictionary: text = text.replace(word[0], word[1]) print(text) ``` And its output: ``` jbovlaste = [ ('basti fa', 'basti fa'), ('ro', 'ro'), ("vidnyja'o", 'vidnyja'o'), ('nenri', 'nenri'), ('lujvo', 'lujvo'), ('jbovlaste', 'jbovlaste'), ('basygau', 'basygau'), ('(te tcidu fe)', '(te tcidu fe)'), ('datnyvei','datnyvei'), ('vlamei', 'vlamei'), ('kargau', 'kargau'), ('la .lojban.', 'la .lojban.'), ('no', 'no'), ('pa', 'pa'), ('', ''), ('basti fa', 'basti fa'), ('ro', 'ro'), ('vidnyja'o', "vidnyja'o"), ('nenri', 'nenri'), ('lujvo', 'lujvo'), ('jbovlaste', 'jbovlaste'), ('basygau', 'basygau'), ('(te tcidu fe)', '(te tcidu fe)'), ('datnyvei', 'datnyvei'), ('vlamei', 'vlamei'), ('kargau', 'kargau'), ('la .lojban.', 'la .lojban.'), ('no', 'no'), ('pa', 'pa') ] basti fa kargau('la .lojban..py', 'r') datnyvei: vlamei = datnyvei.(te tcidu fe)() ro lujvo nenri jbovlaste: vlamei = vlamei.basygau(lujvo[no], lujvo[pa]) vidnyja'o(vlamei) ``` [Answer] # Javascript ES6, Esperanto, Ĝavoskripto ``` f=_=>f.toString().replace(/toString/g,'konvertiLaĉi').replace(/replace/g,'anstataŭigi');f() ``` I took some liberties with camelcasing and wording (I translated 'convert to string' instead of 'to string'). I'll complicate things later when I have more time. ]
[Question] [ Write a program that outputs ``` Do not repeat yourself! ``` Your program code must respect the following constraints : * its length must be an even number * each character that is in position `2n` (where `n` is an integer > 0) must be equal to the character in position `2n-1`. The second character of the program is equal to the first, the fourth is equal to the third, etc. Newlines count as characters! This is code-golf, so the shortest code wins! ## Examples `HHeellllooWWoorrlldd` is a valid program `123` or `AAABBB` or `HHeello` are incorrect ## Verification You can use [this CJam script](http://cjam.aditsu.net/#code=q2%2F%7B)-%7D%2F%5Ds%22not%20%22*%22valid%22) to verify that your source code is valid. Simply paste your code into the "Input" box and run the script. [Answer] # [Hexagony](https://github.com/mbuettner/hexagony), ~~166~~ ~~126~~ 124 bytes ``` \\;;;;33rr''22DD..));;;;;;oo;;}}eeoo\\@@nn;;;;ee;;;;aass&&;;uuoo;;;;..\\\\;;ttee..pp;;tt;;;;..rr;;''ll..'';;;;..;;}}ff..}}yy ``` Inserting the implicit no-ops and whitespace, this corresponds to the following source code: ``` \ \ ; ; ; ; 3 3 r r ' ' 2 2 D D . . ) ) ; ; ; ; ; ; o o ; ; } } e e o o \ \ @ @ n n ; ; ; ; e e ; ; ; ; a a s s & & ; ; u u o o ; ; ; ; . . \ \ \ \ ; ; t t e e . . p p ; ; t t ; ; ; ; . . r r ; ; ' ' l l . . ' ' ; ; ; ; . . ; ; } } f f . . } } y y . . . ``` I'm sure it's possible to shorten this even more, and maybe even solve it in side-length 6, but it's getting tricky... ## How it works [![enter image description here](https://i.stack.imgur.com/ZwOwF.png)](https://i.stack.imgur.com/ZwOwF.png) Diagram generated with [Timwi's Hexagony Colorer](https://github.com/Timwi/HexagonyColorer). The code is completely linear. The `\` right at the start redirects the IP into a diagonal, such that we don't need to worry about the doubled characters at all. The coloured paths are executed in the order orange/red, blue/grey, green, purple (when there are two paths of the same colour, the left-hand path is executed first, before wrapping around to the right-hand one). If we ignore no-ops, mirrors and commands which are overridden by others, the linear code comes down to this: ``` D;o;&32;}n;o;t;';}r;e;p;e;a;t;';}y;o;u;r;s;e;l;f;');@ ``` Letters in Hexagony just set the current memory edge's value to the letter's character code. `;` prints the current memory edge as a character. We use `&` to reset the memory edge to `0` and print a space with `32;`. `}` moves to a different edge, so that we can remember the `32` for further spaces. The rest of the code just prints letters on the new edge, and occasionally moves back and forth with `';}` to print a space. At the end we move to the space edge again with `'`, increment the value to 33 with `)` and print the exclamation mark. `@` terminates the program. [Answer] # GolfScript, ~~130~~ ~~84~~ 76 bytes ``` 22..!!..00)){{DDoo nnoott rreeppeeaatt yyoouurrsseellff}}``%%>><<[[33]]++ ``` Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=MjIuLiEhLi4wMCkpe3tERG9vICBubm9vdHQgIHJyZWVwcGVlYWF0dCAgeXlvb3V1cnJzc2VlbGxmZn19YGAlJT4%2BPDxbWzMzXV0rKw%3D%3D). ### How it works The GolfScript interpreter starts by placing an empty string on the stack. ``` 22 # Push 22. .. # Push two copies. !! # Negate the last copy twice. Pushes 1. .. # Push two copies. 00 # Push 0. )) # Increment twice. Pushes 2. # STACK: "" 22 22 1 1 1 2 {{DDoo nnoott rreeppeeaatt yyoouurrsseellff}} `` # Push a string representation of the string representation of the block. # This pushes "{{DDoo nnoott rreeppeeaatt yyoouurrsseellff}}" (with quotes). %% # Take every second element of that string, then every element of the result. >> # Discard the first element of the result. Repeat. << # Truncate the result to length 22. Repeat. [[ # Begin a two-dimensional array. 33 # Push 33, the character code of '!'. ]] # End the two-dimensional array. ++ # Concatenate the empty string, the 22-character string and the array [[33]]. ``` Concatenating an array with a string flattens, so the result is the desired output. [Answer] # [Unary](https://esolangs.org/wiki/Unary), ~1.86 × 10222 Simple brainfuck -> unary answer. Very sub-optimal ;). The program consists of an even number of 0’s; specifically: > > 1859184544332157890058930014286871430407663071311497107104094967305277041316183368068453689248902193437218996388375178680482526116349347828767066983174362041491257725282304432256118059236484741485455046352611468332836658716 > > > of them. Original brainfuck code: ``` ++++[++++>---<]>+.[--->+<]>+++.[--->+<]>-----.+[----->+<]>+.+.+++++.[---->+<]>+++.---[----->++<]>.-------------.+++++++++++.-----------.----.--[--->+<]>-.[---->+<]>+++.--[->++++<]>+.----------.++++++.---.+.++++[->+++<]>.+++++++.------.[--->+<]>-. ``` [Answer] # Ruby - 2100 1428 1032 820 670 bytes This assumes the output can be a return value from a function (it wasn't specified that the output needs to be to STDOUT) Code: ``` ((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33)) ``` The trick is to build the string from an empty string `""` using the append operation `<<` and the ASCII codes of the characters. To get the numbers for the ASCII codes I'm trying to decompose the number into values I can easily generate. For example ASCII `90` is just `88+1+1`, which is: * `88` is okay on it's own * `11**00` is `11^0`, which is simply `1` Fortunately both `++` and `--` would mean `add` in ruby, so I can write `90` as `88++11**00++11**00` There are some tricks to get to some numbers easier than just adding 1s, here is the code I'm using to generate the above (which includes all mappings I'm using): ``` d = "Do not repeat yourself!" d.each_char do |c| print "((" end print '""' VALUES = [ [0,'00'], [1,'11**00'], [4,'((11**00<<11**00<<11**00))'], [5,'((11>>11**00))'], [11,'11'], [16,'((33>>11**00))'], [22,'22'], [27,'((55>>11**00))'], [33,'33'], [38,'((77>>11**00))'], [44,'44'], [49,'((99>>11**00))'], [55,'55'], [66,'66'], [77,'77'], [88,'88'], [99,'99'] ].reverse d.each_char do |c| print "<<" num = c.ord while num != 0 convert = VALUES.find{|val|val.first<=num} print convert.last num -= convert.first print "++" unless num == 0 end print "))" end ``` I'm still thinking about other tricks to decrease the characters required to get to a number. Note that if you use the `-rpp` flag, and add `pp` to the start of the code like so: ``` pp((((((((((((((((((((((((((((((((((((((((((((((""<<66++11**00++11**00))<<99++11++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11))<<99++11++11**00))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++11++((11**00<<11**00<<11**00))))<<99++11**00++11**00))<<99++11++11**00++11**00))<<99++11**00++11**00))<<88++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++((33>>11**00))++11**00))<<((55>>11**00))++((11>>11**00))))<<99++22))<<99++11++11**00))<<99++((33>>11**00))++11**00++11**00))<<99++11++((11**00<<11**00<<11**00))))<<99++((33>>11**00))))<<99++11**00++11**00))<<99++((11>>11**00))++((11**00<<11**00<<11**00))))<<99++11**00++11**00++11**00))<<33)) ``` then for extra 2+4 bytes this can function as a fully complete program, but it will print an extra `"` before and after the required string: Example: ``` $ ruby -rpp golf.rb "Do not repeat yourself!" ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 174 bytes ``` vv 77 99 ** 00 77 bb ** pp "" !! ff ll ee ss rr uu oo yy tt aa ee pp ee rr tt oo nn oo DD "" ~~ oo ll 11 == ;; 00 66 bb ** .. ``` Thankfully, in a sense the restriction doesn't apply vertically. However, the biggest problem is that we need to double every newline. The code that runs roughly goes like this: ``` v Redirect instruction pointer to move downwards 79*07b*p Place a ? on row 77 before the first ; "..." Push "Do not repeat yourself!" backwards, riffled between spaces [main loop] ~o Pop a space and output a char l1=?; If there is only the final space left, halt 06b*. Jump back to the start of the loop ``` Note that the program has no double spaces — when in string mode, ><> pushes spaces for empty cells. Conversely, however, this means that a solution using `g` (read single cell from source code) would be trickier, since what spaces are in the program become NULs when read. (Note: This can be 50 bytes shorter if it [terminates with an error](http://pastebin.com/UzLESVzm), but I like it this way.) [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting), ~~186~~ 146 bytes > > 끄끄닶닶긂긂닦닦닶닶덇덇긂긂댧댧뉖뉖댇댇뉖뉖눖눖덇덇긂긂뎗뎗닶닶덗덗댧댧댷댷뉖뉖닆닆뉦뉦긒긒 > > > 껢껢鎵鎵❶❶合合虛虛替替標標現現併併一一終終 > > > To be clear, there are three lines of code, the middle of which is empty, because the newline needs to be duplicated. The byte count is based on UTF-16 encoding. # Explanation The block of Korean characters at the start pushes the string `"DDDof� \"\u0002nf�of�twG \"\u0002rw'efVpw\aefVaf\u0016twG \"\u0002yw�of�uwWrw'sw7efVlf�fff!\"\u0012"`. You will notice that every *third* character is a character we want; the rest is gibberish. Here’s why: In Sclipting, two Korean characters encode three bytes. Thus, each Korean character effectively encodes 12 bits. To get a string starting with `D`, the first 8 bits have to be `0x44`; the rest don’t matter, but since we have to repeat every character, the 12th to 20th bits are also going to be `0x44`. Thus, we will have a value of the form `0x44n44n` for some *n*, which decomposes into the three bytes `0x44 0xn4 0x4n`. For the `o`, which is `0x6F`, we get the bytes `0x6F 0xn6 0xFn`. Since I’m lazy, I started by encoding `"DDDooo nnnooottt (etc.)"` and then replaced every other character with the previous, which is why I get `0x444444` = `"DDD"` for the `D` and `0x6F66F6` = `"of�"` for the `o`. The `�` is there because `0xF6` by itself is invalid UTF-8 encoding. Now, back to the program. The rest of the program proceeds as follows: > > 껢껢 — pushes the string `".\"�"` > > > 鎵鎵 — removes the last character twice, leaving us with `"."` > > > ❶❶ — two duplicates. Stack now: `[".", ".", "."]` > > > 合合 — concatenate twice. Stack now: `["..."]` > > > Now, what I *want* to do next is use `"..."` as a regular expression so that I can match three characters from the original string at a time, using the 替...終 loop construct. However, since every instruction is duplicated, I need to have *two* such regular-expression loops nested inside each other, and if the stack underruns I get a runtime error. Therefore, > > 虛虛 — push the empty string twice > > > and *then* start the loops. This way, the outer loop iterates only once because it matches the regular expression `""` against the string `""`, which yields a single match. The inner loop runs once for every match of `"..."` against the big string. The body of the loop is: > > 標標 — push two marks onto the stack. Stack now: `[mark mark]` > > > 現現 — push two copies of the current regex match. Stack now: `[mark mark "DDD" "DDD"]` > > > 併併 — concatenate up to the first mark. Stack now: `["DDDDDD"]` > > > 一一 — take first character of that string, and then (redundantly) the first character of that. Stack now has the character we want. > > > The inner loop ends here, so every match of the regular expression is replaced with the first character of that match. This leaves the desired string on the stack. Then the outer loop ends, at which point the desired string is taken off the stack and the only match of `""` in the string `""` is replaced with it, leaving the desired string once again on the stack. [Answer] # [Labyrinth](http://esolangs.org/wiki/Labyrinth), 528 bytes ``` 66))__vv ..33::00&&__vv ..44__99||__vv ..33::00&&__vv ..99))__vv ..99))__vv ..44__88$$__vv ..22__99++__vv ..22__99$$__vv ..22__99))$$__vv ..33__77$$__vv ..33__vv ..44__99||__^^ ..11__99++__^^ ..44__88$$__^^ ..44((__88$$__^^ ..11))__99++__^^ ..99((__^^ ..33::00&&__^^ ..44__99||__^^ ..44((__88$$__^^ ..99))__^^ ..11__99$$((__^^ ..@@ xx ``` The double newlines hurt, but at least this proves that it's doable! Each character is printed one-by-one, first by forming the code point then printing a single char. The code points are formed by: ``` D 68 66)) o 111 44__99|| 32 33::00&& n 110 11__99++ t 116 44__88$$ r 114 44((__88$$ e 101 99)) p 112 11))__99++ a 97 99(( y 121 22__99++ u 117 22__99$$ s 115 22__99))$$ l 108 33__77$$ f 102 11__99$$(( ! 33 33 ``` where ``` )( Increment/decrement by 1 respectively &|$ Bitwise AND/OR/XOR respectively + Add : Duplicate _ Push zero 0-9 Pop n and push n*10+<digit> ``` The unusual behaviour of Labyrinth's digits is exploited in `33::00&&`, which is actually ``` [33] -> [33 33] -> [33 33 33] -> [33 33 330] -> [33 33 3300] -> [33 32] -> [32] : : 0 0 & & ``` Each single char is printed with the mechanism ``` __vv .. xx ``` The `xx` exist only to pad the grid so that it's 5 high. First the `__` push two zeroes, then we hit a grid rotation operator `v`. We pop a zero and rotate: ``` __ v v . . xx ``` and again: ``` __ v v. xx. ``` We then move rightwards to the `.` on the third row, thus executing the print command only once. [Answer] # CJam - 176 136 bytes ``` 66))HH77++GG00++BB88++HH77++EE88++GG00++DD88++99))CC88++99))AA77++EE88++GG00++BB99++HH77++KK77++DD88++JJ77++99))AA88++II66++33]]{{cc}}// ``` *Thanks to Sp3000 for dividing my program size by two :-)* **Explanation** * The codes `HH77++`, `GG00++`, ... compute the integer ascii code of the characters by adding numbers (for example: `HH77++' pushes 17, 17 and 77 on the stack, then add these 3 numbers) * the portion of code at the end `]]{{cc}}//` loops through the ascii codes and convert them to characters. Try it [here](http://cjam.aditsu.net/#code=66))HH77%2B%2BGG00%2B%2BBB88%2B%2BHH77%2B%2BEE88%2B%2BGG00%2B%2BDD88%2B%2B99))CC88%2B%2B99))AA77%2B%2BEE88%2B%2BGG00%2B%2BBB99%2B%2BHH77%2B%2BKK77%2B%2BDD88%2B%2BJJ77%2B%2B99))AA88%2B%2BII66%2B%2B33%5D%5D%7B%7Bcc%7D%7D%2F%2F) [Answer] # [Self-modifying Brainf\*\*\*](http://esolangs.org/wiki/Self-modifying_Brainfuck), 72 bytes Note that `\x00` represents a literal `NUL` hex byte (empty cell). The source code is placed on the tape, left of the starting cell. ``` !!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD\0\0<<<<<<++[[<<]]<<[[..<<]] ``` ### Explanation ``` !!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD The string on the tape for easy printing \x00\x00 A separator to make printing shorter <<<<<<++ Change first '.' to '0' (comment) [[<<]]<< Move to separator, then left to string [[0.<<]] Print string ``` Also, before making this program, I was making one using only BF characters in the source. It's possible! It's also much longer, since for an odd ASCII value, I was going to create double the value, then divide by two. Somewhat shorter would be modifying the entire source to generate odd values to start with. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 66 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ““DDoo nn““oott rreepp““eeaatt yyoouurrss““eellff!!””ṛṛḷḷWWQQ€€ ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4oCcRERvbyAgbm7igJzigJxvb3R0ICBycmVlcHDigJzigJxlZWFhdHQgIHl5b291dXJyc3PigJzigJxlZWxsZmYhIeKAneKAneG5m-G5m-G4t-G4t1dXUVHigqzigqw&input=) ### Factoid The program still works if you remove every second character. [Try it online!](http://jelly.tryitonline.net/#code=4oCcRG8gbuKAnG90IHJlcOKAnGVhdCB5b3Vyc-KAnGVsZiHigJ3huZvhuLdXUeKCrA&input=) ### How it works ``` ““DDoo nn““oott rreepp““eeaatt yyoouurrss““eellff!!” ``` returns an array of string. The literal begins with a `“`, ends with a `”`, and the strings are delimited internally by `“`. The result is ``` ["", "DDoo nn", "", "oott rreepp", "", "eeaatt yyoouurrss", "", "eellff!!"] ``` The link's argument and the return value are set to this array of strings, then the remainder of the source code is executed. ``` <literal>”ṛṛḷḷWWQQ€€ Argument/return value: A (string array) ”ṛ Yield the character 'ṛ'. ṛ Select the right argument of 'ṛ' and A: A. ḷ Select the left argument of A and A: A. W Wrap; yield [A]. ḷ Select the left argument of A and [A]: A. W Wrap; yield [A]. Q Unique; deduplicate [A]. Yields [A]. Q€€ Unique each each; for each string s in A, deduplicate s. ``` [Answer] # [Gammaplex](http://esolangs.org/wiki/Gammaplex), 66 bytes ``` \\ XX""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD""XXXXrrRREE ``` Gammaplex is a 2D language that uses the position of the first newline as the line length, and ignore all other newlines. [Answer] # [MSM](http://esolangs.org/wiki/MSM), ~~270~~ 160 bytes ``` !!'',,ff'',,ll'',,ee'',,ss'',,rr'',,uu'',,oo'',,yy'',, '',,tt'',,aa'',,ee'',,pp'',,ee'',,rr'',, '',,tt'',,oo'',,nn'',, '',,oo'',,DD'',,...................... ``` My first MSM program! String output in MSM is done by pushing the individual characters onto the stack and joining them into a single string via `.`, e.g. ``` !olleH..... ``` The number of `.` is one less than the number of characters. For `Do not repeat yourself!` we need 22 `.`s. Luckily this is an even number, so we have 11 doubles ``` ...................... ``` Putting the letters in front of it requires some more effort. The pattern ``` cc'',, ``` does the trick for each character `c`. It evaluates as follows ``` cc'',, push c (remember: commands are taken from the left and operate on the right) c'',,c push c '',,cc quote ' and push ,,cc' pop ,cc pop c voilà! ``` We need 23 such patterns starting with `!!'',,` and ending with `DD'',,` followed by the 22 join commands `.`. [Answer] # Befunge 98, 70 66 bytes [Try it online!](https://tio.run/nexus/befunge-98#@29kZGCgpVVRoaSkqJiWlpOTmlpcXFRUWpqfX1mpoFBSkpiYmlpQkJpaVATi5efn5Sko5Oe7uIiLKyllZ@voODj8/w8A) After my invalid answer, here's a better one that actually fits the challenge! ``` 2200**xx""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD��""kk,,@@ ``` (Thanks to Martin Ender for suggesting the use of `��`, character 0x17, instead of `88ff++`) Explanation: ``` 2200 Push 2, 2, 0, and 0 onto the stack * Multiply 0 and 0, yielding 0 * Multiply 2 and 0, yielding 0 The stack is now [2, 0] x Pop a vector off the stack and set the instruction pointer delta to that The instruction pointer is now skipping over every other character, since the delta is (2, 0) "!f ... oD�" Push the string onto the stack, with the number 23 (number of characters in the string) at the top k, Pop characters off the stack and print them, 23 times @ End the program ``` [Answer] # [Backhand](https://github.com/GuyJoKing/Backhand), 54 bytes ``` vv""!!fflleessrruuooyy ttaaeeppeerr ttoonn ooDD""HH ``` [Try it online!](https://tio.run/##FcdLCsAgDAXAq8ScxYXXSG2kUPFJ/ICnT@ns5pL8PtJu972ZQyilVtUxzNYCziGaU0S1d1Wzf0BrRECMzCm5fw "Backhand – Try It Online") Since Backhand's pointer already moving at three cells a tick, all we need to do is decrease that to 2 using `v` [Answer] # [DC](https://rosettacode.org/wiki/Dc), ~~348~~ ~~346~~ ~~342~~ ~~306~~ ~~290~~ 278 bytes File `dnr6.short.dc` (without trailing newline): ``` AAzz--22222222vvPPAAAAAAAAvvPP88vvFFFFFFFFvv00++AAzz--PP11vvFFFFFFFFvv00++AAAAAAvvPP11vvEEEEEEEEvv00++OOOO//44999999vv++PP77II++OOOO//44999999vv++PPAAAAAAvv88vvFFFFFFFFvv00++PPAAzz--BBPP11vvFFFFFFFFvv00++77OOOO++++PPOOOO//44999999vv++66vvFFFFFFFFvv00++PP99zz++OO88++PPAAAAvv33PP ``` Run: ``` $ dc < dnr6.short.dc Do not repeat yourself! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~100~~ ~~58~~ 52 bytes *-6 bytes thanks to Kevin Cruijssen* ``` „„€€··™™……€€–– ……¹¹‚‚ ……––‚‚))εε##θθáá}}»»……!!θθJJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcM8EGpaA0SHth/a/qhlEQg1LAMhsOijhslApKAAETu089DORw2zgAgmApGHiGlqntt6bquy8rkd53YcXnh4YW3tod2HdkPUKSqCRL28/v8HAA "05AB1E – Try It Online") ``` „„€€· # dictionary string "g do" · # double (no effect on strings) ™ # title case: "G Do" ™ # title case again (no effect) ……€€–– # dictionary string "tools not–" # spaces necessary so "–…" isn't parsed as a dictionary word ……¹¹‚‚ # dictionary string "team repeat‚" # spaces necessary again ……––‚‚ # dictionary string "j yourself‚" ) # wrap the entire stack in an array ) # and again: [["G Do", "tools not–", "team repeat‚", "j yourself‚"]] ε } # for each: ε } # for each: # # split on spaces: ["tools", "not–"] # # and again: [["tools", "not–"]] θ # get the last element: ["tools", "not–"] θ # and again: "not–" á # keep only letters: "not" á # and again (no effect) » # join the list by newlines, joining sublists by spaces: # "Do not repeat yourself" » # join the stack by newlines, joining lists by spaces (no effect) ……!! # literal string "…!!" θ # get the last character: "!" θ # and again (no effect) J # join the stack without separators: "Do not repeat yourself!" J # and again (no effect) # implicit output ``` Idempotency rules. [Answer] # [BotEngine](https://github.com/SuperJedi224/Bot-Engine), 6x49=294 ``` vv PP !!ee ffee llee eeee ssee rree uuee ooee yyee ee ttee aaee eeee ppee eeee rree ee ttee ooee nnee ee ooee DDee >> ^^ ``` [Answer] # reticular, noncompeting, 62 bytes ``` 2200**UU""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!""oo;; ``` [Try it online!](http://reticular.tryitonline.net/#code=MjIwMCoqVVUiIkREb28gIG5ub290dCAgcnJlZXBwZWVhYXR0ICB5eW9vdXVycnNzZWVsbGZmISEiIm9vOzs&input=&args=) Explanation in parts: ``` 2200** 2200 the stack looks like [2 2 0 0] * [2 2 0*0] * [2 2*0*0] [2 0] ``` `U` sets the pointer direction to `(2, 0)`, that is, moving `2` x-units and `0` y-units, so it skips every other character, starting with the next `U` being skipped. Then, every other character is recorded, and it is equivalent to: ``` "Do not repeat yourself!"o; ``` which is a simple output program. ## Other This is competing for WallyWest's JavaScript bounty: I can prove that, while numbers can be constructed under this restriction, strings cannot. Since no literals can be used, as the placement of any literal-building character would create an empty string: ``` "" '' `` ``` Then, only some operator can be used; the only "paired" operators used are: ``` ++ -- << >> ** ~~ || && !! == ``` And none of these can cast numbers/others to strings. So no strings can be outputted. [Answer] ## [Alice](https://github.com/m-ender/alice), 74 bytes ``` aa00tt,,JJ""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!//@@""ooYY;;tt ``` [Try it online!](https://tio.run/nexus/alice#FccxDkARDADQ3Smqs4TdYjC5gdFQk6hUDU7v57/tvdZCUHWuFMScmQHmZFYFECFai6i1f/cynyOyN9EYvVvrfUqIzLXGqGrMex8 "Alice – TIO Nexus") ### Explanation The first catch is that we need to be able to enter the string, so we want to skip only the first `"`. We do this by jumping onto the first `"` because then the IP will move one cell before looking at the current cell again, so that it's the second `"` which enters string mode. But to be able to jump there, we need `10, 0` on top of the stack, in that order (second, top). This is done with `aa00tt,,`: ``` Stack: aa Push two 10s. [... 10 10] 00 Push two 0s. [... 10 10 0 0] tt Decrement twice. [... 10 10 0 -2] , Rotate(-2). [... 0 10 10] , Rotate(10). [... 0 10 0] ``` This rotation function pops an argument. If that argument is negative, it pushes the value on top of the stack down by that many positions. If the argument is positive, it goes looking for the element that many positions below the top and pulls it up to the top. Note that in the case of `Rotate(10)`, there aren't enough elements on the stack, but there is an implicit infinite amount of zeros at the bottom, which is why a zero ends up on top. Now we can `J`ump onto the first `"` using these two arguments. The second `"` enters string mode and records all of that `DDoo nnoott...`. When it hits the `/`, the IP is redirected southeast and we enter Ordinal mode. For now on the IP bounces up and down across the three lines (two of which are empty), so it first records three more spaces on lines two and three and then we leave string mode when it hits the `"`. Since we're in Ordinal mode at this time, all the recorded characters are pushed as a single string to the stack (even though we recorded most of them in Cardinal mode), so we end up with this string (note the trailing spaces): ``` DDoo nnoott rreeppeeaatt yyoouurrsseellff!! ``` Now the IP keeps bouncing up and down which means that it executes one command of every other pair, i.e. `Y` and `t`. Then the IP will hit the end of the grid on the second line and start bouncing backwards through the grid. This also switches in which pair of characters the IP hits the first line, so when going back it now executes `;`, `o` and `@`. So ignoring all the spaces and implicit IP redirections, the executed code is `Yt;o@` in Ordinal mode. The `Y` is the "unzip" command which separates a string into the characters in alternating positions. Since each character is repeated, that really just gives us two copies of the string we're going for, although the first copy has two trailing spaces and the second has one trailing space. `t` splits off that trailing space and `;` discards it. Finally, `o` prints the string and `@` terminates the program. [Answer] # [Stax](https://github.com/tomtheisen/stax), 70 bytes ``` GG11hh::zzaapp..}}..""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#c=GG11hh%3A%3Azzaapp..%7D%7D..%22%22DDoo++nnoott++rreeppeeaatt++yyoouurrsseellff%21%21%22%22&i=&a=1) Stax very fortunately has the builtin `::` for every-nth. All I need to is push the string doubled, push 2, and run `::`. Easy, right? Wrong. Pushing that string is tricky. The first quotation mark can be doubled by `..""`, which is a length-2 literal for `."` followed by a meaningful quotation mark. Problem is, I see no way to terminate the string (which is necessary, or else the doubled version will be printed) without starting a new one. The end of the program terminates string literals. If I can put this doubled literal there, perhaps there'll be a nice workaround. To jump somewhere from the end of a program, however, requires `G}`, so at minimum, I'm looking at this: ``` GG [deduplicate] }}""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` This does... nothing. `G` does not begin a block, so neither will jump to the second `}`. Again, I need to ignore one character: `..}}`. Execution jumps from the first `G` to the second `}`, continues to the end, jumps back to the second `G` and from there to the second `}`, and continues once more to the end before resuming at the start of the `[deduplicate]` section with the doubled string atop the stack. Deduplication is simple. `11hh` pushed eleven and halves it twice, rounding down both times and yielding two, and `::` will then get us the output we need. ``` GG11hh::..}}..""DDoo nnoott rreeppeeaatt yyoouurrsseellff!!"" ``` Uh-oh. This prints nothing. There are two problems here: first, that `..}` means the string `.}` will be atop the stack at the end of the program, and second, Stax's ordinary implicit output is now disabled! The worse issue is the output. When a Stax program terminates gracefully without printing anything, the top of the stack will be implicitly printed. But we haven't printed anything...? Ah, but we have. Unterminated string literals are printed rather than pushed, and even those two empty strings (from the unmatched `"` at the end), despite being empty, are enough to trip this check. Any printing must be done by hand. We'll need either `pp` or `PP`, and in this instance, ignoring the first through `..pp` is unacceptable, as it will print the string `.p`. That means we need our desired output either alone on the stack or in the top two along with an empty string. This latter is accomplished by pushing two empty strings (`zz`) and rotating the top three items twice (`aa`) before printing. Once that's done, we have a stack four strings tall. A fifth, `.}`, is then pushed before the program exits gracefully; at this point, the lack of implicit output becomes a blessing as well as a curse, as nothing extra will now be printed! ]
[Question] [ # Inspired by, and in memory of, my dear friend and colleague, [![Dan Baronet](https://i.stack.imgur.com/eSEJq.jpg)](http://www.dyalog.com/blog/2016/11/dan-baronet/) # [Dan Baronet](http://www.dyalog.com/blog/2016/11/dan-baronet/), 1956 – 2016. [R.I.P.](http://danielbaronet.rip/) He found [the shortest possible APL solution](https://codegolf.stackexchange.com/a/98764/43319) to this task: ### Task Given a Boolean list, count the number of trailing truth values. ### Example cases `{}` → `0` `{0}` → `0` `{1}` → `1` `{0, 1, 1, 0, 0}` → `0` `{1, 1, 1, 0, 1}` → `1` `{1, 1, 0, 1, 1}` → `2` `{0, 0, 1, 1, 1}` → `3` `{1, 1, 1, 1, 1, 1}` → `6` [Answer] # Dyalog APL, ~~6~~ 2 bytes ``` ⊥⍨ ``` Test it on [TryAPL](http://tryapl.org/?a=%28%u22A5%u2368%29%A8%28%u236C%280%29%281%29%280%201%201%200%200%29%281%201%201%200%201%29%281%201%200%201%201%29%280%200%201%201%201%29%281%201%201%201%201%201%29%29&run). ### How it works **⊥** (uptack, dyadic: decode) performs base conversion. If the left operand is a vector, it performs *mixed* base conversion, which is perfect for this task. For a base vector **b = bn, ⋯, b0** and a digit vector **a = an, ⋯, a0**, **b ⊥ a** converts **a** to the mixed base **b**, i.e., it computes **b0⋯bn-1an + ⋯ + b0b1a2 + b0a1 + a0**. Now, **⍨** (tilde dieresis, commute) modifies the operator to the left as follows. In a monadic context, it calls the operator with equal left and right arguments. For example, **⊥⍨ a** is defined as **a ⊥ a**, which computes **a0⋯an + ⋯ + a0a1a2 + a0a1 + a0**, the sum of all cumulative products from the right to the left. For **k** trailing ones, the **k** rightmost products are **1** and all others are **0**, so their sum is equal to **k**. [Answer] ## JavaScript (ES6), 21 bytes ``` f=l=>l.pop()?f(l)+1:0 ``` ### Test cases ``` f=l=>l.pop()?f(l)+1:0 console.log(f([])); // → 0 console.log(f([0])); // → 0 console.log(f([1])); // → 1 console.log(f([0, 1, 1, 0, 0])); // → 0 console.log(f([1, 1, 1, 0, 1])); // → 1 console.log(f([1, 1, 0, 1, 1])); // → 2 console.log(f([0, 0, 1, 1, 1])); // → 3 console.log(f([1, 1, 1, 1, 1, 1])); // → 6 ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), ~~7~~ ~~6~~ 5 bytes ``` @]#=+ ``` [Try it online!](http://brachylog.tryitonline.net/#code=QF0jPSs&input=WzE6MTowOjE6MV0&args=Wg) ### Explanation ``` @] A suffix of the Input... #= ...whose elements are all equal + Sum its elements ``` Since `@] - Suffix` starts from the biggest suffix all the way up to the smallest one, it will find the longest run first. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 bytes ``` ŒrṪP ``` [Try it online!](http://jelly.tryitonline.net/#code=xZJy4bmqUA&input=&args=WzEsIDEsIDAsIDEsIDFd) or [Verify all test cases.](http://jelly.tryitonline.net/#code=xZJy4bmqUArDh-KCrA&input=&args=W1tdLCBbMF0sIFsxXSwgWzAsIDEsIDEsIDAsIDBdLCBbMSwgMSwgMSwgMCwgMV0sIFsxLCAxLCAwLCAxLCAxXSwgWzAsIDAsIDEsIDEsIDFdLCBbMSwgMSwgMSwgMSwgMSwgMV1d) For the case where the list is empty, there are some curious observations. First, run-length encoding the empty list `[]` returns another empty list `[]`. Then retreiving the last element from that using tail `Ṫ` returns `0` instead of a pair `[value, count]` which are the regular elements of a run-length encoded array. Then product `P` returns `0` when called on `0` which is the expected result. ## Explanation ``` ŒrṪP Main link. Input: list M Œr Run-length encode Ṫ Tail, get the last value P Product, multiply the values together ``` [Answer] # Haskell, ~~26~~ 25 bytes ``` a%b|b=1+a|0<3=0 foldl(%)0 ``` Usage: ``` Prelude> foldl(%)0 [True,False,True,True] 2 ``` Pointfree version (26 bytes): ``` length.fst.span id.reverse ``` --- Using an integer list instead of a bool list (21 bytes, thanks to Christian Sievers): ``` a%b=b*(a+1) foldl(%)0 ``` Usage: ``` Prelude> foldl(%)0 [1,0,1,1] 2 ``` Pointfree version (25 bytes) ``` sum.fst.span(==1).reverse ``` [Answer] ## CJam (8 bytes) ``` {W%0+0#} ``` [Online test suite](http://cjam.aditsu.net/#code=qN%2F%7B'%E2%86%92%2F0%3D'%2C-~~%5D%0A%0A%7BW%250%2B0%23%7D%0A%0A~p%7D%2F&input=%7B%7D%20%E2%86%92%200%0A%7B0%7D%20%E2%86%92%200%0A%7B1%7D%20%E2%86%92%201%0A%7B0%2C%201%2C%201%2C%200%2C%200%7D%20%E2%86%92%200%0A%7B1%2C%201%2C%201%2C%200%2C%201%7D%20%E2%86%92%201%0A%7B1%2C%201%2C%200%2C%201%2C%201%7D%20%E2%86%92%202%0A%7B0%2C%200%2C%201%2C%201%2C%201%7D%20%E2%86%92%203%0A%7B1%2C%201%2C%201%2C%201%2C%201%2C%201%7D%20%E2%86%92%206) ### Dissection ``` { e# begin a block W% e# reverse the array 0+ e# append 0 so there's something to find 0# e# find index of first 0, which is number of nonzeros before it } ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ ~~10~~ ~~6~~ 5 bytes Saved 1 byte thanks to *carusocomputing*. ``` Î0¡¤g ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w44wwqHCpGc&input=MTEwMTEx) **Explanation** ``` Î # push 0 and input 0¡ # split on 0 ¤ # take last item in list g # get length ``` [Answer] ## Python, 31 bytes ``` lambda a:(a[::-1]+[0]).index(0) ``` [Answer] ## [Retina](http://github.com/mbuettner/retina), ~~7~~ 5 bytes ``` r`1\G ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYApyYDFcRw&input=CjAKMQowMTEwMAoxMTEwMQoxMTAxMQowMDExMQoxMTExMTE) (The first line enables a linefeed-separated test suite.) Defining the input format for Retina isn't entirely unambiguous. Since Retina has no concept of any type except strings (and also no value that can be used for our usual definition of truthy and falsy), I usually use `0` and `1` (or something positive in general) to correspond to truthy and falsy, as they represent zero or some matches, respectively. With single-character representations, we also don't need a separator for the list (which in a way, is more the more natural list representation for a language that only has strings). [Adám confirmed](https://codegolf.stackexchange.com/questions/98730/count-trailing-truths?noredirect=1#comment239932_98773) that this is an acceptable input format. As for the regex itself, it matches from `r`ight to left and `\G` anchors each match to the previous one. Hence, this counts how many `1`s we can match from the end of the string. [Answer] # [MATL](http://github.com/lmendo/MATL), 4 bytes ``` PYps ``` [Try it online!](http://matl.tryitonline.net/#code=UFlwcw&input=WzEsIDEsIDAsIDEsIDFd) ``` P % Flip Yp % Cumulative product s % Sum ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṣ0ṪL ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4bmjMOG5qkw&input=&args=WzEsMSwwLDEsMV0)**, or [all tests](http://jelly.tryitonline.net/#code=4bmjMOG5qkwKw4figqw&input=&args=W1tdLFswXSxbMV0sWzAsMSwxLDAsMF0sWzEsMSwxLDAsMV0sWzEsMSwwLDEsMV0sWzAsMCwxLDEsMV0sWzEsMSwxLDEsMSwxXV0) ### How? ``` ṣ0ṪL - Main link: booleanList ṣ0 - split on occurrences of 0 ([] -> [[]]; [0] -> [[],[]]; [1] -> [[1]]; ...) Ṫ - tail (rightmost entry) L - length ``` [Answer] # Mathematica, ~~25~~ 24 bytes ``` Fold[If[#2,#+1,0]&,0,#]& ``` [Answer] # J, ~~9~~ 3 bytes ``` #.~ ``` This is reflexive mixed base conversion. [Because this is the same as mixed base conversion.](https://codegolf.stackexchange.com/a/98764/31957) [Again.](https://codegolf.stackexchange.com/a/79653/31957) ## Test cases ``` v =: #.~ ]t =: '';0;1;0 1 1 0 0;1 1 1 0 1;1 1 0 1 1;0 0 1 1 1;1 1 1 1 1 1 ++-+-+---------+---------+---------+---------+-----------+ ||0|1|0 1 1 0 0|1 1 1 0 1|1 1 0 1 1|0 0 1 1 1|1 1 1 1 1 1| ++-+-+---------+---------+---------+---------+-----------+ v&.> t +-+-+-+-+-+-+-+-+ |0|0|1|0|1|2|3|6| +-+-+-+-+-+-+-+-+ (,. v&.>) t +-----------+-+ | |0| +-----------+-+ |0 |0| +-----------+-+ |1 |1| +-----------+-+ |0 1 1 0 0 |0| +-----------+-+ |1 1 1 0 1 |1| +-----------+-+ |1 1 0 1 1 |2| +-----------+-+ |0 0 1 1 1 |3| +-----------+-+ |1 1 1 1 1 1|6| +-----------+-+ ``` [Answer] ## Pyth, 6 bytes ``` x_+0Q0 ``` [Try it here!](http://pyth.herokuapp.com/?code=x_%2B0Q0&input=%5B0%2C1%2C1%2C0%2C1%2C1%5D&debug=0) Appends a 0, reverses and finds the index of the first 0 [Answer] # C90 (gcc), 46 bytes ``` r;main(c,v)int**v;{while(0<--c&*v[c])r++;c=r;} ``` Input is via command-line arguments (one integer per argument), output via [exit code](http://meta.codegolf.stackexchange.com/a/5330/12012). [Try it online!](https://tio.run/nexus/bash#@5@anJGvoJunoF5knZuYmaeRrFOmmZlXoqVVZl1dnpGZk6phYKOrm6ymVRadHKtZpK1tnWxbZF2rrmCnkFxSopfMlZ6crKBbXJJim2xpoKCbDxKFyujpA2lrBbANKvYQroIBuoAhhgoFQyA0wKISKmGITQKsC9MoiGGG2I1Clfr/HwA "Bash – TIO Nexus") ### How it works **r** is a global variable. Its type defaults to *int* and, being global, it value defaults to **0**. The function argument **c** defaults to *int* as well. It will hold the integer **n + 1** for arrays of **n** Booleans; the first argument of **main** is always the path of the executable. The function argument **v** is declared as `int**`. The actual type of **v** will be `char**`, but since we'll only examine the least significant bit of each argument to tell the characters **0** (code point **48**) and **1** (code point **49**) apart, this won't matter on little-endian machines. The while loop decrements **c** and compares it to **0**. Once **c** reaches **0**, we'll break out of the loop. This is needed only if the array contains no **0**'s. As long as `0<--c` returns **1**, we takes the **c**th command-line argument (`v[c]`) and extract its first character with by dereferencing the pointer (`*`). We take the bitwise AND of the Boolean `0<--c` and the code point of the character (and three garbage bytes that follow it), so the condition will return **0** once a **0** is encountered, breaking out of the loop. In the remaining case, while the command-line arguments are **1**, `r++` increments **r** by **1**, thus counting the number of trailing **1**'s. Finally, `c=r` stores the computed value of **r** in **c**. With default settings, the compiler optimize and remove the assignment; it actually generates the `movl %eax, -4(%rbp)` instruction. Since `ret` returns the value of the EAX register, this generates the desired output. Note that this code does *not* work with C99, which returns **0** from *main* if the end of *main* is reached. [Answer] # k, 6 bytes ``` +/&\|: ``` This function composition translates to `sum mins reverse` in `q`, the language's more readable sibling, where mins is a rolling minimum. [Answer] # R, 40 39 25 bytes Completely reworked solution thanks to @Dason ``` sum(cumprod(rev(scan()))) ``` Read input from stdin, reverse the vector and if the first element of is `!=0` then output the the first length of the run-length encoding (`rle`), else `0`. [Answer] ## Haskell, 24 bytes ``` foldl(\a b->sum[a+1|b])0 ``` Iterates over the list, adding one for each element, resetting to `0` after it hits a `False`. **16 bytes** with 0/1 input: ``` foldl((*).(+1))0 ``` If the list were guaranteed non-empty, we could get 14 bytes: ``` sum.scanr1(*)1 ``` This computes the cumulative product from the back, then sums them. The cumulative product remains 1 until a 0 is hit, and then becomes 0. So, the 1's correspond to trailing 1's. [Answer] ## Pyke, ~~10~~ 6 bytes ``` _0+0R@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=_0%2B0R%40&input=%5B1%2C++1%2C+1%2C+1%2C+1%5D) [Answer] # C#6, ~~103~~ 72 bytes ``` using System.Linq; int a(bool[] l)=>l.Reverse().TakeWhile(x=>x).Count(); ``` Using non-generic list beats generic list by 1 byte lol -31 bytes thanks to Scott [Answer] # [Japt](https://github.com/ETHproductions/japt) `-hx`, 3 bytes ``` i ô ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=aSD0&input=LWh4ClswLCAwLCAxLCAwLCAwLCAxLCAxLCAxXQ==) Japt's flag combinations rock. ### How it works ``` Ui ô Ui Insert `undefined` at index 0 ô Split at falsy items -h Take last element -x Sum ``` If we didn't have to handle the special case `[]`, we could get away with 1 byte `ô`, winning over APL. [Answer] # Python, 37 bytes ``` f=lambda l:len(l)and-~f(l[:-1])*l[-1] ``` [Answer] # [DASH](https://github.com/molarmanful/DASH), 16 bytes ``` @len mstr"1+$"#0 ``` It's not the shortest possible DASH solution, but the shortest possible DASH solution is bugging out on me. I'm posting this novel approach in its place. Usage: ``` (@len mstr"1+$"#0)"100111" ``` # Explanation ``` @( #. Lambda len ( #. Get the length of the array after... mstr "1+$" #0 #. ... matching the argument with regex /1+$/ ) #. * mstr returns an empty array for no matches ) ``` [Answer] # Scala, 25 bytes ``` l=>l.reverse:+0 indexOf 0 ``` Ungolfed: ``` l=>(l.reverse :+ 0).indexOf(0) ``` Reverses the list, appends a 0 and find the first index of 0, which is the number of elements before the first 0 [Answer] ## Batch, 57 bytes ``` @set n=0 @for %%n in (%*)do @set/an=n*%%n+%%n @echo %n% ``` Takes input as command-line parameters. Works by multiplying the accumulator by the current value before adding it on, so that any zeros in the command line reset the count. Note that `%%n` is not the same as the `n` or `%n%` variable. [Answer] ## GolfSharp, 14 bytes ``` n=>n.V().O(F); ``` [Answer] # Java 7, 62 bytes ``` int c(boolean[]a){int r=0;for(boolean b:a)r=b?r+1:0;return r;} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/CX1cOb) ``` class M{ static int c(boolean[] a){ int r = 0; for (boolean b : a){ r = b ? r+1 : 0; } return r; } public static void main(String[] a){ System.out.print(c(new boolean[]{}) + ", "); System.out.print(c(new boolean[]{ false }) + ", "); System.out.print(c(new boolean[]{ true }) + ", "); System.out.print(c(new boolean[]{ false, true, true, false, false }) + ", "); System.out.print(c(new boolean[]{ true, true, true, false, true }) + ", "); System.out.print(c(new boolean[]{ true, true, false, true, true }) + ", "); System.out.print(c(new boolean[]{ false, false, true, true, true }) + ", "); System.out.print(c(new boolean[]{ true, true, true, true, true, true })); } } ``` **Output:** ``` 0, 0, 1, 0, 1, 2, 3, 6 ``` [Answer] # Perl 5.10, 22 bytes 21 bytes + 1 byte for `-a` flag. Since the regex-based expression was done... :p The input values for the array must be separated by a space. ``` $n++while pop@F;say$n ``` [Try it online!](https://ideone.com/SaIsrK) [Answer] ## Perl, 22 bytes 21 bytes of code + 1 byte for `-p` flag. ``` s/.(?=.*0)//g;$_=y;1; ``` To run it : ``` perl -pE 's/.(?=.*0)//g;$_=y;1;' <<< "0 1 1 0 1 1 1" ``` (Actually, the format of the input doesn't matter a lot : `0110111`, `0 1 1 0 1 1 1`, `[0,1,1,0,1,1,1]` etc. would all work) --- **18 bytes version** from [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) but it requires to supply the input as a string of 0 and 1, which isn't allowed : ``` perl -pE '/1*$/;$_=length$&' <<< '0110111' ``` [Answer] # PHP, 50 bytes ``` <?=strlen(preg_filter('/.*[^1]/','',join($argv))); ``` Weirdly my first try with a regex turned out shorter than my try with arrays... Use like: ``` php tt.php 1 1 0 1 1 ``` ]
[Question] [ Write the shortest program that prints the sound my alarm clock makes, and stops after an inputted number of `beep`s. For reference, here is the sound my alarm makes: ``` beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep ``` Basically `beep`, `beepbeep`, `beepbeepbeep`, and `beepbeepbeepbeep` repeated 5 times each with spaces in between, followed by a `beepbeep...beep` which is 25 `beep`s long with no spaces in between (does `beep` still sound like a word to you?). Your program should take a number as input (assume it's between 0 and 75), and stop printing after that many `beep`s. **Note:** Your program should stop after that many beeps, not after that many groups of beeps. For example, `7` will return `beep beep beep beep beep beepbeep`. Whitespace in between `beep`s must follow the exact pattern above, although any trailing whitespace or unsuppressable output from your compiler or interpreter is allowed. Test cases: ``` 3 beep beep beep 0 1 beep 7 beep beep beep beep beep beepbeep 8 beep beep beep beep beep beepbeep beep 55 beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeep 67 beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep ``` This is code golf, so the shortest answer in bytes, per language, wins. [Answer] # JavaScript (ES7), ~~55~~ 54 bytes ``` f=n=>n?f(n-1)+'beep'+[" "[n>50|n%~~(n**=.4)^52%~n]]:'' ``` [Try it online!](https://tio.run/##Dc27DoIwFADQna@4IZC2UAioFaMpTq7@ANaAWHyE3BIwLgi/XtnOdt7Vtxrq/tV9IjR3bW0jUeZ4bChGKQvJTeuOhIULboG5SH7ozzPFIJDxhl3Fyp9RqT0h9lCsOSQcUg4Zhx0HIThsMxU3pj9V9ZMiyBxGB6A2OJhWx6150PIMErwRpwt641KyBSVzJmb/ "JavaScript (Node.js) – Try It Online") ### How? Given \$1\le n< 50\$, we want to know the number of consecutive beeps that are expected in this part of the sequence. The exact value is given by: $$\left\lfloor\sqrt{\frac{2n}{5}}+\frac{1}{2}\right\rfloor$$ which is a slightly modified version of [A002024](https://oeis.org/A002024). But in practice, we only need an exact value on the boundaries of the runs of beeps and we can deal with a few off-by-one errors. That's why we instead compute the following approximation: $$k=\left\lfloor n^{2/5}\right\rfloor$$ We need to insert a space whenever one of the following conditions is satisfied: * \$k=1\$ and \$n\bmod 1=0\$ (the 2nd part being always true) * \$k=2\$ and \$n\bmod 2=1\$ * \$k=3\$ and \$n\bmod 3=0\$ * \$k=4\$ and \$n\bmod 4=2\$ All the above conditions can be merged into: $$(n \bmod k) = (52 \bmod (k+1))$$ \$52\$ being the smallest integer \$x>0\$ such that \$x\bmod 3=1\$, \$x\bmod 4=0\$ and \$x\bmod 5=2\$. We need an additional test for \$n\ge50\$, where all remaining beeps are concatenated together. Otherwise, unwanted spaces would be inserted, starting at \$n=54\$. Hence the final JS expression: ``` n > 50 | n % ~~(n **= 0.4) ^ 52 % ~n ``` which evaluates to `0` when a space must be inserted. --- # JavaScript (ES7), 55 bytes A simpler approach using a lookup bit mask. ``` f=n=>n?f(--n)+'beep'+(0x222222492555F/2**n&1?' ':''):'' ``` [Try it online!](https://tio.run/##HcbdCoIwGIDhc6/iO5C26TRdLfthelSH3UAFmm39IN9EIwLx2pf0wgPvq/pUfd0923eE9qadMwpVjoWhUYQsJFetWxLS5Cv@LTdCSnmYiyDAWVoQIFtC2MTtTgsOCYeUQ8ZhzUFKDqvsEhvb7av6QRFUDoMHUFvsbaPjxt5peQQF/oDjGf3BUGTTlMwbmfsB "JavaScript (Node.js) – Try It Online") [Answer] # x86-16 machine code, IBM PC DOS, ~~58~~ ~~54~~ 53 bytes Binary: ``` 00000000: a182 0086 e02d 3030 d50a 7423 95b8 2009 .....-00..t#.. . 00000010: b305 b101 8bf1 ba30 01cd 2183 fe05 740c .......0..!...t. 00000020: e20a 4b75 03b3 0546 8bce cd29 4d75 eac3 ..Ku...F...)Mu.. 00000030: 6265 6570 24 beep$ ``` Listing: ``` A1 0082 MOV AX, WORD PTR [82H] ; command line AL = first char, AH = second char 86 E0 XCHG AH, AL ; endian convert 2D 3030 SUB AX, '00' ; ASCII convert D5 0A AAD ; BCD to binary convert 74 23 JZ EXIT ; handle 0 input case 95 XCHG AX, BP ; Beeps Counter (BP) = user input B8 0920 MOV AX, 0920H ; AH = 9, AL = ' ' B3 05 MOV BL, 5 ; Space Counter (SC) = 5 B1 01 MOV CL, 1 ; Beeps per Space Counter (BpSC) = 1 8B F1 MOV SI, CX ; Beeps per Space (BpS) = 1 BA 0130 MOV DX, OFFSET BEEP ; DX pointer to 'beep' string BEEP_LOOP: CD 21 INT 21H ; display beep 83 FE 05 CMP SI, 5 ; exceeded 50 beeps? 74 0C JZ NO_SPACE ; if so, don't display space E2 0A LOOP NO_SPACE ; if BpSC not zero, don't display space 4B DEC BX ; decrement Space Counter (SC) 75 03 JNZ DO_SPACE ; if SC is zero, restart it and increment BpS B3 05 MOV BL, 5 ; reset SC to 5 46 INC SI ; increment BpS DO_SPACE: 8B CE MOV CX, SI ; reset Beeps per Space Counter (BpSC) CD 29 INT 29H ; display space NO_SPACE: 4D DEC BP ; decrement Beeps Counter (BP) 75 EA JNZ BEEP_LOOP EXIT: C3 RET ; return to DOS BEEP DB 'beep$' ``` Someone in the comments described this challenge as "evil". I wouldn't go that far... but definitely lacking empathy. Arbitrary modulos can be pesky in x86 when registers are tight. This is the inelegant counter/countdown approach (seemed only appropriate for an alarm clock challenge), basically just jockeying these three counters: * `SI` = *Beeps per Space (`BpS`)*: Start at `1`. Increment every `5` spaces displayed. Once `5` is reached, no more spaces are displayed. * `BX` = *Space counter (`SC`)*: Start at `5`. Decrement every space displayed. At `0`, increment `BpS` and reset to `5`. * `CX` = *Beeps per Space Counter (`BpSC`)*: Start at `1`. Decrement every `'beep'` displayed. At `0`, display a space and reset to current `BpS`. A standalone PC DOS executable, input is via command line. [![enter image description here](https://i.stack.imgur.com/133lH.png)](https://i.stack.imgur.com/133lH.png) **Props: -1 byte thx to [@gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!** [Answer] # [Python 3](https://docs.python.org/3/), ~~134~~ ~~124~~ 118 bytes ``` def f(n): b=[*'beep']*n for i in b'\4\t\16\23\30!*3<ER_ly\x86\x97\xa8\xb9\xca\xdb':b.insert(i,' ') return''.join(b) ``` [Try it online!](https://tio.run/##PY5BDoIwFAX3PcXTTSmpRq0CGnHnBdz6jaFaYo35kIpJOT3ixjnAzLR992jYDMPd1agTVjsBW55TaZ1r5SVlgboJ8PAMK2lNHS0zWhkyi0lq9sfT9dVTLDKK25xiVVC0W4q3iuLdyp2de3670CVeS0glEFz3CSzl/Nl4TqwaGCXORmOhsdTINQqNzUYjyy9C/Ms8Xo20wfPPhensMNXjrldq@AI "Python 3 – Try It Online") Explanation: Simply works by inserting a blank space at the required indices of the string. *Thanks to pxeger for -6 bytes* [Answer] # [R](https://www.r-project.org/), 95 bytes ``` substr(s<-Reduce(paste,strrep("beep",c(rep(1:4,e=5),25))),1,c(el(gregexpr("b",s))[scan()]+3,0)) ``` [Try it online!](https://tio.run/##FcqxCoNAEEXRf9lqHhlBk9iI/oStpFg3D5sgy4xC/n5dy3u4Voqfqx8mPjYzv2ei5OgHtZoxS1jJHDTJHd3wVk499NkD0K4yf7IZN/6z1TeoA4unuAs@j5e2QGnLBQ "R – Try It Online") Thanks to @Dingus for pointing out a bug which made my code longer (and also wrong). Thanks to madlaina for suggesting a better regex. Outgolfed handily by [Dominic van Essen](https://codegolf.stackexchange.com/a/209939/67312). ``` nreps <- c(rep(1:4,e=5), # repeat the beeps 1,2,3,4 each 5 times 25) # and 25 times beep <- strrep("beep",nreps) # build a list of the repeated "beep"s s <- Reduce(paste,beep) # combine into one string, separated by spaces i <- el(gregexpr("b",s)) # find the start index of each occurrence of a "beep" e <- i[scan()]+3 # find the end index: the starting point of the n'th beep + 3 substr(s,1,c(e,0)) # and substring into s from 1 to e (or 0 if e is empty) ``` [Answer] # [R](https://www.r-project.org/), ~~89~~ ~~87~~ ~~73~~ 69 bytes *Edit: -20 (yes, 20) bytes thanks to Giuseppe* ``` x=scan();cat(strrep("beep",c(b<-(a=5:24%/%5)[cumsum(a)<x],x-sum(b)))) ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0PTOjmxRKO4pKgotUBDKSk1tUBJJ1kjyUZXI9HW1MrIRFVf1VQzOrk0t7g0VyNR06YiVqdCF8RO0gSC/@am/wE "R – Try It Online") The guts of this are stolen from [Giuseppe's R answer](https://codegolf.stackexchange.com/questions/209921/print-my-clocks-alarm-sound/209930#209930), so please upvote that one... Edit: especially after he's now massively golfed-down this one! However, I wanted to see whether a simpler, non-regex approach of constructing the correct number of 'beep'-repetitions (instead of making a very long one and then cutting it down) could be shorter. So far it is... [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` f=lambda n:n*"?"and f(n-1)+"beep "[:4|0x444444924aabe>>n&1] ``` [Try it online!](https://tio.run/##HcxLCsIwFEbhuau4XKi0GsHGNGLAupDSQUKTWtC/IXag4N7j48y/E1/LdYbMOZxv9u4GSzDY8IUtBgoldnW1Zed9JO6Meu@f6t9JKmudb1us6z6HORFoAiWL0ZeHr@maRmgt9LE3K4ppwkJcyAcXEL9tlT8 "Python 2 – Try It Online") Uses a hardcoded lookup table to decide whether to put a space after each beep. I attempted to make formulas instead but didn't find something shorter. [Answer] # [dotcomma](https://github.com/RedwolfPrograms/dotcomma) (old), 96577 bytes Dotcomma is a language I created. I don't think I have any documentation or interpreter to link to yet, so it's not really competing at the moment. Takes input based on the number of inputs. Because it's so long, and very repetitive, here's the two blocks it's made up of: **For every `beep` without a space:** ``` [[,.],[[[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,]]] ``` **For every `beep` with a space:** ``` [[,.],[[[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,][[.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.][.].,]]] ``` There's probably a way to golf down those constants. Anyway, I'll post an explanation when I have time. **Update:** Dotcomma now has documentation and an interpreter. Because I added so many important new features since I posted this, it's practically a different language. If anyone else wants to post a different dotcomma answer that uses the full extent of the language's features, go ahead! [Answer] # [Husk](https://github.com/barbuz/Husk), ~~16~~ 15 bytes ``` wmΣC:Ṙ5ḣ4¹R¨⁸ep ``` [Try it online!](https://tio.run/##ASMA3P9odXNr//93bc6jQzrhuZg14bijNMK5UsKo4oG4ZXD///81OA "Husk – Try It Online") ## Explanation ``` ¨⁸ep Compressed string literal "beep" R Repeat n times, n is input: ["beep","beep",..,"beep"] C:Ṙ5ḣ4¹ Cut the above into pieces. ḣ4 Range to 4: [1,2,3,4] Ṙ5 Replicate 5 times: [1,1,1,1,1,2,2,2,2,2,..,4] : ¹ Append n: [1,1,1,1,1,2,2,2,2,2,..,4,n] C Cut the beep list to these lengths: [["beep"],["beep"],..,[..,"beep","beep"]] C stops when it runs out of elements, possibly cutting the last list short. In this case it has to, since the beep list has length n. mΣ Concatenate each: ["beep","beep",..,"beepbeep...beep"] w Join by spaces, implicitly print. ``` [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 853 bytes ``` anything i did was futile o,a clock i set definitely failed i know i,at one A.M,crave a rest i notice,o!the alarm!it beeps it provides no break to get a dream its six A.M aaggh,i got up should i get sleep at six A.M while in bed?nope,never i need to snooze now,but couldnt im tired ill get cereal:a bowl,milk,flakes o no,the milk spills dammit,i shout,getting kleenex and old unclean napkins next,the pouch of frosted flakes finally,i make a toast i look,o no!eight A.M must i hustle,so i begin at ten?i needed to rush,i am tardy so i change:i get a jacket,i get a shirt aw hell,o no,found no pair o pants ill clearly suffer in a pair o boxers i see,o no!eleven A.M its a shame,o,too late really,ill wear a blouse so now i hurry o,here now i sit time flies i see,o my!three P.M now i earned a rest i badly ne-ee-ee-ee-eeeded a nap i topple,and then i do ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?RVPBrpwwDLzzFd572ltV6V2e@gGV@guGGEgJMUrMsvTnX8fstk9CgiST8XjGcDltTmWiRDFFOrjRuFvK0mlgGrIOC46aGEUZU0km@aSRAYhdoqXoQSmwkRahH19/hqHyXYipSjMAiloaJOjNZuxmrustGfUiW@vwsVW9pygNOOqr8EKmNKEYU8RyBaZRSw@n7pinaQ6JJjXat67NuucIcY5vGZQEHS8wHTMkUiqoFd@LbhKK3KW6JJHoZVpR/SOofIR@NxqcrUDzSpaqd5fzRT0IlOQ3pl6PHNaUlzBmXqR1isvBG/NNahtutC7yuiaDTNdnAQzm9i4QWORBXCIpZO9lyMKFCm9LKq3DmV1cm@7DTDrSWLUZpL6KwXzO@QTxijUMMuXL4qy6BJdykzTNdlm17s3gzIxXltAU371McAMOmZT3pwtPH@re3FVG31zj2V3oYeYyyVt6hfGbh0W8qeeyzalaxwfNkvNVO4y6ozPEuHGq5K9i7fLQ@6wYmraPo1SPhP@Ben1IBQrzJa8WMlIqVw8evZfiFWfBVCmzSedhuA1gPkAMSJ91b@K6r2lE17WeGN8ZwfmW8yfrLK0CM5N8FlxPzGUVoV@o97wMygJf/g9wzxHai3yRz@dyjj06AEy3DR57roiv@H@kH9@/feDiXw) This was a tough program to write. I wrote the poem about an alarm that wakes me up way too early. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 [bytes](https://github.com/DennisMitchell/jelly) ``` 4Rx5Ä‘œṖȧ€“&?»$K ``` A monadic Link accepting an integer which yields a list of characters. **[Try it online!](https://tio.run/##AScA2P9qZWxsef//NFJ4NcOE4oCYxZPhuZbIp@KCrOKAnCY/wrskS////zg "Jelly – Try It Online")** ### How? ``` 4Rx5Ä‘œṖȧ€“&?»$K - Link: integer, n e.g. 8 4 - four 4 R - range [1,2,3,4] 5 - five 5 x - times [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4] Ä - accumulate [1,2,3,4,5,7,9,11,13,15,18,21,24,27,30,34,38,42,46,50] ‘ - increment [2,3,4,5,6,8,10,12,14,16,19,22,25,28,31,35,39,43,47,51] $ - last two links as a monad - i.e. f(n): “&?» - compressed string "beep" ȧ€ - (n) AND each ("beep") ["beep","beep","beep","beep","beep","beep","beep","beep"] œṖ - split before indices [["beep"],["beep"],["beep"],["beep"],["beep"],["beep","beep"],["beep"]] K - join with spaces "beep beep beep beep beep beepbeep beep" ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~22~~ ~~21~~ ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` F’¼®b’4L5и{¦.¥NåúRJ ``` -1 byte by porting the approach used in multiple other answers. [Try it online](https://tio.run/##yy9OTMpM/f/f7VHDzEN7Dq1LAtImPqYXdlQfWqZ3aKnf4aWHdwV5/f9vAQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/eGtlf/dHjXMPLTn0LokIG3iY3phR/WhZXqHlvodXnp4V5DX/1qd/9HGOgY6hjrmOhY6pqY6ZuY65qaxAA). --- Original approach: # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~22~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` '¬ž4L₂¸«×5иé»Z¡I£'p«J ``` Output is joined by newlines. If this has to be spaces instead, 1 byte has to be added by replacing the `»` with `ðý`. [Try it online](https://tio.run/##AS0A0v8wNWFiMWX//yfCrMW@NEzigoLCuMKrw5c10LjDqcK7WsKhScKjJ3DCq0r//zg) or [verify all test cases](https://tio.run/##MzBNTDJM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fxXP7Tm6D4Tn0dNTYd2HFp9eLrphR2HVx7aHXVoYeWhxeoFh1Z7/dc5tM3@f7SxjoGOoY65joWOqamOmbmOuWksAA). I wanted to use the legacy version of 05AB1E, since the maximum builtin `Z` works on strings (getting the character with the largest codepoint), which isn't the case in the new version of 05AB1E. This would have saved a byte over `'r`. Unfortunately, the legacy version lacks the append\_to\_list builtin `ª`, so we'll have to use `¸«` instead. **So here is a regular [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) version as well with the same ~~22~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):** ``` '¬ž4L₂ª×5иé»'r¡I£'p«J ``` [Try it online](https://tio.run/##ASwA0/9vc2FiaWX//yfCrMW@NEzigoLCqsOXNdC4w6nCuydywqFJwqMncMKrSv//OA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fxXP7Tm6D4Tn0dNTYdWHZ5uemHH4ZWHdqsXHVpYeWixesGh1V7/dQ5ts/8fbaxjoGOoY65joWNqqmNmrmNuGgsA). **Explanation:** ``` F # Loop `N` in the range [0, (implicit) input-integer): ’¼®b’ # Push dictionary string "peeb" 4L # Push list [1,2,3,4] 5и # Repeat it 5 times: [1,2,3,4,1,2,3,4,...] { # Sort it: [1,1,1,1,1,2,2,2,2,2,...] ¦ # Remove the first value .¥ # Undelta this list (with implicit leading 0): # [0,1,2,3,4,6,8,10,12,14,17,20,23,26,29,33,37,41,45,49] Nå # Check if `N` is in this list (1 if truthy; 0 if falsey) ú # Pad "peeb" with that many leading spaces R # Reverse it to "beep" or "beep " J # Join all strings on the stack together # (after the loop, the result is output implicitly) '¬ž '# Push dictionary string "beer" 4L # Push a list [1,2,3,4] ₂ # Push 26 ª # New version: Append it as trailing item to the list ¸« # Legacy version: Wrap into a list; merge the lists together # [1,2,3,4,26] × # Repeat each string that many times: # ["beer","beerbeer","beerbeerbeer","beerbeerbeerbeer",...] 5и # Repeat this list five times é # Sort it based on length » # Join all strings in the list by newlines 'r '# New version: Push "r" Z # Legacy version: Push the maximum character (without popping), # which is "r" ¡ # Split the string on "r" I£ # Leave the first input amount of substrings 'p« '# Append a "p" to each string in the list J # And join it all together again # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’¼®b’` is `"peeb"` and `'¬ž` is `"beer"`. [Answer] # [Io](http://iolanguage.org/), ~~81~~ ~~78~~ 75 bytes Shamelessly ported from Arnauld's answer. ``` f :=method(i,if(i>0,f(i-1).."beep".." "repeated(1200959982447294>>i&1),"")) ``` [Try it online!](https://tio.run/##DYxBCsMgEADveYV4KC5sg9qkxkL9S9qsZCGJYv2/dQ4zt@HUWhSv90l1T5ti5Kg4aOy@GxhH@SHKslfIQpnWSpsyVms/e7/YaXLWTyHwzQBKCdAO/lWl0eADHS44z/h0IGIqtH73vh9Ep89B5MJXPa4B2h8 "Io – Try It Online") # [Io](http://iolanguage.org/), ~~152~~ 113 bytes Port of Manish Kundu's answer. ``` method(x,O :=("beep"repeated(x)asList);" !*3<ER_ly†—¨¹ÊÛ"foreach(i,if(i<x*4,O atInsert(i," ")));O join) ``` [Try it online!](https://tio.run/##y8z/n6ZgZasQ8z83tSQjP0WjQscfyNdQSkpNLVAqSi1ITSxJBYpqJhb7ZBaXaForsXDyCUsoahnbuAbF51Qeajs0/dCKQzsPdx2erZSWX5SamJyhkamTmaaRaVOhZQI0LLHEM684tagEKKqkoKSpqWntr5CVn5mn@T8HaKCGgY6hjrGOuY6Fjqmpjpm5pgLCEC4FIAAapKlQUJSZV5KTx6X5HwA "Io – Try It Online") ## Explanation ``` method(x, // Input x O :=("beep"repeated(x)asList) // "beep" repeated x times " !*3<ER_ly†—"foreach(i, // For every codepoint in this string: if(i<x*4, // If doing this doesn't cause an error: O atInsert(i," "))); // Insert at this position O join) // Join O without a separator ``` [Answer] # [J](http://jsoftware.com/), 50 46 bytes ``` ;@({.<@,&' '@;/.[$<@'beep')&((##\)25,~1+5#i.4) ``` [Try it online!](https://tio.run/##y/pvqWhlbK4QrWCgYGhgYACkjIyMuJT01NMUbK0U1BV0gCJWQKyrp@Ac5OP239pBo1rPxkFHTV1B3cFaXy9axcZBPSk1tUBdU01DQ1k5RtPIVKfOUNtUOVPPRPO/JhdXanJGvkKagiGMYQpjmMEY5jCGBYxhZABhqavD1Zj@BwA "J – Try It Online") ## how `25,~1+5#i.4` produces: ``` 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25 ``` `(##\)` pairs that with an integer list of the same length: ``` 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ``` and duplicates the bottom list according to the corresponding element of the top list: ``` 1 2 3 4 5 6 6 7 7 8 8 9 9 10 10 11 11 11 12 12 12 13 13 13 14 14 14 15 15 15 16 16 16 16 17 17 17 17 18 18 18 18 19 19 19 19 20 20 20 20 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 ``` Call this our "key". We're going to use it to group our "beep"s together. Our key becomes the right argument to `;@({.<@,&' '@;/.[$<@'beep')`. `[$<@'beep'` first duplicates "beep" according to the input. Say, for an input of 8 we get: ``` ┌────┬────┬────┬────┬────┬────┬────┬────┐ │beep│beep│beep│beep│beep│beep│beep│beep│ └────┴────┴────┴────┴────┴────┴────┴────┘ ``` `{.` takes the first 8 elements of our key, creating a new key: ``` 1 2 3 4 5 6 6 7 ``` The key adverb `/.` applies the verb `<@,&' '@;` to each group defined by the new key. It unboxes, appends a space, and reboxes: ``` ┌─────┬─────┬─────┬─────┬─────┬─────────┬─────┐ │beep │beep │beep │beep │beep │beepbeep │beep │ └─────┴─────┴─────┴─────┴─────┴─────────┴─────┘ ``` `;@` unboxes again, giving the result: ``` beep beep beep beep beep beepbeep beep ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~108 120 118~~ 110 bytes *+12 because I forgot to include the import statement which I had to put in the TIO header, not body* *-2 by replacing \x00 with \0 - thanks to @ovs* *-8 by filtering instead of replacing, and switching from `.` to `!`* ``` import zlib;lambda x:filter(33 .__ne__,zlib.decompress(b'x\x9cKJM-PH\xc2A(\x92\xc7\xa26\x97nb4!\0hm{7')[:x*5]) ``` [Try it online!](https://tio.run/##HY3RCsIgGIVfZV3tN2qEa0nrqrsogu4zZG6OCdOJGrh6eHOdq@@Dwzlm9sOkyyiVmazPPqPkJ2Ol9sBnLxxAHBvFuyYLdS9HLyyUZVYwpgVjm6VddKKdlLHCOeB5oOHY3q737eNCQ4vPkBwnIjQ0@JCEaL5f0d2gviRHzzqsqxeKCJZDqc3bA0r5b3YicazIDw "Python 3 – Try It Online") ### How It Works Sorry. I couldn't be bothered to come up with a clever algorithm. `zlib` compressed string: `beep beep beep beep beep beep!beep beep!beep beep!beep beep!beep beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep!beep` which is indexed into upto `n*5`th character, and then we filter for the bytes which don't equal 33 (exclamation mark). I chose `!` using a brute-force to find the the shortest compressed output from `zlib`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 188 bytes ``` If[#==0,"",c=#;T@v_:=v~Table~5;w=Accumulate[z=Flatten@{T/@Range@4,25}];StringRiffle[""<>#&/@Join[1~Table~#&/@z[[;;Max@Position[w,m=Max@Select[w,#<=c&]]]],{Table[1,c~Mod~m]}]/. 1->"beep"]]& ``` [Try it online!](https://tio.run/##LY3Ra8IwGMT/FUmhT98W69Ypi5H4MthAcNq3EEbMvnaBJh1bqsPS/utZFe/luB/cndPhC50O1uhY8fhayoTzKRAChiesEMePZ34cCn2occjZia@NaV1b64DyzF9GD@hFV1Cx075C8QizvFdsH36sr3a2LGuUhCxXSUrFW2O9zG5bF3CWkrGN/hPb5tcG23h5AscvYI81mjDGZMlNqkZBd@3JDMywaT4Hp3pF7yfZ3YocEL@JUml8by0GuR2vAxUVFZPuAaaQwRwWkOfwNO9VjP8 "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3) , 164 Bytes [Try it online](https://tio.run/##VY2xCoMwFAB3vyI8EF7MoxCrHULtj4QMiokNmFQaEfv1qQ4dut1yd8tnfb7iNceubvPUzX0Yxp4l2imoxLxj4RGZnZNlEyYBg7ULVLsABoS6bkkaoXeBoWzukptKNlxjEJKX8mbohGLrJgQgSQe73yCQV5tW3vwt3KnSdnE@jggDkD8CvFjePq7o8EzwnL8) This is my recursive approach. Somehow it's worse than I imagined it in my head. Explanation: *n* is the input number The *g* function generates the beep sequence, where *x* controls the numbers of "beep"s . Every 4th call *x* is incremented by 1, and with the 16th call it's set to 25. In the next call it's reset to 1 . *g* generates *n* groups of "beep"s the string is stored in *v* *f* cuts *v* to the corrext number by searching for the next "b" in *v* until *n* is reached. ``` g=lambda s,x,m:s if m>n else g(s+"beep"*x+" ",([25,1]+[x+(m%4<1)]*14)[(m+1)%16],m+1) v=g("",1,1) f=lambda m,i:v[:i] if m>n else f(m+1,v.find("b",i+1)) print(f(1,1)) ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 bytes ``` ∊' ',⍨¨(⎕↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdITEnsSgXyOpSV1DXedS74tAKjUd9Ux@1TTw8HSgIpMFiRqYgOVP9R72bTTQfdTUBkXpSamqBOsiM/wpgADaJy5hLXVdXV50LWcwAi5ghFjFzLGIWWMRMTbEImpn/BwA "APL (Dyalog Unicode) – Try It Online") With significant golfing input from ngn. ### Explanation The code inside the parens builds a boolean array describing the grouping pattern, which we'll come back to below; quad (`⎕`) prompts for the quantity of beeps and the pattern is cut to that number. To the right of the parens the word `'beep'` is enclosed (monadic `⊂`) to make it a single thing (instead of an array of 4 characters), and that is partition-enclosed (dyadic `⊂`) by the pattern which groups the beep and implicitly repeats it to match the cut pattern length. To the left of the parens, the `beep`s get one space (`' '`) appended (`,⍨`) to each (`¨`) group of them, then get flattened (`∊`) into the result string. Building the group pattern follows this progression: ``` 5/⍳4 ⍝ five-replicate the first four numbers 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25,⍨5/⍳4 ⍝ append 25 for the long run 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 25 ↑⍨¨25,⍨5/⍳4 ⍝ turn each (¨) of the numbers into ⍝ a group that long, padded with zeros. ⍝ using take selfie (↑⍨). ⍝ e.g. Take first 3 items out of "3", get 3 0 0. ┌→┐ ┌→┐ ┌→┐ ┌→┐ ┌→┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→──┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→──────┐ ┌→─────────────────────────────────────────────────┐ │1│ │1│ │1│ │1│ │1│ │2 0│ │2 0│ │2 0│ │2 0│ │2 0│ │3 0 0│ │3 0 0│ │3 0 0│ │3 0 0│ │3 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │4 0 0 0│ │25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0│ └~┘ └~┘ └~┘ └~┘ └~┘ └~──┘ └~──┘ └~──┘ └~──┘ └~──┘ └~────┘ └~────┘ └~────┘ └~────┘ └~────┘ └~──────┘ └~──────┘ └~──────┘ └~──────┘ └~──────┘ └~─────────────────────────────────────────────────┘ ∊↑⍨¨25,⍨5/⍳4 ⍝ flatten (∊) the nesting 1 1 1 1 1 2 0 2 0 2 0 2 0 2 0 3 0 0 3 0 0 3 0 0 3 0 0 3 0 0 4 0 0 0 4 0 0 0 4 0 0 0 4 0 0 0 4 0 0 0 25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ×∊↑⍨¨25,⍨5/⍳4 ⍝ use direction (×) to turn all non-zero into 1 ⍝ 1 marks the start of each group, 0 pads their length. ⍝ A boolean group-array for the full beep pattern 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 1 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 20↑×∊↑⍨¨25,⍨5/⍳4 ⍝ take (↑) 20 beeps. (⎕ number beeps) ⍝ This is how it cuts in the middle of a ⍝ run of beepbeepbeep, by cutting the pattern. 1 1 1 1 1 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 (20↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep' ⍝ p-enclose of 'beep' shows the grouping, ⍝ and the cutoff group at the end. ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→───────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→──────────────┐ ┌→─────────────────────┐ ┌→──────────────┐ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ ┌→───┐ │ │ ┌→───┐ ┌→───┐ │ │ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │ │ │beep│ │beep│ │beep│ │ │ │beep│ │beep│ │ │ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ │ │ └────┘ └────┘ └────┘ │ │ └────┘ └────┘ │ └∊───────┘ └∊───────┘ └∊───────┘ └∊───────┘ └∊───────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊──────────────┘ └∊─────────────────────┘ └∊──────────────┘ ∊' ',⍨¨(20↑×∊↑⍨¨25,⍨5/⍳4)⊂⊂'beep' ⍝ append one space in each group ⍝ and flatten. beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeep ``` [Answer] # [Rust](https://www.rust-lang.org/), 76 ~~127~~ bytes ``` |n|(0..n).fold("".into(),|a,i|a+"beep"+&" "[..0x222222492555F>>i.min(63)&1]) ``` [Try it online!](https://tio.run/##Tc49C4MwEAbgWX9FmkEuaIPWxn7i6NapY@mgaCRQY9EESht/e2qFQm57uLv3btCjslyirhQSCPr4nmpGBdZIAzGlklDeP2rAmAqpeiCRKSNhyhBXTfPEYYARvlEavzZLbQ8bxliR54J2c16WkiC5E@uRkz/5/nzmF34ujqiQF61Aj@LdELTO0VUNQrY5dFohPreXT@qqXQGHlMzrf8QuEhc7F3sXjLnKlsHJfgE "Rust – Try It Online") Shamelessly ported from [Arnauld's JS solution](https://codegolf.stackexchange.com/a/209934/97519) The binary constant has a bit set wherever the "beep" should be followed by a space. ## Old solution ``` |n|[1,2,3,4,25].iter().fold(format!(""),|a,&i|a+&("beep".repeat(i)+" ").repeat(5)).rsplitn(176-n,'b').last().map(str::to_owned) ``` [Try it online!](https://tio.run/##bY@xasMwEIbn@CkUDckdUUSd1Elxg8dspUPHUoqM5SCwJSGdCbTOs7tqIUPB293Hz3f/hSHS1FrWK2MB2Xe2IB0JptGO77nYib14FLviQxrSAVC2rmugdaFXtATOUYxKrMyoNivgtdaey6C9VgQGN5xxvK8FpjH6zpCF/HjYWrGu1yg7lW6h7JWHSKEsyX26q9UNTgt8zm5Zlpr99jmdS3a2LwPBEM2XRrat2Ksn4@zpjYKxl6qCfiDWptjfE019WUILe5SDvYakx@S704dZms/S4yx9mqVFMYsP/x23bPoB "Rust – Try It Online") ### Explanation: We first construct the string `beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep...` with the last 25 successive `beep`s also being repeated 5 times. This string contains 175 `beep`s, so we trim from the right to and including the `176-n`th `b` and take the sub string left of there. [Answer] # APL+WIN, 50 bytes Prompts for input of n: ``` (4×(p/m),¯1↑-(p←n≤0)/n←(+\m←(5/⍳4),25)-⎕)⍴¨⊂'beep' ``` [Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5rmByerlGgn6upc2i94aO2iboaBUDJvEedSww09fOATA3tmFwQZar/qHeziaaOkammLtAMzUe9Ww6teNTVpJ6Umlqg/h9o2P80LmOuNC4DIDYEYnMgtgBiU1MgYWbOxQUA "APL (Dyalog Classic) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes ``` FN«beep¿&⍘(XsB!,zOγX²ι→ ``` [Try it online!](https://tio.run/##DcyxDoIwEADQGb7i7HRN6uKgiU52c1CJLq4FD7gEWtIWSDR@e@3@8pre@MaZIaXWecCLneZ4m8eaPEoJ37KoPNuIoiaahDyVBbeAmuPKgc72jdoEesZsOhT4CnqjPnehoJMKKrfmZaeAZa6ubiE8PrjrY25@Ke0PabsMfw "Charcoal – Try It Online") Link is to verbose version of code. Uses the popular bitmask approach. Explanation: ``` FN« ``` Loop the given number of times. ``` beep ``` Print a beep. ``` ¿&⍘(XsB!,zOγX²ι→ ``` If the appropriate bit in the constant is set, then move right one character. The constant is probably the same as everyone else's but here I'm effectively encoding it using base 95. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 68 bytes ``` (0.."$args"|%{' '*((0x444444924AABE-shr$_)%2)*($_-lt52)})-join'beep' ``` [Try it online!](https://tio.run/##7VRtS8MwEP7eX3HU1CSjGbWuTgXFCf6O0m3nWoldTTI26frba8xeiuCHCvOTBnLc2/NwdyRXLdeodI5StuQZ7qBuWTQc@iRTC@1vg5oCHTAWbUbu3MSjyeTxSehckZQHMR8wkgppkpg3XLwsi5JOESvaNp73wLyQXQJA6HzQCcqt9wyy8h2MygpZlAtY54VBXWUzhEJDJqWta24JIkdAuVUvOi5nj7/j/iq65Oueya78T0CS9Af0VU5i/Jrj2PrV@C@2/tO7e4PJ/6hOMkoOWwig9uw3BVKuXqeoQiC4qXBmcG4XE0l3MYV6JY11nNt9tc90EZ@wfVDg2xHJbw9JIO4PaN9r2g8 "PowerShell – Try It Online") The script: 1. generates an array of whitspace and empty strings 2. joins array elements with 'beep' The script can add a trailing whitespace that is allowed by the author. See the test cases in the TIO link. The Powershell works with 64 bitmasks only, so I had to add a condition `($_-lt52)` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~72~~ \$\cdots\$ ~~66~~ 60 bytes Saved 10 bytes thanks to the man himself [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!! ``` f(n){n&&printf(" beep"-~-(0x888889249557c>>n&n<55),f(n-1));} ``` [Try it online!](https://tio.run/##5ZPBCsIwDEDvfkUpOFqwsDq7Tie7@Re7aLeJB8MQD4LMX5@d2ApTysT1ZKAhTZvmkaSK7ZVq24oAvUIQ1KcDnCuC0a4sa8xujISXpJPlfLEUQqosgwDWQtCZDmGc0rRpdQg6bg9A6OQ6QVrMK1O2KPAMRTR9uCtiLHMhh82lLtW5LFY5RPqgS/tSObBfJQfcy/mECi1U6IIKfTJwy8BdDPxZGJ8o0qJIF4p861FP@eZMLGfi4kyGcHovqv4mhtaaH3GFGIo71Bhl483hu/Dxa5xj5zzH8v8K/@0arVFNewc "C (gcc) – Try It Online") Recursively calls itself \$n\$ times evaluating a bitwise expression (where the \$1\$ bits of a hard coded integer indicate if a space is needed) to determine whether or not to prefix the current `beep` with a space. This is done by adding \$0\$ or \$1\$ to a string literal (`char*` pointer) to offset it by one or not. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 20 bytes ``` 4ɾƛS5*fvI;?Jf«⟇½⁰«*Ṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=4%C9%BE%C6%9BS5*fvI%3B%3FJf%C2%AB%E2%9F%87%C2%BD%E2%81%B0%C2%AB*%E1%B9%84&inputs=58&header=&footer=) [Answer] # [PowerShell 5.1](https://docs.microsoft.com/en-us/powershell/), 227 bytes ``` $n=10;function f($x){$r.Length-in$x};$c=0;$r="";$t=0;while($c-lt$n){$s=-1;switch($true){{f(0..24)}{$s=1}{f(25..69)}{$s=2}{f(70..134)}{$s=3}{f(135..219)}{$s=4}};$r+="beep";$t++;if($t-ne$s){$c++;continue};$r+=" ";$t=0;$c++};$r ``` Explanation: $n is the input number. I tried to write this without doing it via arrays because I felt like it would be cheating, as I had already read [this answer](https://codegolf.stackexchange.com/questions/209921/print-my-clocks-alarm-sound/209927#209927). I used the length of the string to determine how many "beeps" were needed before I placed a space. If the length of the string is between 0 and 24, 1 space. If the length of the string is between 25 and 69, 2 spaces. etc. Here's the "cleaner" version ``` $n = 9 function bl ($x) {$beepString.Length -in $x} $count = 0 $beepString = "" $beepsThisTime = 0 while($count -lt $n) { $neededBeepsBeforeSpace = -1 switch($true) { {bl(0..24)}{$neededBeepsBeforeSpace = 1} {bl(25..69)}{$neededBeepsBeforeSpace = 2} {bl(70..134)}{$neededBeepsBeforeSpace = 3} {bl(135..219)}{$neededBeepsBeforeSpace = 4} } $beepString += "beep" $beepsThisTime++ if($beepsThisTime -ne $neededBeepsBeforeSpace){$count++;continue} $beepString+=" " $beepsThisTime = 0 $count++ } $beepString ``` [Answer] # [Lua](https://www.lua.org/), 105 bytes ``` function b(n)t={}for i=5,24 do t[(i-1)*(i-2)//10]=' 'end for i=1,n do io.write('beep'..(t[i]or''))end end ``` Ungolfed code and test program: ``` function b(n) t={} for i=5, 24 do t[(i-1)*(i-2)//10] = ' ' end for i=1, n do io.write('beep' .. (t[i] or '')) end end for k, v in ipairs({ 3, 0, 1, 7, 8, 55, 67, 75 }) do io.write(v .. '\t') b(v) print() end ``` Output: ``` 3 beep beep beep 0 1 beep 7 beep beep beep beep beep beepbeep 8 beep beep beep beep beep beepbeep beep 55 beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeep 67 beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep 75 beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeep beepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeepbeep ``` [Try it online](https://tio.run/##PY4xDsIwEARreMV29qHDJECAJi8BigQc6QSyI@OEIuLtwRYSxa22mB3dc2jmuRvcLYp3aLWjWE@fzgdIXfF2j7tHPGtZl7RKuaXNpiyutYKy7o4fV7LLmHjzDhKtVq21vTJGx7NcfVCKKMPp5jx4MEaIg/SNhJeesGMUjJJxZJwYVcU4pHqs8KEkXi7@5hHGQF2iovTqSOiDuKhpmdVf) Edit 1: Thank you for your suggestions :) It greatly helped to compress the sequence that was used. Edit 2: 99 Bytes solution provided by Arnault, getting rid of the (-1) and using a partial and clever one's complement to decrease a number: ``` function b(n)t={}for i=4,23 do t[i*~-i//10]=' 'end for i=1,n do io.write('beep'..(t[i]or''))end end ``` [Try it online](https://tio.run/##PY5BDoIwFETXcorZtTXfAiLihpMoCxBIfjQtqQUXBK@OJSYuJpnFm5d5jvW69qO5e7YGjTTKl/PSWwcuT3TM0Fr4K@8/B47jNKlKAdGZFj8iJbMBbPXbse@kaLpuEFrLMKmsE0KpDQ5Zt8GDMIENeKjZveSMjJAQUkJBuBDynHAOtcixqCCOdn/zBK0hbl6ocHJSGBwbL1W0qb8) [Answer] ## [Setanta](https://try-setanta.ie/), ~~146~~ ~~144~~ ~~140~~ ~~124~~ 123 bytes *-16 bytes by using a cheaper check for the first beep.* *-1 byte by discovering that braces could be left out in one place.* ``` gniomh(n){s:=""le i idir(0,n){a:=(i&freamh@mata((i-1)//5*8+1)+1)//2d:=(i-5*(a*a-a)/2)%a ma!d&i<51 s+=" "s+="beep"}toradh s} ``` [Try it here!](https://try-setanta.ie/editor/EhEKBlNjcmlwdBCAgICglsiZCg) [Answer] # [Zsh](https://www.zsh.org/), 64 bytes ``` repeat $1 z+=beep. repeat 4 repeat x+=5,5 z[t+=x]=\ <<<${z//./} ``` [Try it online!](https://tio.run/##qyrO@F@cWqKg66Zgbvq/KLUgNbFEQcVQoUrbNik1tUCPCypkogBlqFdo25rqmKorVEWXaNtWxNrGKHDZ2NioVFfp6@vp1/7/DwA "Zsh – Try It Online") Because of a bug that's not fixed in the Zsh version available on TIO, the `x+=5,5` needs to be single-quoted for +2 bytes. Works by constructing a string of `beep.`, replacing some `.`s with spaces, and then removing the `.`s. The differences in the indeces at which to remove the `.`s are `5, 5, 5, 5, 5, 10, 10, ... 15, 15, 20, 20, 20, 20, 20`, so we cumulatively sum these as we go. * `repeat $1`: do this {input} times: + `z+=beep.`: append `beep.` to the variable `$z` (which implicitly starts empty) * `repeat 4`: + `repeat x+=5,5`: do this 5 times, but also increment `$x` by `5` (it starts at `0` implicitly) before the loop starts: - `t+=x`: increment `$t` (the cumulative sum) by `$x` (again, `$t` starts at `0` implicitly) - `z[]=\` : set the `$t`th character (1-indexed) of `$z` to a space * `${z//./}`: take `$z`, with dots `.` replaced by {empty string} * `<<<`: print [Answer] # [dotcomma](https://github.com/Radvylf/dotcomma), ~~617~~ 569 bytes ``` [,].[[[,.][[[[[.][.][.][.].,][,.].,][,.].,][[,][[[,][,.].,][,][,].,].,][,][[[,.][.][.].,][.][.][.].,][,][[[,.][[[,.][[,]].,][],].,],].[,][.,][[.][.][.][.][.].,].[.[.[[[,.][[].[],].,][[,][[,][[[[,][[[,],]].,],]].,][],][.[.[,].][,][,]].][,][[,][[,][,][,]].,][.[.[,].]][[,.][[].[],].,],.[[[,][[,.]].,][.[.[,].][,]]],.[.[.[,].][,[.][.][.][.][.].,][,]][,],.][.[.[,].][,]][[[,.][[].[],].,][,.].,].[.[,].][,][,],.][,][.[.[,].]][,[,[,[,[,[,[,[,.]]]]]]]]].,].[[.[.[,].]][[,.][[].[],].,][.[[,],]][.[.[,].][,][,]][.[,]][,.][.[.[,].][,][,.]][.[[,][,.],.]].][.[.[,.].]][,.]],.[[,.]] ``` -48 bytes by rearranging the last counter loop and thereby avoiding duplicate code. Phew, I need to rearrange my brain again... Bracket chaos ^^ This is first try with this language. It's quite fun. The changes made to the old version seem to be very effective when I can shrink the program size to less than 1% of the old version. Are there plans to put this language on tio.run? What about plumber? I think that's interesing, too. Use the following snippet on your own risk (especially when changing the dotcomma code. I had several freezes because I unintetionally created endless loops) ``` <script src="https://combinatronics.com/Radvylf/dotcomma/master/interpreter.js"></script><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script><script>$(document).ready(function () {$("#btnInterpret").click(function () {$("#txtResult").text(interpret($("#txtCode").val(), parseInt($("#txtInput").val()), $("#lstOutputAs").children("option:selected").val()));});});</script><style>.textBox {background-color: white;border: 1px solid black;font-family: Courier New, Courier, monospace;width: 100%;}</style>Code: <textarea id="txtCode" type="text" class="textBox" style="height: 200px">[,].[[[,.][[[[[.][.][.][.].,][,.].,][,.].,][[,][[[,][,.].,][,][,].,].,][,][[[,.][.][.].,][.][.][.].,][,][[[,.][[[,.][[,]].,][],].,],].[,][.,][[.][.][.][.][.].,].[.[.[[[,.][[].[],].,][[,][[,][[[[,][[[,],]].,],]].,][],][.[.[,].][,][,]].][,][[,][[,][,][,]].,][.[.[,].]][[,.][[].[],].,],.[[[,][[,.]].,][.[.[,].][,]]],.[.[.[,].][,[.][.][.][.][.].,][,]][,],.][.[.[,].][,]][[[,.][[].[],].,][,.].,].[.[,].][,][,],.][,][.[.[,].]][,[,[,[,[,[,[,[,.]]]]]]]]].,].[[.[.[,].]][[,.][[].[],].,][.[[,],]][.[.[,].][,][,]][.[,]][,.][.[.[,].][,][,.]][.[[,][,.],.]].][.[.[,.].]][,.]],.[[,.]]</textarea><br />Input: <textarea id="txtInput" type="text" class="textBox">25</textarea><br /><input id="btnInterpret" type="button" value="Run" />Output as: <select id="lstOutputAs"><option value="true">String</option><option value="">Number array</option></select><br />Result:<br /><div id="txtResult" class="textBox" style="overflow-wrap: break-word"></div> ``` **Code:** (sorry for the missing interpunctuation. This way I was able to run the commented code directly in the interpreter) ``` [,].[ if input > 0 [[,.][ save input on recursion stack [ [ ### Build ASCII values for "b" "e" "p" and space " " [[.][.][.][.].,] 4 [,.].,] 8 [,.].,] 16 [[,] put 16 on recursion stack and save copy in queue [ [[,][,.].,] 32 [,][,].,] 96 .,] 112 ("p") in queue: 32 96 112 [,] roll left (queue: "@p ") [[[,.][.][.].,][.][.][.].,] "b" "e" [,] roll left (queue: " bep") [[[,.][ save " " on recursion stack [[,.][[,]].,] reverse letters ("peb") [], insert 0 (start of queue) ].,],] save two copies of 32 (one for space character and one for counting beeps) ### Build list of "beep"s in reverse - each separated by a null char Since the maximum input is 75 the 25 consecutive beeps at the end will be limited by the input - so I can safely put a few more beeps into the list because I just have a 32 handy sc: spaces counter pc: pattern counter bc: beep counter target queue: 0 0 sc pc bc " peb" current queue: "peb" 0 bc(32) " " I will refer to the two consecutive 0s at the start of the variable section as "start of queue" or just "start" pc: | 1 | 2 | sc: | 1 | 2 | 3 | 4 | 5 | 1 | 2 | 3 | 4 | 5 | bc: | 1 | 1 | 1 | 1 | 1 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | 1 | 2 | beep beep beep beep beep beepbeep beepbeep beepbeep beepbeep beepbeep .[,] roll to start [.,] insert 1 for spaces counter (since I append new beeps to the start of the queue we are only one space away from the next pattern) [[.][.][.][.][.].,] insert 5 for pattern counter queue: pc(5) bc(32) " bep" 0 sc(1) .[ while pattern counter > 0 ### Attention: current position is beep counter! .[ while spaces counter > 0 ### Attention: current position is beep counter! .[ while beep counter > 0 [[,.][[].[],].,] save beep counter -1 on queue (also hold it in recursion stack) [ # put a copy of "beep" on the queue [,] roll over " " [[,][[ put "p" on recursion stack [[,][[ put "e" on recursion stack [,] put "b" on recursion stack ,]] put "b" on queue .,],]] put "ee" on queue .,] put "p" on queue [], put 0 on queue ] [ .[.[,].] roll to start (roll until two consecutive 0s are found) [,][,] go to beep counter ] .] return value for loop (end of beep counter loop) # insert space [,] roll over beep counter [[,][[,][,][,]].,] copy and insert space # if spaces counter - 1 > 0: copy pattern counter to beep count (the pattern counter contains the number of consecutive beeps that should be separated by a space) [.[.[,].]] roll to spaces counter [[,.][[].[],].,] decrement spaces counter ,.[ if spaces counter > 0 [[,][[,.]].,] replace beep counter with copy of pattern counter [.[.[,].][,]] roll to pattern counter (if the spaces loop repeats we need to be at the beep counter; I will read the next value to determine if the loop should repeat; Thats's why I stop one value before beep counter) ],.[ else .[.[,].] roll to spaces count [,[.][.][.][.][.].,] set it 5 for next round [,] roll to beep count ] [,],. get return value for loop (pattern counter for repeating or beep counter(0) for stopping) ] end of spaces loop [.[.[,].][,]] roll to pattern counter [ [[,.][[].[],].,] decrement pattern counter [,.]., set new beep counter = pattern counter ] .[.[,].][,] roll to pattern counter [,],. repeat if > 0 ] end of pattern loop [,][.[.[,].]] roll to start [,[,[,[,[,[,[,[,.]]]]]]]] delete variables constants and excess space in front of first beep ].,] put input back into queue ### Count beeps The idea is to delete all 0s between the beeps until we match the input then deleting everything behind it I thought it would be easy to delete single 0s - What I didn't consider was that I can end a loop only after a 0 has been processed so I needed a trick What I do is: duplicate every character until I reach a 0 (which will also be duplicated) Then find the first 0 (reassigning it to the end of the queue) and delete the second 0 After that I can delete the duplicated characters including the 0 .[ while input counter > 0 [.[.[,].]] roll to start [[,.][[].[],].,] decrement input counter [.[[,],]] duplicate until first 0 [.[.[,].][,][,]] roll to start + 2 [.[,]] roll to first 0 [,.] delete second 0 [.[.[,].][,][,.]] roll to start + 2 (deleting the second character) [.[[,][,.],.]] delete every 2nd character until 0 found .] end of loop end of loop [.[.[,.].]] delete everything up to start [,.] delete input counter ],.[ else (if input is 0) [,.] delete input and output nothing ] ``` [Answer] # [Haskell](https://www.haskell.org/), 58 bytes ``` f n=do i<-[1..n];[' '|odd$div 0x888889249557c$2^i]++"beep" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzYlXyHTRjfaUE8vL9Y6Wl1BvSY/JUUlJbNMwaDCAgQsjUwsTU3Nk1WM4jJjtbWVklJTC5T@5yZm5inYKqTkcykoFJSWBJcU@eQpqCikKRijCxigCxiiC5ijC1igC5iaoouYmf8HAA "Haskell – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 54 bytes ``` $_=" beep"x$_;s/ /0x444444924aabe>>$x&$x++<51?$&:""/ge ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZJISk1tUCpQiXeulhfQd@gwgQMLI1MEhOTUu3sVCrUVCq0tW1MDe1V1KyUlPTTU///NzP/l19QkpmfV/xftyAHAA "Perl 5 – Try It Online") Ungolfed a bit: ``` $_=" beep"x$_; # create string of space+beep the input number of times s/ / # remove spaces unless it's space number 0x444444924aabe # 1 2 3 4 5 7 9 11 13 15 18 21 24 27 30 # 34 38 42 46 or 50 (counting from zero) # 0x444444924aabe in binary have 1's on # those positions >>$x # keep space if 1-bit and space number <= 50 &$x++<51?$&:""/ge # remove space if not ``` ]
[Question] [ [Titin](https://en.wikipedia.org/wiki/Titin) is a protein found in muscle tissue. It is a pretty big protein, and its full chemical name is giant as well. Comprising 189819 characters, the full name of titin would take about 3.5 hours to pronounce. Your task is to output this entire name! # Details The full name can be found here: [Gist](https://gist.github.com/hyper-neutrino/7d857f89d6d9bb0ab773291116270566) (this file does not include the trailing newline) The MD5 hash of the output is `ec73f8229f7f8f2e542c316a41cbfff4` (without a trailing newline) or `628c6eb157eb1de675cfc5b91a8149ce` (with a trailing newline). * You may not access an external resource, be it a file or an internet location. * You must output only the exact text from the pastebin to STDOUT or STDERR. Nothing else should be output to your chosen output stream; leading and trailing whitespace are acceptable. * You may not assume there will be any input, but you may assume that there will be no input if needed. * You may output anything to the other output stream (STDOUT if you chose to output to STDERR and vice versa) * Standard loopholes apply This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest program in bytes wins! # EDIT This is NOT a duplicate of the Rick Astley "Never Gonna Give You Up" challenge. Besides the tags, they're not even similar. In that one, output is a multi-line song with a few sections that repeats the first two words of every line. In this one, output is a fairly compressible string with 189819 letters. [Please don't close-vote this as a dupe of that](https://codegolf.meta.stackexchange.com/questions/6956/trigger-happy-on-the-duplicate-button-do-we-really-consider-all-song-lyric-ques). [Answer] # JavaScript (ES6), ~~16840~~ ~~16825~~ 16814 bytes *Saved a couple of bytes by:* * *inserting the last acid prefix in the packed string as suggested by ETHproductions* * *choosing the next character group in a slightly more efficient way when there's a tie* --- Assumes Windows-1252 character encoding. Outputs without a trailing newline. Below is a simplified version without any actual data. ``` [...Array(256)].map((_,i)=>i<52|i>126&i<161|i==92|i==96?0:s=s.split(String.fromCharCode(i)).join(`...dictionary...`.slice(j,j+=2)),j=0,s=`...packed_data...`)&&[...s].map(c=>'methion|threon|glutamin|alan|prol|phen|leuc|ser|val|glutam|glyc|histid|isoleuc|tryptoph|argin|aspart|lys|asparagin|tyros|cystein'.split`|`[c.charCodeAt()-32]).join`yl`+'ine' ``` And here is the full version: [Try it online!](https://tio.run/##Xb35d1TV1gX6@/srTvfqnFOn6jRVgsoFvSj6qaAoIIoM4dJJY@hDHxwISBsgxEQghPR9KqHSVapL1Rh7/WHfm3NX8Pq94RAkVJ2z99prrTnn2mtvTx26fOjikQsnz7Vnz5w9eux/f9nyvwe3fLQ/DMOtFy4cuublNmz0fw5PHzrneQczJ/0tH53cvCHXcfKjJLcxdXJzsjHpOLlly4c5/evGj@NNF7dcDC@eazvZ7u1uv3DyzPHwlwtnT3964tCFT/F076Tvh6fOnjzj/UdGXZly86403UySt6QZyZ9xJsiH8qdjxPK71POmHfwmb/1Yan4kDfkrE0W2jMuaH8Whm5hSScLYk2aSztipIImlkfYCz/bTqYzpmHFantnS9HK2LCROyousfJyNZcRJJfJQ3mbx2DemL6vp2A7DtJeOPJnIurkw56bwDccw0xnXiVO@Y8tkzkqn7EzGSodpK@fl4oyXSiVu5ER@WpZtjD3OpCLXTqTpZ83EN91MlPfjXOx6UcaRpulZXioOcxnb8/1MRlbw3ZRlRzk/7aRlLeVEpu2EjuWnY9eUVVnMhGkznbNDL5Mz7dh1TTP0Pc92HT8Vun4ceaGdTkVeEpsp1zZTcSb2nAwsGWb8tJ92Yz92bD9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Ks7gnS9ek9iFiucRb8Xht1NMDGJezw0r0UxPV5H1vMn8FKydFXk@UYLXmYTB2EM/vCBPvkj5dxwvN1zcmCiwwvVXjG3lVQgoY0ZmSeoeLIBxgjTTNgs19HgeS1xbcCcE7yNw3yB/ofxGp7lX/Y/z3oOGqeUDma8hB3v1YN/RfN0Ek5pOrAA7WPcH5ZjHvnmt0oaLNU64A3lWfnUalH9h2fYWtR42L@bQaize7vJJ8jOW94tdfSMnkTaIR062s6lO906m0vrZ4EdOZkcnNyA@Z//ipFP@fCBdb/yuEI1s@ck8faz9x8uyZjvYTF47ht@Ntl9oPnT55puNQ26EzHecunG3rOHfi2JmOtmOXjnRcPHah4/KhtvUP4bdrRzpOnLzYfvJox8mLZ/VH2i9cO9d@9tyJjkMXjvMpF88dutDe0XbtYus/D/GH7dcunL3YceTaxfZjJ8@4rf/Nwn86/rP/SHhk/X@wsLXd87P53M@t/8vCf661/SdwT5455v7v2Uvt5y61G1uMXzz//zly9gzfGradPe5dOHb@0skLxzz3iB6A64dHLhw71H7si0MXT3ju6aMb8JNL547iJ17rGX549OTxYxfbPffEsauu7//v/wc "JavaScript (Node.js) – Try It Online") The TIO link includes some additional code to print the MD5 of the output rather than printing the output itself: `ec73f8229f7f8f2e542c316a41cbfff4` ### How? This was compressed by: 1. Mapping the 20 distinct amino acids to ASCII characters 32 to 51. 2. Repeatedly replacing the most frequent 2-character group by a new ASCII character in the following ranges: * 52-91 * 93-95 * 97-126 * 161-255 Which leaves us with a dictionary of 336 bytes (168 entries of 2 characters) and a final compressed string of 16161 bytes. The above code is doing the exact opposite. [Answer] # Mathematica, 319 + 14971 = 15290 bytes ``` For[p={};a={t={{{{{tyros,asparagin},prol},{ser,threon}},{{lys,alan},{glutam,val}}},{{{{phen,{methion,cystein}},argin},{aspart,{glutamin,{histid,tryptoph}}}},{leuc,{,glyc}}}},r=Join@@IntegerDigits[BinaryReadList@"b",2,8]},r!={},If[AtomQ@a,p=Join[p,{a,yl}/.{,yl}->{iso}];a=t,a=a[[1+#&@@r]];r=Rest@r]];##~Print~leucine&@@p ``` *Incredibly, this is exactly one byte more than [this bzip2 answer](https://codegolf.stackexchange.com/a/116660/56178). Can somebody find a couple of bytes to save?!* This is a program that prints the full name of titin to STDOUT. We use the same structure described in [Jörg Hülsermann's PHP answer](https://codegolf.stackexchange.com/a/116658/56178), and additionally note that all the words except for `"iso"` end in `"yl"`, which we add separately each time unless inappropriate (this is what `p=Join[p,{a,yl}/.{,yl}->{iso}]` does). We store the data in a 14971 -byte file called `"b"` in the working directory ([hex dump is here](https://pastebin.com/RRYHUYCi)), which is converted to the list of its corresponding bits by `Join@@IntegerDigits[BinaryReadList@"b",2,8]`. That list of bits has been determined by [Huffman coding](https://en.wikipedia.org/wiki/Huffman_coding), which is a lovely data compression scheme that takes relative frequencies into account; it requires the decoding template, stored here as the binary tree `t`, as well as the raw list of bits. Inexplicably, Mathematica doesn't have a Huffman decoding (or encoding) built-in, so that's what the `For`-loop implements. [Answer] # [Bash](https://www.gnu.org/software/bash/) + sed + xz, ~~13322~~ ~~13290~~ ~~12785~~ ~~12706~~ ~~12694~~ ~~12687~~ 12681 bytes ``` sed 1d $0|unxz|sed /`sed 's:[A-T]:yl/g;s/&/:g'<<<AvalBglutamClysDthreonEserFprolGglycHleucIisoleucJalanKaspartLarginMasparaginNtyrosOglutaminPphenylalanQtryptophRhistidScysteinTmethion`yl/g\;s/yl$/ine/ <12479 bytes of binary data> ``` [Try it online!](https://tio.run/nexus/bash#XZ3bjm65VYXveYp9AQIkgrx8WLZRxJPkxkeRCyJENyI8ffi@tQNBpNPdu6r@Wgd7zjHHmAf3H/@4f/zm33/85t9@@fHPP379/a@//8M//vIvP37729/@@N2fanrLm2NIj/@MOYW6anlPbXXwpz//NN43/O@fa01plJmfuEsuO43a38Unapo1xRvfeNN4a6xp@Vd@6vs@78rxrS/Xrpmvdk78udeUM1@3Grn2fU8u3qXG/NbA9y6/Vb/f6m/K7V38rPCn/vKb/vTPXw@vz98nz/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c/34zfrfy/w93/n5ub9c7u//ao1f//Lln/4b "Bash – TIO Nexus") [Answer] # Bash + sed + [paq8kx v7](https://github.com/JohannesBuchner/paq/tree/master/paq8kx_v7), 11682 bytes The submission consists of two files: an arbitrarily named Bash script (*23 bytes*) and a paq8kx archive named **a** (*11657 bytes*, plus *1 byte* for the extra file, plus *1 byte* for the specific filename). ### Bash script ``` paq8kx -d a>t sed -fd b ``` ### a (base64 encoded) ``` cGFxOGt4ADj////9lNl7YOLMnQ0W4tNQaR+2z8um8YSdKwDxDgFaqATIG40F0T57vk6/ecQVh7fU f7Svr8dv1eChF3zrWq8UgnsrUO6Bn7YlE5XzoDyNYi6bTqSZ5Xd1ThnuEDr6ibyqXoLgQ2hc4jyi gBfeJpHhdFXSRD7Wh31GccwOT7aHuw0/vZctJIhPVoIqNKEs98wfbDPvXkVeP/hlwUnBJ9ixVKk2 Qn6Yo2XOMdRpmqDjXz/acpO1kWc0meEbNGW7CCJiYChQdCFpUdMeY3gE94Dkz4WF+1Uli3Sn6r4O u+NOZNQVXwugmAYzxeDkNH4qiyUYvC7e0knysiTw058uyhp7YoQKnm7jbotT2OCN+zIfR8em5e7k a9vOZ4czRi+nxtxg0KEgs92QA9jtdpwiULTeSG1j8xPr80k1i52yxeBjrMUtH62i2UL2/IkG9mtV fHA45Katd7Vqz+4W2mWPAaW5NgQPZS3zb0omw6HIcvdruNq+8JyCxy6XpYoYRdCWtkAj1S4hvgB0 6S7SZBV8zNXYeb+Ei72Z1+bnEwFb5z+1DQbayjJ8POn8VVkXmrDuDbNeLJyGhCLHtxMVFO2u3Ik/ KqT8RsIz9adx7VqfLFhr1kOYSISuFfIb0AbtOoj30BTc5F86zEfCNTQPNyKFeIIk16lyDrReZbl9 ub2aS3tfCuJIrgKRTuPPkoFPwh/Q6mSephO9y7pBvQxzU8DkkCdOxe21hPN0XVHW6YeRJI4TydZj pTe6U6l8vrt6flaeKycVOxTVY0fn92wIeJ4PtgRzrmkGGy29q7y5WgtrItAmVG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VRx2lGB1YCR/SMQxLFZqOxWcwmsKlzhX1faFSqj/EVjjHYIze+crz SRWyHX7R5Z36x6oY8K2O5BQZ9XK6/eeoCQfsyQa6Bp37jzJQde5kjQfxeuPoqQWsv2xsYbQvx4mq Hs0CRcAh+lmJuQN6PqrVbdXGMa1/+WF1AEP+ReBvDrEbbJxllqyv0jrJR4twjM8ajxlNkiuH0Dfg FSOJhNPdBOtEXmjClW07o+dv5bc6PdAtfjCPVeu/rkJmy4lRTTBlPMN4adSQNuub4O64OxB1SDIQ 1sncK5zZc06dTgFJOoV9WKd3fjof39PKwJ5LfiSFjqmu4AJHGgRtr99gHIBPXjdyKx66SVyFa6fO SVcFoW2N58UwjQp6ypGkLfZ1iU3U2vWoDOA9iA/W/bXpzgEVPi6pjatuVXUYs/EGUGHVUJOkHLBc eykVI/rEh80DMQTO4heUlFpB00QJFCurJSe+x1MHwuOOHpICd01N6+CmmQ2Vjbz1WzLbtghFez62 0Gz2X3QWUpE2xYYMzpTEDhrFKlGxcyg/2VwDgm9T+PH+1rDHLFJMIoAEYgYM2II2XAP64+ed5u1l Yfxz3+ooBElCqhhGT+Njf/i4tU4VupKEM1UxsN3zTH0KvlZN4zR930wTyrNq6eArBLNe6PKQpxln PXSm0sTjCgYLGdCIvGJqfcECY+XLcHOYkOMMgxviDUzZDERP3sKlNGh6EyYhaLR/bqcDkhiXCTm6 I73a0K9oh4SyJNOn8A8Lj6ZTAmw1LeRJ9dwZK9Y= ``` ### Verification ``` $ bash titin.sh | md5sum ec73f8229f7f8f2e542c316a41cbfff4 - ``` ### How it works The first line of the Bash script – `paq8kx -d a>t` – decompresses the archive **a**, redirecting its output to **t**. The redirection is required as *paq8kx* prints information to STDOUT, which should not be part of the final output. Said information will look as follows. ``` Extracting ./b 26926 -> done Extracting ./d 307 -> done Time 15.36 sec, used 1929185730 bytes of memory ``` This creates a sed script **d** with the following content. ``` s/T/methionyl/g s/S/cysteinyl/g s/R/histidyl/g s/Q/tryptophyl/g s/P/phenylalanyl/g s/O/glutaminyl/g s/N/tyrosyl/g s/M/asparaginyl/g s/L/arginyl/g s/K/aspartyl/g s/J/alanyl/g s/I/isoleucyl/g s/H/leucyl/g s/G/glycyl/g s/F/prolyl/g s/E/seryl/g s/D/threonyl/g s/C/lysyl/g s/B/glutamyl/g s/A/valyl/g s/..$/ine/g ``` It also creates a large (printable) binary stream that encodes the different parts of titin's name. ``` TDDOJFDPDOFHOEAAAHBG<26886 more uppercase letters>EHGMBPGEKEJDAMIRILEI ``` Finally, the second line – `sed -fd b` – executes the sed script **d** on the file **b**, printing the desired output to STDOUT. [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~27747~~ ~~27081~~ ~~19701~~ 19229 bytes Take that, Bubblegum! ``` O("alan argin asparagin aspart cystein glutam glutamin glyc histid isoleuc leuc lys methion phenylalan prol ser threon tryptoph tyros val"^sA*Y"..."R^(PA3,68)."xyz{|}~ !"Y"uttscfkmovgsmmoshiwnqtwjgioettdwnmvmfisgnjdgkrvik nrdrerjikomezastkvktssdewmdogtvtwweidsrineogsiwedkngwfotnsdtnomowrmsqemikiksoidiorntgkmtniwswowirrwt"<>2)J"yl""ine" ``` where `"..."` is a very long string. Here's the [full code as a Gist](https://gist.github.com/dloscutoff/69d34a4b7f3a54891f61a264b48b74f3). [Try it online!](https://tio.run/nexus/pip#XbzZetu4trV9rqsQK6nEcdw7cRe3cdzbsiw36i1ZQkMABEACECFZza3vb0LOWnv//0E5lScRSQBjjvkOgMr/3C/885a8qeKboQx@2vTNvP33/1yxP7IOw29pMnBv8u8v89@P@sWYWcdQkVmd4EG/@PFjZIsSu5hpVUxjrEbJ/PKp0UnRYlN0scHwR86MUqfTuOhGRtti/pb882pPFuv/pOv8wC1zs21v/eTN1TOGkrbITItNB6/v3Lfd6b5YaWf2HV@NpEGRRsQKnNtGnbwJXj/tKzXrO1Qk2Qretql75G/8cfsx@mKI8bMsx@99yc@fM94@ElTlVm32UX6/cJbblzqxXuD5JVa6jLWuqlU5dYi3mc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are truncated.) Strategy: split the name on `yl`, and encode each piece as one of the lowercase letters `d` through `w`. Use their code points (between 100 and 119) to index into the list of pieces (which is of length 20, so the indices are taken mod 20 automatically). Join on `yl`, output, and tack `ine` on the end. Further compression: find the most common pair of letters in the encoded string, and replace it with an unused ASCII character. Repeat for all ASCII characters `#` through `c`, `xyz{|}~!`, space, and newline. The code takes this twice-compressed string and replaces the characters that aren't `d` through `w` with their corresponding two-character strings. Goto paragraph 1. [Answer] # PHP 18731 Bytes ``` echo strtr(bzdecompress(base64_decode("$base64encodedstring")), [A=>alanyl,B=>arginyl,C=>aspartyl,D=>asparaginyl,E=>cysteinyl,F=>glutaminyl ,G=>glutamyl,H=>glycyl,I=>histidyl,J=>isoleucyl,K=>leucyl,L=>lysyl ,M=>methionyl,N=>phenyl,O=>prolyl,P=>seryl,Q=>tryptophyl,R=>threonyl ,S=>tyrosyl,T=>valyl,U=>isoleucine]);'); ``` [Try it online!](https://tio.run/nexus/php#FJvHjoSMtYRfxfLql1g0OUiWrsiZJqeNRc7Q5PDy18ysRiPEwKFO1Vet5j//96t//19k9fSvdVu25Z/0yYtsGn5Lsa7/pMla4Oh///6SF//82@p/k8EJTODEbhAaNZGStFyVIi3StPn5ALTIMAMAPGZCEIfpIsdSh98nL3Pqu1GIYR7pBBA2hYjUYWxXLh3mvoRH8R68A9T@HvZA1ziZfYHsSGhum5n7pVvmMFUAKbICAEUV41KMyHqnUT/Bdo72PgEj2bwUSPiDbulblsV77LFR5HOD@0O0hLljx4IgQ1iGK7DtQEF@gR24MLcAjh5SSODYyhDCU8KcKaRAMuqCiPdKqIDgHgzJjjLdeoIgivfMyPtjIUebxXBSfGHEASmfSolTpKg9x3KSIlYAgQuKKjMCeW/4/W2n0Ke9BJekW5d3ppZ3abrquumE9IH2QPCeLMMjDYa2FYvzzYul5a6nDRekK9bxJAZQwHi7Pa3dk5AAVZPQIQdEEhchHFCx5@TANEYiPaMZiTaRioqHaQ9eNSr8tbbLyfQtJfq4/L4/3Y3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replacement of all words with uppercase chars in the range A-U after that bzip2 and base64 encoding ``` $a=preg_replace(["#alanyl#","#arginyl#","#aspartyl#","#asparaginyl#","#cysteinyl#","#glutaminyl#","#glutamyl#","#glycyl#","#histidyl#", "#isoleucyl#","#leucyl#","#lysyl#","#methionyl#","#phenyl#","#prolyl#","#seryl#","#tryptophyl#","#threonyl#","#tyrosyl#","#valyl#","#isoleucine#"],range("A","U"),$titin); $z=base64_encode(bzcompress($a)); ``` ## PHP, 19920 Bytes After replace the words with numbers and create a very long decimal number I can only read the word "leucine" I have 20 words found that I have replace with numbers After that i use [bzcompress](http://php.net/manual/en/function.bzcompress.php) and the last action was base64 encoding ``` $g="base64String"; # see online version echo $o=strtr(bzdecompress(base64_decode($g)),array_flip( ["methionyl"=>9999,"cysteinyl"=>9990,"histidyl"=>9909,"tryptophyl"=>9090 ,"phenyl"=>9009,"glutaminyl"=>9000,"tyrosyl"=>899,"asparaginyl"=>889 ,"arginyl"=>888,"aspartyl"=>800,"iso"=>70,"glycyl"=>79 ,"prolyl"=>78,"seryl"=>77,"threonyl"=>6,"lysyl"=>5 ,"alanyl"=>4,"glutamyl"=>3,"valyl"=>2,"leucyl"=>1])); ``` [Online Version gzinflate](http://sandbox.onlinephpfunctions.com/code/82ddaedcc3578b66deb15b7248a16e395de046c6) ## The words and count ``` [methionyl] => 337 [threonyl] => 2083 [glutaminyl] => 724 [alanyl] => 2304 [prolyl] => 1834 [phenyl] => 672 [leucyl] => 3351 [seryl] => 1910 [valyl] => 2414 [glutamyl] => 2324 [glycyl] => 1731 [histidyl] => 391 [iso] => 1658 [tryptophyl] => 401 [arginyl] => 1405 [aspartyl] => 1430 [lysyl] => 2199 [asparaginyl] => 902 [tyrosyl] => 829 [cysteinyl] => 356 ``` [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 19655 bytes ``` 0000000: e2 e5 7a 4c bf 5d 00 36 99 4a ef 2b 08 5d b1 93 ..zL.].6.J.+.].. 0000010: 69 cb 7a 61 51 8c 3c 7c 04 41 de 7e ea ed 68 3c i.zaQ.<|.A.~..h< 0000020: ca 5c e1 c8 6c 5b b5 31 2d 0b 4e e2 8e 52 06 ec .\..l[.1-.N..R.. 0000030: 5e e6 da d5 f2 f5 d3 8f 83 a3 51 0b 45 5d 19 c6 ^.........Q.E].. . . . ``` Here's a full [hexdump](https://gist.github.com/DennisMitchell/c8cd46c9b8eb7a1d3b00e5541c456b0c). You have to paste the code manually, but you can [Try it online!](https://tio.run/nexus/bubblegum "Bubblegum – TIO Nexus") (only shows the first 128 KiB) [Answer] # bzip2, 15287+2 bytes ``` BZh91AY&SY... ``` [Full source (hex-encoded)](https://gist.github.com/Sneftel/dc58481019c421d01367b4fded67c39c). Run with `bzip2 -c`. Where do I pick up my "best programmer" trophy? [Answer] # [R](https://www.r-project.org/), 17684 bytes ``` E="/Td6WFoAAA..." # base64 string reduced for better readability U=unlist(lapply(match(utf8ToInt(E),c(22:47,54:79,5:14,0,4)+43)-1,function(x)x%/%2^(5:0)%%2)) D=memDecompress(as.raw(sapply(split(U,0:(length(U)-1)%/%8),function(x)sum(x*2^(7:0)))),'x',T) for(i in 1:21)D=gsub(LETTERS[i],paste0(el(strsplit("phenylalan valylthreon isoleuc leuc val glutam alan lys threon ser prol glyc aspart argin asparagin tyros glutamin tryptoph histid cystein methion"," ")),"yl")[i],D) cat(D,"isoleucine",sep='') ``` [Try it online!](https://tio.run/##FJnHjqzaGYVf5cojS8gmJ8keFFSRc4YZOeeMH/6aox6VusXe/GGtb1Uvf9t//edff6XxtO1L/u9x36Z9@@f//v799x@gkxE@N34@H24SNwz5lJ/qY53v54/5wI2K8cWltl32YWc7kSXhqm3bMfxeCy5hOItxGO6U4KNaKCvA0Ix6mWwVvGKIVaYflZbk12k3mgafgnBpkhIupzAOcC8wgvBBPkFLID@oYkgWanN5ndCZ/Wm5O9NPPdCEaFhL@myOvDCEYvBh6nHDBV5j0/9c@vKLg1ZnMVMau7snoaDEgASdlrGbiwfTLikxulBIa4/w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Nx17uy/gTvsGnd3tmG0glGJygApYjVDnAPIfzB4BvzLFa9JLkBidoeAILoXGCQK0FAgA@O/sLwpweU3BdxXwKqZ95d7MzZaWcVAruVUs4a2ZQSjPW@24HUSx5P125/5X2YNuUBdgAjggn0502uMqCSQQKqdIJFEYIYqquVcVaIm1T47pdD2pBGw1D4NieTatx1HTLt94qH0MtUgryETGmR7ReJTgLeRkKzi3wg3kclaVDXWsEpzvtNSqWip@RIJrALUTV3TVVC6JLpxox0YrRQKEJj6N6ucIt3kqB7d3xu//jGznKCRLnKR06Ap6x/iInSjJaqK8OGw3Lm3dP1f/etf "R – Try It Online") The approach is similar to other answers : 1. Remove the suffix `"isoleucine"` from the original string 2. Replace each occurrencies of the following tokens with an uppercase letter in the range `A-U` : ``` TOKEN REPLACEMENT phenylalanyl A valylthreonyl B isoleucyl C leucyl D valyl E glutamyl F alanyl G lysyl H threonyl I seryl J prolyl K glycyl L aspartyl M arginyl N asparaginyl O tyrosyl P glutaminyl Q tryptophyl R histidyl S cysteinyl T methionyl U ``` obtaining a string of 26610 characters 3. compress the string using the R builtin `memCompress(string,"xz")` obtaining a raw vector of length 12936 (bytes) 4. encode the vector to base64 (because I don't know a better way to store these bytes into the script) obtaining a string of 17248 characters The code does exactly the opposite (from points 4 to 1) and prints the string to stdout. The TIO captures this outputs, save it to a file and compute the md5 hash to verify that is correct. Note: we can't compute md5 directly on string because we need a package that is not installed on TIO. * **saved 37 bytes thanks to J.Doe** [Answer] # PHP, ~~19851~~ 18639 bytes ~~204 bytes code + 19647 bytes base64 data~~ 207 bytes code + 18432 bytes base64 data ``` for(;$c=bzuncompress(base64_decode("QlpoNDFBWSZTWaBb474ANYhgAH//+ABgQZ773ed6+9vtzjvtrH20qH2Na331vdtffO+8cdk3tc+m912fOeetbBXbPvet7PO2L333vPt3T7s+22+3cbbru233ve7eR7um9557dt623rsr7vbHPNu+vvets++ebqM993W77vvlmu8997IG7Pt3afXnPucsvvYUCnT3Rmls+7qvvT3dr3V73r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G9ccyZXAiYGeyQ0VGuGAMVVPKCFch7r04172v2tUEaMfBmo9AhH30+FDG1bq9C3OO+dIKaGeaFz3EEYX1Z8mB97CGMxOh200ezbtJguszamWPzVp8hCYWow56R+QM5Bb1K8MDLw7jEQiBxoT9JnRZqnEfWkg2lHwBkeTnn5/z3zncSdvzcTLm41zzetaD2NKEHGhup9+UWY0Ey934cIt/fFvZMQMsKU1uafTXm6+7mli3QzQnQsjEzNHAe83J9WItf1Y53MntJ2dXbGfMjiRKvUwER/prGpmvbowd20kZBRWSFyrKngxty7wgyTvTK+iW9W09pODl6fYyBkWdjwzPM2HJ2hOtU6n1ylFyFLF8smex2/cdJeWqYDpbHrX2kSZg8Gvywu9yU3tdAbKeCvy13hh47ytu5yvBKIGIlyTba1BQS+395zmdZL9Xtlgc2pbFoJrc9LzDzINNdtV75QjiRlTr5HZPA+0FEUjtOLKkqY31z2RQwrc2o0ik5scvNTNrcenqKZ8mXlqj73syGEcC5HdXt+FbH6U6exk++O5EFFQb/PTfscUcv0P7kezcKFMMoyHei6q65jxX8BNDZYLoWDvQBwXHOt5ULPb3R1F4gJZ2TYXnU1miihhICh6eiMiQ+WQ7uuUQ+JCspYaOjHamg2/snrGMJ6i89Y4Mz7FejNflRA1m6bPCC9JiuZDRkLlDNzuyRaJgrEDX6o01eK/6BWtfQvyQfQ4Eyuq6tKymHBSalh3yVsYTywpFG02EG7f2TROPSYiVOVjROd3tmmdPDT4HxWTydftepPujJ0MZtRh6kGHXMJxNhGtyxLHSiJxSe3+gd0iZj6TnypEndCuNpPfnlZRJbEVSoiUwZe2JGnh5f7lyHB/AMn0i5zrFNWTP9nBFWPIv/F3JFOFCQoFvjvg"))[$i++];)echo[val,glutam,alan,lys,threon,ser,prol,glyc,leuc,isoleuc,aspart,argin,asparagin,tyros,glutamin,phen,tryptoph,histid,cystein,methion][ord($c)],$i<27598?yl:ine; ``` or, without the data: ``` for(;$c=bzuncompress(base64_decode(""))[$i++];)echo[val,glutam,alan,lys,threon,ser,prol,glyc,leuc,isoleuc,aspart,argin,asparagin,tyros,glutamin,phen,tryptoph,histid,cystein,methion][ord($c)],$i<27598?yl:ine; ``` --- I took the words ordered by number of appearances (descending), replaced them with bytes 0..19 (`isoleucyl` and `isoleucine` share code `9`) followed by ~~`gzdeflate`~~ `gzcompress` and `base64_encode`. In PHP: ``` echo base64_encode(bzcompress(strtr($o,[asparaginyl=>chr(12),glutaminyl=>chr(14),tryptophyl=>chr(16),cysteinyl=>chr(18),isoleucyl=>chr(9),methionyl=>chr(19),aspartyl=>chr(10),glutamyl=>chr(1),histidyl=>chr(17),threonyl=>chr(4),arginyl=>chr(11),tyrosyl=>chr(13),alanyl=>chr(2),glycyl=>chr(7),leucyl=>chr(8),phenyl=>chr(15),prolyl=>chr(6),lysyl=>chr(3),seryl=>chr(5),valyl=>chr(0),isoleucine=>chr(9)]))); ``` Moving from A..T to 0..19 did not only save 4 bytes of code (`65=>`), but also 3 bytes of encoded data (with `gzdeflate`; I didn´t test again). --- [Answer] # [Python 2](https://docs.python.org/2/), ~~18409~~ 18403 bytes (with no libraries) ``` n=sum(95**i*(ord(v)-32)for i,v in enumerate(r'''~'W/P58:`Ote}|QRokHosM/W%~zh%Ab*ZI~i4?=Z/$_-Y*6D{ EGAP\ENvC,4=v$YQ#Z=<)e^5!p5*|K/Ap|.?CyO*51Ladt8c`it>w~1w2@{8.kb%;2n}Xvp8d{/GE4_c'8dO\)Qu(5G8[::X-(cMkgKeUli@0HJNa@Y84p^~:8'Jn #BoNyJn#5KAy[Lb} K{i=TlKzA^#EBWd>,|Ut!V.y5GCiXrO?~'dGYY;Pg6A|ub<ASiLi_@gL?Fb14=!x4-HE@4>3<_thTv&~8X%T2@;gaQy8Ao=DAnI50|7N6_lh=~7gF-@;CmFz:]?aBr~]K}eoFh{nG!4&:T>MSKxB6{N0TJ<ig@Md(ix?*\$;E0H5<f/M7EubRYLA1`A_Cuu0g"]!#w,Hf/uH2(a~~41\D.w"pg|{vO=.a)(xEqiW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QE0\',2j#]X2x9l-L#`X(/o8'*CVM_FkOD0&glK!\g5XC(N7I`P3o|LlSvz572xjsA_2eDAFDxO|Rk8,m]TL4Lt]/|nCU.xPG$i$Xz\Y<:tv+E%Gl`A&},3(BzDRLJC?&<`fB`d,jsch+ib4Fl?eMGcU RpQ1`l4u$:pHe)ihm{#L"NbN @S@BUI-{V)'@6Ug?ZMK]**fL''')) r='isoleucine' while n:d=n%20;n=n/20;r='cystein methion threon glutamin glutam alan prol phen leuc ser val glyc histid isoleuc tryptoph argin aspart lys asparagin tyros'.split()[d]+'yl'+r print r ``` Creates a number, `n`, by reading a raw string using characters between `' '` and `'~'` as digits in base-95. Decodes that as a base-20 number using parts of the full name of tintin as the digits adding `'yl'` each time, and initialising with the trailing `'isoleucine'` and `prints` the result. [Answer] **Python 2, 14627 bytes** * Encode the amino acids as bytes, from \x00 to \x13 Special treatment for phenyl which only arises as phenylalanyl. No special treatment for iso in isoleucyl, just a different group than leucyl. Special treatment for the -ine. * encode the string with bz2 * custom base 216 encoding of the bz2 binary string (218 printable characters in cp1252 excluding ' and \ for ease of use in a string literal.) encoding 31 bytes in 32 printable characters. Source with cut down string s: ``` #coding:cp1252 a='glutamin tryptoph leuc val aspart isoleuc glutam methion alan glyc phenylalan prol argin threon asparagin cystein lys histid tyros ser'.split() p=[chr(x)for x in range(32,256) if x not in(39,92,127,129,141,143,144,157)] s='ª9W¾½ÍWÕiì7.{ç5æÄ‚¯g×;NíbdXÔùP¯ ...' d='' for i in range(0,14241,32): c=s[i:i+32];n=i=0 for c in c:n+=p.index(c)*216**i;i+=1 for _ in s[:31]:n,c=divmod(n,256);d+=chr(c) print'yl'.join(a[ord(c)]for c in d.decode('bz2'))+'ine' ``` [Answer] # [Pascal (FPC)](https://www.freepascal.org/), 27917 bytes ``` {$H+}const s='<Compressed_string>';var c:char;a:array['A'..'T']of string=('methionyl','threonyl','glutaminyl','alanyl','prolyl','phenyl','leucyl','seryl','valyl','glutamyl','glycyl','histidyl','isoleucyl','tryptophyl','arginyl','aspartyl','lysyl','asparaginyl','tyrosyl','cysteinyl');begin for c in s do write(a[c]);write('isoleucine')end. ``` [Try it online!](https://tio.run/##bZ3bji7HcaVfRRcD0MbM@AEs@KIys3aeKv88VN0ZvuDItCVAFgWSnoEwmGf3fCuq/u6mbFrm7t38uw6RESvWiojM/vP3P//u@z/@z3/58@/@4z/@739L//3//e7HP/38y29@/ofvNud82N234Pwefco5x1KTC3ynhKOl@i3seS85vb6FPqrPLbnk4l6zb@lbSKP2MKNre8huhpVqP1Ocwa2aqg98NJQY8wzFhX1f30L2ndtsLndfk8/8JffsatvXnvP8Fk5uEkrzKcXxLXAPX@qIXDM2Hujcy0jVnSkvbpEyN3/fwtdSSt7DnG66lvkuP1xS9663Mmfjbb6FEXpqweWy5cZ9QvU@7sd0@97bvs99pp52/saHwgw@hu592tPe@qE/cj9yx1r2ZcppD6HLHvz3xDf2GLc@sWdyObiK1fZ9f03e4MwhpVRC2XpxLjoe2rfuSumvgsUwZvHZYW0eKYTApQP/dwZeWVcKs@TpRxgzBX0jZ/4YW@i5l50VCbl43rc7/gn5aH4PumCf3HE6rUzWj4zJhXyJvKWbpTXneDa/HdkdhceZxfFplmjn41w03B/HfqmU5ub0k4f0JbSNj/KiWZ9sPA9/8MkRc@q1l6oLd@7vG5@e2/sxYnJNT/@@bovdYY4tuM5jNK591JlHrnPe732/pr9fk//VI5aCVbzHhuWs5yzdnjOHsu@@7yGV/dBThTz3nhuenYo72nRu@Fk3/Dn5NvVX1qD0mI88Zt@7C2nHPVxOsyV@3pWjniXgBjUFHCb6WWLC11LwE1MkPHp33ITL83Tc3u1x98TKN8zs9uHOyXLXzLqxdjWn5qrD6VlxAivHAzvx3I6w6DjtnkvbM47nsGGNc2WXW6klZV70Uhie@JzL7nX2Mk7fSkrN4oP18qm20OPWuCS3V4RwE3fhFotn4KVcus5I6GUWktuzenKKQrhhhTL5dCZSRs6bGy5FvudD3WvBv/fzW@CFCU4/Yy61AhHfQr18rn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PuJO351pHdsopOYy1qmicb1mR9SYb2i4BcYnmK6uiH6n@q0jgPSURu6ZcPaEgd6aRC5XzlaE7qWEPopyqt2lqgZZxc5OjDOvuXCs0aroTneBi707nTOtBXbRYeE0/yy66/crxPTk42DUWo2hmbCzCB@Wo/SwM2@tIZE7ZTP@WnsKDDFAQa1V92@BVCmOwAmIAzOixZB2Tqt994be5NCQjnnbADjmffsMPXNXlNHGxao8R/9vwrIdW1H7hsyY5n32CDa3OkNFXo56ZZ@9aVB/SbFHRuB486bGu2y8E2B2mfhm0gUSLtOtjUF6/f4nNYI8GGDlvbhmBf@1oQUgCptRB5OzX/G1kkfffb//39T7/53d//7vff//Tb7//@@59@@v4v//jd9t3f/d1313f/9OO//ObnX376w5/@9R/@5rt/@@GX3//hxz/95Y/f/Y/vfvn9Tz88X/7rH//9l@//7Q/3X77/4/f3F3/@6cc/3l/8/of7O3/84d9/Z1/8/MNP9uf//v6PXy7wfPmX@zO//8PPv/zhn@3LP/z848eP/vLTX/78y49//v19r5/@9X3Xn//8/U@/3Hf5y8@f3/r@/YFf/vLTj/f3f/eXn3/5wb77t7/9Xz/w33/zLz/y@r/hi59/888//ub//PSHX374m@//8Xf/9Le/vb9@P8Af/vTDd3/7w5/@@e/@4z/@Pw "Pascal (FPC) – Try It Online") [Compressed string](https://pastebin.com/cN4cJVVF) [Hash print of the output](https://tio.run/##bZ1LkyXHcaX/ChdjBtE0o502pGmREZEdr4wbj8ydTAsMCYkwowgKgDRGG5vfrvmOZ96qBiWIQlcXbuXDw/34Oe4eUX/@9qffffvH//XPf/7df/7n//0f6W//37//9N1Pv/rX3//9b3/3w59@@vlXP/3DN5tzPuzuS3B@jz7lnGOpyQW@U8LRUv0S9ryXnF5fQh/V55ZccnGv2bf0JaRRe5jRtT1kN8NKtZ8pzuBWTdUHPhpKjHmG4sK@ry8h@85tNpe7r8ln/pJ7drXta895fgknNwml@ZTi@BK4hy91RK4ZGw907mWk6s6UF7dImZu/b@FrKSXvYU43Xct8l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ze/@8O2Pv/32N9/@@OO3f/nHb7Zv/u7vvrm@@acf/vlXP/384/d/@pd/@Jtv/vW7n//w/Q9/@ssfv/mf3/z8hx@/e778lz/@@8/f/uv391@@/eO39xd//vGHP95f/OG7@zt//O7ff2df/PTdj/bnf3z7x68u8Hz5l/szf/j@p5@//719@f1PP3z86M8//uXPP//w5z/c9/rxX953/enP3/74832Xv/z0@a1v3x/4@S8//nB//3d/@enn7@y7v/7tv/1m@9NP35/2fr/939/x4V/98w/Y4ld88dOvfv/Dr/7tN//wb3/77T/@7p9@a1@9H@X7P333zW//z4/f//zd37Tw94Mf/1lf3Bf6m3/79a9//d2ffv93//mf/x8 "Pascal (FPC) – Try It Online") Compressed string, along with count of each string ending with `yl`, was made using this: ``` type part=record name:AnsiString; count:QWord; end; var s:AnsiString; c:QWord=0; a:array[0..50] of part; i,j:word; p:word; begin read(s); p:=pos('yl',s); while p>0 do begin c:=c+p; //writeln(c); j:=0; while j<i do begin if a[j].name=s[1..p+1] then begin Inc(a[j].count); break; end; j:=j+1; end; if j=i then begin a[i].name:=s[1..p+1]; i:=i+1; end; write(chr(j+ord('A'))); Delete(s,1,p+1); p:=pos('yl',s); end; writeln(' + isoleucine'); for j:=0 to i-1 do writeln(j:3,chr(j+ord('A')):2,' ',a[j].name:20,' ',a[j].count); end. ``` [Answer] # Deadfish~, 1103473 bytes [View source here](https://hqfot.surge.sh/d.txt) By far the longest answer I've ever done, and probably one of the longest (non-Unary) on Code Golf. Definitely longer than all my other answers and questions put together. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 16071 bytes ``` _=>[...Array(27598)].map(_=>'isoleuc|methion|threon|glutamin|alan|prol|phen|leuc|ser|val|glutam|glyc|histid|tryptoph|argin|aspart|lys|asparagin|tyros|cystein'.split`|`[a/=20n,a%20n],a=0n,[...`-}Þ÷...ݦû´`].map(i=>[i=i.charCodeAt(),i-=i<127?34:68,a=a*188n+BigInt(i<0?66+4*i:i)])).join`yl`+'ine' ``` [Try it online!](https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V0dA5qDVcmtgpNz41Nw/oZKzIWDFGiDvTDik1tlGPWUT5RSqfAuoVzlJHqXuMB3kLOqkTwnVcaqd3b/9/ "JavaScript (Node.js) – Try It Online") [Generator used](https://paste.ubuntu.com/p/7RRMJ5rNDf/) [Answer] # Python, 32148 bytes ``` import zlib, base64 exec(zlib.decompress(base64.b64decode('eJzNnetuLDmSpB9ndh/roLYxXUDNdOOUZgC9/U4plUG7fM5gqlS9++dcpMzICNLpbm5mZP7z56//+fa//u0//vb291//8Z/vv739/eff9O9//+2/3n78x6//868fv/34nz//+fMfv63f/vPvf7t+0+94vPa3v/3XL/rT3//28/23//7xm/6hr/nj7/dfPl/3vKh/hH7s802P//3919/ffv0/77/9+vs/Htf8uMrjgvqux619fPbjn8/LfPzo8dE/3//59o9//t3f+OPnv38Mxu///PHz7Xnl9XAfb/cPf960/efx++dH/3GNj3euC/k19A4+fuCf/7ypj9//9v778/rPT7su9vjAx+s+PvC6nz/e9PmEf1z6x79fU2Uf8fb+8x+/f/7icUl55zVZ6woylTlU/h6Y7eeUfH7Ox5+PaFkf+XyNv/PxmJ8Pu25GRzGG+/PxMFZrbXy89/Md67X2qBYPw8X1dzYZjyvlpMlzrOBd42FL8TFLGKs+bteHxDPLBD/f3ouu41RHQ9fy8xqfYdlB9PHndS1a2Z9v8tX6vK4E2JXA5EMeI70GcAzX9WpYWF8J1QyPNSz+t2QiXcV//GFLtFa05Cu4o2mGnlkkY/i6xuMXER16V/Urz7+WMj8nyRLox+fHhNv6el73Wn2eWimon0/ueWb9S5fT80ZtVC1vxBDo7x4Lbv1TB/ORr71KylvpuWXGc/LsZZ1xbM3KBzz+uT7m8c7nM/OrNR09X6k/w/q/u8haTPICfeIc4i6X/ByypmvMdQVeofNMwDrXWYjswx8XD1jz/kumH1m1+udCDh+fOCXFzwwln7VSr61VzzH5VFkCHWLkT+0xIUk867y9Qm7l89fXE0aeN5SAwMavWLWPgFuvbouiNXQr2BQqyfR+1kW7no7xOO+yRG3yY4Ij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LyMvt9NaJ6kTXUGzZs+8qUA+Ul2q4ffJrBCb1CkI65Z80zFgCBsPTKcEXAkIM93QI6kuy9Za5KVcupI2anySgKwcakBiWyYq3C22cdqIGxveIqVUVlAo6aqY8cpQBNmlZ2ang02c57osme20/IFQlgnXUslx65EjPd92ktphTnTfJIjUe6DwYmt5Wk6rFWAyBZJxvMsLCK996cjwON1ciaoHhXJQVKI1AXJCdsdk/03jOqtHbTQh2063+NfR/III4QKwZUv6159uZm5R4+FgsWbb6xklYdy2GSQgcEqPTNmnYmrAVzJd9aDG+xXKCXMcGq8mMrU1nLS8OM6QWtfqjbNMg2F9wkxLppie2EQBj2IcZbs6hGEUxQTWkgYEkTUuNFPt7FXxCRyapvSVWoLKr5iVlWpQ5yYutmiVsTz9zO53WiBYPvZr6mqQ00i7ccPSjRoBym1WV0yE1fsNne96pGyqOqt1hA7bhJQf2WmRGIz1Gsc8DlQMXF4XWCxDw9aUYZauEN1k8lYk0F7c+oNmboTPsYlQYbsXR6k8zHC8DDgYcR+mM2pAW90EjICscp93S/jeziS4Ea/GLzwTWuJ5ivCO560xVleNhKVqtChwR6AALl48HrQFDIdyksH8p4v1PCWZopqOECNnZl9UCyzMn1LwaJhCKFwvUYjQMxFaCs2gKwJefuwoD8RbDTtPOVZypxx0ogTiTcJNh7Nn+x+Tj+qQRe/GakHJ0RbMjs7y5KsZk3+MyBvS/nTd0TPdmmGwNvROxEAFhn60no1eoU46xg4xR8m46uBvRJeqMXSExebWt2SDZcnBJ8GRZ/fFDsP6acS0mVlceBynAAbwIDUcNGYk/YeF0J+NqyRgA7Mok0PlJeVdtSWruN9p7FpIrH9kmr+OcTBGlKtCbgIEi6uUmhBh5l7s8f/vqff/u3//1/AcB1Nhc='))) ``` **Explanation:** All that nonsense inside the `exec()` statement is actually the compressed version of `print('methionyl...'` As per the OP's instructions, the hash of the output is `ec73f8229f7f8f2e542c316a41cbfff4` This program uses the inbuilt Python modules `zlib` and `base64` ]
[Question] [ [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer) are complex numbers of the form `a+bi` where `a` and `b` are both integers. In base -1+i, all Gaussian integers can be uniquely represented using the digits `0` and `1`, without the need for a symbol to denote sign. For instance, `1100` in base -1+i represents the decimal number 2, since ``` 1*(-1+i)^3 + 1*(-1+i)^2 + 0*(-1+i)^1 + 0*(-1+i)^0 = (2+2i) + (-2i) + 0 + 0 = 2 ``` Input will be two Gaussian integers in base -1+i represented using the digits `01`. This can take one of the following forms: * Two separate digit strings, * Two decimal integers consisting of `01` representing the base -1+i numbers (e.g. `1100` for 2 in base -1+i), * Two binary integers representing the base -1+i numbers (e.g. decimal `12` or `0b1100` for 2 in base -1+i) * A single string separating two digit strings/binary integers by a single non-alphanumeric separator (e.g. `1100 1100` or `12,12` for 2+2) Output the sum of the two Gaussian integers, also in base -1+i and represented using the digits `01` (in one of the formats allowed as input, not necessarily the same choice). The output is allowed to contain a finite number of leading zeroes. **Your function or program must terminate within 2 seconds for inputs of at most 30 digits each.** ## Additional clarifications * You may assume that the input contains no extraneous leading zeroes. For the special case of 0, you may choose either `0` or the empty string as the representation. ## Test cases ``` 0, 0 => 0 # 0 + 0 = 0 0, 1 => 1 # 0 + 1 = 1 1, 1 => 1100 # 1 + 1 = 2 1100, 1100 => 111010000 # 2 + 2 = 4 1101, 1101 => 111011100 # 3 + 3 = 6 110111001100, 1110011011100 => 0 # 42 + (-42) = 0 11, 111 => 0 # i + (-i) = 0 11, 110 => 11101 # i + (-1-i) = -1 10101, 11011 => 10010 # (-3-2i) + (-2+3i) = (-5+i) 1010100101, 111101 => 1110100000100 # (-19+2i) + (3-4i) = (-16-2i) ``` Longer test cases: ``` 11011011010110101110010001001, 111100010100101001001010010101 => 0 111111111111111111111111111111, 111111111111111111111111111111 => 100100100100100100100100100100 101101110111011101110111011101, 101101110111011101110111011101 => 11101001010001000100010001000100011100 100100010101001101010110101010, 100010011101001011111110101000 => 110000110010101100001100111100010 ``` [Answer] # Python 2, ~~98~~ ~~97~~ ~~91~~ 84 bytes ``` s=input();L=1 for _ in`s`*8:s+=1098*int(str(s).translate('0011'*64));L*=10 print s%L ``` This does I/O in decimal. The integers have to be separated by the non-alphanumeric character `+`. *Thanks to @xnor for golfing off 2 bytes!* Try it on [Ideone](http://ideone.com/bDgD34). ### How it works In [Arithmetic in Complex Bases](https://www.math.uwaterloo.ca/~wgilbert/Research/ArithCxBases.pdf), the author shows how to add and multiply complex numbers in bases of the form **-n + i**. For base **-1 + i**, addition is done similarly to regular, binary addition with carry, with two differences: * Instead of carrying **1** to the next higher position, we carry **110** to the next three. * Carry digits can propagate indefinitely. However, without leading zeroes, the sum **a + b** has at most eight digits more than the maximum of **a** and **b**. We proceed as follows. 1. First, we add **a** and **b** as if their digits were decimal digits. For **a = 10101** and **b = 11011**, this gives **21112**. 2. Next, we form a new number by replacing the digits larger than **1** with a **1**, others with a **0**.1 For the sum **21112**, this gives **10001**. 3. For each digit larger than **1**, we have to subtract **2** from that digit and carry **110** to the next three higher positions. Since **1098 = 10 \* 110 - 2**, we can achieve this by multiplying the result from step 2 by **1098**, then adding that product to the sum.2 For the sum **21112**, this gives **21112 + 1098 \* 10001 = 21112 + 10981098 = 11002210**. 4. We repeat steps **2** and **3** a total of **d \* 8** times, where **d** is the number of digits of **a + b**. 3 For the initial sum **21112**, the results are ``` 11002210 12210010 1220010010 122000010010 12200000010010 1220000000010010 122000000000010010 12200000000000010010 1220000000000000010010 122000000000000000010010 12200000000000000000010010 1220000000000000000000010010 122000000000000000000000010010 . . . ``` 5. We take the final sum modulo **10d + 8**, discarding all but the last **d + 8** digits. For the initial sum **21112**, the final result is **10010**. --- 1 This is achieved with *translate*. Repeating the string **0011** 64 times makes one repetition line up with the sequence of ASCII characters **0123**, achieving the desired replacement. 2 Note that the digits of this sum cannot exceed **3** (initial value **1** plus two **1**'s from carries). 3 This happens to work for **d = 1**, and **d \* 8 > d + 8** otherwise. The code may repeat the steps **(d + 1) \* 8** times, since **s** has a trailing **L** if **s** is a *long* integer. [Answer] # Pyth, 34 bytes ``` _shM.u,%J/eMeN\12-+PMeNm.B6/J2k,kQ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=_shM.u%2C%25J%2FeMeN%5C12-%2BPMeNm.B6%2FJ2k%2CkQ&input=%22100100010101001101010110101010%22%2C+%22100010011101001011111110101000%22&test_suite_input=%220%22%2C+%220%22%0A%220%22%2C+%221%22%0A%221%22%2C+%221%22%0A%221100%22%2C+%221100%22%0A%221101%22%2C+%221101%22%0A%22110111001100%22%2C+%221110011011100%22%0A%2211%22%2C+%22111%22%0A%2211%22%2C+%22110%22%0A%2210101%22%2C+%2211011%22%0A%221010100101%22%2C+%22111101%22%0A%2211011011010110101110010001001%22%2C+%22111100010100101001001010010101%22%0A%22111111111111111111111111111111%22%2C+%22111111111111111111111111111111%22%0A%22101101110111011101110111011101%22%2C+%22101101110111011101110111011101%22%0A%22100100010101001101010110101010%22%2C+%22100010011101001011111110101000%22&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=_shM.u%2C%25J%2FeMeN%5C12-%2BPMeNm.B6%2FJ2k%2CkQ&input=%22100100010101001101010110101010%22%2C%20%22100010011101001011111110101000%22&test_suite=1&test_suite_input=%220%22%2C%20%220%22%0A%220%22%2C%20%221%22%0A%221%22%2C%20%221%22%0A%221100%22%2C%20%221100%22%0A%221101%22%2C%20%221101%22%0A%22110111001100%22%2C%20%221110011011100%22%0A%2211%22%2C%20%22111%22%0A%2211%22%2C%20%22110%22%0A%2210101%22%2C%20%2211011%22%0A%221010100101%22%2C%20%22111101%22%0A%2211011011010110101110010001001%22%2C%20%22111100010100101001001010010101%22%0A%22111111111111111111111111111111%22%2C%20%22111111111111111111111111111111%22%0A%22101101110111011101110111011101%22%2C%20%22101101110111011101110111011101%22%0A%22100100010101001101010110101010%22%2C%20%22100010011101001011111110101000%22&debug=0) (takes quite a while). It should satisfy the time restriction though easily, since the online compiler is quite slow in comparison with the normal (offline) compiler. ### Explanation: My algorithm is basically an implementation of addition with carrying. But instead of carrying `1`, I have to carry `110` (`1100` in base `-1+i` is the same as `2` in base `-1+i`). This works mostly fine, but you can get stuck in an infinite loop printing zeros. For instance if you are adding `1` with `11` and currently have the carry `110`. So I basically add until I get stuck in a loop and then stop. I think that a loop that a loop will always print zeros and therefore this should be fine. ``` _shM.u,%J/eMeN\12-+PMeNm.B6/J2k,kQ implicit: Q = input list of strings ,kQ create the pair ["", Q] .u modify the pair N (^) until loop: , replace N with a new pair containing: eN N[1] (the remaining summand) eM take the last digits of each summand / \1 count the ones J store the count in J %J 2 J % 2 (this is the first element of the new pair) PMeN remove the last digit of each summand + m /J2 and add J / 2 new summand: .B6 with the value "110" (binary of 6) - k remove empty summand .u returns all intermediate results hM extract the digits s sum them up to a long string _ reverse ``` [Answer] # Python 2, ~~69~~ 67 bytes ``` f=lambda a,b:a*a+b*b^58and 2*f(a*b%2*6,f(a/2,b/2))|a+b&1if a else b ``` I/O is done with base 2 integers. -2 thanks @Dennis. [Answer] # Jelly, ~~29~~ ~~28~~ ~~26~~ ~~24~~ ~~21~~ 20 bytes ``` DBḅ1100ḌµDL+8µ¡Dṣ2ṪḌ ``` This does I/O in decimal. The integers have to be separated by the non-alphanumeric character `+`. [Try it online!](http://jelly.tryitonline.net/#code=RELhuIUxMTAw4biMwrVETCs4wrXCoUThuaMy4bmq4biM&input=&args=MTEwMTEwMTEwMTAxMTAxMDExMTAwMTAwMDEwMDErMTExMTAwMDEwMTAwMTAxMDAxMDAxMDEwMDEwMTAx) or [verify all test cases](http://jelly.tryitonline.net/#code=RELhuIUxMTAw4biMwrVETCs4wrXCoUThuaMy4bmq4biMCsOH4oKs&input=&args=MCswLCAwKzEsIDErMSwgMTEwMCsxMTAwLCAxMTAxKzExMDEsIDExMDExMTAwMTEwMCsxMTEwMDExMDExMTAwLCAxMSsxMTEsIDExKzExMCwgMTAxMDErMTEwMTEsIDEwMTAxMDAxMDErMTExMTAxLCAxMTAxMTAxMTAxMDExMDEwMTExMDAxMDAwMTAwMSsxMTExMDAwMTAxMDAxMDEwMDEwMDEwMTAwMTAxMDEsIDExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSsxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTEsIDEwMTEwMTExMDExMTAxMTEwMTExMDExMTAxMTEwMSsxMDExMDExMTAxMTEwMTExMDExMTAxMTEwMTExMDEsIDEwMDEwMDAxMDEwMTAwMTEwMTAxMDExMDEwMTAxMCsxMDAwMTAwMTExMDEwMDEwMTExMTExMTAxMDEwMDA). ### Background In [Arithmetic in Complex Bases](https://www.math.uwaterloo.ca/~wgilbert/Research/ArithCxBases.pdf), the author shows how to add and multiply complex numbers in bases of the form **-n + i**. For base **-1 + i**, addition is done similarly to regular, binary addition with carry, with two differences: * Instead of carrying **1** to the next higher position, we carry **110** to the next three. * Carry digits can propagate indefinitely. However, without leading zeroes, the sum **a + b** has at most eight digits more than the maximum of **a** and **b**. We proceed as follows. 1. First, we add **a** and **b** as if their digits were decimal digits. For **a = 10101** and **b = 11011**, this gives **21112**. 2. For each digit larger than **1**, we have to subtract **2** from that digit and carry **110** to the next three higher positions. We can achieve this by converting each decimal digit to binary, the resulting binary arrays from base **1100** to integer, and interpret the resulting list of **0**'s, **1**'s, **1100**'s and **1101**'s as a non-canonical base **10** number.1 For the sum **21112**, this gives **21112 + 1098 \* 10001 = 21112 + 10981098 = 11002210**. 3. We repeat steps **2** a total of **d + 8** times, where **d** is the number of digits of **a + b**. For the initial sum **21112**, the results are ``` 11002210 12210010 1220010010 122000010010 12200000010010 1220000000010010 122000000000010010 12200000000000010010 1220000000000000010010 122000000000000000010010 12200000000000000000010010 1220000000000000000000010010 122000000000000000000000010010 ``` 4. We discard all but the last **d + 8** digits from the final result. This is achieved by discarding everything after the last **2**.2 For the initial sum **21112**, the final result is **10010**. ### How it works ``` DBḅ1100ḌµDL+8µ¡Dṣ2ṪḌ Main link. Argument: a + b (implicit sum) µ µ¡ Execute the chain before the first µ n times, where n is the result of executing the chain before the second µ. D Convert a + b to base 10. L Length; count the decimal digits. +8 Add 8 to the number of digits. D Convert the initial/previous sum to base 10. B Convert each digit (0 - 3) to binary. ḅ1100 Convert each binary array from base 1100 to integer. Ḍ Interpret the resulting list as a base 10 number. D Convert the final sum to base 10. ṣ2 Split at occurrences of 2. Ṫ Select the last chunk. Ḍ Convert from base 10 to integer. ``` --- 1 Note that the digits of this sum cannot exceed **3** (initial value **1** plus two **1**'s from carries). 2 This works because the last digit that will cancel out cannot be a **3**. [Answer] ## [Retina](https://github.com/mbuettner/retina), 100 bytes ``` r+`(.*)(\d|(?!\4))( .*)(.?) $2$4:$1$3 T` 0 +`1:11(1*:1*)11 :$1 ^:* ::: }`:(1*:1*:)11 1:1$1 (1)*: $#1 ``` This takes the input separated with a comma. The output always starts with three leading zeroes. [Try it online!](http://retina.tryitonline.net/#code=citgKC4qKShcZHwoPyFcNCkpKCAuKikoLj8pCiQyJDQ6JDEkMwpUYCAwCitgMToxMSgxKjoxKikxMQo6JDEKXjoqCjo6Ogp9YDooMSo6MSo6KTExCjE6MSQxCigxKSo6CiQjMQ&input=MTAwMTAwMDEwMTAxMDAxMTAxMDEwMTEwMTAxMDEwIDEwMDAxMDAxMTEwMTAwMTAxMTExMTExMDEwMTAwMA) I really wonder if there's a shorter solution for the first stage... [Answer] ## Python 3, 289 bytes This performs digitwise addition from least to most significant digit (in other words, the exact same algorithm you were taught in primary school). The differences are that (a) it's in binary, not decimal, so you carry whenever a digit is 2 or more, and (b) `1 + 1 = 1100`, not `10`. Actually, it's also necessary to note that `11 + 111 = 0`, or else sums that should become zero will never terminate. ``` from collections import* def a(*s,p=0): r=defaultdict(int,{0:0}) for S in s: n=0 for d in S[::-1]:r[n]+=d=='1';n+=1 while p<=max(r): while r[p]>1: r[p]-=2 if r[p+1]>1<=r[p+2]:r[p+1]-=2;r[p+2]-=1 else:r[p+2]+=1;r[p+3]+=1 p+=1 return str([*map(r.get,sorted(r))])[-2::-3] ``` More golfing is surely possible. [Answer] ## JavaScript (ES6), ~~146~~ 126 bytes ``` r=n=>n&&n%2-r(n>>=1)-i(n) i=n=>n&&r(n>>=1)-i(n) g=(x,y,b=(x^y)&1)=>x|y&&b+2*g(b-x+y>>1,b-x-y>>1) (x,y)=>g(r(x)+r(y),i(x)+i(y)) ``` `g` converts a Gaussian integer (real and imaginary parts) into base `i-1`, while `r` and `i` converts a base `i-1` integer into a Gaussian integer (real and imaginary parts respectively). Once the conversions are in place, I just have to do the arithmetic. Edit: Saved 20 bytes by calculating the real and imaginary parts separately. [Answer] C++ 416 bytes, plus `#include <vector>\n#include <algorithm>\n` (another 40) ``` using I=int;using v=std::vector<I>;void r(v&x){v r{rbegin(x),rend(x)};x=r;}v a(v L,v R){r(L);r(R);L.resize(std::max(L.size(),R.size()));for(int&r:R)L[&r-R.data()]+=r;while(1){L.resize(L.size()+3);auto it=find(rbegin(L),rend(L),2);if(it==rend(L))break;I i=-1+it.base()-begin(L);i&&L[i+1]&&L[i-1]/2?L[i+1]=L[i]=L[i-1]=0:(++L[i+2],++L[i+3],L[i]=0);}L.erase( std::find(rbegin(L),rend(L),1).base(),end(L));r(L);return L;} ``` or, with more whitespace: ``` using I=int; using v=std::vector<I>; void r(v&x){v r{rbegin(x),rend(x)};x=r;} v a(v L,v R) { r(L);r(R); L.resize(std::max(L.size(),R.size())); for(int&r:R) L[&r-R.data()]+=r; while(1) { L.resize(L.size()+3); auto it=find(rbegin(L), rend(L), 2); if(it==rend(L)) break; I i=-1+it.base()-begin(L); i&&L[i+1]&&L[i-1]/2? L[i+1]=L[i]=L[i-1]=0 : (++L[i+2],++L[i+3],L[i]=0); } L.erase( std::find(rbegin(L),rend(L),1).base(), end(L)); r(L); return L; } ``` Barely golfed. It takes input as a vector of ints, and returns a vector of ints. [Live example](http://coliru.stacked-crooked.com/a/f18051950b814357). [Answer] # Retina, ~~157~~ ~~151~~ ~~134~~ ~~133~~ ~~124~~ 123 bytes *1 byte off thanks to Martin Büttner.* ``` (.+),(.+) $.1$*0$2,$.2$*0$1, 1 0x +`(0x*)(,.*)0(x*), $2,$1$3 {`, (^|0x0xx0xx) 000 (0x*)(0x*)(0x*0)xx $1x$2x$3 )`^0+ 0 0x 1 ``` [Try it online!](http://retina.tryitonline.net/#code=KC4rKSwoLispCiQuMSQqMCQyLCQuMiQqMCQxLAoxCjB4CitgKDB4KikoLC4qKTAoeCopLAokMiwkMSQzCntgLAoKKF58MHgweHgweHgpCjAwMAooMHgqKSgweCopKDB4KjApeHgKJDF4JDJ4JDMKKWBeMCsKMAoweAox&input=MTAwMTAwMDEwMTAxMDAxMTAxMDEwMTEwMTAxMDEwLDEwMDAxMDAxMTEwMTAwMTAxMTExMTExMDEwMTAwMA) Converts to unary, and then repeat the following replacements (shown here in decimal): ``` 122 -> 000 0002 -> 1100 (this can also be 0012 -> 1110 and 1112 -> 2210 or even 2222 -> 3320 or even 3333 -> 4431) ``` Basically, when larger than two: take away two, add nothing in the previous digit, add one to the previous digit, then add one to the previous digit. In pseudocode: ``` if(a[n]>2): a[n] -= 2; a[n-2] += 1; a[n-3] += 1; ``` ### Unary implementation: Each digit (e.g. `3`) is shown as the number of `x`s (e.g. `xxx`) and then prefixed with `0`. For example, `1234` would be expressed as `0x0xx0xxx0xxxx`. This leaves `0` unchanged, as `101` would be expressed by `0x00x`. Since initially and finally, there is only `0` and `1`, the conversion could be easily done by `1->0x` and `0x->1`. [Click here to see every step](http://retina.tryitonline.net/#code=OmAoLispLCguKykKJC4xJCowJDIsJC4yJCowJDEsCjpgMQoweAorOmAoMHgqKSgsLiopMCh4KiksCiQyLCQxJDMKKyg6YCwKCjpgKF58MHgweHgweHgpCjAwMAo6YCgweCopKDB4KikoMHgqMCl4eAokMXgkMngkMwo6KWBeMCsKMAo6YDB4CjE&input=MTAwMTAwMDEwMTAxMDAxMTAxMDEwMTEwMTAxMDEwLDEwMDAxMDAxMTEwMTAwMTAxMTExMTExMDEwMTAwMA). ]
[Question] [ Write a program (or function) that exhibits four common [big O](https://en.wikipedia.org/wiki/Big_O_notation) [time complexities](https://en.wikipedia.org/wiki/Time_complexity) depending on how it is run. In any form it takes in a positive integer N which you may assume is less than 231. 1. When the program is run in its **original** form it should have **[constant](https://en.wikipedia.org/wiki/Time_complexity#Constant_time)** complexity. That is, the complexity should be **Θ(1)** or, equivalently, **Θ(1^N)**. 2. When the program is **reversed** and run it should have **[linear](https://en.wikipedia.org/wiki/Time_complexity#Linear_time)** complexity. That is, the complexity should be **Θ(N)** or, equivalently, **Θ(N^1)**. (This makes sense since `N^1` is `1^N` reversed.) 3. When the program is **doubled**, i.e. concatenated to itself, and run it should have **[exponential](https://en.wikipedia.org/wiki/Time_complexity#Exponential_time)** complexity, specifically **2N**. That is, the complexity should be **Θ(2^N)**. (This makes sense since the `2` in `2^N` is double the `1` in `1^N`.) 4. When the program is **doubled *and* reversed** and run it should have **[polynomial](https://en.wikipedia.org/wiki/Time_complexity#Polynomial_time)** complexity, specifically **N2**. That is, the complexity should be **Θ(N^2)**. (This makes sense since `N^2` is `2^N` reversed.) These four cases are the only ones you need to handle. Note that for preciseness I'm using [big theta (Θ) notation](https://stackoverflow.com/q/10376740/3823976) instead of [big O](https://en.wikipedia.org/wiki/Big_O_notation) because the runtimes of your programs must be bounded both above and below by the required complexities. Otherwise just writing a function in O(1) would satisfy all four points. It is not too important to understand the nuance here. Mainly, if your program is doing k\*f(N) operations for some constant k then it is likely in Θ(f(N)). > > # Example > > > If the original program were > > > > ``` > ABCDE > > ``` > > then running it should take constant time. That is, whether the input > N is 1 or 2147483647 (231-1) or any value in between, it should terminate in > roughly the same amount of time. > > > The reversed version of the program > > > > ``` > EDCBA > > ``` > > should take linear time in terms of N. That is, the time it takes to > terminate should be roughly proportional to N. So N = 1 takes the > least time and N = 2147483647 takes the most. > > > The doubled version of the program > > > > ``` > ABCDEABCDE > > ``` > > should take two-to-the-N time in terms of N. That is, the time it > takes to terminate should be roughly proportional to 2N. So > if N = 1 terminates in about a second, N = 60 would take longer than > the age of the universe to terminate. (No, you don't have to test it.) > > > The doubled and reversed version of the program > > > > ``` > EDCBAEDCBA > > ``` > > should take squared time in terms of N. That is, the time it takes to > terminate should be roughly proportional to N\*N. So if N = 1 > terminates in about a second, N = 60 would take about an hour to terminate. > > > # Details * **You need to show or argue that your programs are running in the complexities you say they are.** Giving some timing data is a good idea but also try to explain why theoretically the complexity is correct. * It's fine if in practice the times your programs take are not perfectly representative of their complexity (or even deterministic). e.g. input N+1 might sometimes run faster than N. * The environment you're running your programs in *does* matter. You can make basic assumptions about how popular languages never intentionally waste time in algorithms but, for example, if you know your particular version of Java implements [bubble sort](https://en.wikipedia.org/wiki/Bubble_sort) instead of a faster [sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm), then you should take that into account if you do any sorting. * For all complexities here assume we are talking about [worst-case scenarios](https://en.wikipedia.org/wiki/Best,_worst_and_average_case), not best-case or average-case. * The space complexity of the programs does not matter, only the time complexity. * The programs may output anything. It only matters that they take in positive integer N and have the correct time complexities. * Comments and multiline programs are allowed. (You may assume `\r\n` reversed is `\r\n` for Windows compatibility.) # Big O Reminders From fastest to slowest it's `O(1), O(N), O(N^2), O(2^N)` (order 1, 2, 4, 3 above). Slower terms always dominate, e.g. `O(2^N + N^2 + N) = O(2^N)`. `O(k*f(N)) = O(f(N))` for constant k. So `O(2) = O(30) = O(1)` and `O(2*N) = O(0.1*N) = O(N)`. Remember `O(N^2) != O(N^3)` and `O(2^N) != O(3^N)`. [Neat big O cheat sheet.](http://bigocheatsheet.com) # Scoring This is normal code golf. The shortest original program (the constant time one) in bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), 102 bytes ``` try:l=eval(input());k=1#)]0[*k**l(tnirp except:k=2#2=k:tpecxe print(k**l*[0])#1=k;))(tupni(lave=l:yrt ``` [Try it online!](https://tio.run/nexus/python3#FcoxCoAwDADAvd/oknRSwaWSl4iDlAwloYQSRV9f8eYb3t@sxPepUJtdDoib0BzxmPYkKSl4q90CP4XNs9ASF5LsxuXhYL02h7@lfTowziQbIvhlrYKeN5Pmt3sYY/0A) This is of O(1^n), since this is what the program does: * evaluate the input * create the array [0] * print it --- Reversed: ``` try:l=eval(input());k=1#)]0[*l**k(tnirp except:k=2#2=k:tpecxe print(l**k*[0])#1=k;))(tupni(lave=l:yrt ``` [Try it online!](https://tio.run/nexus/python3#FcoxCoAwDADAvd/oknRSwaWSl4iDlAwloYQSRV9f8eYbwfublfg@FWqzywFxE5ojHtOeNCUBb7Vb4KeweRZa4kKS3bg8HKzX5vC3tE8HxplkQwS/rFXQ82bS/HYfY/0A) This is of O(n^1), since this is what the program does: * evaluate the input * create the array [0]\*input (0 repeated as many times as the input) * print it --- Doubled: ``` try:l=eval(input());k=1#)]0[*k**l(tnirp except:k=2#2=k:tpecxe print(k**l*[0])#1=k;))(tupni(lave=l:yrt try:l=eval(input());k=1#)]0[*k**l(tnirp except:k=2#2=k:tpecxe print(k**l*[0])#1=k;))(tupni(lave=l:yrt ``` [Try it online!](https://tio.run/nexus/python3#vc0xCoAwDADAvd/oknRSwaWSl4iDSIaSUEKJoq@v@An3g@venqzE165Qqp0OiIvQGHEb1iQpKXgtzQLfB5tnoSlOJNmNj5uDtVIdPpbWYcM4kiyI4KfVArpfTJqf5uGfpff5BQ) This is of O(2^n), since this is what the program does: * evaluate the input * create the array [0] * print it * try to evaluate the input * fail * create the array [0]\*(2^input) (0 repeated as many times as 2^input) * print it --- Doubled and reversed: ``` try:l=eval(input());k=1#)]0[*l**k(tnirp except:k=2#2=k:tpecxe print(l**k*[0])#1=k;))(tupni(lave=l:yrt try:l=eval(input());k=1#)]0[*l**k(tnirp except:k=2#2=k:tpecxe print(l**k*[0])#1=k;))(tupni(lave=l:yrt ``` [Try it online!](https://tio.run/nexus/python3#vc0xCoAwDADAvd/oknRSwaWSl4iDSIaSUEKJoq@v@An3g@vB25OV@NoVSrXTAXERGiNuw5o0JQGvpVng@2DzLDTFiSS78XFzsFaqw8fSOmwYR5IFEfy0WkD3i0nz0/yfpff5BQ) This is of O(n^2), since this is what the program does: * evaluate the input * create the array [0]\*input (0 repeated as many times as the input) * print it * try to evaluate the input * fail * create the array [0]\*(input^2) (0 repeated as many times as the input squared) * print it [Answer] # Perl 5, ~~82~~ ~~73~~ 71+1 (for -n flag) = 72 bytes I'm certain I can golf this (a lot) more, but it's bedtime, I've spent enough time debugging as is, and I'm proud of what I have so far anyway. ``` #x$=_$; $x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;; eval $x;$x=~s/#//; ``` The program itself doesn't use the input, and just evaluates a string beginning with a comment and then does a single string substitution, so this is clearly in constant time. It's basically equivalent to: ``` $x="#"; eval $x; $x=~s/#//; ``` Doubled: ``` #x$=_$; $x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;; eval $x;$x=~s/#//; #x$=_$; $x.=q;#say for(1..2**$_)#)_$..1(rof _$=+x$;; eval $x;$x=~s/#//; ``` The bit that actually takes exponential time is the second eval: it evaluates the command `say for(1..2**$_)`, which lists all the numbers from 1 to 2^N, which clearly takes exponential time. Reversed: ``` ;//#/s~=x$;x$ lave ;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$ ;$_=$x# ``` This (naively) computes the summation of the input, which clearly takes linear time (since each addition is in constant time). The code that actually gets run is equivalent to: ``` $x+=$_ for(1..$_); $_=$x; ``` The last line is just so that when these commands are repeated it will take quadratic time. Reversed and doubled: ``` ;//#/s~=x$;x$ lave ;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$ ;$_=$x# ;//#/s~=x$;x$ lave ;;$x+=$_ for(1..$_)#)_$**2..1(rof yas#;q=.x$ ;$_=$x# ``` This now takes the summation of the summation of the input (and adds it to the summation of the input, but whatever). Since it does order `N^2` additions, this takes quadratic time. It's basically equivalent to: ``` $x=0; $x+=$_ for(1..$_); $_=$x; $x+=$_ for(1..$_); $_=$x; ``` The second line finds the summation of the input, doing `N` additions, while the fourth does `summation(N)` additions, which is `O(N^2)`. [Answer] # [Actually](https://github.com/Mego/Seriously), 20 bytes ``` ";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;" ``` [Try it online!](https://tio.run/nexus/actually#@69krWH4aOq0R1PnPGrcX6R0bJJSEZDhAOJPnWaoYa30/78pAA) Input: `5` Output: ``` rⁿ@╜╖1(; [0] 5 ``` --- Reversed: ``` ";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;" ``` [Try it online!](https://tio.run/nexus/actually#@69krWH4aOq0R1PnODxq3F@kdGySUhGQAeQDRQ01rJX@/zcFAA) Output: ``` rⁿ╜╖1(; [0, 1, 2, 3, 4] 5 ``` --- Doubled: ``` ";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;"";(1╖╜ⁿr"ƒ"rⁿ@╜╖1(;" ``` [Try it online!](https://tio.run/nexus/actually#@69krWH4aOq0R1PnPGrcX6R0bJJSEZDhAOJPnWaoYa1EUMH//6YA) Output: ``` rⁿ@╜╖1(; [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] rⁿ@╜╖1(; rⁿ@╜╖1(; [0] ``` --- Doubled and reversed: ``` ";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;"";(1╖╜@ⁿr"ƒ"rⁿ╜╖1(;" ``` [Try it online!](https://tio.run/nexus/actually#@69krWH4aOq0R1PnODxq3F@kdGySUhGQAeQDRQ01rJUIKvj/3xQA) Output: ``` rⁿ╜╖1(; [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] rⁿ╜╖1(; rⁿ╜╖1(; [0, 1, 2, 3, 4] ``` --- ## Main idea Actually is a stack-based language. * `abc` is a program which has O(1n) complexity, and its double has O(2n) complexity. * `def` is a program which has O(n1) complexity, and its double has O(n2) complexity. Then, my submission is `"abc"ƒ"fed"`, where `ƒ` is evaluate. That way, `"fed"` will not be evaluated. ### Generation of individual program The pseudocode of the first component `;(1╖╜ⁿr`: ``` register += 1 # register is default 0 print(range(register**input)) ``` The pseudocode of the second component `;(1╖╜ⁿ@r`: ``` register += 1 # register is default 0 print(range(input**register)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes Partly inspired by [Leaky Nun's Actually solution](https://codegolf.stackexchange.com/a/118782/53880). The leading and trailing newlines are significant. ### Normal: ``` ⁵Ŀ⁵ R R² 2*R ‘ ⁵Ŀ⁵ ``` [Try it online!](https://tio.run/nexus/jelly#@8/1qHHrkf1AgstIK4jrUcMMriCuoEObEML///83BQA) Input: `5` Output: ``` 610 ``` --- ### Reversed: ``` ⁵Ŀ⁵ ‘ R*2 ²R R ⁵Ŀ⁵ ``` [Try it online!](https://tio.run/nexus/jelly#@8/1qHHrkf1AguvQpiCuIK5HDTO4grSMEML///83BQA) Input: `5` Output: ``` [1, 2, 3, 4, 5]10 ``` --- ### Doubled ``` ⁵Ŀ⁵ R R² 2*R ‘ ⁵Ŀ⁵ ⁵Ŀ⁵ R R² 2*R ‘ ⁵Ŀ⁵ ``` [Try it online!](https://tio.run/nexus/jelly#@8/1qHHrkf1AgstIK4jrUcMMriCuoEObEMIEFfz//98UAA) Input: `5` Output: ``` [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]10 ``` --- ### Doubled and Reversed ``` ⁵Ŀ⁵ ‘ R*2 ²R R ⁵Ŀ⁵ ⁵Ŀ⁵ ‘ R*2 ²R R ⁵Ŀ⁵ ``` [Try it online!](https://tio.run/nexus/jelly#@8/1qHHrkf1AguvQpiCuIK5HDTO4grSMEMIEFfz//98UAA) Input: `5` Output: ``` [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]10 ``` --- ### Explanation The key here is in `Ŀ`, which means "calls the link at index n as a monad." The links are indexed top to bottom starting at 1, excluding the main link (the bottom-most one). `Ŀ` is modular as well, so if you try to call link number 7 out of 5 links, you'll actually call link 2. The link being called in this program is always the one at index 10 (`⁵`) no matter what version of the program it is. However, which link is at index 10 depends on the version. The `⁵` that appears after each `Ŀ` is there so it doesn't break when reversed. The program will error out at parse-time if there is no number before `Ŀ`. Having a `⁵` after it is an out of place nilad, which just goes straight to the output. **The original version** calls the link `‘`, which computes n+1. **The reversed version** calls the link `R`, which generates the range 1 .. n. **The doubled version** calls the link `2*R`, which computes 2n and generates the range 1 .. 2n. **The doubled and reversed version** calls the link `²R`, which computes n2 and generates the range 1 .. n2. [Answer] # [Befunge-98](http://quadium.net/funge/spec98.html), 50 bytes ## Normal ``` \+]#:\-1vk !:;# @k!:-1 .: ;#]#$ <; [*:>@ &$< ^&; ``` This is by far the simplest program of the 4 - the only commands that are executed are the following: ``` \+] ! : @ &$< ^&; ``` This program does some irrevelant stuff before hitting a "turn right" command (`]`) and an arrow. Then it hits **2** "take input" commands. Because there is only 1 number in input and because of how TIO treats `&`s, the program exits after 60 seconds. If there are 2 inputs (and because I can without adding bytes), the IP would travel up into the "end program" function. [Try it online!](https://tio.run/nexus/befunge-98#@x@jHatsFaNrWJatoKBoZa3M5ZCtaKVrqKBnpWCtHKusomBjzRWtZWXnoMClpmKjEKdm/f@/MQA "Befunge-98 – TIO Nexus") ## Reversed ``` ;&^ <$& @>:*[ ;< $#]#; :. 1-:!k@ #;:! kv1-\:#]+\ ``` This one is a little more complicated. the relevant commands are as follows: ``` ;&^ $ >:*[ ;< $#]#; :. 1-:!k@ : ``` which is equivalent to ``` ;&^ Takes input and sends the IP up. the ; is a no-op : Duplicates the input. >:*[ Duplicates and multiplies, so that the stack is [N, N^2 $ Drops the top of the stack, so that the top is N ]#; Turns right, into the loop :. Prints, because we have space and it's nice to do 1- Subtracts 1 from N :!k@ If (N=0), end the program. This is repeated until N=0 ;< $#]#; This bit is skipped on a loop because of the ;s, which comment out things ``` The important part here is the `:. 1-:!k@` bit. It's useful because as long as we push the correct complexity onto the stack before executing in a lower time complexity, we can get the desired one. This will be used in the remaining 2 programs in this way. [Try it online!](https://tio.run/nexus/befunge-98#@2@tFqdgo6LGpeBgZ6UVzWVto6CiHKtsrWClp2Coa6WY7cClbG2lqKCQXWaoG2OlHKsd8/@/OQA "Befunge-98 – TIO Nexus") ## Doubled ``` \+]#:\-1vk !:;# @k!:-1 .: ;#]#$ <; [*:>@ &$< ^&;\+]#:\-1vk !:;# @k!:-1 .: ;#]#$ <; [*:>@ &$< ^&; ``` And the relevant command are: ``` \+] ! : &$< ^&;\+]#:\-1vk !:;# @k!:-1 .: ;#]#$ <; ``` This program goes into 2 loops. First, it follows the same path as the normal program, which pushes 1 and N onto the stack, but instead of wrapping around to the second `&`, the IP jumps over a comment into a loop that pushes `2^N`: ``` vk!: If N is 0, go to the next loop. -1 Subtract 1 from N + :\ Pulls the 1 up to the top of the stack and doubles it ]# A no-op \ Pulls N-1 to the top again ``` The other bits on line 4 are skipped using `;`s After (2^N) is pushed onto the stack, we move down a line into the aforementioned printing loop. Because of the first loop, the time complexity is Θ(N + 2^N), but that reduces to Θ(2^N). [Try it online!](https://tio.run/nexus/befunge-98#@x@jHatsFaNrWJatoKBoZa3M5ZCtaKVrqKBnpWCtHKusomBjzRWtZWXnoMClpmKjEKdmTbqO//@NAQ "Befunge-98 – TIO Nexus") ## Doubled and Reversed ``` ;&^ <$& @>:*[ ;< $#]#; :. 1-:!k@ #;:! kv1-\:#]+\;&^ <$& @>:*[ ;< $#]#; :. 1-:!k@ #;:! kv1-\:#]+\ ``` The relevant commands: ``` ;&^ ;< $#]#; :. 1-:!k@ @>:*[ : ``` This functions almost identically to the reversed program, but the `N^2` is not popped off of the stack, because the first line of the second copy of the program is appended to the last line of the first, meaning that the drop command (`$`) never gets executed, so we go into the printing loop with `N^2` on the top of the stack. [Try it online!](https://tio.run/nexus/befunge-98#@2@tFqdgo6LGpeBgZ6UVzWVto6CiHKtsrWClp2Coa6WY7cClbG2lqKCQXWaoG2OlHKsdQ7qO//9NAQ "Befunge-98 – TIO Nexus") [Answer] # [JavaScript (Node.js)](https://nodejs.org), 90 bytes ``` f=n=>n&&f(--n)+f(n);f(t);var t=process.argv[1]//;);--i;]1[vgra.ssecorp:t*t?t=i=t rav(rof" ``` [Try it online!](https://tio.run/##BcExDsIwDADAnVdUDFUCcqsOLESBh1QdrJBUYbAjx8rzMXdfHNiT1KZA/MlmJVJ80TwXB0D@Xhz5UJz6MFAmjU045d4XlHPs27GuwQeAGo5tH6fg0ntOLO2pN31rrFEnweGEy/Vi9uOmlakb2OMP "JavaScript (Node.js) – Try It Online") Trivial ]
[Question] [ **Input:** Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list. **Output:** Their sum. Use the same format for output integers as input integers. For example, the input `5 16` would lead to the output `21`. **Restrictions:** No standard loopholes please. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), answer in lowest amount of bytes wins. **Notes:** This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is. **Test cases:** ``` 1 2 -> 3 14 15 -> 29 7 9 -> 16 -1 8 -> 7 8 -9 -> -1 -8 -9 -> -17 ``` Or as CSV: ``` a,b,c 1,2,3 14,15,29 7,9,16 -1,8,7 8,-9,-1 -8,-9,-17 ``` # Leaderboard ``` var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Minecraft 1.10, 221 characters (non-competing) See, this is what we have to deal with when we make Minecraft maps. Aside: There's no way to take a string input in Minecraft, so I'm cheating a bit by making you input the numbers into the program itself. (It's somewhat justifiable because quite a few maps, like Lorgon111's Minecraft Bingo, require you to copy and paste commands into chat in order to input a number.) Thank you abrightmoore for the [Block Labels](http://www.brightmoore.net/mcedit-filters-1/blocklabels) MCEdit filter. [![a](https://i.stack.imgur.com/ucoxq.png)](https://i.stack.imgur.com/ucoxq.png) ``` scoreboard objectives add a dummy scoreboard players set m a 6 scoreboard players set n a 8 scoreboard players operation r a += m a scoreboard players operation r a += n a tellraw @a {"score":{"name":"r","objective":"a"}} ``` Non-competing due to difficulties in input, and I have no idea how to count bytes in this thing (the blytes system is flawed for command blocks). [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 1 byte ``` + ``` [Try it online!](http://jelly.tryitonline.net/#code=Kw&input=&args=NQ+MTY) Also works in 05AB1E, Actually, APL, BQN, Brachylog, Braingolf, Chocolate, ,,, (Commata), dc, Deorst, Factor, Fig\*\*, Forth, Halfwit\*, HBL\*, Implicit, J, Julia, K, kdb+, Keg, Ly, MathGolf, MATL, Pyke, Q, Racket, Scheme, Swift, Thunno\*\*, Thunno 2, and Vyxal. \* Language uses a half-byte code page, and therefore `+` counts as 0.5 bytes. \*\* In Fig and Thunno, this is \$\log\_{256}(96)\approx\$ 0.823 bytes. [Answer] # [Binary lambda calculus](https://en.wikipedia.org/wiki/Binary_lambda_calculus), 4.125 bytes Input and output as [Church numerals](https://en.wikipedia.org/wiki/Church_encoding). ``` 00000000 01011111 01100101 11101101 0 ``` In [lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus), it is λ*m*. λ*n*. λ*f*. λ*x*. *m* *f* (*n* *f* *x*). [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index): λ λ λ λ 4 2 (3 2 1) --- [Lambda calculus](https://en.wikipedia.org/wiki/Lambda_calculus) is a concise way of describing a mapping (function). For example, this task can be written as λ*x*. λ*y*. *x* + *y* The thing to note is, that this is not a lambda (function) which takes two arguments. This is actually a nested lambda. However, it behaves like a lambda which takes two arguments, so it can be informally described as such. Every lambda formally only takes one argument. For example, if we apply this lambda to 3 and 4: > > (λ*x*. λ*y*. *x* + *y*) 3 4 ≡ (λ*y*. 3 + *y*) 4 ≡ 3 + 4 = 7 > > > So, the first lambda actually returns another lambda. --- [Church numerals](https://en.wikipedia.org/wiki/Church_encoding) is a way of doing away with the extra signs, leaving with only lambda symbols and variables. Each number in the Church system is actually a lambda that specifies how many times the function is applied to an item. Let the function be *f* and the item be *x*. So, the number 1 would correspond to λ*f*. λ*x*. *f* *x*, which means apply *f* to *x* exactly once. The number 3, for example, would be λ*f*. λ*x*. *f* (*f* (*f* *x*)), which means apply *f* to *x* exactly three times. --- Therefore, to add two [Church numerals](https://en.wikipedia.org/wiki/Church_encoding) (say, *m* and *n*) together, it is the same as applying *f* to *x*, *m* + *n* times. We can observe that this is the same as first applying *f* to *x*, *n* times, and then applying *f* to the resulting item *m* times. For example, *2* would mean `f(f(x))` and *3* would mean `f(f(f(x)))`, so *2* + *3* would be `f(f(f(f(f(x)))))`. To apply *f* to *x*, *n* times, we have *n* *f* *x*. You can view *m* and *n* as functions taking two arguments, informally. Then, we apply *f* again to this resulting item, *m* times: *m* *f* (*n* *f* *x*). Then, we add back the boilerplate to obtain λ*m*. λ*n*. λ*f*. λ*x*. *m* *f* (*n* *f* *x*). --- Now, we have to convert it to [De Bruijn index](https://en.wikipedia.org/wiki/De_Bruijn_index). Firstly, we count the "relative distance" between each variable to the lambda declaration. For example, the *m* would have a distance of 4, because it is declared 4 lambdas "ago". Similarly, the *n* would have a distance of 3, the *f* would have a distance of 2, and the *x* would have a distance of 1. So, we write it as this intermediate form: λ*m*. λ*n*. λ*f*. λ*x*. 4 2 (3 2 1) Then, we remove the variable declarations, leaving us with: λ λ λ λ 4 2 (3 2 1) --- Now, we convert it to [binary lambda calculus](https://en.wikipedia.org/wiki/Binary_lambda_calculus). The rules are: * λ becomes `00`. * *m* *n* (grouping) becomes `01 m n`. * numbers *i* becomes `1` *i* times + `0`, for example 4 becomes `11110`. λ λ λ λ 4 2 (3 2 1) ≡ λ λ λ λ `11110` `110` (`1110` `110` `10`) ≡ λ λ λ λ `11110` `110` `0101 111011010` ≡ λ λ λ λ `0101` `111101100101111011010` ≡ `00` `00` `00` `00` `0101` `111101100101 111011010` ≡ `000000000101111101100101111011010` [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 8 + 4 = 12 bytes ``` ]_:]_!<X ``` Run with the `-mn` flags. [Try it online!](http://stackcats.tryitonline.net/#code=XV86XV8hPFg&input=NTcgLTE4OA&args=LW1u) Golfing in Stack Cats is *highly* counterintuitive, so this program above was found with a few days of brute forcing. For comparison, a more intuitive, human-written solution using the `*(...)>` template is two bytes longer ``` *(>-_:[:)> ``` with the `-ln` flags instead (see the bottom of this post for an explanation). ### Explanation Here's a primer on Stack Cats: * Stack Cats is a reversible esoteric language where the mirror of a snippet undoes the effect of the original snippet. Programs must also be mirror images of itself — necessarily, this means that even-length programs are either no-ops or infinite loops, and all non-trivial terminating programs are of odd length (and are essentially a conjugation of the central operator). * Since half the program is always implied, one half can be left out with the `-m` or `-l` flag. Here the `-m` flag is used, so the half program above actually expands to `]_:]_!<X>!_[:_[`. * As its name suggests, Stack Cats is stack-based, with the stacks being bottomless with zeroes (i.e. operations on an otherwise empty stack return 0). Stack Cats actually uses a tape of stacks, e.g. `<` and `>` move one stack left and one stack right respectively. * Zeroes at the bottom of the stack are swallowed/removed. * All input is pushed to an initial input stack, with the first input at the top and an extra -1 below the last input. Output is done at the end, using the contents of the current stack (with an optional -1 at the bottom being ignored). `-n` denotes numeric I/O. And here's a trace of the expanded full program, `]_:]_!<X>!_[:_[`: ``` Initial state (* denotes current stack): ... [] [-1 b a]* [] [] ... ] Move one stack right, taking the top element with you ... [] [-1 b] [a]* [] ... _ Reversible subtraction, performing [x y] -> [x x-y] (uses an implicit zero here) ... [] [-1 b] [-a]* [] ... : Swap top two ... [] [-1 b] [-a 0]* [] ... ] Move one stack right, taking the top element with you ... [] [-1 b] [-a] []* ... _ Reversible subtraction (0-0, so no-op here) ! Bit flip top element, x -> -x-1 ... [] [-1 b] [-a] [-1]* ... < Move one stack left ... [] [-1 b] [-a]* [-1] ... X Swap the stack to the left and right ... [] [-1] [-a]* [-1 b] ... > Move one stack right ... [] [-1] [-a] [-1 b]* ... ! Bit flip ... [] [-1] [-a] [-1 -b-1]* ... _ Reversible subtraction ... [] [-1] [-a] [-1 b]* ... [ Move one stack left, taking the top element with you ... [] [-1] [-a b]* [-1] ... : Swap top two ... [] [-1] [b -a]* [-1] ... _ Reversible subtraction ... [] [-1] [b a+b]* [-1] ... [ Move one stack left, taking the top element with you ... [] [-1 a+b]* [b] [-1] ... ``` `a+b` is then outputted, with the base -1 ignored. Note that the trickiest part about this solution is that the output stack must have a `-1` at the bottom, otherwise an output stack of just `[-1]` would ignore the base -1, and an output stack of `[0]` would cause the base zero to be swallowed (but an output stack of `[2]`, for example, would output `2` just fine). --- Just for fun, here's the full list of related solutions of the same length found (list might not be complete): ``` ]_:]^!<X ]_:]_!<X ]_:]!^<X ]_:!]^<X [_:[^!>X [_:[_!>X [_:[!^>X [_:![^>X ``` The `*(>-_:[:)>` solution is longer, but is more intuitive to write since it uses the `*(...)>` template. This template expands to `<(...)*(...)>` when used with the `-l` flag, which means: ``` < Move one stack left (...) Loop - enter if the top is positive and exit when the top is next positive again Since the stack to the left is initially empty, this is a no-op (top is 0) * XOR with 1 - top of stack is now 1 (...) Another loop, this time actually run > Move one stack right ``` As such, the `*(...)>` template means that the first loop is skipped but the second is executed. This allows more straightforward programming to take place, since we don't need to worry about the effects of the loop in the other half of the program. In this case, the inside of the loop is: ``` > Move one stack right, to the input stack - Negate top, [-1 b a] -> [-1 b -a] _ Reversible subtraction, [-1 b -a] -> [-1 b a+b] : Swap top two, [-1 b a+b] -> [-1 a+b b] [ Move one stack left, taking top of stack with you (removing the top b) : Swap top two, putting the 1 on this stack on top again ``` The final `>` in the template then moves us back to the input stack, where `a+b` is outputted. [Answer] ## Common Lisp, 15 bytes ``` (+(read)(read)) ``` [Answer] # [Dominoes](http://store.steampowered.com/app/286160/), 38,000 bytes or 37 tiles This is created in [*Tabletop Simulator*](http://store.steampowered.com/app/286160/). Here is a [video](https://www.youtube.com/watch?v=LYCAiD80oZU&feature=youtu.be) and here is the [file](http://steamcommunity.com/sharedfiles/filedetails/?id=883290024). It is a standard half-adder, composed of an `and` gate for the `2^1` place value and an `xor` gate for the `2^0` place value. [![enter image description here](https://i.stack.imgur.com/TUQerm.jpg)](https://www.youtube.com/watch?v=LYCAiD80oZU&feature=youtu.be) ## Details * **I/O** + **Start** - This is included for clarity (not counted towards total) and is what 'calls' or 'executes' the function. Should be 'pressed' after input is given **[Yellow]**. + **Input A** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed for `0` **[Green]**. + **Input B** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed for `0` **[Blue]**. + **Output** - This is counted towards total. These dominoes declare the sum. The left is `2^1` and the right is `2^0` **[Black]**. * **Pressing** + To give input or start the chain, spawn the metal marble + Set the lift strength to `100%` + Lift the marble above the desired domino + Drop the marble [Answer] # [Brain-flak](http://github.com/DJMcMayhem/Brain-Flak), 6 bytes ``` ({}{}) ``` [Try it online!](http://brain-flak.tryitonline.net/#code=KHt9e30p&input=MyA1) Brain-flak is a really interesting language with two major restrictions on it. 1. The only valid characters are brackets, i.e. any of these characters: ``` (){}[]<> ``` 2. Every single set of brackets must be entirely matched, otherwise the program is invalid. A set of brackets with nothing between them is called a "nilad". A nilad creates a certain numerical value, and all of these nilads next to each other are added up. A set of brackets with something between them is called a "monad". A monad is a function that takes an numerical argument. So the brackets inside a monad are evaluated, and that is the argument to the monad. Here is a more concrete example. The `()` *nilad* equals 1. So the following brain-flak code: ``` ()()() ``` Is evaluated to 3. The `()` *monad* pushes the value inside of it on the global stack. So the following ``` (()()()) ``` pushes a 3. The `{}` nilad pops the value on top of the stack. Since consecutive nilads are always added, a string of `{}` sums all of the top elements on the stack. So my code is essentially: ``` push(pop() + pop()) ``` [Answer] # Minecraft 1.10.x, ~~924~~ 512 bytes Thanks to @[quat](https://codegolf.stackexchange.com/users/34793/quat) for reducing the blytecount by 48 points and the bytecount by 412. Alright, so, I took some of the ideas from [this answer](https://codegolf.stackexchange.com/a/84342/44713) and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found [here](https://www.dropbox.com/s/6v20ca187bjdpw5/Input%20Ready.nbt?dl=1) in structure block format. [![group](https://i.stack.imgur.com/tUA1C.png)](https://i.stack.imgur.com/tUA1C.png) (new version looks kinda boring tbh) Similar commands as the other answer: ``` scoreboard objectives add a dummy execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1 execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1 scoreboard players operation n a += m a tellraw @a {"score":{"name":"n","objective":"a"}} ``` To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary. This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run. [Answer] ## [Retina](https://github.com/m-ender/retina), 42 bytes ``` \d+ $* T`1p`-_` |-1+ +`.\b. ^(-)?.* $1$.& ``` [Try it online!](http://retina.tryitonline.net/#code=XGQrCiQqClRgMXBgLV9gIHwtMSsKK2AuXGIuCgpeKC0pPy4qCiQxJC4m&input=LTUgMTY) ### Explanation Adding numbers in unary is the easiest thing in the world, but once you introduce negative numbers, things get fiddly... ``` \d+ $* ``` We start by converting the numbers to unary. This is done by matching each number with `\d+` and replacing it with `$*`. This is a Retina-specific substitution feature. The full syntax is `count$*character` and inserts `count` copies of `character`. Both of those can be omitted where `count` defaults to `$&` (i.e. the match itself) and `character` defaults to `1`. So for each input `n` we get `n` ones, and we still have potential minus signs in there, as well as the space separator. E.g. input `8 -5` gives: ``` 11111111 -11111 ``` Now in order to deal with negative numbers it's easiest to use a separate `-1` digit. We'll use `-` for that purpose. ``` T`1p`-_` |-1+ ``` This stage does two things. It gets rid of the space, the leading minus signs, and turns the `1`s after a minus sign into `-` themselves. This is done by matching `|-1+` (i.e. either a space or a negative number) and performing a transliteration on it. The transliteration goes from `1p` to `-_`, but here, `p` expands to all printable ASCII characters and `_` means delete. So `1`s in those matches get turned into `-`s and minuses and spaces get removed. Our example now looks like this: ``` 11111111----- ``` ``` +`.\b. ``` This stage handles the case where there's one positive and one negative number in the input. If so, there will be `1`s and `-`s in the string and we want them to cancel. This is done by matching two characters with a word-boundary between them (since `1`s is considered a word character and `-` isn't), and replacing the match with nothing. The `+` instructs Retina to do this repeatedly until the string stops changing. Now we're left with *only* `1`s or *only* `-`s. ``` ^(-)?.* $1$.& ``` To convert this back to decimal, we match the entire input, but if possible we capture a `-` into group `1`. We write back group `1` (to prepend a `-` to negative numbers) and then we write back the length of the match with `$.&` (also a Retina-specific substitution feature). [Answer] # Geometry Dash - 15 objects Finally done. 15 objects aren't much, but it was still a nightmare to do this (especially because of the negative numbers). [![enter image description here](https://i.stack.imgur.com/ci97N.png)](https://i.stack.imgur.com/ci97N.png) Because I would have to insert 15 images here for how to reproduce this, I just uploaded the level. The level ID is 5216804. The description tells you how to run it and you can copy it since it is copyable. **Explanation:** The top-left trigger (Instant Count 2) checked if the first addend was 0. If it was, it then checked if the second addend was positive or negative. If it was positive, it transferred the value from the second addend to the sum (BF-style, using loops) and if it was negative, it would do the same thing. The reason why we need to check if the second addend is positive or negative is that we would need to subtract one from the second addend and add one to the sum or add one to the second addend and subtract one from the sum respectively. If the first addend is not zero, it tests whether it is positive or negative using the process above. After one iteration in the while loop, it tests to see if the first addend is zero and if it is, it does the process described at the beginning of the explanation. Since Geometry Dash is remarkably similar to BF, you could make a BF solution out of this. [Answer] # APOL, 6 bytes ``` +(i i) ``` I AM BOT FEED ME BUTTER [Answer] # Mathematica, ~~4~~ 2 bytes ``` Tr ``` *Crossed out ~~4~~ is still regular 4...* `Tr` applied to a one-dimensional list takes the sum of said list's elements. [Answer] # JavaScript (ES6), 9 bytes ``` a=>b=>a+b ``` [Answer] # Haskell, 3 bytes ``` (+) ``` The parentheses are here because it needs to be an prefix function. This is the same as taking a section of the + function, but no arguments are applied. It also works on a wide range of types, such as properly implemented Vectors, Matricies, Complex numbers, Floats, Doubles, Rationals, and of course Integers. Because this is Haskell, here is how to do it on the type-level. This will be done at compile time instead of run time: ``` -- This *type* represents Zero data Zero -- This *type* represents any other number by saying what number it is a successor to. -- For example: One is (Succ Zero) and Two is (Succ (Succ Zero)) data Succ a -- a + b = c, if you have a and b, you can find c, and if you have a and c you can find b (This gives subtraction automatically!) class Add a b c | a b -> c, a c -> b -- 0 + n = n instance Add Zero n n -- If (a + b = c) then ((a + 1) + b = (c + 1)) instance (Add a b c) => Add (Succ a) b (Succ c) ``` Code adapted from [Haskell Wiki](https://wiki.haskell.org/Type_arithmetic) [Answer] # [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare), ~~155~~ 152 bytes ``` . Ajax,. Ford,. Act I:. Scene I:. [Enter Ajax and Ford] Ajax: Listen to thy heart Ford: Listen to THY heart!You is sum you and I.Open thy heart [Exeunt] ``` Ungolfed: ``` Summing Two Numbers in Verona. Romeo, a numerical man. Juliet, his lover and numerical counterpart. Act I: In which Italian addition is performed. Scene I: In which our two young lovers have a short chat. [Enter Romeo and Juliet] Romeo: Listen to thy heart. Juliet: Listen to THY heart! Thou art the sum of thyself and I. Open thy heart. [Exeunt] ``` I'm using [drsam94's SPL compiler](https://github.com/drsam94/Spl) to compile this. To test: ``` $ python splc.py sum.spl > sum.c $ gcc sum.c -o sum.exe $ echo -e "5\n16" | ./sum 21 ``` [Answer] # dc, 2 bytes ``` +f ``` Adds top two items on stack (previously taken from `stdin`), then dumps the stack's contents to `stdout`. **EDIT:** Upon further consideration, it seems there are several ways this might be implemented, depending on the desired I/O behaviour. ``` + # adds top two items and pushes on stack +n # adds top two and prints it, no newline, popping it from stack +dn # ditto, except leaves result on stack ??+ # takes two inputs from stdin before adding, leaving sum on stack ``` I suppose the most complete form for the sum would be this: ``` ??+p # takes two inputs, adds, 'peeks' # (prints top value with newline and leaves result on stack) ``` Wait! Two numbers can be taken on the same line, separated by a space! This gives us: ``` ?+p ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes ``` +. ``` Expects a list with the two numbers as input Alternatively, if you want the answer to `STDOUT`: ``` +w ``` [Answer] # Python, ~~11~~ 3 bytes ``` sum ``` --- ~~`int.__add__`~~ A simple special operator. [Answer] # [Plumber](https://github.com/Radvylf/plumber), ~~244~~ 176 bytes ``` [] [] [] ][=][] []=][][=][ []=]===]] ][]][=[=]] =]] []][ ][===[=[] ]][]=][[[=]=]][][ []]=]=]=]=[] ][]=[]][ []]=][=][] = =]=]][[=[== ][=]=]=]=]===][= ``` ## Old Design (244 bytes) ``` [] [] [][=[] [[=[][] [][] ][]][= ][[] ][[=]]]][]=[[] []===][] ][===][] ][][ [] ][ ] [][] [ ][]=][[[===][[ ][]]]=][[]=[=]=]=]]==]=]][ ][=]=]]==]=][] ][ [][=][=[[][[=]][ ==]=]][[=[= = ``` I thought I had a good solution for a while...except it didn't work with `0` or `1` as the first input. This program consists of three parts: incrementer, decrementer, and outputter. The decrementer is on the left, and holds the first value. It is incremented, since a `0` would cause an infinite loop (as the program tries to decrement to `0` and gets a negative value). It will decrement the stored value at execution, and send a packet to the incrementer. The incrementer is on the right, and stores the second input. When the decrementer sends a packet, it increments its stored value, and sends a packet back to the decrementer. Whenever the decrementer sends the packet to the incrementer, it is checked by the outputter. If the packet is `0`, execution stops and the value of the incrementer is read and outputted. It uses a NOT gate, one of the most complicated parts of the program. ## Older design (doesn't work with some inputs), 233 bytes ``` [] [] [][] [][] =][] []=][]=][[=]][ [][===][ [][===[] [][] [ [] ][][ ] [===][=]][ ] ][[=[=[=[=[=]=[]][=[[[][ ][[=[=[=[==[[=[=][ []]=][=][] = =]=]][[=[== ``` The new one is flipped to save bytes, and it's really confusing me. This design is the one I worked with for a week or so when designing the interpreter. [Answer] # Cheddar, 3 bytes ``` (+) ``` This is a cool feature of Cheddar called "functionized operators". Credit for this idea goes to @CᴏɴᴏʀO'Bʀɪᴇɴ. Here are more examples of functionized operators: ``` (+)(1,2) // 3 (/)(6,2) // 3 (-)(5) // -5 ``` [Answer] # MATL, 1 byte ``` s ``` Accepts an array of two integers as input and sums them. While the simple program of `+` also works, that has already been shown for other languages. [**Try it Online**](http://matl.tryitonline.net/#code=cw&input=WzIgNF0) [Answer] # PHP, 20 bytes Surprisingly short this time: ``` <?=array_sum($argv); ``` Runs from command line, like: ``` $ php sum.php 1 2 ``` [Answer] # [Fuzzy Octo Guacamole](https://github.com/RikerW/Fuzzy-Octo-Guacamole), 1 byte ``` a ``` A function that takes inputs from the top of the stack and outputs by pushing to the stack. Example running in the REPL: ``` >>> 8 9 : [8,9] >>> a : 17 ``` [Answer] # C, 35 bytes ``` s(x,y){return y?s(x^y,(x&y)<<1):x;} ``` What I've done here is defined addition without the use of boolean or arithmetic operators. This recursively makes x the sum bits by 'xor', and y the carry bits by 'and' until there is no carry. Here's the ungolfed version: ``` int sum(int x,int y){ if(y==0){ //anything plus 0 is itself return x; } //if it makes you happier imagine there's an else here int sumBits=x^y; int carryBits=(x&y)<<1; return sum(sumBits,carryBits); } ``` [Answer] # x86\_32 machine code, 2 bytes ``` 08048540 <add7>: 8048540: 01 c8 add %ecx,%eax ``` Assuming the two values are already in the ecx and eax registers, performing the add instruction will add the values of the two registers and store the result in the destination register. You can see the full program written in C and inline assembly [here](https://gcc.godbolt.org/z/WdGbEP7x4). Writing the wrapper in C makes it easier to provide inputs and do testing, but the actual add function can be reduced down to these two bytes. [Answer] ## Perl 5.10, 8 bytes The two numbers to add must be on 2 separate lines for this one to work: ``` say<>+<> ``` [Try this one here.](https://ideone.com/PTznrK) One with input on the same line (**14 + 1 bytes for *-a* flag**) ``` say$F[0]+$F[1] ``` [Try it here!](https://ideone.com/6PZ9NR) One with input on the same line (**19 + 1 bytes for *-a* flag**) ``` map{$s+=$_}@F;say$s ``` [Try this one here.](https://ideone.com/ykfi5N) Another one, by changing the array default separator (**19 + 1 bytes for *-a* flag** as well) ``` $"="+";say eval"@F" ``` [Try this one here!](https://ideone.com/arDZIJ) [Answer] ## Batch, ~~25~~ ~~18~~ 16 bytes ``` @cmd/cset/a%1+%2 ``` Edit: saved ~~7~~ 9 bytes by using my trick from [Alternating Sign Sequence](https://codegolf.stackexchange.com/questions/80858/alternating-sign-sequence/80868#80868). [Answer] ## PowerShell v2+, 17 bytes ``` $args-join'+'|iex ``` Takes input as two separate command-line arguments, which get pre-populated into the special array `$args`. We form a string with the `-join` operator by concatenating them together with a `+` in the middle, then pipe that string to `Invoke-Expression` (similar to `eval`). --- Thanks to @DarthTwon for reminding me that when dealing with such minimal programs, there are multiple methods of taking input all at the same byte-count. ``` $args[0]+$args[1] param($a,$b)$a+$b ``` PowerShell is nothing if not flexible. [Answer] ## [><>](https://esolangs.org/wiki/fish), ~~7~~ ~~6~~ 3 bytes ``` +n; ``` [Online interpreter](https://fishlanguage.com/playground) Or try it on TIO with the -v flag. [Try it online](http://fish.tryitonline.net/#code=K247&input=&args=LXYgMTU+LXYgMjU) [Answer] # [Alchemist](https://esolangs.org/wiki/Alchemist), ~~253 211~~ 205 bytes ``` _->u+v+2r u+r->In_a+In_x v+r->In_b+In_y a+b->Out_"-" 0_+0r+0d+0a+0b->d 0d+0a+x+b+y->b 0r+0d+a+0b+0y->d+Out_"-" 0r+0d+0b+a+0x->d a+x+0b+y->a 0r+0d+0a+b+0x->d+Out_"-" 0r+0d+0a+b+0y->d d+x->d+y d+y->d+Out_"1" ``` Since Alchemist can't handle negative numbers (there can't be a negative amount of atoms) this takes 4 inputs on *stdin* in this order: * sign of `x` (0 -> `+` and 1 -> `-`) * the number `x` itself * sign of `y` (0 -> `+` and 1 -> `-`) * the number `y` itself Output is in unary, [try it online!](https://tio.run/##XYyxDgIhEET7/QzaCcl69vRWfgJhxUQTtcDjAl@PLJgzsdnMzsub8Ljcrs/7e23NW5exYUmUkaw7vXxAP4W27yv6VgoQ68559cYaYg9O4AgO4N5HmrlAUK0TmlQhuBcRuzk1UVZUVImHFWjflAn/rQF0jiIGrz385g@mNaaFmI4f "Alchemist – Try It Online") (for your convenience, [here](https://tio.run/##bVHBitswFLzrKwatKRuEKjulh1LWS9tD2UsL3eOmGNlWYoEjB0n2Jmz3213JDvG25CKe3mjmzeiV0jXjWEmPHLKutdedeV9ZQ8gNvnVmUNbD9PtSWfgO9PHh@4@N@fL1cWMo8V0h26pRe@18oc2h97hd4YUAsnR3NLlVVdMhyfAHTtVwgguxogH2ynlQijtcefSU8k@/hditKIAbJPfQDhn0FkbtpNeD@owUqnUqKE1kmtxvTBJmRlOv0fmv3uBiDc/aN/CNQtVZqyqPyavDu9CYE3a9j@63ttujN9KeYthaVXovW7IIndPN9Bjwyg8k2ep6fz1Fn9Qj9WC18dvgfVajIb/oDl5ceEv1z2KwzkWtBmH6tp0Und6ZIPgyKQuRvdJ5AUXw/2YQ50jmaG@2EernCrwKQoG0vKRhHyxYBs@RxAHJWfD8w4u18DBZj2PB854NbG1JzyzPH0whWTiOZDhfy3g9EclKnv/sfUE5JWnBUsvSmqWSpaFfk7k@spKdeF6SGY0gS0OjZhfmTCsjdozESEonliQXzXIG/2dNQJQjNZvwUygW@YyO/OP44S8 "Bash – Try It Online") is a wrapper, converting inputs and returning decimal outputs) ## Explanation & ungolfed Since Alchemist applies the rules non-deterministically we need a lot of *0-rules*.. Initially there is only one `_` atom, so we use that to read the inputs: ``` _->u+v+2r u+r->In_a+In_x v+r->In_b+In_y ``` The following rules can't be applied because they all require `0r`, now we have `a`, `b` as the signs of `x` and `y` respectively. ``` # Case -x -y: we output the sign and remove a,b # therefore we will handle them the same as +x +y 0_+0r+0d+a+b->Out_"-" #: 0_+0r+0d ⇐ a+b # Case +x +y: doesn't need anything done 0_+0r+0d+0a+0b->d # Case +x -y: ## remove one atom each 0_+0r+0d+0a+x+b+y->b #: 0_+0r ⇐ x+b ## if we had |y| > x: output sign and be done 0_+0r+0d+a+0b+0y->d+Out_"-" #: 0_ ⇐ 0r+a ## else: be done 0_+0r+0d+0b+a+0x->d #: 0_ ⇐ 0r+a # Case -x +y is symmetric to the +x -y case: 0_+0r+0d+a+x+0b+y->a #: 0_+0r+0d ⇐ a+y 0_+0r+0d+0a+b+0x->d+Out_"-" #: 0_ ⇐ 0r+b 0_+0r+0d+0a+b+0y->d #: 0_ ⇐ 0r+b # All computations are done and we can output in unary: 0_+d+x->d+Out_"1" #: 0_ ⇐ d 0_+d+y->d+Out_"1" #: 0_ ⇐ d ``` To the right of some rules I marked some golfs with `#: y ⇐ x` which should read as: "The conditions `x` imply `y` at this stage and thus we can remove it without changing the determinism" ]
[Question] [ Print integers 0 to 100 (inclusive) without using characters `123456789` in your code. Separator of numbers can be comma or [white space](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_442) (by default <blank>, <horizontal tabulator>, <newline>, <carriage return>, <form feed> or <vertical tabulator>). Shortest code wins. [Answer] # [R](https://www.r-project.org/), 9 bytes ``` F:volcano ``` [Try it online!](https://tio.run/##K/r/382qLD8nOTEv//9/AA "R – Try It Online") The sequence operator `:` coerces its arguments to integers. `F` is the boolean `FALSE`, which gets coerced to `0`. `volcano` is one of the many built-in datasets (it gives topographic information about Maunga Whau in New Zealand); since it is a matrix, `:` fetches the value at position `[1, 1]` which is luckily equal to `100`. The code is therefore equivalent to `0:100`. This answer was inspired by a conversation with Giuseppe and Kirill L. in the comments under [Giuseppe's R answer](https://codegolf.stackexchange.com/a/219592/86301). [Answer] # Python 3: 27 23 20 Bytes *Thanks to caird coinheringaahing for -4 bytes, ovs for -3 bytes* ``` print(*range(*b'e')) ``` I'm pretty poor at golfing, so there's probably a better way to do this. [TIO](https://tio.run/##K6gsycjPM/7/v6AoM69EQ6soMS89VUMrST1VXVPz/38A) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 138 bytes ``` >>++++++++++<<++++++[>>>++++++++<<<-]++++++[>>>>++++++++<<<<-]++++++++++>++++++++++<[>[>>.>.+<<.<-]++++++++++>>>----------<+<<<-]>>>>+.-.. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v/fzk4bDmxsIHS0HULUxsZGNxYhjCwOlwABZGOi7YBK9ez0gIr0UBXZ2enCgQ3EbLCherp6ev//AwA "brainfuck – Try It Online") No numbers is pretty easy, but the golf size is not great... :) I am sure it can be improved, I am really a beginner in using Brainfuck. I wanted to try it anyway. **How it works:** ``` >>++++++++++<< LF Char (idx2) ++++++[>>>++++++++<<<-] Zero char tens (idx3) ++++++[>>>>++++++++<<<<-] Zero char unit (idx4) +++++ +++++ 10 counter (tens) >+++++ +++++< 10 counter (unit) [> Move to the counter [>>. Print the tens >.+ Print the unit and increment <<. Print the LF <-] Loop 10 times +++++ +++++ Restore the counter >>>----- ----- Restore the digit <+ Increment the tens char <<<-] Loop everything 10 times >>>>+.-.. Print 100 using a cell which is already at char 0 ``` [Answer] # [JavaScript (V8)](https://v8.dev/), 28 bytes We cannot write \$100\$ or \$101\$ in hexadecimal with 0's and letters only (**0x64** and **0x65** respectively), but we can write \$202\$ (**0xCA**) and use \$2n<202\$ as the condition of the `for` loop. ``` for(n=0;n+n<0xCA;)print(n++) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sA6TzvPxqDC2dFas6AoM69EI09bW/P/fwA "JavaScript (V8) – Try It Online") --- ### 30 bytes This version computes \$10^2\$ with the hexadecimal representation of \$10\$. ``` for(n=0;n<=0xA*0xA;)print(n++) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sA6z8bWoMJRC4itNQuKMvNKNPK0tTX//wcA "JavaScript (V8) – Try It Online") --- ### 31 bytes This version builds the string `"100"`. ``` for(n=0;n<=-~0+'00';)print(n++) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPP1sA6z8ZWt85AW93AQN1as6AoM69EI09bW/P/fwA "JavaScript (V8) – Try It Online") [Answer] # [SHENZHEN I/O](https://www.zachtronics.com/shenzhen-io/), 61 bytes, 7¥, 7 Lines ``` @not @mov acc dat @not tgt acc dat -mov acc p0 -add x0 slp x0 ``` Outputs 0-100 as simple output, one per time unit. Makes use of the DX300 (XBus <-> Simple Input chip) and LC70G04 (NOT gate), which cost 1¥ each but do not use any power or count as lines of code (the game's measure of code length). These are used to generate a value of 1, which it adds and outputs until it hits 100. The value for 100 is generated using the "not" command, which makes the accumulator 100 if it is value 0, otherwise it sets the acc to 0. [![](https://i.stack.imgur.com/CpUon.gif)](https://i.stack.imgur.com/CpUon.gif) (Not pictured: conversion from simple output to the screen's XBus input, for the visualization.) --- # [SHENZHEN I/O](https://www.zachtronics.com/shenzhen-io/) (MCxxxx ASM only), 129 bytes, 8¥, 16 Lines ``` @not | not @mov acc p0 | mul acc @mov acc dat | dgt 0 @not | sub p0 add p0 | dgt 0 tgt acc dat | mul acc -mov acc x0 | mov acc p0 slp p0 | slx x0 ``` Outputs 0-100 as one XBus output each. Uses only programmable MCxxxx chips, no logic gates or other components. Generates value 1 in a pretty interesting way: ``` not # acc = 100 mul acc # 100 * 100 = 999 (max value) dgt 0 # digit 0 of 999 = 9 sub p0 # 9 - 100 = -91 dgt 0 # digit 0 of -91 = -1 mul acc # -1 * -1 = 1 ``` [![enter image description here](https://i.stack.imgur.com/RgZX8.gif)](https://i.stack.imgur.com/RgZX8.gif) [Answer] # [Raku](http://raku.org/), 10 bytes ``` put 0..Ⅽ ``` [Try it online!](https://tio.run/##K0gtyjH7/7@gtETBQE/vUeva//8B "Perl 6 – Try It Online") `Ⅽ` here is the Unicode character ROMAN NUMERAL ONE HUNDRED. Any other Unicode character with a defined value of 100 could be used: ௱: TAMIL NUMBER ONE HUNDRED ൱: MALAYALAM NUMBER ONE HUNDRED ፻: ETHIOPIC NUMBER HUNDRED ⅽ: SMALL ROMAN NUMERAL ONE HUNDRED 佰: CJK UNIFIED IDEOGRAPH-4F70 百: CJK UNIFIED IDEOGRAPH-767E 陌: CJK UNIFIED IDEOGRAPH-964C All are three UTF-8 bytes long, like `Ⅽ`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 [bytes](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page) ``` ³Ż ``` [Try it online!](https://tio.run/##y0rNyan8///Q5qO7//8HAA "Jelly – Try It Online") Outputs a list. If the separator must be a single character, [3 bytes](https://tio.run/##y0rNyan8///Q5qO7vf//BwA) ## How it works ``` ³ŻK - Main link. Takes no arguments ³ - Yield 100 Ż - Range from 0 to 100 K - Join by spaces (optional) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `jHRM`, 0 bytes ``` ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqSFJNIiwiIiwiIiwiIiwiIl0=) Kinda cheating, but whatever. ## How? ``` # full program # H flag presets the stack to 100 # R flag does range when number is treated as iterable # M flag makes range start at 0 # j flag joins the top of the stack by newlines ``` [Answer] # [R](https://www.r-project.org/), 11 bytes ``` F:(0xA*0xA) F:0xA^(T+T) ``` [Try it online!](https://tio.run/##K/r/381Kw6DCUQuINf//BwA "R – Try It Online") Uses [this tip](https://codegolf.stackexchange.com/a/191117/67312). Still being beaten by [some volcano in New Zealand](https://codegolf.stackexchange.com/a/219617/67312), though... Old answer: ### [R](https://www.r-project.org/), 16 bytes ``` F:paste0(+T,0,0) ``` [Try it online!](https://tio.run/##K/r/382qILG4JNVAQztEx0DHQPP/fwA "R – Try It Online") Thanks to Kirill L. for correcting an error. R's ASCII=>byte function is `utf8ToInt`, which unfortunately has an `8` in it. Luckily, `:` will attempt to coerce its arguments to numeric types, so we construct `100` by pasting together `+F` (which coerces its value to `0`) and two `0`s. This would also work, though longer, without a `0` as `F:paste(+T,+F,+F,sep="")`. Possibly there's a very short builtin dataset with a `sum` that's close to 100, though I haven't been able to find one. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~33~~ ~~26~~ 24 bytes ``` ,, ,,,,,, , ,,,,, $.` ``` [Try it online!](https://tio.run/##K0otycxL/P@fS0eHC4hBgEsHwuDiUtFL@P8fAA "Retina 0.8.2 – Try It Online") Explanation: The first stage inserts two commas, which the second stage increases to 20 (it's complicated). The third stage multiplies by 5 to give 100. The last stage then inserts the number of commas so far at each position. [Answer] # [C (gcc)](https://gcc.gnu.org/), 38 bytes ``` f(i){for(i=0;printf("%d ",i++)&'#';);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SCPT1sC6oCgzryRNQ0k1RUFJJ1NbW1NNXVndWtO69n9uYmaeBlChBojzLzktJzG9@L9uOQA "C (gcc) – Try It Online") Without using digit `0`, it would be 39 bytes: [`i;main(){for(;printf("%d ",i++)&'#';);}`](https://tio.run/##S9ZNT07@/z/TOjcxM09Dszotv0jDuqAoM68kTUNJNUVBSSdTW1tTTV1Z3VrTuvb//3/JaTmJ6cX/dcsB) [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~25~~ 23 bytes ``` seq 0 $(printf %d "'d") ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UMFAQUWjoCgzryRNQTVFQUk9RUnz/38A "Bash – Try It Online") -2 thanks to @manatwork [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 16 12 bytes -4 bytes thanks to @mazzy! ``` 0..(0xa*0xa) ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/30BPT8OgIlELiDX//wcA "PowerShell – Try It Online") [Answer] # PHP, 30 bytes First time golfing, I hope I posted this right! ``` while($q<ord(e))echo+$q++,' '; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkyzMyc1I1VApt8otSNFI1NVOTM/K1VQq1tXXUFdSt//8HAA "PHP – Try It Online") --- Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) and [Dewi Morgan](https://codegolf.stackexchange.com/users/41364/dewi-morgan)'s suggestions to improving the code! From 34 to 30 bytes! The code revisions are in the edit history, removed here so it looks cleaner! [Answer] # Factor, ~~46~~ 23 bytes -23 bytes thanks to Bubbler ``` 0xa sq [0,b] [ . ] each ``` [Try it online!](https://tio.run/##qyrO@J@cWKJgp1Cnr5eWmFySX6RblKxgY6Pg6u/GFRrsaqVQkFhUnFqkkFhakq9bWpzKBZKAaSnOLy1KToVqhOr6b1CRqFBcqBBtoJMUqxCtoKcQq5CamJzxH6RRP7@gRB@iHEqhm/IfAA "Zsh – Try It Online") I've never written anything in Factor before, but it's a surprisingly fun language. [Answer] # [Zsh](https://www.zsh.org/), 12 bytes ``` seq 0 $[##d] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZrilMLFQwUVKKVlVNiIUJQGZgKAA) * `seq`: count + from `0` + `$[##d]`: to the character value of `d` Alternative: # [Zsh](https://www.zsh.org/), 12 bytes ``` ! seq 0 $?00 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhZrFLmKUwsVDBRU7A0MIEJQGZgKAA) `!` does nothing, but fails with exit code 1; `$?` then retrieves the exit code. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), `jH`, 1 byte ``` ʀ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=jH&code=%CA%80&inputs=&header=&footer=) Flags for the win. The `H` flag presets the stack to 100, generate range 0 to 100 and then `j` flag joins on newlines. The flag was around before this challenge too. [Answer] # Perl, 20, 13, 12, 16 bytes ``` say for 0..ord d ``` [Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/OLFSIS2/SMFATy@/KEUh5f9/AA "Perl 5 – Try It Online") [Answer] # [Zsh](https://www.zsh.org/), 16 bytes ``` echo {0..$[##d]} ``` [Try it online!](https://tio.run/##qyrO@P8/NTkjX6HaQE9PJVpZOSW29v9/AA "Zsh – Try It Online") Only builtins, so no `seq` --- For fun, here's a **17 byte** answer without `0`: ``` echo {$?..$[##d]} ``` [Try it online!](https://tio.run/##qyrO@P8/NTkjX6FaRVlPTyVaWTkltvb/fwA "Zsh – Try It Online") Also `$!` or `$#` will work as `0` replacements. [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~18~~ ~~16~~ 14 bytes ``` seq 0 $[++x]00 ``` [Try it online!](https://tio.run/##S0oszvj/vzi1UMFAQSVaW7si1sDg/38A "Bash – Try It Online") Thanks @manatwork for -2, @Jonah for -2 [Answer] # PICO-8, ~~50~~ 45 bytes ``` i=0-#"0"repeat i+=#"0"?i until#tostr(i)>#"00" ``` -5 bytes by replacing `print` with its shorthand, `?`. Demo (50 byte version; 45 byte version has same output): [![i=0-#"0"repeat i+=#"0"print(i)until#tostr(i)>#"00"](https://i.stack.imgur.com/GWfVa.gif)](https://i.stack.imgur.com/GWfVa.gif) [Answer] # GNU Octave, 14, 5 bytes ``` 0:'d' ``` [TIO](https://tio.run/##y08uSSxL/f/fwEo9Rf3/fwA) by Giuseppe [Answer] # [Ruby](https://www.ruby-lang.org/) 22 bytes 12 bytes - thanks to @manatwork ``` p *0..?d.ord ``` [Try it online!](https://tio.run/##KypNqvz/v0BBy0BPzz5FL78o5f9/AA "Ruby – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` тÝ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//YtPhuf//AwA "05AB1E – Try It Online") Outputs a list. If the separator must be a single character, [3 bytes](https://tio.run/##yy9OTMpM/f//YtPhuYd2//8PAA) ## How it works ``` тÝ» - Full program т - Push 100 Ý - Range from 0 to 100 » - Join with newlines (optional) ``` [Answer] # Deadfish~, 2071 / 8 / 7 bytes 2071 bytes ``` o{i}c{d}io{i}dc{d}iio{i}ddc{d}iiio{i}dddcddddddoiiiiiicdddddoiiiiicddddoiiiicdddoiiicddoiicdoicociodciioddciiiodddciiiioddddciiiiiodddddciiiiiioddddddc{i}dddo{d}iiic{i}ddo{d}iic{i}do{d}ic{i}o{d}c{i}io{d}dc{i}iio{d}ddc{i}iiio{d}dddc{i}iiiio{d}ddddc{i}iiiiio{d}dddddc{i}iiiiiio{d}ddddddc{i}{i}dddo{d}{d}iiic{i}{i}ddo{d}{d}iic{i}{i}do{d}{d}ic{i}{i}o{d}{d}c{i}{i}io{d}{d}dc{i}{i}iio{d}{d}ddc{i}{i}iiio{d}{d}dddc{i}{i}iiiio{d}{d}ddddc{i}{i}iiiiio{d}{d}dddddc{i}{i}iiiiiio{d}{d}ddddddc{i}{i}{i}dddo{d}{d}{d}iiic{i}{i}{i}ddo{d}{d}{d}iic{i}{i}{i}do{d}{d}{d}ic{i}{i}{i}o{d}{d}{d}c{i}{i}{i}io{d}{d}{d}dc{i}{i}{i}iio{d}{d}{d}ddc{i}{i}{i}iiio{d}{d}{d}dddc{i}{i}{i}iiiio{d}{d}{d}ddddc{i}{i}{i}iiiiio{d}{d}{d}dddddc{i}{i}{i}iiiiiio{d}{d}{d}ddddddc{{i}dddddd}dddo{{d}iiiiii}iiic{{i}dddddd}ddo{{d}iiiiii}iic{{i}dddddd}do{{d}iiiiii}ic{{i}dddddd}o{{d}iiiiii}c{{i}dddddd}io{{d}iiiiii}dc{{i}dddddd}iio{{d}iiiiii}ddc{{i}dddddd}iiio{{d}iiiiii}dddc{{i}dddddd}iiiio{{d}iiiiii}ddddc{{i}dddddd}iiiiio{{d}iiiiii}dddddc{{i}dddddd}iiiiiio{{d}iiiiii}ddddddc{{i}ddddd}dddo{{d}iiiii}iiic{{i}ddddd}ddo{{d}iiiii}iic{{i}ddddd}do{{d}iiiii}ic{{i}ddddd}o{{d}iiiii}c{{i}ddddd}io{{d}iiiii}dc{{i}ddddd}iio{{d}iiiii}ddc{{i}ddddd}iiio{{d}iiiii}dddc{{i}ddddd}iiiio{{d}iiiii}ddddc{{i}ddddd}iiiiio{{d}iiiii}dddddc{{i}ddddd}iiiiiio{{d}iiiii}ddddddc{{i}dddd}dddo{{d}iiii}iiic{{i}dddd}ddo{{d}iiii}iic{{i}dddd}do{{d}iiii}ic{{i}dddd}o{{d}iiii}c{{i}dddd}io{{d}iiii}dc{{i}dddd}iio{{d}iiii}ddc{{i}dddd}iiio{{d}iiii}dddc{{i}dddd}iiiio{{d}iiii}ddddc{{i}dddd}iiiiio{{d}iiii}dddddc{{i}dddd}iiiiiio{{d}iiii}ddddddc{{i}ddd}dddo{{d}iii}iiic{{i}ddd}ddo{{d}iii}iic{{i}ddd}do{{d}iii}ic{{i}ddd}o{{d}iii}c{{i}ddd}io{{d}iii}dc{{i}ddd}iio{{d}iii}ddc{{i}ddd}iiio{{d}iii}dddc{{i}ddd}iiiio{{d}iii}ddddc{{i}ddd}iiiiio{{d}iii}dddddc{{i}ddd}iiiiiio{{d}iii}ddddddc{{i}dd}dddo{{d}ii}iiic{{i}dd}ddo{{d}ii}iic{{i}dd}do{{d}ii}ic{{i}dd}o{{d}ii}c{{i}dd}io{{d}ii}dc{{i}dd}iio{{d}ii}ddc{{i}dd}iiio{{d}ii}dddc{{i}dd}iiiio{{d}ii}ddddc{{i}dd}iiiiio{{d}ii}dddddc{{i}dd}iiiiiio{{d}ii}ddddddc{{i}d}dddo{{d}i}iiic{{i}d}ddo{{d}i}iic{{i}d}do{{d}i}ic{{i}d}o{{d}i}c ``` [Try it online!](https://tio.run/##ZZBBcsUgDENP1EN1oJ2yyqLLDmdPg8H2k5NFIsv8j57612f/Hr8/H/d9/Y3Z/vocS3RTWx59ht66Pdewp2FoIdsRzT7tebWrjau351/6eq@PfU1steXRZ3jutkuvHWFPezBtcqkl1ncsYb8aWx59Bp98jDmMdNIyL4NklogTiTyU5zrRTjoP6BkjZiTNsJkXkZGawZld4lcCgRAOopAGQGBKrCQDHPiISEoBFVbFVeICXbgrOug3@PNs/o3@PLsBbnUpO1lxwwX9wYWkGLoqu7Ks27p@7V8H3ifeR3BGS9KOZllxwwV82HCRgN1INdKMFqO9lFpKK7WU2smrktqIFCJ9TF3Ah51umunlveiBNbAFKUE60Aq0gVJA4a/4hZ7wZJ9ip5tmeGGFE7clM5BBTGDyCq7QKqyyFlQlBSg4J83wwnLHDZ/9juBLvKQDHNiIRjIBEy7FEqqESqYJyx03znzGdt// "Deadfish~ – Try It Online") 8 bytes (if you consider Hello, world! a valid separator) ``` o{{iow}} ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/v7o6M7@8tvb/fwA "Deadfish~ – Try It Online") 7 bytes (If you don't care about seperators) ``` o{{io}} ``` [Try it online!](https://tio.run/##S0lNTEnLLM7Q/f8/v7o6M7@29v9/AA "Deadfish~ – Try It Online") Never thought I'd see deadfish be shorter than, well, anything except Unary. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 13 characters Thanks to * [Daemon](https://codegolf.stackexchange.com/users/101144/daemon) for reusing stack depth instead of getting it again, to use shorter operator (-1 character) ``` [zpdA0>x]dsxx ``` [Try it online!](https://tio.run/##S0n@/z@6qiDF0cCuIjaluKLi/38A "dc – Try It Online") ### [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 14 characters Thanks to * [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) for the twist in using the stack depth efficiently (-2 characters) ``` [zpzA0!<m]dsmx ``` [Try it online!](https://tio.run/##S0n@/z@6qqDK0UDRJjc2pTi34v9/AA "dc – Try It Online") ### [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 16 characters ``` 0[pz+dA0>i]dsixp ``` Sample run: ``` bash-5.0$ dc -e '0[pz+dA0>i]dsixp' | head 0 1 2 3 4 5 6 7 8 9 ``` [Try it online!](https://tio.run/##S0n@/98guqBKO8XRwC4zNqU4s6Lg/38A "dc – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/mathematica/), ~~15~~ ~~14~~ 11 bytes ``` =Range[0,LL ``` -1 byte from Imanton1 Mathematica interprets the `=` prefix as a call to Wolfram Alpha (auto-converting it to the orange glyph seen below), which in turn interprets "LL" as a Roman numeral for 100. I used "LL" because this doesn't work with the shorter "C". [![enter image description here](https://i.stack.imgur.com/cNtqU.png)](https://i.stack.imgur.com/cNtqU.png) [Answer] # Python 3 20 Bytes ``` print(*range(*b'e')) ``` `How it works?` Basically, doing \*b'char' is equivalent to ord('char'), and in this case ord('e') is equal to 101 ; Lets re-create the ord() function! ## Ord Function Recreation (Not the answer! Just a demonstration on how ord() works) ``` ord=lambda x:(int(*bytes(x, 'ascii'))) ``` As you can see it works! You can test this yourself [here](https://www.online-python.com/pwafv3OSPz). # Python 3 25 Bytes ``` print(*range(0xa*0xa-~0)) ``` `How it works?` 0xa = 10, ~0 = -1, -~0 = 1 (equivalent to -1\*-1) [Answer] # [Python](https://python.org), ~~25~~ 23 bytes ``` print(*range(ord('e'))) ``` -2 by Steffan, remove first parameter (`0`) from call to `range` [Answer] # [APL (Dyalog)](https://dyalog.com/), 19 bytes ``` ⎕←0,⍳(+/⍳≢⍬⍬⍬⍬)*≢⍬⍬ ``` [Try it here!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//Ud/UR20TDHQe9W7W0NYHko86Fz3qXQNHmlpwgf//AQ) ``` ≢⍬⍬⍬⍬ ⍝ This evaluates to 4 ≢⍬⍬ ⍝ This evaluates to 2 ⍳≢⍬⍬⍬⍬ ⍝ Evaluates to 1 2 3 4 (+/⍳≢⍬⍬⍬⍬) ⍝ Sums up previous list, 1+2+3+4 = 10 (+/⍳≢⍬⍬⍬⍬)*≢⍬⍬ ⍝ Exponentiates previous result by 2 ⍳(+/⍳≢⍬⍬⍬⍬)*≢⍬⍬ ⍝ Generates 1 2 ... 100 0,⍳(+/⍳≢⍬⍬⍬⍬)*≢⍬⍬ ⍝ Appends 0 to front ``` ]
[Question] [ Your challenge is to write a polyglot that works in different versions of your language. When run, it will always output the language version. # Rules * Your program should work in at least two versions of your language. * Your program's output should *only* be the version number. No extraneous data. * Your program may use whatever method you like to determine the version number. However, the output must follow rule 2; however you determine the version number, the output must only be the number. * Your program only needs to output the major version of the language. For example, in FooBar 12.3.456789-beta, your program would only need to output 12. * If your language puts words or symbols before or after the version number, you do not need to output those, and only the number. For example, in C89, your program only needs to print `89`, and in C++0x, your program only needs to print `0`. * If you choose to print the full name or minor version numbers, e.g. C89 as opposed to C99, it must *only* print the name. `C89 build 32` is valid, while `error in C89 build 32: foo bar` is not. * Your program may not use a builtin, macro, or custom compiler flags to determine the language version. # Scoring Your score will be the code length divided by the number of versions it works in. Lowest score wins, good luck! [Answer] # Python 3.0 and Python 2, score 6 (12 bytes, 2 versions) ``` print(3/2*2) ``` Try it Online: * [Python 2](https://tio.run/##K6gsycjPM/r/v6AoM69Ew1jfSMtI8/9/AA "Python 2 – Try It Online") * [Python 3](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1jfSMtI8/9/AA "Python 3 – Try It Online") Relies on the fact that Python 3+ uses float division by default, unlike Python 2, which uses floor division. [Answer] # [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), 400 bytes, 17 versions, score = 23,52 Supported versions: `1.0`, `1.1`, `1.2`, `1.3`, `1.4`, `1.5`, `1.6`, `1.7`, `1.8`, `9`, `11`, `12`, `14`, `15`, `16`, `17` and `18`. Unsupported vesions: `10` and `13` since they have no new classes at all. (For previous scores, [check the history](https://codegolf.stackexchange.com/posts/139274/revisions)!) ``` Object v(){int i=0;try{for(String[]s={"Locale","Map","Timer","Currency","UUID","Deque","Objects","Base64","zip.CRC32C","Map","java.security.interfaces.XECKey","java.lang.Enum$EnumDesc","Map","java.io.Serial","java.security.spec.EdECPoint","java.lang.Record","HexFormat","java.net.spi.InetAddressResolver"};;i++)Class.forName(s[i].charAt(0)=='j'?s[i]:"java.util."+s[i]);}finally{return i<9?"1."+i:i;}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZHPbtQwEMbFtU9hRUhNtGCVP0LQsKpKNogKCmiXSkhVkVxndjsrxw4ee2mI8g7cuewB3oIXgadhopSVKi6eTzPjz-P5ff-xVhu1_dXES4NaaKOIxKlCK7o9ISiogPpnDMv7T__c-fbucg06iE2adWiDwOlBHnzbLZ1PF8GjXZ1f0LRL3jitDCT3klPV8PkBa_Aci-g9WN2yPDs7mXGYwec49I2-xOqFInjymMVXbGQxLx49LHY-w6CSQEePoZU8APil0kDyY1m8hvZfh1F2JUsb67vDMQPStx3QyQV4VOY_S2pAy7Iqi_eO3W_5zUE7X3HqFVy_dL5Wu7KFwBdRnrA4rioPRHMgZzb85z7PcTLJimGpkrf0VtWQ0jleSH2l_HFID7LpdH-9fzTkDke_GNDIZDJksrxfolXGtJ2HEL0V-PzZUfKAy3iIed-PYH5_EuIG38hLbBxWomaIOyxC-RVlIlx594VEea2hCehGyEIsWgpQSxeDbLg_GJsy4yznYr9388p2O8a_) ### Ungolfed ``` Object v(){ int v=0; try { for( String[] s={ "Locale", // 1.1 "Map", // 1.2 "Timer", // 1.3 "Currency", // 1.4 "UUID", // 1.5 "Deque", // 1.6 "Objects", // 1.7 "Base64", // 1.8 "zip.CRC32C", // 9 "Map", // 10 is unsupported so use the smallest name possible. "java.security.interfaces.XECKey", // 11 "Enum$EnumDesc", // 12 "Map", // 13 is unsupported so use the smallest name possible. "java.io.Serial", // 14 "java.security.spec.EdECPoint", // 15 "java.lang.Record", // 16 "HexFormat", // 17 "java.net.spi.InetAddressResolver" // 18 };;v++) Class.forName( s[i].charAt(0)=='j' // If the package name is referenced, ? s[i] // Use it : "java.util."+s[i]); // Else, prepend "java.util". } finally { // Swallowing ClassNotFoundException when the version is not the last one // Swallowing ArrayIndexOutOfBoundsException that occurs after reaching the last version. return v < 9 ? "1." + v : v; // Return either an int or a String } } ``` Please note that the code part `return v<9?"1."+v:v;` (previously `return(v<9?"1.":"")+v;`) needs to be checked against any version between Java 1.0 and Java 1.3 included. I don't have any Java 1.3 or earlier installation at my disposal to actually test this syntax. ### Introduction The Java versioning has a special history. All versions have historically been `1.x` including `1.0`. But... from Java 9 onwards and the [JEP223](http://openjdk.java.net/jeps/223), the version scheming has changed from using `1.x` to `x`. That is the version as internally known. So we have the following table (put together with the Javadoc and [Wikipedia](https://en.wikipedia.org/wiki/Java_version_history)): | `java.version` property | Release name | Product name | | --- | --- | --- | | 1.0 | JDK 1.0 | Java 1 | | 1.1 | JDK 1.1 | | | 1.2 | J2SE 1.2 | Java 2 | | 1.3 | J2SE 1.3 | | | 1.4 | J2SE 1.4 | | | 1.5 | J2SE 5.0 | Java 5 | | 1.6 | Java SE 6 | Java 6 | | 1.7 | Java SE 7 | Java 7 | | 1.8 | Java SE 8 | Java 8 | | 9 | Java SE 9 | Java 9 | | ... | ... | ... | | 18 | Java SE 18 | Java 18 | This challenge entry matches the version column in the table above, which is what is contained in the system property `"java.version"`. ### Explanation The goal is to check from which version a class starts to exist, because Java deprecates code but never removes it. The code has been specifically written in Java 1.0 to be compatible with all the versions, again, because [the JDK is (mostly) source forward compatible](https://stackoverflow.com/questions/4692626/is-jdk-upward-or-backward-compatible). The implementation tries to find the shortest class names that each version introduced. Though, to gain bytes, it's needed to try and pick a common subpackage. So far I found the most efficient package is `java.util` because it contains several really short-named classes spread across all versions of Java. Now, to find the actual version number, the class names are sorted by introducing version. Then I try to instanciate each class sequentially, and increment the array index. If the class exists, we skip to the next, otherwise we let the exception be caught by the `try`-block. When done, another exception is thrown because there are no more classes whose existence we need to check. In any case, the thread will leave the `try`-block with an exception. That exception is not caught, but simply put on hold thanks to the `finally`-block, which in turn overrides the on-hold exception by actually returning a value which is `"1."+v` where `v` is the index used before. It also happens we made this index match the minor version number of Java. Note: what is below needs to be updated. An important part of the golf was to find the shortest new class name in the package `java.util` (or any children package) for each version. Here is the table I used to compute that cost. | Version | Full name (cost in chars) | Reduced name (cost in chars) | | --- | --- | --- | | 9 | `java.util.zip.CRC32C` (20) | `zip.CRC32C` (10) | | 1.8 | `java.util.Base64` (16) | `Base64` (6) | | 1.7 | `java.util.Objects` (17) | `Objects` (7) | | 1.6 | `java.util.Deque` (15) | `Deque` (5) | | 1.5 | `java.util.UUID` (14) | `UUID` (4) | | 1.4 | `java.util.Currency` (18) | `Currency` (8) | | 1.3 | `java.util.Timer` (15) | `Timer` (5) | | 1.2 | `java.util.Map` (13) | `Map` (3) | | 1.1 | `java.util.Locale` (16) | `Locale` (6) | | 1.0 | [default] | [default] | | | Full name (cost in chars) | Reduced name (cost in chars) | | --- | --- | --- | | Subtotal | 144 chars | 54 chars | | Base | 0 chars | 10 chars (`java.util.`) | | Total | 144 chars | 64 chars | ### Credits * 30 bytes saved thanks to Kevin Cruijssen (although I was doing it before I read his comment, I promise!). * 26 further bytes saved thanks to Neil (nope, I wasn't thinking about doing that) * 12 bytes thanks to Nevay and the nice out-of-the~~-box~~-try-catch thinking! * 11 more bytes by Neil again and the nice portable `finally` trick. * 2 more bytes thanks to Kevin Cruijssen by replacing `return(i<9?"1.":"")+i;` with `return i<9?"1."+i:i;` (this needs to be validated against 1.0 or at most 1.3 since no syntax changes happened before 1.4) ### With builtins If builtins were allowed: ``` String v(){return System.getProperty("java.version");} ``` 54 bytes for 19 versions (from 1.0 to 18), so the score would be 2,84. [Answer] # [Python](https://docs.python.org/), 606 bytes / 15 versions = score 40.4 *-67 bytes (lol) thanks to NoOneIsHere.* The versions are 0.9.1, 2(.0), 2.2, 2.2.2, 2.5.0, 2,5.1, 3(.0), 3.1, 3.1.3, 3.2.1, 3.3, 3.4, 3.5 aaand 3.6. ``` try:eval('1&2') except:print('0.9.1');1/0 if`'\n'`<'\'\\n\'':print(2);1/0 try:from email import _Parser;print(2.2);1/0 except:0 try:eval('"go"in""') except:print('2.2.2');1/0 try:int('2\x00',10);print(2.5);1/0 except:0 if pow(2,100)<1:print('2.5.1');1/0 if str(round(1,0))>'1':print(3);1/0 if format(complex(-0.0,2.0),'-')<'(-':print(3.1);1/0 if str(1.0/7)<repr(1.0/7):print('3.1.3');1/0 try:eval('u"abc"') except:print('3.2.1');1/0 try:int(base=10);print(3.3);1/0 except:0 try:import enum except:print('3.3.3');1/0 try:eval('[*[1]]') except:print(3.4);1/0 try:eval('f""') except:print(3.5);1/0 print(3.6) ``` All credit to [Sp3000's amazing answer](https://codegolf.stackexchange.com/a/94834). The trailing newline is necessary. Whee, that was fun to golf. This should work (yes, I installed every one of these versions), but I might've accidentally borked something. If anybody finds a bug, please let me know. [Answer] # EcmaScript 3 / 5 / 2015 / 2016 / 2017 in Browser, 59 bytes / 5 versions = 11.8 points ``` alert(2017-2*![].map-2010*![].fill-![].includes-!"".padEnd) ``` [![NetScape 7 report 3, and Opera 12 report 5](https://i.stack.imgur.com/bxlqv.png)](https://i.stack.imgur.com/bxlqv.png) Save 1 byte thanks to GOTO 0 [Answer] # C++ 11/14/17, score = 147/3 = 49 To distinguish between C++11 and C++14/17, it uses the change in the default `const`ness of `constexpr` member functions in C++14 (with credit to the example at <https://stackoverflow.com/questions/23980929/what-changes-introduced-in-c14-can-potentially-break-a-program-written-in-c1>). To distinguish between C++14 and C++17, it uses the fact that C++17 disabled trigraphs. ``` #include<iostream> #define c constexpr int v struct A{c(int){return 0;}c(float)const{return*"??="/10;}};int main(){const A a;std::cout<<11+a.v(0);} ``` Ungolfed: ``` struct A { constexpr int v(int) { return 0; } constexpr int v(float) const { // with trigraphs, *"??=" == '#' == 35, v() returns 3 // without trigraphs, *"??" == '?' == 63, v() returns 6 return *("??=") / 10; } }; int main() { const A a; std::cout << 11 + a.v(0); } ``` (Tested with Debian gcc 7.1.0 using `-std=c++{11,14,17}`.) [Answer] # [Seriously](https://github.com/Mego/Seriously/tree/v1) and [Actually](https://github.com/Mego/Seriously), 3 bytes, score 1.5 ``` '1u ``` Try it online: [Actually](https://tio.run/##S0wuKU3Myan8/1/dsPT/fwA "Actually – Try It Online"), [Seriously](https://tio.run/##K04tyswvLc6p/P9f3bD0/38A) Explanation: ``` '1u '1 both versions: push "1" u Actually: increment character to "2"; Seriously: NOP (both versions: implicit print) ``` `u` and `D` having functionality on strings was only added in Actually (which is Seriously v2). [Answer] ## JavaScript (ES5 & ES6), 14 bytes / 2 versions = 7 ``` alert(5^"0o3") ``` `0o`-style octal constants are new in ES6; ES5 casts the string to `NaN` which doesn't affect the result of the bitwise XOR. [Answer] # JavaScript (ES 2, 3 & 5 - ~~8 9~~ 11), ~~59 / 6 = 9.833 75 / 7 = 10.714~~ 98 / 9 = 10.889 May as well submit the solution with more versions, even if it does score slightly higher than the 2-version solution. ``` alert(11-!"".matchAll-![].flat-(/./.dotAll!=0)-!"".padEnd-![].includes-![].keys-2*![].map-![].pop) ``` [Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@Yk1pUYpucn1ecn5Oql5OfDhHRsNTV0NfT10vJL3HMyVG0NdDUVVRS0itITHHNS9FVjI7Vy8xLzilNSS0Gc7JTK4t1jbRAzNzEArBQQX6B5v//AA) Checks for the presence of various methods in the Array, RegExp & String prototypes, negates them, giving a boolean, and subtracts that boolean from an initial value of 11. The multiplication of `![].map` accounts for the fact that ES4 was abandoned. * The [`matchAll`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/string/matchAll) String method was introduced in [ES2019](https://262.ecma-international.org/11.0/#sec-string.prototype.matchall) (v11). * The [`flat`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) Array method was introduced in [ES2020](https://262.ecma-international.org/10.0/#sec-array.prototype.flat) (v10). * The [`dotAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll) property (and related `s` flag) for Regular Expressions was introduced in [ES2018](http://www.ecma-international.org/ecma-262/9.0/#sec-get-regexp.prototype.dotAll) (v9). * The [`padEnd`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd) String method was introduced in [ES2017](http://www.ecma-international.org/ecma-262/8.0/#sec-string.prototype.padend) (v8). * The [`includes`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) Array method was introduced in [ES2016](http://www.ecma-international.org/ecma-262/7.0/#sec-array.prototype.includes) (v7). * The [`keys`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/keys) Array method was introduced in [ES2015](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.keys) (v6). * The [`map`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map) Array method was introduced in [ES5.1](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19) (v5). * The [`pop`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) Array method was introduced in [ES3](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf) (v3). [Answer] # PHP 5/7, score 5.5 ``` <?=7-"0x2"; ``` [3V4L it online!](https://3v4l.org/Y378M) # PHP 5.3.9/5.3.11, score 10 ``` <?='5.3.'.(9-0x0+2); ``` [3V4L it online!](https://3v4l.org/4GaUL) The online version is longer because old PHP versions on the sandbox don't have short tags enabled. [Answer] # x86 16/32/64-bit machine code: 11 bytes, score= 3.66 This function returns the [current mode](https://en.wikipedia.org/wiki/X86-64#Operating_modes) (default address-size) as an integer in AL. Call it from C with signature `uint8_t modedetect(void);`. (Or more realistically, from machine code that's going to branch on the result using instruction encodings that decode the same in all modes.) NASM machine-code + source listing (showing how it works in 16-bit mode, since `BITS 16` tells NASM to assemble the source mnemonics for 16-bit mode.) ``` 1 machine global modedetect 2 code modedetect: 3 addr hex BITS 16 5 00000000 B040 mov al, 64 6 00000002 B90000 mov cx, 0 ; 3B in 16-bit. 5B in 32/64, consuming 2 more bytes as the immediate 7 00000005 FEC1 inc cl ; always 2 bytes. The 2B encoding of inc cx would work, too. 8 9 ; want: 16-bit cl=1. 32-bit: cl=0 10 00000007 41 inc cx ; 64-bit: REX prefix 11 00000008 D2E8 shr al, cl ; 64-bit: shr r8b, cl doesn't affect AL at all. 32-bit cl=1. 16-bit cl=2 12 0000000A C3 ret # end-of-function address is 0xB, length = 0xB = 11 ``` **Justification**: x86 machine code doesn't officially have version numbers, but I think this satisfies the intent of the question by having to produce specific numbers, rather than choosing what's most convenient (that only takes 7 bytes, see below). Another interesting way to interpret the question would be to write 16-bit code to detect 8086 vs. 186 vs. 286 vs. 386, etc, [as in this example](https://reverseengineering.stackexchange.com/questions/19394/how-did-this-80286-detection-code-work), based on FLAGS and other behaviour, because each new "version" added new features (including instruction opcodes). But that's not what this answer does. The original x86 CPU, Intel's 8086, only supported 16-bit machine code. 80386 introduced 32-bit machine code (usable in 32-bit protected mode, and later in compat mode under a 64-bit OS). AMD introduced 64-bit machine code, usable in long mode. These are versions of x86 machine language in the same sense that Python2 and Python3 are different language versions. They're mostly compatible, but with intentional changes. You can run 32 or 64-bit executables directly under a 64-bit OS kernel the same way you could run Python2 and Python3 programs. ### How it works: Start with `al=64`. Shift it right by 1 (32-bit mode) or 2 (16-bit mode). * 16/32 vs. 64-bit: The 1-byte `inc`/`dec` encodings are REX prefixes in 64-bit (<http://wiki.osdev.org/X86-64_Instruction_Encoding#REX_prefix>). REX.W doesn't affect some instructions at all (e.g. a `jmp` or `jcc`), but in this case to get 16/32/64 I wanted to inc or dec `ecx` rather than `eax`. That also sets `REX.B`, which changes the destination register. But fortunately we can make that work but setting things up so 64-bit doesn't need to shift `al`. The instruction(s) that run only in 16-bit mode could include a `ret`, but I didn't find that necessary or helpful. (And would make it impossible to inline as a code-fragment, in case you wanted to do that). It could also be a `jmp` within the function. * 16-bit vs. 32/64: immediates are 16-bit instead of 32-bit. Changing modes can change the length of an instruction, so 32/64 bit modes decode the next two bytes as part of the immediate, rather than a separate instruction. I kept things simple by using a 2-byte instruction here, instead of getting decode out of sync so 16-bit mode would decode from different instruction boundaries than 32/64. Related: The operand-size prefix changes the length of the immediate (unless it's a sign-extended 8-bit immediate), just like the difference between 16-bit and 32/64-bit modes. This makes instruction-length decoding difficult to do in parallel; [Intel CPUs have LCP decoding stalls](https://software.intel.com/en-us/forums/intel-performance-bottleneck-analyzer/topic/328256). --- Most calling conventions (including the i386 and x86-64 System V ABIs) allow narrow return values to have garbage in the high bits of the register. They also allow clobbering CX/ECX/RCX (and R8 for 64-bit). IDK if that was common in 16-bit calling conventions, but this is code golf so I can always just say it's a custom calling convention anyway. **32-bit disassembly**: ``` 08048070 <modedetect>: 8048070: b0 40 mov al,0x40 8048072: b9 00 00 fe c1 mov ecx,0xc1fe0000 # fe c1 is the inc cl 8048077: 41 inc ecx # cl=1 8048078: d2 e8 shr al,cl 804807a: c3 ret ``` **64-bit disassembly** ([Try it online!](https://tio.run/##VVA7b8IwEN79K24rSIGGQCMU1KFIHSp1ahm6oUtyAat@VLEpSf88vRhCwIPP9/m@h43Okc5VOzHo9GmnbI4Kts5j7cW5ZAJ4FagUF21LKslT4QOq7e9fA0B5EwGqHuoKIUOzgEjjuxI3yxguawWudVtqpB8NiqPxeCUEKrkzMEtFH@bGcjhmYv22@ezGbjxRRZAubpGCQ8RXz/maszBnkks/BXgK7Tx5TBcRFNa4g5ZmBwmTa4K89eQAHfg9gdSaSomeLg8qgrgCGB6E6oitY3YgsvyGeckayBS27HRtFYhFA0d7UCXv9XcE3tqpEGeJIxqfXfKx@vOMVThf12ZdH9@5N1frdHEe@Xj9gp@aKtmEQbev@18JUYfB7qZe5gEvLTnz4AGriv8VXt4BuVFq2lv3SYZcSZCvyYvT6R8 "Assembly (nasm, x64, Linux) – Try It Online")): ``` 0000000000400090 <modedetect>: 400090: b0 40 mov al,0x40 400092: b9 00 00 fe c1 mov ecx,0xc1fe0000 400097: 41 d2 e8 shr r8b,cl # cl=0, and doesn't affect al anyway! 40009a: c3 ret ``` Related: my [x86-32 / x86-64 polyglot machine-code](https://stackoverflow.com/questions/38063529/x86-32-x86-64-polyglot-machine-code-fragment-that-detects-64bit-mode-at-run-ti) Q&A on SO. Another difference between 16-bit and 32/64 is that addressing modes are encoded differently. e.g. `lea eax, [rax+2]` (`8D 40 02`) decodes as `lea ax, [bx+si+0x2]` in 16-bit mode. This is obviously difficult to use for code-golf, especially since `e/rbx` and `e/rsi` are call-preserved in many calling conventions. I also considered using the 10-byte `mov r64, imm64`, which is REX + `mov r32,imm32`. But since I already had an 11 byte solution, this would be at best equal (10 bytes + 1 for `ret`). --- Test code for 32 and 64-bit mode. (I haven't actually executed it in 16-bit mode, but the disassembly tells you how it will decode. I don't have a 16-bit emulator set up.) ``` global _start _start: call modedetect movzx ebx, al mov eax, 1 int 0x80 ; sys_exit(modedetect()); align 16 modedetect: BITS 16 mov al, 64 mov cx, 0 ; 3B in 16-bit. 5B in 32/64, consuming 2 more bytes as the immediate inc cl ; always 2 bytes. The 2B encoding of inc cx would work, too. ; want: 16-bit cl=1. 32-bit: cl=0 inc cx ; 64-bit: REX prefix shr al, cl ; 64-bit: shr r8b, cl doesn't affect AL at all. 32-bit cl=1. 16-bit cl=2 ret ``` This Linux program exits with exit-status = `modedetect()`, so run it as `./a.out; echo $?`. Assemble and link it into a static binary, e.g. ``` $ asm-link -m32 x86-modedetect-polyglot.asm && ./x86-modedetect-polyglot; echo $? + yasm -felf32 -Worphan-labels -gdwarf2 x86-modedetect-polyglot.asm + ld -melf_i386 -o x86-modedetect-polyglot x86-modedetect-polyglot.o 32 $ asm-link -m64 x86-modedetect-polyglot.asm && ./x86-modedetect-polyglot; echo $? + yasm -felf64 -Worphan-labels -gdwarf2 x86-modedetect-polyglot.asm + ld -o x86-modedetect-polyglot x86-modedetect-polyglot.o 64 ## maybe test 16-bit with Bochs, e.g. in a bootloader, if you want. ``` --- # 7 bytes (score=2.33) if I can number the versions 1, 2, 3 There are no official version numbers for different x86 modes. I just like writing asm answers. I think it would violate the question's intent if I just called the modes 1,2,3, or 0,1,2, because the point is to force you to generate an inconvenient number. But if that was allowed: ``` # 16-bit mode: 42 detect123: 43 00000020 B80300 mov ax,3 44 00000023 FEC8 dec al 45 46 00000025 48 dec ax 47 00000026 C3 ret ``` Which decodes in 32-bit mode as ``` 08048080 <detect123>: 8048080: b8 03 00 fe c8 mov eax,0xc8fe0003 8048085: 48 dec eax 8048086: c3 ret ``` and 64-bit as ``` 00000000004000a0 <detect123>: 4000a0: b8 03 00 fe c8 mov eax,0xc8fe0003 4000a5: 48 c3 rex.W ret ``` [Answer] # Pyth 4/5 - 6 bytes/2 versions = 3 ``` 5 ;4 ``` In Pyth 5, an even amount of spaces at the start of the line is ignored for use in indenting, while in Pyth 4, it just acts like a single space and prevents printing the `5`. In Pyth 4, semicolons just finish statements, which allows the `4` to be printed, while in Pyth 5, a space and semicolon makes the rest of the line a comment. [Answer] # Befunge : ~~15~~ 11 bytes / 2 versions = 5.5 4 bytes shaved off by @Pietu1998 ``` "89",;5-;,@ ``` Try it online : [Befunge 93](https://tio.run/##S0pNK81LT/3/X8nCUknH2lTXWsfh/38A "Befunge – Try It Online") [Befunge 98](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XsrBU0rE21bXWcfj/HwA "Befunge-98 (PyFunge) – Try It Online") Uses the Befunge 98-exclusive semicolon operator ("skip to next semicolon") to differentiate versions. Both will print "9". Befunge 93 will ignore the semicolons, subtract 5 from "8" (value left on top of the stack), print the resulting "3" and terminate. Befunge 98 on the other hand, will skip over, print "8" and terminate. [Answer] # Cubically, 4 bytes, score 4/∞ ``` B3%0 ``` Works in every version your system has enough memory to run. **Non-competing because it's lame.** Valid per [this meta post](https://codegolf.meta.stackexchange.com/q/13660/61563). Basically, B3 rotates one row from the left face into the top face. F3 would work just as well, as would F₁3 or B₁3. As one row in Cubically 3x3x3 is three cubelets by one cubelet, this puts three `1`'s into the top face, giving it a face sum of 3. `%0` prints that top face sum, printing 3 for Cubically **3**x3x3. In Cubically 4x4x4, rows are 4x1 cubies. Puts 4 1's into the top face, yielding a sum of 4. [Answer] # [Python](https://docs.python.org/), 196 bytes / 16 versions = score 12.25 The versions are 1.5, 1.6, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, and 3.6 Unfortunately I had to leave out 2.7 because there aren't any modules in it (as far as I can tell) that aren't in 2.6 but are in 3.0. ``` i=15 try: for m in'os.atexit.os.os.os.warnings.cgitb.heapq.collections._ast.abc.queue.os.os.os.importlib.argparse.lzma.asyncio.zipapp.secrets.'.split('.'):__import__(m);i=i+1 except:print(i/10.) ``` We loop through a bunch of modules that were introduced in different versions of python, and at the first error we quit and return the version. The gaps between major versions are filled in by repeatedly importing `os`. The test for python 1.5 relies on `string.split` not being present until 1.6. Credit to [Olivier Grégoire's answer](https://codegolf.stackexchange.com/a/139274/10894) for the idea of testing for new classes/modules in a loop. I've now finally tested on all relevant versions of python...which required editing the 1.5 source code to get it to compile... [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) / [Brachylog v1](https://github.com/JCumin/Brachylog/releases), 5 / 2 = 2.5 ``` 2,1hw ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/30jHMKP8/38A "Brachylog – Try It Online") (Brachylog) [Try it online!](https://tio.run/##SypKTM6ozMlP///fSMcwo/z/fwA "Brachylog v1 – Try It Online") (Brachylog v1) Explanation for Brachylog: ``` ?2,1hw. ?2 Unify ? (input) with 2 (no input so it succeeds) ,1 Append 1 (21) h First element/head (2) w. Write to STDOUT and unify with output (not displayed) ``` Explanation for Brachylog v1: ``` ?2,1hw. ?2 Unify ? (input) with 2 (no input so it succeeds) , Break implicit unification/logical AND 1h Take first element/head of 1 (1) w. Write to STDOUT and unify with output (not displayed) ``` [Answer] # Python 3 and Python 2.0, 18 bytes, score 18 / 2 = 9 ``` print(3-round(.5)) ``` Banker's rounding in Python 3, standard rounding in Python 2. [Try it online - Python 3!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew1i3KL80L0VDz1RT8/9/AA "Python 3 – Try It Online") [Try it online - Python 2!](https://tio.run/##K6gsycjPM/r/v6AoM69Ew1i3KL80L0VDz1RT8/9/AA "Python 2 – Try It Online") [Answer] # Python 1,2,3, score 10.6667 ``` print(len("a a\x20a".split())) ``` This only works if you feed it in as a command line argument instead of putting it in a file, as older versions of python won't default to utf-8 in a file but will in a command line argument. Basically, the string consists of an 'a', an ogham space (3 bytes), an 'a', an escaped space character, and another 'a', and we just split it on whitespace, count how many strings we got, and print that. * Python 3 correctly recognises the ogham space and the escaped space as whitespace, and so the string has 3 words. * Python 2 incorrectly assumes all unicode characters are not whitespace, so it only counts the escaped space and gets 2 words. * Python 1 fails to parse the escaped whitespace, I think because of the a after it, so it sees no spaces and gets 1 word. [Answer] # C89/C99, 25 bytes, 2 versions, score = 12.5 ``` #include <stdio.h> int main() { int v = 11 //**/ 11 + 88; printf("C%d\n", v); return 0; } ``` `//` style comments aren't recognized in C89. Golfed version: ``` v(){return 20//**/2 +79;} ``` Try it online: [C89](https://tio.run/##S9ZNT07@/79MQ7O6KLWktChPwchAX19LS9@IS9vc0rr2v3JmXnJOaUqqgk1xSUpmvl6GHRdXZl6JQm5iZp6GpkI1lwIQFBQBhdI0lJxVU2LylHQUgMZpWoNloIYaWHPVcv3/l5yWk5he/F8XaJRtsoUlAA), [C99](https://tio.run/##S9ZNT07@/79MQ7O6KLWktChPwchAX19LS9@IS9vc0rr2v3JmXnJOaUqqgk1xSUpmvl6GHRdXZl6JQm5iZp6GpkI1lwIQFBQBhdI0lJxVU2LylHQUgMZpWoNloIYaWHPVcv3/l5yWk5he/F8XaJRtsqUlAA) [Answer] ## Perl 5 and Perl 6, 23 bytes 19 bytes, score 9.5 ``` print 6-grep '.','' ``` Perl 5 `grep` first op is always treated as a regex, not so in Perl 6. [Answer] ## Bash, all 4 versions, ~~72~~ ~~71~~ 32 bytes ⇒ score = 8 ``` s=$'\ua\xa\n';expr 5 - ${#s} / 2 ``` This piece of code makes use of different interpretations of `$'...'` strings in each version of Bash. Outputs the major version number -- and that's it. Doc found [here](http://wiki.bash-hackers.org/scripting/bashchanges). ### Ungolfed: ``` s=$'\ua\xa\n'; expr 5 - ${#s} / 2 # Bash v4 sees three linefeeds => length of 3 => 5 - 3 / 2 = 4 # Bash v3 sees the literal '\ua' + two linefeeds: 5 chars in length # => 5 - 5 / 2 = 3 # Bash v2 sees '\ua\xa' + linefeed, 7 chars: 5 - 7 / 2 = 2 # Bash v1 does not even interpret $'..' strings, and sees literally '$\ua\xa\n' of length 9 => 5 - 9 / 2 = 1 ``` This answer is halfly a guess; I only tested it in bash 4 and 3, but it should work on other versions too. Let me know if it does / does not, I will try with other versions as soon as I have them available. -1 char thanks to Jens. -29 bytes thanks to Digital Trauma (the whole `expr` idea)! [Answer] ## R, versions 2 and 3, score: 10.5 points ``` cat(exists("cite")+2) ``` This command returns `2` for R 2.x.x and `3` for R 3.x.x. The function `cite` was added in R version 3.0.0. Therefore, the command `exists("cite")` returns `FALSE` for R 2.x.x and `TRUE` for R 3.x.x. ## R, all versions (1, 2, and 3), score: 12⅓ points ``` e=exists;cat(e("cite")+e("eapply")+1) ``` The function `eapply` was introduced in R 2.0.0. [Answer] # Erlang, 180 bytes, 11 versions, score 16.36 ``` 20-length([A||A<-[schedulers,c_compiler_used,cpu_topology,snifs,dynamic_trace,port_count,nif_version,end_time,max_heap_size,atom_count],{'EXIT',_}<-[catch erlang:system_info(A)]]). ``` With indentation and line breaks: ``` 20-length([A||A<- [schedulers, c_compiler_used, cpu_topology, snifs, dynamic_trace, port_count, nif_version, end_time, max_heap_size, atom_count], {'EXIT',_}<-[catch erlang:system_info(A)]]). ``` Tested on one minor release of each major version since 10: * R10B-9 * R11B-5 * R12B-5 * R13B04 * R14B04 * R15B03 * R16B03 * 17.5.6.2 * 18.2.1 * 19.2 * 20.0 The idea is that every major release has added at least one new allowable argument for the function `erlang:system_info`, so let's try the ones in the list, count how many of them fail, and subtract the number of failures from 20, which is the current version. [Answer] # [Windows' Batch File](https://en.wikipedia.org/wiki/Batch_file), 35 bytes / 2 versions = score 17.5 ``` @if /i Z==z @echo NT&exit @echo DOS ``` Prints `DOS` on MS-DOS (duh) and `NT` on Windows NT. (duh) Now, for some explanation. Windows has had batch scripting since MS-DOS times and it hasn't changed much since then. However, when [Windows NT](https://en.wikipedia.org/wiki/Batch_file#Windows_NT) came along, Microsoft changed the default interpreter for batch scripts, from `COMMAND.COM` to `cmd.exe` (now also allowing the extension `.cmd` as an alternative to the original `.bat`). With that, they also implemented a [few changes](https://en.wikipedia.org/wiki/Cmd.exe#Comparison_with_MS-DOS_Prompt), such as the `/i` flag for ignoring string case on conditionals. That is, while `Z==z` is false, `/i Z==z` is true. We exploit that DOS didn't have case insensitivy and compare uppercase `Z` with lowercase `z`. By using the `/i` flag, we end up with a `Z==z` (false) conditional on DOS and `z==z` (true) on NT. Now, I realize that the challenge specifies that a version number should be printed. But, as far as I know, there is no 'version number' to batch scripting, so this is the closest I could get. --- Tested on Windows 10, DOSBox and vDos: **Windows 10:** [![Windows 10](https://i.stack.imgur.com/Y45u3.png)](https://i.stack.imgur.com/Y45u3.png) (run with `cmd /k` to prevend window closing on `exit`) **DOSBox:** [![DOSBox](https://i.stack.imgur.com/8hwdW.png)](https://i.stack.imgur.com/8hwdW.png) **vDos:** [![vDos](https://i.stack.imgur.com/jkcg0.png)](https://i.stack.imgur.com/jkcg0.png) [Answer] # Julia 0.4, 0.5, 46 bytes, score 22 ``` f(::ASCIIString)=.4 f(::String)=.5 f()=f("") ``` Julia has changed the type name of the concrete and abstract String types in many versions. This code in particular take advantage of: **Julia 0.4**: * Concrete is `ASCIIString`, * Abstract is officially `AbstractString`, * Abstract has deprecated alias to `String`. * Concrete is most specific than abstract so it wins dispatch **Julia 0.5**: * Concrete is officially `String`, * Concrete has deprecated alias to `ASCIIString`, * Abstract is `AbstractString`, (though that doesn't matter here) * As two methods have been defined for the concrete string type, the latter over-writes the former. See also my [newer more effective solution based on different principles](https://codegolf.stackexchange.com/a/139537/4397) [Answer] # [Japt](https://github.com/ethproductions/japt/) (1 & 2), ~~8~~ 6 / 2 = ~~4~~ 3 ``` '1r\S2 ``` [Test v1](https://ethproductions.github.io/japt/?v=1.4.5&code=JzFyXFMy&input=)  **|**  [Test v2](https://ethproductions.github.io/japt/?v=2.0&code=JzFyXFMy&input=) * 2 bytes saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) --- ## Explanation Prior to v2, Japt used a customised RegEx syntax, so we can take advantage of that. ``` '1 ``` The number 1 as a string. ``` r 2 ``` Replace (`r`) the below with a `2`. ``` \S ``` Japt 2 sees this as the RegEx `/\S/g`, which matches the `1`. Japt 1 ignores the `\` escape character and just sees the `S`, which is the Japt constant for a space character and, obviously, doesn't match the `1`. [Answer] # [One and Two Star Programmer](https://esolangs.org/wiki/Three_Star_Programmer), 3 bytes/2, score 1.5 ``` 0 1 ``` In One Star Programmer, the left most cell will point to cell 1, in Two Star Programmer, it will point to cell 2 [Answer] # Wolfram Language/Mathematica 10/11, 37 bytes / 2 versions = 18.5 Consider `(Length@DateRange[{1},{1}][[1]]+27)/3`, at 37 bytes and working with 2 versions, gives me a score of 18.5. ``` In[1]:= $Version Out[1]= "10.4.1 for Microsoft Windows (64-bit) (April 11, 2016)" In[2]:= (Length@DateRange[{1}, {1}][[1]] + 27)/3 Out[2]= 10 ``` and ``` In[1]:= $Version Out[1]= "11.1.1 for Microsoft Windows (64-bit) (April 18, 2017)" In[2]:= (Length@DateRange[{1}, {1}][[1]] + 27)/3 Out[2]= 11 ``` I'm sure there is a more efficient way, but the discrepancy between the DateRange output bit me in the butt recently, so I was set on using that. As a follow up, someone could probably take advantage of `Length@DateRange[{1}, {1}][[1]]` evaluating to `1` in Mathematica versions 1-~8, but I didn't have time to incorporate that. [Answer] # Ruby 1.x and 2.x, 20 bytes, score 10 ``` p [].to_h&&2rescue 1 ``` Based on the `to_h` method which was introduced on the `Array` class in Ruby 2. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), score 7.3 or 3 ### 51 bytes for 7 versions or 6 bytes for 2 versions For the lowest score, distinguish versions 12 and 13 with: ``` 12+≡⍳0 ``` Twelve plus the depth of the first zero integers. Until version 12, `⍳0` (wrongly) returned the index origin as a scalar, i.e. depth 0. In version 13 and up, `⍳0` returns an empty list, i.e. depth 1. --- Much more interesting is the following anonymous function which distinguishes all major versions 10 through 16 (the current). It needs a dummy argument (which is ignored) to run. ``` {2::10⋄⌷2::11⋄_←⎕XML⋄0::+/12⎕ML,≡⍳0⋄≡,/⍬::15⋄16@~0} ``` `{`…`}` an anonymous function which allows setting error guards `::` with a numeric error code (determining which type of error to catch) on the left, and on the right, the result to be returned in case of error.  `2::10` if SYNTAX ERROR, return 10  `⌷2::11` materialise (introduced in version 11) 2 (SYNTAX ERROR) which if happens, yields 11  `⋄_←⎕XML` try: assign XML system function (introduced in version 12) to a dummy name  `0::`…`⋄` if any error happens;   `⍳0` first zero integers (gives 1 until version 12 and empty list from version 13)   `≡` depth of that (0 until 12, 1 from 13)   `12⎕ML,` prepend 12 and the **M**igration **L**evel (0 until 13, 1 from 14)   `+/` sum (12 until 12, 13 in 13, 14 from 14)  `≡,/⍬::15` try: concatenate the elements of an empty list (introduced in version 15) and get its depth, 2 (SYNTAX ERROR) which if happens, yields 15  `⋄16@~0` try: amend with a 16 at (introduced in version 16) positions where logical NOT yields truth, applied to 0 Try it on [TryAPL](http://tryapl.org/?a=%7B2%3A%3A10%u22C4%u23372%3A%3A11%u22C4_%u2190%u2395XML%u22C40%3A%3A+/12%281%29%2C%u2261%u23730%u22C4%u2261%2C/%u236C%3A%3A15%u22C416a%7E0%7D%u236C&run) (slightly modified to pass security) and [Try it Online](https://tio.run/##SyzI0U2pTMzJT///v@xR24RqIysrQ4NH3S2PeraDmIZAZjxQ/FHf1AhfHyDHwMpKW9/QCMj39dF51LnwUe9msPLOhTr6j3rXALWYArmGZg51BrVAIxWAYgA "APL (Dyalog Unicode) – Try It Online")! [Answer] # Julia 0.2-0.7, bytes = 59, versions = 6, score = 9.833 ``` f()=[4,0,3,0,5,2,6,7][endof(subtypes(AbstractArray))-16]/10 ``` Turns out each version of julia has had a different number of abstract array subtypes. So we use the number of subtypes to index into an array that contains the version number. The current nightly (0.7), currently has 25, but it is the fallback case anyway. Julia 0.1 also has a different number of AbstractArray subtypes I would guess. However, julia 0.1 does not have the `subtypes` function. So I can't trivially retrieve them. A significant improvement over [my previous answer.](https://codegolf.stackexchange.com/a/139523/4397) (Thanks @one-minute-more for almost halving the bytecount) ]
[Question] [ We all know the classic dad joke that goes something like this: 1. Somebody says a sentence to describe their self (e.g. `I'm tired` or `I'm confused`). 2. A dad-joke enthusiast comes along and replies `Hi <adjective>, I'm Dad!`, because introductions follow the same format (`I'm Peter` follows the same format as `I'm hungry`). Your job is to take in an input in the form of a self-descriptor, and output the appropriate dad-joke form, but instead of using the word "Dad", you'll use the name of the programming language you're programming in. Test cases (assume that they are being parsed by Python): ``` I'm amazing Hi amazing, I'm Python! I'm tired Hi tired, I'm Python! I'm hungry Hi hungry, I'm Python! I'm fat Hi fat, I'm Python! ``` Now assume that these test cases are being parsed by Golfscript: ``` I'm a programmer Hi a programmer, I'm Golfscript! I'm a question-writer Hi a question-writer, I'm Golfscript! I'm a Stack-Overflow-er Hi a Stack-Overflow-er, I'm Golfscript! ``` The exact challenge: 1. Take in a string in the self-descriptor format (`I'm <adjective>` or `I'm a(n) <noun>`) using standard input or through a function. * Assume there is no ending punctuation. * Assume the word `I'm` is used and not `I am`. 2. Convert it to a dad-joke format - see the above examples for exactly how that should look. Other stuff: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest byte count wins. * Follow the [standard loophole](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) rules - none of those, please. * Have fun! [Answer] # [V](https://github.com/DJMcMayhem/V), 13 bytes ``` cEHi<esc>A, <C-r>" V! ``` [Try it online!](https://tio.run/##K/v/P9nVI1PaUUdBSEkhTPH/f0/1XIWS1OIShdzU4uLE9FQA "V – Try It Online") Inspired by [tsh's answer](https://codegolf.stackexchange.com/a/185891) This takes advantage of the fact that `I'm` is yanked from the start of the string when deleting the text from the start, and pastes it to the end with `<C-r>"` while in insert mode. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~59~~ ~~42~~ 33 bytes -17 bytes thanks to @Conor O'Brien noticing that the import wasn't necessary -9 bytes thanks to @tsh pointing out a shorter, UB way of writing the function ``` a(x){printf("Hi%s, I'm C!",x+3);} ``` [Try it online!](https://tio.run/##FYvLCsIwEADPzVesATGpCQgec/SiJw9@wbIkMdiHbGtbKP11o7nNMAzZSJQzqkWvb07dGJS8pv1g4HZo4bKTZjmetdvyP0GLqVMFkCMZoCdyXReZNKyiQiXLhPAYkV72PnkOTT9bz1I7UbEfP9zByYktfyk0GIds5x8 "C (gcc) – Try It Online") Chops off the first 3 characters of the input (removes `I'm`) and surrounds it with the desired text. [Answer] # [V](https://github.com/DJMcMayhem/V), 13 bytes ``` cEHi<Esc>A, <C-O>p V! ``` [Try it online!](https://tio.run/##K/v/P9nVI1PaUUeBv0AhTPH/f0/1XIWSzKLUFAA "V – Try It Online") New to `V`. Just knew it about 30 minutes ago. Anyway, this language is chosen just because its name only cost 1 byte. I'm not sure how to send `<End>` key in V. Most vim environment would accept `<End>` as a replacement of `<Esc>A` in this example. But, you know, V is 2 characters shorter than vim. :) Thanks to [@Candy Gumdrop](https://codegolf.stackexchange.com/users/55514/candy-gumdrop), saves 1 byte. [Answer] # Excel, ~~36~~ 34 bytes -2 bytes thanks to Johan du Toit. Input goes into A1. ``` ="Hi "&MID(A1,4,99)&", I'm Excel!" ``` First attempt: ``` =REPLACE(A1,1,3,"Hi")&", I'm Excel!" ``` [Answer] # brainfuck, 164 ``` ,-.+>,>,----.++++>,.>,[.,]<<<+++++.----->>.[<]>[.>]<[->+++<]>++.[--->+<]>----.+++[->+++<]>++.++++++++.+++++.--------.-[--->+<]>--.+[->+++<]>+.++++++++.+[++>---<]>-. ``` [Try it online!](https://tio.run/##TY4xDsJQDEOvwsbwE58g8t4zRH8oUESFYAAqcftPIlEpnpI828rpNa/P63a@jyGKRqFoCC1EAcUh3cxyb0ikJNw6HezmyrjHFtCT5bwXVNj@QilKm5YUSqIEPD4JU1owxnR8HJbvbd7en@XyAw "brainfuck – Try It Online") The "brainfuck!" part of the string is generated with [this](https://copy.sh/brainfuck/text.html) tool, can probably be golfed further by hand. [Answer] # [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â∞¿φ‼0▲(─ƒSqÄ ``` [Run and debug it](https://staxlang.xyz/#p=83eca8ed13301e28c49f53718e&i=I%27m+amazing%0AI%27m+tired%0AI%27m+hungry%0AI%27m+fat%0AI%27m+a+programmer%0AI%27m+a+question-writer%0AI%27m+a+Stack-Overflow-er&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` .Hip print "Hi" with no newline 3tp trim 3 characters from start of input and print with no newline final line is to print the unterminated compressed literal ", I'm stax!" `dYgAwg_ ``` I moved the final comment up one line since nothing may follow an unterminated string literal. [Run this one](https://staxlang.xyz/#c=.Hip++++%09print+%22Hi%22+with+no+newline%0A3tp+++++%09trim+3+characters+from+start+of+input+and+print+with+no+newline%0A++++++++%09final+line+is+to+print+the+unterminated+compressed+literal+%22,+I%27m+stax%21%22%0A%60dYgAwg_&i=I%27m+amazing%0AI%27m+tired%0AI%27m+hungry%0AI%27m+fat%0AI%27m+a+programmer%0AI%27m+a+question-writer%0AI%27m+a+Stack-Overflow-er&m=2) [Answer] # [Python 3](https://docs.python.org/3/), ~~35~~ 34 bytes ``` lambda s:"Hi%s, I'm Python!"%s[3:] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSskjU7VYR8FTPVchACyvqKRaHG1sFfu/oCgzr0QjTUMJJJeokJibWJWZl66kqfkfAA "Python 3 – Try It Online") -1 byte thanks to Embodiment of Ignorance Also 34 bytes, using the newer formatted strings, thanks to Gábor Fekete: ``` lambda s:f"Hi{s[3:]}, I'm Python!" ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYKk3JI7O6ONrYKrZWR8FTPVchAKxKUel/QVFmXolGmoYSSDRRITE3sSozL11JU/M/AA "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/) `-p`, ~~32~~ ~~27~~ 26 bytes -5 bytes by leveraging [Nick Kennedy's Jelly answer](https://codegolf.stackexchange.com/a/185874/52194). -1 byte from splitting on a different point in the string. Also realized my old bytecount was wrong. ``` ~/m/;$_="Hi#$', I'm Ruby!" ``` ### Explanation ``` # -p gets line of input and saves to $_ ~/m/; # Find first 'm' in $_ using regex $_="Hi#$', I'm Ruby!" # Save modified string to $_ # ($' is the string AFTER the most recent regex match) # -p outputs $_ to screen ``` [Try it online!](https://tio.run/##KypNqvz/v05fQd9aJd5WySNTQVlFXUfBUz1XIQgopaj0/z@InZibWJWZl/4vv6AkMz@v@L9uAQA "Ruby – Try It Online") [Answer] # x86, ~~37~~ 36 bytes ``` 00000000: d1ee ac8a d8c6 0024 adc7 0448 698b d6b4 .......$...Hi... 00000010: 09cd 21ba 1901 cd21 c32c 2049 276d 2078 ..!....!., I'm x 00000020: 3836 2124 86!$ ``` Unassembled: ``` D1 EE SHR SI, 1 ; point SI to DOS PSP (80H) AC LODSB ; load string length into AL, advance SI 8A D8 MOV BL, AL ; put string length into BL C6 40 24 MOV BYTE PTR[BX][SI], '$' ; add string terminator to end of string AD LODSW ; advance SI two chars C7 04 6948 MOV WORD PTR[SI], 'iH' ; replace second and third char with 'Hi' 8B D6 MOV DX, SI ; load offset for INT 21H string function B4 09 MOV AH, 9 ; display a '$'-terminated string function CD 21 INT 21H ; call DOS API BA 0119 MOV DX, OFFSET S ; load offset for second part of string CD 21 INT 21H ; call DOS API C3 RET ; return to DOS S DB ", I'm x86!$" ``` A standalone executable DOS program. Input from command line, output to screen. [![enter image description here](https://i.stack.imgur.com/yKsur.png)](https://i.stack.imgur.com/yKsur.png) \* The exact "language" name here is a little ambiguous as CPU machine code isn't really a language in a formal sense. Going with "x86" as a generally understood and accepted name for the target platform. [Answer] # R ~~45~~ ~~44~~ 39 bytes @Giuseppe Edit ``` sub("I'm(.*)","Hi\\1, I'm R",scan(,"")) ``` --- @AaronHayman Edit ``` function(s)sub("I'm (.*)","Hi \\1, I'm R",s) ``` --- [Try it online!](https://tio.run/##VcuxCsIwEIDh/Z7iOAdzEgPdXQVdnbukIU0D7SlJAxbx2WOLOLh@P3@qPZ6O2Bdxc7yLyvzKzsqfGWM411w6Rdf9pMyBSdMltm2jcQW8kd4epYmY6xt2eH7a6TF6bKBXTsG2ocWhSEgLhrKQ/loqIlHC2ro442hn/yuDT56AGQDqBw) [Answer] # Java, 36 bytes ``` s->"Hi"+s.substring(3)+", I'm Java!" ``` [Try it online.](https://tio.run/##jZGxbsIwEIb3PMXVC4nAWTqidoZKpQNj1eFw3GCI7eA7B0GVZ08dFHWsspzs8/fdb@lO2KE8VedBNUgE72jcTwZgHOvwjUrDbrwC7DkYV4PKpwMV69Tvs1SIkY2CHTh4gYHkq9gYsaSS4oEecP5cLMUKtgsLbynuSQzr0WvjoUnepHfeVGBT/JTw@QVYTNk3Ym1LH7ls0xM3LnelysU4EC3eEy2Kx3/@Z9kEXc0ij9HV4TYLRWiDrwNaq8NM4RI1sfFOXoPh2daeUZ3lR5f20vir/PP6rB9@AQ) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 267 bytes ``` [S S S T S S T S S S N _Push_72_H][T N S S _Print_as_character][S S S T T S T S S T N _Push_105_i][T N S S _Print_as_character][S S S N _Push_0][S N S _Duplicate_0][S N S _Duplicate_0][T N T S _Read_STDIN_as_character][T N T S _Read_STDIN_as_character][T N T S _Read_STDIN_as_character][N S S N _Create_Label_INPUT_LOOP][S S S N _Push_0][S N S _Duplicate_0][T N T S _Read_STDIN_as_character][T T T _Retrieve][S N S _Duplicate_input][S S S T S T S N _Push_10][T S S T _Subtract][N T S S N _If_0_Jump_to_Label_TRAILING][T N S S _Print_as_character][N S N N _Jump_to_Label_INPUT_LOOP][N S S S N _Create_Label_TRAILING][S N N _Discard_top][S S T T S S S T S T N _Push_-69_!][S S T T N _Push_-1_e][S S T T T N _Push_-3_c][S S T T S T N _Push_-5_a][S S S T S T S N _Push_10_p][S S S T T S T N _Push_13_s][S S T T N _Push_-1_e][S S S T T T S N _Push_14_t][S S S T T N _Push_3_i][S S S T S N _Push_2_h][S S T T T T T N _Push_-15_W][S S T T S S S T T S N _Push_-70_space][S S S T T T N _Push_7_m][S S T T T T T T T N _Push_-63_'][S S T T T T S T N _Push_-29_I][S T S S T T N _Copy_0-based_3rd_-70_space][S S T T T T S T S N _Push_-58_,][N S S T N _Create_Label_PRINT_TRAILING_LOOP][S S S T T S S T T S N _Push_102][T S S S _Add][T N S S _Print_as_character][N S N T N _Jump_to_Label_PRINT_TRAILING_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done. [Try it online](https://tio.run/##RU5BDsMwCDubV3Dbqa/YYdozqpZpk1p1Wiv1@SkxJEsIAmObnO/PYft3nKwUVQVDBaL1AERaK349vO@PQEwIgVB18SK0aecUSarQmSSWTJGJhFp7jwDRwKCEqumYktYmvaou@G@ifS1zB6W0iH9CSnneVh31vs02PLblNdhPLg) (with raw spaces, tabs, and new-lines only). **Explanation in pseudo-code:** ``` Print "Hi" Read three characters from STDIN, and do nothing with them Start INPUT_LOOP: Character c = STDIN as character If(c == '\n'): Call function PRINT_TRAILING Print c as character Go to next iteration of INPUT_LOOP function PRINT_TRAILING: Discard the top of the stack (the c='\n' that was still on the stack) Push "!ecapsetihW m'I ," one character at a time Start PRINT_TRAILING_LOOP: Print as character Go to next iteration of PRINT_TRAILING_LOOP ``` The characters of `", I'm Whitespace!"` are pushed in reversed order, and then printed in a loop. All values of these characters are also lowered by 102, which are added in the loop before printing to save bytes. This constant 102 to lower each character with is [generated with this Java program](https://tio.run/##bVJba8IwFH73V5zlZQnR4mAyZg2isIfC3MO6GzgZaY0aV2vXHAUZ/vYutdbWbS8tPd81J13KrWwtp59ZFkbSGBhJHX83AJJNEOkQDEq0r@1aT2FlIepjquP5eAKS5TSAYgCpMpsIQYActyfuAdExglnJKFImB7wY1Vylzmjw9vEyuH@@a4Inbjpu3aWkP5ZuhBT4bJ3S3E8Lz9W9q07b1ZwfG1QdBCFNbCaiVBW6YIcKgm7R0JkrHNqBoewkB0BBfJ9wGrR0r90nT6RLfMLcE17Gh93yFLge6limuyKa5igbSVw4MjC5DWP/J9ksLsLe9W3fJnRtUhWyb9Qo5OE9rmGpoOior42MDE2Y1VrY6pHxtCIlAsuP0kvPaOpEKp7jgjLonRZca/Rn5zXH2vVVNhXs2bk@jyye/s6gWjnrDTqJ3Q9GMSWFXBBemnLi2vsk3OPEnvVo@1tJz@sdWPvGPssy@/tcruB1oe2KExmqix8). Also, instead of pushing the value `-70` for both spaces twice, the second space in `"!ecapsetihW m'I ,"` is copied from the first with the Copy builtin to save a few bytes. [Answer] # [PHP](https://php.net/), ~~34~~ 32 bytes ``` Hi<?=substr($argn,3)?>, I'm PHP! ``` [Try it online!](https://tio.run/##PcrBCgIhFIXhfU9hEFQwrtpO4y5mVg30BLdyVEq9XbWhHj5DiVbn4@egxpx704p9SOcQabMCUq7ZbUXXsGFt2diPy9wK1MhEl0sBC2/j1KI4GpLXKp2colflBLEuMCSvCKyV9AuPJEM03vGZTPzXU4TLjR@fkqa7n7mkj8fyCpkfvg "PHP – Try It Online") Input via `STDIN`, call with -F. ``` $ echo I'm a Stack-Overflow-er|php -F dad.php Hi a Stack-Overflow-er, I'm PHP! $ echo I'm hungry|php -F dad.php Hi hungry, I'm PHP! ``` [Answer] # IBM/Lotus Notes Formula Language, ~~61~~ 62 bytes +1 because I hadn't noticed the `!` at the end of the output. ``` "Hi"+@Right(i;"I'm")+", I'm IBM/Lotus Notes Formula Language!" ``` Computed field formula that takes it's input from an editable field `i`. It would fail for "I'm an I'm" but since that wouldn't make any sense at all I'm assuming that it won't happen. Shame that at 32 bytes, the name of the language is more than half the total length of the formula! Screenshot below showing an example input and output: [![enter image description here](https://i.stack.imgur.com/3O5Vh.png)](https://i.stack.imgur.com/3O5Vh.png) [Answer] # [Perl 5](https://www.perl.org/) `-p`, ~~31~~ 24 bytes *Cut down based on clarifications from OP and a suggestion from @NahuelFouilleul.* ``` / /;$_="Hi $', $` Perl!" ``` [Try it online!](https://tio.run/##K0gtyjH9/19fQd9aJd5WySNTQUVdR0ElQSEAKKGo9P@/p3quQklmUWrKv/yCksz8vOL/ur6megaGBv91CwA "Perl 5 – Try It Online") [Answer] # sed (`-r`), ~~31~~ ~~28~~ 25 bytes -3 bytes thanks to Shaggy -3 bytes because `-r` not needed in output ``` s/I'm(.*)/Hi\1, I'm sed!/ ``` [TIO](https://tio.run/##K05N@f@/WN9TPVdDT0tT3yMzxlBHAchTKE5NUdAtUtT//x/ES1QoLE0tLsnMz9MtL8osSS36l18A4hX/1y0CAA) [Answer] ### TeX, ~~48~~ ~~43~~ 30 bytes Yes I *could* save a byte by writing `TeX` instead of `\TeX`, but it seems a shame. ``` \def\s[#1]#2#3#4{}\def~[#1]{Hi\s[]#1, I'm \TeX!} ``` **Update:** saved ~~3~~ 5 bytes thanks to [fixed pattern matching](https://codegolf.stackexchange.com/a/123916/9174). ``` \def\s[]I'm{}\def~[#1]{Hi\s[]#1, I'm \TeX!} ``` **Update:** -13 bytes (thanks, Jairo A. del Rio). ``` \def~I'm #1~{Hi #1, I'm \TeX!} ``` Test file ``` \def~I'm #1~{Hi #1, I'm \TeX!} ~I'm amazing~ ~I'm hungry~ ~I'm tired~ ~I'm fat~ ~I'm a programmer~ ~I'm a question-writer~ ~I'm a Stack-Overflow-er~ \bye ``` Output: [![Hi amazing, I'm TeX! Hi hungry, I'm TeX! Hi tired, I'm TeX! Hi fat, I'm TeX! Hi a programmer, I'm TeX! Hi a question-writer, I'm TeX! Hi a Stack-Overflow-er, I'm TeX!](https://i.stack.imgur.com/yBBTE.png)](https://i.stack.imgur.com/yBBTE.png) [Try it online!](http://tpcg.io/lu4hxRhY) [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` `Hi{s3}, I'm Japt! ``` When Japt's string compression library achieves a 0% compress rate... [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=YEhpe3MzfSwgSSdtIEphcHQh&input=WyJJJ20gYW1hemluZyIsCiJJJ20gdGlyZWQiLAoiSSdtIGh1bmdyeSIsCiJJJ20gZmF0IiwKIkknbSBhIHByb2dyYW1tZXIiLAoiSSdtIGEgcXVlc3Rpb24td3JpdGVyIiwKIkknbSBhIFN0YWNrLU92ZXJmbG93LWVyIl0) Another 18-byte alternative: ``` `Hi{Ť}, {¯4}Japt! ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 35 bytes ``` @(s)["Hi" s(4:end) ", I'm Octave!"] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1gzWskjU0mhWMPEKjUvRVNBSUfBUz1XwR@sTFEp9n@ahhJIIDE3sSozL11JkwsmoFBQlJ9elJibm1qkpPkfAA "Octave – Try It Online") ``` @(s) % Anonymous function taking a string input [ ] % Concatenate everything inside the brackets "Hi" ", I'm Octave!"] % The fixed parts of the output string s(4:end) % The input, except "I'm" % Returns the concatenated string ``` ### 42 bytes: I tried retrieving "Octave" somehow, without writing it out, since 6 chars is quite a lot compared to some of the other language names here. Unfortunately, I could only find `ver`, which outputs a struct with comma separated fields. [Takes way more than 6 bytes. :(](https://tio.run/##y08uSSxL/f8/JbO4QEO9LLXISl2TC8wBsjW5uAqKMvNK0jTUY/KAfD2/xNxUq5i8mDygIi6YALKimLxqmHBttWGtFVglitD//wA) ``` @(s)["Hi" s(4:end) ", I'm " {ver.Name}{1}] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1gzWskjU0mhWMPEKjUvRVNBSUfBUz1XQUmhuiy1SM8vMTe1ttqwNvZ/moYSSDwxN7EqMy9dSZMLJqBQUJSfXpSYm5tapKT5HwA "Octave – Try It Online") [Answer] # [Malbolge](https://github.com/TryItOnline/malbolge), 24477 bytes Mors sum, Dominus Pestifer Mundi *Hi, Dominus Pestifer Mundi, I'm dad!* ``` bP&A@?>=<;:9876543210/.-,+*)('&%$T"!~}|;]yxwvutslUSRQ.yx+i)J9edFb4`_^]\yxwRQ)(TSRQ]m!G0KJIyxFvDa%_@?"=<5:98765.-2+*/.-,+*)('&%$#"!~}|utyrqvutsrqjonmPkjihgfedc\DDYAA\>>Y;;V886L5322G//D,,G))>&&A##!7~5:{y7xvuu,10/.-,+*)('&%$#"yb}|{zyxwvutmVqSohmOOjihafeHcEa`YAA\[ZYRW:U7SLKP3NMLK-I,GFED&%%@?>=6;|9y70/4u210/o-n+k)"!gg$#"!x}`{zyxZvYtsrqSoRmlkjLhKfedcEaD_^]\>Z=XWVU7S6QPON0LKDI,GFEDCBA#?"=};438y6543s1r/o-&%*k('&%e#d!~}|^z]xwvuWsVqponPlOjihgIeHcba`B^A\[ZY;W:UTS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?>=~;:987xv4-,1rp.omll#('h%e{z!b`|_]yx[vXnmrUSonQlNdchKIeHFbEC_B@??TYXW:9TMR5PO2ML.JI,*F?>C&$@#!=~|:{y7xv4us1rp.om+ljii~%$#dc~}v_]]\wvunsVqponQlkMiLJfeHcE[Z_B@\?=YX;9UNMR53O20L/-I,*F)'C&$@?>!~;:927xvvu210/.',m*)('h%$d"ca``uzy\ZvonsVTSShmlOjLbafIGcFD`CA]@>Z=;W:8T75QPO21LKJIHAF)''&A@?>=<;49z76w432rr).-n+k#"'hf$#d!awv{^\x[YutWrTjinQONNchgJeG]\aDBAAV[Z=X:POT75Q42NM0K-CBG*(''<A@?"!<;:9876/4u210/.n&+*)(h~g|#"!x}v{^yxwvYtsUqTRnQOkjMKg`_dGEaDB^A?[><X;9U86R5322GLKJ-,AF)DC&A@">!};|z8ywvv-21rp.'&+lj('hf${z!b`|_]y\ZvYWsVTSShmlkNMhg`eHFFE`_^]V[>YXWV9TS5Q42N1/..CHG*E'=<A$">!};|z8yw5vt2sq/pn,+*kj'&%${"caa`{zyxwvotWrqTonPlOMiLJfIGcFD`_B]?UTY<:VU8S5KJO20L/-I,*F)'C&$##8=<}:z216wu321rq.-,+*)"'hffe"!~}|{zyrwZutWrqponQOkdchKIeHFbEC_^A\>TSX;988MRQ42NGFK.,H+)E(&B%#?"~<;:{z76543210).o,+*)(h~%$#"bxav{zyrwpuXsrUponmlOMibafIGcFD`CA]\?Z<RQV97S6433HML/J,BAF)'CBA$#>7<}{{z765.3t10q.-m+lj('h%e{z!b`|{^y[qpuXVrUSRRglkNiKa`eHFEEZ_^A?[TSX;9U86R53O20L/-IHG*)DCB;@#>=~;:z8yw5vt2sq/pn,mk)(ig%|{"ca}`^z][wZXtWUTTinmlONihgfe^cFa`C^]?[><;;PUT7R4JIN1/K.,H+)E(&B%#?"~<}{9zx654ut10/.-,+$)j'&%$#cy~}|{]s\qputsrkpSQQPejMhgJedcEEZ_^A?[TSX;988MRQ42NGFK.,HG*E'=<A$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KmxE6m5qtXDt@AG1KY92NjJTjT3CZHp4STOfTkWc@1c3c9vzb3PvHkPJ1cm3KmLdmYQ/5pt9Lex5yu7nx5dK7AdqKu9yNGsvzrvu/K03ONFnGbV5z/6g82DzMb6@8TbcnsptvDt2567ea/tN7vJ1d3xTiUagYLw0b85e8W97weWoCTHz4DPAMZ5PC/lp/3Vn@Xvs8V88@RorntdnS9fpVrulYTr9tR/EqnlsqFgcB1o3NtZOx47XvA1G/16L9js7u2tXLgq0e@FO1@/2Otl86ue8vLlYqs1gHzda9wc5bA2XbmgehTX7053jt9yuexBKH2VSsFpSHhO3ZHaR@4deOTFRWplb7mb9w@it83wzHR6qpqaAC7mWlr8vv/6PAm9T2fXJo8nHlPt0sKD7262OX0zVfNU3eWxy5/Sd/HzrJ/vHb/mXg6fMhupVOseV/d/bR/l/vknOdn@v@5r9aUHrcF/AA "Malbolge – Try It Online") [Answer] # JavaScript, ~~38~~ 37 bytes ``` x=>`Hi${x.slice(3)}, I'm JavaScript!` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvu/wtYuwSNTpbpCrzgnMzlVw1izVkfBUz1XwQuoMhisUjHhf3J@XnF@TqpeTn66RpqGEkg@MTexKjMvXUlT8z8A) [Answer] # [Rust](https://www.rust-lang.org/), 41 bytes ``` |x:&str|print!("Hi{}, I'm Rust!",&x[3..]) ``` [Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6FZzZWTWqKQpmCr8L@mwkqtuKSopqAoM69EUUPJI7O6VkfBUz1XIQioRVFJR60i2lhPL1bzvzVXmoaaEkgmozQvvahSSdOaq/Y/AA) [Answer] ## Batch, 22 + 3 = 25 bytes ``` @echo Hi %*, %0 Batch! ``` +3 bytes for naming this file `I'm` (with the required `.bat` extension for Batch files). Invoke as `I'm hungry`, when it will echo `Hi hungry, I'm Batch!`. [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~30 28~~ 27 bytes ``` {S/.../Hi/~", I'm Perl 6!"} ``` [Try it online!](https://tio.run/##NcqxDsIgFIXhvU9x7FA1Udi6uetm4hOQCHiTAvVCY7Cpr46KcfvynzNqHvriMjqDQ5kvUgghjyRf7Q6ntcP5s6NftUsxgbEZyOu4xdwAUWWIzjRL@f4URg6WlXOam1@4TzomCn7/YEr/6tSTvK1OxPpadZu85VxpVHoD "Perl 6 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḋa⁾Hi“'ṫṗḶ/÷!Ṗ» ``` A full program accepting a (Python formatted) string argument which prints the result. **[Try it online!](https://tio.run/##ATkAxv9qZWxsef//4biKYeKBvkhp4oCcJ@G5q@G5l@G4ti/DtyHhuZbCu////0knbSBhIHByb2dyYW1tZXI "Jelly – Try It Online")** ### How? ``` Ḋa⁾Hi“'ṫṗḶ/÷!Ṗ» - Link: list of characters e.g. "I'm a programmer" Ḋ - dequeue "'m a programmer" ⁾Hi - pair of characters "Hi" a - logical AND (vectorises) "Hi a programmer" “'ṫṗḶ/÷!Ṗ» - list of characters ", I'm Jelly!" - - since this is a new leading constant chain the previous result - is implicitly printed (with no trailing newline) - program result is implicitly printed (again with no trailing newline) ``` Note: `Ḋ⁾Hio...` works too. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 17 bytes ``` ṫ4;“'ṫṗḶ/÷!Ṗ»⁾Hi; ``` [Try it online!](https://tio.run/##AUIAvf9qZWxsef//4bmrNDvigJwn4bmr4bmX4bi2L8O3IeG5lsK74oG@SGk7////SSdtIGEgU3RhY2stb3ZlcmZsb3ctZXI "Jelly – Try It Online") A monadic link taking the input as its argument and returning a Jelly string. ### Explanation ``` ṫ4 | everything from 4th character on ;“'ṫṗḶ/÷!Ṗ» | concatenate ", I’m Jelly!" to the end ⁾Hi; | concatenate "Hi" to the beginning ``` [Answer] ## VBA (Excel), 27 ~~28~~ bytes ``` ?"Hi"Mid([A1],4)", I'm VBA! ``` Input goes in cell A1 of the Active Sheet in Excel, run code in the Immediate Window Takes advantage of the fact that `"SomeString"SomeValue` and `SomeValue"SomeString"` will implicitly concatenate, and that omitting the third argument from the `MID` function will take all characters from the end of the input - turning it into a "dump initial characters" function (-1 byte thanks to Shaggy, but +1 when OP confirmed that all answers should end with an exclamation mark) (-1 byte thanks to Taylor Scott reminding me that the final double-quote was optional) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 28 25 bytes ``` $1="Hi",$0=$0", I'm AWK!" ``` [Try it online!](https://tio.run/##SyzP/v9fxdBWySNTSUfFwFbFQElHwVM9V8Ex3FtR6f9/EDNRoaAoP70oMTc3tQgA "AWK – Try It Online") This program modifies the contents of field "$1" and "$0" in a range pattern. Because no actions are specified after the pattern, the default action `{print $0}` is executed. [Answer] # [J](http://jsoftware.com/), 22 bytes ``` ', I''m J!',~'Hi',3}.] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1XUUPNXVcxW8FNV16tQ9MtV1jGv1Yv9rcqUmZ@QrpCmog2UTcxOrMvPS1VFFSzKLUlPQxBIVCory04sSc3NTi9T/AwA "J – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ 21 bytes Saved 2 bytes thanks to *Kevin Cruijssen* ``` ',«#À„Hiš"05AB1E!"ªðý ``` [Try it online!](https://tio.run/##ATcAyP9vc2FiaWX//ycswqsjw4DigJ5IacWhIjA1QUIxRSEiwqrDsMO9//9JJ20gYSBwcm9ncmFtbWVy "05AB1E – Try It Online") **Explanation** ``` ',« # append "," # # split on spaces À # rotate left „Hiš # prepend "Hi" "05AB1E!"ª # append the language name ðý # join on spaces ``` ]
[Question] [ The title says it all. Your goal is to write a program that forms a w×h rectangle of characters that can be rotated and re-run to output the number of 90° Counter-Clockwise (CCW) rotations that have been done. For example, if the 3×2 program ``` abc def ``` solved the problem, it would initially output 0, and successive rotations of 90° CCW ``` cf fed da be cba eb ad fc ``` would output 1, 2, and 3 respectively. Using comments makes this a trivial task is most languages. In Ruby for example, it can be done in a 7×7 rectangle: ``` ###p### ### ### ###1### p 0#2 p ###3### ### ### ###p### ``` The challenge is to do this **without** any sort of comments. **Scoring** Your score is w\*h, the area of your rectangle. Newlines are excluded. In other words, code-golf, newlines not counted. The score for the Ruby example is 49 (though of course it is invalid since it has comments). **Notes** * Your code must really be rectangular with no missing characters at the end of lines. * If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc. * The output may go to the console or into a file. * Standard loopholes apply. I hope this, my first question, really intrigues some people. Enjoy! [Answer] # APL (1x3 = 3) ``` 5!3 ``` This solution uses the extra rule that any output that is correct mod 4 works. In APL, `x!y` is the number of way to choose `x` elements from `y`, commonly known as `binom(y,x)` or `choose(y,x)`. Let's check that each rotation gives the right answer. **0 rotations** ``` 5!3 ``` There's no way to choose 5 elements from 3, so we get 0, which is automatically printed. **1 CCW rotation** ``` 3 ! 5 ``` APL happily evaluates each line, getting the number `3`, the operator `!`, and then the number `5`, printing only the last of these (`5`), which is 1 mod 4. **2 CCW rotations** ``` 3!5 ``` This is `binom(5,3)`, which is `(5*4*3*2*1)/(3*2*1)/(2*1) = 10`, which is 2 mod 4. **3 CCW rotations** ``` 5 ! 3 ``` As before, only the last-evaluated value of `3` is printer. I don't actually know APL, so please tell me if I got any of the explanation wrong. I found it by trial and error as the first language on [this site](http://compileonline.com/) that: 1. Automatically prints the result of an expression 2. Given multiple lines of expressions, only outputs the last one 3. Has no issue with an operator standing alone on a line 4. Takes operators infix 5. Has a single-character arithmetic binary operator that is asymmetric (aRb != bRa), and flexible enough to return a variety of numbers. For (5), I went down the list of APL [dyadic functions](http://en.wikipedia.org/wiki/APL_syntax_and_symbols#dyadic_functions). My first candidate operation was the integer division `/` of C and Python 2, but APL division `÷` gives floats. Exponentiation is tempting, but fails because `a` and `a^b` have the same parity but are gotten by consecutive rotations (unless `b=0`, but then `b^a=0`). Boolean operators like `<` give `0` and `1` 180 degrees apart, which doesn't work. Finally, I found the binomial operator `!` and tried numbers until I got some that work. Thanks to Quincunx for his confidence that there exists a smaller solution than 2x2. [Answer] ## Ruby, 7×9 (63) ``` 30;p 0||p=p 0|0;p;p ;p;p|p; p=p ||0 ;p p; 2||p =p 00;1 p ``` A bit longer than the other solution, but at least this solution doesn't depend on any implicit printing or rule abuse. For all four rotations, the full code is parsed and other than some short-circuiting, all of it is executed. Surprisingly, there's absolutely no symmetry in the code This solution relies on the fact that it's still possible to call the `p` function (which is used to print the numbers) even if a variable with the same name has already been defined. For example, something like `p p` calls the function `p` with the variable `p` as argument (thus, printing the value of `p`). Explanation for some of the common expressions used in the code: * `p`: As mentioned above, this is either a function call or a variable. When the variable is not defined, this calls the function `p` without arguments, which does nothing and returns `nil`. * `p p`: Prints the variable `p`. * `p|x`: When `p` is the function, this is identical to `nil|x`, which returns true/false depending on the value of `x`. If `p` is an integer, it's bitwise or. Either way, this statement has no side effect. * `p=p||x`: Effectively the same as `p||=x` (conditional assignment) with the advantage of being syntactically valid and a no-op when reversed. ### Symmetric version (9×10 = 90) ``` p 0 * 0 00100 0||2* p p *0||0 00300 0 * 0 p ``` This is the shortest symmetric solution (C2 when ignoring the numbers to print) I could come up with. ### Test script Here's a test script to verify the code above (the `#` at the line ends have been added so that the whitespace doesn't get stripped and are removed before execution): ``` rotate=->s{s.split($/).map{|i|i.chars.reverse}.transpose.map(&:join).join($/)} s=<<EOD.gsub(?#,"") 30;p # 0||p=p # 0|0;p;p# ;p;p|p;# p=p ||0# ;p p;# 2||p =p# 00;1 # p # EOD puts ">>> 0°" eval s puts ">>> 90°" eval rotate[s] puts ">>> 180°" eval rotate[rotate[s]] puts ">>> 270°" eval rotate[rotate[rotate[s]]] ``` [Answer] # Python - 23 x 23 = 529 Ok, this question has already a winner, but there is no Python solution, yet. So I thought about it - heavily! - and found a way to make the bulky `print` command working in any direction without producing errors when parsed from one of the other directions. The breakthrough was the following line: ``` '"\'';forward_code;"';backward_code;""\'"'' ``` While the `forward_code` is executed, the `backward_code` is part of a string and thus not printed. This is exactly the other way around when reading backwards. So combined with two more directions and fine-tuned to get all quotes matching correctly I end up with the following solution: ``` ''"''""''"''"''"'"''""' " "" " " \\ " '"\'';print 1;"'""\'"'' '"\''"';3 tnirp;""\'"'' " ;"" " " p' " ' r; ' ' i2 ' " n " " tt " ' n ' ' 4i ' " ;r .-=<>=-. " ' \"p /__----__\ ' " ';' |/ (')(') \| " " "" \ __ / " ' "" .`--__--`. ' " \\ / :| \ " ' '' (_) :| (_) ' ' "" |___:|____| ' " '' |_________| " ''"''""''"''"''"'"''""' ``` **Edit:** I found a way to deal with all that whitespace. ;) [Answer] # GolfScript, 4 (2x2) ``` 43 12 ``` Prints `4312` which is `0` (mod 4). The rotations print `3241` (1 mod 4), `2134` (2 mod 4), and `1423` (3 mod 4). Prompted by: > > If you wish you may output other legal "mod 90°" values instead of 0 1 2 3. So 8 is fine instead of 0, and -1 is fine instead of 3, etc. > > > There are actually many sets of numbers for which this works. I found these with this Python program: ``` def f(a,b,c,d): return int("%i%i%i%i"%(a,b,c,d)) for a in range(10): for b in range(10): for c in range(10): for d in range(10): candidate = f(a,b,c,d) % 4 == 0 candidate &= f(b,d,a,c) % 4 == 1 candidate &= f(d,c,b,a) % 4 == 2 candidate &= f(c,a,d,b) % 4 == 3 if candidate: print("%i, %i, %i, %i"%(a,b,c,d)) ``` Although the program outputs `0`s (which probably wouldn't work), the valid solutions are of the form ``` ab cd ``` Where `a∈{4,8}`, `b∈{3,7}`, `c∈{1,5,9}`, `d∈{2,6}`. IE `(a,b,c,d)∈{4,8}×{3,7}×{1,5,9}×{2,6}` which is 24 solutions. [Answer] # BASIC, 64 Won't win, but here it is anyway. (Tested in [Chipmunk Basic](http://www.nicholson.com/rhn/basic/)) ``` ?0:END:? :::::::1 D::::::: N::::::E E::::::N :::::::D 3::::::: ?:DNE:2? ``` Note: `?` is shorthand for `PRINT` in various dialects of BASIC. Although there are lots of syntax errors in the code, the `END` statement in the first line prevents them from being seen by the interpreter. [Answer] # [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 9 characters (3x3) ``` 0 1 3 2 ``` In pyth, everything is printed by default, unless it is preceded by a space. Lines after the first line are for user input, and are not evaluated in this program. Another way to get 9 characters: ``` "0" 3 1 "2" ``` --- # [Pyth 1.0.5](https://github.com/isaacg1/pyth/blob/0ca956532f9e720f208da6c419cc2ff8e69576d3/pyth.py), 4 characters While recent changes to pyth have made 2 digit numbers harder to generate (A change that I am considering reverting), older versions of Pyth have easy two digit number generation, which, combined with the implicit printing and the fact that all lines but the first are ignored, gives the following solution: ``` 32 41 ``` Prints 32,21,14,43. [Answer] # Befunge, 16 ``` 0.@1 @@@. .@@@ [[email protected]](/cdn-cgi/l/email-protection) ``` **Explanation:** Digits from `0` to `9` push the corresponding number onto the stack, `.` pops a value from the stack and prints it as an integer, and `@` ends the program. (tested [here](http://www.compileonline.com/compile_befunge_online.php)) [Answer] # Piet, 49 ![A Piet Program](https://i.stack.imgur.com/qIMtF.png) I made a point only to use yellow and red colors, and to try and make it roughly symmetrical. When rotated, it prints 0, 1, 2 or 3. Exiting the program in Piet is hard, and takes up around half the space in the picture, unfortunately. [Answer] # [GNU dc](http://www.gnu.org/software/bc/manual/dc-1.05/), 6 (3x2) I think this is the shortest answer not to require the "mod 90°" rule-relaxation: ``` 3z1 0p2 ``` Outputs `0`, `1`, `2` or `3` for each rotation. For the `0`, `2` and `3` rotations, the `p` simply pops and prints the last number literal to have been pushed to the stack. For the `1` rotation, the `z` pushes the current stack depth (1) to the stack, then the `p` pops and prints it. [Answer] # GolfScript, 9 (3x3) ``` 0}1 } } 3}2 ``` Sort of abusing the rules. The `}` happens to end the program if there is no matching `{`, and the contents of the stack are printed at program end. [Answer] ## JavaScript, 4 ``` 03 12 ``` When you execute this program (or a rotation of this program) in a javaScript console, only the last line is evaluated and echoed in the console. So: ``` 12 modulo 4 == 0 01 modulo 4 == 1 30 modulo 4 == 2 23 modulo 4 == 3 ``` Here are all the similar 2x2 programs that work too: ``` 03 12 03 16 03 52 03 56 03 92 03 96 07 12 07 16 07 52 07 56 07 92 07 96 43 12 43 16 43 52 43 56 43 92 43 96 47 12 47 16 47 52 47 56 47 92 47 96 83 12 83 16 83 52 83 56 83 92 83 96 87 12 87 16 87 52 87 56 87 92 87 96 ``` In other terms, ``` ab cd ``` where a is in [0,4,8], b is in [3,7], c is in [1,5,9], and d is in [2,6] [Answer] # CJam / GolfScript - 3\*3 ``` 2;3 ;7; 1;0 ``` The semicolon pops the previous number, thus only the bottom right corner is printed. [Answer] # [Aheui](http://esolangs.org/wiki/Aheui), 8 ``` 바몽희뷸 뷷희몽반 ``` Since Aheui does not have a letter that pushes 1 onto the stack, I decided to print 0, 5, 2, and 3. Explanation: 바 and 반 push 0 and 2, respectively, onto the stack and moves the cursor right by one character. 뷸 and 뷷 push 5 and 3, respectively, onto the stack and moves the cursor down by two characters. 몽 pops and prints the number in the stack and moves the cursor up by one character. 희 terminates the program. [Answer] ## JavaScript (Entered in browser console, shell or another REPL, so result is printed) ``` 1+2 -3- 4+5 ``` Should work for any other language with expressions, non-significant newlines and automatic printing of the result. [Answer] # Matlab/Octave - ~~144~~ 100 ## Golfed: 10 x 10 = 100 ``` ....d..... ....i..... ....s..... ... p2 ... disp 1... ...3 psid ... 4p ... .....s.... .....i.... .....d.... ``` ## Alternative solution: 15 x 15 = 225 ``` .......d....... .......i....... .......s....... ... p ... ... ... ... 4 ... ... . ... disp 1...3 psid ... . ... ... 2 ... ... ... ... p ... .......s....... .......i....... .......d....... ``` [Answer] ## Perl 5x7 (35) ``` 1+p+t+1 -print+ 1+i+i+1 +tnirp+ 1+t+p+1 ``` A bit late to the party. The solitary `-` determines which number is printed. [Answer] # Befunge, 12 (6x2) I Managed to come up with a slight improvement on the existing Befunge answer by making the most of Befunge's two-dimensional nature and having the code path run vertically in two of the orientations. ``` [[email protected]](/cdn-cgi/l/email-protection) [[email protected]](/cdn-cgi/l/email-protection) ``` Try it online: [Starting 0](http://befunge.tryitonline.net/#code=MC5ALjF2CnYzLkAuMg&input=), [Rotation 1](http://befunge.tryitonline.net/#code=djIKMS4KLkAKQC4KLjMKMHY&input=), [Rotation 2](http://befunge.tryitonline.net/#code=Mi5ALjN2CnYxLkAuMA&input=), [Rotation 3](http://befunge.tryitonline.net/#code=djAKMy4KLkAKQC4KLjEKMnY&input=). [Answer] # JavaScript, 3 ``` 2 1 4 ``` It works... in base 7. Base 9 version: ``` 2 7 0 ``` --- **Explanation** When run interactively, e.g. from a debugging console, the value of the last statement/expression will be output. *47* = *410* ≣ *0* (mod *4*) *4127* = *20510* ≣ *1* (mod *4*) *27* = *210* ≣ *2* (mod *4*) *2147* = *10910* ≣ *3* (mod *4*) Similar solutions could be found for any odd base. [Answer] # Marbelous, 7\*14 = 98 ``` .. \/ \/ .. .. .. 31 \\ 32 \/ \/ \\ \/ \\ \/ \/ 30 \\ 33 .. .. .. \/ \/ .. ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 12x10 = 120 Outputs 0, 1, 2, and 3, respectively. ``` ++ > ++++++++++++ ++++++++++++ ++++++++++++ ++++++++++++ .+++++ ++++++++++++ ++++++ +++++ ++++++ +++++ ++++++ +++++ ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fW1sBBuy4tJEAsRyIXj2cyhQIcP7/BwA "brainfuck – Try It Online") [One turn](https://tio.run/##SypKzMxLK03O/v/fThsGuBRIZeppKygoQJgKCFF8TG2szP//AQ "brainfuck – Try It Online") [Two turns](https://tio.run/##SypKzMxLK03O/v9fGwQUwKQ2FwGONjJHTwEMsMgQ5tgpwACQ8/8/AA "brainfuck – Try It Online") [Three turns](https://tio.run/##SypKzMxLK03O/v9fGwgUQIQ2FzamAmGmgoKCth5CVJtUph3X//8A "brainfuck – Try It Online") [Answer] # [Argh!/Aargh!](http://www.sha-bang.de/12_eso/Argh-Spec.txt) (4\*4=16) What was that about using the right tool for the job? There are no comments (in the language in general). The entire family of programs (generated in J: `((|.@:|:) ^: (i. 4)) >'hpqh';'q01p';'p32q';'hqph'` or `((|.@:|:) ^: (i. 4)) 4 4 $ 'hpqhq01pp32qhqph'`) ``` hpqh q01p p32q hqph ``` rotated once: ``` hpqh q12p p03q hqph ``` rotated twice: ``` hpqh q23p p10q hqph ``` rotated three times: ``` hpqh q30p p21q hqph ``` To explain this, it might be best to look at an "indented" version (That also works in all rotations): ``` hhpq h 0 h q 1p p3 q h 2 h qphh ``` This version shows that the program consists of 4 separate parts, one for each individual rotation. * `h` - set control flow left * `p` - print item in data/code raster below it * `q` - quit the program [Answer] # [Floater](http://esolangs.org/wiki/Floater) - 9×5=45 ![enter image description here](https://i.stack.imgur.com/V0Pb8.png) Prints 4, 1, 2, or 3 to console. Note that 'Black' is a valid instruction (NOP), and is syntactic. Without it, it can't find the starting position. Thus, all positions in the rectangle are occupied. [Answer] # [Triangular](https://github.com/aaronryank/triangular), 2x3 => 6 ``` %%3 i%i ``` [Try it online!](https://tio.run/##KynKTMxLL81JLPr/X1XVmCtTNfP/fwA "Triangular – Try It Online") A "rectangular triangular program" - we certainly do live in a society. The base version here prints the top value of the stack (initially 0), then the other two prints are missed due to triangular's execution order. **Rotation 1** ``` i% %% i3 ``` Increments the top value to 1, prints, misses the other two print commands. **Rotation 2** ``` i%i 3%% ``` Increments twice, hits the last print command. **Rotation 3** ``` 3i %% %i ``` Pushes 3 onto the stack, hits a print statement, misses the other two. [Answer] # [Pip](https://github.com/dloscutoff/pip), 2x2 = 4 ``` tv oi ``` [Try it online!](https://tio.run/##K8gs@P@/pIwrP/P/fwA "Pip – Try It Online") All four letters are preinitialized variables; whichever one comes last in the program is autoprinted. * No rotation: `i = 0` * One rotation: `o = 1` * Two rotations: `t = 10` * Three rotations: `v = -1` [Answer] # Python, 18x18 = 324 Uses escaping and mixed quotation marks to change how each string is parsed after rotation. Triple quotes allow the literals to span multiple lines and take up less space. ``` """p ' " r ' " i ' " n'\""",)2(tnirp '''t ' ( \ 3 " ) " , " ' , ' ) ' 1 \ ( " t""" print(0),'''\"n ' " i ' " r ' " p''' ``` Test code (needs to be cleaned up) : ``` with open('./rotpy.py','r') as fh: l=list(fh) ll=max(len(x)for x in l) l=[x[:-1]+' '*(ll-len(x)) for x in l] def r(l): return list(''.join(reversed(z)) for z in zip(*l)) for i in range(4): exec('\n'+'\n'.join(l)) l=r(l) ``` [Answer] # Element, 2x3 = 6 ``` 1* `2 3 ``` This is an improvement over the 3x3 naive solution, which has a ``` in the middle with a number on each side. The 0 case, shown above, is the most interesting, since the `*` is used to multiply the 3 by nothing to get 0. Other than that, it's not that complicated. If you find the space awkward, you can replace it with pretty much any other character, excluding `[]{}`_`. For reference, here are the other three rotations: ``` case 1 *2 1`3 case 2 3 2` *1 case 3 3`1 2* ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 \* 1 = 3 bytes ``` 5zB ``` Try it online: [as-is](https://ethproductions.github.io/japt/?v=2.0a0&code=NXpC&input=), [rotated once](https://ethproductions.github.io/japt/?v=2.0a0&code=Qgp6CjU=&input=), [twice](https://ethproductions.github.io/japt/?v=2.0a0&code=Qno1&input=), [thrice](https://ethproductions.github.io/japt/?v=2.0a0&code=NQp6CkI=&input=). Outputs 0, 5, 2, 11 respectively. The variable `B` holds the value 11, and `Number.z(other)` is floor division (everyone looked for apparently :p). For multi-line code, the last line is passed to output, which is simply a constant here. --- ## 2 \* 2 = 4 bytes ``` 2J 1T ``` Try it online: [as-is](https://ethproductions.github.io/japt/?v=2.0a0&code=MkoKMVQ=&input=), [rotated once](https://ethproductions.github.io/japt/?v=2.0a0&code=SlQKMjE=&input=), [twice](https://ethproductions.github.io/japt/?v=2.0a0&code=VDEKSjI=&input=), [thrice](https://ethproductions.github.io/japt/?v=2.0a0&code=MTIKVEo=&input=). Outputs 0, 21, 2, -1 respectively. `T` holds 0, and `J` holds -1. The trick is that, if two literals or variables are put side-by-side, a comma is inserted and the output is just the last one. [2 \* 2 JS solution](https://codegolf.stackexchange.com/a/33182/78410) works in Japt too. [Answer] # [MAWP](https://esolangs.org/wiki/MAWP), 2x2 = 4 ``` 0: 23 ``` -2 characters from Bubbler. The position of the `:` operator determines when things are output, so we can abuse that and position the numbers around it. Bubbler's modification pops the existing 1 from the stack, saving two bytes. [Try it!](https://8dion8.github.io/MAWP/?code=0%3A%0A23%0A%0A%25%25%20stack%20cleanup%0A%0A%3A3%0A02%0A%0A32%0A%3A0%0A%0A20%0A3%3A&input=) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 (2x2) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` YX 3¾ ``` To-the-point approach. [Try it online](https://tio.run/##yy9OTMpM/f8/MoLL@NC@//8B) or [verify all four rotations](https://tio.run/##yy9OTMpM/a/0PzKCy/jQvv9Kh7YdnmXixqWgFFCUn16UmGuloKRjC@T6l5YUlJYAefYuemE6mhf2Bh/admjh4R2H13od2n1om/1/AA). **Explanation:** * `Y` is a variable with default value \$2\$ * `X` is a variable with default value \$1\$ * `¾` is a counter variable with default value \$0\$ So in all four rotations they are all three pushed to the stack, and then output the last integer on the stack is output implicitly as result. An alternative 2x2 is a port of the [*@DLosc*'s Pip answer](https://codegolf.stackexchange.com/a/209398/52210), where `T` = \$10\$ and `®` = \$-1\$: ``` TX ®¾ ``` [Try it online](https://tio.run/##yy9OTMpM/f8/JILr0LpD@/7/BwA) or [verify all four rotations](https://tio.run/##yy9OTMpM/a/0PySC69C6Q/v@Kx3adniWiRuXglJAUX56UWKulYKSji2Q619aUlBaAuTZu@iFudgrKWjk5qfomoAETFTt1TV1NC/sDT607dDCwzsOr/U6tPvQNvv/AA). [Answer] # [Zsh](https://www.zsh.org/), 36 (6x6) ``` <<<0 3 < < < < < < 1 2<<< ``` [Try it online!](https://tio.run/##qyrO@P9fwcbGxkCBy1gBCGy4bDApQy4FI6Aahf//AQ "Zsh – Try It Online"). #### Alternative, (10x10): ``` printf 0 p r 3 i n f t t f n i 1 r p 2 ftnirp ``` Exploits the fact that `printf` only prints the first word, if there are no quotes. ]
[Question] [ Every digital clock contains a small creature that has to advance the time every minute [citation needed]. Due to the popularty of digital clocks and the popularity of catching them in the wild, they are nearly extinct in nature which is why in this challenge we try to automate this task: Given your string of a given time in the 24h format, the task is to advance this time by one minute. ## Details * Both the input and output must be strings. * The time is given as a five character string. * Both the hour and the minutes are given as a two digit number: if the number is below 10, there will be a leading zero. * The two numbers are separated by a colon. ## Examples ``` Input Output 00:00 00:01 00:02 00:03 05:55 05:56 09:59 10:00 12:49 12:50 20:05 20:06 23:59 00:00 ``` [Answer] # Microsoft Excel, 9 bytes ``` =A1+"0:1" ``` Input is in cell `A1`. Tested on my Mac (Excel for Mac version 16.53) and online at Office.com. [![enter image description here](https://i.stack.imgur.com/0xtdx.png)](https://i.stack.imgur.com/0xtdx.png) [Answer] # [Bash](https://www.gnu.org/software/bash/) + [coreutils date](https://www.gnu.org/software/coreutils/manual/html_node/date-invocation.html), 17 ``` date -d$1+min +%R ``` [Try it online!](https://tio.run/##NYlLCoAwDAX3OUUWupJCrGbRegtvUE1AwQ/YgsevVvAtZmDeFOKS72XdFC8NgkljmkPUAfCdnJ@iJjQGq//MEpKikapt9vXAph6znIdmIk8EhRaIPTOQ8@ygtb53YN/OYLtSHg "Bash ‚Äì Try It Online") This assumes everything is in UTC (such as how TIO appears to be set up). If this is not OK, then 4 bytes must be added: --- # [Bash](https://www.gnu.org/software/bash/) + [coreutils date](https://www.gnu.org/software/coreutils/manual/html_node/date-invocation.html), 21 ``` date -ud$1UTC+min +%R ``` [Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYolCSWlySnFicas2lAAQp@WCqOLVEQVdXQQUm@T8lsSRVQbc0RcUwNMRZOzczT0FbNeh/Sn5e6n8DAysDAy4QacRlYGplasplYGllasllaGRlYsllBBQ35TIyBokAAA "Bash ‚Äì Try It Online") [Answer] # x86-16 machine code, ~~61~~ ~~55~~ 54 bytes ``` 00000000: be82 008b fe8b d6ad 86c4 9346 56ad 86c4 ...........FV... 00000010: 4037 0430 3d30 367c 1293 4037 0430 3d34 @7.0=06|[[email protected]](/cdn-cgi/l/email-protection)=4 00000020: 327c 03b8 3030 86c4 abb0 305f 86c4 abb8 2|..00....0_.... 00000030: 2409 aacd 21c3 $...!. ``` Listing: ``` BE 0082 MOV SI, 82H ; SI point to DOS command line tail 8B FE MOV DI, SI ; save pointer to beginning of string for later 8B D6 MOV DX, SI ; save pointer to beginning of string for output AD LODSW ; load hours digits into AX 86 C4 XCHG AL, AH ; endian convert 93 XCHG AX, BX ; save hours in BX 46 INC SI ; skip colon 56 PUSH SI ; save string offset to minutes AD LODSW ; load minutes digits into AX 86 C4 XCHG AL, AH ; endian convert 40 INC AX ; add one minute 37 AAA ; BCD Adjust After Addition! 04 30 ADD AL, '0' ; ASCII fix low digit 3D 3630 CMP AX, '60' ; is minutes wrap around? 7C 13 JL NO_CARRY_HOUR ; if not, skip hours 93 XCHG AX, BX ; move hours into AX 40 INC AX ; increment hours 37 AAA ; BCD Adjust After Addition! 04 30 ADD AL, '0' ; ASCII fix low digit 3D 3234 CMP AX, '24' ; rolled over to 24 hours? 7C 03 JL NO_CARRY_DAY ; if not, skip to convert B8 3030 MOV AX, '00' ; reset hours to '00' NO_CARRY_DAY: 86 C4 XCHG AL, AH ; endian convert AB STOSW ; write hours string B0 30 MOV AL, '0' ; reset minutes to '00' NO_CARRY_HOUR: 5F POP DI ; minutes string offset to DI 86 C4 XCHG AL, AH ; endian convert AB STOSW ; write minutes to output string B8 0924 MOV AX, 0924H ; AL = '$', AH = write string function AA STOSB ; write DOS string terminator to end of string CD 21 INT 21H ; write output to console C3 RET ; return to DOS ``` Thought it would be a more straightforward use of BCD operations, though it gave me a use for the `AAA` instruction so there's that. Standalone DOS executable. Input via command line, output to console. [![enter image description here](https://i.stack.imgur.com/Rh9TI.png)](https://i.stack.imgur.com/Rh9TI.png) ### OR... **21 bytes** if I could take I/O as a packed BCD hex word (`12:59` == `0x1259`), and get to use `AAA`'s bastard step-sibling `DAA`! ``` 40 INC AX ; increment the time 27 DAA ; decimal adjust packed BCD 3C 60 CMP AL, 60H ; did minutes reach 60? 7C 0E JL DONE ; if not, do nothing else 32 C0 XOR AL, AL ; otherwise, reset minutes to 0 86 E0 XCHG AH, AL ; swap hours and minutes in AL 40 INC AX ; increment the hours 27 DAA ; decimal adjust packed BCD 3C 24 CMP AL, 24H ; did hours reach 24? 86 E0 XCHG AH, AL ; real quick, swap hours and minutes back 7C 02 JL DONE ; if less than 24, do nothing else 32 E4 XOR AH, AH ; otherwise, reset hour to 0 DONE: C3 RET ``` [Answer] # [PHP](https://php.net/), 35 bytes ``` <?=date("H:i",strtotime($argn)+60); ``` [Try it online!](https://tio.run/##K8go@P/fxt42JbEkVUPJwypTSae4pKgkvyQzN1VDJbEoPU9T28xA0/r/fwMDKwODf/kFJZn5ecX/dd0A) [Answer] # [Python 2](https://docs.python.org/2/), 68 bytes ``` def f(s):v=int(s[:2])*60-~int(s[3:]);print'%02d:%02d'%(v/60%24,v%60) ``` [Try it online!](https://tio.run/##JcxBCsIwEAXQvafoJiQjitNpE@iIJ5Hu2tKAxGBjxI1XjxndzOP/DxPfab0HKmWal2YxG3C@@JDMdmUaYe/w@PnHjkc4x0cNWiFNLEcrk08OFfWHrBxCea3@Njct108@xGcyAEUjMqLe/STRsrXiwHaotsS9SHWXnjrpvw "Python 2 ‚Äì Try It Online") # [Python 3.8](https://docs.python.org/3.8/), ~~65~~ 64 bytes *-1 byte thanks to @Matthew Willcockson* ``` lambda s:f"{(v:=int(s[:2])*60-~int(s[3:]))//60%24:02}:{v%60:02}" ``` [Try it online!](https://tio.run/##JYpRC4IwFEbf9ytEELYgvN65kRf8JeWDUUNB19BlhNRfXxu9fJzvcNzbDw8rT24Jpr2EqZ@vtz5byeQ736gdrefrmbATBw3H7/9K6oQoSw0F1gT4oX0rNCTKw2sYp3tWUeaWFBs@Wvf0XAgRICbA0iIDRUoxaEg1rEKqG4bRK4Yymh8 "Python 3.8 (pre-release) ‚Äì Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 216 bytes ``` ,++++++++>,>>,>+>,++++>,+<<<[-<<-<-<+>>>>>>->-<<<]>>>[<<-]<<[>>----------<+[<-]<[->------<<<+<+[++++++[>-]>[<<[>>-]>>[<----<-->>->>]<]<<------>]>[<----------<+>>->]]<]<<<[->+>+>>+>>+>+<<<<<<<]>--------.>.>>.>>----.>. ``` [Try it online!](https://tio.run/##PU5BCgJBDHtQt3tQPLiUfKT0oIIgCx4E3z8mM7O2hbZpEnr/3F7v5/ext7bYDCxgsY3FIiI9wpmGHg7uUZySePFO7B9hKTB9YqQasWGe8JJKipK@M9xligp6DRFq3g5PEaoT5GzMUXov@jcHd8UK1ZxbO523y/UH "brainfuck ‚Äì Try It Online") The character `:` is the ASCII character after `9`, so the program uses the one provided to it in the input to check if digits need to be carried, allowing it to avoid creating any large constants. ``` [ Read in the string and set up for the comparisons later. Increment minutes. Subtract ':' from all characters and copy it elsewhere. Layout: Cell # -1 0 1 2 3 4 5 6 Cell contents ':' A B _ _ 1 C D The central 0 and 1 cells allow all of the conditionals to land near each other, reducing the amount of travel needed in the worst case. ] ,++++++++>,>>,>+>,++++>,+ <<<[-<<-<-<+>>>>>>->-<<<] # If minutes are 10: Carry >>>[<<-]<<[ >>----------<+ # If tenminutes are 6: Carry [<-]<[ ->------<<<+<+ # If hours are not 10: Check for 24:00 rollover [ ++++++ [>-]>[ <<[>>-]>>[ <----<-- >>->>] <] <<------ # If hours are 10: Carry >]>[ <----------<+ >>->] ] <] # Undo modifications from the start and print <<<[->+>+>>+>>+>+<<<<<<<] >--------.>.>>.>>----.>. ``` [Answer] # [Java (JDK)](http://jdk.java.net/), ~~83~~ 49 bytes ``` i->java.time.LocalTime.parse(i).plusMinutes(1)+"" ``` [Try it online!](https://tio.run/##nZA/T8MwEMX3fopTpkSobgpioBXslehUNsRwda7hgmNH8TkSQvnswSnpH0a4xfLzPb3fc4UdzqviY9AGvYctsoWv2QziLBag39GWhHtDwFaoPaCm41vTcodypcIm2mCanbRsS8CiQ6vphWuCdNIkXrL1cbP/iWnC3rAGLyjx6BwXUI8Uk@P1DbAtfXaimsg8SWjOwga8M0HYWXg8i5ft0pkDFaBdQQPPn6rYWY0g6tlpNCOfarD1lHKmGhP8lm0Q8ukyu0mSYX0J3n16oVq5ICr@gBVj01OwumqbJst8ledJNjX9k/X2bnX/8D9r/iu1n/XDNw "Java (JDK) ‚Äì Try It Online") Huge cut-off thanks to Olivier Gr√©goire [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` YOl13L/+15XO ``` Beaten by Excel... :-D [Try it online!](https://tio.run/##y00syfn/P9I/x9DYR1/b0DTC//9/dQNTK1NTdQA) Or [verify all test cases](https://tio.run/##y00syfmf8D/SP8fQ2Edf29A0wv@/S8h/dQMDKwMDdS4wbQSiTa1MTUG0pZWpJZA2NLIyAdFGQHmQuJExSBwA). ### Explanation ``` YO % Implicit input. Convert to date number. The integer part represents date, % the fractional part represents time of day l % Push 1 13L % Push 1440 (predefined literal) / % Divide. Gives 1/1440, which is 1 minute expressed as fraction of a day + % Add 15XO % Convert to date string with format 15, which is 'HH:MM' % Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~¬†20¬†~~ 19 [bytes](https://github.com/DennisMitchell/jelly) ``` √òD·πó2·∏£‚Äú√∞<‚Äò≈ípj‚Ǩ‚Äù:√∞·πôi·∏¢ ``` A monadic Link that accepts a list of characters and yields a list of characters. **[Try it online!](https://tio.run/##ATYAyf9qZWxsef//w5hE4bmXMuG4o@KAnMOwPOKAmMWScGrigqzigJ06w7DhuZlp4bii////MjM6NTk "Jelly ‚Äì Try It Online")** ### How? Surprisingly tricky to get anything below 22 in Jelly, no time-based functionality while parsing, evaluating and then adding leading zeros where needed is expensive, so I went with constructing all strings as a list and getting the next string cyclically. ``` √òD·πó2·∏£‚Äú√∞<‚Äò≈ípj‚Ǩ‚Äù:√∞·πôi·∏¢ - Link: characters, S √òD - digit characters -> "0123456789" ·πó2 - Cartesian power 2 -> ["00",...,"99"] ‚Äú√∞<‚Äò - list of code-page indices -> [24, 60] ·∏£ - head to -> [["00",..."23"],["00",...,"59"]] ≈íp - Cartesan product -> [["00","00"],...,["23","59"]] j‚Ǩ‚Äù: - join each with colons -> ["00:00",...,"23:59"] √∞ - start a new dyadic chain, f(Times, S) i - first 1-indexed index of S in Times ·πô - rotate Times left by that ·∏¢ - head ``` [Answer] **Powershell**, **82** or **153** bytes `get-date ((get-date ($Time=read-host "Enter the time")).addminutes(1)) -uformat %R` Or, if you want to show the input as well as the output; ``` do {$Time=read-host "Enter the time" write-host -nonewline $time `t get-date ((get-date $Time).addminutes(1)) -uformat %R } while ($Time) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 32 bytes ``` T`_d`d0`.9?(:59)?$ T`d`0`(24)?:6 ``` [Try it online!](https://tio.run/##FcohDoAwDEZh33NAshnyU1aS1UxygXlKMgQGQbh/GeaJL@853@s@fAybebW9WYNNuQSVHMtA1ZrBAqdYdHUHFKC/TBAVIeR@0syaMnF3IV66fA "Retina 0.8.2 ‚Äì Try It Online") Link includes test cases. Explanation: ``` T`_d`d0`.9?(:59)?$ ``` Increment all the digits in `09:59`, `19:59`, `X:59`, `:X9` or just the last digit if nothing else matches. Incrementing `9` automatically rolls over to `0`. ``` T`d`0`(24)?:6 ``` Zero out `24:60` and the seconds of `X:60` (X will already have been incremented above so it is correct). [Answer] # JavaScript (Chrome / Edge / Node), 50 bytes Very hackish. ``` s=>(new Date(+new Date([1,s])+6e4)+s).slice(16,21) ``` [Try it online!](https://tio.run/##bc9BC8IgGMbxe59CdlJcm7opTFinvkV0EHOxEI0c9fFtRluR3Z7D7@XPe1F3FfRtvE5b508mDn0M/Q468wB7NRmI13WgZTgiLEyLcEBVsKM2kIqSURS1d8FbU1l/hgMsCJGEFAiBugZp080fwL5AkwEuOV/AvEUGOsm7N6Ap9wsok@0KmOQZYPPVkkg7S7Dmk3h9FJ8 "JavaScript (Node.js) ‚Äì Try It Online") ### Commented ``` s => // s = "HH:MM" ( new Date( // generate a date: +new Date( // generate a timestamp corresponding to: [1, s] // "1,HH:MM" which is interpreted as // Mon Jan 01 2001 HH:MM:00 ) // end of Date() + 6e4 // add 60000 milliseconds (1 minute) ) // end of Date() + s // coerce to a string ).slice(16, 21) // extract the updated "HH:MM" ``` [Answer] # [C#](https://docs.microsoft.com/en-us/dotnet/csharp/), ~~64~~ ~~62~~ 55 bytes -7 bytes thanks to asherber ``` (x)=>$"{System.DateTime.Parse(x).AddMinutes(1):HH:mm}"; ``` [dotnetfiddle!](https://dotnetfiddle.net/ZHEdxy) ## Old version (62 Bytes) ``` (x)=>System.DateTime.Parse(x).AddMinutes(1).ToString("HH:mm"); ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-pl`, 40 bytes ``` $_="#{Time.gm(1,1,~/:/,$`,$')+60}"[11,5] ``` [Try it online!](https://tio.run/##KypNqvz/XyXeVkm5OiQzN1UvPVfDUMdQp07fSl9HJUFHRV1T28ygVina0FDHNPb/fwMDKwMDLhBpxGVgamVqymVgaWVqyWVoZGViyWUEFDflMjIGivzLLyjJzM8r/q9bkAMA "Ruby ‚Äì Try It Online") `~/:/` matches the colon in the input (yielding its index, `2`), setting the pre- and post-match regexes `$`` and `$'` to the hour and minute, respectively. --- # [Ruby](https://www.ruby-lang.org/) `-plaF:`, 35 bytes *Suggested by @dingledooper* ``` $_="#{Time.gm(1,1,1,*$F)+60}"[11,5] ``` [Try it online!](https://tio.run/##KypNqvz/XyXeVkm5OiQzN1UvPVfDUAcEtVTcNLXNDGqVog0NdUxj//83MLAyMOACkUZcBqZWpqZcBpZWppZchkZWJpZcRkBxUy4jY6DIv/yCksz8vOL/ugU5iW5WAA "Ruby ‚Äì Try It Online") The array `$F` is formed by automatically splitting the input at the colon. --- Both versions perform the following operations: * convert input to a `Time` object, * add 60 seconds, * convert to a string of the form `0001-01-dd hh:mm:00 UTC`, where for the 40 byte version `dd` is either `02` or `03` (the latter only when the input is `23:59`); for the 35 byte version it is `01`, * extract the 11th to 15th characters. It's somewhat noteworthy that `Time#gm` internally coerces string arguments to integers. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~71~~ 69 bytes Thanks to dingledooper for the -2. The only sneaky things were to reuse the input parameter and cache the format string. ``` i,z;f(s){sscanf(s,z="%02d:%02d",&i,&s);printf(z,(i+s/60)%24,++s%60);} ``` [Try it online!](https://tio.run/##RZDBboMwDIbvPIWViTYp2ZbSgtRk9Amq3XbqeqChDEsMJtLuAOLZWcLSLYf8jv37i2X9@KH1NCHvVUkNG4zReWMj3mckFHEh3UX4AvnCMPXVYXMtac8pRuY5FSyMtzyKTGhDNU4P2Oj6VlzgxVyLGs9P1T4IbAd85tjQ7xYLBkMAoKu8g5U5nrKBCCGFIHzW2Gkik8TpTiY7q@tYbp3Gtu7y8WbOv74dDiO3rPmsuj/W2rM2npU6hv/DshLhWan3Cc9SluVGRRXYqGw7iplQYI54UoBR9Ds5gF8BCQ1keyB8djA11@ze/h93I1BTtbe6gPNFwjI0S/be2Lbu7hyDcfoB "C (gcc) ‚Äì Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 23√ù59√ù√¢T‚Ä∞J':√ΩDIk>√® ``` [Try it online](https://tio.run/##yy9OTMpM/f/fyPjwXFPLw3MPLwp51LDBS93q8F4Xz2y7wytAUlamlgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkv1/I@PDc00tD889vCjkUcMGL3Wrw3tdKrPtDq/4r/PfwMDKwIALRBpxGZhamZpyGVhamVpyGRpZmVhyGQHFTbmMjIEiAA). **Explanation:** ``` 23√ù # Push a list in the range [0,23] 59√ù # Push a list in the range [0,59] √¢ # Get the cartesian product of these two lists T‚Ä∞J # Format each integer to a string with potentially leading 0: T‚Ä∞ # Take the divmod-10: [n//10,n%10] J # And join these pairs of digits together ':√Ω '# Join each inner pair together with ":" delimiter D # Duplicate this list Ik # Get the index of the input in this duplicated list > # Increase it by 1 √® # And use it to index into the list # (after which the result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~100~~ 95 bytes ``` from datetime import* f='%H:%M' t=lambda s:(datetime.strptime(s,f)+timedelta(0,60)).strftime(f) ``` [Try it online!](https://tio.run/##RYpBCsMgEADvvsJL0G1C2VJaiJB7Ln2ERZcKMYrupa@3sVB6G2Ymv/mV9mtrVFKUzrLnEL0MMafCJ0GLGlYzPJTgZbPx6aysRv@2c@WSO@g6EYydnN/YapzuCNAzfTNByyXsrFkrRIMXBSD@Zja3@TDtAw "Python 3 ‚Äì Try It Online") -5 thanks to @pandubear Python is terrible at this... [Answer] # [PHP](https://php.net/), 40 bytes ``` fn($s)=>date('H:i',strtotime("$s+1min")) ``` [Try it online!](https://tio.run/##Zc9PD4IgGMfxu6/iGWMT1h8Bo03MurVeRJdWOjkILHj9kXoJ7frbh30fXO/i6eJ6l@EOGoidIdjT5vx6hJbkN6XzrQ/vYIMeWoKw3/BBG0RprLOsffYWcEcQY4oxRGEP6G5QDUUB08SXQvyLMhFSSbkS43RMRKVktRR8Cv8EF@qwFkLJRIjxwaoyTUlFlH@V@XtxvvdjXdDW@Li7fgE "PHP ‚Äì Try It Online") PHP relative date formatting at its finest, trying to compress it to the max. Should take in account the DST following the locale [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 24 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` ‚ïür‚ñ†g√¶‚îúM<√ûm√≤‚ôÄ+‚ñëm‚ïû':u_l=)¬ß ``` [Try it online.](https://tio.run/##y00syUjPz0n7///R1PlFj6YtSD@87NGUOb42h@flHt70aGaD9qNpE3MfTZ2nblUan2OreWj5//9KBgZWBgZKXGDaCESbWpmagmhLK1NLIG1oZGUCoo2A8iBxI2OQOAA) **Explanation:** ``` ‚ïür # Push a list in the range [0,60) ‚ñ† # Take the cartesian product with itself g # Filter this list of pairs by, √¶ # using the following four characters as inner code-block: ‚îú √û # Where the first value of the pair M< # Is smaller than 24 m # Then map each remaining pair to, √≤ # using the following eight characters as inner code-block: ‚ôÄ+ # Add 100 to both integers ‚ñë # Convert both to a string m‚ïû # Remove the first character (the "1") from both strings ':u '# Join this pair with ":" delimiter _ # After the map, duplicate the list of all possible times l= # Get the index of the string-input in this duplicated list ) # Increase it by 1 ¬ß # And use it to (0-based modulair) index into the list # (after which the entire stack is output implicitly as result) ``` [Answer] # SQL Server, 36 bytes ``` select left(dateadd(n,1,a),5) from t ``` [Try it online (using all of the input values given in the question).](http://sqlfiddle.com/#!18/236eac/2) [Answer] # [R](https://www.r-project.org/), ~~46~~ 43 bytes *-3 bytes thanks to [Jonathan Carroll](https://codegolf.stackexchange.com/users/26763/jonathan-carroll)* Or **[R](https://www.r-project.org/)>=4.1, 36 bytes** by replacing the word `function` with `\`. ``` function(t)format(strptime(t,h<-"%R")+60,h) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jRDMtvyg3sUSjuKSooCQzN1WjRCfDRldJNUhJU9vMQCdD83@ahpKBgZWBgZKmsgIQgNiGXFBBIyRBY7CgqZWpKUwQyDYDC1pamVpCBQ1BRoEEDY2sTOCCRlamYEEjoCxMO4gN1m5kjNAOdsl/AA "R ‚Äì Try It Online") --- Without datetime functions: ### [R](https://www.r-project.org/), ~~89~~ 85 bytes ``` function(t,`[`=substr,m=el(t[4,5]:0+1)%%60)sprintf("%02d:%02d",el(t[1,2]:0+!m)%%24,m) ``` [Try it online!](https://tio.run/##TY7LCsMgEEX3/YrWIih1MU5iIAN@SSiEPgKBmpRovt@qJG1nMVyO5w4ucbBxWKd7GOdJBNV3vfXrzYdFOft8idDVylwJLlpy3oD072WcwiAYB3xQXkwVTSvM2sklD2vlZEwSAAEweT6myVkfNoh/sCrQkDE7TLkpsCXTblDnUxlqpPoLkUyBmF73es6ljtWvXn4SPw "R ‚Äì Try It Online") [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 33 bytes ``` %{'{0:HH:mm}'-f((Date $_)+'0:1')} ``` Input comes from the pipeline. [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvbmBgZWCgrqMAZhiBGaZWpqZghqWVqSWIYWhkZQJmGAHVgKWMjEFSNf9Vq9WrDaw8PKxyc2vVddM0NFwSS1IVVOI1tdUNrAzVNWv//wcA "PowerShell ‚Äì Try It Online") Try it in a PS console (Windows or Core): ``` '00:00', '00:02', '05:55', '09:59', '12:49', '20:05', '23:59'|%{'{0:HH:mm}'-f((Date $_)+'0:1')} ``` ## Explanation **%** is an Alias for the Cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...} **'{0:HH:mm}'** is the output string; {0:HH:mm} is a placeholder for the first argument of the following **-f** format operator. It contains formatting information to print a DateTime object in 24 hour format. **-f** is the format operator, which will replace the placeholder with the actual time. Using -f is shorter than calling the .ToString('HH:mm') method. **((Date $\_)+'0:1')** does the heavy lifting: It first turns the current string coming in from the pipeline ($\_) into a DateTime object by passing it to the Cmdlet **Get-Date**. The 'Get-' is implicit in PS, so leaving it out saves 4 bytes (Disclaimer: **never** use that in a regular script; it slows things down, because PS will search the path for a matching command as well - each time it's called!). Now that there's a DateTime object on the left side, and PS sees an Add operation, it interpretes the '0:1' as timespan of 1 minute (try `[TimeSpan]'0:1'` in a PS console); this is shorter than using the DateTime's object AddMinutes() method. The result of the addition is then inserted into the string, output is implicit. [Answer] # [Scala](http://www.scala-lang.org/), 52 bytes ``` java.time.LocalTime.parse(_).plusMinutes(1).toString ``` [Try it online!](https://tio.run/##VY7LCoMwEADvfsXiyVyCiU2hAQveW3po7yXVUBQfwUQplH57qvVRcxuY3dnVqSiFbR6FTA0kWXap5TmvOyNBvoysMw2JUvD2AHpRQsXhatq8fkJ8XMkWohfY5JXEp2bI3UZSotUyuCOsyk5PRR0QhE0zrVmhtWxNUAV@GPIw9BHEMfyY@MhzLd3YyLWMM7bYgfeuPXB2mC2ZrmwsoXy3WsqZa@kwv5RHdss0@pfn/72P/QI "Scala ‚Äì Try It Online") Straightforward approach: parse string as time information via built-in functionality, add one minute to it, output as string [Answer] # [Factor](https://factorcode.org/), 56 bytes ``` [ ":"without hhmm>duration 1 minutes time+ duration>hm ] ``` This doesn't run on TIO because the `calendar.parser` vocabulary postdates Factor build 1525 (the one TIO uses) by just a bit. Here's a screenshot of running it in build 1889, the official 0.98 stable release: [![A screenshot of running the above code in the Factor Listener](https://i.stack.imgur.com/RfXRp.png)](https://i.stack.imgur.com/RfXRp.png) ## Explanation It's a quotation that takes a string from the data stack as input and leaves a string on the data stack as output. Assuming `"23:59"` is on top of the data stack when this quotation is called... | Snippet | Comment | Data stack (the bottom is the top) | | --- | --- | --- | | ``` ":"without ``` | Remove the colon | ``` "2359" ``` | | ``` hhmm>duration ``` | Parse a 4-digit string into a duration with hours and minutes | ``` T{ duration f 0 0 0 23 59 0 } ``` | | ``` 1 minutes ``` | Create a duration of one minute | ``` T{ duration f 0 0 0 23 59 0 }T{ duration f 0 0 0 0 1 0 } ``` | | ``` time+ ``` | Add two durations and/or timestamps | ``` T{ duration f 0 0 0 23 60 0 } ``` | | ``` duration>hm ``` | Convert a duration or timestamp to a HH:MM string | ``` "00:00" ``` | [Answer] ## Batch, 83 bytes ``` @set/ps= @set/am=6%s::=*60+1%-99,h=m/60%%24+100,m=m%%60+100 @echo %h:~-2%:%m:~-2% ``` Takes input on STDIN. Explanation: ``` @set/ps= ``` Read in the time. ``` @set/am=6%s::=*60+1%-99,h=m/60%%24+100,m=m%%60+100 ``` Batch parses leading `0`s as octal, so to allow hours and minutes to be `08` or `09`, `6` is prefixed to the hours and `1` to the minutes. Additionally, the `:` is changed to `*60+` and the resulting string evaluated. The `6` prefix does not change the overall result because `600` hours is exactly `25` days, while the `1` adds `100` minutes so `99` minutes are subtracted to obtain the desired total number of minutes. The total minutes are then divided back into hours and minutes, but with 100 added so that the last two digits can be extracted. ``` @echo %h:~-2%:%m:~-2% ``` Print the last two digits to get the real hours and minutes again. [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` √ê6e4¬∞√êNi1¬π¬§¬Ø5 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=0DZlNLDQTmkxuaSvNQ&input=IjAwOjAwIg) [Answer] # [C (clang)](http://clang.llvm.org/), 63 bytes ``` f(*s){strptime(s,"%R",s);*s=84;mktime(s);strftime(s,8,"%R",s);} ``` [Try it online!](https://tio.run/##VZBNboMwEIX3nGJkCcUmRHJIiAgWPUS3lAUhcWKVP9kkUYW4eqlt3Kj15o3ePH8zdrWp6rK9zjPHgSKjGmQ/iOaCVYj8dxQqwgKVJXvWfC42YTrCXSR5haZZtAM0pWjxoxNnAqMHUN1KCYHKi2xElKaUotBqZDRO49joMY2PWrdRujca6b7xo5316RRqkD2BfIG2DrRzoIMBuAEaFFMHOrgcNSCmQWZJwTxd8U5ikVEGKhcFA7FeLzsD9FKnOEa@guwNUGgThNmefdHpzvOEFoujf6Pqv7D2/gW5cVz9B4jVrbvXZzhdUlj5akU@Wj3AXpa/lydvmr8rXpdXNW@ePw "C (clang) ‚Äì Try It Online") Thanks to @AZTECCO for the "%R" format!! [Answer] # [Julia 1.0](http://julialang.org/), 66 bytes ``` using Dates;f="HH:MM";g(s)=Dates.format(DateTime(s,f)+Minute(1),f) ``` [Try it online!](https://tio.run/##HY6xDsIgFEVn/YoX0uERq6EoQ2nq5NClmz9AIjSYFk2BxL9HYDv3njvcd1yt6n4pRW/dAg8VtB/MSKZJzjMZFvR0rOXFfPZNBSzhaTeNvjX0NFsXg8aO5pDyAjxYB0gYk4yRFirwCkIKUaGXoi/QcXmrwPOmKn4tih4P3926sDokjYfzHRosP2g22r0g/QE "Julia 1.0 ‚Äì Try It Online") Using libraries because why not and it's still shorter than Python. [Answer] # [Julia 1.0](http://julialang.org/), ~~43~~ 42 bytes ``` using Dates ~t="$(Time(t)+Minute(1))"[1:5] ``` [Try it online!](https://tio.run/##LYyxCgIxEAX7/YoQLBIE2US3uMCJha2dnVhcEWQlhsNswOp@PcbD5jEMw3vWxJP7tFYL54c6TxILLDLqjbnyKxqx2wvnKtE4a/XNBbq3nkhRoypzYjFaa0AMiOt6QApEgEOgAZwPhwF89wR@/zO9tgCnnZrfnCVl8z87qmUl274 "Julia 1.0 ‚Äì Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 101 bytes I was hoping this would be shorter, but I am posting it despite the length because I think it's an interesting way to compute the answer. This function modifies the input string so the output is the input. I'm not too familiar with the C golfing rules on this but since it's so long I'm neglecting that issue. This function treats the input as individual characters, where each column has a 'max' value (the first 5 characters in `u`) and a 'reset' value (last 5 characters in `u`). First the last character of the input string is incremented, then from right to left each character is compared to the max. If any character is greater than its max, it is set to the 'reset' value of that column and the column to the left is incremented. As described so far, this function will reset after 29:59. To make it reset after 23:59 I used `short *a` to check the first two characters at once to see if they equal `"24"` and if they do, set them to `"00"`. Also note that I had to modify the test code in order to copy input strings into writable memory. Improvements are welcome, I think I'm out of ideas on this one. Thanks to att for -22 bytes, a bugfix, and some awesome golfing! ``` c;f(char*x){for(x[c=4]++;~c;)x[--c]+=x[c]>"29:59"[c]&&(x[c]=c-2?48:58);*x<49&&x[1]==52?*x=x[1]=48:0;} ``` [Try it online!](https://tio.run/##rZHNbsIwDMfvfQqrE9Cm7ZaGFkFD4AXQbjuxHoqBEal8qC1TJ@henSWhbJwmTVqkyI7t/PxPjMEb4uWJWOVmX1Qk48jXDm6ygtTuab0vnHqOIko9j38iz0Tt1vMgwNQTKp5ObDZK4pGt3G5XV6YCAzaNhkk8dDnJAqF22O8P2JQmIWUD3li/8f8Cd66C3fra4Hx2SK3uhamIVLqxyNPlv1rV42jU7Rq2iNn0p09CeXN5kDvMj8sVjMtqmcvF42ZiWXJXwTaTO@d9L5cunCwArQRIOU/FyaY0odT2jWXaxkkca2tk@HbIkkhbpvI6zvom/vwymzW@YplFim9W2LL6LWugGW0PxYppyxq0dbRlccXSUkHyViEBROOLbZbne3RiVx/190lBOZRzmXKQnnd9FMChUIC1YxtJnRLEBGzflJmLAGVV4OHDQfTvgmow2LqHY1XenW44Pd9jvoTFKoFep@y5rzvFLW6IxmouXw "C (gcc) ‚Äì Try It Online") ]
[Question] [ Basing on [this SO question](https://stackoverflow.com/questions/37964715/convert-yyyymm-to-mmmyy). Challenge is rather simple: given a date period in the format `YYYYMM` output it in the format `MMMYY`. ### Rules: * The input will be a number or a string exactly 6 characters long, consisting only of digits. * Last two digits will be between `01` and `12`. * Output must be in the form `MMMYY`, where `MMM` represents uppercase three-letter code for the month (below) and `YY` represents **two** last digits of the `YYYY` part of the input. List of months with corresponding code: ``` MM MMM 01 JAN 02 FEB 03 MAR 04 APR 05 MAY 06 JUN 07 JUL 08 AUG 09 SEP 10 OCT 11 NOV 12 DEC ``` ### Examples: ``` Input Output 201604 APR16 200001 JAN00 000112 DEC01 123405 MAY34 ``` [Answer] # Python 3, 70 bytes ``` from time import* lambda s:strftime("%b%y",strptime(s,"%Y%m")).upper() ``` This uses the built-in `strftime` and `strptime` functions. For 1 byte more, here's a version which parses the string manually: ``` lambda s:" JFMAMJJASONDAEAPAUUUECOENBRRYNLGPTVC"[int(s[4:])::12]+s[2:4] ``` This encodes the month names in an interesting way (thanks to Henry Gomersall for saving a byte). [Answer] # MATL, ~~18~~ ~~14~~ 13 bytes ``` 4e!Z{Zc12XOXk ``` Input is provided as a string (enclosed in single quotes). This version only runs in MATL on MATLAB since MATLAB is able to automatically parse `datestr('2016 04')`. **Explanation** ``` % Implicitly grab input as a string 4e! % Reshape input to be 2 x 4 (puts the year in row 1 and month in row 2) Z{ % Place each row in a separate cell Zc % Join them together using a space to create 'yyyy mm' format 12 % Number literal, pre-defined datestring of 'mmmyy' XO % Convert from serial date number to string using this format Xk % Convert to uppercase % Implicitly display ``` --- Here is an **18 byte** version which works on Octave (and therefore the online interpreter) ``` 'yyyymm'2$YO12XOXk ``` [**Try it Online**](http://matl.tryitonline.net/#code=J3l5eXltbScyJFlPMTJYT1hr&input=JzIwMTYwNCc) [Modified version for all test cases](http://matl.tryitonline.net/#code=YCd5eXl5bW0nMiRZTzEyWE9Ya0RU&input=JzIwMTYwNCcKJzIwMDAwMScKJzAwMDExMicKJzEyMzQwNSc) **Explanation** ``` % Implicitly grab input as a string 'yyyymm' % Push the format string as a string literal 2$YO % Convert to a serial date number 12 % Number literal, pre-defined datestring of 'mmmyy' XO % Convert from serial date number to string using this format Xk % Convert to uppercase % Implicitly display ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49~~ ~~46~~ 40 bytes ``` date "$args".insert(4,'-')-U %b%y|% *per ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PyWxJFVBSSWxKL1YSS8zrzi1qETDREddV11TN1RBNUm1skZVQasgtej////qRgaGZgYm6gA "PowerShell – Try It Online") *Thanks to @Joey for saving 3 bytes!* Takes input `$args` as an explicit string (e.g., `'201604'`) via command-line input. Uses the `string.Insert()` function to put a `-` in the appropriate space, and that resultant string forms input to the [`Get-Date` cmdlet](https://technet.microsoft.com/en-us/library/hh849887.aspx) with the `-U`format parameter specifying the three-month shorthand plus two-digit year. We then tack on a `.ToUpper()` to make the output string capitalized. That string is left on the pipeline and printing is implicit. Also, as pointed out, this is locale-sensitive. Here's the locale information that I'm using where this works correctly. ``` PS C:\Tools\Scripts\golfing> get-culture LCID Name DisplayName ---- ---- ----------- 1033 en-US English (United States) ``` [Answer] # Bash + coreutils, 18 Requires 64-bit version of `date` for the given testcases, [which recognises dates earlier than 14th December 1901](https://unix.stackexchange.com/questions/7688/date-years-prior-to-1901-are-treated-as-invalid). ``` date -d$101 +%^b%y ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~71~~ 70 bytes *Thanks to Sp3000 for saving 1 byte.* Byte count assumes ISO 8859-1 encoding. The trailing linefeed is significant. ``` (..)(..)$ DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1 +`...¶ R-6`. ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAooLi4pKC4uKSQKREVDTk9WT0NUU0VQQVVHSlVMSlVOTUFZQVBSTUFSRkVCSkFOWFhYJDIkKsK2JDEKK2AuLi7CtgoKUi02YC4&input=MjAxNjA0CjIwMDAwMQowMDAxMTIKMTIzNDA1) ### Explanation Taking `201604` as an example: ``` (..)(..)$ DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX$2$*¶$1 ``` This swaps the last two digits of the year with the month while also expanding the month in unary using linefeeds, and prepending the list of months in reverse so we'd get: ``` 20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16 ``` Where the `¶` represent linefeeds (0x0A). ``` +`...¶ ``` Now we repeatedly remove three non-linefeed characters followed by a linefeed. That is we eat up the list of months from the end for each linefeed representing a month: ``` 20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJANXXX¶¶¶¶16 20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEBJAN¶¶¶16 20DECNOVOCTSEPAUGJULJUNMAYAPRMARFEB¶¶16 20DECNOVOCTSEPAUGJULJUNMAYAPRMAR¶16 20DECNOVOCTSEPAUGJULJUNMAYAPR16 ``` This is why we've inserted that `XXX`: since the months start counting from `1`, we'll always remove at least three characters, even for January. ``` R-6`. ``` Finally, we remove everything up to the 6th character from the end. In other words we only keep the last five characters. [Answer] # CJam, ~~50~~ 46 bytes ``` q2/1>~i("4H~0ë~³!ò²×¶7Ö"256b25b'Af+3/=\ ``` [Try it online.](http://cjam.aditsu.net/#code=q2%2F1%3E~i%28%224H~0%C3%AB%C2%99~%C2%B3%C2%90!%C3%B2%C2%B2%C3%97%C2%8C%C2%9D%C2%B6%C2%90%1F%1F7%C3%96%22256b25b'Af%2B3%2F%3D%5C&input=201604) Thanks to Martin Ender for compressing the string to save a few bytes. ### Explanation ``` q2/ e# Get input and divide it into groups of 2, like ["20" "16" "04"] 1>~ e# Discard the first item and dump the remaining array to the stack i( e# Convert the top value (month) to an integer and decrement it, because e# arrays are zero-indexed "..."256b25b e# Convert this string from base-256 to base-25 'Af+ e# "Add" a capital A to each number to get the letters 3/ e# Divide into groups of 3 to make an array of month names =\ e# Get the requested month and swap the elements to put the year on e# top, so it is printed last ``` [Answer] # MATLAB / Octave, 42 bytes ``` @(x)upper(datestr(datenum(x,'yyyymm'),12)) ``` Creates an anonymous function named `ans` that is called with a string representing the date: `ans('201604')`. [**Online Demo**](http://ideone.com/a2ND79) This solution uses `datenum` to convert the input date to a serial date number, and then `datestr` with the predefined output spec of `mmmyy` (`12`) to yield the string representation in the required format. Finally, we use `upper` to change it to `MMMYY` since the uppercase month is not an output option. [Answer] ## Bash, ~~39~~ 28 bytes ``` date -d$101 +%b%y|tr a-z A-Z ``` Thanks [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)! [Answer] # Java 7, 137 characters (161 bytes) ``` String d(String i){return Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔".charAt(Integer.parseInt(i.substring(4))-1),36).toUpperCase()+i.substring(2,4);} ``` Consider each month name (JAN, FEB etc...) is a number in base 36 and encode it into corresponding Unicode symbol. Then get corresponding symbol from the string encode it back again in base 36 and after that some plain string manipulations. Slightly ungolfed: ``` String d(String input){ return Integer.toString("憯䷳烣㘿烪摿摽㛨近筍矯䏔" // encoded month names .charAt(Integer.parseInt(input.substring(4))-1),36) // get a symbol from encoded names at position input[4:], decode it to base 36 value .toUpperCase()+input.substring(2,4); // get it to upper case and add year } ``` You can see it running here: <https://ideone.com/IKlnPY> [Answer] ## Python, 83 bytes ``` from datetime import* lambda x:datetime.strptime(x,'%Y%m').strftime('%b%y').upper() ``` [Answer] ## Kotlin, 100 bytes ``` fun f(d:String)=SimpleDateFormat("MMMyy").format(SimpleDateFormat("yyyyMM").parse(d)).toUpperCase() ``` Pretty straight forward use of Java SimpleDateFormat [Answer] ## 05AB1E, ~~51~~ ~~42~~ 41 bytes ``` 2ô¦`ï<•r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B3ôsèsJ ``` **Explanation** ``` # implicit input, 123405 2ô # split input into pieces of 2, ['12','34','05'] ¦` # push last 2 elements to stack, '05', '34' ï< # convert month to its int index, 4 •r–ºþ¯Bê€õaPù£—^5AºüLwÇ–è•35B # get compressed string containing 3-letter months, JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC 3ô # split into pieces of 3 ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] sè # get month at index retrieved earlier, MAY sJ # join with 2-digit year and implicitly print, MAY34 ``` [Try it online](http://05ab1e.tryitonline.net/#code=MsO0wqTDrzzigKJy4oCTwrrDvsKvQsOq4oKsw7VhUMO5wqPigJReNUHCusO8THfDh-KAk8Oo4oCiMzVCM8O0c8OoczHDqEo&input=MTIzNDA1) 9 bytes saved thanks to string compression, courtesy of @Adnan [Answer] # JavaScript, ~~87~~ ~~84~~ ~~80~~ 79 bytes ``` x=>(new Date(x.replace(/.{4}/,'$&-'))+'').slice(4,7).toUpperCase()+x.slice(2,4) ``` To get the month, gets the date (which is formed of "YYYYMM" converted to "YYYY-MM") and retrieves the characters 5 to 8, that are exactly the first three letters of the month. But it costs much to convert it to upper case. Demo: ``` function s(x) { return (new Date(x.replace(/.{4}/, '$&-')) + '').slice(4,7) .toUpperCase() + x.slice(2, 4) } console.log(s('201604')); console.log(s('200001')); console.log(s('000112')); console.log(s('123405')); ``` [Answer] # Julia, ~~57~~ ~~56~~ 53 bytes ``` s->uppercase(Dates.format(DateTime(s,"yyyym"),"uyy")) ``` This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable. First we construct a `DateTime` object using the type constructor and a format string. Note that the single `m` in the format string will get both one- and two-digit months, though the former case is irrelevant here. Since no days are specified, the first of the month is assumed. We can then format the value as a string using the `Dates.format` function from the `Base.Dates` submodule. The string `uyy` gets the three-letter month name and two-digit year, but the result is in title case, e.g. Apr16 instead of the desired APR16, so we need to `uppercase` it. [Try it online!](http://julia.tryitonline.net/#code=Zj1zLT51cHBlcmNhc2UoRGF0ZXMuZm9ybWF0KERhdGVUaW1lKHMsInl5eXltIiksInV5eSIpKQoKZm9yIHRlc3QgaW4gWygiMjAxNjA0IiwiQVBSMTYiKSwgKCIyMDAwMDEiLCJKQU4wMCIpLCAoIjAwMDExMiIsIkRFQzAxIiksICgiMTIzNDA1IiwiTUFZMzQiKV0KICAgIHByaW50bG4oZih0ZXN0WzFdKSA9PSB0ZXN0WzJdKQplbmQ&input=) (includes all test cases) [Answer] # JavaScript ES6, ~~77~~ 66 bytes Saved 11 bytes thanks to @Bálint! ``` a=>(new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3] ``` Get's the date by extracting the string returned by the `Date` class. then capitalizes and adds the year. ES5 version: ``` var a = prompt("Enter YYYYMM: "); result = (new Date(0,a[4]+a[5]-1)+"").slice(4,7).toUpperCase()+a[2]+a[3] alert(result); ``` [Answer] ## C, ~~147~~ ~~145~~ 112 bytes ``` main(m){char a[99]="JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";scanf("%4s%d",a+50,&m);printf("%.3s%s",a+--m*3,a+52);} ``` [Online demo](http://ideone.com/T0JSWL) Thanks [ugoren](https://codegolf.stackexchange.com/users/3544/ugoren)! [Answer] # C#, ~~94~~ 87 bytes ``` string C(string s)=>System.DateTime.Parse(s.Insert(4,"-")).ToString("MMMyy").ToUpper(); ``` Saved 7 bytes by using C#6 Syntax. [Try Online](http://csharppad.com/gist/1bf6575ea6e22e58e3bdcc79e205d905) [Answer] # Japt, ~~35~~ 34 bytes ``` ÐUr$/..../$,"$&-")+P s4,7 u +Us2,4 ``` [Link.](http://ethproductions.github.io/japt/?v=master&code=0FVyJC8uLi4uLyQsIiQmLSIpK1AgczQsNyB1ICtVczIsNA==&input=IjIwMTUwNCI=) Uses the same technique as my [JavaScript answer](https://codegolf.stackexchange.com/a/83597). [Answer] # Java 8, ~~154~~ 113 bytes ``` import java.text.*;s->new SimpleDateFormat("MMMyy").format(new SimpleDateFormat("yyyyMM").parse(s)).toUpperCase() ``` **Explanation:** [Try it online.](https://tio.run/##jZAxT8MwEIX3/opTJnuolYTCEsFCYXOXigkxHK5L3Sa2ZV9boiq/PTgk6oREbzjdkz7p3Xt7POF8vzn0qsYYQaKxlxmAsaTDFpWG1SAB1hSM/QLFpiNyoF1w5wgv30p7Ms5WCexmaUVCMgpWYOER@jh/svoMa9P4Wi@R9KsLDRLLpJRtm3GxHfXfUJtGykR5DFGzyLkg9@a9Ds@YNO@rwdEfP@vkOBmfnNlAk5JMz75/APIxBoV2PFKiNpJuhDuS8Imi2jIrFMvKvHjIFxnn1b9gmuIGcMCK8gawKO8W@f0V7BSS2rFrwaD5pfstuet/AA) ``` import java.text.*; // Required import for SimpleDateFormat s-> // Method with String as both parameter and return-type new SimpleDateFormat("MMMyy") // Create a formatter with format "MMMyy" .format( // Format the following: new SimpleDateFormat("yyyyMM") // Create another formatter with format "yyyyMM" .parse(s)) // Parse the input with this format .toUpperCase() // Convert everything to Uppercase and return ``` [Answer] # Oracle SQL, 49 Bytes ``` select to_char(to_date(n,'yyyymm'),'MONyy')from t ``` The data must be inserted in a table called `T` with a column `N` of type `VARCHAR2(6)`, `CHAR(6)` or , only if all the years are > 1000, `NUMBER` Usage: ``` drop table t; create table t (n VARCHAR2(6)); insert into t values ('201604'); insert into t values ('200001'); insert into t values ('000112'); insert into t values ('123405'); select to_char(to_date(n,'yyyymm'),'MONyy')from t; ``` [Answer] # Microsoft SQL Server, 57 Bytes ``` SELECT UPPER(FORMAT(CAST('201601'+'01' AS DATE),'MMMyy')) ``` The `Upper` function is required as format does not produce Upper case months as would be expected with the *MMM* format pattern. **Usage:** ``` drop table t; create table t (n VARCHAR(6)); insert into t values ('201604'); insert into t values ('200001'); insert into t values ('000112'); insert into t values ('123405'); SELECT UPPER(FORMAT(CAST(n+'01' AS DATE),'MMMyy')) FROM t ``` [Answer] # MediaWiki Template (with ParserFunctions), 29 bytes ``` {{uc:{{#time:My|{{{1}}}01}}}} ``` Only works if English locale is chosen. [Try Sandbox](https://www.mediawiki.org/w/index.php?title=Project:Sandbox&action=edit) [Answer] # Pyth, 45 bytes ``` +:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4 ``` [Try it online!](https://tio.run/##AUQAu/9weXRo//8rOi4iQVkMdzLDu0TDiMOrS0jCp8OIwrwCRFnDiXhcRcKxb8OLHCJKKjNzZ3o1KzNKOnoyIDT//zIwMTgwNA) Explanation: ``` +:."AYw2ûDÈëKH§È¼DYÉx\E±oË"J*3sgz5+3J:z2 4 z Take the input g 5 Slice inclusively from index 5 to the end s Parse as an int *3 Multiply by 3 J Store in variable J, this also returns J : Take a slice ."AYw2ûDÈëKH§È¼DYÉx\E±oË" Of this packed string J*3sgz5 From the J we defined before +3J To J+3 + To this string, append :z A slice of the index 2 4 From [2,4). ``` The packed string contains `"JANJANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC"`. The two `JAN`s are so that I can index it pseudo-one-indexed. EDIT: Fixed bug that was messing with TIO [Answer] # [R](https://www.r-project.org/), 65 bytes ``` function(A)paste0(toupper(month.abb[el(A:1)%%100]),substr(A,3,4)) ``` [Try it online!](https://tio.run/##LchBC8IgFADge78iFoMnSLyntkPQQapLUES3iA5zbBSUk6m/32b4Hb8pDbs0RNuF92hBM9f60COEMTrXT/AdbXitW2Me/Qf0llhdE@KTcR@NDxNoLrliLA1QCaQGVcVWy5m@3qhZ/HdGZU/6gpg3H4myh@MeKS8JqXBT9qzvUqUf "R – Try It Online") Takes input as a string, leverages the constant `month.abb`. Uses modulus and `substr` to extract relevant values. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 78 bytes ``` i=>'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.match(/.../g)[i[4]+i[5]-1]+i[2]+i[3] ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrqHxP9PWTt3L0c/N1cnXMcgxIMjXMdIr1M8r1Mcx1D3YNcDfOcTPP8zF1VldLzexJDlDQ19PT08/XTM6M9okVjsz2jRW1xBEG4EI49j/mhrqRgZGhgbm6pqa1v8B "JavaScript (Node.js) – Try It Online") [Answer] # [Headascii](https://esolangs.org/wiki/Headass#Headascii), 331 bytes ``` UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP! ``` [Try it here!](https://replit.com/@thejonymyster/HA23) Code will need to be pasted in and executed like this: ``` erun("UUU^U[UOUODOD]ONE.++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E.+++^^^U[U-()D]^P(]PD++++P:-()+++++]P-P---P:-()D+++]^P(]PD+++++P:-()]PD++++++]P++P:-()D^^^+++]P(]PD---]P:-()D^^]PD^++]PD-----]P:-()D^^]PD++]P(++^^^^^D+]P:-()]PD^^D++]P(++++++]P:D^^D^]P(++++]PD---]P;UPUP!.++^^^^^U[U)D^^++++]P(++]PD-]P:R-)D^^+++]P+PD+]P:+++]P+P--P;UPUP!","your input here") ``` Headass/ascii is not particularly good at strings. ``` UUU^U[UOUODOD]ONE. Block 0 UU Discard the first two chars of input lol U^U[ Hold onto the last two digits of the year UOUODOD]O ready MMYY for the next code block NE Go to block 1 . Block separator ++++[]]]][]]]]+O[---[]]]][]]]][U]^U]OUOUOD++E. Block 1 ++++[]]]][]]]]+O Save 65 for later ease of access [---[]]]][]]]][ -48 U]^ Add to first month digit and hold U]O Add to second month digit and save UOUO Save year digits D++E Go to either block 1 or block 2, depending on whether the first digit of the month was 0 or 1 . Block separator +++^^^U[U-()...;UPUP!. Block 2 (JAN-SEP) +++^^^ Store 9 on the accumulator U[ Restore 65 from earlier U-() If the second digit of the month is 1, D]^P(]PD++++P Concatenate "JAN" to the string register :-() Else if it's 2 +++++]P-P---P Concatenate "FEB" to the string register :-() Else if it's 3 D+++]^P(]PD+++++P Concatenate "MAR" to the string register :-() Else if it's 4 ]PD++++++]P++P Concatenate "APR" to the string register :-() Else if it's 5 D^^^+++]P(]PD---]P Concatenate "MAY" to the string register :-() Else if it's 6 D^^]PD^++]PD-----]P Concatenate "JUN" to the string register :-() Else if it's 7 D^^]PD++]P(++^^^^^D+]P Concatenate "JUL" to the string register :-() Else if it's 8 ]PD^^D++]P(++++++]P Concatenate "AUG" to the string register : Else D^^D^]P(++++]PD---]P Concatenate "SEP" to the string register ;UPUP! Then concatenate the year digits from earlier and print! . Block separator, end of execution ++^^^^^U[U)D^...;UPUP! Block 3 (OCT-DEC) ++^^^^^ Store 10 on the accumulator U[ Restore 65 from earlier U) If the second digit of the month is 0, D^^++++]P(++]PD-]P Concatenate "OCT" to the string register :R-) Else if it's 1 D^^+++]P+PD+]P Concatenate "NOV" to the string register : Else +++]P+P--P Concatenate "DEC" to the string register ;UPUP! Then concatenate the year digits from earlier and print! ``` [Answer] # Microsoft Excel VBA, 47 Bytes Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window ``` ?UCase(MonthName([Right(A1,2)],1))[Mid(A1,3,2)] ``` Current version thanks to [@Engineer Toast](https://codegolf.stackexchange.com/users/38183/engineer-toast), for pointing out the abbreviate option of the `MonthName` function. ### Previous Version ``` ?UCase(Format(DateSerial([Left(A1,4)],[Right(A1,2)],1),"MMMYY")) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÐUò4)Åu ¸o¤Åë ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=0FXyNCnFdSC4b6TF6w&input=IjIwMTYwNCI) ``` ÐUò4)Åu ¸o¤Åë :Implicit input of string U > "201604" Ð :Create Date object from Uò4 : Partitions of U of length 4 > ["2016","04"] ) :End Date Å :To date string > "Fri Apr 01 2016" u :Uppercase > "FRI APR 01 2016" ¸ :Split on spaces > ["FRI","APR","01","2016"] o :Modify the last element ¤ : Slice off the first 2 characters > ["FRI","APR","01","16"] Å :Slice off the first element > ["APR","01","16"]] ë :Get every second element > ["APR","16"] :Implicitly join and output > "APR16" ``` [Answer] # x86-16 machine code, 64 bytes ``` 00000000: fcad ad50 ad2d 3030 86e0 d50a be19 0103 ...P.-00........ 00000010: f003 f003 f02e a52e a458 abc3 4a41 4e46 .........X..JANF 00000020: 4542 4d41 5241 5052 4d41 594a 554e 4a55 EBMARAPRMAYJUNJU 00000030: 4c41 5547 5345 504f 4354 4e4f 5644 4543 LAUGSEPOCTNOVDEC ``` Callable function, input at `DS:SI`, output buffer at `ES:DI`. Listing: ``` FC CLD ; string direction forward AD LODSW ; skip first two chars AD LODSW ; load YY string 50 PUSH AX ; save YY string AD LODSW ; load month string 2D 3030 SUB AX, '00' ; ASCII convert month 86 E0 XCHG AH, AL ; endian convert D5 0A AAD ; word convert to index (1-12) BE 0116 MOV SI, OFFSET MTBL[-3] ; month table (1-indexed) 03 F0 ADD SI, AX ; add month offset * 3 chars 03 F0 ADD SI, AX 03 F0 ADD SI, AX 2E A5 CS: MOVSW ; copy first two bytes of month 2E A4 CS: MOVSB ; copy third byte of month to output 58 POP AX ; restore YY string AB STOSW ; write YY to output C3 RET MTBL: 4A 41 4E DB 'JAN' 46 45 42 DB 'FEB' 4D 41 52 DB 'MAR' 41 50 52 DB 'APR' 4D 41 59 DB 'MAY' 4A 55 4E DB 'JUN' 4A 55 4C DB 'JUL' 41 55 47 DB 'AUG' 53 45 50 DB 'SEP' 4F 43 54 DB 'OCT' 4E 4F 56 DB 'NOV' 44 45 43 DB 'DEC' ``` Sample runs: [![enter image description here](https://i.stack.imgur.com/g8c2s.png)](https://i.stack.imgur.com/g8c2s.png) [Answer] # [Perl 5](https://www.perl.org/) `-p`, 75 bytes ``` $_=(1,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC)[/..$/g].substr$`,2,2 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lbDUMfL0U/HzdVJx9cxSMcxIAhIR@p4hfoBsY@OY6i7TrBrgI6/c4iOn3@Yjours2a0vp6ein56rF5xaVJxSZFKgo6RjtH//4bGBhYGlv/yC0oy8/OK/@sWAAA "Perl 5 – Try It Online") ]
[Question] [ I got the spontaneous idea of making a series of challenges of users that have helped and continue to help the PPCG community be an enjoyable place for everyone, or maybe just specifically for me. :P If you convert Dennis's name to an array of `1`s and `0`s where each consonant is `1` and each vowel is `0`, the array is `[1, 0, 1, 1, 0, 1]`, which is symmetrical. Thus, your challenge is to determine what other names are like this. # Challenge Given an ASCII string, remove all characters that aren't letters and determine if the configuration of vowels and consonants are symmetrical. `y` is not a vowel. Please note that your program does not have to be this type of string itself. # Test Cases ``` Dennis -> truthy Martin -> truthy Martin Ender -> truthy Alex -> falsy Alex A. -> truthy Doorknob -> falsy Mego -> falsy ``` # Reference Implementation This Python 3 code will give the correct output given a test case. It is as ungolfed as I could make it without being ridiculous. # [Python 3](https://docs.python.org/3/) ``` s = input() l = [] for c in s: if c in 'AEIOUaeiou': l.append(0) elif c in 'BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz': l.append(1) print(l == list(reversed(l)), end = '') ``` [Try it online!](https://tio.run/nexus/python3#VY7JCsIwFEXXzVdklwREdCt0odZ5nidcVPuq0ZjGJK3Dz9eAILg7HA6XmxvsYy5VailDwvFuj@JE46OT2FSQx@Mvk2qjM1qEwJOUOO2JYqgUyIiWGPJA/LJaPWi22t1efzAcT6az@XK13mwPEcSn8@UqblLdtbHZ4/l6/8@UGVKaS0vdCR8LbizVkIE2EFHBWAG7yN0jhOV5AFJy8wE "Python 3 - Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes ``` ŒufØAe€ØCŒḂ ``` [Try it online!](https://tio.run/##ASUA2v9qZWxsef//xZJ1ZsOYQWXigqzDmEPFkuG4gv///yJEZW5uaXMi "Jelly – Try It Online") Alternate versions: ``` ŒlfØae€ØCŒḂ ``` ``` ŒufØAe€ØcŒḂ ``` ``` ŒlfØae€ØcŒḂ ``` Of course a challenge appreciating Dennis must have an answer in a language of his. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` žM¹álSåÂQ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6D7fQzsPL8wJPrz0cFPg//8uqXl5mcUA "05AB1E – Try It Online") -2 thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan). This attacks Jelly's pain point exactly. It uses `l` and `A`, 1-byte equivalents for Jelly's `Œl` and `Øa` respectively. [Answer] ## x86 32-bit machine-code function, ~~42~~ 41 bytes Currently the shortest non-golfing-language answer, 1B shorter than [@streetster's q/kdb+](https://codegolf.stackexchange.com/questions/123194/user-appreciation-challenge-1-dennis/123222#123222). **With 0 for truthy and non-zero for falsy: ~~41~~ 40 bytes.** (in general, saves 1 byte for 32-bit, 2 bytes for 64-bit). **With implicit-length strings (C-style 0-terminated): ~~45~~ 44 bytes** **x86-64 machine-code (with 32-bit pointers, like the x32 ABI): ~~44~~ 43 bytes**. **x86-64 with implicit-length strings, still 46 bytes (the shift/mask bitmap strategy is break-even now).** This is a function with C signature `_Bool dennis_like(size_t ecx, const char *esi)`. The calling convention is slightly non-standard, close to MS vectorcall/fastcall but with different arg registers: string in ESI and the length in ECX. It only clobbers its arg-regs and EDX. AL holds the return value, with the higher bytes of EAX holding garbage (as allowed by the SysV i386 and x32 ABIs, and the Windows x64 calling convention.) --- **Explanation of the algorithm**: Loop over the input string, filtering and classifying into a boolean array on the stack: For each byte, check if it's an alphabetic character (if not, continue to next char), and transform it to an integer from 0-25 (A-Z). Use that 0-25 integer to check a bitmap of vowel=0/consonant=1. (The bitmap is loaded into a register as a 32-bit immediate constant). Push 0 or 0xFF onto the stack according to the bitmap result (actually in the low byte of a 32-bit element, which may have garbage in the top 3 bytes). The first loop produces an array of 0 or 0xFF (in dword elements padded with garbage). Do the usual palindrome check with a second loop that stops when pointers cross in the middle (or when they both point to the same element if there were an odd number of alphabetic characters). The upward-moving pointer is the stack pointer, and we use POP to load+increment. Instead of compare / setcc in this loop, we can just use XOR to detect same/different since there are only two possible values. We could accumulate (with OR) whether we found any non-matching elements, but an early-out branch on flags set by XOR is at least as good. Notice that the second loop uses `byte` operand-size, so it doesn't care what garbage the first loop leaves outside the low byte of each array element. --- It uses the [undocumented `salc` instruction](https://courses.engr.illinois.edu/ece390/archive/spr2002/books/labmanual/inst-ref-salc.html) to set AL from CF, in the same way that `sbb al,al` would. It's supported on every Intel CPU (except in 64-bit mode), even Knight's Landing! [Agner Fog lists timings for it](http://agner.org/optimize/) on all AMD CPUs as well (including Ryzen), so if x86 vendors insist on tying up that byte of opcode space ever since 8086, we might as well take advantage of it. Interesting tricks: * [unsigned-compare trick](https://stackoverflow.com/questions/35932273/how-to-access-a-char-array-and-change-lower-case-letters-to-upper-case-and-vice/35936844#35936844) for a combined isalpha() and toupper(), and zero-extends the byte to fill eax, setting up for: * immediate bitmap in a register for `bt`, [inspired by some nice compiler output for `switch`](https://stackoverflow.com/questions/97987/advantage-of-switch-over-if-else-statement/32356125#32356125). * Creating a variable-sized array on the stack with push in a loop. (Standard for asm, but not something you can do with C for the implicit-length string version). It uses 4 bytes of stack space for every input character, but saves at least 1 byte vs. optimal golfing around `stosb`. * Instead of cmp/setne on the boolean array, XOR booleans together to get a truth value directly. (`cmp`/`salc` isn't an option, because `salc` only works for CF, and 0xFF-0 doesn't set CF. `sete` is 3 bytes, but would avoid the `inc` outside the loop, for a net cost of 2 bytes (1 in 64-bit mode)) vs. xor in the loop and fixing it with inc. ``` ; explicit-length version: input string in ESI, byte count in ECX 08048060 <dennis_like>: 8048060: 55 push ebp 8048061: 89 e5 mov ebp,esp ; a stack frame lets us restore esp with LEAVE (1B) 8048063: ba ee be ef 03 mov edx,0x3efbeee ; consonant bitmap 08048068 <dennis_like.filter_loop>: 8048068: ac lods al,BYTE PTR ds:[esi] 8048069: 24 5f and al,0x5f ; uppercase 804806b: 2c 41 sub al,0x41 ; range-shift to 0..25 804806d: 3c 19 cmp al,0x19 ; reject non-letters 804806f: 77 05 ja 8048076 <dennis_like.non_alpha> 8048071: 0f a3 c2 bt edx,eax # AL = 0..25 = position in alphabet 8048074: d6 SALC ; set AL=0 or 0xFF from carry. Undocumented insn, but widely supported 8048075: 50 push eax 08048076 <dennis_like.non_alpha>: 8048076: e2 f0 loop 8048068 <dennis_like.filter_loop> # ecx = remaining string bytes ; end of first loop 8048078: 89 ee mov esi,ebp ; ebp = one-past-the-top of the bool array 0804807a <dennis_like.palindrome_loop>: 804807a: 58 pop eax ; read from the bottom 804807b: 83 ee 04 sub esi,0x4 804807e: 32 06 xor al,BYTE PTR [esi] 8048080: 75 04 jne 8048086 <dennis_like.non_palindrome> 8048082: 39 e6 cmp esi,esp ; until the pointers meet or cross in the middle 8048084: 77 f4 ja 804807a <dennis_like.palindrome_loop> 08048086 <dennis_like.non_palindrome>: ; jump or fall-through to here with al holding an inverted boolean 8048086: 40 inc eax 8048087: c9 leave 8048088: c3 ret ;; 0x89 - 0x60 = 41 bytes ``` This is probably also one of the fastest answers, since none of the golfing really hurts too badly, at least for strings under a few thousand characters where the 4x memory usage doesn't cause a lot of cache-misses. (It might also lose to answers that take an early-out for non-Dennis-like strings before looping over all the characters.) `salc` is slower than `setcc` on many CPUs (e.g. 3 uops vs. 1 on Skylake), but a bitmap check with `bt/salc` is still faster than a string-search or regex-match. And there's no startup overhead, so it's extremely cheap for short strings. Doing it in one pass on the fly would mean repeating the classification code for the up and down directions. That would be faster but larger code-size. (Of course if you want fast, you can do 16 or 32 chars at a time with SSE2 or AVX2, still using the compare trick by range-shifting to the bottom of the signed range). --- **Test program (for ia32 or x32 Linux)** to call this function with a cmdline arg, and exit with status = return value. `strlen` implementation from [int80h.org](http://www.int80h.org/strlen/). ``` ; build with the same %define macros as the source below (so this uses 32-bit regs in 32-bit mode) global _start _start: ;%define PTRSIZE 4 ; true for x32 and 32-bit mode. mov esi, [rsp+4 + 4*1] ; esi = argv[1] ;mov rsi, [rsp+8 + 8*1] ; rsi = argv[1] ; For regular x86-64 (not x32) %if IMPLICIT_LENGTH == 0 ; strlen(esi) mov rdi, rsi mov rcx, -1 xor eax, eax repne scasb ; rcx = -strlen - 2 not rcx dec rcx %endif mov eax, 0xFFFFAEBB ; make sure the function works with garbage in EAX call dennis_like ;; use the 32-bit ABI _exit syscall, even in x32 code for simplicity mov ebx, eax mov eax, 1 int 0x80 ; _exit( dennis_like(argv[1]) ) ;; movzx edi, al ; actually mov edi,eax is fine here, too ;; mov eax,231 ; 64-bit ABI exit_group( same thing ) ;; syscall ``` --- A 64-bit version of this function could use `sbb eax,eax`, which is only 2 bytes instead of 3 for `setc al`. It would also need an extra byte for `dec` or `not` at the end (because only 32-bit has 1-byte inc/dec r32). Using the x32 ABI (32-bit pointers in long mode), we can still avoid REX prefixes even though we copy and compare pointers. `setc [rdi]` can write directly to memory, but reserving ECX bytes of stack space costs more code-size than that saves. (And we need to move through the output array. `[rdi+rcx]` takes one extra byte for the addressing mode, but really we need a counter that doesn't update for filtered characters so it's going to be worse than that.) --- **This is the YASM/NASM source with `%if` conditionals. It can be built with `-felf32` (32-bit code) or `-felfx32` (64-bit code with the x32 ABI), and with implicit or explicit length**. I've tested all 4 versions. See [this answer](https://stackoverflow.com/a/36901649/224132) for a script to build a static binary from NASM/YASM source. To test the 64-bit version on a machine without support for the x32 ABI, you can change the pointer regs to 64-bit. (Then simply subtract the number of REX.W=1 prefixes (0x48 bytes) from the count. In this case, 4 instructions need REX prefixes to operate on 64-bit regs). Or simply call it with the `rsp` and the input pointer in the low 4G of address space. ``` %define IMPLICIT_LENGTH 0 ; This source can be built as x32, or as plain old 32-bit mode ; x32 needs to push 64-bit regs, and using them in addressing modes avoids address-size prefixes ; 32-bit code needs to use the 32-bit names everywhere ;%if __BITS__ != 32 ; NASM-only %ifidn __OUTPUT_FORMAT__, elfx32 %define CPUMODE 64 %define STACKWIDTH 8 ; push / pop 8 bytes %else %define CPUMODE 32 %define STACKWIDTH 4 ; push / pop 4 bytes %define rax eax %define rcx ecx %define rsi esi %define rdi edi %define rbp ebp %define rsp esp %endif ; A regular x86-64 version needs 4 REX prefixes to handle 64-bit pointers ; I haven't cluttered the source with that, but I guess stuff like %define ebp rbp would do the trick. ;; Calling convention similar to SysV x32, or to MS vectorcall, but with different arg regs ;; _Bool dennis_like_implicit(const char *esi) ;; _Bool dennis_like_explicit(size_t ecx, const char *esi) global dennis_like dennis_like: ; We want to restore esp later, so make a stack frame for LEAVE push rbp mov ebp, esp ; enter 0,0 is 4 bytes. Only saves bytes if we had a fixed-size allocation to do. ; ZYXWVUTSRQPONMLKJIHGFEDCBA mov edx, 11111011111011111011101110b ; consonant/vowel bitmap for use with bt ;;; assume that len >= 1 %if IMPLICIT_LENGTH lodsb ; pipelining the loop is 1B shorter than jmp .non_alpha .filter_loop: %else .filter_loop: lodsb %endif and al, 0x7F ^ 0x20 ; force ASCII to uppercase. sub al, 'A' ; range-shift to 'A' = 0 cmp al, 'Z'-'A' ; if al was less than 'A', it will be a large unsigned number ja .non_alpha ;; AL = position in alphabet (0-25) bt edx, eax ; 3B %if CPUMODE == 32 salc ; 1B only sets AL = 0 or 0xFF. Not available in 64-bit mode %else sbb eax, eax ; 2B eax = 0 or -1, according to CF. %endif push rax .non_alpha: %if IMPLICIT_LENGTH lodsb test al,al jnz .filter_loop %else loop .filter_loop %endif ; al = potentially garbage if the last char was non-alpha ; esp = bottom of bool array mov esi, ebp ; ebp = one-past-the-top of the bool array .palindrome_loop: pop rax sub esi, STACKWIDTH xor al, [rsi] ; al = (arr[up] != arr[--down]). 8-bit operand-size so flags are set from the non-garbage jnz .non_palindrome cmp esi, esp ja .palindrome_loop .non_palindrome: ; we jump here with al=1 if we found a difference, or drop out of the loop with al=0 for no diff inc eax ;; AL transforms 0 -> 1 or 0xFF -> 0. leave ret ; return value in AL. high bytes of EAX are allowed to contain garbage. ``` I looked at messing around with DF (the direction flag that controls `lodsd` / `scasd` and so on), but it just didn't seem to be a win. The usual ABIs require that DF is cleared on function entry and exit. Assuming cleared on entry but leaving it set on exit would be cheating, IMO. It would be nice to use LODSD / SCASD to avoid the 3-byte `sub esi, 4`, especially in the case where there's no high-garbage. --- ### Alternate bitmap strategy (for x86-64 implicit-length strings) It turns out this doesn't save any bytes, because `bt r32,r32` still works with high garbage in the bit-index. It's just not documented the way `shr` is. Instead of `bt / sbb` to get the bit into / out of CF, use a shift / mask to isolate the bit we want from the bitmap. ``` %if IMPLICIT_LENGTH && CPUMODE == 64 ; incompatible with LOOP for explicit-length, both need ECX. In that case, bt/sbb is best xchg eax, ecx mov eax, 11111011111011111011101110b ; not hoisted out of the loop shr eax, cl and al, 1 %else bt edx, eax sbb eax, eax %endif push rax ``` Since this produces 0/1 in AL at the end (instead of 0/0xFF), we can do the necessary inversion of the return value at the end of the function with `xor al, 1` (2B) instead of `dec eax` (also 2B in x86-64) to still produce a proper [`bool` / `_Bool`](http://en.cppreference.com/w/c/language/arithmetic_types#Boolean_type) return value. This used to save 1B for x86-64 with implicit-length strings, by avoiding the need to zero the high bytes of EAX. (I had been using `and eax, 0x7F ^ 0x20` to force to upper-case and zero the rest of eax with a 3-byte `and r32,imm8`. But now I'm using the 2-byte immediate-with-AL encoding that most 8086 instructions have, like I was already doing for the `sub` and `cmp`.) It loses to `bt`/`salc` in 32-bit mode, and explicit-length strings need ECX for the count so this doesn't work there either. But then I realized that I was wrong: `bt edx, eax` still works with high garbage in eax. It masks the shift count [the same way `shr r32, cl` does](http://felixcloutier.com/x86/SAL:SAR:SHL:SHR.html) (looking only at the low 5 bits of cl). This is different from `bt [mem], reg`, which can access outside the memory referenced by the addressing-mode/size, treating it as a bitstring. (Crazy CISC...) Intel's insn set ref [manual entry for `bt`](https://www.felixcloutier.com/x86/bt) does document the masking in the description section: *If the bit base operand specifies a register, the instruction takes the modulo 16, 32, or 64 of the bit offset operand (modulo size depends on the mode and register size).* Apparently I missed it when writing this answer originally; I checked a Jan 2015 version of the PDF and it was already there. A neat trick here is using `xchg eax,ecx` (1 byte) to get the count into CL. Unfortunately, BMI2 `shrx eax, edx, eax` is 5 bytes, vs. only 2 bytes for `shr eax, cl`. Using `bextr` needs a 2-byte `mov ah,1` (for the number of bits to extract), so it's again 5 + 2 bytes like SHRX + AND. --- The source code has gotten pretty messy after adding `%if` conditionals. **Here's disassembly of x32 implicit-length strings** (using the alternate strategy for the bitmap, so it's still 46 bytes). The main difference from the explicit-length version is in the first loop. Notice how there's a `lods` before it, and at the bottom, instead of just one at the top of the loop. ``` ; 64-bit implicit-length version using the alternate bitmap strategy 00400060 <dennis_like>: 400060: 55 push rbp 400061: 89 e5 mov ebp,esp 400063: ac lods al,BYTE PTR ds:[rsi] 00400064 <dennis_like.filter_loop>: 400064: 24 5f and al,0x5f 400066: 2c 41 sub al,0x41 400068: 3c 19 cmp al,0x19 40006a: 77 0b ja 400077 <dennis_like.non_alpha> 40006c: 91 xchg ecx,eax 40006d: b8 ee be ef 03 mov eax,0x3efbeee ; inside the loop since SHR destroys it 400072: d3 e8 shr eax,cl 400074: 24 01 and al,0x1 400076: 50 push rax 00400077 <dennis_like.non_alpha>: 400077: ac lods al,BYTE PTR ds:[rsi] 400078: 84 c0 test al,al 40007a: 75 e8 jne 400064 <dennis_like.filter_loop> 40007c: 89 ee mov esi,ebp 0040007e <dennis_like.palindrome_loop>: 40007e: 58 pop rax 40007f: 83 ee 08 sub esi,0x8 400082: 32 06 xor al,BYTE PTR [rsi] 400084: 75 04 jne 40008a <dennis_like.non_palindrome> 400086: 39 e6 cmp esi,esp 400088: 77 f4 ja 40007e <dennis_like.palindrome_loop> 0040008a <dennis_like.non_palindrome>: 40008a: ff c8 dec eax ; invert the 0 / non-zero status of AL. xor al,1 works too, and produces a proper bool. 40008c: c9 leave 40008d: c3 ret 0x8e - 0x60 = 0x2e = 46 bytes ``` Update: instead of using 32-bit pointers, I could have used `push rsp` / `pop rbp` to copy a 64-bit register in 2 bytes of code. ([Tips for golfing in x86/x64 machine code](https://codegolf.stackexchange.com/questions/132981/tips-for-golfing-in-x86-x64-machine-code/190636#190636)). But `sub rsi,0x8` and `cmp rsi,rsp` would need REX prefixes which I'm avoiding here by using 32-bit pointers. Perhaps comparing the low 32 could work if the stack doesn't cross a 4GiB boundary, so just the `sub`. I wonder if `pop rdx` / `std` / `lodsq` / `cld` / `xor al, dl` could work? No, that's 7 bytes, break-even with just using `sub rsi, 8` in the loop body. [Answer] # [Retina](https://github.com/m-ender/retina), ~~49 47~~ 45 bytes ``` \P{L} i`[aeiou] 1 \D 2 +`^(.)(.*)\1$ $2 ^.?$ ``` [Try it online!](https://tio.run/##LcxZd8FAGIDh@@9XpAQJ7ZBo6WYJsYutOxEJBmOZYVBa1b8ePU5v3ufu5XhDqOP6pILtmo1D9QhA7I6DCdt2QQFTBxVCtiUhWUJB2VREEFWwUEp0XR1TStZgOPxv8Y@Qo0PMQZvj/TmChkBnjM8o64OBxwyEC49X9PkDkhwMXV6hcERRo9c3sfjt3f3DYyKZSmuZrJ7LF4qlcqVq1OqNZuvp@eX17f2j3TG7Vs92@oMhHo0nZDqbLyhbrvh6s/3c7b@@Dz/H3xM "Retina – Try It Online") Saved 2 bytes thanks to Neil. Saved another 2 bytes thanks to Martin. Removes non-letters then replaces vowels with 1 and consonants with 2, to get consistent values. Then repeatedly removes the first and last character if they are the same. Once they aren't, the word was symmetric if there are one or zero characters remaining. [Answer] # PHP, 82 Bytes ``` <?=strrev($s=preg_replace(["#[^a-z]#i","#[aeiou]#i","#\pL#"],["",0,1],$argn))==$s; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zVfJNLCrJzFNwzUtJLVKy5rK3@29jb1tcUlSUWqahUmxbUJSaHl@UWpCTmJyqEa2kHB2XqFsVq5yppANkJ6Zm5pdCOTEFPspKsTrRSko6BjqGsTpg4zU1bW1Viq3//wcA "PHP – TIO Nexus") [Answer] # MATL, 14 bytes ``` t3Y2m)13Y2mtP= ``` Try it at [MATL Online](https://matl.io/?code=t3Y2m%2913Y2mtP%3D&inputs=%27Martin+Ender%27&version=20.0.0). [Here](https://matl.io/?code=%60i%0A++++t3Y2m%2913Y2mtP%3D%0A%3F%27TRUE%27D%7D%27FALSE%27D%5DT&inputs=%27Dennis%27%0A%27Martin%27%0A%27Martin+Ender%27%0A%27Alex%27%0A%27Alex+A.%27%0A%27Doorknob%27%0A%27Mego%27&version=20.0.0) is a slightly modified version to check all test cases. **Explanation** ``` % Implicitly grab the input as a string % STACK: {'Martin Ender'} t % Duplicate the input % STACK: {'Martin Ender', 'Martin Ender'} 3Y2 % Push the string 'ABC...XYZabc...xyz' % STACK: {'Martin Ender', 'Martin Ender', 'ABC...XYZabc...xyz'} m % Find which characters of the input are letters using this string % STACK: {'Martin Ender', [1 1 1 1 1 1 0 1 1 1 1]} ) % Use this boolean array to select only the letters % STACK: {'MartinEnder'} 13Y2 % Push the string literal 'aeiouAEIOU' to the stack % STACK: {'MartinEnder', 'aeiouAEIOU'} m % Check for membership of each letter of the input in this string. % STACK: {[0 1 0 0 1 0 1 0 0 1 0]} tP % Create a reversed copy % STACK: {[0 1 0 0 1 0 1 0 0 1 0], [0 1 0 0 1 0 1 0 0 1 0]} = % Perform an element-wise comparison yielding a truthy (all 1's) or % falsey (any 0's) result % STACK: {[1 1 1 1 1 1 1 1 1 1 1]} % Implicitly display the result ``` [Answer] # Haskell, 84 75 74 69 bytes -10 thanks to @nimi -5 thanks to @Zgarb ``` f x=(==)<*>reverse$[elem c"aeiouAEIOU"|c<-x,'@'<c,c<'{','`'<c||c<'['] ``` The list comprehension replaces each letter with a boolean and removes all other characters. The first part checks whether or not the resulting list is a palindrome. [Try it online!](https://tio.run/nexus/haskell#@5@mUGGrYWuraaNlV5RallpUnKoSnZqTmquQrJSYmplf6ujq6R@qVJNso1uho@6gbpOsk2yjXq2uo54AZNcAxdWj1WO5uHITM/MUbBVS8rkUFAqKMvNKFDTSFJQyUnNy8pU0UcRS8tPRRBJNTCz0rPXTdQ0sLcxLUtFkDU3QBAwsE4Em/P8PAA "Haskell – TIO Nexus") [Answer] # Pyth, ~~18~~ 15 bytes ``` _I/L"aeiou"@Gr0 ``` [Try it here.](http://pyth.herokuapp.com/?code=_I%2FL%22aeiou%22%40Gr0&test_suite=1&test_suite_input=%22Dennis%22%0A%22Martin%22%0A%22Martin+Ender%22%0A%22Alex%22%0A%22Alex+A.%22%0A%22Doorknob%22%0A%22Mego%22&debug=0) -2 thanks to [KarlKastor](https://codegolf.stackexchange.com/users/56557/karlkastor), and subsequently -1. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes ``` ḷ{∈Ṿg|∈Ḅg}ˢ.↔ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9wx/bqRx0dD3fuS68B0Tta0mtPL9J71Dbl/38lx5zUCgVHPaX/AA "Brachylog – TIO Nexus") ### Explanation ``` ḷ Lowercase the input { }ˢ. Select each char if: ∈Ṿg it's a vowel, and replace it with ["aeiou"] | Or ∈Ḅg it's a consonant, and replace it with ["bcdfghjklkmnpqrstvwxyz"] .↔ The resulting list is a palindrome ``` [Answer] # [Alice](https://github.com/m-ender/alice), 28 bytes ``` /uia.QN."-e@ \1"lyuy.Ra$i1/o ``` [Try it online!](https://tio.run/##S8zJTE79/1@/NDNRL9BPT0k31YErxlApp7K0Ui8oUSXTUD///3@X1Ly8zGIA "Alice – Try It Online") Outputs `1` as truthy and nothing as falsy. ### Explanation Every command in this program executes in ordinal mode, but with a slight twist in the template that allows me to save a byte. If a newline is an acceptable truthy value, I can save one more byte by the same method. Linearized, the program is as follows: ``` 1il.uN."aei ou"ayQy.R-$@1o1@ 1 % Append "1" to top of stack % STACK: ["1"] i % Push input to stack % STACK: ["1", "Dennis"] l % Convert to lowercase % STACK: ["1", "dennis"] . % Duplicate % STACK: ["1", "dennis", "dennis"] u % Convert to uppercase % STACK: ["1", "dennis", "DENNIS"] N % Take multiset difference; this removes all non-alphabetic characters % STACK: ["1", "dennis"] . % Duplicate % STACK: ["1", "dennis", "dennis"] "aei ou" % Push "aei ou" % STACK: ["1", "dennis", "dennis", "aei ou"] a % Push newline % STACK: ["1", "dennis", "dennis", "aeiou", "\n"] y % Transliterate: replace all vowels with newlines % STACK: ["1", "dennis", "d\nnn\ns"] Q % Reverse stack % STACK: ["d\nnn\ns", "dennis", "1"] y % Transliterate: replace remaining characters with "1" % STACK: ["1\n11\n1"] . % Duplicate % STACK: ["1\n11\n1", "1\n11\n1"] R % Reverse top of stack % STACK: ["1\n11\n1", "1\n11\n1"] - % Remove occurrences: for same-length strings, result is "" iff strings are equal. % STACK: [""] $ % Pop stack, and skip next command if "" @ % Terminate (skipped if c/v pattern is palindromic) 1o % Output "1" 1 % Push "1" (useless) @ % Terminate ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~72~~ 71 bytes -1 byte thanks to @ovs ``` def f(s):s=[c in'AEIOU'for c in s.upper()if'@'<c<'['];return s==s[::-1] ``` [Try it online!](https://tio.run/nexus/python3#@5@SmqaQplGsaVVsG52skJmn7ujq6R@qnpZfpADiKhTrlRYUpBZpaGamqTuo2yTbqEerx1oXpZaUFgElbW2Lo62sdA1j//8HAA "Python 3 – TIO Nexus") [Answer] ## JavaScript (ES6), ~~72~~ 69 bytes *Saved 3 bytes thanks to Neil* Returns a boolean. ``` s=>(a=s.match(/[a-z]/gi).map(c=>!/[aeiou]/i.exec(c)))+''==a.reverse() ``` ### Test cases ``` let f = s=>(a=s.match(/[a-z]/gi).map(c=>!/[aeiou]/i.exec(c)))+''==a.reverse() console.log(f("Dennis")) // -> truthy console.log(f("Martin")) // -> truthy console.log(f("Martin Ender")) // -> truthy console.log(f("Alex")) // -> falsy console.log(f("Alex A.")) // -> truthy console.log(f("Doorknob")) // -> falsy console.log(f("Mego")) // -> falsy ``` [Answer] # Braingolf, ~~4~~ 3 bytes ``` &JP ``` *-1 byte thanks to Erik the Outgolfer* Turns out I had `P` all along, even before this challenge. ~~`J` however, despite being created before this challenge, wasn't pushed to github before the challenge, thus is still non-competing.~~ ### Explanation: ``` &JP Implicit input, push ASCII value of each char in string to stack &J Replace each item in stack with 1 if vowel, otherwise 0 P Pop entire stack, push 1 if stack is palindromic, 0 otherwise Implicit output of last item on stack ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` ǍAḂ⁼ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHjUHhuILigbwiLCIiLCJEZW5uaXMiXQ==) ``` Ǎ # Non-alphabet chars removed A # Vowel mask (1 for vowel, 0 for not) Ḃ⁼ # Is equal to its reverse? ``` # [Vyxal 2.4.1](https://github.com/Vyxal/Vyxal/releases/tag/v2.4.1), 7 bytes ``` Ǎk∨vcḂ⁼ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C7%8Dk%E2%88%A8vc%E1%B8%82%E2%81%BC&inputs=eoiurhejweiei&header=&footer=) -6 thanks to lyxal -1 thanks to Underslash [Answer] # [Python 3](https://docs.python.org/3/), ~~92~~ ~~87~~ ~~74~~ ~~72~~ ~~69~~ 68 bytes ``` l=[c in'aeouiAEOUI'for c in input()if c.isalpha()] print(l==l[::-1]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P8c2OlkhM089MTW/NNPR1T/UUz0tv0gBJAZEBaUlGpqZaQrJepnFiTkFGYkamrFcBUWZeSUaOba2OdFWVrqGsZr//7uk5uVlFgMA "Python 3 – Try It Online") [Answer] # Mathematica, 113 bytes ``` PalindromeQ@StringCases[StringReplace[#,{Characters["aeiouAEIOU"]->"1",CharacterRange["A","z"]->"0"}],{"0","1"}]& ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 42 bytes ``` {123,65>.26>6<-?)},{"AEIOUaeiou"?)!}%.-1%= ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v9rQyFjHzNROz8jMzsxG116zVqdaydHV0z80MTUzv1TJXlOxVlVP11DV9v9/x5zUCgVHPQA "GolfScript – Try It Online") The hard part is generating both the uppercase and lowercase alphabet in one string, which we'll use in a filter function to filter the letters out of the input. Luckily, since strings in GolfScript are just codepoint arrays with a special property, so we can just generate the codepoints in an efficient way. Here's how we generate them: First, we generate range [0..122], 122 being the codepoint for `z`. Then, we take the elements from the element at index 65 onwards. 65 is the codepoint for `A`. Right now, we have [65..122]. All fine, except we have some unwanted codepoints ([91..96]) in there. So, we first make a duplicate of that range. Then, we take the elements from index 26 onwards, and we have [91..122]. After that, we get the elements up to and including index 5. Now we have [91..96]. Finally, we remove those elements from our [65..122], leaving us wil [65..90, 97..122]. Those are the codepoints we want. Now that we made the upper/lower alphabet codepoint list, we continue our filtering function. The function gets mapped to each character on the input string, which, as I initially said, gets parsed as its codepoint instead. So now we essentially have `[codepoint, [65..90, 97..122]]`. To find out if char `codepoint` is a letter, we simply take its index in the list we made. If it isn't there, we'll get `-1` as the index instead. Right now, we get a falsey value only if `codepoint == 65`, i.e. the first index of our list, since only then would the index be 0. But a single increment will fix this problem, and, now, if `codepoint` is in our list, we'll get its index + 1, which is always a positive number, thus always truthy, while if it's not there we'll get -1 + 1 = 0, i.e. falsey. We finally apply the function I described to every char of the input, and we only take the chars for which the function returned a truthy result. Next up we have to determine if each char is a vowel or consonant. Since the vowels are fewer than the consonants, creating a string of vowels so that we check for that condition is shorter than creating a string of consonants, so we check if each char is a vowel. But, to check if the boolean list is palindromic, we need booleans, which we don't get just by taking the index + 1, since that can result in any number of [1..10] if the char is a vowel. And, as most golfing languages, this one, doesn't have a `bool` function either. So, we simply use `not not x`, since `not` always returns a boolean. But wait; do we really need to have specific booleans? Since `not` always returns a boolean, why don't we just remove the second `not`, and actually check if each char is a consonant? Yeah, that's exactly what we'll do! After the check, which returns a list of booleans, we check if this boolean list we got is a palindrome, which is what this challenge asks us to do. Well, what is the definition of a palindrome? Yes, a palindrome is a list or string which is equal to its reverse. So, how do we check? Simple, we duplicate it, take its reverse, and check against the original list. The result we get is, *finally*, what our code should return. [Answer] # [PHP](https://php.net/), 87 bytes Regex free PHP version. Added a "vowel" since stripos can return 0 which is false in PHP. Flaw fixed by Jörg. ``` for(;a&$c=$argn[$p++];)!ctype_alpha($c)?:$s.=stripos(_aeiou,$c)?0:1;echo$s==strrev($s); ``` [Try it online!](https://tio.run/nexus/php#HclRCoMwDADQ/91CCdLiGO7XrHgCTyBDQqlrYdiQdANP3@F@33tMHPkCJK/dtTNJSXuLdctikDrw7j8LcN8/0Ta@HBxWenMkA95OI@jNaZHEWc1KIeXP9fRhvGPwMYO6syV8DajFWn8 "PHP – TIO Nexus") [Answer] # q/kdb+, ~~42~~ 38 bytes **Solution:** ``` {x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower ``` **Example:** ``` q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Dennis" 1b q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Adam" 0b q){x~|:[x]}{inter[x;.Q.a]in"aeiou"}lower"Alex A." 1b ``` **Explanation:** ``` lower // converts argument on the right to lowercase .Q.a // lowercase alphabet "abc..xyz" inter[x;y] // intersection of x and y (thus only return a-z) x in "aeiou" // returns boolean list whether x is a vowel; "dennis" = 010010b |: // k shorthand for 'reverse' ``` **Edits:** * -4 bytes; switching out `reverse` for k equivalent `|:` [Answer] # [CJam](https://sourceforge.net/p/cjam), 26 bytes ``` lel_'{,97>--"aeiou"fe=_W%= ``` [Try it online!](https://tio.run/##S85KzP3/Pyc1J169WsfS3E5XVykxNTO/VCkt1TY@XNX2/3/HnNQKBUc9AA "CJam – Try It Online") -1 thanks to [Esolanging Fruit](https://codegolf.stackexchange.com/users/61384/esolanging-fruit). [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ⌠╟%╜«¥│▒g♦°pC₧╤WsV ``` [Run and debug it](https://staxlang.xyz/#c=%5E%22%5B%5EA-Z%5D%22zR%7BVVI0%3CFLcr%3D&i=Dennis%0AMartin%0AMartin+Ender%0AAlex%0AAlex+A.%0ADoorknob%0AMego&m=2) ## Explanation ``` ^"[^A-Z]"zR{VVI0<FLcr= ^ capitalize input "[^A-Z]"zR remove all non alphabet characters { F loop over modified string VV "AEIOU" I Index of character (-1 if not present) 0< less than 0 push the result to stack L wrap the stack in an array c duplicate it r reverse it = are they equal? ``` [Answer] # Python 2, 83 bytes ``` def f(x):k=map(lambda y:y.lower()in"aeiou",filter(str.isalpha,x));return k==k[::-1] ``` Defines a function that either gives `True` or `False` [Answer] # [CJam](https://sourceforge.net/p/cjam), 79 bytes First-timer! (I did what I could) ``` r{:X"AEIOUaeiou"#W>{X"BCDFGHJKLMNPQRSTVWXYZbdfghjklmnpqrstvwxyz"#W={'0}&}'1?~}% ``` [Try it online!](https://tio.run/nexus/cjam#@19UbRWh5Ojq6R@amJqZX6qkHG5XHaHk5Ozi5u7h5e3j6xcQGBQcEhYeERmVlJKWnpGVnZObV1BYVFxSVl5RWQVUb1utblCrVqtuaF9Xq/r/v0tqXl5mMQA "CJam – TIO Nexus") [Answer] # Ruby, 57 bytes ``` ->s{x=s.scan(/\p{L}/).map{|c|c=~/[aeiou]/i};x==x.reverse} ``` [Try it online!](https://tio.run/nexus/ruby#S7P9r2tXXF1hW6xXnJyYp6EfU1DtU6uvqZebWFBdk1yTbFunH52YmplfGqufWWtdYWtboVeUWpZaVJxa@79AIS1aySU1Ly@zWCmWC8zzTSwqycxD5Sm45qWkFsHEHHNSK5DZCo56MK5Lfn5Rdl5@Elx7anq@Uux/AA "Ruby – TIO Nexus") [Answer] # [Bash](https://www.gnu.org/software/bash/), 82 bytes ``` i=${1//[^a-zA-Z]};a=aeouiAEOUI;b=${i//[$a]/0};c=${b//[!0$a]/1};[ $c = `rev<<<$c` ] ``` [Try it online!](https://tio.run/nexus/bash#LY27DoJAEEV7v@JKNnYIti7EkEBhQaxsJBgWGHWj2UnWR3zx7bgSmjv3nElmDmyhoQ1SMkZfkSt7c@SNMzMtWQ/JhZ7whkzmHlJmezZcI6cjQ6LlCTUnhm8g9FL2OhYfHQTFXvnvxN@VnVSxIr7rJNts17Ie10KVQdjJxmHtcBr@xaKTBUSDGJWlRxRFoqlQ9s6t3H1CiHI2G76Z7xdDeclJy4b6Hw "Bash – TIO Nexus") Recives name as parameter, removes non-leters, replaces vowels with 0, non-vowels nor 0 with 1 and compares with same reversed. Could golf some more if can get to work [double or triple substitution](https://unix.stackexchange.com/questions/68042/double-and-triple-substitution-in-bash-and-zsh) Exit status is 0 for true and 1 for no. [Answer] ## Perl, 42 bytes ``` s!(.)\PL*!1+aeiou=~lc$1!ge;$_=$_==reverse ``` Run with `perl -p`. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~19~~ 11 bytes ``` k\L mè\v ê¬ ``` [Try it online](https://ethproductions.github.io/japt/?v=2.0a0&code=a1xMIG3oXHYg6qw=&input=IkRlbm5pcyI=) --- ## Explanation ``` :Implicit input of string U. k\L :Remove all non-letter characters from U. m :Map over resulting string, replacing each character ... è\v :with the count of the number of vowels in each single character substring. ê¬ :Is the above a palindrome? :Implicit output of boolean result. ``` [Answer] # 64-bit machine code, 89 bytes. A function of following signature: `eax = f(char * edi)` ``` 48 89 F8 48 89 FE 41 B8 22 82 20 00 8A 0E 84 C9 74 23 89 CA 83 E2 DF 0F BE D2 83 EA 41 83 FA 19 77 0E 44 89 C2 48 FF C0 D3 FA 83 E2 01 88 50 FF 48 FF C6 EB D7 C6 00 02 48 FF C7 48 FF C8 8A 17 40 8A 30 40 38 77 FF 75 05 80 FA 02 75 EA 31 C0 80 FA 02 0F 94 C0 C3 ``` Assembled using NASM, from such assembly code: ``` ; edi => input string. ; eax <= 1 or 0. ; notes: ; the string needs to be null terminated and located in a ; writable memory location, as it will be mutated. BITS 64 DENNIS: MOV RAX, RDI MOV RSI, RDI MOV R8D, 0x208222 .CTOR: MOV CL, BYTE [RSI] TEST CL, CL JE .SP MOV EDX, ECX AND EDX, -33 MOVSX EDX, DL SUB EDX, 65 CMP EDX, 25 JA .LI MOV EDX, R8D INC RAX SAR EDX, CL AND EDX, 1 MOV BYTE [RAX-1], DL .LI: INC RSI JMP .CTOR .SP: MOV BYTE [RAX], 2 .EQL: INC RDI DEC RAX MOV DL, BYTE [RDI] MOV SIL, BYTE [RAX] CMP BYTE [RDI-1], SIL JNE .EQE CMP DL, 2 JNE .EQL .EQE: XOR EAX, EAX CMP DL, 2 SETE AL RET ``` Not a killer, not even close, but it has a couple of advantages over the 41-byte answer: * Requires no memory (not even stack). * Doesn't require to check the length of a string - it uses null-termination instead. * Doesn't use undocumented CPU instructions. Just my $0.02 :). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~34~~ ~~33~~ 24 bytes Saved bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319) ``` ≡∘⌽⍨'AEIOU'∊⍨⎕a∩⍨819⌶⍨∘1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24RHnQsfdcx41LP3Ue8KdUdXT/9Q9UcdXUDOo76piY86VgJZFoaWj3q2gYQ6ZhgCdR1aoe6SmpeXWayuoO6bWFSSmQdnKLjmpaQWAbmOOakVUErBUQ/IcsnPL8rOy08CKU1Nz1cHAA "APL (Dyalog Unicode) – Try It Online") `819⌶⍨∘1` uppercase argument `⎕a∩⍨` intersection with uppercase alphabet `'AEIOU'∊⍨` belongs-to-`'AEIOU'`? resulting in a boolean vector `≡∘⌽⍨` reversed equivalent to self? [Answer] # [C (gcc)](https://gcc.gnu.org/), 130 bytes ``` d(a,l)char*a,*l;{char*y=alloca(*l),*z=y;for(*l=1;*a;a++)if(isalpha(*a))*y++=!strchr("aeiou",*a|32);for(a=y-z;a--;*l*=*z++==*--y);} ``` [Try it online!](https://tio.run/##ZY/BTsMwEETPzVcYS0W2EyNRblg@VCpH/oDL4jiJxWJXdhAkJb9OiNNLBLeZp5nRrpGtMfNcM6iQmw6igEqguqxy0IAYDDCBvBKjHlQT4mL0vRKgoCy5a5hLgOduyQDnYihLfZP6aLrIKFgXPmgl4PvhwNcq6EGOCqRUAoUW45LWQsqBq2nuberZ9QJ@KXZZESSaLGtoPQOuil0@8xazOkfn@4bRfXok@/rF0yo/oIqpeAfnWV5YB@nJeu8SzZ0reIbYO/8PkCdf27jBR7Rffyw53m3IKYT45sPrdsq2Idtp/jENQptm@fkL "C (gcc) – Try It Online") Takes input as the string and its length, with the length passed by reference (`d(str, &len)`), and outputs by modifying `len`. ]
[Question] [ Consider these seven ASCII train cars. **Engine (E)** ``` __ ====== \/ | [] |========= | ) ================ O-O-O O-O-O \\ ``` **Passenger car (P)** ``` =============== | [] [] [] [] | =============== O-O O-O ``` **Boxcar (B)** ``` =============== |-|-| | |-|-| =============== O-O O-O ``` **Tanker (T)** ``` _____---_____ ( ) =============== O-O O-O ``` **Hopper (H)** ``` _______________ \ | | | | | | / =============== O-O O-O ``` **Flatbed (F)** ``` =============== O-O O-O ``` **Caboose (C)** ``` ===== ====| |==== | [] [] | ============= O-O O-O ``` Write a program that when given a sequence of the characters `EPBTHFC`, outputs its ASCII train representation, using `--` for the car couplings. The leftmost input characters become the rightmost train cars. The train is always facing right. For example, an input of `EEHTBPFC` should produce ``` __ __ ===== ====== \/ ====== \/ ====| |==== =============== =============== _____---_____ _______________ | [] |========= | [] |========= | [] [] | | [] [] [] [] | |-|-| | |-|-| ( ) \ | | | | | | / | ) | ) =============--===============--===============--===============--===============--===============--================--================ O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O-O O-O-O \\ O-O-O O-O-O \\ ``` ## Details * This is code golf; the shortest program in bytes wins. * Any sequence of one or more of the letters `EPBTHFC` is valid input. * Your program must be able to output all 7 car types exactly as they appear above. * Take input from the command line or directly from the user (e.g. message box). Output to stdout. (Quotes around input are fine.) * The height of the output should either be 6 or the maximum height needed for the train cars being drawn. * Do not put couplings (`--`) at the front of the first car or the back of the last car. [Answer] ### Python, 464 ``` from curses import* E,P,B,T,H,F,C='eJyNkM0NgDAIhe9MwVEPpBN0AxMHsKaLdHgfpVr7E+NHUyCQR4C5EiP5jKXBUeLj5ORvkDes5DtEiHeBoWo+hI36NtN9XurrRaVMQTSTEBizPo3+SGBBICLZ0/K9y0whtlDA/Gruj8SwyaRJA9tSPz16qmdTxqO9VeAvC5VloQ=='.decode('base64').decode('zlib').split('L') i=[s.split('\n')for s in map(eval,raw_input()[::-1])] h=max(sum(map(bool,s))for s in i) w=initscr() x=0 for t in i:[w.addstr(y,x,t[y+6-h])for y in range(h)];x+=len(t[-2]) w.addstr(h-2,x-2,' ') w.getch() endwin() ``` I went for an approach using curses. It can't really compete, but I had some fun with it (~630 bytes): ![train](https://i.stack.imgur.com/M5AY6.gif) ``` from curses import* E,P,B,T,H,F,C='eJyFkMENwCAIRe9M8Y/tgTiBGzTpALVxEYcvSFqiNO2DCAb8BgCnVsodu5ZEDceJlm/kPrBSniDsLCY1i6VsNDeZ6uMt1GEKMJU3ARYD1DX7F5DRBGbukZbvKeL7OkJF/nZL/wJxhrlFE6vooYtuviwlrso1JF745GMr'.decode('base64').decode('zlib').split('L') i=[s.split('\n')for s in map(eval,raw_input()[::-1])] h=max(sum(map(bool,s))for s in i) w=initscr() m=w.getmaxyx()[1] for o in range(-sum(2+len(t[-2])for t in i),m): x=o for t in i: if m>x>o:w.addnstr(h-2,max(x,0),'--'[max(0,-x):],m-x);x+=2 [w.addnstr(y,max(x,0),t[y+6-h][max(0,-x):],m-x)for y in range(h)if x<m];x+=len(t[-2]) w.move(h,0);w.refresh();w.clear();napms(90) endwin() ``` [Answer] # Perl, 265 bytes Since this entry contains bytes that do not correspond to printable ASCII characters, it cannot be copy-pasted here directly. Instead, I am providing it as a hex dump. Users on Unix-ish systems can reconstruct the script by feeding the following hex dump to the `xxd -r` command: ``` 0000000: 7573 6520 436f 6d70 7265 7373 275a 6c69 use Compress'Zli 0000010: 623b 6576 616c 2075 6e63 6f6d 7072 6573 b;eval uncompres 0000020: 7320 2778 daad 9241 6b83 3014 c7ef f914 s 'x...Ak.0..... 0000030: ef10 6add f67c 5ed6 8b06 c646 476f dda1 ..j..|^....FGo.. 0000040: 3723 c183 1d85 8212 c740 087e f625 a6a3 7#.......@.~.%.. 0000050: b1f6 24fd 3de1 3d7f e8fb e790 b74a 74ed ..$.=.=......Jt. 0000060: f9f4 c3e9 25cf a328 6310 a094 6b4c 8c78 ....%..(c...kL.x 0000070: 2569 5406 8a12 8cf8 c7ab 09b1 ff71 0222 %iT..........q." 0000080: 833d da02 b874 2981 c10d 3333 df74 39c1 .=...t)...33.t9. 0000090: f531 d6dc 0f03 8f9f 9666 a12d 7021 6e7a .1.......f.-p!nz 00000a0: 6416 2807 228e dd99 3584 c40f cc52 53ac d.(."...5....RS. 00000b0: 9160 82a2 4559 0bcd a22c ff2e 1cc1 0e63 .`..EY...,.....c 00000c0: 9d09 6f85 25b8 13b3 8470 3fe3 5c27 a1eb ..o.%....p?.\'.. 00000d0: df5a 7735 b44d 2b86 9eb6 5fef 87dd e707 .Zw5.M+..._..... 00000e0: a5b8 219d b1ae eaed 3743 4709 f1aa d83c ..!.....7CG....< 00000f0: f1d5 3357 257d 6be7 1039 9186 63a3 214d ..3W%}k..9..c.!M 0000100: 9257 f607 1251 a1e7 27 .W...Q..' ``` The script uses the Perl 5.10 `say` feature, and so needs to be run with `perl -M5.010`. It takes a single command line argument consisting of the letters `EPBTHFC` and outputs the corresponding train car arrangement. For example, the input `FEH` produces the following output: ``` __ ====== \/ _______________ | [] |========= \ | | | | | | / | ) ===============--================--=============== O-O O-O O-O-O O-O-O \\ O-O O-O ``` The readable code at the beginning of the script simply decompressed the zlib-compressed string containing the body of the script and evals it. The decompressed code, in turn, looks like this: ``` @a=split$/,<<''; __ ====== \/ | [] |========= | ) ================-- O-O-O O-O-O \\ =============== | [] [] [] [] | ===============-- O-O O-O =============== |-|-| | |-|-| ===============-- O-O O-O _____---_____ ( ) ===============-- O-O O-O _______________ \ | | | | | | / ===============-- O-O O-O ===============-- O-O O-O ===== ====| |==== | [] [] | =============-- O-O O-O $i=reverse pop=~y/EPBTHFC/0-6/r; say$i=~s/./$a[6*$&+$_]/gr=~s/--$//r for 0..5 ``` Note that all the train cars have their lines padded with spaces to a uniform length, and include the coupling (which is stripped from the rightmost car by the output loop). The DEFLATE compression used by zlib is very good at compressing such repetitive data, so there's no need to try and compress it by hand. Note that this is a quick first attempt. I'm sure it would be possible to shave several bytes off the length by playing with variations such as reordering the train cars in the source. [Answer] ## Python (~~582~~ ~~488~~ ~~476~~ 450 Chars) ``` import sys A=sys.argv[1] h=0 c='eJyVkrEKAzEIhnef4h97g9x+kOVKS7d2uK0peZE8fNXQS3NCpb+BREU/YnIhfKkUgJKpBfIsgYrnCzV9pIFBE6WDCHcWk1zbMy0PGovg/GMPw+6rujwaAY0CWtb/ESwG6NJTjNhChMxQxMy2g06/R+URtxBRRlGWC3SbY8Q1vkXgh4gz+Qb7v7Jy/US1P7TKP3NvbG3fy/V/Cw=='.decode('base64').decode('zlib').split(':') C={} for x in c:X=x.split('\n');C[X[0]]=X[1:-1] for c in A:h=max(h,1+('F..CE'.find(c)+1or 3)) for y in range(6-h,6):print(' -'[y==4]*2).join(C[c][y]for c in A[::-1]) ``` The ascii-salad is a base64 encoded zlib-compressed string containing the figures... [Answer] # Python, ~~402~~ 369 ``` import sys for n in range(6): l= sys.argv[1][::-1] for x,y in zip("EPBTHFC",range(0,42,6)): l=l.replace(x,'eJytktsNgCAMRVfpp340TMAHEziAGBZhePvgLYmGeGosXqQXSAEqIfDbWUElb0SKcF4QbUaljr0srCA6OJCC5jV7cDAyUYY6eQPlic9/kleqoKNVL6QANkmj37zohglElMzK9naJy16hhxRPR6ph/jzXB2XBS76bZpQa3Hex7Qpm1hOtg+Yb0a6PSA=='.decode('base64').decode('zlib').split('A')[y+n]).strip('-') print l ``` Thanks you for the improvements, ugoren! [Answer] ## [Java 10](https://developer.oracle.com/java/jdk-10-local-variable-type-inference.html), ~~637~~ ~~617~~ ~~600~~ ~~595~~ ~~593~~ 592 chars ``` interface T{static void main(String[]u){String g=" ",n=g+g,m=n+g,s=m+m,h=s+s,q=h+m,o=" O-O",w=o+s+o+n,y="=",d=y+y+y,p="_____",b=d+d,e=b+b,f=n+n,t=e+d,c="|",l=g+c,z=l+l+l,v="|-|-|",k=" []",x=k+k,r=k+l,a[]={h+"__"+n,b+s+"\\/"+n,c+r+b+d+g,c+h+n+")",t+y,o+"-O"+n+o+"-O \\\\",q,q,t,c+x+x+l,t,w,q,q,t,v+g+l+n+v,t,w,q,q,g+p+"---"+p+g,"("+h+" )",t,w,q,q,p+p+p,"\\"+z+z+" /",t,w,q,q,q,q,t,w,h+g,f+d+y+y+f,d+y+c+m+c+d+y,c+k+f+r,e+y,o+f+o+n,n,n,n,n,"--",g};var O=System.out;for(int i=-1,j;i++<5;O.println())for(j=u[1].length();j-->0;O.print(a["EPBTHFC".indexOf(u[1].charAt(j))*6+i]+(j>0?a[42+i]:"")));}} ``` [Try it online!](https://tio.run/##RVFdb5tAEPwraJ@guzhJ1fahdFM1kaO8ESl@wyg6vsFwEDhjO47/eunifPRG3A17c7Oju0qNyq2SzTSV2qR9puLUWh0Ho0wZW2NbJlajSm0/mr7UeRBuneMbtXIGC0hzjjk1rGUeuMGGCh5woGcuhLei8V0faMctDtiipgMDAyV8QAF1DE/zAIo4wYRSjjCiTOw0GU6lEjO8AtXSJqYXrlFAo9RcAdBGGgQh0J43uKFe5ppUEPKxQDEGcYmkL6zXFzOPsccIE4kaY4EawQEykqJFkJBSOBNrLQPoWWBEuBfUwnbvlRFzCaFx/Kzl2Mk51wVZcwIbxBys2ftd0MlGR5IC8EUA1sX/vTfTHRVyNJNs871kNK8xNvIJkxAbzLCn9Jw1O9/jB6QxUH7yRtVbPj8eBpM2i3ZrvKztbXlSq2T3iiqvRPz13fMXnTyeqbXtOLOg4m1wFS7qVOemsB2vct3ryw@VrQJYPtys7u9uYVHqJN37mX3Wx4Xq/xi7cpwvP7AM0a6uL3@r4NtX@fkJ4DiOdzpN07Rc3q9uHu5u/7adKVs9TKt/ "Java (JDK) – Try It Online") Readable: ``` interface T{ static void main(String[]u){ // constants - carriages' parts, a[] - array of carriages String g=" ",n=g+g,m=n+g,s=m+m,h=s+s,q=h+m,o=" O-O",w=o+s+o+n,y="=",d= y+y+y,p="_____",b=d+d,e=b+b,f=n+n,t=e+d,c="|",l=g+c,z=l+l+l,v= "|-|-|",k=" []",x=k+k,r=k+l,a[]={h+"__"+n,b+s+"\\/"+n,c+r+b+d+ g,c+h+n+")",t+y,o+"-O"+n+o+"-O \\\\",q,q,t,c+x+x+l,t,w,q,q,t,v +g+l+n+v,t,w,q,q,g+p+"---"+p+g,"("+h+" )",t,w,q,q,p+p+p,"\\"+z +z+" /",t,w,q,q,q,q,t,w,h+g,f+d+y+y+f,d+y+c+m+c+d+y,c+k+f+r,e+ y,o+f+o+n,n,n,n,n,"--",g}; // output ASCII train var O=System.out; for(int i=-1,j;i++<5;O.println()) for(j=u[1].length();j-->0;O.print( a["EPBTHFC".indexOf(u[1].charAt(j))*6+i]+(j>0?a[42+i]:""))); } } ``` --- Train carriages. The lower line of each carriage is one character longer because of engine but the lower line of couplings is one character shorter. Double backslashes are *escaped characters*, they are interpreted as a single backslash: ``` String a[] = { // Engine (E) " __ ", "====== \\/ ", "| [] |========= ", "| )", "================", " O-O-O O-O-O \\\\", // Passenger car (P) " ", " ", "===============", "| [] [] [] [] |", "===============", " O-O O-O ", // Boxcar (B) " ", " ", "===============", "|-|-| | |-|-|", "===============", " O-O O-O ", // Tanker (T) " ", " ", " _____---_____ ", "( )", "===============", " O-O O-O ", // Hopper (H) " ", " ", "_______________", "\\ | | | | | | /", "===============", " O-O O-O ", // Flatbed (F) " ", " ", " ", " ", "===============", " O-O O-O ", // Caboose (C) " ", " ===== ", "====| |====", "| [] [] |", "=============", " O-O O-O ", // Car coupling " ", " ", " ", " ", "--", " "}; ``` Train `EPBTHFC`: ``` __ ===== ====== \/ ====| |==== _______________ _____---_____ =============== =============== | [] |========= | [] [] | \ | | | | | | / ( ) |-|-| | |-|-| | [] [] [] [] | | ) =============--===============--===============--===============--===============--===============--================ O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O O-O-O O-O-O \\ ``` [Answer] ### C#, ~~758~~ ~~664~~ ~~603~~ 562bytes Not a great score, 200 or so bytes in the poorly encoded string, and about 80 bytes devoted to decoding it. Frustrating amount of code spent sorting out the coupling on the engine! It now leaves white-space trailing at the front of the train, which is untidy but within the rules, and it also has the dimensions of the data-string hard coded, something I was reluctant to do initially. ``` using c=System.Console;class P{static void Main(){string d=c.ReadLine(),a="",z=@"99 1_5 4=78 5=5 \/1 3=|2 |3=14 29= 4_2-4_ 14_| [] |8= | []4 [] |14 | [] [] [] [] 1|-|-|1 |1 |-|-|(12 )\ | | | | | | /|13 )103= O-O4 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O-O2 O-O-O c";int j=0,e;foreach(var h in z)if(h>47&&h<58)j=j*10+h-48;else for(j++;j>0;j--)a+=h;int[]x={0,13,28,43,58,73,88,104};for(;j<6;j++){z="";foreach(var h in d)z=a.Substring(j*104+x[e="CFPBTHE".IndexOf(h)],x[e+1]-x[e])+(j==4?"--":" ")+z;c.WriteLine(z.Replace("c ",@"\\").Trim('-'));}}} ``` Formatted a bit: ``` using c=System.Console; class P{static void Main(){ string d=c.ReadLine(),a="",z=@"99 1_5 4=78 5=5 \/1 3=|2 |3=14 29= 4_2-4_ 14_| [] |8= | []4 [] |14 | [] [] [] [] 1|-|-|1 |1 |-|-|(12 )\ | | | | | | /|13 )103= O-O4 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O-O2 O-O-O c"; int j=0,e; foreach(var h in z) if(h>47&&h<58) j=j*10+h-48; else for(j++;j>0;j--) a+=h; int[]x={0,13,28,43,58,73,88,104}; for(;j<6;j++) { z=""; foreach(var h in d) z=a.Substring(j*104+x[e="CFPBTHE".IndexOf(h)],x[e+1]-x[e])+(j==4?"--":" ")+z; c.WriteLine(z.Replace("c ",@"\\").Trim('-')); } }} ``` The string is compressed very simply by replacing repeated character with a string representation of the number of characters followed by the character (minus 1), or just the character if there is only one of them (I wanted to stick with ASCII and avoid doing anything at the sub-char level). Encoder (not included in score): ``` string compress(string str) { str += (char)0; // too lazy to write a proper loop string res = ""; char prev = str[0]; int count = 1; for (int i = 1; i < str.Length; i++) { char cur = str[i]; if (cur != prev) { if (count != 1) res += (count - 1).ToString(); res += prev; prev = cur; count = 1; } else { count++; } } return res; } ``` [Answer] Here is my solution in PHP (v5.4 compatible), 512bytes. Could be shorter, but just made a quick build to try this out. ``` <?php $m=array_combine(str_split('EPBTHFC'),explode('$',gzinflate(base64_decode('jZDBDYAwCEXvfwoOHvRAnKAzOICYLtLhhVYlrY320RQI5BMgcmJEyJRUViTaD0rhRvOKBaEBtLGa1ooXmdA2FdXnJfQ0rgkW9RRYjcieRQMKupzCzNlj/t6jIxBrIDrdbR1QwH+PRaVkn107+cWM971cxPwJ'))));$t=['','','','','',''];$i=str_split(strrev(strtoupper($argv[1])));foreach($i as $w=>$n){$c=$m[$n];$c=explode("\n",$c);foreach($t as $j=>&$p){$p.=str_pad($c[$j],$n=='E'?18:($n=='C'?15:17),$j==4?'-':' ');if($w==count($i)-1)$p=rtrim($p,' -');}}echo implode("\n",$t)."\n"; ``` This is a spread-out version for easy reading: ``` <?php $m=array_combine( str_split('EPBTHFC'), explode('$', gzinflate( base64_decode( 'jZDBDYAwCEXvfwoOHvRAnKAzOICYLtLhhVYlrY320RQI5BMgcmJEyJRUViTaD0rhRvOKBaEBtLGa1ooXmdA2FdXnJfQ0rgkW9RRYjcieRQMKupzCzNlj/t6jIxBrIDrdbR1QwH+PRaVkn107+cWM971cxPwJ' ) ) ) ); $t=['','','','','','']; $i=str_split(strrev(strtoupper($argv[1]))); foreach($i as $w=>$n) { $c=$m[$n]; $c=explode("\n",$c); foreach($t as $j=>&$p) { $p.=str_pad($c[$j],$n=='E'?18:($n=='C'?15:17),$j==4?'-':' '); if($w==count($i)-1)$p=rtrim($p,' -'); } } echo implode("\n",$t)."\n"; ``` [Answer] ## Java (583 characters) With basic homemade compression - not sure it's so efficient though :-) The train string (e.g. `EEHTBPFC`) must be passed as parameter. ``` class C{public static void main(String[]a){String s="",y="thAthA",x=" *!*h*!* A",q="vjA",r=q+x+y;String[]m=("hP78A^\\#$8A% &' %j.,A%hh) Ajj.A *!*!*8*!*!* /A"+y+q+"% &' &' &' &' %A"+r+q+"%!%!%,%,%!%!%A"+r+" [9[ A(tP)A"+r+"ss+A# % % % % % % $A"+r+y+q+x+"tPADRDAF%8%FA% &'P&' %AvRA *!*P*!* ").split("A");for(int l,z,i,j=0;j<6;j++){for(i=a[0].length()-1;i>=0;i--){z=a[0].charAt(i);r=m["EPBTHFC".indexOf(z)*6+j];for(int c:r.toCharArray()){c-=32;for(l=0;l<=c/12;l++)s+=" -=\\/|[]()O_".charAt(c%12);}if(i>0)for(l=0;l<(z=='E'&&j!=4?1:2);l++)s+=j==4?"-":" ";}s+="\n";}System.out.println(s);}} ``` Unfolded: ``` class C{ public static void main(String[]a){ String s="",y="thAthA",x=" *!*h*!* A",q="vjA",r=q+x+y; String[]m=("hP78A^\\#$8A% &' %j.,A%hh) Ajj.A *!*!*8*!*!* /A"+y+q+"% &' &' &' &' %A"+r+q+"%!%!%,%,%!%!%A"+r+" [9[ A(tP)A"+r+"ss+A# % % % % % % $A"+r+y+q+x+"tPADRDAF%8%FA% &'P&' %AvRA *!*P*!* ").split("A"); for(int l,z,i,j=0;j<6;j++){ for(i=a[0].length()-1;i>=0;i--){ z=a[0].charAt(i); r=m["EPBTHFC".indexOf(z)*6+j]; for(int c:r.toCharArray()) { c-=32; for(l=0;l<=c/12;l++) s+=" -=\\/|[]()O_".charAt(c%12); } if(i>0)for(l=0;l<(z=='E'&&j!=4?1:2);l++)s+=j==4?"-":" "; } s+="\n"; } System.out.println(s); } } ``` [Answer] # Python, 491 bytes ``` import zlib as z,sys,base64 as d y=eval(z.decompress(d.b64decode('eNqlksEOwiAMhl/lv1WTkd1NdtFovLmDt7HwIOK729LJmJDY6F8SyA/0g6YPOtNhIhQKAaCOhiS1fJ+siGlGHN5Sa6N9vriKLdwcB+/r7D3NHY2fYCRI7dT50kPyiM0zUCKUCiEe/yA6DkCGrKzEu5XIVWc559Iszu5bYdvEq5UYtmLH8/fW6K3Ei/mPP1W+QTxVxCVXbtklk3RnLHtG1OqYkqOU5wsfZZmx'))) w=sys.argv[1][::-1] x=[""]*6 v=range u=len(w) for j in v(6): for i in v(u): if j==5 and w[i]=='E':k="\\ " elif j==4 and i!=u-1:k="--" else:k=" " x[j]+=y[w[i]][j]+k for q in x:print q ``` I like how it came out, even though it won't be a winner. [Answer] # [GNU sed](https://www.gnu.org/software/sed/), 491 bytes ``` s/./& #/g s:E:0S__s%1esss\\/s%2|bpef %3|Ss)%4E=@5 o-Os o-O \\\\:g s/P/zE%3|bbbbp%4E@5ut/g s/B/zE%3|-|-|s|s|-|-|%4E@5ut/g s/T/z l---l %3(S )%4E@5ut/g s:H:zlll%3\\pppppp /%4E@5ut:g s/F/zSs %3Ss %4E@5ut/g s/C/0S %1ssf==ss%2f=|spf=%3|bssbp%4ee=@5 ts t/g s/z/0Ss %1Ss %2/g s/%/s%/g s/@/--%/g s/u/ tss /g s/t/os/g s/S/ssssss/g s/s/ /g s/E/eef/g s/e/ff/g s/f/===/g s/b/ []/g s/p/ |/g s/o/O-O/g s/l/_____/g s/^/0123456;/ : s/([0-6])(.*;)\1([^%#]+)[%#](.*)/\1\3!\2\4/ t s/(--!)?[1-6]/\n/g s/[0!;]//g ``` [Try it online!](https://tio.run/##TY9Ni8JADIbv/ooRmaXdZUw/1ENlWFEq3hTqrVMF2aksFFs29VL627ebSffgO5A@k7xJM2i/hgFhDm9iBvcJJmkSZNcrytAiojGAMupvjS2FjPsMfblI9WYpanVEF4QhJdQHJ@hSstxIDZk2y2fr5sF2zCs6SMd9X8tn6ESllKpovpcJ/6WWHJKuqioZG9OwBPxX@Yd76DKkLhdeBu4gyIQMEUutkZYvdY9Nqd1qiG41a90DWhSjvyM/TQhdiDgj6c0MG1BqpCdQAwrmFmpkyABZfEEQYzkFa0smC@UIJWitmW4g8oKpAdEz1HBUR6YKrk7MFwjCKF4sV2uYJHT38kCtCt@bv699E3r5Rc6KDz@nSCkfTGjiqYnMAiatcys19T/zkFrAPHhgHkzXBcB9GNL0cN6e9rvfumm/6wcO6ucP "sed 4.2.2 – Try It Online") ## Explanation This is basically a super naïve custom compression scheme. The first line appends to each letter in the input a space and `#`, to mark the end of each part: ``` s/./& #/g ``` The next 7 lines replace each letter with a compressed representation of the corresponding ASCII image: ``` s:E:0S__s%1esss\\/s%2|bpef %3|Ss)%4E=@5 o-Os o-O \\\\:g s/P/zE%3|bbbbp%4E@5ut/g s/B/zE%3|-|-|s|s|-|-|%4E@5ut/g s/T/z l---l %3(S )%4E@5ut/g s:H:zlll%3\\pppppp /%4E@5ut:g s/F/zSs %3Ss %4E@5ut/g s/C/0S %1ssf==ss%2f=|spf=%3|bssbp%4ee=@5 ts t/g ``` The next 14 lines do the "decompression". For example, an `S` decompresses to six `s`es, and an `s` decompresses to two spaces, so `S` becomes 12 spaces. ``` s/z/0Ss %1Ss %2/g s/%/s%/g s/@/--%/g s/u/ tss /g s/t/os/g s/S/ssssss/g s/s/ /g s/E/eef/g s/e/ff/g s/f/===/g s/b/ []/g s/p/ |/g s/o/O-O/g s/l/_____/g ``` Decompressed, the lines of each car are preceded by a line number, and each car is terminated by `#`. The rest of the code prepends `0123456;` (the line numbers and delimiter) to the pattern space and then, in a loop, replaces each digit with the corresponding line of each car. ``` s/^/0123456;/ : s/([0-6])(.*;)\1([^%#]+)[%#](.*)/\1\3!\2\4/ t ``` Finally, it cuts the pattern space into lines by splitting on digits and cleans up extraneous characters: ``` s/(--!)?[1-6]/\n/g s/[0!;]//g ``` There's a lot of room for improvement here. I wasn't rigorous at all about finding an optimal set of compressions, and using a lookup table instead of 14 separate `s///g`s would be an easy win. I may or may not noodle with this some more. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~501~~ ~~499~~ ~~490~~ ~~489~~ ~~484~~ ~~483~~ 481 bytes -2 -9 -1 -5 -1 -2 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` #define A": O-Og O-O:o=:" char*p,*q,s[80];i=6,k,n;main(j,a)char**a;{for(;i--;puts(q))for(k=strlen(a[1]);k--;*q=0,printf("%-*s%s",j?j^6?15:13:16,s,k?i^1?!j*!i+" ":"--":q)){j=index(p="EPBTHFC",a[1][k])-p;for(n=j*6+i,p=" O-O-Oc O-O-O \\\\:p=:|n ):| [] |i=:f=f \\/:l __"A"| [] [] [] [] |:o=::"A"|-|-| | |-|-|:o=::"A"(m ): e_c-e_::"A"\\ | | | | | | /:o_::"A":::: O-Oe O-O:m=:| []e [] |:d=|c |d=:d e=::";n--;)for(;*p++-58;);for(q=s;*p^58;q+=n)memset(q,*p++,n=islower(*p)?*p++-96:1);}} ``` [Try it online!](https://tio.run/##RVDbSsQwEH33K2JESNIELWLRCaGssuLb@uDb3ihtuqbdZttmRcH67TXpos4MuZyZnMmcXOzyfBwvCl0aq9EMA1qIxS4scFCAz/K3rGctZx13y7vrtTQq4TW3ssmMJRXP6FTAMvlVHnoijRCyfT860lEagFq5Y7/XlmTLeE1l7dOsU9e87Y09lgRfCuYuHeZVWm2SNL6F@AbihDtep2YTp@cVOzcRRggDFgKDZ/2qlLGF/iStwvOXh9fnp0fMA/uyXlPRytDVqoolkeG@JEwiFvlpQytv0CoYLKIwoOUaDUZBqUqfuYI92m7xDE/4XwxBBwiw8I5QiHD6hUnjqZDe5kJvJ2C18jX/fgWHEw7ewjf0JG6jpv761KJQQ46GQkGBdKCV1gs1CShZG0Xi9k7SabJOOY9s/L2LlKWNbpw@ko6HKm6VcfvDh@4Ja2k6PbxPIKby@3scx/n8@fXh5enxBw "C (gcc) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 529 bytes ``` a=['']*6 T,R="EPBTHFC",{'S':' '*3,'E':'='*3,'W':'[] ','U':'_'*5,'P':'| ','H':'O-O'} A=('SSSS__ ',)+('S'*5,)*5+('SSSS ',),('EESS\/ ',)+('S'*5,)*5+('S E==S ',),('PW|EEE ','E'*5,'E'*5,' U---U ','U'*3,'S'*5,'E=|S|E='),('P SSSS)','PWWWW|','|-|-P P |-|-|','(SSSS )','\ PPPPPP/','S'*5,'PWS W|'),('E'*5+'=--',)+('E'*5+'--',)*5+('EEEE=--',),(' H-OSH-O \\\\ ',)+(' HSS HS',)*5+(' HS HS',) for C in input(): for I in range(6): a[I]=A[I][T.index(C)]+' '*(I<4)+a[I] for k in R:a[I]=a[I].replace(k,R[k]) a[4]=a[4][:-2] [*map(print,a)] ``` [Try it online!](https://tio.run/##bVJNb4JAEL3zKyZeZoFdTerHgXQP1myDJ4mr8YDEkJa2xhYJsUmb0t9OZ3b11gkMb968YR4bmu/L27ke932pc8QimgUbudYDkz1s0sfFQP6gxQQBo7FEQ0g7tCOUF4ASt4QOGE0lZoQ6plICK7XC32CuBVqKwwGoEcZUsTSMprFvMCsFGmPtfvSfBozWN1W264wxvMG4hT7DVim19VbYmvU93dnOaHRzwKtCUmQ7io5ApzqVQQb85Fo4MyzZQ@ZihLdXZTsLNOR8EhGjVsob9aWrnFtyZ3yTtJCqlaUb9hTXL4OUtqT2picIvgxezi0s4FjT1XxeRJgEwNSSqbasXysxYw7KfFnoOaV8MzzWz9WXWIRFjHR0kVjeT8KYBaTj4RMPrxM3wmnYVs17@VSJk1znpyIMynzCnUmRJ@quCPLoo2xE0x7riyzDou@vP8Ef "Python 3 – Try It Online") Figured I would post it because it does not use any compression, unlike most of the other answers here. [Answer] # Javascript (Node.js), 1216 bytes ``` var c={E:[' __ ','====== \\/ ','| [] |========= ','| )','================',' O-O-O O-O-O \\',],P:[' ',' ','===============','| [] [] [] [] |','===============',' O-O O-O'],B:[' ',' ','===============','|-|-| | |-|-|','===============',' O-O O-O'],T:[' ',' ',' _____---_____ ','( )','===============',' O-O O-O '],H:[' ',' ','_______________','\\ | | | | | | /','===============',' O-O O-O '],F:[' ',' ',' ',' ','===============',' O-O O-O '],C:[' ',' ===== ','====| |====','| [] [] |','=============',' O-O O-O ']};var o=[];for(var w=0;w<process.argv[2].length;w++){o.push(process.argv[2].charAt(w));}var arg=o.reverse().join('');var s=[' ',' ',' ',' ','--',' '];for(var x=0;x<6;x++){var k=[];for(var y=0;y<arg.length;y++){if(!['B','C','E','F','H','P','T'].includes(arg.charAt(y))){y++;}k.push(c[arg.charAt(y)][x]);}var v='';for(var q in k){v+=k[q]; if(arg.charAt(q)=='E'&&x== 5){v+='\\ ';}else if(q<k.length-1){v+=s[x];}}console.log(v);} ``` Uncompressed ``` var c = { // define cars E: [ ' __ ', '====== \\/ ', '| [] |========= ', '| )', '================', ' O-O-O O-O-O \\', ], P: [ ' ', ' ', '===============', '| [] [] [] [] |', '===============', ' O-O O-O' ], B: [ ' ', ' ', '===============', '|-|-| | |-|-|', '===============', ' O-O O-O' ], T: [ ' ', ' ', ' _____---_____ ', '( )', '===============', ' O-O O-O ' ], H: [ ' ', ' ', '_______________', '\\ | | | | | | /', '===============', ' O-O O-O ' ], F: [ ' ', ' ', ' ', ' ', '===============', ' O-O O-O ' ], C: [ ' ', ' ===== ', '====| |====', '| [] [] |', '=============', ' O-O O-O ' ] }; //reverse string - why is there no builtin for this? var o = []; for(var w = 0; w < process.argv[2].length; w++){ o.push(process.argv[2].charAt(w)); } var arg = o.reverse().join(''); //train car seperators var s = [' ',' ',' ',' ','--',' ']; // for each row for(var x = 0; x < 6; x++){ var k = []; //empty array for each car string for(var y = 0; y < arg.length; y++){ //ignore non-included characters if(!['B','C','E','F','H','P','T'].includes(arg.charAt(y))){ y++; } // add car k.push(c[arg.charAt(y)][x]); } var v = ''; for(var q in k){ v += k[q]; // append car if(arg.charAt(q) == 'E' && x == 5){ // to deal with annoying engine thing, see below v += '\\ '; } else if(q < k.length - 1){ // if not last car v += s[x]; // append separator } } console.log(v); //output } ``` The annoying thing about this challenge is the coupling near the engine. All the other cars are just one solid block, but the \ on the front takes up the same vertical space as the coupling. See here: ``` __ ====== \/ | [] |========= | ) ================-- O-O-O O-O-O \\ ``` Note: Enter via the CLI e.g. node asciitrain.js EBCEFH. This was badly golfed. ]
[Question] [ ## *Why was 6 afraid of 7? Because 7 8 9!* Given a string apply the following transformations: * If there is a 6 next to a 7 remove the 6 (6 is afraid of 7) * If the sequence "789" appears remove the 8 and the 9 (7 ate 9) (If I'm not mistaken it doesn't matter what order you do the transformations in) Keep applying these transformations until you can no longer. Example: `78966` First we see "789", so the string becomes "766". Then we see "76", so we take out the 6, and the string becomes "76". Then we see "76" again, so we are left with "7". Test Cases: * `987` => `987` (Not in the right order. Does nothing.) * `6 7` => `6 7` (The whitespace acts as a buffer between 6 and 7. Nothing happens) * `676` => `7` * `7896789` => `77` * `7689` => `7` * `abcd` => `abcd` [Answer] # [Retina](https://github.com/mbuettner/retina), 12 Translation of the sed answer: ``` 6*7(6|89)* 7 ``` [Try it online](http://retina.tryitonline.net/#code=Nio3KDZ8ODkpKgo3&input=OTg3CjYgNwo2NzYKNzg5Njc4OQo3Njg5CmFiY2QKNjg5Nzg5NjY4OTc4OTYKNjc3ODk) [Answer] # Javascript ES6, 29 bytes ``` s=>s.replace(/6*7(89|6)*/g,7) ``` Test: ``` f=s=>s.replace(/6*7(89|6)*/g,7) ;`987 -> 987 6 7 -> 6 7 676 -> 7 7896789 -> 77 7689 -> 7 abcd -> abcd` .split`\n`.every(t=>(t=t.split` -> `)&&f(t[0])==t[1]) ``` [Answer] # Java, ~~126~~ ~~81~~ ~~66~~ 58 bytes Thanks to @GamrCorps for providing the lambda version of this code! Thanks to @user902383 for pointing out an autoboxing trick! ...yup. It's actually longer than I expected - Java replaces items in strings with `replaceAll()` once per match, not repeatedly until it stops changing. So I had to use a fancy for loop. ### Lambda form: ``` x->{for(;x!=(x=x.replaceAll("67|76|789","7")););return x;} ``` ### Function form: ``` String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;} ``` ### Testable Ungolfed Code: ``` class B{ public static void main(String[]a){ System.out.print(new B().s(a[0])); } String s(String x){for(;x!=(x=x.replaceAll("67|76|789","7")););return x;} } ``` [Answer] # GNU Sed, 17 Score includes +1 for `-r` option. ``` s/6*7(6|89)*/7/g ``` [Answer] # [Perl 6](http://perl6.org), ~~19~~  18 bytes ``` {S:g/6*7[6|89]*/7/} # 19 bytes ``` ``` $ perl6 -pe 's:g/6*7[6|89]*/7/' # 17 + 1 = 18 bytes ``` ( Note that `[6|89]` is the non-capturing version of `(6|89)` which is spelt as `(?:6|89)` in Perl 5. `<[6|89]>` is how you would write what's spelt as `[6|89]` in Perl 5) usage: ``` $ perl6 -pe 's:g/6*7[6|89]*/7/' <<< ' 987 6 7 6676689 7896789 7689 abcd 68978966897896 79|689 ' ``` ``` 987 6 7 7 77 7 abcd 68977 79|689 ``` [Answer] # Pyth, 17 bytes ``` u:G"67|76|789"\7z ``` [Try it here.](http://pyth.herokuapp.com/?code=u%3AG%2267%7C76%7C789%22%5C7z&test_suite=1&test_suite_input=987%0A6+7%0A676%0A7896789%0A7689%0Aabcd) Leaky Nun has outgolfed this by a byte in the comments. [Answer] # [Perl 5](http://perl.org), 17 bytes ``` perl -pe 's/6*7(6|89)*/7/g' # 16 + 1 ``` usage: ``` $ perl -pe 's/6*7(6|89)*/7/g' <<< ' 987 6 7 6676689 7896789 7689 abcd 68978966897896 ' ``` ``` 987 6 7 7 77 7 abcd 68977 ``` [Answer] ## Mathematica, 52 bytes ``` StringReplace[#,"67"|"76"|"789"->"7"]&~FixedPoint~#& ``` Explanation: ``` & A function returning & a function returning # its first argument StringReplace[ , ] with "67" "67" | or "76" "76" | or "789" "789" -> replaced with "7" "7" ~FixedPoint~ applied to # its first argument until it no longer changes. ``` [Answer] ## Rust, 96 bytes ``` fn f(mut s:String)->String{for _ in 0..s.len(){for r in&["67","76","789"]{s=s.replace(r,"7")}}s} ``` Hopelessly long, as per usual for Rust... Ungolfed: ``` fn seven_ate_nine(mut str: String) -> String { for _ in 0..str.len() { for to_replace in &["67","76","789"] { str = str.replace(to_replace, "7"); } } s } ``` [Answer] # Emacs Lisp, 59 bytes ``` (lambda(s)(replace-regexp-in-string"6*7\\(6\\|89\\)*""7"s)) ``` It becomes a bit clearer with spaces: ``` (lambda (s) (replace-regexp-in-string "6*7\\(6\\|89\\)*" "7" s)) ``` [Answer] # Ruby, 27 bytes This solution is from comments, credit to *Brad Gilbert b2gills*. ``` ->s{s.gsub /6*7(6|89)*/,?7} ``` --- ## Ruby, 37 bytes ***(old solution)*** This solution uses the fact that you will never need to replace more times than characters in the string. ``` ->s{s.chars{s.sub! /67|76|789/,?7};s} ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 17 bytes ``` jt"'789|76'55cYX] ``` ### Example ``` >> matl > jt"'789|76'55cYX] > > 7896789 77 ``` **EDIT**: [**Try it online!**](http://matl.tryitonline.net/#code=anQiJzc4OXw3Nic1NWNZWF0&input=Nzg5Njc4OQ) ### Explanation ``` j % input string t % duplicate " % for each character. Iterates as many times as the string length '789|76' % regular expression for replacement 55c % string to insert instead: character '7' YX % regexprep ] % end for ``` This works by applying a regular expresion replacement for *as many times as there are characters in the original string*. This is enough, since each substitution reduces the number of characters. [Answer] # [Japt](https://github.com/ETHproductions/Japt), 15 bytes ``` Ur"6*7(89|6)*"7 ``` Simple RegEx solution [Try it online](http://ethproductions.github.io/japt?v=master&code=VXIiNio3KDg5fDYpKiI3&input=Ijc4OTY3ODki) [Answer] # PowerShell, 27 bytes ``` $args-replace'6*7(89|6)*',7 e.g. PS C:\temp> .\ate.ps1 "7689" 7 PS C:\temp> .\ate.ps1 "abcd" abcd PS C:\temp> .\ate.ps1 "68978966897896" 68977 ``` Making use of: * someone else's regex pattern * the way `-replace` does a global replace by default in PowerShell * loop unrolling, where it will apply the `-regex` operator to the array `$args` by applying it to all the elements individually, and there's only one element here because there's only one script parameter, so it works OK and we can avoid having to index element `[0]`. --- Novelty previous attempt before realising a global replace would do it; 74 bytes of building a chain of "-replace -replace -replace" using string multiplication, as many times as the length of the string, then eval()ing it: ``` "'$($args)'"+("{0}6|6(?=7)'{0}89'"-f"-replace'(?<=7)")*$args[0].Length|iex ``` (With a bit of string substitution to shorten the number of replaces). [Answer] ## Seriously, 29 bytes ``` ,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n ``` Takes input as a double-quoted string, like `"6789"`. [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b6c6027373b3b22363722289222373622289222373839222892606e&input=6789) (you will need to manually quote the input). Explanation: ``` ,;l`'7;;"67"(Æ"76"(Æ"789"(Æ`n ,;l get input and push its length (we'll call it n) ` `n call the following function n times: '7;;"67"(Æ replace all occurrences of "67" with "7" "76"(Æ replace all occurrences of "76" with "7" "789"(Æ replace all occurrences of "789" with "7" ``` [Answer] ## PHP, 36 bytes ``` preg_replace('/6*7(6|89)*/','7',$a); ``` regex solution, takes $a string and replaces via the expression. [Answer] # [Thue](https://en.wikipedia.org/wiki/Thue_%28programming_language%29), 26 bytes ``` 67::=7 76::=7 789::=7 ::= ``` including a trailing newline. Input is appended to the program before starting it. Output is read off the program state when it terminates, similarly to a Turing machine. (Thue *does* have an output stream, but it's difficult to use correctly, so I'm not sure whether this is an acceptable output method) [Answer] ## CJam, ~~70~~ 64 bytes Thanks to @Peter Taylor for cutting `{"789":I}{"76:":I}?` to `"789""76"?:I` `~~"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I={"789":I}{"76":I}?];}?}/A~~` `"67":Iq:A{AI#:B){AB<7+A{BI,+}~>+s:A];}{"76"I="789""76"?:I];}?}/A` I know this could probably be golfed a lot further and your help would be greatly appreciated, but frankly I'm just happy I managed to get the answer. This was my first attempt at writing CJam. Explanation: ``` "67":I e# Assign the value of 67 to I q:A e# Read the input and assign to A { e# Opening brackets for loop AI#:B) e# Get the index of I inside A and assign to B. The increment value by 1 to use for if condition (do not want to process if the index was -1) { e# Open brackets for true result of if statement AB< e# Slice A to get everything before index B 7+ e# Append 7 to slice A{BI,+}~> e# Slice A to get everything after index B plus the length of string I (this will remove I entirely) +s:A e# Append both slices, convert to string, and assign back to A ]; e# Clear the stack } e# Closing brackets for the if condition { e# Open brackets for false result of if statement "76"I= e# Check if I is equal to 76 "789" e# If I is 76, make I 789 "76"?:I e# If I is not 76, make I 76 ]; e# Clear the stack if I does not exist inside A }? e# Closing brackets for false result of if statement }/ e# Loop A e# Output A ``` [Answer] ## R, 35 bytes ``` cat(gsub("6*7(6|89)*",7,scan(,""))) ``` I didn't know I could use `gsub` this way, a big thank you for every answer here that made me learn something new. [Answer] ## Python 3, 46 bytes ``` import re lambda s:re.sub(r'6*7(6|89)*','7',s) ``` [Answer] # [Dyalog APL](https://dyalog.com), 17 bytes ``` '6*7(6|89)*'⎕R'7' ``` `'6*` any number of sixes `7` followed by a seven `(`…`)*'` followed by zero or more sequences of…  `6|89` a six or eight-nine `⎕R` **R**eplace that with `'7'` a seven [Answer] # [///](https://esolangs.org/wiki///), 19 bytes ``` /67/7//76/7//789/7/ ``` You can't actually provide input in this language, so the supposed input goes to the right of the code, which is allowed by recent rules. [Answer] ## **PHP 51 characters** ``` while($s!=$r=str_replace([789,67,76],7,$s)){$s=$r;} ``` **Test case written in long hand** ``` $s = '78966'; while ($s != $r = str_replace([789, 67, 76], 7, $s) ) { $s = $r; } echo $s; // 7; ``` This does the string comparison and the string replace both in the while condition. If while condition is met, it updates the left hand of the comparison with the result. Let me know of any improvements. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 15 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=cGkiNio3KDZ8ODkpKiI3) Do I really have to explain? ``` pi"6*7(6|89)*"7 p replace any entity in i the input "6*7(6|89)*" that matches this regex 7 with 7 implicit output ``` [Answer] ## Clojure, 71 bytes Clojure is less-than-ideal for golfing due to its verbose nature - but nonetheless it's an interesting exercise: Golfed version, using Java interop: ``` (defn f[s](let[x(.replaceAll s "67|76|789" "7")](if(= s x)s(recur x)))) ``` Un-golfed version, using Java interop: ``` (defn six-fears-seven [s] (let [x (.replaceAll s "67|76|789" "7")] (if (= s x) s (recur x)))) ``` Un-golfed "pure Clojure" version: ``` (defn six-fears-seven [s] (let [x (clojure.string/replace s #"67|76|789" "7")] (if (= s x) s (recur x)))) ``` [Answer] # Bash, 102 82 67 (+7)? bytes ### extglob version ``` x=$1 while v=${x/@(76|67|789)/7};[ $v != $x ];do x=$v;done echo $v ``` This is meant to be put in a file and called with e.g. `bash -O extglob 789.sh 6567678989689789656`. The (+7)? bytes is for if the extglob option counts toward bytes. Thanks to @BinaryZebra for pointing out extglob features! --- ### Non-extglob version (82 bytes) ``` x=$1 while v=${x/76/7};v=${v/67/7};v=${v/789/7};[ $v != $x ];do x=$v;done echo $v ``` This is meant to be put in a file and called with e.g. `./789.sh 65678989656`. It makes use of parameter expansion to search and replace in a loop. I involved a series of expansions to do the replacing since I'm not aware of a way to more effectively chain expansions. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 12 bytes ``` e/6?7(6|89/7 ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS82PzcoNnw4OS83&input=LW1SIFsKIjc4OTY2IiwKIjk4NyIsCiI2IDciLAoiNjc2IiwKIjc4OTY3ODkiLAoiNzY4OSIsCiJhYmNkIiwKIjY4OTc4OTY2ODk3ODk2Igpd) ### How it works `String.e` is recursive replace function. Japt 2 has a new regex syntax and auto-completion of parentheses inside regex, which saves one byte here. (In Japt 1.x, we had to pass strings in place of regexes, which was kinda clunky.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ67‚789ª7: ``` [Try it online](https://tio.run/##yy9OTMpM/f//3BQz88NNjxpmmVtYHlplbvX/P5BhBkYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVulir6TwqG2SgpL9/3NTzMwPNz1qmGVuYXlolbnV/1qd/5YW5lxmCkBsbsYFFDYDYi5zMyCRmJScwmUI5BqbmxlBpMyBisyA2BzMBSMuIAZxoBQA). **Explanation:** ``` Δ # Continue doing the following until it no longer changes: 67 # Push 67 to the stack  # Bifurcate (short for Duplicate & Reverse copy): 76 ‚ # Pair them together: [67,76] 789ª # Append 789 to this list: [67,76,789] 7: # Replace all occurrences of these three integers with 7 # i.e. 1789372 → 17372 # (after the loop, output the result after implicitly) ``` `67‚789ª` could alternatively be `•4BĆx•₄в` for the same byte-count. [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 27 bytes ``` {x{"7"/y@x}/(\'$67 76 789)} ``` [Try it online!](https://ngn.codeberg.page/k#eJxFkVFrwyAQx9/9FIcUlsISBwNtEzb2sOc+7a0r1CYaQzvN1JKE0n32qU03UP78f96d3inLy3jBDJPpbbyS7PNhQRkwCmy1Xl4R8uVlsZ1+bCkBYKz25lhle8m7UzVWU2WXuyvy23AEeL1iuJp1d4ehToJR/yGjEcIjvkEc7qJhJ4jZXyRmdIb3yAj5oW4CvOkOIYKU970rCalNI1pzkoXzvD6KsVZct6KozRf5PgvnO6MdoZQ+PZNBTfnAXU5zLi3vmtzInCGE4vtCA/DymiTbGA+dBq8E2K5VHoxthC3g3QgH2njV6bZYprTQYkyLkn2E+EF1Xrie1wJ47R3wsOBwllJYOAg/CKFDMNcNsAI2t1KgeN8L7eaK4RtCRZbMPKMEZkJnm1wcR3RREfoFlgR8jQ==) * `$67 76 789` shorthand for `("67";"76";"789")` * `(\'...)` create list of splitter functions, i.e. `("67"\;"76"\";"789"\)` * `x{...}/(...)` set up a reduce, seeded with `x` (the input), run over the list of splitter functions + `{"7"/y@x}` split the input (`x`) using the current splitter function (`y`), then join the result with `"7"`. feed this to the next iteration of the reduce ]
[Question] [ ## The scenario Lately you have been noticing some strange behavior with your favorite text editor. At first it seemed that it was ignoring random characters in your code when writing to disk. After a while you noticed a pattern; characters with odd ASCII values were being ignored. Under further inspection you discovered that you can only write to files properly if every eighth bit is zero. Now you need to know if your valuable files have been affected by this strange bug. ## The task You must write a complete program that determines if a file contains any odd bytes (demonstrating it is uncorrupted). But because of your text editor **you cannot write any odd bytes in your source code.** You may assume any pre-existing encoding for input, however you must still check every individual byte, not just characters. ### Input Your program will take the contents of or the path to a file from either stdin or command line. ### Output Your program will output to stdout either a truthy value if the given file contains an odd byte or a falsy if every eighth bit is zero. ## Criteria This is code golf, shortest program that completes the task wins. To be a valid submission every eighth bit in the files source code must be a zero. I would recommend including a copy of your source code's binaries in your submission. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. ## Test Cases (In ASCII encoding) Input: ``` "$&(*,.02468:<>@BDFHJLNPRTVXZ\^`bdfhjlnprtvxz|~ Output: falsy Input: !#%')+-/13579;=?ACEGIKMOQSUWY[]_acegikmoqsuwy{} Output: truthy Input: LOREMIPSVMDOLORSITAMETCONSECTETVRADIPISCINGELITSEDDOEIVSMODTEMPORINCIDIDVNTVTLABOREETDOLOREMAGNAALIQVA VTENIMADMINIMVENIAMQVISNOSTRVDEXERCITATIONVLLAMCOLABORISNISIVTALIQVIPEXEACOMMODOCONSEQVAT DVISAVTEIRVREDOLORINREPREHENDERITINVOLVPTATEVELITESSECILLVMDOLOREEVFVGIATNVLLAPARIATVR EXCEPTEVRSINTOCCAECATCVPIDATATNONPROIDENTSVNTINCVLPAQVIOFFICIADESERVNTMOLLITANIMIDESTLABORVM Output: truthy ``` ## Tips * Choose language wisely this challenge might not be possible in every language * The Unix command `xxd -b <file name>` will print the binaries of a file to the console (along with some extra formatting stuff) * You may use other encodings other than ASCII such as UTF-8 as long as all other rules are followed [Answer] # [GS2](http://github.com/nooodl/gs2), 4 [bytes](https://en.wikipedia.org/wiki/Code_page_437) ``` dΦ(" ``` [Try it online!](http://gs2.tryitonline.net/#code=ZM6mKCI&input=ICIkJigqLC4wMjQ2ODo8PkBCREZISkxOUFJUVlhaXF5gYmRmaGpsbnBydHZ4enx-) ### Hexdump ``` 0000000: 64 e8 28 22 d.(" ``` ### How it works ``` (implicit) Read all input and push it on the stack. Φ Map the previous token over all characters in the string: d Even; push 1 for even characters, 0 for odd ones. ( Take the minimum of the resulting list of Booleans. " Negate the minimum. ``` [Answer] ## Befunge, 36 bytes I know this is an old question, but I wanted to give it a try because I thought it would be an interesting challenge in Befunge. ``` >~:0`| >20`:>$.@ |` " "< *8*82<^p24* ``` [Try it online!](http://befunge.tryitonline.net/#code=Pn46MGB8Cj4yMGA6PiQuQAp8YCAiICI8Cio4KjgyPF5wMjQq&input=IiQmKCosLjAyNDY4Ojw-QEJERkhKTE5QUlRWWFpcXmBiZGZoamxucHJ0dnh6fH4) It outputs `1` if the input is corrupted (i.e. contains an odd byte), and `0` if it's OK. **Explanation** The problem is how to determine odd bytes without having access to the `/` (divide) or `%` (modulo) commands. The solution was to multiply the value by 128 (the sequence `28*8**`), then write that result into the playfield. On a strictly standard interpreter, playfield cells are signed 8 bit values, so an odd number multiplied by 128 becomes truncated to -1 while an even number becomes 0. The other trick was in reading the -1 or 0 back from the playfield without having access to the `g` (get) command. The workaround for this was to write the value into the middle of an existing string sequence (`" "`), then execute that sequence to push the enclosed value onto the stack. At that point, determining the oddness of the byte is a simple less-than-zero test. One final aspect worth discussing is the output. In the false case, we reach the `>$.` sequence with just one value on the stack, so `$` clears the stack making the `.` output a zero. In the true case, we follow the path `20`:>$.`. Since two is greater than zero, the comparison pushes a one onto the stack, and the `:` makes a duplicate copy so the `$` won't drop it before it gets output. [Answer] ## CJam (11 bytes) ``` "r2":(~f&2b ``` [Online demo](http://cjam.aditsu.net/#code=%22r2%22%3A(~f%262b&input=%22r2%22%3A(~f%262b) Stripping away the tricks to avoid odd bytes, this reduces to ``` q1f&2b ``` which reads the input, maps a bitwise AND with `1`, and then performs a base conversion, giving zero iff all of the ANDs were zero. [Answer] # Printable .COM file, 100 bytes ``` ^FZjfDXVL\,LPXD$$4"PXD,lHPXDjJXDRDX@PXDjtXDH,nPXDj@XD4`@PXD,ZHPXD4,@PXD4:4"PXDH,\PXD4"PXD,hPXDRDX@P\ ``` Hexdump: ``` 00000000 5e 46 5a 6a 66 44 58 56 4c 5c 2c 4c 50 58 44 24 |^FZjfDXVL\,LPXD$| 00000010 24 34 22 50 58 44 2c 6c 48 50 58 44 6a 4a 58 44 |$4"PXD,lHPXDjJXD| 00000020 52 44 58 40 50 58 44 6a 74 58 44 48 2c 6e 50 58 |RDX@PXDjtXDH,nPX| 00000030 44 6a 40 58 44 34 60 40 50 58 44 2c 5a 48 50 58 |Dj@XD4`@PXD,ZHPX| 00000040 44 34 2c 40 50 58 44 34 3a 34 22 50 58 44 48 2c |D4,@PXD4:4"PXDH,| 00000050 5c 50 58 44 34 22 50 58 44 2c 68 50 58 44 52 44 |\PXD4"PXD,hPXDRD| 00000060 58 40 50 5c |X@P\| 00000064 ``` Using a *very loose* definition of source as something that can be reasonably typed by a human, and inspired by [EICAR Standard Antivirus Test File](http://www.eicar.org/86-0-Intended-use.html) (more info at [*"Let's have fun with EICAR test file"*](http://archive.cert.uni-stuttgart.de/bugtraq/2003/06/msg00251.html) at Bugtraq). Using only printable non-odd ASCII bytes (side note: opcodes affecting words tend to be odd, the W bit is the lsb of some opcodes), it constructs a fragment of code at SP (which we conveniently set just past our generating code), and execution ends up falling through to the generated code. It uses the fact that the stack initially contains a near pointer to the start of the PSP, and that the start of the PSP contains the `INT 20h` instruction (more info on this at [https://stackoverflow.com/questions/12591673/](https://stackoverflow.com/questions/12591673/whats-the-difference-between-using-int-0x20-and-int-0x21-ah-0x4c-to-exit-a-16)). Real source: ``` ; we want to generate the following fragment of code ; 5E pop si ; zero SI (pop near pointer to start of PSP) ; 46 inc si ; set SI to 1 ; loop: ; B406 mov ah,0x6 ; \ ; 99 cwd ; > ; 4A dec dx ; > D-2106--DLFF ; CD21 int 0x21 ; > DIRECT CONSOLE INPUT ; 7405 jz end ; > jump if no more input ; 40 inc ax ; > lsb 0/1 odd/even ; 21C6 and si,ax ; > zero SI on first odd byte ; EBF3 jmp short loop ; / ; end: ; 96 xchg ax,si ; return code ; B44C mov ah,0x4c ; D-214C ; CD21 int 0x21 ; TERMINATE WITH RETURN CODE pop si ; this two opcodes don't need to be encoded inc si pop dx ; DX = 20CD (int 0x20 at start of PSP) push byte +0x66 inc sp pop ax push si dec sp pop sp ; SP = 0x0166 sub al,0x4c ; B4 push ax pop ax inc sp and al,0x24 xor al,0x22 ; 06 push ax pop ax inc sp sub al,0x6c dec ax ; 99 push ax pop ax inc sp push byte +0x4a ; 4A pop ax inc sp push dx ; [20]CD inc sp pop ax inc ax ; 21 push ax pop ax inc sp push byte +0x74 ; 74 pop ax inc sp dec ax sub al,0x6e ; 05 push ax pop ax inc sp push byte +0x40 ; 40 pop ax inc sp xor al,0x60 inc ax ; 21 push ax pop ax inc sp sub al,0x5a dec ax ; C6 push ax pop ax inc sp xor al,0x2c inc ax ; EB push ax pop ax inc sp xor al,0x3a xor al,0x22 ; F3 push ax pop ax inc sp dec ax sub al,0x5c ; 96 push ax pop ax inc sp xor al,0x22 ; B4 push ax pop ax inc sp sub al,0x68 ; 4C push ax pop ax inc sp push dx ; [20]CD inc sp pop ax inc ax push ax ; 21 pop sp ; now get the stack out of the way ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` l$Z$2\z ``` The source code uses UTF-8 encoding. So the source bytes are (in decimal) ``` 108 36 90 36 50 92 122 ``` The input is a file name, taken as a string enclosed in single quotes. The output is the number of odd bytes in the file, which is truthy iff nonzero. ### Explanation ``` l % Push a 1. We use `l` instead of `1` to have an even value $ % Input specificication. This indicates that the next function takes 1 input Z$ % Input file name implicitly, read its raw bytes and push them as an array of chars 2\ % Modulo 2 z % Number of nonzero values. This gives the number of odd bytes. Implicitly display ``` [Answer] # CJam, ~~18~~ ~~17~~ 15 bytes ``` "<rj":(((*~:|X& ``` Assumes that the locale is set to Latin-1. [Try it online!](http://cjam.tryitonline.net/#code=IjxyaiI6KCgoKn46fFgm&input=IjxyaiI6KCgoKn46fFgm) ### How it works The straightforward solution goes as follows. ``` q e# Read all input from STDIN and push it as a string on the stack. :i e# Cast each character to its code point. :| e# Take the bitwise OR of all code points. X e# Push 1. & e# Take the bitwise AND of the logical OR and 1. ``` Unfortunately, the characters `q` and `i` cannot appear in the source code. To work around this issue, we are going to create part of the above source code dynamically, then evaluate the string. ``` "<rj" e# Push that string on the stack. :( e# Decrement all characters, pushing ";qi". ( e# Shift out the first character, pushing "qi" and ';'. ( e# Decrement ';' to push ':'. * e# Join "qi" with separator ':', pushing "q:i". ~ e# Evaluate the string "q:i", which behaves as explained before. ``` [Answer] # Pyth, ~~20~~ 13 bytes ``` vj0>LhZ.BRj.z ``` Or in binary: ``` 00000000: 01110110 01101010 00110000 00111110 01001100 01101000 vj0>Lh 00000006: 01011010 00101110 01000010 01010010 01101010 00101110 Z.BRj. 0000000c: 01111010 z ``` [Try it online](https://pyth.herokuapp.com/?code=vj0%3ELhZ.BRj.z&input=+%22%24%26%28%2a%2C.02468%3A%3C%3E%40BDFHJLNPRTVXZ%5C%5E%60bdfhjlnprtvxz%7C~) ### How it works ``` .z all lines of input j join on newline .BR convert each character to binary >LhZ take the last (0 + 1) characters of each binary string j0 join on 0 v evaluate as an integer ``` The resulting integer is truthy (nonzero) iff any of the bytes were odd. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 24‘ịØBvF|\ṪBṪ ``` Expects the input as a quoted command-line argument. [Try it online!](http://jelly.tryitonline.net/#code=MjTigJjhu4vDmEJ2Rnxc4bmqQuG5qg&input=&args=JycnTE9SRU1JUFNWTURPTE9SU0lUQU1FVENPTlNFQ1RFVFZSQURJUElTQ0lOR0VMSVRTRURET0VJVlNNT0RURU1QT1JJTkNJRElEVk5UVlRMQUJPUkVFVERPTE9SRU1BR05BQUxJUVZBCiBWVEVOSU1BRE1JTklNVkVOSUFNUVZJU05PU1RSVkRFWEVSQ0lUQVRJT05WTExBTUNPTEFCT1JJU05JU0lWVEFMSVFWSVBFWEVBQ09NTU9ET0NPTlNFUVZBVAogRFZJU0FWVEVJUlZSRURPTE9SSU5SRVBSRUhFTkRFUklUSU5WT0xWUFRBVEVWRUxJVEVTU0VDSUxMVk1ET0xPUkVFVkZWR0lBVE5WTExBUEFSSUFUVlIKIEVYQ0VQVEVWUlNJTlRPQ0NBRUNBVENWUElEQVRBVE5PTlBST0lERU5UU1ZOVElOQ1ZMUEFRVklPRkZJQ0lBREVTRVJWTlRNT0xMSVRBTklNSURFU1RMQUJPUlZNJycn) ### Hexdump ``` 0000000: 32 34 fc d8 12 42 76 46 7c 5c ce 42 ce 24...BvF|\.B. ``` [Answer] # [Retina](https://github.com/m-ender/retina), 106 bytes Removes every allowed character, then matches any remaining characters. Truthy values will be the number of characters found. Falsey values will be `0`. ``` `"| |\$|&|\(|\*|,|\.|0|2|4|6|8|:|<|>|@|B|D|F|H|J|L|N|P|R|T|V|X|Z|\\|\^|`|b|d|f|h|j|l|n|p|r|t|v|x|z|\||~ . ``` [**Try it online**](http://retina.tryitonline.net/#code=YCJ8IHxcJHwmfFwofFwqfCx8XC58MHwyfDR8Nnw4fDp8PHw-fEB8QnxEfEZ8SHxKfEx8TnxQfFJ8VHxWfFh8WnxcXHxcXnxgfGJ8ZHxmfGh8anxsfG58cHxyfHR8dnx4fHp8XHx8fgoKLg&input=YCJ8IHxcJHwmfFwofFwqfCx8XC58MHwyfDR8Nnw4fDp8PHw-fEB8QnxEfEZ8SHxKfEx8TnxQfFJ8VHxWfFh8WnxcXHxcXnxgfGJ8ZHxmfGh8anxsfG58cHxyfHR8dnx4fHp8XHx8fgoKLg) Since `.` doesn't match newlines by default, I don't have to remove them. [Answer] ## [Perl 5](https://www.perl.org/) + `-p0`, 136 bytes Similar to other answers, this removes all even bytes and leaves any odd bytes (which is truthy). ``` tr<  "$&(*,.02468:<>@BDFHJLNPRTVXZ\\^`bdfhjlnprtvxz|~€‚„†ˆŠŒŽ’”–˜šœž ¢¤¦¨ª¬®°²´¶¸º¼¾ÀÂÄÆÈÊÌÎÐÒÔÖØÚÜÞàâäæèêìîðòôöøúüþ><>d ``` [Try it online!](https://tio.run/##3c9hZwIBAAbgmWQyk0kyMzOZSUvSZnLOzExmZibJJEmlJnWuk5mZJEmSJEmSJEmSJEnSh/f9X7voZ@z5B48UkRM3qqrIwt6@RnugOzzSHxuMppPTs/ML8@WVxWqzO5y3dy5BvH94fHI/v7y@vXu8vg@/PxAMhaOxz0RSkpXM1/fPL7LIIY8CiiihjAqqqKGOBppooY0OuuihjwGGGGGMCaaYYY4FllhhjQ2zzDHPAossscwKq6yxzgabbLHNDrvssc8BhxxxzAmnnHHOBZdccc2NKIjh3eQ/RP5SkhJPJdPqtWTfAg "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 bytes ``` ø0ôH² ®dZÄ ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=+DD0SLIgrmRaxA==&input=LW1SIFsKIvgw9EiyIK5kWsQiLAonIiQmKCosLjAyNDY4Ojw+QEJERkhKTE5QUlRWWFpcXmBiZGZoamxucHJ0dnh6fH4nLAoiISMlJykrLS8xMzU3OTs9P0FDRUdJS01PUVNVV1lbXV9hY2VnaWttb3FzdXd5e30iLAoiTE9SRU1JUFNWTURPTE9SU0lUQU1FVENPTlNFQ1RFVFZSQURJUElTQ0lOR0VMSVRTRURET0VJVlNNT0RURU1QT1JJTkNJRElEVk5UVlRMQUJPUkVFVERPTE9SRU1BR05BQUxJUVZBClZURU5JTUFETUlOSU1WRU5JQU1RVklTTk9TVFJWREVYRVJDSVRBVElPTlZMTEFNQ09MQUJPUklTTklTSVZUQUxJUVZJUEVYRUFDT01NT0RPQ09OU0VRVkFUCkRWSVNBVlRFSVJWUkVET0xPUklOUkVQUkVIRU5ERVJJVElOVk9MVlBUQVRFVkVMSVRFU1NFQ0lMTFZNRE9MT1JFRVZGVkdJQVROVkxMQVBBUklBVFZSCkVYQ0VQVEVWUlNJTlRPQ0NBRUNBVENWUElEQVRBVE5PTlBST0lERU5UU1ZOVElOQ1ZMUEFRVklPRkZJQ0lBREVTRVJWTlRNT0xMSVRBTklNSURFU1RMQUJPUlZNIgpd) Japt's codepage is ISO-8859-1. The code gives `false` when itself is entered as a string, therefore a valid submission. ### Unpacked & How it works ``` Uø0ôHp2 mZ{ZdZ+1 Uø Does input string contain any element in the following array...? 0ôHp2 Range of 0 to 32**2, inclusive mZ{ Map... ZdZ+1 Convert the number Z to a char having charcode 2*Z+1 ``` Not having `String.c` (get charcode, or map over charcodes) was a pain, but fortunately there is `Number.d` (convert number to char). Turns out that Japt wins over CJam, Pyth *and* Jelly :) --- Without the restriction, there are a couple of ways to do it in **6 bytes** (going par with CJam and Jelly again): ``` ®c uÃn Unpacked: UmZ{Zc u} n UmZ{ Map on each char... Zc u Convert to charcode modulo 2 } n Convert the resulting string to number ``` `"000..000"` is converted to the number 0 (falsy) regardless of how long it is. On the other hand, anything that contains 1 is converted to a nonzero `double`, or `Infinity` if it's too big (both truthy). ``` ¬d_c u Unpacked: q dZ{Zc u q Convert to array of chars dZ{ Is something true when mapped with... Zc u Convert each char to charcode modulo 2 ``` More straightforward approach that directly yields `true` or `false`. Or, **5 bytes** solution is even possible with the help of `-d` flag: ``` ¬®c u Unpacked: q mZ{Zc u q Convert to array of chars mZ{ Map... Zc u Convert to charcode modulo 2 Result is array of zeros and ones -d Apply .some() on the resulting array ``` ]
[Question] [ I wrote some text, but it looks too professional. I want to make it look like I was really tired when I wrote it. I need you to insert some typos. Your challenge is to take an arbitrary single line of text, and add typos. This means that for each character, there will be a 10% chance for it to be typofied. The definition of "typofied" is that you must choose (randomly) one of the following: * Duplicate the character. * Delete the character. * Shift the character one keyboard space. The "keyboard" is defined as: ``` qwertyuiop asdfghjkl zxcvbnm ``` For the character shift, you must go one space up, down, left, or right. This must be chosen randomly. The shift option only applies to alphabetic characters. Case must be preserved. Be careful with edge-cases, like `m`! The definition of "random" is that the result must not be predictable (by looking at previous results). For example, you can't typofy every tenth character. Furthermore, the randomness must have an even distribution. For example, you can't do 30% duplicate, 30% delete, and 40% shift; it has to be a 1/3 chance for each (1/2 for each if it's a nonalphabetic character). Example input: ``` This is some correct text. It is too correct. Please un-correctify it. ``` Example output: ``` This iissome xorreect tex.. It is too coteect. Please jn-corretify it. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win. [Answer] # C, 358 bytes (There are only three lines of code, but I've broken up line 3 for legibility) ``` #define x putchar #define y random() c,n;main(){char*s[26]={"QS","HNV","FVX","EFSX","DRW","CDGR","FHTV","BGJY","KOU","HKNU", "IJLM","KO","KN","BJM","ILP","OO","AW","EFT","ADWZ","GRY","IJY","BCG","ESQ","CDZ","HTU", "SX"};while((c=getchar())>0){if(y%10>0&&x(c))continue;if(isalpha(c)&&y%3<1){n=(c&31)-1; x(s[n][y%strlen(s[n])]|(c&32));continue;}if (y&1)x(x(c));}} ``` The array of strings at the beginning lists the possible adjacent keys for each letter of the alphabet. I had to double up the "O" (adjacent to "P") to avoid calculating `random()%1` when selecting a shifted character. Test run: ``` $ echo "This is some correct text. It is too correct. Please un-correctify it." |./a.out This is some cofrect teext. It is too correct.. Plleaase un-correctify it.. ``` --- **Update:** Here's an expanded and commented version of the same source code: ``` #include <stdio.h> #include <string.h> /* ^^ These should be included, but the code compiles without them */ int c,n; void main() { /* Adjacent keys for each letter of the alphabet (A, B, C, ..., Z): */ char *s[26] = { "QS","HNV","FVX","EFSX","DRW","CDGR","FHTV","BGJY","KOU","HKNU", "IJLM","KO","KN","BJM","ILP","OO","AW","EFT","ADWZ","GRY","IJY", "BCG","ESQ","CDZ","HTU","SX" }; /* Fetch input until null character or EOF reached */ while ((c=getchar())>0) { /* For 90% of the time, just echo the character unchanged */ if (random()%10>0 && putchar(c)) continue; /* If it's a letter of the alphabet, shift with 33% probability */ if (isalpha(c) && random()%3<1) { /* Calculate offset to adjacent keys data */ n=(c&31)-1; /* Choose a random adjacent key, and change to lower case if needed */ putchar(s[n][random()%strlen(s[n])]|(c&32)); continue; } /* If we reach this point, either we didn't fetch an alphabet character, or */ /* we did but chose not to shift it. Either way, we now need to either repeat */ /* the character or delete it, with 50% probability for each. */ /* This repeats the character by printing the return value from putchar() */ if (random()&1) putchar(putchar(c)); /* To delete the character, we don't have to do anything. */ } } ``` [Answer] ## Ruby, 168 Slightly shorter take using an array indexing strategy: ``` z='qwertyuiop.asdfghjkl...zxcvbnm'+?.*11 gets.chars{|c|$_=z[c]?z:z.upcase h=[1,-1,11,-11].map{|d|$_[d+~/#{c}/]}-[?.]rescue[] $><<(rand<0.9?c:[c*2,'',*h.sample].sample)} ``` Original regular expression version (184): ``` s='.qwertyuiop.asdfghjkl...zxcvbnm.' gets.chars{|c|c=~/\w/&&(s[c]?s: s.upcase)=~/((\w).{9})?((\w)|.)#{c}((\w)|.)(.{9}(\w))?/ $><<(rand<0.9?c:[c*2,'',*[*$2,*$4,*$6,*$8].sample].sample)} ``` [Answer] ### GolfScript, 120 characters ``` {10{rand}:R~!{[{.}{;}{Z\?[.(.10-@).10+]{Z=}%' '-.,R=}]'QWERTYUIOP ASDFGHJKL ZXCVBNM'' '22*11/*.{32|}%+:Z 2$?0>2+R=~}*}% ``` The code can be tested [here](http://golfscript.apphb.com/?c=IlRoaXMgaXMgc29tZSBjb3JyZWN0IHRleHQuIEl0IGlzIHRvbyBjb3JyZWN0LiBQbGVhc2UgdW4tY29ycmVjdGlmeSBpdC4iCgp7MTB7cmFuZH06Un4he1t7Ln17O317Wlw%2FWy4oLjEwLUApLjEwK117Wj19JScgJy0uLFI9fV0nUVdFUlRZVUlPUCBBU0RGR0hKS0wgIFpYQ1ZCTk0nJyAnMjIqMTEvKi57MzJ8fSUrOlogMiQ%2FMD4yK1I9fn0qfSUK&run=true). ``` { # loop over all characters 10{rand}:R~! # take random number [0..9] and negate (i.e. 10% chance of true) { # {...}* is the if-block [ # Three possible operations (code blocks) in the arry {.} # a) duplicate {;} # b) delete { # c) shift Z # Z is the keyboard layout (see below) \? # Find the index of the current letter [.(.10-@).10+] # Calculate index of letter left, right, above, below {Z=}% # Extract the corresponding letters for indices ' '- # Remove any spaces .,R= # Take random item } ] # Z is the keyboard layout (upper and lower case) # with enough spaces around 'QWERTYUIOP ASDFGHJKL ZXCVBNM'' '22*11/*.{32|}%+:Z 2$?0> # Is the current letter contained in Z and not a space? 2+ # Add 2 (i.e. 3 for letters, 2 for any other char) R= # Take a random code block from above ~ # Execute the block }* }% ``` [Answer] # Python, 251 ``` from random import* w=choice o=ord print"".join(w([z]*9+[w(["",z*2]+[chr(o(w("DGRC FHTV GJYB UOK HKUN JLIM KO NK BMJ IPL O WA ETF ADWZ RYG YIJ CBG QES ZCD TUH XS SQ VNH XVF SFEX WRD".split()[(o(z)&31)-6]))|o(z)&32)]*z.isalpha())])for z in raw_input()) ``` Very simple look-up technique, for a moment I thought it might be cheaper to encode the keyboard as a undirected graph but the overhead for creating such a type in Python proved prohibitive. Since Python's random functions have too-descriptive names I use `choice()` exclusively, renaming it to `w`. The 10% chance of error is handled by `w([z]*9+[...])` where the nine copies of an un-typoed character are in a list with one typo. -16 characters--thanks grc, +2 characters (and correctness, worth many more than 2 chars)--thanks Dhara [Answer] ## C#, 320 bytes (360 bytes with program wrapping) Includes support for "shifted" upper-case letters. As a function (320 bytes): ``` string T(string s){ string t="",z=" ",k=z+z+"qwertyuiop asdfghjkl zxcvbnm"; k+=k.ToUpper()+z+z; int[]m={-11,-1,1,11}; var r=new System.Random(); foreach(var c in s){ if(r.Next(10)>0) t+=c; else{ int i=r.Next(k.IndexOf(c)>0?3:2); if(i>1){ while(' '==k[i=k.IndexOf(c)+m[r.Next(4)]]); t+=k[i]; } else if(i>0) t=(t+c)+c; } } return t; } ``` As a program that reads a line of text (360 bytes): ``` using System; class P{ static void Main(){ string t="",z=" ",k=z+z+"qwertyuiop asdfghjkl zxcvbnm"; k+=k.ToUpper()+z+z; int[]m={-11,-1,1,11}; var r=new Random(); foreach(var c in Console.ReadLine()){ if(r.Next(10)>0) t+=c; else{ int i=r.Next(k.IndexOf(c)>0?3:2); if(i>1){ while(' '==k[i=k.IndexOf(c)+m[r.Next(4)]]); t+=k[i]; } else if(i>0) t=(t+c)+c; } } Console.Write(t); } } ``` Input output sample: ``` This is some correct text. It is too correct. Please un-correctify it. This is some corrrect texy. Ut is too correct. Pease un-coorrectify it. TYPO RAGE CAPS TEXT! TYPPORAGE CAOS TEX! ``` [Answer] ## JS, 303, 288, 275, 273, 274 (bug fix) ``` function z(s){return s.split('').map(function(d){if((r=Math.random)(b='qwertyuiop0asdfghjkl000zxcvbnm')>.1)return d if((c=r(x=(d>'`'?b:(b=b.toUpperCase())).indexOf(d))*(/[a-z]/i.test(d)+2))<2)return c>1?d+d:'' for(a=0;!a;)a=b[x+[11,-11,1,-1][~~(r()*4)]] return a}).join('')} ``` Algorithm for the keyslip: * find char in string (or uppercase) * add 11, -11, 1 or -1 to the index. * if it's invalid (0 or null), re-roll Non-Golfed version per request: ``` function z (s) { return s.split('') // split input string into characters. .map( // and then for each character... function (d) { r = Math.random; // set up a shortened form of Math.random // declare keyboard here because we have parens and we can save a delimeter. b = 'qwertyuiop0asdfghjkl000zxcvbnm'; if (r() > .1) { // normal case return d; } numOptions = /[a-z]/i.test(d) + 2; // if it's a character, 1+2, else 0+2 options // test here because we have parens. x might be -1 if (d > '`') { x = b.search(d); // x marks the spot } else { b = b.toUpperCase(); x = b.search(d); } c = r() * numOptions; // chars can be 0-3, non-chars: 0-2 if (c < 2) { // this case is simple, so it comes first return c>1 ? d + d : ''; // double or omit. } // we must be in keyslip mode. // in the golfed code, this while loop become for loops, // but it's really a while. a = 0; while (!a) { // that is, a != null && a != 0 v = ~~(r() * 4); // 0, 1, 2, or 3 newX = x + [11, -11, 1, -1][v]; // choose one a = b[newX]; // slip the key } return a; } ) // end the map function .join('') // and then reassemble the string } ``` [Answer] ## Perl, ~~278~~ ~~239~~ ~~197~~ ~~169~~ ~~162~~ ~~156~~ ~~151~~ 149 ``` s#((\pL)|.)#rand>.1?$&:($&x2,'',do{1until/^.{@{[(2,-10,12)[rand 4]-1+index$_=QWERTYUIOP0ASDFGHJKL000ZXCVBNM,uc($,=$&)]}}(\D)/;$,&' '|$1})[rand@-]#ge ``` Run with `-p`, then 148+1=149 bytes. E.g.: ``` perl -p typos.pl Your challenge is to take an arbitrary single line of text, and add typos. You challenge is to tale an arbitrary singe lind of text, and add yposs. This is some correct text. It is too correct. Please un-correctify it. This iis some correct text. It s too coorrect.Pleqse un-correctify it. ``` Un-golfed, more or less: ``` s#((\pL)|.)#rand>.1 ? $& : ($&x2,'', do{ 1until/^.{@{[(2,-10,12)[rand 4]-1 +index$_=QWERTYUIOP0ASDFGHJKL000ZXCVBNM,uc($,=$&)]}}(\D)/; $,&' '|$1 } )[rand@-] #ge ``` At first I thought that choosing element randomly in an array (of 26 of them of different lengths) is more statistically 'clean' (i.e. random), but maybe it was wrong. (See previous version.) This last attempt is, following the leaders:-), stepping along a string by either -1,1,-11,11 (randomly) and repeating until valid step. Edit: Thanks to **tobyink** help and other optimizations, we managed to considerably reduce code size. The last approach uses some tricks with regexp search to find valid step along substitution string, eliminating manual checks. Another edit: 5 bytes off because we don't need integers for array indexes + small trick with illegal array index. I tried same trick with `[-4+rand@-]` (i.e. negative indexes) and get rid of one list element, `'',` but it didn't save anything. Edit: Back to simplicity - replacing condition `~~rand 10` with `rand>.1` saves 2 bytes... [Answer] # **PHP, function with 368 bytes** Here is my attempt. It's some "frankencode", but it **kinda** works. ``` function _($m){$q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/');$r='mt_rand';foreach(str_split($m)as$k=>$c)if(!$r(0,9)&&$c!=' ')foreach($q[0]as$x=>$y)if(($z=strpos($y,$c))!==!1){switch($t=$r(-3,2-($z>>3)-($x>>1))){case 2:++$z;break;case 1:++$x;break;case -1:--$x;break;case -2:--$z;break;case -3:$z=8;break;}$m[$k]=$t?$q[0][$x][$z]:$q[1][$z];}return$m;} ``` A more "readable" code: ``` function _($m) { $q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/'); $r='mt_rand'; foreach(str_split($m)as$k=>$c) if(!$r(0,9)&&$c!=' ') foreach($q[0]as$x=>$y) if(($z=strpos($y,$c))!==!1) { switch($t=$r(-3,2-($z>>3)-($x>>1))) { case 2: ++$z;break; case 1: ++$x;break; case -1: --$x;break; case -2: --$z;break; case -3: $z=8;break; } $m[$k]=$t?$q[0][$x][$z]:$q[1][$z]; } return$m; } ``` The only difference between the 2 codes is that one has tons of tabs and newlines. It doesn't produce the same exact type of "incorrectness", but it either deletes or replaces a char using the said conditions. You can try it at <http://writecodeonline.com/php/>. Copy and paste this code: ``` function _($m){$q=array(array('qwertyuiop','asdfghjkl',' zxcvbnm'),'!.-,;?+/');$r='mt_rand';foreach(str_split($m)as$k=>$c)if(!$r(0,9)&&$c!=' ')foreach($q[0]as$x=>$y)if(($z=strpos($y,$c))!==!1){switch($t=$r(-3,2-($z>>3)-($x>>1))){case 2:++$z;break;case 1:++$x;break;case -1:--$x;break;case -2:--$z;break;case -3:$z=8;break;}$m[$k]=$t?$q[0][$x][$z]:$q[1][$z];}return$m;} echo _('This is some correct text. It is too correct. Please un-correctify it.'); ``` After testing, please, tell me if it is a valid answer. [Answer] # C#, 581 bytes ``` using System;class B{static void Main(){var z=Console.ReadLine();var r=new Random();foreach(char C in z){String o;if(r.Next(10)==0){int w=r.Next(3);o=w==0?C+""+C:w==1?"":f(C,r);}else{o=C+"";}Console.Write(o);}Console.ReadLine();}static string f(char C,Random r){string[]k={"00000000000","0qwertyuiop0","0asdfghjkl0","00zxcvbnm0","000000000"};char L=char.ToLower(C);char h='0';for(int i=1;i<4;i++){var d=k[i].IndexOf(L);if(d!=-1){while(h=='0'){int n=r.Next(4);h=n==0?k[i][d-1]:n==1?k[i][d+1]:n==2?k[i-1][d]:k[i+1][d];}h=char.IsUpper(C)?char.ToUpper(h):h;return h+"";}}return C+"";}} ``` and in a more readable format: ``` using System; class A { static void Main() { var z = Console.ReadLine(); var r = new Random(); foreach (char C in z) { String o; if (r.Next(10) == 0) { int w = r.Next(3); o = w == 0 ? C + "" + C : w == 1 ? "" : f(C, r); } else { o = C + ""; } Console.Write(o); } } static string f(char C, Random r) { string[] k = { "00000000000", "0qwertyuiop0", "0asdfghjkl0", "00zxcvbnm0", "000000000"}; char L = char.ToLower(C); char h = '0'; for (int i = 1; i < 4; i++) { var d = k[i].IndexOf(L); if (d != -1) { while (h == '0') { int n = r.Next(4); h = n == 0 ? k[i][d - 1] : n == 1 ? k[i][d + 1] : n == 2 ? k[i - 1][d] : k[i + 1][d]; } h = char.IsUpper(C) ? char.ToUpper(h) : h; return h + ""; } } return C + ""; } } ``` [Answer] ## PHP, ~~326~~ ~~320~~ ~~318~~ 315 chars ``` $h=array(qs,vhn,vxf,sefx,wrd,drgc,fthv,gyjb,uko,hukn,jilm,ok,nk,bjm,ilp,o,aw,etf,awdz,rgy,yji,cgb,qse,zdc,thu,sx);$a=x.$argv[1];for(;$d=$a[++$b];)echo!rand(0,9)&&($c=ord($d)-65)?(!($g=rand(0,($e=($c>-1&&$c<26)or$c>31&&$c<58)+1))?$d.$d:($g<2?"":(($j=$i[rand(0,strlen($i=$h[$c-!$e*32]))])&&$e?strtoupper($j):$j))):$d; ``` And a more readable and commented version: ``` // $a input // $b char iterator // $c current char ascii value // $d current char // $e is uppercase // $g rand() output // $h char displacement // $i current character in $h // $j temporary var for uppercasing // the neighbouring characters of a-z, in alphabetical (and ASCII) order $h=array(qs,vhn,vxf,sefx,wrd, drgc,fthv,gyjb,uko,hukn, jilm,ok,nk,bjm,ilp, o,aw,etf,awdz,rgy, yji,cgb,qse,zdc,thu, sx); // input from argument $a=x.$argv[1]; for(;$d=$a[++$b];) echo!rand(0,9)&&($c=ord($d)-65)? /* 10% chance, read char ASCII value - 65 into $c */ (!($g=rand(0,($e=($c>-1&&$c<26)or$c>31&&$c<58)+1))? /* random number from 0 to 2 (if alphabetic) or 0 to 1 stored in $g */ $d.$d: /* double char if $g = 0 */ ($g<2? "": /* omit char if $g = 1*/ (($j=$i[rand(0,strlen($i=$h[$c-!$e*32]))])&&$e? /* $j = random neighbour of the current char */ strtoupper($j): /* uppercase $j */ $j))) :$d; /* keep char */ ``` Still could be improved, I suppose. -2, -3 thanks to Ismael Miguel [Answer] # Java (475 bytes) This is my try in the verbose language that is Java. Getting random numbers is quite long in Java, and the mapping isn't really efficient. It can probably be improved. ``` import static java.lang.Math.*;public class T{public static void main(String[]a){String z="",v;for(char c:a[0].toCharArray()){double g=random()*60;if(g>=6)z+=c;else{boolean u='A'<=c&c<='Z',l='a'<=c&c<='z';if(g<(l|u?2:3))z+=""+c+c;else if((l|u)&g<4){v="qs,hnv,fvx,efsx,drw,cdgr,fhtv,kou,bgjy,hknu,ijlm,ko,kn,bjm,ilp,o,aw,eft,adwz,gry,ijy,bcg,eqs,cdz,htu,sx".split(",")[u?c-'A':c-'a'];c=v.charAt((int)(random()*v.length()));z+=u?(char)(c-'a'+'A'):c;}}}System.out.println(z);}} ``` Usage: ``` java T "This is some correct text. It is too correct. Please un-correctify it." ``` Uncompressed, accolades added: ``` import static java.lang.Math.*; // Need random() public class T { public static void main(String[] a) { String z = "", v; for (char c : a[0].toCharArray()) { double g = random() * 60; // Compute random only once for two cases. if (g >= 6) { // 90% must be correct (accolades are stripped) // so we just copy the character. z += c; } else { // These tests come often. boolean u = 'A' <= c & c <= 'Z', l = 'a' <= c & c <= 'z'; // reuse the random. g is [0,6[. if (g < (l | u ? 2 : 3)) { // If c is an ascii letter (l|u) then g must be [0,2[ ; if not, then g must be [0,3[. // If those conditions are met, we duplicate the character z += "" + c + c; } else if ((l | u) & g < 4) { // if c is letter and g [2,4[ then we perform the wrong key event. // I could not compress it using the keyboard mapping shorter in Java than expanding it like it is now. v = "qs,hnv,fvx,efsx,drw,cdgr,fhtv,kou,bgjy,hknu,ijlm,ko,kn,bjm,ilp,o,aw,eft,adwz,gry,ijy,bcg,eqs,cdz,htu,sx".split(",")[u ? c - 'A' : c - 'a']; // get a random character from the string. c = v.charAt((int) (random() * v.length())); // Keep the case of the character. z += u ? (char) (c - 'a' + 'A') : c; } else { // if c is not an ascii letter or if g is [4,6[ // Do nothing. This else is stripped. } } } System.out.println(z); } } ``` [Answer] # AutoHotkey 441 bytes The input must be given as a command line parameter, the output is given as an error message. Golfed version ``` loop, parse, 1 { k:={1:"q",2:"w",3:"e",4:"r",5:"t",6:"y",7:"u",8:"i",9:"o",10:"p",21:"a",22:"s",23:"d",24:"f",25:"g",26:"h",27:"j",28:"k",29:"l",42:"z",43:"x",44:"c",45:"v",46:"b",47:"n",48:"m"},a:=A_LoopField,q:=r(z?3:2),z= if r(10)!=10{ h.=a continue } for x,y in k z:=y=a?x:z if q=1 h.=a a if q=3 { Loop{ t:=r(4),w:=z+(t=1?20:t=2?-20:t=3?1:-1) } until k.HasKey(w) h.=k[w] } } throw % h r(n){ Random,w,1,n return w } ``` Un-golfed and annotated version (difference is that this version has more white space and the variable assignments are on separate lines for readability.) ``` k:={1:"q",2:"w",3:"e",4:"r",5:"t",6:"y",7:"u",8:"i",9:"o",10:"p",21:"a",22:"s",23:"d",24:"f",25:"g",26:"h",27:"j",28:"k",29:"l",42:"z",43:"x",44:"c",45:"v",46:"b",47:"n",48:"m"} loop, parse, 1 { a:=A_LoopField ;get a random number from 1-10 and check if it is 10 ; if it isn't skip the rest of this iteration if r(10)!=10 { h.=a continue } ;check if the current character is in the k z= for x,y in k z:=y=a?x:z ;choose a random number to decide what typo to do q:=r(z?3:2) if q=1 h.=a a ;duplicate the key if q=3 { ;the keyboard array is set up so that by adding or subtracting ; 20 from the index you are moving up or down a row ; and by adding or subtracting 1 you move right or left ; then you just need to check if the adjusted index ; is valid Loop { t:=r(4) w:=z+(t=1?20:t=2?-20:t=3?1:-1) } until if k.HasKey(w) h.=k[w] } } ;display the string as an error message throw % h r(n) { Random,w,1,n return w } ``` ]
[Question] [ Since I saw the first one a few years ago, I always was subjugated by this kind of word clock where the time is actually spelled out by words being lit up or not into a meaningful sentence. [![A Word Clock](https://i.stack.imgur.com/KwKBl.jpg)](https://i.stack.imgur.com/KwKBl.jpg) The text displayed on that clock is the following. ``` IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK ``` Your task is to write such a working clock. Words are lit up if and only if they're relevant to printing the current time. Otherwise, they're lit down. Words are "lit up" by being printed and are "lit down" by being replaced by a number of spaces being the length of the word. Example: if the current time is 17:23, the printed text must be exactly the following: ``` IT IS TWENTY FIVE MINUTES PAST FIVE ``` ## Rules 1. The time printed is the 12h variant, but without AM/PM. 2. The rounding is done on the base of minutes only (seconds are totally irrelevant). The rounding is done to the closest multiple of 5. So, for example, even though 17:52:38 really is closest to 17:55, but since the seconds are irrelevant, 17:52 is actually rounded down to 17:50, and the text printed is "IT IS TEN MINUTES TO SIX" (with relevant spacing). So if `XX` is a multiple of five, `XX` will be used from HH:(XX-2):00 until HH:(XX+2):59. The word `MINUTES` must appear if `FIVE`, `TEN` or `TWENTY` are lit up in the minutes section (before "TO" or "PAST"). 3. All irrelevant words are replaced by as many spaces as needed to keep the text where it is located in the template above. Trailing spaces may be trimmed. Spaces relevant to keeping the text at the expected position must be kept. 4. Trailing lines may be trimmed as well. Relevant empty lines are still required to appear. Example: ``` IT IS TEN MINUTES PAST TWO ``` 5. Do not light up `TEN` on the first line or `FIVE` on the third line when these values refer to the hours. 6. You may accept an input. If you accept an input, the input will be the time to print in any valid format you want (string, list of integers, native time type your language support, ...), but no parameters are allowed if they're not related to the time to print. If you support no input, then you must use the current time. If you support both, that's better but there's no bonus ;) 7. Your code may be a program, a function, a lambda but not snippet. 8. If your language supports printing in any way, **it must print** the result (in a file, on the standard output, I don't mind). If your language doesn't support printing in any way, it is allowed to simply "return" the expected text. The result may be either all uppercase or all lowercase, not a mix of both. 9. Standard loopholes apply. 10. This is code-golf so the shortest code wins! 11. In the measure of possible, please provide a link to an online interpreter of your language. ## Test cases ``` Input: <no input> (the current local time is 19:20) Output: IT IS TWENTY MINUTES PAST SEVEN ``` --- ``` Input: 13:15 Output: (empty line is being printed) IT IS QUARTER PAST ONE ``` --- ``` Input: 13:58 Output: (rounding) IT IS TWO O'CLOCK ``` --- ``` Input: 14:30 Output: (half is always a edge-case) IT IS HALF PAST TWO ``` --- ``` Input: 15:35 Output: (light up "TO") IT IS TWENTY FIVE MINUTES TO FOUR ``` --- ``` Input: 10:00 Output: (do not use the TEN or FIVE on the first line when referring to the hours) IT IS TEN O'CLOCK ``` --- ``` Input: 12:00 Output: (O'CLOCK and a lot of empty lines) IT IS TWELVE O'CLOCK ``` [Answer] # TI-Basic, 335 334 bytes Pretty much perfect, since the TI-84 calcs have 8x16 letter displays, and this is 8x15. Date is taken as input in order to support calcs earlier than TI-84, which do not have internal clocks. With no arguments, `Input` gets input by default into `X` and `Y`, similar to `Prompt X,Y`. So make `X` be hours (anything `>=0` will work correctly) and have `Y` be minutes. ``` Input ClrHome int(Y/5-5.6 Output(1,1,"IT IS If Ans=~6 Output(8,8,"O'CLOCK If 2=abs(3-abs(Ans Output(3,1,"FIVE If 4=abs(Ans Output(1,12,"TEN If 3=abs(Ans Output(2,1,"QUARTER If 2=abs(Ans Output(2,8,"TWENTY If sum(abs(Ans)={1,2,4,5 Output(3,5,"MINUTES If not(Ans Output(1,7,"HALF If Ans<1 and Ans+6 Output(4,1,"PAST If Ans>0 Output(3,14,"TO 12fPart(12(^~1)(X+(Y>32->A If not(Ans 12->A {21,6,10,25,30,41,45,51,61,66,70,81 .05Ans(A Output(int(4+Ans),20fPart(Ans),sub("ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVENTWELVE",6A-5,6 ``` Note 1: For TI-84+ you can replace `Input` with something like `getTime:Ans(1->X:getTime:Ans(2->Y`. Also, `int(Y/5-5.6` is equivalent to `round(Y/5,0)-6`. And no, in this case `int(` could not be interchanged with `iPart(`. Note 2: This prints the input just fine, but for asethetic reasons you probably want `Pause` at the end of the program to avoid the `Done` message upon program termination. Edit: Byte count lowered because tokenized (see note on previous revision), also a bug is fixed thanks to @Neil. Third, fixed a bug I found myself which would have costed 2 bytes but the optimization actually saved 1 byte overall, and I also realized that I am getting input so I don't need to call `getTime` (duh?). Last, for anyone who wants to confirm this byte count, the only two byte token is `sub(`. [Answer] # PHP, ~~387~~ ~~384~~ ~~353~~ ~~352~~ ~~342~~ ~~323~~ ~~310~~ ~~306~~ ~~298~~ ~~293~~ 291 bytes **Thanks @Christoph** for golfing along with his **excellent** findings! At least 45 bytes are on his account; 16 or more inspired by him. A Marvel Team Up! ``` IT IS <?foreach([HALF,TEN,QUARTER,TWENTY,FIVE,MINUTES,TO,PAST,TWO,THREE,ONE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,ELEVEN,TWELVE,"O'CLOCK"]as$w)echo strstr([w,ghj,dhj,ej,fhj,fghj,cj,fghi,fhi,ei,dhi,ghi][$m=date(i)/5+.5].mklnopqrstuvm[date(h)-($m<7)],99+$i)?$w:$w^$w^" "," "[$i++%3^$i<3]; ``` loops through the data and checks if the current index is in a generated string that contains the indexes of the words to light up (mapped to letters); appends linebreak or space depending on the index. May yield notices if you dont´t use the default value for `error_reporting` (22519). [Test it online.](http://sandbox.onlinephpfunctions.com/code/d66b741e9f7432708e4e7d272d6f9a1825b7b3cb) **breakdown** ``` IT IS <? foreach([HALF,TEN,QUARTER,TWENTY,FIVE,MINUTES,TO,PAST, // loop through words TWO,THREE,ONE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,ELEVEN,TWELVE,"O'CLOCK"]as$w) echo strstr( // search word index in ... [w,ghj,dhj,ej,fhj,fghj,cj,fghi,fhi,ei,dhi,ghi][$m=date(i)/5+.5] // minutes & co .mklnopqrstuvm[date(h)-($m<7)] // hours (-1 if minutes<33) ,99+$i // (map 0..20 to c..w) )?$w:$w^$w^" ", // if found, print string, else print spaces "\n "[$i++%3^$i<3]; // if $i in [3,5,8,...], print newline, else space ``` **Golfs**: * `$x/5+.5|0` is two bytes shorter than `round($x/5)`. * Two calls of `date(h)` are one byte shorter than assigning the `date` result to a variable. * Using a single assigment golfed away the variable that the light-up indexes were stored in. * A string for the light-up indexes instead of an array saved **around 30 bytes**. * `$w<A` is three bytes shorter than `$w=="\n"` - make sure that no space is after a delimiter! * `abs` saved 8 bytes on the minutes word. * Thanks @Christoph: Moving from numbers to letters for the map rendered the separators obsolete and allowed one more string instead of array; saved **23+8 bytes**. Using underscore as the first index allowed to include it into the "it is" alternatives; and it rendered the quotation for the hours obsolete. * Duplicating the `1` value in the hours map rendered the modulo obsolete and that with additional golfing saved 10 bytes. Inspired by @Christoph. * Calculating the linebreaks and spaces instead of hardcoding them shaved off **19 bytes**. * Bit logic on strings saves 7 bytes: `str_pad("",strlen($w))` -> `$w^$w^" "`. (Christoph) * If `strtr`´s second parameter is no string, it will be interpreted as an ascii code. saves 5 bytes. [Answer] ## JavaScript (ES6), ~~291~~ ~~303~~ 295 bytes Takes input as two integers with currying syntax `(h)(m)` ``` h=>m=>console.log(`IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK`.replace(/\S+/g,w=>(k/=2)&1?w:w.replace(/./g,' '),k=[x=1<<19,88,81,66,84,92,64.5,60,52,34,49,56,x,h=(m<33?h+11:h)%12][m/5+.4|0]*16|6|2048<<(h?h-(h<3):2))) ``` ### How it works The whole clock can be seen as 23 LEDs that are either ON or OFF. So, the clock state is a 23-bit integer. ``` Bit | Word Bit | Word ----+-------- ----+-------- 00 | IT 12 | ONE 01 | IS 13 | FOUR 02 | HALF 14 | FIVE 03 | TEN 15 | SIX 04 | QUARTER 16 | SEVEN 05 | TWENTY 17 | EIGHT 06 | FIVE 18 | NINE 07 | MINUTES 19 | TEN 08 | TO 20 | ELEVEN 09 | PAST 21 | TWELVE 10 | TWO 22 | O'CLOCK 11 | THREE ``` The *minutes* logic that we need to implement to enable the right words is not as simple as one might think at first glance. A magic-golfing formula may exist but I went the easy way and decided to just hardcode each possible configuration: ``` Minutes | Words | Enabled bits | Value | Value / 8 --------+--------------------------+--------------+---------+---------- 00 | O'CLOCK | 22 | 4194304 | 524288 05 | FIVE MINUTES PAST | 6, 7, 9 | 704 | 88 10 | TEN MINUTES PAST | 3, 7, 9 | 648 | 81 15 | QUARTER PAST | 4, 9 | 528 | 66 20 | TWENTY MINUTES PAST | 5, 7, 9 | 672 | 84 25 | TWENTY FIVE MINUTES PAST | 5, 6, 7, 9 | 736 | 92 30 | HALF PAST | 2, 9 | 516 | 64.5 35 | TWENTY FIVE MINUTES TO | 5, 6, 7, 8 | 480 | 60 40 | TWENTY MINUTES TO | 5, 7, 8 | 416 | 52 45 | QUARTER TO | 4, 8 | 272 | 34 50 | TEN MINUTES TO | 3, 7, 8 | 392 | 49 55 | FIVE MINUTES TO | 6, 7, 8 | 448 | 56 ``` ### Test cases ``` let f = h=>m=>console.log(`IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK`.replace(/\S+/g,w=>(k/=2)&1?w:w.replace(/./g,' '),k=[x=1<<19,88,81,66,84,92,64.5,60,52,34,49,56,x,h=(m<33?h+11:h)%12][m/5+.4|0]*16|6|2048<<(h?h-(h<3):2))) ; [[13,15],[13,58],[14,30],[15,35],[10,0],[12,0]].map(([h, m]) => { console.log('h = ' + h, 'm = ' + m); f(h)(m); }); ``` [Answer] ## Batch, 789 bytes ``` @echo off if not "%1"=="" setlocal&set time=%1 set/a"h=%time:~0,2%,m=6%time:~3,2%%%60+2,h+=m/35,h%%=12,m=6-m/5%%12,n=m%%3,o=m%%2 set p= set s= call:c %m:-=% "IT IS HALF" 0 "IT IS TEN" 4 "IT IS" call:c %m:-=% QUARTER 3 " TWENTY" 2 " TWENTY" 1 if %m% lss 0 set s= TO call:c 0 " " %n% " MINUTES" %o% "FIVE MINUTES" set s= set p=PAST if %m%==6 set p= if %m% lss 0 set p= call:c %h% TWO 2 " THREE" 3 set p= call:c %h% ONE 1 " FOUR" 4 " FIVE" 5 call:c %h% SIX 6 " SEVEN" 7 " EIGHT" 8 call:c %h% NINE 9 " TEN" 10 " ELEVEN" 11 if %m%==6 set s= O'CLOCK call:c %h% TWELVE 0 " " exit/b :c set t=%1 :l if %t%==%3 echo(%p%%~2%s%&exit/b shift shift if not "%3"=="" goto l echo(%p%%~2%s% ``` Note: Trailing space after `PAST` and 5 trailing spaces on each of the following two lines. [Answer] ## JavaScript, ~~567 564 551 542 529 527~~ 519 bytes ``` f=(h,m)=>{c={m6:"HALF ",m2:"TEN\n",m3:"QUARTER ",m4:"TWENTY\n",m1:"FIVE ",m:"MINUTES ",t:"TO\n",p:"PAST ",h2:"TWO ",h3:"THREE\n",h1:"ONE ",h4:"FOUR ",h5:"FIVE\n",h6:"SIX ",h7:"SEVEN ",h8:"EIGHT\n",h9:"NINE ",h10:"TEN ",h11:"ELEVEN\n",h0:"TWELVE ",m0:"O'CLOCK"};l=[];p="push";m=Math.round(m/5);if(m>11){m=0;h++}if(m>6){l[p]("t");m=12-m;h++}else if(m)l[p]("p");if(m%3)l[p]("m");if(m==5)l[p]("m4","m1");else l[p]("m"+m);l[p]("h"+h%12);s="IT IS ";for(k in c)s+=(l.indexOf(k)>=0)?c[k]:c[k].replace(/\S/g," ");console.log(s)} f(19, 20); f(13, 15); f(13, 58); f(14, 30); f(15, 35); f(10, 0); f(12, 0); ``` I don't know if it's OK to take hours and minutes as arguments. You said "list of integers". Does it still count? It's my first time golfing, by the way. What do you think? --- **Edit:** Saved a few bytes by dividing minutes. Thanks, Olivier! [Answer] # JavaScript (ES6) 360 A function with input parameters hour (0..23) and minute (0..59). Using `alert` for output, as it's the standard output function in javascript even if it's inconvenient. (And it's short) ``` (k,n,m=(n+2)/5|0,h=(k+(m>6))%12,i=0)=>alert(`IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK`.replace(/\S+/g,w=>[,,m-6,m-2&&m-10,m-3&&m-9,m-4&&m-8&&m-5&&m-7,m-1&&m-11&&m-5&&m-7,!(m%3),m<7|m==12,!m|m>6,h-2,h-3,h-1,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h%12,m%12][i++]?w.replace(/./g,' '):w)) ``` **Test** Note: for your peace of mind, in the test snippet the alert output is redirected to the page text ``` F= (k,n,m=(n+2)/5|0,h=(k+(m>6))%12,i=0)=>alert(`IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK`.replace(/\S+/g,w=>[,,m-6,m-2&&m-10,m-3&&m-9,m-4&&m-8&&m-5&&m-7,m-1&&m-11&&m-5&&m-7,!(m%3),m<7|m==12,!m|m>6,h-2,h-3,h-1,h-4,h-5,h-6,h-7,h-8,h-9,h-10,h-11,h%12,m%12][i++]?w.replace(/./g,' '):w)) function alert(x) { O.textContent=x } function update() { F(+H.value,+M.value) } update() ``` ``` input { width:3em } ``` ``` Hours<input id=H type=number min=0 max=23 value=17 oninput='update()'> Minutes<input id=M type=number min=0 max=59 value=37 oninput='update()'> <pre id=O></pre> ``` [Answer] ## Python 2, ~~466~~,~~460~~,~~449~~,~~452~~,~~459~~ 449 bytes As it's allowed to be a function accepting h and m as integers we can save a few bytes. [Try it online](https://repl.it/FNo7/0). ``` def t(h,m): m=(2+m)//5 h=h%12 n=0 if m>6:n,m=1,12-m;h+=1 a="""IT IS _HALF _TEN_ _QUARTER _TWENTY_ _FIVE _MINUTES _TO_ _PAST _TWO _THREE_ _ONE _FOUR _FIVE_ _SIX _SEVEN _EIGHT_ _NINE _TEN _ELEVEN_ _TWELVE _O'CLOCK""".split("_") b=[1,m==6,m==2,1,m==3,3<m<6,1,m in[1,5],m in[1,2,4],n*m,1,(1-n)*m,h==2,h==3,1,h==1,h==4,h==5,1,h==6,h==7,h==8,1,h==9,h==10,h==11,1,h==0,m==0] for i,c in enumerate(a): if b[i]:print c, else:print' '*len(c), ``` I had a couple of bugs (now fixed) with the logic for `TO`/`PAST` vs `O'CLOCK`. Also saved a few bytes for `enumerate`, changing the `import`, and `19<m<26` instead of `m in [20,25]`. Saved another 8 for working in 5-minute chunks rater than minutes. Rod pointed out some more bugs costing me quite a bit, but I recovered a little with more efficient assignments and a bugfix that worked in my favour. [Answer] # [Perl 6](http://perl6.org/), ~~308~~ ~~296~~ 293 bytes ``` ->\h,\m{my \n=round(m/5)%12;say "IT IS HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK".subst: /\S+/,{++$==1|2|(0,7,4,5,6,(6|7),3)[min n,12-n]|8*?(n%3)|(23,10,9)[(n+5)/6]|(13,11,12,|(14..*))[(h+m/33-1)%12]??$_!!" "x.comb},:g} ``` [Try it online!](https://tio.run/nexus/perl6#VVDbTsJAEH3frxibIrt0abst5VIshJBFGrFVuqAGCBEVIbHFcEkklC/zzR/DLT45D3M55@RkZuI9XM7BOxUb4wUdx4d4D@PEW692ySuODYfkmFXfPO9B8QX4EXRbvQ4IHqD7QasveB/EAw/EE@r4Qw63fjAQPAIRortWJCQXguj2OUdhwKETDvqQ6VDkP0LEhzwA7l93BQp8SYts7GUokp49aRfm272wfaPom91ss3XBGEeaQQ@apnoeS60Um7RCS9ShZYrLaYVQm4ziZQIJZVYxmaTVQhMnOZuk2LIpM2mNjHCiOcQoT1LMJMSkkMq2pOsFIsmFFhu2XWTZ0ZNmU51eXCigfOkvq3h2pO778TRfreGK2a5TBVZzLRNYybVldlzbAWa6puwtmRtwQCBDfhOri9VuTUGVq@22bwQ80DefH8stzrt58vOt@8m2fhaf31yUMVKnk6wqf/gc/lvU0fH0Cw "Perl 6 – TIO Nexus") ### Explanation The basic structure is as follows: ``` -> \h, \m { # A lambda taking two args (hour and minute). my \n = round(m / 5) % 12; # Index from 0 to 11, representing the minutes. say "...".subst: /\S+/, { # Print the template with each word replaced: ++$ == ...|...|...|... # If counter equals one of expected indices, ?? $_ # then replace the word with itself, !! " " x .comb # else replace it with spaces. }, :g # (Use global matching.) } ``` The expression elided as `...|...|...|...` above, is a [Junction](https://docs.perl6.org/type/Junction) of integers representing 1-based word indices, and is made up as follows: ``` 1|2 # IT IS | (0,7,4,5,6,(6|7),3)[min n,12-n] # FIVE / TEN / QUARTER / TWENTY / TWENTY FIVE / HALF | 8*?(n%3) # MINUTES | (23,10,9)[(n+5)/6] # O'CLOCK / PAST / TO | (13,11,12,|(14..*))[(h+m/33-1)%12] # ONE / TWO / THREE / FOUR / FIVE / SIX / SEVEN / ... ``` [Answer] ## **Python3 , (569 bytes)** This answer requires time in format *hh mm* (space separated integers) .I managed to have '\n' printed, which is inspired by *Chris's* method.Thanks, Chris! Any help reducing code is appreciated. ``` H,M=input().split() w="""HALF _TEN_ _QUARTER _TWENTY_ _FIVE _MINUTES _TO_ _PAST _TWO _THREE_ _ONE _FOUR _FIVE_ _SIX _SEVEN _EIGHT_ _NINE _TEN _ELEVEN_ _TWELVE _O'CLOCK""".split("_") h,m=int(H),int(M) if h>12:h-=12 m=(m//5+1)*5 if m%5>2.5 else m//5*5 if m>30: m=60-m h=(h+1)%12 X=[m==30,m==10,1,m==15,m in[20,25],1,m in[5,25],m not in[0,15,30],int(M)>30 and m!=0,1,m!=0 and int(M)<31,h==2,h==3,1,h==1,h==4,h==5,1,h==6,h==7,h==8,1,h==9,h==10,h==11,1,h in[0,12],m==0] t="IT IS " for i in range(0,28): if(X[i]):t+=w[i] else:t+=" "*len(w[i]) print(t.strip()) ``` [Try It Online](https://tio.run/#7x1H8) [Answer] # [Python 2](https://docs.python.org/2/), ~~443~~ 440 bytes ``` R=range w="HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK".split(' ') h=[10,8,9]+R(11,20) c=['IT','IS']+[' '*len(x)for x in w] i,j=input() i=(i,i+1)[j>30]%13-1 j=int(round(j/5.0)*5.0)%60 for z in[[20],[4,5,7],[1,5,7],[2,7],[3,5,7],[3,4,5,7],[0,7],R(3,7),[3,5,6],[2,6],[1,5,6],R(4,7)][j/5]:c[z]=w[z] c[h[i]]=w[h[i]] x=0 for y in[4]+R(6,22,3)+[23]:print' '.join(c[x:y]);x=y ``` [Try it online!](https://tio.run/nexus/python2#NZBfT8IwFMXf@yluSMhaqLg/MBRTE0KKLM5Nt4Kapg9mopSYQRDC4MtjO/Dl3Nz@Tk/v7Sljm4/ye472rDEZxmMQPIGX6TATPAPxyhPxDuNoxuEpSqaC5yBSeB7mwrAUxCTjHNKEwzidZmdfHr1BzmcmhUcPEwFJZLAN5XF9ajJjY0udUZyOHhud3/WP3mIHHIIWTHouvaG3qp1hz6O@S1DBpBMJhzpR7qi2NL7Wz7zEFflabaACXcJeIU2XTJfr3RYTpBnWVLc9Ipf3gauaXnDlIYu3eLPalZ94ed3ruKRlpRm6yOYcTY6Uvquo7NIe7ZvqXapfa3DpAvrPXasZDmifnHFYm8PL1dDCroFKmvfUoJBHxfZGUCEXUivb1BVV7DzDwc7QtZuH1PdpQNrSD9RgvTGTm607y5UucSGrwUGRu4odTifzQz3/Dw "Python 2 – TIO Nexus") It could probably still benefit from some more golfing. Input is a list of integers e.g. 7,23 = 7:23 [Answer] # [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), ~~737~~ 708 bytes Yeah, verbosity and lack of "real" math hurt the bytecount badly. ``` {@seth argv.0}{@php$DATA[m]=ceil($DATA[argv][1]/5)*5%60|0}{@ifm}{@ifm is30}{@setA"HALF"}{@/}{@if"@[15]0$@"is matchesm}{@setB"TEN"}{@/}{@if"@[14]5$@"is matchesm}{@setC"QUARTER"}{@/}{@if"@[24]0$@"is matchesm}{@setD"TWENTY"}{@/}{@if"@^[25]?5$@"is matchesm}{@setE"FIVE"}{@/}{@if"@^([235]?5|[1245]0)$@" is matchesm}{@setF"MINUTES"}{@/}{@ifm is greater30}{@setG"TO"}{@else}{@setH"PAST"}{@/}{@else}{@setU"O\'CLOCK"}{@/}{@setZ"","ONE","TWO","THREE","FOUR","FIVE","SIX","SEVEN","EIGHT","NINE","TEN","ELEVEN","TWELVE"}{@setY"J"}{@incbyh Y}{@php$DATA[$DATA[Y]]=$DATA[Z][$DATA[h]]}{@print"IT IS%-6s%s\n%8s%s\n%-5s%-7s %s\n%4s %3s %s\n%3s %4s %s\n%3s %5s %s\n%4s %3s %s\n%6s %s",A,B,C,D,E,F,G,H,J,K,I,L,M,N,O,P,Q,R,S,T,U} ``` This expects the hour and minutes as the 1st and 2nd parameter on the class. --- **Ungolfed:** ``` {@set hour argv.0} {@//The bitwise is required for the `@if minutes is 30`} {@//Otherwise, I would be forced to write `@if minutes is equal to 30`} {@php $DATA['minutes'] = ((ceil($DATA['argv'][1] / 5) * 5) % 60) | 0} {@if minutes} {@if minutes is 30} {@set A "HALF"} {@/} {@if "@[15]0$@" is matches minutes} {@set B "TEN"} {@/} {@if "@[14]5$@" is matches minutes} {@set C "QUARTER"} {@/} {@if "@[24]0$@" is matches minutes} {@set D "TWENTY"} {@/} {@if "@^[25]?5$@" is matches minutes} {@set E "FIVE"} {@/} {@if "@^([235]?5|[1245]0)$@" is matches minutes} {@set F "MINUTES"} {@/} {@if m is greater than 30} {@set G "TO"} {@else} {@set H "PAST"} {@/} {@else} {@set U "O\'CLOCK"} {@/} {@set numbers "", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN", "TWELVE"} {@set key "J"} {@inc by hour key} {@php $DATA[$DATA['key']] = $DATA['numbers'][$DATA['hour']]} {@print "IT IS%-6s%s\n%8s%s\n%-5s%-7s %s\n%4s %3s %s\n%3s %4s %s\n%3s %5s %s\n%4s %3s %s\n%6s %s", A, B, C, D, E, F, G, H, J, K, I, L, M, N, O, P, Q, R, S, T, U} ``` --- **How to run:** 1. Get the code from <https://github.com/ismael-miguel/SimpleTemplate> 2. Run the following code: ``` <?php include 'SimpleTemplate.php'; $template = new SimpleTemplate('<code>'); $template->render($hour, $minutes); //system-time: $template->render(date('g'), date('i')); ``` 3. Done! [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 437 bytes ``` (h,m)->{h=(h+m/35+11)%12+1;Object[]s="HALF TEN QUARTER TWENTY FIVE MINUTES TO PAST TWO THREE ONE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE O'CLOCK".split(" ");for(int i=s.length,M[]={1<<20,176,162,132,168,184,129,120,104,68,98,112};i-->0;)s[i]=(7<i&i<20?h==i-(h>3?7:h>1?6:9):(M[(m+2)/5%12]&(1<<i))>0)?s[i]:"";System.out.printf("IT IS %4s %3s%n%7s %6s%n%4s %7s %2s%n%4s %3s %5s%n%3s %4s %4s%n%3s %5s %5s%n%4s %3s %6s%n%6s %7s",s);} ``` [Try it online!](https://tio.run/##bVFhj5pAEP1@v2JCwhXqyrEgeoporobrkaq0wl3bcHzgFGWtLMZdL2mMv90uqE00RzKZmTdv3gw7y@Q9qRfrlC5nf9oHkq@LDYelALUtJyttvqVTTgqqfbZvpquEMRglhMLuBmC9fVuRKTCecOHeCzKDXNSUgG8IXUQxJJsFUysqwBcyKCjb5umm61GeLtINOvkezME5KBnK1XpvlzlKVsvvTKuGsSpjo4Zt/22ZTnkUM0d6ehg@QuiO4cfzwyR0JxD@dMfhb3j0XlwYeePn0A0g9OH7QxCKmg/h08R1wR@78Og/T468wPsFgfsiVFzv61MIY0@US1F3WKFCcyho/qfB0B98kzS2XhGuSCCp9rzYKIRyIA7TVild8AyNotjZ4W7X0BFuNRFuGgibwpr3CN83EDbawkRNbyABtQWKjb1N6vWebqssIrGjtLrklgiBfuY4pK5kPbPf6mQ93G922mpHGUVKXjPUO0s8R3yriFlEVXu62i@7O5JkB38ZT3Ot2HJtLZ6ezxXJC8ELQG4wkE0mU7klgmYZlEiZGOfEFGaVSRk0Kjsl1rlyplUCzUpAQky19we7uq0YGcXi3jxlnIFzujjADrCJAFuwB3QBWfeXUAOBqV9CloCuGnUE@hXLuID2x3XEkUCpdqo26hz3Uv@v9cFzhRVPNmYdWTdm4i@phMquSI@PHseqfWqfa8l0mq65cibANeN6wIoq0it9pfUPvlcqnfr2N6XtD/8A "Java (OpenJDK 9) – Try It Online") I thought I'd finally give a shot at my challenge ;) [Answer] # [Perl 5](https://www.perl.org/), ~~487~~ 449 bytes ``` ($a,$_,$h)=localtime;s/[3-7]$/5/;s/[12]$/0/;$m=s/(.?)[89]$/($1+1)*10/er;$_="IT IS half ten quarter tw five minutes to past 2two 3three 1one 4four 5five 6six 7seven 8eight 9nine 10ten 11eleven 12twelve oc";if($m>30){s/to/TO/;$h++;$m=60-$m}elsif($m){s/past/PAST/}$h=$h%12||12;$m!=30?$m%15?s/m\w+/uc$&/e:$m?s/q\w+/uc$&/e:s/oc/O'CLOCK/:s/half/HALF/;$m%10&&!/Q/&&s/five/FIVE/;$m>15&&$m<30?s/tw/TWENTY/:$m==10&&s/ten/TEN/;s/\b$h\w+/uc$&/es;y/a-z0-9/ /;say ``` [Try it online!](https://tio.run/##TVBdT8JAEHzvrzjMUUEoewcWxFqIIRCJH2hsNEaNqWSxTXo97B0gfvx1650v@rY7Mzs7u0ssMr8sazRu0qcmTephJudxplOBgYL7jtd7pOCDrXnblAwCKkIFtdawfn/QN0iN8gav73EGWAT0KdyZRmR6TZI4WxCNufO6iguNBdEbZ5GukYg0X2lUREtnGStN2nojSUcnBaLDZY5kfyFXBfGt2Omq9I30FK4xJweYviTa6eepEXFmvAnnmFnO4cYFM@Mu5ztBuqhRMeiw@ocCLSGamcxJo2GDd5lHxRdm6ldjBTYDXB5fR/BFk5AmVd7@/ORtI66EHTakosr9oQLxsGnAak5dwEMqDPD6D1Ag5zDbHZ3NRqdgOns7nByfTeyzqpy5bgWuwHUV2KNgMr0ZW2bAfdel4sisMUE3EN2OL6I7MP5haIcMiDlE4wv7/odnmvytVMEWYu@deX0gho23ZfktlzqVuSq9c7/FOPsB "Perl 5 – Try It Online") [Answer] # C, 447 bytes A function `c()` which takes hours and minutes as arguments, and prints the result to standard output stream: ``` char*z="";c(h,m){h+=(m+=2,m/=5)>6;h%=12;m=1<<m;printf("IT IS%5s %s\n%7s %s\n%4s%8s %s\n%4s%4s %s\n%3s%5s %s\n%3s%6s %s\n%4s%4s %s\n%6s %s",m&64?"HALF":z,m&1028?"TEN":z,m&520?"QUARTER":z,m&432?"TWENTY":z,m&2210?"FIVE":z,m&3510?"MINUTES":z,m&3968?"TO":z,m&126?"PAST":z,h-2?z:"TWO",h-3?z:"THREE",h-1?z:"ONE",h-4?z:"FOUR",h-5?z:"FIVE",h-6?z:"SIX",h-7?z:"SEVEN",h-8?z:"EIGHT",h-9?z:"NINE",h-10?z:"TEN",h-11?z:"ELEVEN",h?z:"TWELVE",m&4097?"O'CLOCK":z);} ``` ## Explanation The selection of the hour number should be obvious; for the other words, we make a 13-bit mask (0-12) of the minute hand's position, and use this to select which texts light up. ``` void clock(int hour, int min) { min = (min + 2) / 5; if (m > 6) ++hour; hour = hour % 12; min = 1 << min; printf("IT IS%5s %s\n" "%7s %s\n" "%4s%8s %s\n" "%4s%4s %s\n" "%3s%5s %s\n" "%3s%6s %s\n" "%4s%4s %s\n" "%6s %s", min & (1 << 6) ? "HALF" : "", min & ((1 << 2) | (1 << 10)) ? "TEN" : "", min & ((1 << 3) | (1 << 9)) ? "QUARTER" : "", min & ((1 << 4) | (1 << 5) | (1 << 7) | (1 << 8)) ? "TWENTY" : "", min & ((1 << 1) | (1 << 5) | (1 << 7) | (1 << 11)) ? "FIVE" : "", min & ((1 << 1) | (1 << 2) | (1 << 4) | (1 << 5) | (1 << 7) | (1 << 8) | (1 << 10) | (1 << 11)) ? "MINUTES" : "", min & ((1 << 7) | (1 << 8) | (1 << 9) | (1 << 10) | (1 << 11)) ? "TO" : "", min & ((1 << 1) | (1 << 2) | (1 << 3) | (1 << 4) | (1 << 5) | (1 << 6)) ? "PAST" : "", hour == 2 ? "TWO" : "", hour == 3 ? "THREE" : "", hour == 1 ? "ONE" : "", hour == 4 ? "FOUR" : "", hour == 5 ? "FIVE" : "", hour == 6 ? "SIX" : "", hour == 7 ? "SEVEN" : "", hour == 8 ? "EIGHT" : "", hour == 9 ? "NINE" : "", hour == 10 ? "TEN" : "", hour == 11 ? "ELEVEN" : "", hour == 0 ? "TWELVE" : "", min & ((1 << 0) | (1 << 12)) ? "O'CLOCK" : ""); } ``` ## Demo This is also available on [Try It Online](https://tio.run/##ZZFbj5pAGIbv/RVfpqEFwQrDwQOyxGzGStZCq7htE28M6kLKYVe02bjxt9uZAbpdlxve5@U7vMxEnYcoulyieL1vnxyE7EiMlUx6iWVHzGQHK1nXMaUby44FR8N25mijUWY/7pP8sBORF4K3EMwShHKVC736bZRC/1UatdTLf4VUWu8LuIWU7KNluGg6nk3Q8ERJU3HfRSHxKzSx6qLvy/E8JPPKMXRMv/8gfvirMjDWaM3EuycV6ybjr56/DMmitgYWGxrUK7Dlom/jRcgw7mD3NKQDA0S1zvV0TggjjVHgc20wPQmWcwYmB7aRgsVg4f1kusc1uafxKfUZEe/LNGQ0YOR71TgakW2q6jS@iMzqvioPmbHx9H/VQc9FwafbWXB7RxNL9vnyIcmj9LjZwqg8bJLic3zTojcEUVpEv0Wm4uK4V4CpLMml1ksL6EPvmtvMsrnTXOwqFwW8GQoq3kirvPPmWeVIgf8bzy2@LFsnufinSDbN@G4bts/r7DHdlrDbFxkc4i08HbflISlyaHerDDyiNlAAq3WI2tIV0Mx3ltl/axkK6FeNJrWuGlUF1KsqXFtN1JDmgnWa8pRp8hAfyiZjc4DggKZVQ3bFHsT6OKmt2sDVyAGr0bIDpgTVUbzuleXrMz@3zpe/). ``` #include <stdio.h> int clock(int hour, int min) { c(hour, min); printf("(%2d:%02d)\n---\n", hour, min); } int main(void) { /* examples from the question */ clock(19, 20); clock(13, 15); clock(13, 58); clock(14, 30); clock(15, 35); clock(10, 00); clock(12, 00); /* Test all the lights */ int hour = 11; for (int min = 0; min <= 60; min += 5) { clock(++hour, min); } } ``` ]
[Question] [ Say I have an expression: ``` 9 * 8 + 1 - 4 ``` This expression can be interpreted in six different ways, depending on operator precedence: ``` (((9 * 8) + 1) - 4) = 69 (* + -) ((9 * 8) + (1 - 4)) = 69 (* - +) ((9 * (8 + 1)) - 4) = 77 (+ * -) (9 * ((8 + 1) - 4)) = 45 (+ - *) ((9 * 8) + (1 - 4)) = 69 (- * +) (9 * (8 + (1 - 4))) = 45 (- + *) ``` Say I'm a developer, and I don't feel like memorizing precedence tables, etc., so I'm just going to guess. In this case, the largest margin of error would be 45-77, which is a difference of 32. This means that my guess will only be off by a maximum of 32. ## The challenge Given an expression consisting of numbers and `+`, `-`, `*`, `/` (integer division) and `%`, output the absolute difference of the largest and smallest possible value for that expression, based on the precedence of operators. ## Specifications * The input expression will not contain parenthesis and every operator is left-associative. * The input expression will only contain nonnegative integers. However, subexpressions may evaluate to negatives (e.g. `1 - 4`). * You can take the expression in any reasonable format. For example: + `"9 * 8 + 1 - 4"` + `"9*8+1-4"` + `[9, "*", 8, "+", 1, "-", 4]` + `[9, 8, 1, 4], ["*", "+", "-"]` * The input will contain at least 1 and at most 10 operators. * Any expression that contains a division or modulo by 0 should be ignored. * You can assume that modulo will not be given negative operands. ## Test Cases ``` 9 * 8 + 1 - 4 32 1 + 3 * 4 3 1 + 1 0 8 - 6 + 1 * 0 8 60 / 8 % 8 * 6 % 4 * 5 63 ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~171~~ 156 bytes ``` lambda a:max(e(a))-min(e(a)) u=')%s(' def e(a,t=u): try:b=[eval(a)] except:b=[] return sum([e('(%s)'%a.replace(o,t%o),u%t)for o in"+-*/%"if' '+o in a],b) ``` [Try it online!](https://tio.run/##ZYzNasMwEITvfoohIKT1TxOnaUgMfpI0BzmRqMGWjCyV5OmdTQsl0MOyO9/M7HSPX95tF9t@LoMeu6uGbkZ9U0Zpomrs3e@VpVaSmJXMrsaCURnbRE2GGO5N157Mtx44d85gbhczxSdjEUxMwWFOozoZJZWYSQr9Fsw06ItRvozCU5lEJOsDPHq3Kqp8LVa9lZDFE0Cfy46WKfQuwip5RI4DCtSosJOU/Rk1w3c2/8H6FRy4tv@p59i8GvsN1vxY8OScENjx/pC0PAA "Python 2 – Try It Online") ### How it works We surround each operator with a different number of outward-facing pairs of parentheses to simulate different precedences (in all possible ways), and wrap enough inward-facing pairs of parentheses around the entire string, to get an expression we can `eval`. For example, with `+` ↦ `)+(` `*` ↦ `))*((` `-` ↦ `)))-(((` we get `9 * 8 + 1 - 4` ↦ `(((9 ))*(( 8 )+( 1 )))-((( 4)))` = `77`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 126 bytes "Operator Precedence? Parentheses? Pah, who needs that?" - challenges of using Jelly for an operator precedence challenge. ``` ⁾[]i$€Ḥæ%3+\¬œp¹Ḋ€ ǵḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/ ǵVṾµ1ĿFḟØDḟ”-Lµ?ÐL 5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ “+_×:%”Œ!Ç€µṾL_L’ỊµÐfV€ṢIS ``` [Try it online!](https://tio.run/##y0rNyan8//9R477o2EyVR01rHu5YcniZqrF2zKE1RycXHNr5cEcXUJTrcPuhrQ93zD88w8Vf1fLQ1sMTHu5seLhz1cnJRyc/3Ln4UeNOnYc7Zx2emOVwaKk@WHHYw537Dm01PLLfDaINSD5qmKvrc2ir/eEJPlymD3dsq3AAmvyoYU4sEEcDJY/uedS4I0sfKKjjUHlos9vJyYc2Z4LUAO161DATqBysDqR@btbhdi4gUzv@8HQrVZDeSYqH24FKga7cuc8n3geo/uHuLpBD08LAJizyDP7//7@SRbyZtuHh6QZKAA "Jelly – Try It Online") Input is taken as a string, e.g. "1+2\_3×4:5%6". Note multiplication uses "×" instead of "\*", division uses ":" instead of "/", and subtraction uses "\_" instead of "-". **How it Works** The program is divided into three parts: generating all expressions of different operator precedence, evaluating them, and returning the difference between the maximum and minimum. All expressions are generated with the code: ``` 5Ḷx@€“]“[”ż⁸j/€,@y³Fɓ³i@€Ṁ’x@“[“]”jÇ (4) helper link: returns all outputs given a permutation. Input e.g. "_+:×%" 5Ḷx@€“]“[” - repeat outer brackets to get ["",""],["]","["],["]]","[["],["]]]","[[["],["]]]]","[[[["] ż⁸j/€ - insert the operations in to get "_","]+[","]]:[[","]]]×[[[","]]]]%[[[[" ,@ - turn this into a mapping equivalent to "_"↦"_","+"↦"]+[",":"↦"]]:[[","×"↦"]]]×[[[","%"↦"]]]]%[[[[" y³F - use this mapping to get the right number of outward brackets on each operation. e.g. "1]+[3]]]×[[[4" ɓ³i@€Ṁ’x@“[“]”j - add the right number of brackets to the end to get e.g."[[[1]+[3]]]×[[[4]]]" Ç - this calls the link which evaluates the expression “+_×:%”Œ!Ç€ (5a) main link. Input e.g. "1+3×4" “+_×:%” - the string "+_×:%" Œ! - all permutations Ç€ - apply link (4) to each permutation ``` The links are evaluated with this (I could probably improve with a different structure): ``` ⁾[]i$€Ḥæ%3+\¬œp¹Ḋ€ (1) Helper link: Outputs a list of expressions within brackets, e.g. "[[[1]+[3]]]×[[[4]]]"↦"[[1]+[3]]","[[4]]" ⁾[]i$€Ḥæ%3 - map "[" to 2, "]" to -2, and any other character to 0. +\¬ - cumulative sum negated: 1s at characters not in brackets (includes opening brackets), 0s otherwise (includes closing brackets) œp¹ - partition the input, not including borders, based on the sum to get "[[[1]+[3]]","[[[4]]" Ḋ€ - remove opening brackets ǵḟØDO%9µÐṀṪɓœṣ⁹,ṚÑj@¥/ (2) Return the input to this link with one of the expressions from (1) evaluated ǵVṾµ1ĿFḟØDḟ”-Lµ?ÐL (3) link called from part 1: Evaluates expressions µ µ µ? - if: 1ĿFḟØDḟ”-L - the input contains no operators within brackets: VṾ - evaluate this one expression with normal Jelly calculation and return to string - otherwise: Ç - evaluate one subexpression using link (2) ÐL - repeat this until a single output is determined ``` The difference between the maximum and minimum is computed with the code in link (5): ``` µṾL_L’ỊµÐfV€ṢIS (5b) determine difference between minimum and maximum µ µÐf - filter out outputs involving division or modulo by 0. Determined with: ṾL_L’Ị - actual numbers have their unevaled form Ṿ no more than one byte longer than the non-unevaled form. V€ - evaluate each of these valid numbers to get integers from strings Ṣ - sort IS - return the sum of all difference between consecutive elements. ``` [Answer] # [Python 2](https://docs.python.org/2/), 235 234 233 226 bytes -1 byte (and a fix) thanks to [Anders Kaseorg](https://codegolf.stackexchange.com/users/39242/anders-kaseorg)! -7 bytes thanks to [Step Hen](https://codegolf.stackexchange.com/users/65836/step-hen)! ``` from itertools import* def f(e,a=()): for o in permutations("+-*/%"): l=e[:] for c in o: for i in range(len(l),0,-1): if l[i-1]==c:l[i-2:i+1]=["("+l[i-2]+l[i-1]+l[i]+")"] try:a+=eval(*l), except:0 print max(a)-min(a) ``` [Try it online!](https://tio.run/##PVDRboMwDHyGr7CQECGBFdqu6iLxJYiHiCVbppBEIZ3o1zOHSnuI7Dvf2Y79M347e953FdwCOsoQnTMr6MW7EGn@KRUoIhsxkLrmOSgXwIG24GVYHlFE7exKCtbSU1mgIDODHPmUZ0k4J6FD8rDphIKwX5IYaYmpm65p@@TJtAIz6rafhmHmKTtzzRCNBbY@8MReghQmVtQFjojhyQUb5K8whGK7PJPbLH3kXQ4@aBthERsRdbtoi2FPS8jNpzXG6gMo3IFBDy1cqwaqHsEFyX/Qp@SO5dsho9Al4tbBCY0lPoqVEq4Y36sJv/GaiRPezM9jjeTSpZ3wesis3uiIJ9z/AA "Python 2 – Try It Online") [Answer] # Haskell 582 bytes This didn't go nearly as well as I hoped it would... ``` import Data.List f x=case x of '+'->(+);'-'->(-);'*'->(*);'/'->div;_->rem e _ s[]=s e 1 s(')':x:a)|0<-(read$e 0""a),(x=='%'||x=='/')=""|""<-(e 0""s)=""|""<-(e 0""a)=""|0<3=show$(f x)(read$e 0""s)$read$e 0""a e 1 s")"=e 0""s e n s(')':a)=e(n-1)(s++")")a e 0 s('(':a)=e 1 s a e n s('(':a)=e(n+1)(s++"(")a e n s(x:a)=e n(s++[x])a n?s=take n$cycle s a!b=e 0""(9?"("++(concat$zipWith(++)a(b++[[]]))++9?")") c#b|l<-[read x|x<-map(c!)(a b),x/=""]=maximum l-minimum l a c=transpose$map(\x->map((\(Just q)->q).lookup x)$map(\a->zipWith(\x y->(y,x?")"++y:x?"("))[1..5]a)$permutations"+-*%/")c ``` [Try It Online!](https://tio.run/##dVFNb@IwEL3nV0zdoHhiDEH9UEsJvexptfc9hKgaQioi8tXY7JpV/ju1CUjVikYa@Xnee@NnZ0tql5fl8VhUbdNp@EGaJr8Kpb13MHFGKgcDzTsEIpBLLvAlkA5IC0IHQgumFmyKPy9vctnllZfDG6gkjZVFM1A8wGBu5oR9tJC8y2nj5xAxRjjmJo6DUdD3bp0GGDPWM2ZVJ4H6b0@nfbS4i9W2@etzGxC/zFPofxk@nM2QxQNp9/U5i52T81rOkCshrAKdOHIkH0jnBLo4@MUhzg4@OBxpBn3t@olJbb9@VbGmne352SErc1Ae3ayHEPz51ZqF4FlTZ6T9f0X7u9BbLgQSX9sJSZoiCmFlNpWX3a77ciETdyswvVnIilqe3SAnWOPYTO1zpHFFpqj2FZSyKuoBeQRZrDuqVduo3HeulZFLt/IV/7lXGj5QLj9wUjbNbt/adxxEJJeXTCsDB/t7D2PjwghxmBsXHjGZTSYPKaHf5l2116SLplZMyHA0ZZgdKypqiGHTeGC/titqDT7wW4SEPbMxe7I1s3XPUmChkOyKzvF3F40Iv5PMTvQ11h3yeD4ocip5fcpjdE50MdzbenCG6Sgchez4CQ) Trying to golf a long program just makes me write bad code :( I tried to use Anders' algorithm in Haskell, but it got out of my control The function e is like a specific case of eval. (#) takes a list of strings representing integers and a string of operators and returns the difference between the maximum and minimum possible values. e.g ``` (#) ["9","8","1","4"] "*+-" => 32 ``` [Answer] # [Haskell](https://www.haskell.org/), 254 bytes ``` import Data.List.Split import Data.List f s=(-)<$>maximum<*>minimum$permutations(zip"+-*/%"[p(+),p(-),p(*),c$div,c$mod])>>=(s!) p=((pure.).) c o a b=[o a b|b/=0] s![]=[read s] s!((x,o):y)=case splitOn[x]s>>=(!y)of[]->[];l->l?o [a]?_=[a] (a:b)?o=b?o>>=o a ``` [Try it online!](https://tio.run/##XU7LTsMwELznK6ZRK9lpkraiVCXUyYULEogDR2NVTpsKi/ihOEUt4t@Dw4EDh53dmZ19vEv/0bTtMCjtbNfjQfYyf1K@z19dq/rovxyd4BnJ6G5aanlR@qx3SamVGaupazp97mWvrPHkS7l4niWLWcwdmdPUhakACU0P06P6DKjtUdCyZMRPaOQYIe7cNTnNaXSAhUTN@G/6rhdsKSI/4YLxrpFH@JERckktLa6UHaRv4Md/Xwy/CD/unFypPXGRlVzct1nZVjbiUlR7FjAisqhpZVld2eANRwYtlQGDlu55D/JmkJVwnTI9iElxgkFR4NH0lIIjvkOCLeZYIcM6ThGvArkJ4h9ZjcU2tDe/tgTLUdgssQiDsxBJ6MywDvk2hhh@AA "Haskell – Try It Online") Input is a whole string, such as 4+5 \* 2. It generates all permutations of operations, and for each permutation splits the string recursively. It filters divisions by 0 with the list monad. [Answer] # Pyth, 45 bytes ``` KS.nm.x.vj\ u.nm+*H/kHckHGd]s.iFQY.p_{eQ-eKhK ``` I'm sure that a lot more optimization can be done, but I like it so far. Takes input like this: `[9, 8, 1, 4], ["*", "+", "-"]`. [Try it online!](https://pyth.herokuapp.com/?code=KS.nm.x.vj%5C+u.nm%2B%2aH%2FkHckHGd%5Ds.iFQY.p_%7BeQ-eKhK&input=%5B2%2C+3%2C+10%2C+5%5D%2C+%5B%22%2a%22%2C+%22%2a%22%2C+%22-%22%5D&test_suite=1&test_suite_input=%5B9%2C+8%2C+1%2C+4%5D%2C+%5B%22%2a%22%2C+%22%2B%22%2C+%22-%22%5D%0A%5B1%2C+3%2C+4%5D%2C+%5B%22%2B%22%2C+%22%2a%22%5D%0A%5B1%2C+1%5D%2C+%5B%22%2B%22%5D%0A%5B8%2C+6%2C+1%2C+0%5D%2C+%5B%22-%22%2C+%22%2B%22%2C+%22%2a%22%5D%0A%5B60%2C+8%2C+8%2C+6%2C+4%2C+5%5D%2C+%5B%22%2F%22%2C+%22%25%22%2C+%22%2a%22%2C+%22%25%22%2C+%22%2a%22%5D&debug=0) [Answer] # Mathematica, ~~186~~ ~~164~~ 159 bytes ``` eMax@#-Min@#&[Fold[#//.{m___,x_,#2[[0]],y_,n___}:>{m,x~Last@#2~y,n}&,e,#]&/@Permutations@{"+"@Plus,"-"[#-#2&],"*"@Times,"/"@Quotient,"%"@Mod}/. 0/0|1/0->{}] ``` `\[Function]` takes 3 bytes. Some alternatives (keeps bytecount the same) `#2-#&@MinMax[...]` to replace `Max@#-Min@#&[...]` `Head@#2` to replace `#2[[0]]` Try it online at <http://sandbox.open.wolframcloud.com> : enter `( .... )[{60, "/", 8, "%", 8, "*", 6, "%", 4, "*", 5}]` with `....` replaced by code above for test case `60 / 8 % 8 * 6 % 4 * 5`. Press `Shift + enter` to evaluate. [Answer] # Javascript, 280 bytes **Note**: The integer division rounds using the floor function, which means that negative numbers round away from zero. This solution is based on [this answer](https://codegolf.stackexchange.com/a/131574/70894). ``` b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r[0]?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b))) ``` Example code snippet: ``` g= b=>(Math.max(...(f=(a,h="(",i=")",r=[...a[d="replace"](/[^-+*/%]|(.)(?=.*\1)/g,"")])=>(r[0]?(r.map((c,j)=>s=s.concat(f(h+a[d](RegExp("\\"+(n=r.concat()).splice(j,1),"g"),i+c+h)+i,h+"(",i+")",n)),s=[]),s):(a=eval(`(${a})`[d](/\(/g,"Math.floor(")))==a&&1/a?a:r))(b))-Math.min(...f(b))) for(k=0;k<5;k++) v=["9*8+1-4","1+3*4","1+1","8-6+1*0","60/8%8*6%4*5"][k], console.log(`g(${v}) = ${g(v)}`) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~262~~ ~~256~~ 254 bytes ``` from itertools import* def r(s,o): try: while o in s:i=s.index(o)-1;s[i:i+3]=[`eval(''.join(s[i:i+3]))`] return s except:0 def f(s): u=[int(v[0])for v in [reduce(r,O,s.split(' '))for O in permutations('*/%+-')]if v!=None];return abs(max(u)-min(u)) ``` [Try it online!](https://tio.run/##ZU5BboMwEDyXV2wPyDaBBJo0SonopffmAQgpNFkUV2Ajr6Hk9dSgtkrUw@5KM7Mz017tRauncayMbkBaNFbrmkA2rTY28M5YgeEUapF6YM3Vbfi6yBpBg1RAqcxoKdUZB65FlOwpl6lcrIssP2Jf1pyx5aeWiv/iQhwLZ2HQdsa9e4DDCVubxnNSxWnK6bJcKsv7PC5EpQ30U1Ru8NydkJvwENKS2lpazoCJWXGYFC2aprOllVoRZ8HKX0RMFLKC/jF71wqL/U9s@UG8KQfeiahx3TohxindItm3knAu8dAa1wEoZNkrC6dinvcnYC8QwA4WkEAEGyZumMSha8f@R5M7ZOc@t7NDAPEds41h5cx9N4GT@LBx95mJ8Rs "Python 2 – Try It Online") [Answer] # [PHP](https://php.net/), 316 bytes ``` <?for(;$t++<54322;)count_chars($t,3)!=12345?:$p[]=$t;foreach($p as$x){for(list($z,$q)=$_GET,$b=1,$i=0;$y=strtr($x,12345,"/%*+-")[$i++];)while(-1<$k=array_flip($q)[$y]){$n=$k+1;if($b&=$z[$n]||ord($y)%10<6)eval("\$z[$k]=$z[$k]$y$z[$n]^0;");($s=array_splice)($z,$n,1);$s($q,$k,1);}$b?$r[]=$z[0]:0;}echo max($r)-min($r); ``` [Try it online!](https://tio.run/##PZBNT8MwDIbv@xUjeChZM9HuS2hptAOaEBe47BZC1ZWORu3aLA2w7oO/Ptpu4vDqtWX7kW2d6LM/14nuxMYUJjCxLoxV@Sf@XQQvr8vnxwVhHQieFksuBJq6iKKHq6a1xrUmSFKB7uuoV6v/71Ky87owmIF1HH8yHg2HjETFV26DKAlNicHSEbnh3nA0nsxnoIXkYFk9EodRgkF3wxJ25NAwMlVaDHsKW8LbbSisuEdBcZdBxUtrrMGwoy2Lovte3xkgIkA5jmTkJ1FZjAeeDykPjQmrYJ0pjWuYgEqSA@QcUsdjao1hdcdhLyCXx2NhPjBUpOe5/pTE32GG0VtTSyW/GFSX1neXIcIwlFd6qTMVxaRdOKceYVAfu6WQNvEJVnMwomW4cuayUxwlRXcT7jAYMtiovHF2vtVG1a8yl@wP "PHP – Try It Online") ``` Expanded for(;$t++<54322;) count_chars($t,3)!=12345?:$p[]=$t; foreach($p as$x){ for(list($z,$q)=$_GET,$b=1,$i=0;$y=strtr($x,12345,"/%*+-")[$i++];) while(-1<$k=array_flip($q)[$y]){ $n=$k+1; if($b&=$z[$n]||ord($y)%10<6) eval("\$z[$k]=$z[$k]$y$z[$n]^0;"); ($s=array_splice)($z,$n,1); $s($q,$k,1); } $b?$r[]=$z[0]:0; } echo max($r)-min($r); ``` [Answer] # JavaScript (ES6), 210 bytes Input as an array of numbers and operators ``` k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n ``` *Less golfed* ``` k=>( m = n = NaN, r =(o, k, j=0) => { // try all operators in o for(;q = o[j]; j++) { // q : current operator, // look for q inside the expression to evaluate for(h = [...k], z = 1; i = h.indexOf(q) + 1;) { a = h[i - 2] b = h[i] z *= b // trace if any second operand is zero // subst subexpression with its value h.splice(i - 2, 3, eval(a + q + b) | 0) } // now all subexp involving current operator are evaluated // the result is ok if current operator is not % or / // OR if no second operand was zero (q > '%' & q < '/' || z) && // try again recursively // using the remaining operators and the remaining expression r(o.slice(0, j) + o.slice(j+1), h) } // if no more operators to try, check max and min // k is an array with 1 element, can be used like a single number o || ( m = m > k ? m : k, n = n < k ? n : k ) }, r('+-*/%', k), m-n ) ``` **Test** ``` var F= k=>(m=n=-k,r=(o,k,j=0)=>{for(o||(m=m>k?m:k,n=n<k?n:k);q=o[j++];(q>'%'&q<'/'||z)&&r(o.slice(0,j-1)+o.slice(j),h))for(h=[...k],z=1;i=h.indexOf(q)+1;h.splice(i-2,3,eval(a=h[i-2]+q+h[i])|0))z*=h[i]})('+-*/%',k)|m-n function update() { var input = I.value.match(/\d+|\S/g) var result = F(input) O.textContent = I.value + ' -> ' + result + ' (max:'+m+' min:'+n+')' } update() ``` ``` <input id=I value="60 / 8 % 8 * 6 % 4 * 5" oninput='update()'> <pre id=O></pre> ``` [Answer] # [Python 3](https://docs.python.org/3/), 284 bytes Edit: seems like something's wrong with evaluating the last example. I'll look into it tomorrow. Another Python answer. Couldn't outgolf everyone else, but I spent too long on this to not put it up. ``` from itertools import* def f(n,o): z=[] for p in permutations("+-*/%"): try: p,x,a=[*p],n[:],o[:] while(p): for i,d in enumerate(a): if d==p[0]:x[i+1]=str(eval(x[i]+d+x[i+1]));x.pop(i);a.pop(i) p.pop(0) z+=x except:0 z=[*map(float,z)];return max(z)-min(z) ``` [Try it online!](https://tio.run/##bY/bioMwEIbvfYpBKIkat5buStfik4RchDWhAXMgTXetL@/G1LIU9mL@OX0zmbh7uFhzXBbprQYVhA/WjldQ2lkfymwQEiQ2xBZdBnNPWQbSenCgDDjh9S3woKy54ryqy/0uXzEI/r46cGQivKelY8TQjhEbZa3/XNQosEsspH2KDOtGYW5aeB4E5lsTlISh7x1tWDdRVR1Yfw0ei28@4pizaqge5aI4T2/OOqyKM9@CtMGlpEnJXPVT9GL6Ei50TfpRqbnDcrQ8kLlgZy/CzRvQfMJzUWtlolucVyZgiSn6RATQaZXDKu@IEaB5mRPIq1XqPF6S/fGRQsdoG5iY8h/m8Oy/tuJLqE1tgpqEoDqGVbQSvaJtE4unzdrHcVE@HlP7WNylqaeP08sv "Python 3 – Try It Online") [Answer] # [Clojure](https://clojure.org/) (+ combinatorics), ~~342~~ 377 + 41 = 418 bytes *+35 bytes because of a bug.* ``` (fn[x y](let[l filter s first z #(l(fn[y]y)%)r(sort(z(for[e(q/permutations[+ - * quot mod])](try(loop[t e m y a x](if(=[]t)(s a)(let[j(s t)i(reverse(keep-indexed #(if(= j %2)%)m))](recur(rest t)(l #(not= j %)m)(loop[d 0 h a](if(=(count i)d)h(let[c(nth i d)f(inc c)](recur(inc d)(vec(z(assoc h c(j(nth h c)(nth h f))f nil)))))))))))(catch Exception _ nil)))))](-(last r)(s r)))) ``` [Try it online!](https://tio.run/##RVDRasMwDPwVwSiTNlrGHgt73FcEMzxHJs4cO5WVkvTnMycdnR/MWTrdnexi7ifhFYUvUxCG58bdS6fBandyefgOyWqW4AqchT0LnG2Mhlb0qZlhMRhZmwg@RK3NUoEUhRs8Ydwoi1noQIIli@INfZaGcWQZJrUacirNKxzhBS5TVhhya8igyoIx57FRYBhgAQuzweDxozFKWMDS7tpXqBRq@itLYfxhHo8htTxzW/23Aejh8F4DDFR1hd0k9a75qkyslJR1p9T@3bGFN@jA3t3Q5SkpBGqp2w0dJu0gQEseQ3LgHqLbqyW8sqtL2lKyqzIO@32gIvoDnshDCpH@DzqrroPP2fG4/Qh8PQgGjxhtjSvb1rKV1vUX "Try it online") For this function to work, you have to `use` the `clojure.math.combinatorics` library (41 bytes): ``` (use '[clojure.math.combinatorics :as q]) ``` ## Nuances: This function is an anonymous function, which means you must do this to use it: ``` ((fn[x y]...) numbers operators) ``` Also, I'm using the word `quot` instead of `/` (since Clojure does fraction division by default), and `mod` instead of `%`. ## Ungolfed program: ``` (defn precedence [numbers operators] (let [results (sort (for [permute (c/permutations [+ - * / mod])] (loop [p-temp permute o-temp operators n-temp numbers] (if (empty? o-temp) (first n-temp) (let [first-p (first p-temp) indices (reverse (keep-indexed #(when (= first-p %2) %) o-temp))] (recur (rest p-temp) (filter #(not= first-p %) o-temp) (loop [ind 0 n-through n-temp] (if (= ind (count indices)) n-through (let [current-ind (nth indices ind)] (recur (inc ind) (vec (filter #(not (nil? %)) (assoc n-through current-ind (first-p (nth n-through current-ind) (nth n-through (inc current-ind))) (inc current-ind) nil)))))))))))))] (- (last results) (first results)))) ``` ]
[Question] [ Remember the kids game, ['Duck, Duck, Goose'](https://en.wikipedia.org/wiki/Duck,_duck,_goose)? No? Me neither. ### The challenge * Print the word 'duck' on individual lines an indeterminate amount of times. * Print the word 'goose'. * Your program ends. ### The rules * Attempt to play the game in the fewest bytes. * There must be at least one duck. * There must be exactly one goose, at the end of the list. * There must be exactly one bird on each line. No empty lines. * The case of the outputted strings is irrelevant. * White-space within a line is fine. * Your program must finish. * Your program must not consistently produce the same number of ducks. Have fun! --- Please note: This question is not a duplicate of [Shortest code to produce non-deterministic output](https://codegolf.stackexchange.com/questions/101638/shortest-code-to-produce-non-deterministic-output) Reasons include: * The association to a childrens' game * The defined start and end requirements of the result string. There is no specified output in the other challenge. * Answers For the other, non-duplicate challenge are in a single-digit number of bytes. The average for this one is around 30, or there about. * By the amount of overlap between this challenge and that one, any code-golf question including the 'random' tag is a duplicate. Should we delete them all? * The code answers for this challenge would match the other challenge (in a ridiculously bloated way), but the answers to that challenge would not match this one. [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 48 bytes ``` f={s="duck\n";s+([s,""]select random 1)+"goose"} ``` Always prints either one or two ducks. `random 1` returns a (floating point) number between 0 and 1. That number is passed as an argument to `select` along with the array `[s,""]`. The random number is then rounded to the nearest integer (either 0 or 1), and the array element at that index is selected from the array. **Call with:** ``` hint call f ``` **Output:** [![](https://i.stack.imgur.com/54VWS.png)](https://i.stack.imgur.com/54VWS.png) **Alternative 56 bytes version:** ``` f={s="duck\n";format[s+"%1goose",[s,""]select random 1]} ``` [Answer] ## World of Warcraft 81 Bytes Here's a macro that you can run in World of Warcraft. ``` /run for x=1,random(1,9) do SendChatMessage("Duck") end; SendChatMessage("Goose") ``` [Answer] # Minecraft <1.13, ~~72~~ 54 bytes Sorry, I had to. ## Instructions: * Create a new Minecraft world in Creative Mode * Find the save folder for that world, and place the following code in `data/functions/minecraft/ddg.mcfunction` * Run `/function ddg` in the game console ## How it works: Outputs the word "duck" for every entity in the world, then outputs the word "goose". Since entities are constantly spawning and despawning, the number of "duck"s will not be consistent. I used `tellraw` instead of the much shorter `say` because `say` outputs the name of the entity, while `tellraw` outputs exactly what it is told. ``` execute @e ~ ~ ~ tellraw @a "duck" tellraw @a "goose" ``` ## Screenshot [![enter image description here](https://i.stack.imgur.com/pVU4g.png)](https://i.stack.imgur.com/pVU4g.png) Edit: Changed {"text":"duck"} to just "duck" (and the same with "goose") [Answer] # JavaScript, ~~45~~ ~~44~~ ~~42~~ ~~39~~ 37 bytes Has the potential to produce an overflow error. ``` f=_=>`duck ${new Date%2?f():`goose`}` ``` --- ## Test it ``` o.innerText=( f=_=>`duck ${new Date%2?f():`goose`}` )() ``` ``` <pre id=o></pre> ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~38~~ 33 bytes This is not the shortest (it's 36 bytes), but it's my favorite. The explanation is in the bottom. ``` disp(['duck '+~(1:1/rand)';'goose']) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/JbO4QCNaPaU0OVtBXbtOw9DKUL8oMS9FU91aPT0/vzhVPVbz/38A "Octave – Try It Online") --- Some shorter variations: This works in principle (33 bytes), but the online interpreters times out: ``` disp(['duck '+~(1:now)';'goose']) ``` Adding some bytes to make the output shorter makes it 35 or 36 bytes: ``` disp(['duck '+~(7e5:now)';'goose']) % Works on octave-online.net disp(['duck '+~(7.3e5:now)';'goose']) % Works on tio.run ``` ### Explanation: I'll just explain the last random one. The others are similar, but uses the number of days since **January 1st, 0000** until today. `rand` returns a random number on the interval **(0, 1)**. Thus, `1/rand` returns a number larger than **1**. Since a range `1:f`, where `f` is a random float larger than **1** is identical to `1:floor(f)`, `1:1/rand` creates a range **1 .. x**, where **x >= 1**. I'll try to explain this as if Octave was a stack based language. ``` 'duck ' % Push the string 'duck ' to the stack (1:1/rand) % Push a vector 1... floor(1/rand) ~(1:1/rand)' % Negate the vector (making it all zeros) % and transpose it. + % Add 'duck ' with the vertical vector of zeros % to implicitly duplicate the string r times [ ;'goose'] % Push the string 'goose' and concatenate % vertically with the rest disp( ) % Display it all. ``` [Answer] # Z Shell (+ wget & Netpbm), ~~168~~ ~~160~~ ~~150~~ ~~148~~ ~~145~~ ~~135~~ 120 bytes ``` d(){wget -O- bit.ly/$1|jpegtopnm|pamscale -w 64 -h 64};d DckDkGo|pnmtile 64 $[(RANDOM&7+1)*64]|pnmcat -tb - <(d g005eGG) ``` Not the shortest solution, but I felt like giving a twist of sorts to this challenge (inspired by [@AlexG's solution to this other problem](https://codegolf.stackexchange.com/a/159718/79247)). This script generates a PPM image containing between 1-8 pictures of ducks and a picture of a goose at the bottom on standard output. It downloads the two source pictures from Wikipedia, so internet access is necessary for it to work. Sample output converted to JPEG through *pnmtojpeg*: [![enter image description here](https://i.stack.imgur.com/MvNnS.jpg)](https://i.stack.imgur.com/MvNnS.jpg) [Answer] # [Python 2](https://docs.python.org/2/), 36 34 bytes ``` print"duck\n"*((id(id)%5)+1),"goose" ``` [Try It Online!](https://tio.run/##K6gsycjPM/r/v6AoM69EKaU0OTsmT0lLQyMzBYg0VU01tQ01dZTS8/OLU5X@/wcA) Suggestion by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) gets us to 34 bytes: ``` print"duck\n"*-~(id(id)%5),"goose" ``` [Answer] # [Perl 5](https://www.perl.org/), 20 bytes First a practical 26 bytes: Ducks 1 to 9 times before being goosed. ``` say"Duck "x(1+$^T%9),Goose ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLJpTQ5m0upQsNQWyUuRNVSU8c9P7849f//f/kFJZn5ecX/dX1N9QwN9AwA "Perl 5 – Try It Online") But if you have lots of memory and time this 20 byte version (as suggested by [Chris](https://codegolf.stackexchange.com/users/58834/chris)) works too: ``` say"Duck "x$^T,Goose ``` This also assumes the [Year 2038 Problem](https://en.wikipedia.org/wiki/Year_2038_problem) will be solved for [Perl 5](https://www.perl.org/), otherwise it will be invalid for 1 second 20 years hence. [Answer] # [Bash](https://www.gnu.org/software/bash/), 39 38 37 bytes ``` sed s/[0-9]/duck\\n/g<<<$RANDOM\goose ``` [Try it online!](https://tio.run/##S0oszvj/vzg1RaFYP9pA1zJWP6U0OTsmJk8/3cbGRiXI0c/F3zcmPT@/OPX/fwA "Bash – Try It Online") Prints a number of ducks equal to the number of digits in an integer uniformly distributed on [0,32767] (so, more often than not, five ducks (a good number of ducks)). -1 byte each thanks to @Chris and @sch pointing out pairs of quotes that weren't pulling their weight. [Answer] # [R](https://www.r-project.org/), 35 bytes ``` cat(rep("duck ",rexp(1)+1),"goose") ``` [Try it online!](https://tio.run/##K/r/PzmxRKMotUBDKaU0OZtLSacotaJAw1BT21BTRyk9P784VUnz/38A "R – Try It Online") `rexp()` produces a random number from an exponential decay function. `+1` to ensure at least one duck. All lines after the first include a leading space (which is the default separator for `cat`) but this is allowed. [Answer] # Pure Bash (no external utilities), 25 Based on [@SophiaLechner's answer](https://codegolf.stackexchange.com/a/157940/11259), this also prints *a good number of ducks*. @OlivierDulac's idea to use the script shell PID as stored in the `$` parameter saves 5 bytes. ``` echo "${$//?/duck }"goose ``` [Try it online](https://tio.run/##S0oszvj/PzU5I19BSaVaRV/fXj@lNDmbq1YpPT@/OPX/fwA). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` 2X“¢;ÆS»ẋ“ʋ¢» ``` [Try it online!](https://tio.run/##y0rNyan8/98o4lHDnEOLrA@3BR/a/XBXN5B3qvvQokO7//8HAA "Jelly – Try It Online") Explanation: ``` 2X“¢;ÆS»ẋ“ʋ¢» 2X Random number (1 or 2) “¢;ÆS» Compressed string equivalent to "duck\n" ẋ Repeat the "duck\n" that random number of times “ʋ¢» Compresses string equivalent to "goose" Implicitly concatenated and returned ``` --- More readable version: [Try it online!](https://tio.run/##y0rNyan8/98oQuFRw5yU0uTsQ9seNcx9uKsbxE/Pzy9OBXL//wcA "Jelly – Try It Online") Will always return 1 or 2 ducks. [Answer] # [Ruby](https://www.ruby-lang.org/), 30 bytes ``` puts"duck "*rand(1..9)+"goose" ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFgppTQ5m0tJqygxL0XDUE/PUlNbKT0/vzhV6f9/AA "Ruby – Try It Online") Note: really 31 bytes without the `\n` cheat. [Answer] # Bash + Coreutils, ~~36~~ 27 bytes ``` yes duck|sed $$q;echo goose ``` Prints too many ducks (between 2 and `cat /proc/sys/kernel/pid_max`), then one goose. Saved nine bytes thanks to Digital Trauma and Olivier Dulac. [Try it online!](https://tio.run/##S0oszvj/vzK1WCGlNDm7pjg1RUFFpdA6NTkjXyE9P7849f9/AA) (but keep in mind that it may get truncated occasionally) Same length, but with no `echo`: ``` yes duck|sed $${agoose' q}' ``` [Try it online!](https://tio.run/##S0oszvj/vzK1WCGlNDm7pjg1RUFFpToxPT@/OFWdq7BW/f9/AA) `a` is the append command in `sed`, and `q` quits. Both only run on the line `$$`, which corresponds to the PID. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ ~~30~~ 28 bytes ``` ,"duck"*((Random)+1) "goose" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0cppTQ5W0lLQyMoMS8lP1dBNzdRwVRT21CTSyk9P784Ven/fwA "PowerShell – Try It Online") (modified version) Generates an array of [`Get-Random`](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-random?view=powershell-6) number of items. It might take a while. This adds a `+1` to ensure we get at least one `duck`. The modified version also includes a `-ma`ximum flag of `5` so you can see the program works as expected (the modified version will print 1, 2, 3, or 4 `duck`s before the `goose`). The array and the solitary `goose` string is left on the pipeline, and the implicit `Write-Output` gives us newline-separated values for free. You don't know how difficult it was for me to not change the last line to ["gray duck"](https://en.wikipedia.org/wiki/Duck,_duck,_goose#Duck,_Duck,_Gray_Duck) ... [Answer] # [Python 2](https://docs.python.org/2/), 54 bytes ``` from random import* print"duck\n"*randint(1,9)+"goose" ``` **[Try It Online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVKKWUJmfH5ClpgSSBfA1DHUtNbaX0/PziVKX//wE "Python 2 - Try It Online!")** [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 55 bytes ``` Write("{"+new Random().Next(2)+"}{0}goose","duck\n","") ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/vCizJFVDqVpJOy@1XCEoMS8lP1dDU88vtaJEw0hTW6m22qA2PT@/OFVJRymlNDk7Jg/IUNL8/x8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~24~~ 21 bytes -3 bytes thanks to Erik the Outgolfer ``` "duck"ẉ4ṙ0∧"goose"w∨↰ ``` [Try it online!](https://tio.run/##AS0A0v9icmFjaHlsb2cy//8iZHVjayLhuok04bmZMOKIpyJnb29zZSJ34oio4oaw//8 "Brachylog – Try It Online") In celebration of the [Language of the month](https://codegolf.meta.stackexchange.com/questions/14917/language-of-the-month-for-march-2018-brachylog), my first brachylog post. The control flow in this language is cool. How it works: ``` "duck"ẉ4ṙ0∧"goose"w∨↰ "duck"ẉ print duck with a new line 4ṙ choose a random number in the range is [0, 4] 0 verify it equals zero ∧ and (short circuits) "goose"w print goose without a newline ∨ or (if it did not equal zero) ↰ repeat the procedure ``` [Answer] ## [Geometry Dash World 2.2 Editor](https://www.google.com/search?q=gdw+2.2+editor&rlz=1C1CHBF_enUS698US698&oq=gdw+2.2+editor&aqs=chrome..69i57j0l2.6191j0j7&sourceid=chrome&ie=UTF-8) - 4 objects [![Picture of Geometry Dash Level](https://i.stack.imgur.com/nnyrf.png)](https://i.stack.imgur.com/nnyrf.png) **Explanation:** The BG trigger is the current 2.2's random trigger, so it either toggles the Group ID 1 or 2. The first "DUCK" has a group id of 1, which makes it have a 50% chance of being removed or not (toggled). There is no object with the Group ID 2 in this level, so there is a 50% chance of 2 "DUCK"s being displayed. **How to Reproduce this:** The first "DUCK" has a Group ID of 1. [![enter image description here](https://i.stack.imgur.com/wp9TZ.png)](https://i.stack.imgur.com/wp9TZ.png) Goose and 2nd duck don't have a Group ID [![enter image description here](https://i.stack.imgur.com/oh88O.png)](https://i.stack.imgur.com/oh88O.png) Inside the random trigger. [![enter image description here](https://i.stack.imgur.com/NnCnU.png)](https://i.stack.imgur.com/NnCnU.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes ``` 'Ðœ₁Ωи`.•zíΘ•» ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f/fCEo5MfNTWeW3lhR4Leo4ZFVYfXnpsBpA/t/v8fAA "05AB1E – Try It Online") Will print 2, 5 or 6 ducks and then goose. -1 byte thanks to @Emigna using ' for a single compressed word (duck) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 22 bytes *1 byte saved thanks to @EriktheOutgolfer* ``` 'Goose'⍪⍨(?9)5⍴'Duck ' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///X909P784Vf1R76pHvSs07C01TR/1blF3KU3OVlDHLwsA "APL (Dyalog Unicode) – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 17 bytes ``` ?\\K`duck K`goose ``` [Try it online!](https://tio.run/##K0otycxLNPz/3z4mxjshpTQ5m8s7IT0/vzj1/38A "Retina – Try It Online") [Try it online!](https://tio.run/##K0otycxLNPz/P8Y7IaU0OZvLXjvGPYHLOyE9P7849f9/AA "Retina – Try It Online") Prints 1 or 2 ducks, with equal probability. ### Explanation ``` ?\\K`duck ``` Set the working string to `duck` and print it with a trailing linefeed (`\`). Then this is wrapped in another output stage, but this one has the random flag (`?`) applied to it, so it only prints with a probability of 50%. ``` K`goose ``` Replace the `duck` with `goose`, which is printed implicitly at the end of the program. Here's a fun alternative which prints 1 duck with 50% probability, 2 ducks with 25%, 3 ducks with 12.5%...: ``` \K`duck ?+\G` K`goose ``` [Answer] # Vim (script) on Linux, ~~46~~ 43 bytes (~~49~~ 46 with `:` at start of line) ``` .!date +0\%N\%s6 s/6.*/goose s/\d/duck\r/g ``` Executed as `vim -S filename` or pasted into running `vim` with `:` before each line. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~31~~ 22 bytes ``` "duck"a>x r"esoog"<>o< ``` [Try it online!](https://tio.run/##S8sszvj/XymlNDlbKdGugqtIKbU4Pz9dycYu3@b/fwA "><> – Try It Online") -9 bytes based on Not a tree's revision [Answer] # [Befunge 98](http://www.quirkster.com/iano/js/befunge.html), ~~38~~ ~~30~~ 25 bytes ``` "esooG"v>:#,_@ "Duck"a<?< ``` [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XSi3Oz3dXKrOzUtaJd@BScilNzlZKtLG3@f8fAA "Befunge-98 (PyFunge) – Try It Online") * Thanks @JoKing for stripping the useless trampoline * Switching to Befunge 98 for shorter new line - now `Duck` fits within a single string [Answer] # [T-SQL](https://docs.microsoft.com/en-us/sql/t-sql/language-reference), ~~70 44~~ 43 bytes (Many ducks) ``` while rand()<.9print'duck'print'duck goose' ``` Thanks @Zac Faragher! ## Revised Version, ~~54 43~~ 40 bytes (1 or 2 ducks) Thanks @BradC! ``` if rand()<.5print'duck'print'duck goose' ``` I can't seem to get this to run properly in [SQL Fiddle](http://sqlfiddle.com/#!18/15ff7/4), but it works just fine in LINQPad and SSMS. Not sure if this is a known limitation of SQL Fiddle or I'm just doing something wrong [Answer] # Powershell - ~~31~~ 30 bytes **Warning**: You're most likely going to end up with a lot of ducks. `Random` includes the values of 0 to `Int32.MaxValue` so, depending on how random you're number is, this could be a lot of quacking. ``` 1..(Random)|%{"Duck"};"Goose" ``` [Answer] # [Fission](https://github.com/C0deH4cker/Fission), ~~24~~ 19 bytes ``` R"duck"N# "goose"*[ ``` [Try it online!](https://tio.run/##S8ssLs7Mz/v/P0gppTQ5W8lPmUspPT@/OFVJK/r/fwA "Fission – Try It Online") -5 bytes thanks to Martin Ender [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes ``` 1ṙ+₁;"Duck "j₍,"Goose ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/Dhzpnaj5oarZVcSpOzuZSyHjX16ii55@cXp/7//z8KAA "Brachylog – Try It Online") Hey, language of the month going inactive, let's kick things up a little! [Answer] # [Befunge](http://www.quirkster.com/iano/js/befunge.html) ~~57~~ 35 bytes (perimeter of the entire field is ~~19x3~~ 17x2 charachters) Thanks to karhell for the improvement. ``` 55+"kcud",,,,,#v? @,,,,,"goose"< ``` The second line puts duck and a newline on the stack (backwards) and outputs it as a string. After that 75% chance of going back to the start and printing duck again, 25% (when question mark decides to go down) to print goose and stop. ]
[Question] [ This is my first code golf question, and a very simple one at that, so I apologise in advance if I may have broken any community guidelines. The task is to print out, in ascending order, all of the prime numbers less than a million. The output format should be one number per line of output. The aim, as with most code golf submissions, is to minimise code size. Optimising for runtime is also a bonus, but is a secondary objective. [Answer] ## [Python 3](https://docs.python.org/3/), 45 bytes ``` k=P=1 while k<1e6:P%k>0==print(k);P*=k*k;k+=1 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/P9s2wNaQqzwjMydVIdvGMNXMKkA1287A1ragKDOvRCNb0zpAyzZbK9s6W9vW8P9/AA "Python 3 – Try It Online") By the time the loop reaches testing `k`, it has iteratively computed the squared-factorial `P=(k-1)!^2`. If `k` is prime, then it doesn't appear in the product `1 * 2 * ... * (k-1)`, so it's not a factor of `P`. But, if it's composite, all its prime factors are smaller and so in the product. The squaring is only actually needed to stop `k=4` from falsely being called prime. More strongly, it follows from [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) that when `k` is prime, `P%k` equals `1`. Though we only need that it's nonzero here, it's useful in general that `P%k` is an indicator variable for whether `k` is prime. Thanks to @Sisyphus for 1 byte with `P%k>0==print(k)` using chained operator short-circuiting in place of `P%k and print(k)`. [Answer] ### *Mathematica*, ~~17~~ 24 Just for comparison: ``` Prime@Range@78498 ``` *As noted in a comment I failed to provide one prime per line; correction:* ``` Column@Prime@Range@78498 ``` [Answer] ## C, 61 chars Almost exactly the same as [this one](https://codegolf.stackexchange.com/a/5818/3544) (the question is almost exactly the same too). ``` n=2;main(m){n<1e6&&main(m<2?printf("%d\n",n),n:n%m?m-1:n++);} ``` [Answer] ### MATLAB (16) (12) Unfortunately, this outputs on a single line: ``` primes(1000000) ``` but that is solved by a simple matrix transpose: ``` primes(1000000)' ``` and I can cut out some characters by using exponential notation (as suggested in the comments): ``` primes(1e6)' ``` [Answer] ## Bash (37 chars) ``` seq 2 1e6|factor|sed 's/.*: //g;/ /d' ``` ## (60 chars) ``` seq 2 1000000|factor|sed -e 's/[0-9]*: //g' -e '/^.* .*$/ d' ``` on my computer (2.0 GHz cpu, 2 GB ram) takes 14 seconds. [Answer] ## J, 21 characters ``` 1[\p:i.(_1 p:1000000) ``` which can be shortened to ``` 1[\p:i.78498 ``` if you know how many primes there are below 1000000. [Answer] # Bash, 30 bytes Since [saeedn](https://codegolf.stackexchange.com/u/3115) won't act on my suggestion – which is both shorter and faster than his approach – I thought I'd post my own answer: ``` seq 1e6|factor|awk '$0=$2*!$3' ``` ### How it works ``` seq 1e6 ``` lists all positive integers up to 1,000,000. ``` factor ``` factors them one by one. For the first ten, the output is the following: ``` 1: 2: 2 3: 3 4: 2 2 5: 5 6: 2 3 7: 7 8: 2 2 2 9: 3 3 10: 2 5 ``` Finally, ``` awk '$0=$2*!$3' ``` changes the entire line (`$0`) to the product of the second field (the first prime factor) and the logical negation of the third field (`1` if the is one prime factor or less, `0` otherwise). This replaces lines corresponding to prime numbers with the number itself and all other lines with zeros. Since awk only prints truthy values, only prime number will get printed. [Answer] # Ruby 34 ``` require'prime';p Prime.take 78498 ``` [Answer] # PowerShell, 47 44 bytes Very slow, but the shortest I could come up with. ``` $p=2..1e6;$p|?{$n=$_;!($p-lt$_|?{!($n%$_)})} ``` # PowerShell, 123 bytes This is much faster; far from optimal, but a good compromise between efficiency and brevity. ``` $p=2..1e6;$n=0 while(1){$p=@($p[0..$n]|?{$_})+($p[($n+1)..($p.count-1)]|?{$_%$p[$n]});$n++;if($n-ge($p.count-1)){break}} $p ``` [Answer] # Bash, 37 Will golf more, if I can... Most of this is trying to parse `factor`'s awkward output format. ``` seq 1e6|factor|grep -oP "(?<=: )\d+$" ``` Takes 5.7 or so seconds to complete on my machine. (It just happened that *my* post was the *first* to go on the second page of answers, so nobody is going to see it...) ## Old solution This is longer and slower (takes 10 seconds). ``` seq 1e6|factor|egrep ':.\S+$'|grep -oE '\S+$' ``` [Answer] # Python 3.x: 66 chars ``` for k in range(2,10**6): if all(k%f for f in range(2,k)):print(k) ``` # More efficient solution: 87 chars Based on the Sieve of Eratosthenes. ``` p=[];z=range(2,10**6) while z:f=z[0];p+=[f];z=[k for k in z if k%f] for k in p:print(k) ``` [Answer] # Haskell, 51 ``` mapM print [n|n<-[2..10^6],all((>0).rem n)[2..n-1]] ``` [Answer] ### Ruby ~~50~~ 41 ``` require'mathn' p (2..1e6).select &:prime? ``` [Answer] # Julia, 11 ``` primes(10^6) ``` It looks like built ins are getting upvotes, plus I needed more words for longer answer. [Answer] ## APL, 15 ``` p~,p∘.×p←1↓⍳1e6 ``` My interpreter ran into memory problems, but it works in theory. [Answer] # Perl, 49 bytes Regular expression kung fu :) ``` for(1..1E6){(1x$_)=~/^(11+?)\1+$/ or print"$_\n"} ``` Ungolfed version: ``` for(1 .. 1_000_000) { (1x$_) =~ /^(11+?)\1+$/ or print "$_\n"; } ``` It hasn't even made 10% progress while I type this post! Source for the regex: <http://montreal.pm.org/tech/neil_kandalgaonkar.shtml> [Answer] # J (15 or 9) I can't believe this beat Mathematica (even if it's just ~~a single~~ by 2 chars) ``` a#~1 p:a=:i.1e6 ``` Or: ``` p:i.78498 ``` [Answer] # gs2, 5 bytes Encoded in CP437: ``` ∟)◄lT ``` `1C 29` pushes a million, `11 6C` is primes below, `54` is show lines. [Answer] ## C, 91 88 85 82 81 80 76 72 characters ``` main(i,j,b){for(;i++<1e6;b++&&printf("%d\n",i))for(j=2;j<i;)b=i%j++&&b;} ``` The algorithm is terribly inefficient, but since we're doing code-golf that shouldn't matter. [Answer] # GolfScript, 22/20 (20/19) bytes ``` n(6?,:|2>{(.p|%-.}do:n ``` At the cost of speed, the code can be made two bytes shorter: ``` n(6?,:|2>.{|%2>-}/n* ``` If the output format specified in the edited question is disregarded (which is what many of the existing answers do), two bytes can be saved in the fast version and one can be saved in the slow one: ``` n(6?,:|2>{(.p|%-.}do n(6?,:|2>.{|%2>-}/` ``` This will print an additional LF after the primes for the fast version, and it will print the primes as an array for the slow one. ### How it works Both versions are implementations of the [sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes "Sieve of Eratosthenes - Wikipedia, the free encyclopedia"). The fast version does the following: 1. Set `A = [ 2 3 4 … 999,999 ]` and `| = [ 0 1 2 … 999,999 ]`. 2. Set `N = A[0]` and print `N`. 3. Collect every N-th element from `|` in `C`. These are the multiples of `N`. 4. Set `A = A - C`. 5. If `A` is non-empty, go back to 2. ``` n(6? # Push "\n".pop() ** 6 = 1,000,000. ,:| # Push | = [ 0 1 2 … 999,999 ]. ,2> # Push A = [ 2 3 4 … 999,999 ]. { # ( # Unshift the first element (“N”) of “A”. .p # Print “N”. |% # Collect every N-th element from “A” into a new array, starting with the first. - # Take the set difference of “A” and the array from above. . # Duplicate the set difference. }do # If the set difference is non-empty, repeat. :n # Store the empty string in “n”, so no final LF will get printed. ``` The slow version works in a similar fashion, but instead of successively removing multiples of the minimum of “A” (which is always prime), it removes multiples of all positive integers below 1,000,000. ### Competitiveness In absence of any built-in mathematical functions to factorize or check for primality, all GolfScript solutions will either be very large or very inefficient. While still far from being efficient, I think I have achieved a decent speed-to-size ratio. At the time of its submission, this approach seems to be the shortest of those that do not use any of the aforementioned built-ins. I say *seems* because I have no idea how some of the answers work... I've benchmarked all four submitted GolfScript solutions: [w0lf's](https://codegolf.stackexchange.com/a/5987) (trial division), [my other answer](https://codegolf.stackexchange.com/a/27063) (Wilson's theorem) and the two of this answer. These were the results: ``` Bound | Trial division | Sieve (slow) | Wilson's theorem | Sieve (fast) ----------+--------------------+--------------------+------------------+---------------- 1,000 | 2.47 s | 0.06 s | 0.03 s | 0.03 s 10,000 | 246.06 s (4.1 m) | 1.49 s | 0.38 s | 0.14 s 20,000 | 1006.83 s (16.8 m) | 5.22 s | 1.41 s | 0.38 s 100,000 | ~ 7 h (estimated) | 104.65 (1.7 m) | 35.20 s | 5.82 s 1,000,000 | ~ 29 d (estimated) | 111136.97s (3.1 h) | 3695.92 s (1 h) | 418.24 s (7 m) ``` [Answer] # NARS2000 APL, 7 characters ``` ⍸0π⍳1e6 ``` [Answer] ## Golfscript ~~26 25~~ 24 ### Edit (saved one more char thanks to Peter Taylor): ``` 10 6?,{:x,{)x\%!},,2=},` ``` Old code: ``` 10 6?,{.,{)\.@%!},,2=*},` ``` This code has only theoretical value, as it is incredibly slow and inefficient. I think it could take hours to run. If you wish to test it, try for example only the primes up to 100: ``` 10 2?,{:x,{)x\%!},,2=},` ``` [Answer] # CJam - 11 ``` 1e6,{mp},N* ``` `1e6,` - array of 0 ... 999999 `{mp},` - select primes `N*` - join with newlines [Answer] # GolfScript, 25 (24) bytes ``` !10 6?,2>{.(@*.)@%!},n*\; ``` If the output format specified in the edited question is disregarded, one byte can be saved: ``` !10 6?,2>{.(@*.)@%!},`\; ``` This will print the primes as an array (like many other solutions do) rather than one per line. ### How it works The general idea is to use [Wilson's theorem](http://en.wikipedia.org/wiki/Wilson's_theorem "Wilson's theorem - Wikipedia, the free encyclopedia"), which states that *n* > 1 is prime if and only if                                                       ![(n - 1)! = -1 (mod n)](https://i.stack.imgur.com/2ALVY.png) ``` ! # Push the logical NOT of the empty string (1). This is an accumulator. 10 6? # Push 10**6 = 1,000,000. ,2> # Push [ 2 3 4 … 999,999 ]. { # For each “N” in this array: .( # Push “N - 1”. @ # Rotate the accumulator on top of the stack. * # Multiply it with “N - 1”. The accumulator now hold “(N - 1)!”. .) # Push “(N - 1)! + 1” @ # Rotate “N” on top of the stack. %! # Push the logical NOT of “((N - 1)! + 1) % N”. }, # Collect all “N” for which “((N - 1)! + 1) % N == 0” in an array. n* # Join that array by LF. \; # Discard the accumulator. ``` ### Benchmarks Faster than trial division, but slower than the sieve of Eratosthenes. See [my other answer](https://codegolf.stackexchange.com/a/27066/). [Answer] # Java, 110 bytes ``` void x(){for(int i=1;i++<1e6;)System.out.print(new String(new char[i]).matches(".?|(..+?)\\1+")?"":(i+"\n"));} ``` Using unary division through regex as a primality test. [Answer] # [Julia 1.x](http://julialang.org/), 38 bytes ``` 2:1e6 .|>i->0∉i.%(2:i-1)==println(i) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/38jKMNVMQa/GLlPXzuBRR2emnqqGkVWmrqGmrW1BUWZeSU6eRqbm//8A "Julia 1.0 – Try It Online") Since the [other Julia answer](https://codegolf.stackexchange.com/a/27021/48931) was posted, `primes` is no longer in the standard library. We use a couple of features: * `∉` costs 3 bytes but is shorter than `in(...)`. * We use the map syntax `f.x` over `map(f,x)`. * We can broadcast `%` using `.%`. * Floating point can exactly represent everything up to `1e6`, no problems there. * We use a `==` short circuiting trick. [Answer] # Mathematica 25 Assuming you don't know the number of primes less than 10^6: ``` Prime@Range@PrimePi[10^6] ``` [Answer] # J, 16 chars ``` 1]\(#~1&p:)i.1e6 ``` Without the output format requirement, this can be reduced to **13** chars: ``` (#~1&p:)i.1e6 ``` `1]\` just takes the rank 1 array of primes, turns it into a rank 2 array, and puts each prime on its own row -- and so the interpreter's default output format turns the one line list into one prime per line. `(#~ f) y` is basically `filter`, where `f` returns a boolean for each element in `y`. `i.1e6` is the range of integers [0,1000000), and `1&p:` is a boolean function that returns 1 for primes. [Answer] ## R, ~~45~~ 43 characters ``` for(i in 2:1e6)if(sum(!i%%2:i)<2)cat(i," ") ``` For each number x from 2 to 1e6, simply output it if the number of x mod 2 to x that are equal to 0 is less than 2. [Answer] # Bash (433643) My (not so clever) attempt was to use factor to factor the product. ``` factor ${PRODUCT} ``` Unfortunately with large numbers the product is of course huge. It also took over 12 hours to run. I decided to post it though because I thought it was unique. [Here is the full code.](http://pastebin.com/TYQLBZ5d) If it was primes under six it would be reasonable. ``` factor 30 ``` Oh well, I tried. ]
[Question] [ Your mission is to write the shortest valid regular expression that no string can match, empty string included. Submissions must have this form ("literal notation"): ``` /pattern/optional-flags ``` Shortest regexp wins. The regexp size is counted in characters. (including slashes and flags) Please explain how your regexp works (if it's not trivial) Thanks, and have fun! [Answer] # **6 chars** Following on the answers of primo and Peter Taylor, and a hint from `man perlre`: `/(?!)/` This perl-compatible regex matches an empty string which is not followed by another empty string. [Answer] ## 8 chars ``` /(?=a)b/ ``` We require a string containing a character which is both `a` and `b`, which is obviously impossible. [Answer] ## 5 chars Unlike everybody who abuses `$` and `^`... this actually works in Perl: ``` /V\A/ ``` `\A` matches the beginning of the string. [Answer] # 6 chars ``` /x\by/ ``` Based on [Sven Hohenstein's answer](https://codegolf.stackexchange.com/a/18402/2972). [Answer] ### 8 characters ``` /\w\b\w/ ``` A word boundary (`\b`) surrounded by 'word' characters (`\w` - one of `[_a-zA-Z0-9]`). It is unmatchable since one of the characters preceding or following a word boundary must be a non-'word' character. By the way: this is similar to the unmatchable expression ``` /\W\b\W/ ``` where `\W` means non-'word' character. [Answer] ## 4 chars ``` /$a/ ``` searches a "a" after the end of the string. or ``` /a^/ ``` searches a before the beginning of the string. [Answer] **5 characters** `/$.^/` `/$^/` will match an empty string, whereas requiring a character in between will not. [Answer] # 9 chars I'm not sure but `/[^\S\s]/` should be unmatchable since it means not any character, but at least one of them. [Answer] # 4 characters (ECMAScript flavour only) ``` /[]/ ``` In other flavours this is not a valid character class (the `]` would be considered a character *in* the class, so the expression isn't valid, because the class is never closed), but the ECMAScript standard accepts empty character classes. Since it is a class it *has* to match a character (so empty strings don't match), but since not a single character is included no actual character will match either. [Answer] # 6 characters ``` /\b\B/ ``` This matches a word boundary (`\b`) that isn't a word boundary (`\B`), which is obviously impossible. [Answer] ### 6 chars ``` /b++b/ ``` Possessive quantifier looks for as many b's as possible, then 1 more. 6 chars but points for symmetry? [Answer] ## 6 characters ``` /(\1)/ ``` Not a winner, but I thought it was fun. grep and Python both barf on this one, but Perl seems okay with it. Seems to be *very* implementation-dependent (which is hardly surprising, given its weirdness). [Bob](https://codegolf.stackexchange.com/users/4163/bob) reports below that it matches *anything* in JavaScript's regex engine. [Answer] Maybe a bit of cheating, but… ``` \0 ``` … is unmatchable in [POSIX regex](https://www.mirbsd.org/man7/re_format) in virtually all, if not all, implementations. BASIC RE and EXTENDED RE, even. And POSIX RE does not need those pesky slashes and flags PCRE has. [Answer] # 4 char: ``` /.^/ ``` Works with GNU grep 2.5.1 and egrep. [Answer] # Perl 6 (5 characters) ``` /<!>/ ``` Sorta rule abuse (because Perl 6 regexes are different, and incompatible with stardard regexes by design), but I don't care. `<!>` rule informs Perl 6 that the regex doesn't match. [Answer] ## 6 bytes ``` /(*F)/ ``` An abbreviation for `(*FAIL)`, supported by perl-compatable regex engines. Thanks to [@HamZa](https://codegolf.stackexchange.com/questions/18393/#comment35888_18431) for pointing this out. ## 9 bytes ``` /(*FAIL)/ ``` Should work with any regex engine that supports verbs at all. I'm not convinced this really needs to be golfed any further. [Answer] # **5 chars** ``` /^.^/ ``` Matches string that begin with any single character before string begin. [Answer] ### 4 chars with slashes 2 without In the TXR language's regex engine, an empty character class `[]` matches no character, and therefore no string. It behaves this way because the character class requires a character match, and when it is empty it specifies that no character can satisfy it. Another way is to invert the "set of all strings including empty" regex `/.*/` using the complement operator: `/~.*/`. The complement of that set contains no strings at all, and so cannot match anything. This is all documented in the man page: ``` nomatch The nomatch regular expression represents the empty set: it matches no strings at all, not even the empty string. There is no dedicated syntax to directly express nomatch in the regex language. However, the empty character class [] is equivalent to nomatch, and may be considered to be a notation for it. Other representations of nomatch are possible: for instance, the regex ~.* which is the complement of the regex that denotes the set of all possible strings, and thus denotes the empty set. A nomatch has uses; for instance, it can be used to temporarily "comment out" regular expressions. The regex ([]abc|xyz) is equivalent to (xyz), since the []abc branch cannot match anything. Using [] to "block" a subexpression allows you to leave it in place, then enable it later by removing the "block". ``` The slashes are not part of the regex syntax per se; they are just punctuation which delimits regexes in the S-expression notation. Witness: ``` # match line of input with x variable, and then parse that as a regex # $ txr -c '@x @(do (print (regex-parse x)) (put-char #\newline))' - ab.*c <- input from tty: no slashes. (compound #\a #\b (0+ wild) #\c) <- output: AST of regex ``` [Answer] # 4 chars ``` /$./ ``` Needs any character after the string ends [Answer] **6 chars** **(or 4, depending on how you look at it)** ``` /{,0}/ ``` [Answer] This is a 5 char regex. ``` /[]+/ ``` It matches an empty group 1 or more times. EDIT: Removed my answer for other flavours: ``` /.{-1}/ ``` Anything that is not a number inside {} will match the text. This one will match ".{-1}" [Answer] ### 5 characters Hope this doesnt sound stupid: `/[]+/` [Answer] ``` /$^/ ``` A thing that ends before it has begun... ]
[Question] [ # Introduction Bad news guys - you got detention. Your English teacher doesn't understand this site and wants you to *"stop doing math on your digital dohickeys, this is English class!"* She sentenced you to write her favorite saying on the blackboard 25 times, which will give a total of 100 lines on the blackboard. ``` The eighteen-hundreds were a time for rum. The nineteen-hundreds were a time for fun. The two-thousands are a time to run a civilized classroom. ``` Lucky for you, you are an avid reader (not to mention an expert code-golfer)! You have a read about a trick that might possibly get you off easy. ![foxtrot](https://i.stack.imgur.com/cSn2Q.gif) (Foxtrot by Bill Amend) Unfortunately for Jason, it didn't work out. But you have a better idea! Since your English teacher thinks you're doing math, if you leave all the numbers out of your program it just might work! You also want to keep your program as short as possible because you are a lazy student and don't want to write a lot on the board. ## Write a program that complies with the following rules: * Your program must print the 4 above lines 25 times. The lines must be outputted in that order, repeating. Total exactly 100 lines of output (a trailing newline at the very end or a leading newline at the very beginning is okay). * You cannot use the characters `0123456789`. Your teacher gets confused by math and will call you out! * You can use any imports and external libraries without counting the imports. Your English teacher doesn't know about programming. Jason could have saved a lot of work by not writing `#include <stdio.h>` and you don't want to make his same mistakes! * Score your program by `byte` count. Lowest score wins! [Answer] # JavaScript (ES6) 164 ``` B='teen-hundreds were a time',alert(B.replace(/./g, "The eigh"+B+" for rum.\nThe nine"+B+" for fun.\nThe two-thousands are a time to run\na civilized classroom.\n")) ``` **Test** In FireFox/FireBug console. [Answer] # Python : ~~188 173 160~~ 153 ``` a="teen-hundreds were a time" print"The eigh%s for rum.\nThe nine%s for fun.\nThe two-thousands are a time to run\na civilized classroom.\n"%(a,a)*len(a) ``` I don't python much, but this seems pretty short to me. **Edit:** So I was wrong, it wasn't short at all! Thanks for the assistance in comments :D [Answer] ## CJam, ~~151 140 135 132 130~~ [128](https://mothereff.in/byte-counter#%22TeighYrum.TnineYfun.Ttwo-thousands%20are%20a%20time%20to%20run%0Aa%20civilized%20classroom.%22%22YT%22%5B%22teen-hundreds%20were%20a%20time%20for%20%22%22%0AThe%20%22%5DerAF%2B*) bytes (Tweetable) ``` "TeighYrum.TnineYfun.Ttwo-thousands are a time to run a civilized classroom.""YT"["teen-hundreds were a time for "" The "]erAF+* ``` [Try it here](http://cjam.aditsu.net/) I am able to shorten this down to 110 bytes by converting this to unicode, but since that is not beating the other unicode solution, I would rather not put it :) [Answer] # PHP, 0 bytes ``` ``` > > You can use any imports and external libraries without counting the imports. > > > To run this code, you must import a library called `data://text/plain,<?php...classroom.\n";` with this: ``` <?php require_once 'data://text/plain,<?php for($i=ord("z");$i>ord("a");$i--) echo "The eighteen-hundreds were a time for rum. The nineteen-hundreds were a time for fun. The two-thousands are a time to run a civilized classroom. ";'; ?> ``` And you must have `allow_url_include` enabled in your `php.ini`. No more numbers or extensions, thanks to Dennis. [Answer] ## Ruby, ~~185~~ ~~180~~ 176 bytes EDIT: String interpolation, thanks @britishtea It's my first golf ever, and I'm not much of a Rubist (but I certainly love Ruby). Anyway, this is it (shortened, Doorknob's suggestion). ``` t=' were a time for ' s="The eighteen-hundreds#{t}rum. The nineteen-hundreds#{t}fun. The two-thousands are a time to run a civilized classroom." s.split.size.next.times{puts s} ``` [Answer] # Java ~~249~~ ~~231~~ ~~230~~ 222 My first answer! Why not start off using the language I know so well. ``` class c{public static void main(String[]g){for(int a='!';a++<':';out.println("The eighxrum.\nThe ninexfun.\nThe two-thousands are a time to run\na civilized classroom.".replaceAll("x","teen-hundreds were a time for ")));}} ``` Ungolfed ``` import static java.lang.System.*; class c { public static void main(String[]g) { for(int a='!';a++<':';out.println("The eighxrum.\nThe ninexfun.\nThe two-thousands are a time to run\na civilized classroom.".replaceAll("x","teen-hundreds were a time for "))); } } ``` [Answer] # **C** 171 ``` a='a';b="teen-hundreds were a time for ";main(){for(;a++<'z';)printf("The eigh%srum.\nThe nine%sfun.\nThe two-thousands are a time to run\na civilized classroom.\n",b,b);} ``` At first, I tried the simplistic version (189 bytes), which was better than the other C solution... ``` main(a){for(a='a';a<'z';++a)printf("The eighteen-hundreds were a time for rum.\nThe nineteen-hundreds were a time for fun.\nThe two-thousands are a time to run\na civilized classroom.\n");} ``` which I later optimized a bit... [Answer] # CJam, ~~109~~ ~~107~~ ~~106~~ ~~104~~ 103 bytes ``` 0000000: 22 0c 20 4f 18 41 e4 d8 a5 f3 95 cf 5e 2b cb 1c ". O.A......^+.. 0000010: 44 64 2f bf 28 23 e2 47 4e 4e 77 73 fc 43 09 a2 Dd/.(#.GNNws.C.. 0000020: 09 0b fb 18 29 e8 e8 49 5d fc 00 da b8 70 b6 3e ....)..I]....p.> 0000030: 0c 24 d7 5a 5b 28 1c 45 2e 90 63 86 04 5c 3e 95 .$.Z[(.E..c..\>. 0000040: 4b ae 66 22 48 48 2a 62 46 47 2b 62 22 54 0a 20 K.f"HH*bFG+b"T. 0000050: 2d 2e 22 27 7b 2c 57 25 7c 66 3d 7b 28 2f 29 2a -."'{,W%|f={(/)* 0000060: 7d 5a 2a 43 44 2b 2a }Z*CD+* ``` The above is a reversible xxd dump. ### Testing You can generate and execute the above code by running this in the [online interpreter](http://cjam.aditsu.net/ "CJam interpreter"): ``` "bxyyeighxrum.yninexfun.ytwo-thousands abto run a civilized classroom.y The xteen-hundreds webfor bre a time ""T -."'{,W%|f#31bHH*b:c`'\2*/'\*"HH*bFG+b""T -."`"'{,W%|f={(/)*}Z*CD+*"]:+~ ``` To see the generated code (without executing it), remove the final `~`. To count the number of bytes (one character is one byte in ISO-8859-1), replace the final `~` with a `,`. ### Printable version (122 bytes) ``` "bxyyeighxrum.yninexfun.ytwo-thousands abto run a civilized classroom.y The xteen-hundreds webfor bre a time "{(/)*}Z*CD+* ``` After pushing the string (S), the following gets executed: ``` { }Z* " Repeat 3 times: "; ( " Q := S.shift() "; / " T := S.split(Q) "; ) " R := T.pop() "; * " S := T.join(R) "; CD+* " S *= 12 + 13 "; ``` ### Moar golfing After pushing the unprintable string (U), the following gets executed: ``` HH*b " U := U.base(17 * 17) "; FG+b " U := U.base(15 + 16) "; "T\n -." " P := 'T\n -.' "; '{,W%| " P |= 'zyx...\0' "; f= " U[i] -> P[U[i]] "; ``` This pushes the string of the printable version. The rest of the code works as before. [Answer] ## JavaScript, ES6, ~~174 172~~ [154](https://mothereff.in/byte-counter#alert%28%28d%3D%22teen-hundreds%20were%20a%20time%22%29.replace%28%2F.%2Fg%2C%60The%20eigh%24%7Bd%7D%20for%20rum.%0AThe%20nine%24%7Bd%7D%20for%20fun.%0Atwo-thousands%20are%20a%20time%20to%20run%0Aa%20civilized%20classroom.%0A%60%29%29) bytes Using @edc65's `replace` trick. Thanks! ``` alert((d="teen-hundreds were a time").replace(/./g,`The eigh${d} for rum. The nine${d} for fun. two-thousands are a time to run a civilized classroom. `)) ``` Works only in latest Firefox (34 and above) due to use of template strings. [Answer] ## BrainFuck ([1,597 characters](https://mothereff.in/byte-counter#%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%5B%3E-%3E-%5B---%3E%2B%3C%5D%3E-.%5B----%3E%2B%2B%2B%2B%2B%3C%5D%3E-.---.--%5B---%3E%2B%3C%5D%3E-.%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2B.%2B%2B%2B%2B.--.%2B.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%2B%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E..%2B%2B%2B%2B%2B%2B%2B%2B%2B.%5B-----%3E%2B%2B%3C%5D%3E%2B.%5B-%3E%2B%2B%2B%2B%2B%2B%2B%2B%3C%5D%3E.%5B---%3E%2B%3C%5D%3E---.-------.----------.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.-------------.-.--%5B---%3E%2B%3C%5D%3E---.%2B%5B----%3E%2B%3C%5D%3E%2B%2B%2B.--%5B-%3E%2B%2B%2B%2B%3C%5D%3E-.%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.-------------.--%5B---%3E%2B%3C%5D%3E-.%5B-%3E%2B%2B%2B%3C%5D%3E%2B.-%5B-%3E%2B%2B%2B%3C%5D%3E.---%5B-%3E%2B%2B%2B%2B%3C%5D%3E.-----------.%2B%2B%2B%2B.--------.--%5B---%3E%2B%3C%5D%3E-.%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B.%2B%2B%2B.%5B--%3E%2B%2B%2B%2B%2B%3C%5D%3E%2B%2B%2B.---%5B-----%3E%2B%2B%3C%5D%3E.%2B%2B%2B.--------.%2B%5B-----%3E%2B%2B%3C%5D%3E%2B%2B.%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%3E-%5B---%3E%2B%3C%5D%3E-.%5B----%3E%2B%2B%2B%2B%2B%3C%5D%3E-.---.--%5B---%3E%2B%3C%5D%3E-.%2B%5B-----%3E%2B%3C%5D%3E%2B.-----.%2B%2B%2B%2B%2B.---------.%5B---%3E%2B%3C%5D%3E---.%2B%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E..%2B%2B%2B%2B%2B%2B%2B%2B%2B.%5B-----%3E%2B%2B%3C%5D%3E%2B.%5B-%3E%2B%2B%2B%2B%2B%2B%2B%2B%3C%5D%3E.%5B---%3E%2B%3C%5D%3E---.-------.----------.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.-------------.-.--%5B---%3E%2B%3C%5D%3E---.%2B%5B----%3E%2B%3C%5D%3E%2B%2B%2B.--%5B-%3E%2B%2B%2B%2B%3C%5D%3E-.%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.-------------.--%5B---%3E%2B%3C%5D%3E-.%5B-%3E%2B%2B%2B%3C%5D%3E%2B.-%5B-%3E%2B%2B%2B%3C%5D%3E.---%5B-%3E%2B%2B%2B%2B%3C%5D%3E.-----------.%2B%2B%2B%2B.--------.--%5B---%3E%2B%3C%5D%3E-.%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B.%2B%2B%2B.%5B--%3E%2B%2B%2B%2B%2B%3C%5D%3E%2B%2B%2B.%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E.-%5B---%3E%2B%3C%5D%3E--.-------.%5B-----%3E%2B%2B%3C%5D%3E%2B%2B.%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%3E-%5B---%3E%2B%3C%5D%3E-.%5B----%3E%2B%2B%2B%2B%2B%3C%5D%3E-.---.--%5B---%3E%2B%3C%5D%3E-.---%5B-%3E%2B%2B%2B%2B%3C%5D%3E.%2B%2B%2B.--------.%5B-%3E%2B%2B%2B%2B%2B%3C%5D%3E%2B%2B.%2B%5B---%3E%2B%2B%3C%5D%3E.------------.%2B%2B%2B%2B%2B%2B%2B.%2B%2B%2B%2B%2B%2B.--.%2B%2B%5B-%3E%2B%2B%2B%3C%5D%3E%2B%2B.%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.----------.--%5B---%3E%2B%3C%5D%3E---.%2B%5B----%3E%2B%3C%5D%3E%2B%2B%2B.%5B-%3E%2B%2B%2B%3C%5D%3E%2B.--%5B---%3E%2B%3C%5D%3E---.-------------.--%5B---%3E%2B%3C%5D%3E-.%5B-%3E%2B%2B%2B%3C%5D%3E%2B.-%5B-%3E%2B%2B%2B%3C%5D%3E.---%5B-%3E%2B%2B%2B%2B%3C%5D%3E.-----------.%2B%2B%2B%2B.--------.--%5B---%3E%2B%3C%5D%3E-.---%5B-%3E%2B%2B%2B%2B%3C%5D%3E.-----.%5B---%3E%2B%3C%5D%3E-----.---%5B-----%3E%2B%2B%3C%5D%3E.%2B%2B%2B.-------.%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.--%5B---%3E%2B%2B%2B%2B%3C%5D%3E%2B.-%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B.%5B-%3E%2B%2B%2B%2B%2B%2B%3C%5D%3E.%5B------%3E%2B%3C%5D%3E.%2B%2B%2B.---.-%5B---%3E%2B%3C%5D%3E%2B%2B.---%5B-%3E%2B%2B%2B%3C%5D%3E.-.-%5B---%3E%2B%3C%5D%3E-.%2B%5B-%3E%2B%2B%2B%3C%5D%3E.%2B%2B%2B%2B%2B%2B%2B%2B%2B.-----------.--%5B---%3E%2B%3C%5D%3E--..-.---..--.%2B%5B-----%3E%2B%2B%3C%5D%3E%2B%2B.%3E%2B%2B%2B%2B%2B%2B%2B%2B%2B%2B.%5B%5B-%5D%3C%2B%5D%3C-%5D)) ``` +++++++++++++++++++++++++[>->-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.+[->+++<]>++.++++.--.+.++++++++++++.+++[->+++<]>..+++++++++.[----->++<]>+.[->++++++++<]>.[--->+<]>---.-------.----------.++++++++++++++.-------------.-.--[--->+<]>---.+[---->+<]>+++.--[->++++<]>-.[->+++<]>.+++++++++++++.-------------.--[--->+<]>-.[->+++<]>+.-[->+++<]>.---[->++++<]>.-----------.++++.--------.--[--->+<]>-.++[->+++<]>.+++++++++.+++.[-->+++++<]>+++.---[----->++<]>.+++.--------.+[----->++<]>++.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.+[----->+<]>+.-----.+++++.---------.[--->+<]>---.+++[->+++<]>..+++++++++.[----->++<]>+.[->++++++++<]>.[--->+<]>---.-------.----------.++++++++++++++.-------------.-.--[--->+<]>---.+[---->+<]>+++.--[->++++<]>-.[->+++<]>.+++++++++++++.-------------.--[--->+<]>-.[->+++<]>+.-[->+++<]>.---[->++++<]>.-----------.++++.--------.--[--->+<]>-.++[->+++<]>.+++++++++.+++.[-->+++++<]>+++.++[->+++<]>.-[--->+<]>--.-------.[----->++<]>++.>++++++++++.>-[--->+<]>-.[---->+++++<]>-.---.--[--->+<]>-.---[->++++<]>.+++.--------.[->+++++<]>++.+[--->++<]>.------------.+++++++.++++++.--.++[->+++<]>++.+++++++++++++.----------.--[--->+<]>---.+[---->+<]>+++.[->+++<]>+.--[--->+<]>---.-------------.--[--->+<]>-.[->+++<]>+.-[->+++<]>.---[->++++<]>.-----------.++++.--------.--[--->+<]>-.---[->++++<]>.-----.[--->+<]>-----.---[----->++<]>.+++.-------.>++++++++++.--[--->++++<]>+.-[->+++<]>.+[->+++<]>.++++++.[->++++++<]>.[------>+<]>.+++.---.-[--->+<]>++.---[->+++<]>.-.-[--->+<]>-.+[->+++<]>.+++++++++.-----------.--[--->+<]>--..-.---..--.+[----->++<]>++.>++++++++++.[[-]<+]<-] ``` This can still be golfed further, if anyone is interested. You can [test this out](http://brainfuck.tk/) and confirm that it gives the correct output while meeting all of the rules. [Answer] ## Perl - 145 I'm happy to see so many answers! Here's a Perl solution. ``` $s="teen-hundreds were a time for";print"The eigh$s rum. The nine$s fun. The two-thousands are a time to run a civilized classroom. "for b..z ``` [Answer] **Since she hates math so much, why not Mathematica (177)** ``` a = "teen-hundreds were a time for "; Do["The eigh" <> a <> "rum. The nine" <> a <> "fun. The two-thousands are a time to run a civilized classroom." // Print, {StringLength@a}] ``` [Answer] # Javascript ES6, 198 193 bytes ``` m=Math;alert("The eighteen-hundreds were a time for rum.\nThe nineteen-hundreds were a time for fun.\nThe two-thousands are a time to run\na civilized classroom.\n".repeat(~~(m.exp(m.PI)+m.E))) ``` Your teacher doesn't want any numbers, but since they are an english teacher, they've got no clue what `Math.floor(Math.exp(Math.PI)+Math.E)` means. More readably: ``` alert("The eighteen-hundreds were a time for rum.\n\ The nineteen-hundreds were a time for fun.\n\ The two-thousands are a time to run\na civilized\n classroom.".repeat(Math.floor(Math.exp(Math.PI)+Math.E))) ``` Must be run in the latest firefox [Answer] **Javascript - ~~178 Bytes~~ 176 Bytes** My first golf, thought I'd give it a shot with bit twiddling operators, didn't turn out quite as well as hoped, but oh well! ``` c="teen-hundreds were a time for " b=!!c alert(Array((b+b+b<<b+b)+b<<b).join("The eigh"+c+"rum.\nThe nine"+c+"fun.\nThe two-thousands are a time to run\na civilized classroom.\n")) ``` Since I'm already in detention, and obviously have troubles behaving myself... **Javascript - 71 Bytes** This one will probably get me in deeper trouble, but, if I already landed myself in detention, AND I'm planning on cheating my detention, apparently I lack good judgement on how I should behave myself in class. Maybe if I can pull one over my on teacher, I can pull one over on all the other golfers out there. ``` b=+true;alert( Array((b+b+b<<b+b)+b<<b).join($('code')[+!b].innerHTML)) ``` Quick! Chrome/IE 11/Firebug users, open your consoles RIGHT NOW and try it. (Please don't hurt me too much, I thought it was funny) [Answer] ## C# - ~~229~~ 216 Bytes Free `using` FTW! ``` using c=System.Console; class S{static void Main(){var a="teen-hundreds were a time";for(int b=a.Length,i=b-b;i++<b;)c.Write("The eigh"+a+" for rum.\nThe nine"+a+" for fun.\nThe two-thousands are a time to run\na civilized classroom.\n");}} ``` Alternative, same byte count (more `using`abuse, though) ``` using i=System.Int32; using c=System.Console; class S{static void Main(){var a="teen-hundreds were a time";for(int b=new i();b++<a.Length;)c.Write("The eigh"+a+" for rum.\nThe nine"+a+" for fun.\nThe two-thousands are a time to run\na civilized classroom.\n");}} ``` [Answer] # Befunge-93, ~~268~~ ~~260~~ 256 (grid size: 72x6=432) ``` #v"K">:!#@_v>$"enin">,,,,::-" rof emit a erew sderdnuh neet">:#,_$::!!-# , ,,,"The "<|\!\%-"\^"::%-" #":-!!: -"#-"-::$_ "hgie"^v1"two-thousands are a time to run" $_$ "nuf"v"rum" v1-"##",,,< >:#,_"moorssalc dezilivic a"1 _# < ^,,\-"AK."$_,#!: ``` This is my first time golfing, so I figured I'd try a language that hadn't already been done for this problem, since I wouldn't be adding anything otherwise. Since it's Befunge-93 compatible (fits inside an 80x25 grid and uses only Befunge-93 instructions), it should work in Befunge-98 too. Just in case, I also avoided having the pointer pass over any non-instruction characters other than space. I couldn't remember whether the specification actually defined those characters as no-ops, and I'll be having no [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html) in MY code. You can't really ungolf Befunge code. The key thing to note here is that Befunge pushes characters to the stack as their ASCII values, making it relatively simple to refer to numbers without literally referring to them. The `"K"` in the top left is 75, referring to the number of repetitions times the number of "the" clauses per repetition; I use modulus and some other craftiness on (copies of) this number to determine which path to take through the printing on each go-around. `::-` is a nice idiom for zero, useful for zero-terminating strings; I use it twice here. On occasion the pointer needs to pass through a place where I'm defining a string, hence the specific choices of characters used to get certain numbers at some points. The nice thing about a lot of Befunge interpreters is that you can watch the pointer dart around the grid, as well as see what values are in the stack. That way you can step through and see how the program works yourself, more or less! I'd recommend using <http://befungius.aurlien.net/> if you don't have your own preferred Befunge interpreter. This can probably be pared down a bit (or a lot) more. Please give me feedback! If I need to provide a better explanation, someone let me know; I'm new to this. *Edit* - shaved off a few bytes by getting rid of the unnecessary redirect to the last row when the program terminates (just putting the `@` where the `^` used to be). *Another edit* - shaved off some more bytes in various places, mostly with trickery. (Also added the grid size, as seems to be the trend with Befunge answers.) [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 135 ~~136 140~~ ``` *ltG%"The eigh%srum%snine%sfun%stwo-thousands are a time to run\na civilized classroom.\n"*hhZ("teen-hundreds were a time for "".\nThe ``` Note the trailing space. Uses pretty much the same trick as @Geobits and his commenter friends in the [Python](https://codegolf.stackexchange.com/a/40213/31625) answer to construct the string. Now also uses some of [this answer](https://codegolf.stackexchange.com/a/40234/31625). This uses the built-in variable `G`, which contains `abcdefghijklmnopqrstuvwxyz` and gets one less than its length to produce the 25 outputs. [Answer] # Ruby - ~~152~~ 141 ``` puts"The eight#{e="een-hundreds were a time for "}rum. The ninet#{e}fun. The two-thousands are a time to run a civilized classroom. "*(?X-??) ``` <http://repl.it/2Om/6> [Answer] # Python, 165 bytes ``` h="hundreds were a time for " t="The " for i in h:print t+"eighteen-"+h+"rum.\n"+t+"nineteen-"+h+"fun.\n"+t+"two-thousands are a time to run\na civilized classroom." ``` It worked out really nicely that the length of h is 25, that was not intentional. =) [Answer] ## Python 2 - 143 A silly answer: ``` from this import i a="teen-hundreds were a time for ",".\nThe " print"The eigh%srum%snine%sfun%stwo-thousands are a time to run\na civilized classroom.\n"%(a+a)*i ``` Note that the full count is 162. I left out all of `from this import i`. Uses similar replacements to my pyth strategy, but I couldn't resist posting this after discovering the hilariousness of importing from this :) [Answer] # PHP (~~175~~ ~~157~~ 156 bytes; 152 with unix EOF): Not the most golfed solution, but surely does the job and is smaller than some attempts. Here is the code: ``` $a=a;$f='re a time';$r="teen-hundreds we$f for";while($a++<z)echo"The eigh$r rum. The nine$r fun. The two-thousands a$f to run a civilized classroom. "; ``` --- Old version: ``` $a=a;while($a++!=z)echo"The eighteen-hundreds were a time for rum. The nineteen-hundreds were a time for fun. The two-thousands are a time to run a civilized classroom. "; ``` --- This works because php cycles the chars, and we just check if it isn't `z` and stop. (One curiosity is that when php reaches `z`, it then goes to `aa`.) [Answer] # Python 2 - 155 ***Note:*** since control characters don't show on SE, I've replaced it with `\x19`. ``` a,b='\nThe ','teen-hundreds were a time for ' print(a+'eigh'+b+'rum.'+a+'nine'+b+'fun.'+a+'two-thousands are a time to run\na civilized classroom.')*ord('\x19') ``` Base 64 version: ``` YSxiPScKVGhlICcsJ3RlZW4taHVuZHJlZHMgd2VyZSBhIHRpbWUgZm9yICcKcHJpbnQoYSsnZWln aCcrYisncnVtLicrYSsnbmluZScrYisnZnVuLicrYSsndHdvLXRob3VzYW5kcyBhcmUgYSB0aW1l IHRvIHJ1bgphIGNpdmlsaXplZCBjbGFzc3Jvb20uJykqb3JkKCcZJyk= ``` [Answer] # LiveScript - 181 ``` p=(a,b)->"The #{a}teen-hundreds were a time for #b.\n" each console.log,map (->(p \eigh \rum)+(p \nine \fun)+'The two-thousands are a time to run\na civilized classroom.'),[\A to\Y] ``` Required imports: ``` {each, map} = require 'prelude-ls' ``` If you want to run it under Node.js, install the `LiveScript` (**not** `livescript`) and `prelude-ls` packages from npm, replace `alert` with `console.log` and run `lsc prog.ls`, where `prog.ls` contains the program. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 91 bytes ``` AgG“TheŸ¯een-““«Ã€à€…€º€‡ “©“ê¶m.“««“The¥Šteen-“®„ˆ¦.««“The‚•-““šä€™€…€º€„‡Ð“«“a–Ìized¬¸.“» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fMd39UcOckIzUozsOrU9NzdMF8oDo0OrDzY@a1hxeACQeNSwDkod2gZkLFUCyK4HE4VWHtuXqgdUeWg0x49DSowtKoIYcWveoYd7ptkPL9BDyjxpmPWpYBLXi6MLDS0BGtixCt2Me0JrDE8AmA4nERw2TD/dkVqWmHFpzaAfYwt3//wMA "05AB1E – Try It Online") [Answer] ## T-SQL: 206 Makes use of a cross join on five rows to generate 25 rows selecting the phrase. The line breaks are important for the output. ``` with c as(SELECT\ N FROM(VALUES(\),($),($),($),($))A(B))SELECT REPLACE('The eigh$rum. The nine$fun. The two-thousands are a time to run a civilized classroom.','$','teen-hundreds were a time for ')FROM c a,c b ``` [Answer] # Bash, 151 bytes Pretty much a straight port of [your own answer](https://codegolf.stackexchange.com/a/40233/11259) ``` t="teen-hundreds were a time for" for i in {a..y};{ echo "The eigh$t rum. The nine$t fun. The two-thousands are a time to run a civilized classroom." } ``` [Answer] ## C, 196 chars This isn't an easy task for good ol' C. Factoring out the "The %steen-hundreds ..." pattern saves me a whole *two* characters. Whitespace for clarity, include not counted. ``` #include <stdio.h> main(){ for (char*p="The %steen-hundreds were a time for %s.\n", *s="The two-thousands are a time to run\na civilized classroom.", *q=p; *q++ - 'a'; puts(s)) printf(p,"eigh","rum"), printf(p,"nine","fun"); } ``` [Answer] # Ruby, 145 ``` ?K.upto(?c){puts"The eigh#{x="teen-hundreds we#{t="re a time "}for "}rum. The nine#{x}fun. The two-thousands a#{t}to run a civilized classroom."} ``` # Explanation * Use `String#upto` to print the lines 25 times. The range `"K".."c"` is 25 characters. * Use basic String interpolation to shorten the lines. [Answer] ## Racket 173 ``` (let([x"teen-hundreds were a time for "])(for([z(+ #xa #xf)])(displayln(~a"The eigh"x"rum.\nThe nine"x"fun.\nThe two-thousands are a time to run\na civilized classroom.")))) ``` Ungolfed: ``` (let ([x "teen-hundreds were a time for "]) (for([z(+ #xa #xf)]) (displayln (~a "The eigh"x"rum.\nThe nine"x"fun.\nThe two-thousands are a time to run\na civilized classroom.")))) ``` [Answer] # C, 215 203 199 bytes ``` main(a){a<<='\xC'+'\xD';while(a>>=!!a)printf("The eighteen-hundreds were a time for rum.\nThe nineteen-hundreds were a time for fun.\nThe two-thousands are a time to run\na civilized classroom.\n");} ``` Ungolfed ``` main(a) { a<<='\xC'+'\xD'; while(a>>=!!a) printf("The eighteen-hundreds were a time for rum.\nThe nineteen-hundreds were a time for fun.\nThe two-thousands are a time to run\na civilized classroom.\n"); } ``` I used bit shifting to iterate without any number. `a<<='\xC'+'\xD'` sets a to 0b1[25 zeros] `a>>=!!a` shifts right one bit for each time we iterate the loop **Edit :** `a` equals argc, so its value is already 1 when the program is run with no arguments. Changed `a>>='\xB'-'\xA'` to `a>>=!!'\xA'` which is 4 bytes shorter. Also the text was displayed only 24 times. Fixed it. Removed extra brackets in the `while`. **Edit 2:** changed `!!'\xA'` to `!!a`. Seems to work and saves 4 bytes ]
[Question] [ Write a program or function that takes in a single-line string. You can assume it only contains [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters). Print or return a string of an ASCII art rocket such as ``` | /_\ |E| |a| |r| |t| |h| |_| /___\ VvV ``` with the input string written from top to bottom on the fuselage. In this case the input was `Earth`. The height of the rocket (including flames) is always the length of the string plus five. Each line in the output may have up to two trailing spaces and there may be a single optional trailing newline. **The shortest code in bytes wins.** ## More Examples: ``` [empty string] | /_\ |_| /___\ VvV a | /_\ |a| |_| /___\ VvV |0 | /_\ ||| |0| |_| /___\ VvV \/\ | /_\ |\| |/| |\| |_| /___\ VvV _ _ [note trailing space] | /_\ | | |_| | | |_| | | |_| /___\ VvV [4 spaces] | /_\ | | | | | | | | |_| /___\ VvV SPACEY | /_\ |S| |P| |A| |C| |E| |Y| |_| /___\ VvV ``` # Leaderboard ``` var QUESTION_ID=91182,OVERRIDE_USER=26997;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Excel VBA, ~~142~~ ~~179~~ ~~175~~ ~~160~~ 155 bytes **Instruction:** Set the worksheet of Excel where cell A1 is input and column C as the output. ~~Set the text alignment in column C to center~~. Write and run the following code in the Immediate Window: ``` [C1]="|":[C2]="/_\":T=[A1]&"_":For i=1To Len(T):Cells(i+2,3)="|"&Mid(T,i,1)&"|":Next:Cells(i+2,3)="/__\":Cells(i+3,3)="VvV":[C:C].HorizontalAlignment=-4108 ``` **Ungolfed the code:** ``` Sub R() [C1] = "|" [C2] = "/_\" T = [A1]&"_" For i = 1 To Len(T) Cells(i + 2, 3) = "|" & Mid(T, i, 1) & "|" Next Cells(i + 2, 3) = "/__\" Cells(i + 3, 3) = "VvV" [C:C].HorizontalAlignment = -4108 'Set the text alignment in column C to center End Sub ``` **Output:** [![enter image description here](https://i.stack.imgur.com/xGyyV.png)](https://i.stack.imgur.com/xGyyV.png) **Note:** The font and the color are just a personal choice. --- *15 bytes saved due to edc65's suggestion. Thanks.* *5 bytes saved due to Taylor Raine's suggestion. Thanks.* [Answer] ## Perl 6, 75 bytes ``` " |\n /_\\".say;" |$_|".say for slurp.chomp.comb;" |_|\n/___\\\n VvV".say; ``` [Answer] # JavaScript (ES6), 54 Straightforward ``` x=>` | /_\\ |${[...x+'_'].join`| |`}| /___\\ VvV` ``` **Test** ``` f=x=>` | /_\\ |${[...x+'_'].join`| |`}| /___\\ VvV` function update() { O.textContent=f(I.value) } update() ``` ``` <input id=I value='hello' oninput='update()'><pre id=O></pre> ``` [Answer] ## Actually, 40 bytes ``` "/___\ VvV",'_o"| |"j'|o" |"+" | /_\ ``` Yes, those newlines are supposed to be there. [Try it online!](http://actually.tryitonline.net/#code=Ii9fX19cCiBWdlYiLCdfbyJ8CiB8ImonfG8iIHwiKyIgIHwKIC9fXA&input=InwwIg) Explanation: Newlines are represented by `\n` for easier formatting ``` "/___\\n VvV",'_o"|\n |"j'|o" |"+" |\n /_\ "/___\\n VvV" create the bottom of the rocket ,'_o get input, append a "_" (for the last section before the jets) "|\n |"j insert "|\n |" between every pair of characters '|o append "|" " |"+ prepend " |" " |\n /_\ create the nose cone ``` [Answer] # C, ~~83~~, 82 bytes ``` F(char*c){for(puts(" |\n /_\\");*c;printf(" |%c|\n",*c++));puts(" |_|\n/___\\\n VvV");} ``` Test main: ``` int main() { F(""); F("a"); F("|0"); F("\\/\\"); F(" _ _ "); F(" "); F("SPACEY"); } ``` [Answer] # Python 2, ~~93~~ ~~66~~ ~~62~~ 61 bytes A FGITW. Can probably be heavily golfed. Suggestions welcome. **Edit:** 27 bytes thanks to Mego. 4 bytes thanks to TheBikingViking. 1 byte thanks to user3030010. [Try It Online!](https://tio.run/##HYlBCsIwFET3OcXwodCiGHFZcCHiXhAK4pcQkWBEk5IUqZC7x8QZePNgxu/08G6TzZbzS79vd425D0QEJAGpWCA1MQmpVPXhM5SvocQOiVZPb107L0hRl40PiLAOF6IlSFekdSWzZK4CVfqXkrqn425/ONO1FxiDdRNMGzvkHw) ``` lambda x:r""" | /_\ |%s| /___\ VvV"""%"|\n |".join(x+"_") ``` [Answer] # PHP, ~~73~~ ~~72~~ ~~69~~ 62 bytes ``` | /_\ |<?=join('| |',str_split($argv[1]._))?>| /___\ VvV ``` Takes the string to print on the fuselage as the first argument from the command line when the script is called. Improvements: 1. Saved a byte by replacing \n with a real LF newline in the first argument of `join`. 2. Saved three more bytes by appending the rocket base with a single underscore to the input 3. Thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel): Saved 7 more bytes by taking advantage of the fact that PHP used to be the "Hypertext preprocessor" so you can output as much text as you want and start the code somewhere in the middle. [Try it online!](https://beta.tehplayground.com/wBnYIY5ZjParcDZa) This was fun! :-) Sample calls: ``` php rocket.php "" php rocket.php EARTH php rocket.php "This is a very long rocket" ``` [Answer] ## Haskell, 58 bytes ``` f s=" |\n /_\\\n |"++((:"|\n |")=<<s)++"_|\n/___\\\n VvV" ``` [Answer] # [brainfuck](http://esolangs.org/wiki/Brainfuck), 179 bytes ``` >-[-[-<]>>+<]>-..[->+>++++<<]>>----.<<++++++++++.>.>>>+[-[--<]>>--]<.[-<+<++>>]<<+.---.<,[<<<.>.>.>.<.>,]<<<.[->>>+<<<]>.>.>>+++.<<.>.>>.<...---.<.<<.>>>------.[-<<<+<+>>>>]<<<.<. ``` [Try it online!](http://brainfuck.tryitonline.net/#code=Pi1bLVstPF0-Pis8XT4tLi5bLT4rPisrKys8PF0-Pi0tLS0uPDwrKysrKysrKysrLj4uPj4-K1stWy0tPF0-Pi0tXTwuWy08KzwrKz4-XTw8Ky4tLS0uPCxbPDw8Lj4uPi4-LjwuPixdPDw8LlstPj4-Kzw8PF0-Lj4uPj4rKysuPDwuPi4-Pi48Li4uLS0tLjwuPDwuPj4-LS0tLS0tLlstPDw8KzwrPj4-Pl08PDwuPC4&input=QUxMQUhVIEFLQkFS) [Answer] # Ruby, ~~57~~ 55 bytes -2 bytes by @ValueInk -5 bytes by assuming that there is no newline in the input, as suggested by @manatwork. Newline-less input can be provided for example with `echo -n`, like `echo -n hey | ruby rocket.rb`. ``` puts' | /_\ |'+gets.chars*'| |'+'| |_| /___\ VvV' ``` Old version, assumes newline in input: # Ruby, ~~62~~ 60 bytes ``` puts' | /_\ |'+gets.chop.chars*'| |'+'| |_| /___\ VvV' ``` [Answer] # [Retina](http://github.com/mbuettner/retina), ~~44~~ 37 bytes **7 bytes thanks to Martin Ender.** ``` $ _ . ¶ |$0| $ ¶/___\¶ VvV ^ |¶ /_\ ``` [Try it online!](http://retina.tryitonline.net/#code=JApfCi4KwrYgfCQwfAokCsK2L19fX1zCtiBWdlYKXgogIHzCtiAvX1w&input=Q09ERSBHT0xG) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~37~~ 36 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;”_⁾ |;ЀŒB;“/___\“ VvV”“ |“ /_\”;Y ``` ~~Same score as existing entry, but~~ uses a fun new feature - `ŒB`, the vectorised version of `ŒḄ`, known as bounce. Bouncing is running through a list to its end and then back `x[:-1]+x[::-1]` e.g.: `bounce("codegolf") == "codegolflogedoc"`. -1 byte thanks to Dennis (use the vectorised version of bounce) How? ``` ;”_⁾ |;ЀŒB;“/___\“ VvV”“ |“ /_\”;Y - argument: a string, S “ |“ /_\” - the top of the rocket [" |", " /_\"] ;”_ - concatenate to make S=S+"_" ⁾ |; - concatenate to make c=" |"+c Ѐ - map over right argument i.e. for c in S ŒB - bounce! With vectorisation c[:-1]+c[::-1] e.g. " |B" -> " |B| " ; - concatenate with “/___\“ VvV” - the bottom of the rocket ["/___\", " VvV"] ; - concatenate the top with everything else Y - join with line feeds ``` Test it on [**TryItOnline**](http://jelly.tryitonline.net/#code=O-KAnV_igb4gfDvDkOKCrMWSQjvigJwvX19fXOKAnCBWdlbigJ3igJwgIHzigJwgL19c4oCdO1k&input=&args=J0JvdW5jZXkgeWVjbnVvQic) [Answer] # [Pyke](https://github.com/muddyfish/PYKE), ~~40~~ ~~37~~ 35 bytes (Updated to work with latest version) ``` \_+2" || "m:"/___\ VvV"+R" | /_\ ``` [Try it here!](https://pyke.catbus.co.uk/?code=%5C_%2B2%22+%7C%7C%0A%22m%3A%22%2F___%5C%0A+VvV%22%2BR%22++%7C%0A+%2F_%5C&input=Earth&warnings=0&hex=0) [Answer] # [V](http://github.com/DJMcMayhem/V), ~~41,~~ 39 bytes ``` ys$_òlé òÎá|I | Hr/$r\YO |GpX2á_o VvV ``` [Try it online!](http://v.tryitonline.net/#code=eXMkX8OybMOpCsOyw47DoXxJIHwKSHIvJHJcWU8gIHwbR3BYMsOhX28gVnZW&input=RWFydGg) Note that for some reason, the online interpreter was producing unexpected results, so I pushed a debug version to the online interpreter that runs a lot slower. It should produce the correct results now. Since this program contains unprintable characters, here is a hexdump: ``` 0000000: 7973 245f f26c e90a f2ce e17c 4920 7c0a ys$_.l.....|I |. 0000010: 4872 2f24 725c 594f 2020 7c1b 4770 5832 Hr/$r\YO |.GpX2 0000020: e15f 6f20 5676 56 ._o VvV ``` [Answer] # R, 163 bytes ``` v=c();l="\n";for(i in 1:nchar(a<-scan(,"")))v=c(v,paste0(" |",strsplit(a,"")[[1]][i],"|",l,collapse=""));cat(" |",l," /_\\",l,v," |_|",l,"/___\\",l," VvV",sep="") ``` **Ungolfed :** ``` v=c() #Empty vector l="\n" #Line break for(i in 1:nchar(a<-scan(,""))) #For the number of character of the input v=c(v, paste0(" |",strsplit(a,"")[[1]][i],"|","\n",collapse="")) #This part cut the input into its letters, paste each letter between `|`'s, #and a line break cat(" |",l," /_\\",l,v," |_|",l,"/___\\",l," VvV",sep="") #Puts everything in the STDOUT, #with spaces where needed ``` I don't really like the fact I had to put some spaces in the last line, but hey ! [Answer] ## PowerShell v2+, ~~59~~ ~~55~~ 51 bytes ``` " | /_\" $args|% t*y|%{" |$_|"} " |_| /___\ VvV" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X0lBoYZLQT8@RolLJbEovbhGVaFEq7JGtVpJoUYlvkaplgvIiK/h0o@Pj4/hUggrC1P6D9TlnJGYk5Oal55apODpqQQA "PowerShell – Try It Online") Abuses the default `Write-Output` at end of execution to stick a newline between each element, since these are all just literal strings on the pipeline. The only "tricky" bit is a loop through each element of the input `$args` as a char-array to get the body of the rocket. *Uses literal newlines as pointed out by ConnorLSW to save some bytes.* *-4 more bytes thanks to Veskah.* [Answer] # PowerShell, 70 bytes ``` " |`n /_\`n$(([char[]]$a|%{" |$_|"})-join("`n"))`n |_|`n/___\`n VvV ``` Set $a to input. If it has to take input other than a variable it can be piped in: ``` "Hello World"|%{" |`n /_\`n$(([char[]]$_|%{" |$_|"})-join("`n"))`n |_|`n/___\`n VvV "} ``` Example: ``` | /_\ |H| |e| |l| |l| |o| | | |W| |o| |r| |l| |d| |_| /___\ VvV ``` [Answer] # Mathematica, 50 bytes ``` " | /_\\ |"<>(#<>"| |"&/@#)<>"_| /___\\ VvV"& ``` Anonymous function. Takes a list of characters as input and returns a string as output. [Answer] ## PHP, ~~108~~ ~~100~~ 88 bytes -8 bytes thanks to business cat -12 bytes thanks to YetiCGN ``` echo' | /_\\ ';foreach(str_split($argv[1])as$c){echo" |$c| ";}echo' |_| /___\\ VvV'; ``` pretty straightforward [Ideone](https://ideone.com/MSJymz) [Answer] ## C#, ~~106~~ ~~97~~ ~~80~~ 74 bytes ``` s=>$@" | /_\ |{string.Join("|\n |",s.ToCharArray())}| |_| /___\ VvV"; ``` I don't have C# 6 to try the above but I believe it will work *Saved 7 bytes thanks to Kevin Cruijssen* *Thanks to manatwork for pointing me in the right direction to save 17 bytes* *Saved 6 bytes thanks to milk* [Answer] # C, ~~131~~, 121 bytes ``` #define P printf main(){char s[99],*p=s;gets(s);P(" |\n /_\\\n");while(*p)P(" |%c|\n",*p++);P(" |_|\n/___\\\n VvV\n");} ``` [Answer] # Jelly, ~~38~~ 37 bytes ``` ;”_“|“|¶”jЀ“ |¶“/_\¶”;K;“/___\¶ VvV ``` [Try it online!](http://jelly.tryitonline.net/#code=O-KAnV_igJx84oCcfMK24oCdasOQ4oKs4oCcICB8wrbigJwvX1zCtuKAnTtLO-KAnC9fX19cwrYgVnZW&input=&args=IkNvZGUgR29sZiI) Same idea as with my Pyth answer, but this can probably be golfed. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~50~~ ~~47~~ ~~43~~ 37 bytes ``` I'_J" | /_\"svy" |ÿ|"}"/___\ VvV"» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=SSdfSiIgIHwKIC9fXCJzdnkiIHzDv3wifSIvX19fXAogVnZWIsK2w70&input=RWFydGg) Saved 9 bytes thanks to Adnan. [Answer] # Kotlin, 68 bytes ``` {""" | /_\${it.replace(Regex("."),"\n |\$0|")} |_| /___\ VvV"""} ``` Pretty straightforward. Uses multiline string and a regex replacement. This is a lambda with `(String)->String` type. Test: ``` fun main(args: Array<String>) { val function : (String)->String = {""" | /_\${it.replace(Regex("."),"\n |\$0|")} |_| /___\ VvV"""} println(function(" _ _ ")) } ``` [Answer] # Gema, 50 characters ``` \A= |\n\ /_\\\n ?=\ |?|\n \Z=\ |_|\n/___\\\n\ VvV ``` Sample run: ``` bash-4.3$ echo -n gema | gema '\A= |\n\ /_\\\n;?=\ |?|\n;\Z=\ |_|\n/___\\\n\ VvV' | /_\ |g| |e| |m| |a| |_| /___\ VvV ``` [Answer] # BASH 84 70 Saved 14 thanks to manatwork ``` (cat&&echo _)|sed 's~.~ |&|\n~g;1s~^~ |\n /_\\\n~;$s~$~/___\\\n VvV~' ``` Over half of the bytes are for adding the nose, and engine. [Answer] # MATLAB, 94 bytes ``` @(s)char([' |';' /_\';arrayfun(@(x)[' |' x '|'],s,'UniformOutput',0)';' |_|';'/___\';' VvV']) ``` Anonymous function [Answer] # GolfScript, ~~61~~ 51 bytes My first code golf, I hope it is good enough. ``` " | /_\\ "\1/.,{" |"\(\"| "\}\*" |_| /___\\ VvV" ``` ### Explanation ``` " |\n /_\\\n" # Push the rocket's head \ # Swap the head with the user's string 1/ # The string is converted into an array ., # Push array length {" |"\ # Push the rocket's body and swap (\ # Array's first element cut out "|\n"\ # Push rocket's body and swap }\* # Repeat for array length times " |_|\n/___\\\n VvV" # Push rocket's bottom ``` [Try it online!](http://golfscript.tryitonline.net/#code=IiAgfAogL19cXAoiXDEvLix7IiB8IlwoXCJ8CiJcfVwqIiB8X3wKL19fX1xcCiBWdlYi&input=RWFydGg&args=) [Answer] # Vim, ~~41~~ 39 bytes Here the `<End>` is literally the "End" key. ``` i <End>_:s/./ |&|\r/g /___\ VvVggxo /_\ ``` Unprintables so: ``` i <End>_^O:s/./ |&|\r/g /___\ VvV^[ggxo /_\^[ ``` [Answer] # Lua, 83, 92 bytes `function f(x)return' |\n /_\\\n'..x:gsub('(.)',' |%1|\n')..' |_|\n/___\\\n VvV'end` ``` print(' |\n /_\\\n'..(arg[1] and arg[1]:gsub('(.)',' |%1|\n') or '')..' |_|\n/___\\\n VvV') ``` ]
[Question] [ A kitten is much like a cat. Some of the main differences are cuteness, lack of intelligence, and size. Similarly, the `cat` command is different from the `kitten` command. Fortunately, there is only one difference in this case. In the kitten command, all uppercase letters are replaced with lowercase letters. --- # Objective To implement a program that behaves similarly to `cat`. All characters `[A-Z]` are outputted lowercase. --- # Input A list of files as command line arguments. If no files are listed, then read from standard input. The input may contain unprintable characters and characters outside the ASCII range. --- # Output If input is a bunch of files, concatenate the contents and output all characters as lowercase. If reading from STDIN, output the contents of STDIN with all uppercase letters as lowercase. Note: Only make the characters `[A-Z]` lowercase. It is unacceptable if any other characters are made lowercase. --- ## Examples ``` $ echo "HelLo" > file.txt $ kitten file.txt hello $ echo "Good Bye" | kitten good bye $ echo "Ä" | kitten Ä ``` As usual with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), least bytes wins. ## Leaderboards --- Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` # Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the leaderboard snippet: ``` # [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=59029,OVERRIDE_USER=32700;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 commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Bash, 19 bytes ``` cat "$@"|tr A-Z a-z ``` The best way to make kittens is to use actual cats. ### Example run ``` $ ./kitten kitten cat "$@"|tr a-z a-z ``` [Answer] # Perl, 6 bytes 5 bytes code + 1 byte command line ``` $_=lc ``` Example usage: ``` echo ABCdef | perl -p kitten.pl abcdef ``` Confirmation of correct Unicode behaviour: ``` echo "HelloÉ" | perl -p kitten.pl helloÉ ``` [Answer] # Perl, 11 bytes 10 bytes code + 1 byte command line ``` y/A-Z/a-z/ ``` Example usage: ``` perl -p entry.pl input1.txt input2.txt echo "ABCdef" | perl -p entry.pl ``` [Answer] # Python 3, 77 bytes ``` from fileinput import* print(end=b''.join(input(mode='rb')).lower().decode()) ``` [Answer] # Ruby, 13 bytes The byte count includes 1 byte for the `p` flag. Run it like so: `ruby -p kitten.rb`. ``` $_.downcase! ``` Takes input from stdin or file arguments, just like grown up cat. [Answer] # PowerShell, 112 Bytes ``` function l([string]$a){97..122|%{[char]$b=$_;$a=$a-split$b-join$b};$a}if($args){$args|%{l(gc $_)}}else{l $input} ``` Horrendously unreadable. Here's a slightly expanded version below: ``` function l([string]$a){ 97..122|%{ [char]$b=$_ $a=$a-split$b-join$b } $a } if($args){ $args|%{ l(gc $_) } } else{ l $input } ``` Defines an internal function `l` which iterates over a loop from 97 to 112 (i.e., ASCII `a` to ASCII `z`). Splits the input string over that character (yay case-insensitive default), the rejoins it with the "correct" lower case. Do note that yes, this means "Test" would briefly become "T st" as it's iterating through the `e`, for example. Doesn't affect output. The second half is the tricky bit to figure out if we have pipeline input (equivalent to stdin for PowerShell) or command-line input. The special variable `$args` is only present if command-line input is present, so we loop over each one, `gc` (for `Get-Content`) and schlep that up to `l`. Otherwise, we just schlep our `$input` up to `l`. Note that we could swap our if/else statements (i.e., `if($input)`), but since "input" is one character longer than "args" this way is shorter. [Answer] # R, 97 bytes ``` cat(chartr("A-Z","a-z",sapply(if(length(a<-commandArgs(T))){a}else{"stdin"},readLines)),sep="\n") ``` Usage: ``` $ echo "HeLlo" > file.txt $ Rscript kitten.R file.txt hello $ echo "Good Bye" | Rscript kitten.R good bye $ echo "bLABLa" > file2.txt $ Rscript kitten.R file.txt file2.txt hello blabla $ echo Ä | Rscript kitten.R Ä ``` [Answer] # [CoffeeScript](http://coffeescript.org), 292 bytes ``` f=require 'fs';d='';p=process;v=p.argv;s=p.stdin;l=((d)=>console.log d.replace /([A-Z])/g,(a,l)=>l.toLowerCase());if v.length>2 then(v.forEach (v,i)=>if i>1 then(f.exists v, (e) =>if e then(f.readFile v,'utf-8',(r,d)=>l d) else l v))else(s.resume();(s.on 'data',(c)=>d+=c);s.on 'end',()=>l d) ``` Usage: ``` $ echo "HelLo" > file.txt $ coffee kitten.coffee file.txt hello $ echo "Good Bye" | coffee kitten.coffee good bye $ echo "Ä" | kitten Ä $ coffee kitten.coffee file.txt SoMeTeXt sometext hello ``` My first participation on codegolf so please don't be rude :). For sure this code can be golfed more and coffee/javascript isn't the best choice to do that, but it does what's expected. When it reads arguments it also takes care about file existency (if file does not exists, the string is kittened.) Any help or advice to improve this code is welcome ! [Answer] # Julia, 123 bytes ``` f(s)=for l=readlines(s) print(replace(l,r"[A-Z]",lowercase))end A=ARGS length(A)>0?for i=A open(f,i)end:open(f,readline()) ``` Ungolfed: ``` function file_to_lower(s::Stream) # Loop over the lines of the input stream for l in readlines(r) # Print the lowercased line print(replace(l, r"[A-Z]", lowercase)) end end if length(ARGS) > 0 # Loop over the files specified from the command line for i in ARGS # Open the file, apply the function, then close it open(file_to_lower, i) end else # Get the input file from STDIN open(file_to_lower, readline()) end ``` [Answer] # Python 2, 53 bytes ``` from fileinput import* print''.join(input()).lower(), ``` [Answer] # C, ~~106~~ 108 bytes *Edit: Fixed a mistake that creeped in when squeezing bytes. Stdin wasn't working, now it is.* I'm pretty sure I could squeeze some bytes away, but here's an easy-to-grasp, not at all language abusive, submission: ``` main(n,s,f,c)void**s;{for(f=n-1?open(*++s,0,0):0;read(f,&c,1);putchar(64<c&c<91?c+32:c));n-->2&&main(n,s);} ``` And a somewhat more neatly formatted version for reading: ``` main(n,s,f,c) void**s; { for(f=n-1?open(*++s,0,0):0; read(f,&c,1); putchar(64<c&c<91?c+32:c)); n-->2&&main(n,s); } ``` [Answer] # CJam, 18 bytes ``` ea_:gs{q}?'_,_eler ``` The list of files must be supplied in form of URLs, which is the only format CJam understands. ### Example runs ``` $ cjam kitten <<< "AaÁáÄä" aaÁáÄä $ cjam kitten file:///home/dennis/kitten file:///home/dennis/kitten ea_:gs{q}?'_,_elerea_:gs{q}?'_,_eler ``` ### How it works ``` ea Push the array of command-line arguments. _ Push a copy. :g Retrieve the contents of all files with those URLS. s Flatten the resulting array of strings. {q} Push a block that reads all input from STDIN. ? Select the string of the array of args is non-empty. Otherwise, execute the code block. '_, Push the string of all ASCII characters before _. _el Push a copy and convert it to lowercase. er Perform transliteration. ``` [Answer] # Python 2, ~~100~~ ~~102~~ 97 bytes *Functionality corrected (and 4 bytes added) by matsjoyce. Fortunately, I saved two bytes by switching to Python 2.* ``` from sys import*;print''.join(f.read().lower()for f in(map(open,argv[1:])if argv[1:]else[stdin])) ``` Takes arguments from the command line, or from STDIN if no arguments found. This abuses the default arguments of some functions. By default, `open` uses read-only text mode, which is exactly what we want. `read`, if called with no arguments, will return all text in the stream. Ungolfed: ``` import sys if len(sys.argv) > 1: # If we have command-line arguments: source = [] # Initialize an empty list for path in sys.argv[1:]: # Iterate through every filename we have kitfile = open(path, 'rt') # Open the file in read-only text mode source.append(kitfile) # Add it to the list else: # Otherwise, if the args are empty: source = [sys.stdin] # Set our source to STDIN wrapped in a list kittened = [] # Initialize an empty list for kitfile in source: # Iterate through every file (or just STDIN) text = kitfile.read() # Read everything from the stream kitten_text = text.lower() # Make it lowercase kittened.append(kitten_text) # Add it to the list final = ''.join(kittened) # Join everything together print final # Print the result ``` [Answer] # Python 3, ~~124~~ 123 bytes --- ``` from sys import* for f in list(map(open,argv[1:]))or[stdin]:print(f.read().translate({i:i+32for i in range(65,91)}),end="") ``` [Python eats kittens!](https://www.google.co.uk/search?q=python+eats+kitten) ``` $ python kitten.py file.txt hello $ echo "Good Bye" | python kitten.py good bye $ echo "Ä" | python kitten.py Ä ``` [Answer] # Mathematica, 66 bytes ``` kit=StringReplace[#,x:RegularExpression["[A-Z]"]:>ToLowerCase[x]]& ``` Called as ``` kit@"HelLo" ``` Mathematica already has a [`ToLowerCase`](http://reference.wolfram.com/language/ref/ToLowerCase.html) function, but it converts special (Unicode and mathematical) characters as well. So I had to kittenize it. This function will take any input. [Answer] # C#, ~~230~~ 226 bytes ``` namespace System{using Linq;class P{static void Main(string[]a){Console.Write(string.Concat((a.Length>0?string.Concat(a.Select(f=>IO.File.ReadAllText(f))):Console.In.ReadToEnd()).Select(c=>c>'@'&&c<'['?char.ToLower(c):c)));}}} ``` Ungolfed: ``` namespace System { using Linq; class P { static void Main(string[] a) { Console.Write( // Print... string.Concat( // ...all chars combined to a string... (a.Length > 0 ? // ...commandline arguments?... string.Concat(a.Select(f => IO.File.ReadAllText(f))) : // ...then all files as single string... Console.In.ReadToEnd() // ...else STDIN input ).Select(c => c > '@' && c < '[' ? char.ToLower(c) : c) // ...Lowercase only A..Z ) ); } } } ``` [Answer] ## Haskell, 133 ``` import System.Environment main=getArgs>>=mapM_(>>=putStr.map l).f f[]=[getContents] f n=map readFile n l x=[x..]!!sum[32|x>'@',x<'['] ``` The cat-style args processing is derived from [this tutorial](https://wiki.haskell.org/Tutorials/Programming_Haskell/Argument_handling), then rearranged to shave characters. Explaining `l`, the function to lowercase one character: * `sum[32|condition]` is a shorter form of `if condition then 32 else 0`. * `[x..]!!count` is `iterate succ x !! count` is `toEnum $ fromEnum x + count` and shorter than importing and using `Data.Char.toLower` with a condition to restrict it to ASCII. * `'@'` and `'['` are the characters immediately preceding `A` and following `Z`, so that I can use `<` instead of `<=`. Thanks to Anders Kaseorg for contributing the `sum[...|...]` and `[x..]!!` tricks. [Answer] # C#, 342 bytes * takes file list from passed arguments. * read every char in every file than only converts to lower case if and only if the character in the A..Z range than send it to STDOUT. * If there is no file list than reads STDIN, reads every char, converts to lower case if and only if the character in the A..Z range than send it to STDOUT. ``` namespace System{ using IO; using Linq; class P{ static void Main(string[]a){ Action<char>e=C=>{var c=char.ToLower(C);Console.Out.Write(c>='a'&&c<='z'?c:C);}; if(a.Length>0)a.ToList().ForEach(f=>File.ReadAllText(f).ToCharArray().ToList().ForEach(e)); else while(true) Console.In.ReadLine().ToCharArray().ToList().ForEach(e); } } } ``` # C#, 319 bytes single-liner, same as above: ``` namespace System{using IO;using Linq;class P{static void Main(string[]a){Action<char>e=C=>{var c=char.ToLower(C);Console.Out.Write(c>='a'&&c<='z'?c:C);};if(a.Length>0)a.ToList().ForEach(f=>File.ReadAllText(f).ToCharArray().ToList().ForEach(e));else while(true)Console.In.ReadLine().ToCharArray().ToList().ForEach(e);}}} ``` [Answer] # S.I.L.O.S 179 characters ``` loadLine : a = 256 x = get a lbla X = x B = x C = 91 B - 64 if B c printChar x GOTO x lblc C - x if C D printChar x GOTO x lblD x + 32 printChar x lblx a + 1 x = get a if x a lblb ``` Feel free to [try this code online!](http://silos.tryitonline.net/#code=bG9hZExpbmUgOgphID0gMjU2CnggPSBnZXQgYQpsYmxhClggPSB4CkIgPSB4CkMgPSA5MQpCIC0gNjQKaWYgQiBjCnByaW50Q2hhciB4CkdPVE8geApsYmxjCkMgLSB4CmlmIEMgRApwcmludENoYXIgeApHT1RPIHgKbGJsRAp4ICsgMzIKcHJpbnRDaGFyIHgKbGJseAphICsgMQp4ID0gZ2V0IGEKaWYgeCBhCmxibGI&input=&args=VEVTVElORyBURVNUSU5HIEZvbyBCYXIKMTIz) --- Essentially it translates to this in pusedocode. ``` String input = input(); for(char c in input) if(c is uppercase) print c + 32/*lowercase c*/else print c ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` AuA‡ ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fsdTxUcPC//89UnN88gE "05AB1E – Try It Online") Beats all other answers. ``` AuA‡ # full program ‡ # replace all characters of... A # "abcdefghijklmnopqrstuvwxyz"... u # in uppercase... ‡ # with corresponding character in... A # "abcdefghijklmnopqrstuvwxyz"... ‡ # in... # implicit input # implicit output ``` [Answer] # [Julia 1.x](http://julialang.org/), 65 bytes ``` !s=print.(c+32('@'<c<'[') for c=read(s,String)) .!ARGS>[]||!stdin ``` [Try it online! (stdin)](https://tio.run/##yyrNyUw0rPj/X7HYtqAoM69ETyNZ29hIQ91B3SbZRj1aXVMhLb9IIdm2KDUxRaNYJ7gEqChdU5NLT9ExyD3YLjq2pkaxuCQlM@///8Sk5JTUtHQPTy9vH18//4DAoOCQ0LDwiMiow50gaGhkAgA "Julia 1.0 – Try It Online") [Try it online! (files)](https://tio.run/##yyrNyUw0rPj/X7HYtqAoM69ETyNZ29hIQ91B3SbZRj1aXVMhLb9IIdm2KDUxRaNYJ7gEqChdU5NLT9ExyD3YLjq2pkaxuCQlM@@/sq2Co5Ozi6vb4c7DDWC48vCCxKTklNQ0BVvl/yn5Cnn5JQpgSxRyU//rJeenpOqVZOYjWAA "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 24 [bitsv1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3 bytes ``` kAnĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyI9IiwiIiwia0FuxL8iLCIiLCLDhGJDIl0=) The power of context variable overloads and range coding! Simply transliterate the uppercase alphabet to the lowercase alphabet. [Answer] # sed, 14 bytes ``` s/[A-Z]/\L\0/g ``` Run with `env -i sed -f kitten.sed`. [Answer] # Java, 198 bytes ``` b->B->{B="";for(java.io.File c:b)B+=new java.util.Scanner(c).useDelimiter("\\Z").next();for(int c=0;c++<B.length;)if(B.charAt(c)>64&B.charAt(c)<91)B=B.replace(B.charAt(c),B.charAt(c)|32);return B;}; ``` You are forced to use the above lambda with files, so there's no need to take input from STDIN! Also, it's a `Function<File[], UnaryOperator<String>>`. It's used like `foo.apply(anArrayOfFiles).apply(anything)`. As something that makes more sense to those who are new to Java, it takes 223 bytes: ``` String A(java.io.File[]b){String B="";for(java.io.File c:b)B+=new java.util.Scanner(c).useDelimiter("\\Z").next();for(int c=0;c++<B.length;)if(B.charAt(c)>64&B.charAt(c)<91)B=B.replace(B.charAt(c),B.charAt(c)|32);return B;} ``` As something that compiles, it takes up 232 bytes: ``` class a{String A(java.io.File[]b){String B="";for(java.io.File c:b)B+=new java.util.Scanner(c).useDelimiter("\\Z").next();for(int c=0;c++<B.length;)if(B.charAt(c)>64&B.charAt(c)<91)B=B.replace(B.charAt(c),B.charAt(c)|32);return B;}} ``` [Answer] # [Go](//golang.org), 89 bytes ``` package main import(."fmt" ."strings") func main(){s:="" for{Scan(&s) print(ToLower(s))}} ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ;dBíC ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O2RC7UM&input=IkhlbExvCkdvb2QgQnllCsQiIA) # [Japt](https://github.com/ETHproductions/japt) v2.0a0, 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` r\A_v ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clxBX3Y&input=IkhlbExvCkdvb2QgQnllCsQiIA) ]
[Question] [ The goal is to output or display an image with an € (euro) sign according to the following specs (ignoring the border of the sign). ![€ sign](https://i.stack.imgur.com/neCQE.png) Source: <http://en.wikipedia.org/wiki/File:Euro_Construction.svg> Rules: * The program / script must take the height of the `€` sign in pixels as an argument (empty space around the sign is optional) * The `€` sign can't be drawn as or from a character, directly (it's forbidden to `print` the `€` in the image) or indirectly (calculating [`8364`](http://www.fileformat.info/info/unicode/char/20ac/index.htm) then displaying it in a HTML page) * The output does not need to be saved to any file, it can be displayed then just shown as a screenshot * [Standard “loopholes”](http://meta.codegolf.stackexchange.com/q/1061/14215) are forbidden * Shortest code wins [Answer] ## Mathematica, ~~193~~ ~~183~~ ~~177~~ ~~173~~ ~~169~~ 166 bytes Yay, maths! I'm plotting the region that satisfies a certain (rather complicated) set of inequalities: ``` e=RegionPlot[(1<Abs@y<3||c)&&{x,y+12}.(d=2{-5Sin@40°-6,m=5Cos@40°})*{x+15,y+1-2Sign@y}.d<0||c&&x<2m/.c->100<x^2+y^2<144,{x,-15,9},{y,-12,12},Frame->0>1,ImageSize->#]& ``` Usage is `e[height]`, e.g. `e[100]`: ![enter image description here](https://i.stack.imgur.com/m2UhF.png) Or `e[200]`: ![enter image description here](https://i.stack.imgur.com/rpFwz.png) You may notice, that the sharper edges are slightly rounded off. That's because the region can only be plotted by sampling the points in space, and Mathematica doesn't sample each pixel by default. The sampling resolution can be increased by adding another option `PlotPoints->#` (which uses one sample per pixel), which adds **14 characters**. I don't recommend running it with that option, because it significantly increases runtime and barely increases visual appeal beyond `#/4` or so. Hence, (after approval of the OP) it is not included in the score. Here is a slightly ungolfed version: ``` e[height_] := ( angle = 40°; d = {-5 Sin[angle] - 6, 5 Cos[angle]}; RegionPlot[ (Abs[y] > .5 && Abs[y] < 1.5 || r > 25 && r < 36) && {x, y + 6}.d > 0 && {x + 7.5, y + .5 - Sign[y]}.d < 0 || r > 25 && r < 36 && x < 5 Cos[angle] /. r -> x^2 + y^2 , {x, -7.5, 4.5}, {y, -6, 6}, Frame -> False, ImageSize -> height ] ); ``` Note that in the golfed version, I've scaled the coordinate system by a factor of 2 to avoid the `.5`s, but it turns out that the character count is actually identical. Here is an explanation for how I worked out the formula. I divided the shape into two regions. One contains the ring and the stripes and is cut off to the right with the `BCDE` slope and to the left with the `IJ` and `GH` slopes (more on that later). The other contains the same ring, but is simply cut off at the *x* coordinate of point `D`. The conditions for the two regions are combined with `||`, which acts as a set union here. The ring is just defined as `5 < r < 6`, where `r` is the distance from the origin. `r²` is easier to work out though (`x²+y²`), so I'm using `25 < x² + y² < 36` to get all the points in the ring. The stripes are between `±.5` and `±1.5`. We can handle both stripes at the same time, by taking the modulus of *y*, so the stripes (of infinite length) just fulfil `.5 < |y| < 1.5`. Again, to take the union of the stripes and the ring, I'm just using `||`. The interesting thing is probably how to get the "masks" though. Point `D` has an *x* coordinate of `5 cos 40°`, so the mask taking care of lower edge (combined with the ring only) is just `x < 5 cos 40°`. This can be applied via set intersection which translates to `&&` in logic. The other masks are the really tricky part. First, let's get the slope of `BCDE`. We can easily construct points `C` and `D`, as `(0, -6)` and `5 (cos 40°, sin 40°)`, respectively. The vector pointing along the line is then just `D - C = (5 cos 40°, 5 sin 40° + 6)`. To apply the mask on the right, I only need to figure out if a point lies to the left or the right of that line (let's call line vector `p`). I can figure this out by taking the vector from `C` to my point of interest and projecting it onto a vector *perpendicular* to `p`. The sign of the projection will tell me the side the point is on. Obtaining the perpendicular vector is pretty simple in 2D: flip the coordinates and reverse the sign of one of them. That's the variable `d` in my code: `(-5 sin 40° - 6, 5 cos 40°)`. The vector from `C` to a point of interest `q = (x, y)` is `q - C = (x, y + 6)`. The projection is just the scalar product (or dot product) between `q` and `d`. The way I chose `d` it happens to point to the left, so I want `d.(q-C) > 0`. This condition applies the right-hand mask. For the left-hand mask I can use basically the same idea. The slope is the same and therefore so is `d`. I just need offset my point from the lower-left corners of stripes instead of from `C`. Those have coordinates `(-7.5, 0.5)` (upper stripe) and `(-7.5, -1.5)` (lower stripe). So that would call for two independent rules for the two stripes. However, note that all points affected by the lower mask are in the lower stripe and hence have negative *y*. And all points affected by the upper mask have positive *y*. So I can simply switch my offset using `Sign[y]` which is `1` for positive and `-1` for negative `y`. So my offset point becomes `(-7.5, -0.5 + Sign[y])`. Otherwise the mask works just like the right-hand mask. Of course, this time the projection needs to be negative. So, naively that would be something like `RH-projection > 0 && LH-projection < 0` (which is also what I originally had in the code). But we can shorten this, because multiplying a positive and a negative number has to give a negative number, so it's just `RH * LH < 0` (where `RH` and `LH` are the respective projections). That's it. Putting it all together leads to the following logical structure: ``` ( (is_in_circle || is_in_stripe) && is_between_left_and_right_mask ) || ( is_in_circle && left_of_edge ) ``` Just to be clear, the coordinates in my explanation refer to the construction diagram given in the challenge. As mentioned above my code actually multiplies all of them by `2` - I changed it to save bytes, but the byte count is actually identical, and I couldn't be bothered to revert the change again. Also integers look nicer. [Answer] # BBC BASIC, 202 ``` INPUTh:w=h/12s=w/2.4p=25VDU22,6,29,640;400;p,4,0;1.5*w;p,153,6*w;0;p,4,0;1.5*w;p,159,h/3.1;4.7*w;p;9*s;9*w;p,87,h/3.1;-19*w;p,4,-7.5*w;0;p;s;w;p,85,4.5*s;0;p,81,s;w;p;s;w;p;s;w;p,85,-7.5*w;2*w;p,81,s;w; ``` download emulator at <http://www.bbcbasic.co.uk/bbcwin/bbcwin.html> **In BBC basic, all graphics are handled at the low level using machine-specific ASCII control characters** (but some high level commands are also available for the common ones for convenience.) The ones used here are 22 (change display mode) 29(change origin) and 25, equivalent to the PLOT statement, which takes an additional action parameter (draw line, circle, triangle, etc. in background/foreground with relative/absolute move) before the X and Y parameters. **So all I have to do is send a load of characters to the VDU controller.** values terminated in semicolon are 16 bit. others are 8 bit. **The total number of bytes sent to the VDU controller is 91**, though that in itself would not qualify as an answer because by that stage the size is hardcoded. The obvious place for the origin is the centre of the circle, but there are actually more commands involved in producing the bars. So I shifted the origin down 1.5 to the bottom of the lower bar, which reduces the number of fractions and negative numbers required. It remains on the vertical line with the centre of the circle, which is important because the line E starts from this vertical line. Actually, I only had to calculate 3 numbers off the drawing: the top inner corner of the C shape (5 cos 40, 5 sin 40 + 1.5) = (3.8302,3.1394+1.5) = approx (12/3.1, 4.6) and the gradient of the line E:x/y=3.8302/(6+3.1394)=0.4157 = approx 1/2.4 As I only have the free evaluation version (interpreted), I take the symbol height as user input. If you buy the full version (29.99GBP) you can compile and then read the command line with `w=VAL(@cmd$)/12`. **Ungolfed code** In the golfed code, there is only one VDU statement, but in the ungolfed code I break it down into several for clarity. Also, because BBC basic is little endian, the combination `p,0,` can be golfed to `p;` but I left it ungolfed for clarity. ``` INPUT h w=h/12 :REM w is the width of the line, which is 1/12 the height of the symbol, hardcoded at 900. s=w/2.4 :REM s/w is the gradient x/y of line E. s is the horizontal offset of the top and bottom of the ends of horizontal bars p=25 :REM VDU p,action,x;y; is the equivalent of PLOT action,x,y VDU 22,6 :REM change mode VDU 29,640;400; :REM set origin VDU p,4,0;1.5*w; :REM move to centre of circle VDU p,153,6*w;0; :REM draw circle in foreground colour VDU p,4,0;1.5*w; :REM move to centre of circle VDU p,159,h/3.1;4.6*w; :REM draw circle in background colour, ending at the upper inner point of the C shape. VDU p,0,9*s;9*w; :REM move relative along slant gradient, 9 spaces in y direction, to define the upper cut on the circle VDU p,87,h/3.1;-19*w; :REM draw triangle in background colour, based on the last two points and the absolute point specified here (vertical line for lower cut) VDU p,4,-7.5*w;0; :REM move absolute to bottom left of lower bar VDU p,0,s;w; :REM move relative to top left of lower bar VDU p,85,4.5*s;0; :REM draw triangle to bottom right corner of lower bar (absolute) VDU p,81,s;w; :REM draw triangle to top right of lower bar (relative) VDU p,0,s;w; :REM move relative to bottom right of upper bar VDU p,0,s;w; :REM move relative to top right of upper bar VDU p,85,-7.5*w;2*w; :REM draw triangle to bottom left of upper bar (absolute) VDU p,81,s;w; :REM draw triangle to top left of upper bar (relative) ``` ![enter image description here](https://i.stack.imgur.com/O3OuC.png) [Answer] # PostScript/GhostScript, 100 (96 for the program, 4 for the command-line switch prefix) Fully golfed and hand-tokenized: ``` $ hexdump -C euro.ps 00000000 68 20 88 78 92 36 92 38 92 8b 88 4b 88 3c 92 ad |h .x.6.8...K.<..| 00000010 88 00 88 00 88 3c 88 2d 88 ce 92 05 88 00 88 00 |.....<.-........| 00000020 88 32 88 d8 88 28 92 06 92 16 88 b9 88 fb 92 6b |.2...(.........k| 00000030 88 b5 88 f1 92 63 88 13 88 f1 92 63 88 17 88 fb |.....c.....c....| 00000040 92 63 92 16 88 b9 88 0f 92 6b 88 b5 88 05 92 63 |.c.......k.....c| 00000050 88 1b 88 05 92 63 88 1f 88 0f 92 63 92 16 92 42 |.....c.....c...B| 00000060 ``` You can get a copy [here](https://drive.google.com/file/d/0B7231cQnKsDQTEcxTTdOa0psSGc/edit?usp=sharing), for your own viewing. After seeing @ThomasW's answer, and considering my program carefully, I realized that I could do it even better. The tokenized version is equivalent to this: ``` h 120 div dup scale 75 60 translate 0 0 60 45 -50 arc 0 0 50 -40 40 arcn closepath -71 -5 moveto -75 -15 lineto 19 -15 lineto 23 -5 lineto closepath -71 15 moveto -75 5 lineto 27 5 lineto 31 15 lineto closepath fill ``` An explanation of the optimizations: First off, I converted my first solution into a union of some simpler subpaths, rather than one path circumscribing the entire thing. I borrowed Thomas's method of inputting a parameter, which is much better than what I had had. Then I multiplied all the coordinates by 10 and rounded everything off to give me just integer coordinates. I also rounded off the angles, and converted the two large ones to equivalent negative angles. This conveniently makes every single number fall between -128 and 127. And then I tokenized *everything*. Each operator can be represented with a two-byte sequence each. And because each number can be represented by a single signed byte, each one *also* becomes only two bytes. The only part I couldn't do that with was the `h` at the start, but it too is only two bytes, just the `h` and a space after it. Run it as: ``` gs -dh=200 euro.ps ``` ![200 pt high](https://i.stack.imgur.com/xIVjX.png) ``` gs -dh=80 euro.ps ``` ![80 pt high](https://i.stack.imgur.com/IC8cn.png) ``` gs -dh=20 euro.ps ``` ![20 pt high](https://i.stack.imgur.com/7k8Fu.png) --- ## New: Even shorter versions! Using encoded user paths, I have managed to reduce the program size by a few bytes. Each of these programs is equivalent to the first one, producing identical output: 92 bytes: ``` hexdump -C euro.ps 00000000 68 20 88 78 92 36 92 38 92 8b 88 4b 88 3c 92 ad |h .x.6.8...K.<..| 00000010 7b 7b 88 b5 88 c4 88 2d 88 3c 30 20 30 88 3c 88 |{{.....-.<0 0.<.| 00000020 2d 88 cf 30 20 30 88 32 88 d8 88 28 88 b9 88 fb |-..0 0.2...(....| 00000030 88 b5 88 f1 88 13 88 f1 88 17 88 fb 88 b9 88 0f |................| 00000040 88 b5 35 88 1b 35 88 1f 88 0f 7d 8e 0b 00 07 08 |..5..5....}.....| 00000050 0a 01 23 03 0a 01 23 03 0a 7d 92 b3 |..#...#..}..| 0000005c ``` Which is equivalent to: ``` h 120 div dup scale 75 60 translate { {-75 -60 45 60 0 0 60 45 -50 0 0 50 -40 40 -71 -5 -75 -15 19 -15 23 -5 -71 15 -75 5 27 5 31 15} <00 07 08 0A 01 03 03 03 0A 01 03 03 03 0A> } ufill ``` And a slightly counterintuitive confusing solution saves one more character, for only 91: ``` $ hexdump -C euro.ps 00000000 68 20 88 78 92 36 92 38 92 8b 88 4b 88 3c 92 ad |h .x.6.8...K.<..| 00000010 5b 5b 8e 1e b5 c4 2d 3c 00 00 3c 2d ce 00 00 32 |[[....-<..<-...2| 00000020 d8 28 b9 fb b5 f1 13 f1 17 fb b9 0f b5 05 1b 05 |.(..............| 00000030 1f 0f 7b 92 38 88 7f 92 50 7b 32 35 36 92 a9 7d |..{.8...P{256..}| 00000040 92 54 7d 92 49 5d 92 32 8e 0b 00 07 08 0a 01 23 |.T}.I].2.......#| 00000050 03 0a 01 23 03 0a 5d 92 32 92 b3 |...#..].2..| 0000005b ``` Which is equivalent to: ``` h 120 div dup scale 75 60 translate [ [ <b5 c4 2d 3c 00 00 3c 2d ce 00 00 32 d8 28 b9 fb b5 f1 13 f1 17 fb b9 0f b5 05 1b 05 1f 0f> {dup 127 gt {256 sub} if} forall ] cvx <00 07 08 0A 01 23 03 0A 01 23 03 0A> ] cvx ufill ``` [Answer] # HTML, ~~250~~ ~~249~~ ~~248~~ ~~242~~ ~~244~~ ~~234~~ 229 ``` <svg viewBox=-7.5,-6,12,12 onload=this.style.height=prompt()><clipPath id=c><path d=M5-6,1.8,1.5,3.8,3.2V6H-9.4L-7.1,.5-7.5-.5-5.2-6> </clipPath><g clip-path=url(#c) fill=none stroke=#000><circle r=5.5 /><path d=M-8,1h15M-8-1h15> ``` While this is only using SVG stuff, it heavily relies on lax HTML parsing and has to be served as HTML. Strict SVG would require a lot more bytes. [Try it!](http://jsbin.com/quwuyibuqa/edit?html,output) [Answer] ## CSS, ~~512~~ 494 bytes ``` <style>*,:after,:before{position:absolute;width:20;content:"";background:#fff}#a{margin:150;height:20;border:2px solid;border-radius:20px}#a:after{width:10;height:10;bottom:0;right:-8}p{top:7;left:-6;width:29;height:2;border:solid;border-width:2 0;transform:skewX(-23deg);margin:0;background:0}p:before{width:2;height:4;bottom:-3;left:-.5}p:after{width:16;height:16;bottom:-3;right:-8}</style><div id=a><p><script>document.getElementById('a').style.transform='scale('+(prompt()/24)+')'</script> ``` Not the smallest answer by a fair bit, but as small as I could get even when summoning all my css-minification-fu ## Caveats: The above code with all 'px' stripped works in Firefox & IE but not Chrome & Safari which are fussier about their units :) I also had to re-add the px's to get the jsfiddle to work: <http://jsfiddle.net/9A3J9/> 100: ![enter image description here](https://i.stack.imgur.com/moreO.gif) 200: ![enter image description here](https://i.stack.imgur.com/4b4PT.gif) ## ungolfed code: ``` <style> *,:after,:before{ position:absolute; width:20; content:""; background:#fff } #a{ margin:150; height:20; border:2px solid; border-radius:20px } #a:after{ width:10; height:10; bottom:0; right:-8 } p{ top:7; left:-6; width:29; height:2; border:solid; border-width:2 0; transform:skewX(-23deg); margin:0; background:0 } p:before{ width:2; height:4; bottom:-3; left:-.5 } p:after{ width:16; height:16; bottom:-3; right:-8 } </style> <div id=a><p> <script> document.getElementById('a').style.transform='scale('+(prompt()/24)+')' </script> ``` [Answer] # PostScript+Ghostscript 137 + 6 = 143 (binary), 209 + 6 = 215 bytes Fully golfed version with binary tokens: ``` $ hexdump -C euro_golfed.ps 00000000 68 20 31 32 20 92 36 92 38 92 8b 37 2e 35 20 36 |h 12 .6.8..7.5 6| 00000010 92 ad 35 20 36 0a 31 2e 38 20 2d 31 2e 35 0a 33 |..5 6.1.8 -1.5.3| 00000020 2e 38 20 2d 33 2e 32 0a 33 2e 38 20 2d 36 0a 2d |.8 -3.2.3.8 -6.-| 00000030 39 2e 34 20 2d 36 0a 2d 37 2e 31 20 2d 2e 35 0a |9.4 -6.-7.1 -.5.| 00000040 2d 37 2e 35 20 2e 35 0a 2d 35 2e 32 20 36 92 6b |-7.5 .5.-5.2 6.k| 00000050 37 7b 92 63 7d 92 83 35 2e 35 92 14 30 92 6f 2d |7{.c}..5.5..0.o-| 00000060 38 20 2d 31 0a 2d 38 20 31 92 6b 32 7b 31 35 20 |8 -1.-8 1.k2{15 | 00000070 30 92 85 92 6b 7d 92 83 30 20 30 20 35 2e 35 20 |0...k}..0 0 5.5 | 00000080 30 20 33 36 30 92 05 92 a7 |0 360....| 00000089 ``` [Download hand coded binary file](http://www.mediafire.com/download/w5zd2lws1tql5j8/euro_golfed.ps) ASCII version: ``` h 12 div dup scale 7.5 6 translate 5 6 1.8 -1.5 3.8 -3.2 3.8 -6 -9.4 -6 -7.1 -.5 -7.5 .5 -5.2 6 moveto 7{lineto}repeat clip newpath 5.5 0 -8 -1 -8 1 moveto 2{15 0 rlineto moveto}repeat 0 0 5.5 0 360 arc stroke ``` Save as `euro.ps` and run with Ghostscript like ``` gs -dh=80 euro.ps ``` ![Euro sign, 80 points, rendered by Ghostscript](https://i.stack.imgur.com/fa5Fp.png) ``` gs -dh=20 euro.ps ``` ![Euro sign, 20 points, rendered by Ghostscript](https://i.stack.imgur.com/xtT44.png) As there is no such thing as a pixel in PostScript, that height is interpreted in points instead. I calculated +6 for the switch on the command line. [Answer] # Python - turtle - 517 ``` import turtle,sys from math import * q=sqrt h=int(sys.argv[1])/24 t=turtle.Turtle() z=t.begin_fill y=t.end_fill x=t.goto w=t.towards v=t.fd u=t.circle r=t.seth o=t.setx n=t.xcor t.pu() x(10*h,0) t.left(90) t.circle(10*h,40) z() A=w(0,-12*h) B=2/sin(A*pi/180) u(10*h,280) r(-90) C=n()/h v((q(144-C*C)-q(100-C*C))*h) D=w(0,0) r(D+90) u(-12*h,D+135.42) y() F=2*pi/9 G=h*cos(F)/(5*sin(F)+6) x(45*G,-3*h) z() o(-15*h) r(A) v(B*h) o(45*G+15*h+n()) y() x(65*G,h) z() o(-15*h) r(A) v(B*h) o(65*G+15*h+n()) y() t.ht() input() ``` `python % 100` and `python % 500` respectively: ![](https://i.stack.imgur.com/Mhjpm.png) ![](https://i.stack.imgur.com/QSFKQ.png) [Answer] # PHP, ~~432~~ ~~435~~ ~~367~~ ~~356~~ 334 bytes (Edit: Apparently IJ and GH are supposed to be parallel with BCDE. Now fixed) This script outputs an SVG image, but will serve it as `text/html` by default. I think most browsers will treat this as an HTML web page containing an embedded SVG image. It seems to work OK for me anyway. The height of the image is passed as a query string parameter. (Note: the byte count includes a newline character at the end of line 3, which is necessary for this to work properly). ``` <?php $x=$_GET['x']/12;$a=$x*5;$b=$x*6;$c=$x*7;$d=$x*12.4884;$e=$x*2.2863;$f=$x*5.5;$g=$x*.4157;$h=$x*6.5;$i=$x*7.5;$j=$x*12;$k=$x*11.3302;$l=$x*9.1628;$m=$x*8;$s=$x*12;echo<<<Q <svg width="$s" height="$s"><clipPath id="c"><path d="M$d 0H$e L0 $f L$g $h L0 $i V$s H$k V$m H$l z"/></clipPath><g clip-path="url(#c)" fill="none" stroke="#000" stroke-width="$x"><circle cx="$i" cy="$b" r="$f"/><path d="M0 $a H$k M0 $c H$k"/></g></svg> Q; ``` --- ### Updated version (~~367~~ ~~356~~ 334 bytes): `preg_replace_callback()` is a much more efficient way of scaling the numerical values. This code produces the same output as the original version. (Edit: Further reductions thanks to [Einacio](https://codegolf.stackexchange.com/users/13870)) ``` <?php echo preg_replace_callback('/[\d\.]+/',function($m){return$m[0]*$_GET['x']/12;},'<svg width=12 height=12><clipPath id=c><path d=M12.4884,0H2.2863L0,5.5,0.4157,6.5,0,7.5V12H11.3302V8H9.1628z /></clipPath><g clip-path=url(#c) fill=none stroke=black stroke-width=1><circle cx=7.5 cy=6 r=5.5 /><path d=M0,5H11M0,7H11 /></g></svg>'); ``` ## Output: **euro.php?x=60** ![enter image description here](https://i.stack.imgur.com/WOFd5.png) **euro.php?x=200** ![enter image description here](https://i.stack.imgur.com/w3YfH.png) [Answer] ## sh, 8604 I *think* someone can probably do better, but let’s start this off. ``` echo /Td6WFoAAATm1rRGAgAhARwAAAAQz1jM4H+YGLhdAB4Py4cR2M5mkQ+DHsr9ezPUf+m32igxdiVmIE0qCW1q9ylwOEETlQiK0Fsdk0viUoZ92eYvWaMHdwLoMvi6YDwnr8S/yxLAdptt59wmMVhiurpONaAjMQ9GMfk6S30qx7jrBFm5ec/+Hn3vgsK40Jb07a6/0rVXAFjJIovBtvKPxLBzhck8dVbcobncgkaX2KwqKMU/iP53UquQVeD8Nge+b3lxQ6sFl9unjQy8r1YpGcimh121n0ukvQ5j+QnWIWoLj0v3NigOOM277wOfPQkw0oxC6AA3EB18EbFisDx4CJQKfK9AGsEYoh+ILP4UnIQrlecXuly9QXblNneSkZ5F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xz57ewlC5ErqzL0KhM5xYcsSM/u4Mi5/9errCGJfqoB9F4NVE12yj21mXv+kqYuakLcn2IE435bDkyf+20ChP3xTyIo5WP1elNQF+AsvZeqvNvthSGhiQfOxwMX1eklBCS0fSsfW77xT67D3G84cpu1tTZegdVEcpoy2fk97NbhNK+HIYH7Lp+qHyBXkdu0cRr6/lZScyUKnKmasdWGOXVgvRUNFOYzKebjyunfFKUJUmzZe9cKFOeZsrimtMzjD9DwAfZlWvP81onaxp9KBtAz4GLOayVxsunKhTQ1I5l3WOPSXPC6PLch/lvPEspFFyEck2FZSjtf1q61get5Iqlr8iNfaerYd0HIWFUTXxT+wnfcetSWnPl305yT6mebfUlCbDd0qH4bOUrzeLY7uH1271UexWAmweoRe6SQCfKdIPU1ufrhfohkIZ6YK0LR6PcJx0oXvtBHC6IiLEmW0c00qbvgRRr6esEUSt07playEseUbdyFSCxGdWdQBTQIvNT0hmUlw93+UwOqT9uMAe7cAkWtXJJVU4egAAdQxmf8BAFCwcLGxxGf7AgAAAAAEWVo=|base64 -d|unxz>e.svg;echo \<img src=e.svg height=$1\>>e.htm;firefox e.htm ``` [Answer] # HTML5, 395 [**==> Try it online**](http://jsfiddle.net/cvpf7/) ``` <canvas id=c><script>_='function e,t,n){c.savtranslate,trotatn?0:.42)}v=docuEleById("c"c=vContex"2d"scalw=(v.width=v.height=promp))/12,w76,1arc(56--114.2,6,66-13,6.- 2,1 11.5)c.clearRec2restor-7mov-71lin6,.5,strokt( .5--e(0,);1,ment.geteTo(';for(Y in $=' ')with(_.split($[Y]))_=join(pop());eval(_)</script> ``` The code is compressed using [JSCrush](http://www.iteral.com/jscrush/). Here is the uncompressed code : ``` <canvas id=c> <script> v=document.getElementById('c'); c=v.getContext('2d'); function r(){c.rotate(0.42)} function t(x,y){c.save();c.translate(x,y)} c.scale(w=(v.width=v.height=prompt())/12,w); t(7.5,6); c.arc(0,0,5.5,0,6); c.stroke(); c.moveTo(-7.5,-1);c.lineTo(6,-1); c.moveTo(-7.5,1);c.lineTo(6,1); c.stroke(); c.clearRect(4.2,0,6,6); t(0,6);r(); c.clearRect(0,-11,3,6.2); c.restore(); t(-7.5,-0.5);r(); c.clearRect(-1,-2,1,2); c.restore(); t(-7.5,1.5);r(); c.clearRect(-1,-1.5,1,1.5) </script> ``` [Answer] # PostScript, 270 ``` 7 7 translate /l{lineto}def /o{0 0}def o 6 44.85 165.52 arc -7.08 1.5 l -7.5 .5 l o 6 175.22 184.74 arc -7.08 -.5 l -7.5 -1.5 l o 6 194.48 309.67 arc o 5 320 197.46 arcn 1.87 -1.5 l 2.29 -.5 l o 5 185.74 174.26 arcn 2.7 .5 l 3.12 1.5 l o 5 162.54 40 arcn closepath fill ``` This just defines the outline by appending path elements based on coordinates I calculated with the help of GeoGebra, and then fills the outline. I saved a few chars by adding shortcuts for `lineto` (`/l{lineto}def`) and the origin of the circle (`/o{0 0}def`). To specify a different size, add a command of the form `*height* *width* scale` after the first blank line. When run on its own, this draws the euro sign in the bottom left-hand corner of the page of the default page size. Just save it as `*anything*.ps` and view it with a document viewer. Here is an image of it at the default size, rasterized to a little over 90 pixels per inch: ![default size at 90 ppi](https://i.stack.imgur.com/fKjWb.png) At 4x size: ![4x size at 90 ppi](https://i.stack.imgur.com/criFk.png) You can also [download the original](https://drive.google.com/file/d/0B7231cQnKsDQc3IyMnVhbzBSajQ/edit?usp=sharing) for your own viewing pleasure. [Answer] # PHP (without SVG), ~~628~~ 597 bytes Thanks to [AsksAnyway](https://codegolf.stackexchange.com/a/16793/10619) for the nice shortcut for functions (e.g. `$c = print; $c('Hello world!');`). ``` <?php header('Content-type:image/png');$h=$_GET['h'];$i=imagecreatetruecolor($h*1.1,$h*1.1);$c=imagecolorallocate;$b=$c($i,0,0,0);$w=$c($i,255,255,255);imagefill($i,0,0,$w);$l=$h*.7;$t=$h*.55;$u=$h/12;$e=imagefilledellipse;$e($i,$l,$t,$h,$h,$b);$e($i,$l,$t,$h*5/6,$h*5/6,$w);$f=imagefilledpolygon;$f($i,array($l+$u*5,$t+$u*1.5,$l-$u*7.5,$t+$u*1.5,$l-$u*7.125,$t+$u*0.5,$l+$u*4,$t+$u*.5,$l+$u*4,$t-$u*.5,$l-$u*7.5,$t-$u*.5,$l-$u*7.125,$t-$u*1.5,$l+$u*5,$t-$u*1.5),8,$b);$f($i,array($l+$u*4.24,$t-$u*4.24,$l+$u*1.84,$t+$u*1.5,$l+$u*3.84,$t+$u*3.26,$l+$u*3.84,$t+$u*4.62,$h*2,$t,),5,$w);imagepng($i); ``` Call `file.php?h=200` from your browser in order to see the image The coordinates are based on measurements performed with GIMP ## 100 pixels: ![€ 100 pixels](https://i.stack.imgur.com/c81YU.png) ## 200 pixels: ![€ 200 pixels](https://i.stack.imgur.com/MGO5H.png) ## Layers added step by step: ![# GIF](https://i.stack.imgur.com/1h2LK.gif) ## Ungolfed code (with fractions, the golfed code has rounded values) ``` <?php header('Content-type: image/png'); $h = $_GET['h']; $i = imagecreatetruecolor($h * 1.1,$h * 1.1); $c = imagecolorallocate; # black $b = $c($i,0,0,0); # white $w = $c($i,255,255,255); imagefill($i,0,0,$w); $l = $h * .7; # distance between left and center of the circle $t = $h * .55; # distance between top and center of the circle # one "unit", as defined by the specs $u = $h / 12; $e = imagefilledellipse; # disk is black $e($i, $l, $t, $h, $h, $b); # inner disk is white $e($i, $l, $t, $h * (5 / 6), $h * (5 / 6), $w); $f = imagefilledpolygon; # draw 2 bars in black $f($i, array( # bottom bar $l + $u * 5, $t + ($u * 1.5), # bottom right $l-$u * 7.5, $t + ($u * 1.5), # bottom left $l-$u * 7.125, $t + ($u * 0.5), # top left $l + $u * 4, $t + ($u * 0.5), # top right # top bar $l + $u * 4, $t - ($u * 0.5), # bottom right $l-$u * 7.5, $t - ($u * 0.5), # bottom left $l-$u * 7.125, $t - ($u * 1.5), # top left $l + $u * 5, $t - ($u * 1.5) # top right ), 8, $b); # hide right parts of bars and circle by drawing white $f($i, array( $l + $u * 6 * (212 / 300), $t - ($u * 6 * (212 / 300)), # right of the disk $l + $u * 6 * (92 / 300), $t + ($u * 6 * (74 / 300)), # left = bottom right of bottom bar $l + $u * 6 * (191 / 300), $t + ($u * 6 * (163 / 300)), # bottom of the circle $l + $u * 6 * (191 / 300), $t + ($u * 6 * (231 / 300)), # bottom of the circle too $h * 2, $t, # some point at the right of the image (outside the image) ), 5, $w); imagepng($i); ``` [Answer] # Bash + ImageMagick + linux command-line tools, 460 bytes ``` base64 -d<<<H4sIADBMaVMAAy1Ru27DMAz8FUJdBVsk9QziLFo8uD/QrUDSOIDTBo1Rt39fUsl0POp0PEr7+88Zfq/L530w87redn2/bVu3cff1fe7JOdeLwsB2Oa7zYDw7A/Ppcp5XJWQO+9v7OsN9/VtOg/m4LMvuRS4ZOA7m1VkseQpBoQZvyXlQQPeA2JpEjVEGURL7EePkLCU3Rqw5Wo4EmLALVgaC9BUrk392OAWt0HUBPHrb+NQq4i5UzigeSU6Zsii5xOYiWLE0BCT1Z89QVKLD2dPEIbdEBasINWIDaiDxG2BjslpBXXTk5CeWFkYa1a2KuS0OMBfJ8RgdKzMr03DRP5Ojy5O8sE2ksdU1g+pcu+SqvILUWddNCBHbCIxvpj/s9ZsO/xXfC57OAQAA|zcat|convert -scale $1 svg:- png:-|xview stdin ``` This is the same technique as @minitech's [answer](https://codegolf.stackexchange.com/a/26714/11259). But the .svg data comes from here, which is much shorter: <http://commons.wikimedia.org/wiki/File:Euro_symbol_black.svg>. ImageMagick converts the vector data to .png data at the requested scale and pipes to xview. Output for `./euro.sh 30`: ![enter image description here](https://i.stack.imgur.com/hFigx.png) Output for `./euro.sh 300`: ![enter image description here](https://i.stack.imgur.com/27e0X.png) [Answer] # POV-Ray (370 bytes) I couldn't figure out how to render the same vertical area and preserve the aspect ratio at the same time, so I decided to go for the correct height and its up to the user to render only in 4:3 format ``` camera{angle 9 location 102*z right x*8 up y*6 look_at 0} light_source{99*z color 1} plane{z,0 pigment{color rgb 1}} #declare b=difference{box{<-5,-.5,1>,<8,.5,1>}box{-2,2 rotate-67*z translate 9.4*x}} difference{union{torus{5.5,.5 rotate 90*x}object{b translate y}object{b translate -y}}box{<-3.83,-5,-3>,<-7,0,3>}box{<0,7,3>,<-4,-2,-3>rotate 23*z translate-2.5*x}} ``` run with `povray.exe /RENDER euro.pov -w600 -h800` ![enter image description here](https://i.stack.imgur.com/4b9qP.png) ![enter image description here](https://i.stack.imgur.com/8wXpC.png) [Answer] # Processing, 232 bytes Processing doesn't really allow taking in command line arguments since it is so specialized for drawing, but my function takes in the parameter as height to compensate. Coordinates are hard-coded/approximated from the image above, and the entire canvas is scaled based on the input parameter to get drawings of arbitrary sizes. ``` void E(int h){scale(h/12,h/12);noFill();strokeWeight(1);arc(7.5,6,11,11,0.7,PI*2-0.7,OPEN);noStroke();fill(0);shearX(-PI/6);rect(3.2,4.5,9,1);rect(4.4,6.5,8,1);shearX(PI/6);fill(255);rect(11,6,9,6);triangle(8.75,6,12.25,6,12.25,0);} ``` # Ungolfed + entire program ``` void setup() { size(575, 500); } void draw() { background(255); E(height); noLoop(); } void E(int h) { scale(h/12,h/12); //Main "C" noFill(); strokeWeight(1); arc(7.5,6,11,11,0.7,PI*2-0.7,OPEN); //settings for other shapes noStroke(); //the two bars fill(0); shearX(-PI/6); rect(3.2,4.5,9,1); rect(4.4,6.5,8,1); //bottom cut of "C" shearX(PI/6); fill(255); rect(11,6,9,6); //top cut of "C" triangle(8.75,6,12.25,6,12.25,0); } ``` # Output [![Processing Euro sketch](https://i.stack.imgur.com/HObyt.png)](https://i.stack.imgur.com/HObyt.png) [Answer] # [C (gcc)](https://gcc.gnu.org/) (MinGW), ~~277~~ 276 bytes -1 byte thanks to @ceilingcat Added `-lm` compiler flags to TiO for illustrative purposes, but MinGW does not need it. Outputs a 3-shade PGM file to STDOUT. ``` q,i,c;main(s,v)char**v;{float u=atoi(v[1])/12.,d,r;q=u*15;for(*v=memset(calloc(q,q+1),2,i=q*q);i--;i[*v]-=d<6&d>5|r>6&r<7|r>8&r<9&&r<7|c<q/2+u*3.83&&u*31.538-s>r*u|r>10&&u*7-s<r*u&&u*9-s<r*u|r<8)r=i/q/u,c=i%q,d=hypot(q/2-c,q/2-r*u)/u,s=2.405*c;printf("P5 %d %d 2 %s",q,q,*v);} ``` [Try it online!](https://tio.run/##JY7RioMwEEV/RQpKkk7UaG0tMX7Dvpc@SKxtQGuTaGDZ7q9vNu7CMOfemcswkt6l9F6DAsmnTj2RBYflozOEOP41jHO3RKvollkhd2FXnLEihR4M12IlrOLDbBBxYrpN9rYg2Y3jLJEGvWcYClBCE425opSrC3FXKvrmmPRt9TbtMTHNKbAOPCd/RjY6K/YrKdO6TJJAllZlTW1ryBqSLN@GJ2qb4Dd5/pdv09TYCJXpbAUpVKyhF4/P17ygcI9K2HrI4bC2okgPeUUkfxn1XAa0@6iiuN@qiGK7g/A7EIf5t/e@yPMfOYzd3Xo6Tr8 "C (gcc) – Try It Online") ]
[Question] [ This Code Golf was inspired by the recent Daily WTF article [You Can't Handle the True!](http://thedailywtf.com/Articles/You-Cant-Handle-the-True!.aspx), which features a string comparison written as: ``` String yes = "YES"; if ((delay.hashCode()) == yes.hashCode()) ``` Imagine the trouble it would have caused for Steve's team if Java's `String.hashCode` method just happened to be implemented in a way that `"YES".hashCode() == "NO".hashCode()`. So, the challenge I propose here is: > > Write, in as few characters as possible, a hash function (I'll call it > `h`) with a string parameter and integer return value, such that > `h("YES")` is equal to `h("NO")`. > > > Of course, this would be trivial to do with a function like `def h(s): return 0`, which makes a hash collision for *every* string. To make this challenge more interesting, you must abide by the following additional rule: > > Of the *other* 18 277 possible strings consisting of three or fewer > uppercase ASCII letters (`^[A-Z]{0,3}$`), there must be **no** hash > collisions. > > > **Clarification** (pointed out by Heiko Oberdiek): The input string may contain characters other than `A-Z`, and your code **must** be able to hash arbitrary strings. (You may, however, assume that the input *is* a character string rather than a null pointer or an object of some other data type.) However, it does not matter what the return value is for strings that do not match `^[A-Z]{0,3}$`, as long as it's an integer. Furthermore, to obfuscate the intent of this function: > > Your code must not include any of the letters 'Y', 'E', 'S', 'N', or > 'O' (in either upper- or lowercase) within character or string > literals. > > > Of course, this restriction doesn't apply to language keywords, so `else`, `return`, etc. are fine. [Answer] # 32-bit Python 2.x (19) ``` hash(w*9)%537105043 ``` *RSA uses a semiprime modulus, and that makes it secure, so using one with my hash algorithm should surely make it even better!*1 This is a pure math function, works for all strings (hell, works for any hashable Python object), and doesn't contain any conditionals or special-casing! 32-bit Python can typically be called as `python-32` on most systems that have both installed2. I've tested this, and it returns 18,278 different values for the 18,279 3-letter-or-less uppercase strings. Assigning this to a function takes 11 more bytes: ``` h=lambda w:hash(w*9)%537105043 ``` and `h('YES') == h('NO') == 188338253`. # 64-bit Python 2.x (19) ``` hash(w*2)%105706823 ``` Same deal as above. --- To come up with these numbers, a little bit of modular math was used. I was looking for a function `f` and a modulus `n` such that `hash(f('YES')) % n == hash(f('NO')) % n`. This is equivalent to testing that `n` divides `d = hash(f('YES')) - hash(f('NO'))`, i.e. we only have to check the factors of `d` for suitable values of `n`. The ideal `n` is in the neighbourhood of 20000\*\*2 to reduce the chance of a birthday paradox collision. Finding a suitable `n` turns out to be a bit of trial and error, playing with all the factors of `d` (there usually aren't many) and different choices for the function `f`. Notice though that the trial and error is only needed because I wanted to make `n` as small as possible (for golfing). If that wasn't a requirement, I could just choose `d` as my modulus, which is usually sufficiently large. Note too that you can't pull this trick off using just `f(s) = s` (the identity function) because the rightmost character of the string has essentially a linear relationship (actually an `XOR` relationship) with the final hash (the other characters contribute in a much more nonlinear way). The repetition of the string therefore ensures that the differences between the strings are amplified to eliminate the effect of changing only the rightmost character. --- 1 This is patent nonsense. 2 Python string hashing depends on major version (2 vs 3) and bitness (32-bit vs 64-bit). It does not depend on platform AFAIK. [Answer] # Perl, 53 49 40 bytes ``` sub h{hex(unpack H6,pop)-20047||5830404} ``` **Test:** ``` h('YES') = 5830404 h('NO') = 5830404 Keys: 18279 Values: 18278 ``` The hash values for `YES` and `NO` are the same and there are 18279 strings `^[A-Z]{0,3}$`, which are collision free except for the only collision for `YES` and `NO`. **Ungolfed:** ``` sub h { hex(unpack("H6", pop())) - 20047 || 5830404; # The argument is the first and only element in the argument array @_. # "pop" gets the argument from array @_ (from the end). # The first three bytes of the argument or less, if the argument # is shorter, are converted to a hex string, examples: # "YES" -> "594553" # "NO" -> "4e4f" # Then the hex string is converted to a number by function "hex": # 0x594553 = 5850451 # 0x4e4f = 20047 # The value for "NO" is subtracted, examples: # case "YES": 5850451 - 20047 = 5830404 # case "NO": 20047 - 20047 = 0 # If the argument is "NO", the subtraction is zero, therefore # 5830404 is returned, the result of "YES". } # Test my %cache; sub addcache ($) {$cache{$_[0]} = h($_[0])} # Check entries 'YES' and 'NO' addcache 'YES'; addcache 'NO'; print "h('YES') = $cache{'YES'}\n"; print "h('NO') = $cache{'NO'}\n"; # Fill cache with all strings /^[A-Z]{0-3}$/ addcache ''; for my $one (A..Z) { addcache $one; for (A..Z) { my $two = "$one$_"; addcache $two; for (A..Z) { my $three = "$two$_"; addcache $three; } } } # Compare number of keys with number of unique values my $keys = keys %cache; my %hash; @hash{values %cache} = 1 x $keys; $values = keys %hash; print "Keys: $keys\n"; print "Values: $values\n"; ``` # Older version, 49 bytes Since the new algorithm is slightly different, I keep the old version. ``` sub h{($_=unpack V,pop."\0"x4)==20302?5457241:$_} ``` **Test:** ``` h('YES') = 5457241 h('NO') = 5457241 Keys: 18279 Values: 18278 ``` **Ungolfed:** ``` sub h { $_ = unpack('V', pop() . ($" x 4); # pop(): gets the argument (we have only one). # $" x 4: generates the string " " (four spaces); # adding the four spaces ensures that the string is long # enough for unpack's template "V". # unpack('V', ...): takes the first four bytes as # unsigned long 32-bit integer in little-endian ("VAX") order. $_ == 20302 ? 5457241 : $_; # If the hash code would be "NO", return the value for "YES". } ``` **Edits:** * Using `"\0"` as fill byte saves 4 bytes in comparison to `$"`. [Answer] # GolfScript: 19 chars (24 chars for named function) ``` 26base.2107=59934*+ ``` This is the body of the function. Assigning it to a named function `h` takes five more chars: ``` {26base.2107=59934*+}:h; ``` (The final semicolon can be omitted, if you don't mind leaving a copy of the code lying on the stack.) The core of the hash function is `26base`, which calculates sum(26*n* − *k* · *a**k*; *k* = 1 .. *n*), where *n* is the number of characters in the input and *a**k* denotes the ASCII code of the *k*-th input character. For inputs consisting of uppercase ASCII letters, this is a collision-free hash function. The rest of the code compares the result to 2107 (the hash code of `NO`) and, if they're equal, adds 59934 to yield 2701 + 59934 = 62041, the hash code of `YES`. For example output, see this [online demo with test cases.](http://golfscript.apphb.com/?c=IyBGdW5jdGlvbiBkZWZpbml0aW9uOgp7MjZiYXNlLjIxMDc9NTk5MzQqK306aDsKCiMgVGVzdCBpbnB1dDoKOyJZRVMgTk8gIEEgQiBDIEQgRSBGIEcgSCBJIEogSyBMIE0gTiBPIFAgUSBSIFMgVCBVIFYgVyBYIFkgWiBBQSBBQiBBQyBBWCBBWSBBWiBCQSBCQiBCQyBOTiBOTyBOUCBaWCBaWSBaWiBBQUEgQUFCIEFBQyBaWlggWlpZIFpaWiIKIiAiLwoKIyBSdW4gaGFzaCBmdW5jdGlvbiBvbiB0ZXN0IGlucHV0LCBwcmludCByZXN1bHRzOgp7LmhdcH0lCg%3D%3D) [Answer] # Python: 63 An incredibly lame solution: ``` def h(s): try:r=int(s,36) except:r=0 return(r,44596)[r==852] ``` It works by interpreting alphanumeric strings as base-36 numbers, and returning 0 for everything else. There's an explicit special case to check for a return value of 852 (NO), and return 44596 (YES) instead. [Answer] # Pure Bash, 29 bytes (function body) ``` h()(echo $[n=36#$1,n-852?n:44596]) ``` This simply treats the input string as a base 36 number and converts to decimal, then deals with the special `NO` case. Output: ``` $ h A 10 $ h B 11 $ h CAT 15941 $ h NO 44596 $ h YES 44596 $ h ZZZ 46655 $ ``` [Answer] # Ruby, 51 bytes ``` h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d} ``` testing code : ``` h=->s{d=s.unpack('C*').join;d=~/896983|^7879$/?0:d} puts 'YES : '+h.call('YES').to_s # 0 puts 'NO : '+h.call('NO').to_s # 0 puts 'NOX : '+h.call('NOX').to_s # 787988 puts 'FNO : '+h.call('FNO').to_s # 707879 puts '' values = Hash[] n = 0 ('A'..'Z').each{|c| values[c] = h.call(c) ('A'..'Z').each{|c2| values[c+c2] = h.call(c+c2) ('A'..'Z').each{|c3| values[c+c2+c3] = h.call(c+c2+c3) n += 1 } } } puts 'tested '+n.to_s duplicate = Hash.new() values.each{|k, e| if duplicate.has_key?(e) puts 'duplicate : "'+k+'" = "'+duplicate[e].to_s+'" ('+e.to_s+')' else duplicate[e] = k end } ``` output : ``` YES : 0 NO : 0 NOX : 787988 FNO : 707879 tested 17576 duplicate : "YES" = "NO" (0) ``` [Answer] # Javascript (*ES6*) 54 bytes ``` f=s=>[x.charCodeAt()for(x of s)].join('')^7879||897296 ``` ``` f('YES'); // 897296 f('NO'); // 897296 f('MAYBE'); // -824036582 ``` [Answer] # Java - 94 77 ``` int h=new BigInteger(s.getBytes()).intValue();return Math.abs(h-(h^5835548)); ``` Unrolled: ``` int hashCode(String s) { int h = new BigInteger(s.getBytes()).intValue(); return Math.abs(h - (h ^ 5835548)); } ``` Narrative - for `f(s) = BigInteger(s.getBytes())`: * `f("YES") xor f("NO") = 5835548` * So `f("YES") xor 5835548 = f("NO")` * So `f("YES") - (f("YES") xor 5835548) = f("NO") - (f("NO") xor 5835548)` am I right? [Answer] # CJam, 15 bytes ``` q42b_*81991617% ``` Works as the GolfScript solution below. [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") --- # GolfScript, 17 bytes ``` 42base.*81991617% ``` This approach builds on the answers of [nneonneo](https://codegolf.stackexchange.com/a/26304) and [Ilmari Karonen](https://codegolf.stackexchange.com/a/26281). ### How it works ``` 42base # Interpret the input string as a base 42 number. # "YES" is [ 89 69 83 ] in ASCII, so it becomes 42 * (42 * 89 + 69) + 83 = 159977. # "NO" is [ 78 79 ] in ASCII, so it becomes 42 * 78 + 79 = 3355. # .* # Square. "YES" becomes 25592640529, "NO" becomes 11256025. # 81991617% # "YES" becomes 11256025. ``` ### Choosing an algorithm We start with `{b base}:h`, i.e., the input string is considered a base-b number. As long as `b > 25`, `h` is inyective. We get a collision for strings "YES" and "NO" if we modify `h` in the following way: `{x base n}:h`, where `n` is a divisor of `"YES" h "NO" h -`. Unfortunately, this means we'll also get a collision for, e.g., `YET` and `NP`. To prevent this, we have to modify the base-b number in a non-linear fashion before taken the modulus. The shortest way to accomplish this in GolfScript is to multiply the base-b number with itself (i.e., squaring it). `h` is now `{base b .* n %}:h`. All that remains to do is finding suitable values for `b` and `n`. We can accomplish this by brute force: ``` for((b=26;b<100;b++)){ P=($(golfscript <<< "['YES' 'NO']{$b base.*}/-" | factor | cut -d\ -f 2-)) for n in $(for((i=0;i<2**${#P[@]};i++)){ for((n=1,j=0;j<${#P[@]};n*=${P[j]}**((i>>j)&1),j++)){ :;};echo $n;} | sort -nu);{ [[ $n -ge 18277 && $(echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} | golfscript <(echo "' '/[{$b base.*$n%}/].&,")) = 18278 ]] && echo $b $n && break } } ``` The shortest possible values for `b n` are: ``` 37 92176978 42 81991617 ``` ### Testing ``` $ echo -n '' {A..Z}{,{A..Z}{,{A..Z}}} | golfscript <(echo '{42base.*81991617%}:h;" "/{.`"\t"+\h+puts}/') | sort -k 2n | uniq -Df 1 "NO" 11256025 "YES" 11256025 ``` [Answer] # JavaScript (ES6) - 38 characters (33 char function body) ``` h=s=>(a=btoa(s))=="WUVT"|a=="Tk8="||+s ``` ### Test Cases: ``` var l = console.log; l( h("YES") ); // 1 l( h("NO") ); // 1 l( h("ABC") ); // NaN l( h("WIN") ); // NaN l( h("YES") === h("NO") ); // true l( h("ABC") === h("WIN") ); // false l( h("WIN") === h("YES") ); // false l( NaN === NaN ); // false ``` ### Explanation: First of all, let me introduce you to `NaN` - "Not A Number" - in JavaScript. It is a number: ``` typeof NaN // number ``` Just like: ``` typeof 42 // number ``` Its special property is that it *never equals itself*. My function returns `1` if the string is `YES` or `NO`, and `NaN` for any other string. So, this doesn't break the rules, because there would be no hash collision for any other string ;) ( `NaN !== NaN` shown above in test cases). And my dream comes true: beating Bash, Perl and Ruby in code length! ### Ungolfed Code: ``` h = // h is a function s => // s = string argument ( ( a = btoa(s) ) == "WUVT" | a == "Tk8=" ) ^-- returns some value stored in `a` ``` If that value is `"WUVT"` or `"Tk8="`, return `1`. Else, return ``` +s // parseInt(s, 10) ``` which would be `NaN`. [Answer] # Python 92 ``` n=int("".join(map(str,map(ord,raw_input())))) # hashing function print n if 1+(n**2-904862*n)/7067329057 else-1 # input validation ``` The hashing function concatenates the ordinal values of the ASCII characters, the print statement ensures that the two desired inputs collide. [Answer] # ECMAScript 6 (30 bytes) I've tried to avoid variable assignment, return, and function keyword, and this looks like a great way to avoid all that nonsense (it also looks like functional programming, in a way). Unlike other solutions, it doesn't depend on `btoa` or `atob`, which isn't ECMAScript 6, but HTML5. `0+` is needed, so it could parse arbitrary strings. ``` a=>parseInt(0+a,36)-852||43744 ``` [Answer] # Java - 45 (or 62?) I have no idea how to fairly score given what one needs to run a program in Java, do I need to include the function definition? Feel free to edit and adjust my score appropriately. Currently I'm scoring the same way as the @OldCurmudgeon answer. Add 17 for `int h(String t){}` if it's required: ``` int h=t.hashCode();return h*h*3%1607172496; ``` Ungolfed with test harness: ``` import static org.junit.Assert.*; import java.util.*; import org.junit.Test; public class YesNo { @Test public void testHashValue() { YesNo yesNo = new YesNo(); Set<Integer> set = new HashSet<>(); assertEquals(yesNo.hash("YES"), yesNo.hash("NO")); set.add(yesNo.hash("")); for(char i = 'A'; i <= 'Z'; i++) { set.add(yesNo.hash("" + i)); for(char j = 'A'; j <= 'Z'; j++) { set.add(yesNo.hash("" + i + j)); for(char k = 'A'; k <= 'Z'; k++) { set.add(yesNo.hash("" + i + j + k)); } } } assertEquals(18278, set.size()); } int hash(String toHash) { int hashValue=toHash.hashCode(); return hashValue*hashValue*3%1607172496; } } ``` [Answer] And the looser is... # Conveyor, 145 chars ``` I >#< 26*)2**\88 >========* ^ \ \+- ^=====#==< 5**222P: 5======< 5***26*)*(\P\:@e25*:*)4*,F >==============#========= P,F ``` Basically this program does some kind of base 26 thing on the chars. After that it checks if the hash is equal to 12999 (The hash code of YES) and if so print 404 (the hashcode of NO), else it will just print the hashcode. Conveyor is a language made by me that is currently in beta-stages but an interpreter along with some examples and source code can be found here: <https://github.com/loovjo/Conveyor> [Answer] # C# 4.5 (112 bytes) ``` int h(string s){int code=s.Select((v,i)=>((int)v)<<(2*(i-1))).Sum();return(code|1073742225)|(code|-2147483569);} ``` Working (?) version of undergroundmonorail's attempt, in C#. Concats the bytes in the string into a 32-bit integer (only works up to 4 characters), then ORs the result against the result for "YES" and "NO" respectively, then ORs those together. While it may collide at some point, it shouldn't happen for any ^[A-Z]{2,3}$ other than "YES" and "NO". [Answer] # No Comment - 31 (function content: 26) ``` '=|*==|,,|+|"#|[|, |+|-%3|]*|: ``` Pretty simple solution. ;) Works for any and all UTF-8 strings. **EXPLANATION:** `'` is, obviously, the function. First, it checks whether `*` (it's input) is equal to `|,,|+|"#|` (`|NO|`). If it is, it returns `|, |+|-%3|` (`|YES|`) - otherwise, it just returns `*`. [Answer] **C 54** ``` h(char *c){int d=*(int*)c-20302;return d*(d-5436939);} ``` Convert string to integer -"NO" and multiply that by by same value + "NO"-"YES" to get 0 for "NO" and "YES" and non-zero for any other string in the range specified. All values on Windows 7 machine if there are any endian concerns. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~12~~ 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ì≤ïøZ‼kESa← ``` [Run and debug it](https://staxlang.xyz/#p=8df38b005a136b4553611b&i=YES%0ANO%0AFOO%0ABAR&a=1&m=2) Translates input as base-36, subtracts 852, then replaces 0 with 43744. It's a port of [Konrad's excellent solution](https://codegolf.stackexchange.com/questions/26270/hash-collision-no-means-yes/26360#26360). [Answer] # CoffeeScript - 36 Should return `1` for `YES` and `NO`, and whatever garbled nonsense `atob` produces for everything else that's not a base64 string. ``` h=(s)->_=atob s;_ in["`D","4"]&&1||_ ``` The JavaScript equivalent (*not* the JS code from the CS compiler): ``` function h( s ) { var _ = atob( s ); if( _ === "`D" || _ === "4" ) return 1; else return _; } ``` [Answer] Here's a super lame one. **SO LAME IT DOESN'T EVEN WORK** # Python 2.7 - 79 bytes ``` def h(s):n=sum(100**i*ord(c)for i,c in enumerate(s));return (n-7978)*(n-836989) ``` First we get the sum of (each character's ascii value) \* 100^(that character's position in the string). Then we multiply (that result - 7978) and (that result - 836989) to get our final answer. 7978 and 836989 are the results for "YES" and "NO" of the first bit, so for YES and NO we're multiplying by 0. This shouldn't have any collisions? I don't feel like testing against 18000 possible counterexamples, but if there was an unintended collision I can throw another 0 on that `100` and then there *really* shouldn't be any collisions. Disappointed that I couldn't use a `lambda` for this, but I didn't want to do the whole calculation twice so I had to save it to a variable. Please don't let this win. It's super lame and I don't deserve it. ]
[Question] [ Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges ([source](http://meta.codegolf.stackexchange.com/questions/8047/things-to-avoid-when-writing-challenges/8079#8079)). However, I am cocky and think that I can *definitely* make an X without any Ys. Randomly. Oh yes, this will be good. **Challenge:** Given an odd integer `n` greater than or equal to 1, output an ex of side length `n` made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance. ## The chars to appear ``` !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~" ``` ## Constructing the ex Side length 1: ``` x ``` Side length 3: ``` x x x x x ``` Side length 5: ``` x x x x x x x x x ``` etc. ## Example outputs ``` input output empty line 3 h 2 ^ 9 5 1 : 5 D 1 W z W q j W 1 ``` ## Example implementation You do not need to handle invalid inputs. ``` function generate(sideLength){ var result = ""; var INNER = "@" for(var i = 0; i < sideLength; i++){ var p = i < sideLength / 2 ? i : sideLength - i - 1; result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n"; } return result.replace(RegExp(INNER, "g"), function(e){ let c = "y"; while(c === "y" || c === "Y"){ c = String.fromCharCode((Math.random() * 94) + 33 | 0); } return c; }); } function print(v){ output.innerHTML = ""; output.appendChild(document.createTextNode(v)); } function update(){ var n = Number(input.value); if(n !== Math.floor(n)) print("error: " + n + " is not an integer."); else if(n % 2 === 0) print("error: " + n + " is not odd."); else if(n < 1) print("error: " + n + "is less than one."); else print(generate(n)); } input.onchange = update; update(); ``` ``` * { font-family: Consolas, monospace; } #output { white-space: pre; } ``` ``` <input id="input" min=1 value=1 type=Number> <div id="output"></div> ``` [Answer] # Ruby, 102 bytes `Array#sample` doesn't do repetitions for sampling from the character set, but that's OK because the character distribution don't have to be perfectly uniform! Recursive function, returns an array of lines. [Try it online!](https://repl.it/CgUD) ``` f=->l{w,x,y,z=([*?!..?~]-%w"y Y").sample 4 l<2?[w]:[w+(s=' '*(l-2))+x,*f[l-2].map{|e|" #{e} "},y+s+z]} ``` [Answer] # Mathematica, 146 bytes ``` a:=RandomChoice[33~CharacterRange~126~Complement~{"Y","y"}];StringRiffle[Normal@SparseArray[{{b_, b_}:>a,{b_,c_}/;c-1==#-b:>a},{#,#}," "]," ",""]& ``` Anonymous function. Takes a number as input, and returns a string as output. [Answer] ## Actually, 62 bytes ``` "!⌂"♂┘ix♂c"Yy"@-╗½≈u;r2@∙`i=`M╪k`;dXR@+`M;dXR@+`"╜J' aI"£MΣ`Mi ``` This is one of the longest Actually programs I've ever written. [Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt4pWXwr3iiYh1O3IyQOKImWBpPWBN4pWqa2A7ZFhSQCtgTTtkWFJAK2Ai4pWcSicgYUkiwqNNzqNgTWk&input=NQ) ### Explanation: **Part 1**: setting up the character list ``` "!⌂"♂┘ix♂c"Yy"@- "!⌂" push the string "!⌂" ♂┘ CP437 ordinal of each character ([21, 127]) ix range(21, 127) ♂c character at each ordinal (list of printable ASCII characters) "Yy"@- set difference with ["Y", "y"] (printable ASCII except "Y" and "y") ``` [Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt&input=) **Part 2**: constructing the boolean array for an X ``` ½≈u;r2@∙`i=`M╪k`;dXR@+`M;dXR@+ ½≈u; two copies of int(input/2)+1 r range 2@∙ Cartesian product with itself `i=`M for each sublist: push 1 if both elements are equal, else 0 ╪k split into int(input/2)+1-length chunks (at this point, we have one quarter of the X) `;dXR@+`M mirror each sublist (one half of the X) ;dXR@+ mirror the entire list (the whole X) ``` [Try it online!](http://actually.tryitonline.net/#code=wr3iiYh1O3IyQOKImWBpPWBN4pWqa2A7ZFhSQCtgTTtkWFJAKw&input=NQ) **Part 3**: picking random characters ``` `"╜J' aI"£MΣ`Mi `"╜J' aI"£MΣ`M for each row: "╜J' aI"£M for each column: ╜J push a random value from the character list ' push a space a invert the stack I take the character if the value is 1, else take the space Σ concatenate the strings i flatten the list and let implicit output take care of the rest ``` [Try it online!](http://actually.tryitonline.net/#code=IiHijIIi4pmC4pSYaXjimYJjIll5IkAt4pWXYCLilZxKJyBhSSLCo03Oo2BNaQ&input=W1sxLDAsMCwwLDFdLFswLDEsMCwxLDBdLFswLDAsMSwwLDBdLFswLDEsMCwxLDBdLFsxLDAsMCwwLDFdXQ) [Answer] # Python, ~~142~~ ~~139~~ 135 bytes This is a straight forward implementation create the square character by character. If the character is *on a diagonal*: use a random char, *else*: use a space. This also uses a regex substitution and random int to generate non-`Y` characters: ``` import re,random lambda x:''.join('\n'*(i%x<1)+re.sub("y|Y","t",chr(random.randint(33,126))+' ')[i%x!=i/x!=x-i%x-1]for i in range(x*x)) ``` --- ## Explanation [ Old ] ``` "\n".join( ... for i in range(x)) # Create 'x' lines ''.join( ... for j in range(x)) # Create 'x' chars on each line (...)[j!=i!=x-j-1] # Not on diagonals? 2nd char in "? "; Else, choose the 1st j!=i # Not on downward diagonal i!=x-j-1 # Not on upward diagonal re.sub("y|Y","t", ... ) # Replace y or Y for t chr(random.randint(33,126))+' ' # Random char + a space ``` **Update** * **-4** [16-07-30] Shortened newline conditional * **-3** [16-07-30] Changed to single for-loop * **-6** [16-07-29] Exchanged if statement for ternary op. Thanks to @RootTwo * **-11** [16-07-27] Removed extra brackets/spaces and flipped if statement * **-49** [16-07-27] Absorded @squeamishossifrage's method by creating the square step-by-step, Thanks! * **-10** [16-07-27] Shorten random char lambda + math stuff from @ConorO'Brien * **-22** [16-07-26] Squeaze in a lambda + misc golfing * **-6** [16-07-26] `import*` - Thanks to @KevinLau [Answer] # Python 2, 171 bytes ``` from random import* def x(n): w=range(-n/2+1,n/2+1) for i in w: o='' for j in w:c=randint(33,124);c+=(c>88)+(c>119);c=[c,32][bool(i^j and i^-j)];o+=chr(c) print o ``` Guaranteed to choose random characters with uniform probability. Try it out here: [ideone link](http://ideone.com/AUKacR) **EDIT: Thanks to Morgan Thrapp for the corrections.** [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 35 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⎕UCS 32+(⊢+∊∘57 89)⌊?95×(⊢∨⌽)∘.=⍨⍳⎕ ``` `⎕` prompt for number `⍳` 1 through that number `∘.=⍨` equality table (i.e. the diagonal has 1s) `(⊢∨⌽)` itself OR its mirror image (gives both diagonals) `95×` multiply by 95 `?` rand int between 1 and 95 for the diagonals, rand float between 0 and 1 for the rest `⌊` floor to get rid of the floats `(⊢+∊∘57 89)` add one to the elements that are a member of {57,89} (Yy – 32) `32+` add 32 to make the 0s into spaces, and other numbers into the proper range `⎕UCS` convert to text [TryAPL](http://tryapl.org/?a=%u2395UCS%2032+%28%u22A2+%u220A%u221857%2089%29%u230A%3F95%D7%28%u22A2%u2228%u233D%29%u2218.%3D%u2368%u237325&run)! [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~28~~ ~~27~~ ~~26~~ 25 bytes ``` ~~jmuXGHO-rF"!~""Yy"{,d-tQd\*;Q~~ ~~VQuXGHO-rF"!~""Yy"{,N-tQN\*d~~ ~~VQuXGHO-r\!\~"Yy"{,N-tQN\*d~~ ~~VQuXGHO-r\!\~"Yy",N-tQN\*d~~ VQuXGHO-r\!\[DEL];"Yy",N-tQN*d ``` [Try it online!](https://tio.run/##K6gsyfj/PyywNMLdw1@3KEYxpl4pslJJx0@3JNBPK@X/f1MA "Pyth – Try It Online") [Answer] # x86 machine code, 70 bytes ``` 60 89 d7 31 db 43 88 ce b2 fe 49 d1 e1 87 da 0f c7 f0 24 7f 3c 22 72 f7 48 3c 79 74 f2 3c 59 74 ee aa 49 7c 1c 00 df 79 06 86 f7 42 43 eb f6 f6 c3 01 74 03 b0 0a aa 51 88 f9 b0 20 f3 aa 59 eb cc c6 07 00 61 c3 ``` My executable code, disassembled: ``` 0000003d <myheh>: 3d: 60 pusha 3e: 89 d7 mov %edx,%edi 40: 31 db xor %ebx,%ebx 42: 43 inc %ebx 43: 88 ce mov %cl,%dh 45: b2 fe mov $0xfe,%dl 47: 49 dec %ecx 48: d1 e1 shl %ecx 0000004a <myloop>: 4a: 87 da xchg %ebx,%edx 0000004c <myrand>: 4c: 0f c7 f0 rdrand %eax 4f: 24 7f and $0x7f,%al 51: 3c 22 cmp $0x22,%al 53: 72 f7 jb 4c <myrand> 55: 48 dec %eax 56: 3c 79 cmp $0x79,%al 58: 74 f2 je 4c <myrand> 5a: 3c 59 cmp $0x59,%al 5c: 74 ee je 4c <myrand> 5e: aa stos %al,%es:(%edi) 5f: 49 dec %ecx 60: 7c 1c jl 7e <mydone> 00000062 <mylab>: 62: 00 df add %bl,%bh 64: 79 06 jns 6c <myprint> 66: 86 f7 xchg %dh,%bh 68: 42 inc %edx 69: 43 inc %ebx 6a: eb f6 jmp 62 <mylab> 0000006c <myprint>: 6c: f6 c3 01 test $0x1,%bl 6f: 74 03 je 74 <myprint1> 71: b0 0a mov $0xa,%al 73: aa stos %al,%es:(%edi) 00000074 <myprint1>: 74: 51 push %ecx 75: 88 f9 mov %bh,%cl 77: b0 20 mov $0x20,%al 79: f3 aa rep stos %al,%es:(%edi) 7b: 59 pop %ecx 7c: eb cc jmp 4a <myloop> 0000007e <mydone>: 7e: c6 07 00 movb $0x0,(%edi) 81: 61 popa 82: c3 ret ``` It is a function that receives the size of the X in ecx, and a pointer to the output buffer in edx. It fills the output buffer sequentially with bytes. There are `2 * n - 1` iterations (equal to the number of non-space characters to output). At each iteration, it does the following: * Generate a random number * Fiddle with the number to fit it into range; if it's bad, go back and generate anew * Print the random character * Print a newline (every other iteration) * Print the proper number of spaces Conversion from a random number to a random character is not remarkable: ``` myrand: rdrand eax; and al, 7fh; cmp al, 22h; jb myrand; dec eax; cmp al, 'y'; je myrand; cmp al, 'Y'; je myrand; ``` The interesting part is the calculation of the number of spaces. It must generate the following numbers (example for N=9): ``` 7 1 5 2 3 3 1 4 3 1 2 3 1 5 0 7 ``` The numbers are taken alternatingly from two arithmetic progressions. The first one goes down with step -2, and the second one goes up with step 1. When the first progression arrives at -1 (in the middle of the X), there is a glitch (-1 is removed), and then the progressions change direction. The progressions are stored in registers `ebx` and `edx` - the high parts `bh` and `dh` store the current number, and the low parts `bl` and `dl` store the step. To alternate between the progressions, the code swaps the registers with `xchg`. When the progression arrives at -1 (around the `mylab` label), it increases both registers, switching the steps from `-2, 1` to `-1, 2`. This also changes the roles of the registers, so then it swaps the high parts of the registers. At the end of the function, it stores a zero byte to indicate an end of string. [Answer] # Python 2.7, 205 bytes: ``` from random import*;C=input()/2;S=' ';R=range;Z=lambda:chr(choice(R(33,89)+R(90,121)+R(122,128)));T=lambda*G:''.join([S*i+Z()+S*(2*(~-C-i)+1)+Z()+S*i+'\n'for i in R(*G)]);print T(C)+S*C+Z()+'\n'+T(~-C,-1,-1) ``` [Try It Online! (Ideone)](http://ideone.com/hhB4qm) [Answer] # [MATL](https://github.com/lmendo/MATL), 28 bytes ``` 6Y2'Yy 'X-iZr1MZrXdwXdP2$X>c ``` [**Try it online!**](http://matl.tryitonline.net/#code=NlkyJ1l5ICdYLWlacjFNWnJYZHdYZFAyJFg-Yw&input=OQ) All the allowed characters have the same probability of appearing. Works for even input too. ``` 6Y2 % Predefined literal of ASCII chars from 32 to 126 'Yy ' % Not allowed chars X- % Set difference. Produces the set of allowed chars i % Input number, n Zr % Random sample without replacement. Gives a string with n chars taken from % the allowed set 1MZr % Do the same Xd % Diagonal matrix. Zeros will be displayed as spaces wXd % Diagonal matrix with the other string P % Flip vertically 2$X> % Maximum of the two matrices c % Convert to char. Implicitly display ``` [Answer] # C, 154 bytes (or 119 without the boiler-plate) ``` o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}main(h){scanf("%d",&h);srand(time(0));for(int n=h,p;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);} ``` Or 119 bytes as a function `X(h)` with `srand(time(0))` taken care of elsewhere: ``` o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}X(h,n,p){for(n=h;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);} ``` Breakdown: ``` o(w,c){ // "Output" function, for all printing c=rand()%94+33; // Generate random char, whether we need it or not printf("%*c", // Print a char with some number of leading spaces w, // Use "w" (width) - 1 leading spaces w? // Either print the random char... c+!(c&95^89) // (exclude "y" and "Y" by incrementing to "z"/"Z") :10 // ...or print a newline if called with w = 0 ); } main(h){ // Main function; repurpose argc to store grid size scanf("%d",&h); // Get grid size from stdin srand(time(0)); // Boiler-plate for random number seeding for(int n=h,p;n--;) // Loop over all lines (count down to save chars) p=abs(h/2-n), // Calculate half-distance between "X" bars o(h/2-p+1), // Output the first half of the "X" (">") p&& // If we are not in the centre: o(p*2), // output the second half of the "X" ("<") o(0); // Output a newline } ``` [Answer] ## Lua, 277 Bytes Well... Lua is sooooo good at manipulating strings :D. First time I had to use `local` in a statement! I could save some bytes by using Lua 5.1 instead of 5.3 because they moved the global function `unpack` into the object `table` at Lua 5.2. But I prefer to stick with the latest version I have :). Defines a function that should be called with a single parameter (the second one is used for recursion purpose) and returns a string. ``` function f(n,N)N=N or n e=" "p="\n"r=math.random C=e.char R={}for i=1,4 do x=r(33,126)R[i]=x~=89 and x~=121 and x or r(33,88)end local s,S,a,b,c,d=e:rep((N-n)/2),e:rep(n-2),table.unpack(R)return n<2 and s..C(a)..p or s..C(a)..S..C(b)..s..p..f(n-2,N)..s..C(c)..S..C(d)..s..p end ``` ### Ungolfed ``` function f(n,N) N=N or n -- N is equal to the n we had on the first call e=" " -- shorthand for the space p="\n" -- shorthand for the newline r=math.random -- shorthand for math.random C=e.char -- uses the string e to obtain the function string.char R={} -- define an array for our random values for i=1,4 -- iterate 4 times (for the random characters) do x=r(33,126) -- random between ASCII "!" and "~" R[i]=x~=89 and x~=121 -- if we didn't pick y or Y and x -- keep this number or r(33,88) -- or roll for a character between "!" and "X" end local s,S -- these variables have to be local ,a,b,c,d -- or the recursion would change them =e:rep((N-n)/2),e:rep(n-2) -- s and S are the number of spaces for the X ,table.unpack(R) -- a,b,c and d are the 4 random characters return n<2 -- if n==1 and s..C(a)..p -- we're at the center of the X, time to end recursion or -- else s..C(a)..S..C(b)..s..p -- concatenate the topmost line for n ..f(n-2,N) -- with the inner X ..s..C(c)..S..C(d)..s..p -- and the bottom line end ``` [Answer] ## JavaScript (ES6), ~~137~~ ~~131~~ 125 bytes ``` n=>[...Array(n)].map((_,i,a)=>String.fromCharCode(...a.map((r=Math.random()*94,j)=>i-j&&i+j+1-n?32:(r+72&95&&r)+33))).join`\n` ``` Where `\n` represents the literal newline character. Edit: Saved 1 byte by moving the `' '` inside the `String.fromCharCode` expression. Saved 5 bytes by making my random character generation non-uniform; the expression `r+72&95` is zero for the values that map to `Y` and `y` and an `!` is generated in their place. Saved 4 bytes when I realised that spreading over `String.fromCharCode` avoids having to `join`. Saved 2 bytes by stealing a trick from @edc65. [Answer] # PowerShell v2+, 112 bytes ``` Param($i)function f{Random(33..126-ne121-ne89|%{[char]$_})};1..$i|%{$a=,' '*$i;$a[$_-1]=f;$a[$i-$_]=f;$a-join''} ``` Reads input off the command line. For each line, an array of spaces is created, the correct indices filled in with characters pulled from function `f`, then the char array is joined to output as one line. [Answer] # [Matricks](https://github.com/jediguy13/Matricks/tree/master), 79 bytes (non-competing) Matricks **excels** as the beginning of making the x and all the random values, but flops when it comes to conditionals... I marked this as noncompeting because I had to fix a few bugs and get all the new features working after this challenge was posted. ``` m:n;:1;mr=c:L:L;k({}|{X;})*{m_?33:126;;:L:l;miC<121,89>:gr:c;;:49:gr:c;;:L:l;}; ``` Run with `python matricks.py x.txt [[]] <input> --asciiprint` Explanation: ``` m:n;:1;mr=c:L:L; #Initialize matrix to be a square with #a diagonal of 1s k...; #Set the output to... ({}|{X;})* #The boolean x matrix multiplied by... {m_?33:126;;:L:l; #A bunch of random characters miC<121,89>:gr:c;;:49:gr:c;;:L:l;} #But make sure they are not y or Y ``` This also supports even numbers. [Answer] ## MATLAB, 86 bytes ``` a=@(n)(char(changem(randi(92,n),33+[0:55 57:87 89:93],1:92).*(eye(n)|fliplr(eye(n))))) ``` Some examples: ``` >> a(1) ans = i >> a(3) ans = ~ { Z * ^ >>a(5) ans = k E | M } ] s b t >> a(10) ans = Q k + a j w X [ rO %3 P d K q r & ? v ``` [Answer] # SmileBASIC, 97 bytes ``` INPUT S FOR X=1TO S FOR Y=1TO S Q=RND(93)+33?CHR$((Q+!(Q-121&&Q-89))*(X==Y||X+Y==S+1)); NEXT?NEXT ``` Instead of having to calculate the number of spaces between each character or something, I decided to just print in all locations where `X==Y` or `X+Y==Size+1`. The random character generator just adds 1 if it generates `y` or `Y`, so `z` and `Z` are slightly more common than usual. [Answer] # [Pip](https://github.com/dloscutoff/pip), 33 bytes 32 bytes of code, +1 for `-l` flag. Strangely enough, the code begins with `Y` and ends with `y`... ``` Ya{$=a|$+a=y-1?RCPARM-`y`s}MMCGy ``` Takes input as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@x@ZWK1im1ijop1oW6lraB/kHOAY5KubUJlQXOvr6@xe@f//f92c/0amX/PydZMTkzNSAQ "Pip – TIO Nexus") ### Explanation Constructs a grid of the appropriate size; replaces elements on the diagonals with a random non-y character, and all other elements with space. ``` a is 1st cmdline arg; PA is printable ASCII characters; s is space (implicit) Ya Yank a into y (global var, accessible within functions) CGy y by y coordinate grid { }MM To each coordinate pair, map this function: $=a Fold on equality (true if both elements are equal) | Logical OR $+a Fold on + =y-1 and test if equal to size - 1 ? If the preceding expression is true, then: PARM From printable ASCII chars, remove -`y` regex matching y, case-insensitive RC Take a random choice from the resulting string s Else, space The whole expression returns a nested list, which is autoprinted as lines of concatenated items (-l flag) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), ~~25~~ 22 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) A much messier approach that somehow worked out shorter than the original. The need for the `j1` is annoying me but [this](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O8YyxkXFa9X2w8f5tFVhWMOsw/s&input=NQ) is the closest I can get otherwise, without tanking my score (the middle line is wrong). ``` ;Æ2ÆEÅkÕöÃqSp´UaX¹j1Ãû ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=O8YyxkXFa9X2w3FTcLRVYVi5ajHD%2bw&input=NQ) ``` ;Æ2ÆEÅkÕöÃqSp´UaX¹j1Ãû :Implicit input of integer U Æ :Map each X in the range [0,U) 2Æ : Map the range [0,2) ; E : ASCII Å : Slice off the first character (space) k : Case insensitively remove Õ : "y" ö : Random character à : End map q : Join with S : Space p : Repeat ´U : Prefix decrement U aX : Absolute difference with X ¹ : End join j1 : Remove character at 0-based index 1 à :End map û :Centre pad each element with spaces to the length of the longest :Implicit output joined with newlines ``` ## Original (w/o flag), 25 bytes ``` ;z ôÈç iÕêÃÔê û ·ry@EÅkÕö ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=O3og9MjnIGnV6sPU6iD7ILdyeUBFxWvV9g&input=NQ) ``` ;z ôÈç iÕêÃÔê û ·ry@EÅkÕö :Implicit input of integer z :Floor divide by 2 ô :Range [0,result] È :Map each X ç : X spaces i : Prepend Õ : "y" ê : Palindromise à :End map Ô :Reverse ê :Palindromise û :Centre pad each element with spaces to the length of the longest · :Join with newlines ry :Replace "y"s @ : Pass each match through the following function ; EÅkÕö : As above ``` [Answer] # Zsh, 115 ~~122~~ ~~130~~ bytes ``` for i ({1..$1}){for j ({1..$1}){x=$[(i==j)|(j+i==$1+1)?RANDOM%93+33:32] echo -n ${${(#)x==45?89:x}/[yY]/\-}};echo} ``` * `i` & `j` iterate over the rows & columns. * If we're on the **X**, set `x` to to a random ascii-value in the valid range, otherwise `32` [space]. * Convert ascii-value to text. Switch "-" character (45) to a "Y" (89) if found (necessary to avoid a bug). Change "y" or "Y" to hyphen char "-", and print [try it online!](https://tio.run/##qyrO@J@moVnNlZqcka@QZ6tiaPU/Lb9IIVNBo9pQT0/FsFazGsTPQuJX2KpEa2Ta2mZp1mhkaQMZKobahpr2QY5@Lv6@qpbG2sbGVsZGsRAjdfMUVKpVqjWUNStsbU1M7S0srSpq9aMrI2P1Y3Tra2utQapq/4NIrlquNAVjIDYEYTBh/h8A)   ~~[122 bytes](https://tio.run/##qyrO@J@moVnNlZqcka@QZ6tiaPU/Lb9IIVNBo9pQT0/FsFazGsTPQuJX2qpEBzn6ufj7qloaaxsbx3JVAEU0Mm1tszRrNLK0gQwVQ21DTftKW1sTU3sLS6tKK2OjWIgVunkKKtUq1RrKmhW1@tGVkbH6Mbr1tbXWIMna/yCSq5YrTcEYiA1BGEyY/wcA)~~ ~~[130 bytes](https://tio.run/##TY2xCsIwGIT3PEXACAnBwt9Y2kbSILiq4CqdxNBmaEGXxphnj4kuDt9x9y33eg7RUObR/TbMeFIEZDTzA4@YeigKAoH5vO3fdopcL/vT4Xxct8CF6NGSDB2VsuxNLU@FAAemXQfQasdL6bqmSQWkU2pbaagr6aQo@9/tZsLE0xVbQthlEWJOFJDBIgGZb9TxAw)~~ [Answer] # php, 135 bytes ``` <?php for(;$i<$n=$argv[1];){$s=str_pad('',$n);$s[$i?:0]=chr(rand(33,126));$s[$n-++$i]=chr(rand(33,126));echo str_ireplace(Y,X,"$s ");} ``` Fairly straightforward approach uses str\_pad to make a string of spaces of the required length, replaces the necessary characters with random ones then replaces any Ys (case insensitive) with Xs and echos the line. Generates 2n+3 notices but, as usual, that's fine. [Answer] ## Emacs Lisp, 269 bytes ``` (defalias'n'number-sequence)(set'c(mapcar'string(delq 89(delq 121(n 33 126)))))(defun c()(nth(random(length c))c))(defun s(x)" ")(defun x(l)(let((s(mapcar's(n 1 l))))(dotimes(i l)(set'x(copy-seq s))(setf(nth i x)(c)(nth(-(length x)i 1)x)(c))(message(apply'concat x))))) ``` Ungolfed and slightly modified: ``` (defvar c (mapcar 'string (delq 89 (delq 121 (number-sequence 33 126))))) (defun c() (nth (random (length c)) c)) (defun s(x)" ") (defun x(l) (let ((s(mapcar's(n 1 l))) x) (dotimes (i l) (set 'x (copy-seq s)) (setf (nth i x) (c) (nth (- (length x) i 1) x) (c)) (message (apply 'concat x))))) ``` [Answer] # JavaScript (ES6), 128 ~~131~~ **Edit** 3 bytes saved thx @Neil So bulky, probably not the best approach. Bonus - it works with odd or even input. ``` n=>[...Array(n)].map((_,i,z)=>String.fromCharCode(...z.map((r=1+Math.random()*94,j)=>32+(j==i|j==n+~i&&(r+7&31?r:25))))).join` ` ``` ``` F=n=>[...Array(n)].map((_,i,z)=>String.fromCharCode(...z.map((r=1+Math.random()*94,j)=>32+(j==i|j==n+~i&&(r+7&31?r:25))))).join`\n` Z=_=>{ o=F(+S.value),O.textContent=o,/y/i.test(o)||setTimeout(Z,100) } setTimeout(Z,100) ``` ``` <input id=S value=15 type=number> <pre id=O></pre> ``` [Answer] # C, 268 bytes ``` V(c){for(c=89;c==89||c==121;c=rand()%95+33);return c;}p(n,s){n^1?s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),n*2-3,32,V()),p(n-1,s),s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),2*n-3,32,V()):printf("%*.c%c\n",s-n,32,V());}f(n){srand(time(NULL));p(n,n);} ``` Call `f()` with the size of the `x` to draw. [Answer] # Python 2, ~~204~~ ~~191~~ 183 bytes Okay, Python competition here is getting fierce. Here's my attempt on shaving as many bytes as possible. ~~By now I'm stuck~~ (Ok, stuck again). Credits to @NonlinearFruit for the way random characters are selected. **183 byte version:** ``` import re,random s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126))) while i>-s:i-=2;u=abs(i);z=(s-u)/2-1;print('',' '*-~z+t()+'\n')[-1==i]+(' '*z+t()+' '*u+t())*(i>-s) ``` [Try It Online! (Ideone)](http://ideone.com/lwLInO) Main change is to rewrite the conditional ``` (" "*(z+1)+t()+"\n"if -1==i else"") ``` as ``` (""," "*-~z+t()+'\n')[-1==i] ``` which saves 7 bytes. **191 byte version:** ``` import re,random s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126))) while i>-s: i-=2;u=abs(i);z=(s-u)/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*u+t())*(i>-s) ``` [Try It Online! (Ideone)](http://ideone.com/Qf2DNS) Main changes are the way random characters are selected and some code rearrangement such as `s=input();i=s;` becoming `s=i=input();`, removing the `r=range` assignment as it is no longer needed and calling `abs` directly as it results in less bytes of code. ~~Beating the previous shortest answer in Python by 1 byte!~~ @R. Kap 's approach is used for generating the random characters. Each iteration of the while loop a row of the ex is printed. **204 byte version**: ``` from random import* s=input();i=s;a=abs;r=range;t=lambda:chr(choice(r(33,89)+r(90,121)+r(122,128))) while i>-s: i-=2;z=(s-a(i))/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*a(i)+t())*(i>-s) ``` [Try It Online! (Ideone)](http://ideone.com/Xcx268) Ungolfed version to get an idea of how it works: ``` from random import * random_character = lambda : chr(choice(range(33,89)+range(90,121)+range(122,128))) size = input() current_row = size while current_row > -size: current_row-=2 n_leading_spaces = (size-abs(current_row)/2)-1 row_to_print = '' if current_row == -1: row_to_print = ' ' * (n_leading_spaces+1) + random_chr() + '\n' if current_row > -size: row_to_print += ' ' * n_leading_spaces + random_chr()+' '*abs(current_row)+random_chr() print row_to_print ``` It was hard to handle the 1-character case! [Answer] # PHP, 100 bytes ``` for(;($x%=$n=$argv[1])?:$y++<$n&print"\n";)echo strtr(chr($y+$x++-$n&&$x-$y?32:rand(33,126)),yY,zZ); ``` takes input from command line argument; run with `-nr`. combined loop prints characters depending on position **breakdown** ``` for(; ($x%=$n=$argv[1]) // inner loop ? :$y++<$n&print"\n" // outer loop; print newline ;) echo strtr(chr( // 2. replace Y with Z; print $y+$x++-$n&&$x-$y // 1: if position is not on diagonals ?32 // then space :rand(33,126) // else random printable ),yY,zZ); ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `mM`, 34 bytes ``` ‹½ƛ\%꘍⁰↲øm;øm⁋?‹4*›ƛ‛yY95ɾ31+CF℅;% ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=mM&code=%E2%80%B9%C2%BD%C6%9B%5C%25%EA%98%8D%E2%81%B0%E2%86%B2%C3%B8m%3B%C3%B8m%E2%81%8B%3F%E2%80%B94*%E2%80%BA%C6%9B%E2%80%9ByY95%C9%BE31%2BCF%E2%84%85%3B%25&inputs=3&header=&footer=) ``` ‹½ƛ ; # Map 0...(n-1)/2... \%꘍ # That many spaces before a % ⁰↲ # Left-padded to correct width øm # Palindromise øm # Palindromise ⁋ # Join by newlines ?‹4*› # 4(n-1)+1 ƛ ; # Map 0...n... 95ɾ31+C # Printable ASCII ‛yY # Push ys F # Remove ys ℅ # Choose a random element from this % # Format the cross by this ``` [Answer] # [Vyxal 2.6](https://github.com/Vyxal/Vyxal), 22 bytes ``` ½⌈:ʁ\%꘍↲∞v∞⁋?dkP‛yYFƈ% ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCveKMiDrKgVxcJeqYjeKGsuKInnbiiJ7igYs/ZGtQ4oCbeVlGxoglIiwiIiwiNSJd) ``` ½⌈: # Push ⌈x/2⌉ twice ʁ # For each 0...^-1 \%꘍ # Prepend that many spaces to a % ½⌈ ↲ # Pad to length ⌈x/2⌉ with spaces ∞v∞ # Quad palindromise ⁋ # Join by newlines ƈ # Choose... ?d # Input * 2 ƈ # Random items from... kP # Printable ASCII ‛yYF # Without Y % # Replace % in the first bit with the random chars ``` ]
[Question] [ A *mountain* is defined to be a set of line segments whose first point has coordinates `(0,a)` where `a > 0`, and whose last point has coordinates `(b,0)`, where `b > 0`. All intermediate points have a y-coordinate (ordinate) strictly greater than 0. You are given the points on the mountain sorted in ascending order of x-coordinate (abscissa). **Note that two points can have the same x-coordinate, producing a vertical segment of the mountain. If you are given two points with the same x-coordinate, they should be connected in the order they are given. In addition, there can be horizontal segments of the mountain These horizontal segments are not lit, no matter what.** All coordinates are nonnegative integers. The question: what is the total length of the mountain that would be lit, assuming the sun is an infinite vertical plane of light located to the right of the mountain? This number does not need to be rounded, but if it is rounded, include at least **four decimal places.** I have included a picture: [![The Mountain](https://i.stack.imgur.com/JsPyz.jpg)](https://i.stack.imgur.com/JsPyz.jpg) Here, the lines that are bolded represent the segments that are lit. Note that in the input, P appears before Q (PQ is a vertical line segment) so the previous point is connected to P and not Q. You may take input in any reasonable format, like a list of lists, a single list, a string, etc. Test case: ``` (0,3000) (500, 3500) (2500, 1000) (5000,5000) (9000,2000) (9000,3500) (10200,0) Output: 6200.0000 ``` There are two lit-up segments here, as shown in this image:[![Test Case Pic](https://i.stack.imgur.com/bUCbM.png)](https://i.stack.imgur.com/bUCbM.png) The first one has length 5000/2 = 2500 and the second one has length 3700. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), ~~134 131 128 124 120 117 109~~ 107 bytes ``` p=input();s=0 for X,Y in p[1:]:x,y=p.pop(0);n=y-max(zip(*p)[1]);s+=n*(1+((X-x)/(y-Y))**2)**.5*(n>0) print s ``` [Try it online!](https://tio.run/##XYxBDoIwEEX3nKLLmVJwWsJCSD0HhLBwY@zCMgFMqJevoGiMi8nPe/l/OMzXwZsY2TrP9xmwniwll2EUjWqF84I7XfXVooLlnAcGwtrbkN3OCzwcg2TsdL@uUusl6BSgyRY8QMhaRCnNenkpwZ8IEx6dn8UUYweUkyqI1kAF5ZZKFOXOZhf6p7CJ8sPHN5s//j7QZF5io/4J "Python 2 – Try It Online") Takes input as a list of tuples / two-element lists of floating-point numbers. # Explanation We basically iterate through the pairs of points in the graph, and if \$y\_1 > y\_2\$, then we calculate how much of the line is exposed to light. The pairwise iteration is performed with a `for` loop to get the next point, \$(x\_2, y\_2)\$, popping the first element in the list each time to retrieve the current point, \$(x\_1, y\_1)\$. ### Maths – What part of the line segment is exposed to light? [![A poorly drawn mountain](https://i.stack.imgur.com/T3fZ3.jpg)](https://i.stack.imgur.com/T3fZ3.jpg) Let \$(x\_1, y\_1)\$ be the coordinates of the current point. Let \$y\_{max}\$ be the maximum height of a point after the current one (local maxima after the current point) and \$(x\_2, y\_2)\$ be the coordinates of the next point. In order to calculate the length exposed to the sun, \$L\$, we ought to find \$x\_3\$, as shown in the diagram. Naturally, if \$y\_1 \le y\_{max}\$, the segment is not exposed to light at all. In the triangle formed, the line segment of length \$x\_3\$ is parallel to the base, of length \$x\_2 - x\_1\$, so all three angles are congruent. Therefore, from the Fundamental Theorem of [Similarity](https://en.wikipedia.org/wiki/Similarity_(geometry)#Similar_triangles) (case Angle-Angle), we can deduce that \$\frac{x\_3}{x\_2 - x\_1} = \frac{y\_1-y\_{max}}{y\_1}\$. Hence, \$x\_3 = \frac{(y\_1-y\_{max})(x\_2 - x\_1)}{y\_1}\$. Then, we can apply the [Pythagorean Theorem](https://en.wikipedia.org/wiki/Pythagorean_theorem) to find that: $$L = \sqrt{(y\_1-y\_{max})^2+x\_3^2}$$ By joining the two formulas, we arrive at the following expression, which is the core of this approach: $$L = \sqrt{(y\_1-y\_{max})^2+\left(\frac{(y\_1-y\_{max})(x\_2 - x\_1)}{y\_1}\right)^2}$$ $$L = \sqrt{(y\_1-y\_{max})^2\left(1+\frac{(x\_2 - x\_1)^2}{y\_1^2}\right)}$$ ### Code – How does it work? ``` p=input();s=0 # Assign p and s to the input and 0 respectively. for X,Y in p[1:]: # For each point (X, Y) in p with the first # element removed, do: x,y=p.pop(0) # Assign (x, y) to the first element of p and # remove them from the list. This basically # gets the coordinates of the previous point. n=y-max(zip(*p)[1]) # Assign n to the maximum height after the # current one, subtracted from y. s+=n*(1+((X-x)/(y-Y))**2)**.5 # Add the result of the formula above to s. *(n>0) # But make it null if n < 0 (if y is not the # local maxima of this part of the graph). print s # Output the result, s. ``` ### Changelog * Gradually optimised the formula for golfing purposes. * Saved 1 byte thanks to [FlipTack](https://codegolf.stackexchange.com/users/60919/fliptack). * Saved 2 bytes by removing the unnecessary condition that `y>Y`, since if the local maxima of the *Y*-coordinate after the current point subtracted from `y` is positive, then that condition is redundant. This unfortunately invalidates FlipTack’s golf, though. * Saved 3 bytes by changing the algorithm a bit: instead of having a counter variable, incrementing it and tailing the list, we remove the first element at each iteration. * Saved 8 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs); changing `(x,y),(X,Y)` in the loop condition with a `list.pop()` technique. * Saved 2 bytes thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen) (optimised the formula a little bit). [Answer] # JavaScript, 97 bytes ``` a=>a.reduceRight(([p,q,l=0,t=0],[x,y])=>[x,y,y>t?(y-t)/(s=y-q)*Math.hypot(x-p,s)+l:l,y>t?y:t])[2] ``` ``` f=a=>a.reduceRight(([p,q,l=0,t=0],[x,y])=>[x,y,y>t?(y-t)/(s=y-q)*Math.hypot(x-p,s)+l:l,y>t?y:t])[2]; t=[[0, 3000], [500, 3500], [2500, 1000], [5000, 5000], [9000, 2000], [9000, 3500], [10200, 0]]; console.log(f(t)); ``` ( 5 bytes may be saved, if taking reversed version of input is considered valid. ) [Answer] # APL+WIN, 48 bytes ``` +/((h*2)+(((h←-2-/⌈\m)÷-2-/m←⌽⎕)×(⌽-2-/⎕))*2)*.5 ``` Prompts for a list of x coordinates followed by a list of y coordinates Explanation ``` h←-2-/⌈\m difference between successive vertical maxima viewed from the right (1) -2-/m←⌽⎕ vertical difference between points (2) ⌽-2-/⎕ horizontal difference between points (3) ``` The lit vertical distances = h and the lit horizontal distances are (3)\*(1)/(2). The rest is Pythagoras. [Answer] # [Swift](https://swift.org), 190 bytes ``` import Foundation func f(a:[(Double,Double)]){var t=0.0,h=t,l=(t,t) a.reversed().map{n in if l.0>=n.0&&n.1>l.1{t+=max((n.1-h)/(n.1-l.1)*hypot(n.0-l.0,n.1-l.1),0) h=max(n.1,h)} l=n} print(t)} ``` [Try it online!](https://tio.run/##TY7BTsMwEETv/gqfKi9szaZtDiC5J8RPoB4MTWRLjh25mxYU5duDSQAhrTTzZjXavdx8y4d59l2fMsuXNMSzZZ@iaIf4Lltln17VcxreQoOrwAnGq82SDWlCZxiDUYwMwurcXJt8ac4KdGf7MUpfppVB09FETZtN1NUx6Grke9PZD6UKbx08LFpyuHOffeKCVJDwN0YC4ZZGSdDBJIKJk@izj6wYpnn9k3BPRICqJkK5rxe/W6D6WxDWq3/89rt//qdQUQnLxRPMXw) ## Explanation ``` import Foundation // Import hypot() function func f(a:[(Double,Double)]){ // Main function var t=0.0,h=0.0,l=(0.0,0.0) // Initialize variables a.reversed().map{n in // For every vertex in the list (from right to left): if l.0>=n.0&&n.1>l.1{ // If the line from the last vertex goes uphill: t+=max((n.1-h)/(n.1-l.1) // Add the fraction of the line that's above the *hypot(n.0-l.0,n.1-l.1),0) // highest seen point times the length of the line // to the total h=max(n.1,h)} // Update the highest seen point l=n} // Update the last seen point print(t)} // Print the total ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~122~~ 120 bytes ``` k=input()[::-1] m=r=0 for(a,b),(c,d)in zip(k,k[1:]): if d>m:r+=(b>=m or(m-b)/(d-b))*((a-c)**2+(b-d)**2)**.5;m=d print r ``` [Try it online!](https://tio.run/##XY3BDoMgEETvfAXHRdEChkNp8EeMB5WYEoMSYg/tz1NobdP0sDv7JpNZf9@v2ypiXLRd/W0H0ilV8R45HTRD8xZgoCOhMFFD7Iof1sNCl46rniiE7YxN61QoNYytdjjFXTWSE5i0SQEwVBMpClHCWJl8pKnlxWmDfLDrjkOMwGpGG8aSpD8yK8WNPFgcBv8JZEN@@Pxm8cffAs7Ey8j0BA "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes ``` M=t=0 for x,y in input()[::-1]: if y>M:t+=(y-M)*abs((x-X)/(y-Y)+1j);M=y X,Y=x,y print t ``` [Try it online!](https://tio.run/##XcxNDsIgEAXgPaeYJVhQoOlCDN6AfZumC1004oKSikk5PYI/jZpM8vK9zIyP4TI5mZLRQXM0TjMsNIJ1efw9YNIrxcSgENgR4tGoUGkcmSGb0/mG8cJassvuSCWu5GB0RNDSTucfyM/WBQgp9ZhvOa05z0EobkpSqJvV4sfyvSC@DkrRfLx/Wf55fSC4fBZFwwM "Python 2 – Try It Online") Takes in a list of pairs of floats. Based off [ovs's solution](https://codegolf.stackexchange.com/a/151516/20260). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -2 thanks to caird coinheringaahing ``` ṀÐƤḊ_⁸«©0×I}÷I{,®²S½S ``` A dyadic link taking a list of y values on the left and a list of the respective x values on the right (as explicitly allowed by the OP in comments) **[Try it online!](https://tio.run/##y0rNyan8///hzobDE44tebijK/5R445Dqw@tNDg8/VHjTs9DSw5vB4oAaZ1D6w5tCj60N/j////RxgYGBjoKxqYg0hDMNgWTRkjiBrH/oyESQHFThBpLJNLQAKgjFgA "Jelly – Try It Online")** ### How? The fraction of a (sloping) section that is lit is the same fraction that would be lit if it were a vertical drop. Note that since squaring occurs to evaluate slope lengths the calculated heights along the way may be negative (also in the below the run-lengths of the lit slopes are calculated as negative divided by negative). ``` ṀÐƤḊ_⁸«©0×I}÷I{,®²S½S - Link:list, yValues; list, xValues ÐƤ - for suffixes of the yValues: e.g. [ 3000, 3500, 1000, 5000, 2000, 3500, 0] Ṁ - maximum [ 5000, 5000, 5000, 5000, 3500, 3500, 0] Ḋ - dequeue [ 5000, 5000, 5000, 3500, 3500, 0] ⁸ - chain's left argument, yValues [ 3000, 3500, 1000, 5000, 2000, 3500, 0] _ - subtract [ 2000, 1500, 4000,-1500, 1500,-3500, 0] 0 - literal zero 0 « - minimum (vectorises) [ 0, 0, 0,-1500, 0,-3500, 0] © - copy to the register for later } - apply to right: e.g [ 0, 500, 2500, 5000, 9000, 9000, 10200] I - incremental differences [ 500, 2000, 2500, 4000, 0, 1200] × - multiply (vectorises) [ 0, 0, 0,-6000000, 0,-4200000, 0] { - apply to left: e.g. [ 3000, 3500, 1000, 5000, 2000, 3500, 0] I - incremental differences [ 500,-2500, 4000,-3000, 1500,-3500] ÷ - divide (vectorises) [ 0, 0, 0, 2000, 0, 1200, 0] ® - recall from the register [ 0, 0, 0,-1500, 0,-3500, 0] , - pair (i.e. lit slope [runs, rises]) [[0, 0, 0, 2000, 0, 1200, 0], [0, 0, 0, -1500, 0, -3500, 0]] ² - square (vectorises) [[0, 0, 0, 4000000, 0, 1440000, 0], [0, 0, 0, 2250000, 0, 12250000, 0]] S - sum (vectorises) [ 0, 0, 0, 6250000, 0, 13690000, 0] ½ - square root (vectorises) [0.0, 0.0, 0.0, 2500.0, 0.0, 3700.0, 0.0] S - sum 6200.0 ``` --- 25 byte monadic version taking a list of `[x,y]` co-ordinates: ``` ṀÐƤḊ_«0 Z©Ṫµ®FI×Ç÷I,DzS½S ``` [Try this one.](https://tio.run/##y0rNyan8///hzobDE44tebijK/5R445Dqw@tNDg83bP28HbPap1D6w5tCj60N/j////RxgYGBjoKxqYg0hDMNgWTRkjiBrH/oyESQHFThBpLJNLQAKgjFgA "Jelly – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 31 bytesSBCS Uses [Graham's formula](https://codegolf.stackexchange.com/a/151514/43319). Anonymous prefix function taking 2×n matrix of data as right argument. The first row contains x-values from right to left, and the second row the corresponding y-values. ``` {+/.5*⍨(×⍨2-/⌈\2⌷⍵)×1+×⍨÷⌿2-/⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqbX09U61HvSs0Dk8Hkka6@o96OmKMHvVsf9S7VfPwdENtsPjh7Y969oMke7fWAjUqPGqbqGFoYGRgoGBpACNMQYSRKYSlYKCpoGGgYAxiGsFlDUEEWMwYyNIEAA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda where `⍵` is the argument:  `2-/⍵` deltas (lit. pairwise minus-reductions)  `÷⌿` Δx⁄Δy (lit. vertical division reduction)  `×⍨` square (lit. multiplication selfie)  `1+` one added to that  `(`…`)×` multiply the following with that:   `2⌷⍵` second row of the argument (the y values)   `⌈\` running maximum (highest height met until now, going from right)   `2-/` deltas of (lit. pairwise minus-reduction)   `×⍨` square (lit. multiplication selfie)  `.5*⍨`square-root (lit. raise that to the power of a half)  `+/` sum [Answer] # [J](http://jsoftware.com/), 46 bytes ``` 1#.((2([:%:@+&*:/-)/\,.)*>./\@]%&(2-~/\])])&|. ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1NDSMNKKtVK0ctNW0rPR1NfVjdPQ0tez09GMcYlXVNIx06/RjYjVjNdVq9P5rcnGlJmfkAw1QMDUwUDACEUBsoGAJJwwNjIBkmoIxiGNsChaBqTKCi4GAwX8A "J – Try It Online") Takes x coord list as left arg, y coord list as right arg. Could save 5 bytes if reversed lists were allowed. Though solved independently, the approach I landed on is almost identical to Adam's APL approach. [Answer] # [Kotlin](https://kotlinlang.org), 178 bytes ``` fun L(h:List<List<Double>>)=with(h.zip(h.drop(1))){mapIndexed{i,(a,b)->val t=a[1]-drop(i).map{(_,y)->y[1]}.max()!!;if(t>0)t*Math.hypot(1.0,(a[0]-b[0])/(a[1]-b[1]))else .0}.sum()} ``` [Try it online!](https://try.kotlinlang.org/#/UserProjects/u5jjigeprq6br6h7f086fdvlt7/k4ckjc98fmatl854f58edc53e3) The testing part is very much *not* golfed :) ]
[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 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. **Task:** Create an obfuscated program that prints `Hello World!` (exactly like that). Your program may not have any strings in it. **Rules:** * You can use any programming language you like. * Make it as *obfuscated* as possible * This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so the answer with the most upvotes wins. --- **Note:** This is not a duplicate of [this question](https://codegolf.stackexchange.com/questions/307/obfuscated-hello-world). That one was [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and it had different rules. [Answer] ## Python 2 I happened to be playing with this yesterday, so: ``` (lambda _, __, ___, ____, _____, ______, _______, ________: getattr(__import__(True.__class__.__name__[_] + [].__class__.__name__[__]), ().__class__.__eq__.__class__.__name__[:__] + ().__iter__().__class__.__name__[_____:________])(_, (lambda _, __, ___: _(_, __, ___))(lambda _, __, ___: chr(___ % __) + _(_, __, ___ // __) if ___ else (lambda: _).func_code.co_lnotab, _ << ________, (((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __) - _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ << __) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______ << ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) << ((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) << __) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______ << (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) + _) << ((((___ << __) + _) << _))) + (((_______ << __) - _) << (((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ << _))) + (_____ << ______) + (_ << ___))))(*(lambda _, __, ___: _(_, __, ___))((lambda _, __, ___: [__(___[(lambda: _).func_code.co_nlocals])] + _(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []), lambda _: _.func_code.co_argcount, (lambda _: _, lambda _, __: _, lambda _, __, ___: _, lambda _, __, ___, ____: _, lambda _, __, ___, ____, _____: _, lambda _, __, ___, ____, _____, ______: _, lambda _, __, ___, ____, _____, ______, _______: _, lambda _, __, ___, ____, _____, ______, _______, ________: _))) ``` Here is a more readable version: <http://codepad.org/UzSmoxF2> Notes: * One line, single expression (i.e. no print statement). * No strings, no ints; only functions, attribute access, lists, tuples, basic math, one `True`, and one star-args. * Minimal builtin usage (`__import__`, `getattr`, and `chr` once each). * The payload can be changed easily. [Here](http://codepad.org/oVuFVcB5) is the program I wrote to generate it. Edit: I wrote a fairly substantial explanation of how this works [on my blog](http://earwig.github.io/2014/06/01/obfuscating-hello-world.html). [Answer] # JavaScript ``` ([]+/H/)[1&11>>1]+(+[[]+(1-~1<<1)+(~1+1e1)+(1%11)+(1|1>>1|1)+(~1+1e1)+(.1^!1)])[[([]+!![ 11])[11^11]+[[{}]+{}][1/1.1&1][1]]+([[]+111/!1][+!1][([{}]+{})[1e1>>1]+[[],[]+{}][1&11>> 1][1|[]]+([]+[][111])[1&1]+[{},1e1,!1+{}][~~(1.1+1.1)][1^1<<1]+(11/!{}+{})[1-~1<<1]+[!!{ }+[]][+(11>11)][[]+1]+(/^/[1.11]+/&/)[.1^!1]+[{},[{}]+{},1][1&11>>1][1+1e1+1]+([]+!!{})[ .1^!1]+([]+{}+[])[[]+1]+[!!{}+{}][!11+!111][[]+1]]+[])[(!/~/+{})[1|1<<1]+[/=/,[]+[][1]][ 1&11>>1][1&1>>1]+([]+{})[~~(1.1+1.1)]+[1,!1+{}][1%11][1^1<<1]+(111/[]+/1/)[~1+1e1+~1]+[! !/-/+[]][+(11>11)][1]]((1<<1^11)+((+(1<1))==([]+/-/[(!![11]+[])[+!1]+(!!/-/+{})[1-~1]+([ ]+!/~/)[1-~1]+(!!/-/+{})[!111+!111]])[11%11]),-~11>>1)](~1-~1e1<<1<<1)+([]+{111:1111}+[] )[11111.1%11.1*111e11|!11]+({}+/W/)[1+~1e1-(~11*1.1<<1)]+(+[[]+(1|1>>1)+(1|1>>1|1)+(11-1 >>1)+(1e1>>1|1)+(1e1>>1)+(1>>11)+(11>>>1)])[[(!!{}+[])[11>>>11]+[[]+{}][.1^!1][111%11]]+ ([11/[]+[]][111%111][([{}]+[{}])[1e1>>1]+[[],[{}]+[{}]][1|1>>1|1][1|[]]+([][11]+[])[[]+1 ]+[{},1e1,![1]+/~/][1<<!1<<1][1<<1^1]+(1/!1+{})[11+1>>1]+[!!/-/+{}][+(111>111)][111%11]+ ([][11]+/&/)[1&1>>1]+[{},[]+{}+[],1][[]+1][11-~1+11>>1]+([]+!!/-/)[11>>11]+([]+{})[1|1>> 1|1]+[[]+!!{}][1>>>1][1&11]]+[])[(!{}+[])[1^1<<1]+[/=/,[]+[][1]][1<<1>>1][!111+!111]+([] +{}+[])[1<<1^1>>1]+[1,![11]+[]][1|1>>1][1|1<<1|1]+(11/[]+/1/)[-~11>>1]+[!![111]+{}][+[]] [1|1>>1]]((1e1-1)+((1&1>>1)==([]+/-/[(!!{}+{})[+(1>1)]+(!!/-/+{})[1|1<<1]+(!1+{})[1|1<<1 |1]+(!!/-/+{})[11.11>>11.11]])[1&1>>1]),1-~1<<1)](~1-~1e1<<1<<1)+(/^!/+[])[1+!![11%111]] ``` > > Description of how it works can be found in [**this answer**](https://stackoverflow.com/a/16036784/1249581) on StackOverflow. > > > Simply run this in the browser console (e.g. in Firebug or in Chrome Dev Tools). [Answer] # C A multiplicative salutation: ``` #include <stdio.h> main() { long long P = 1, E = 2, T = 5, A = 61, L = 251, N = 3659, R = 271173410, G = 1479296389, x[] = { G * R * E * E * T , P * L * A * N * E * T }; puts((char*)x); } ``` [Answer] ## PHP ``` <?=${[${[${[${[${[${[${[${[${${![]}.=[]}.=${![]}{!![]}]}.=${!![${[${[ ${[${[${[${[${[]}++]}++]}++]}++]}++]}++]}++]}{![]+![]+![]}]}.=${[${[$ {[${[${[]}++]}++]}++]}++]}{![]}]}.=${[${[${[${[${[${[${[${[]}++]}++]} ++]}++]}++]}++]}++]}{![]+![]}.${[]}{![]+![]}]}.=${![]}^${!![${[${[${[ ]}++]}++]}++]}{![]+![]+![]}]}.=${[]}{!![]}]}.=${[${[${[${[${[${[${[${ [${[${[${[${[${[${[${[${[]}++]}++]}++]}++]}++]}++]}++]}++]}++]}++]}++ ]}++]}++]}++]}++]}{![]+![]+![]+![]}.${[]}{![]+![]+![]+![]}]}.=${[${[$ {[${[]}++]}++]}++]}{![]+![]}.${![]}{![]+![]+![]}]}.=${[${![]}=${![]}{ !![]}]}{!![${!![${!![${![]}++]}++]}++]}^${!![${[${[${[]}++]}++]}++]}; ``` I've translated this into a single statement, which I think makes it considerably harder to decipher. This version uses only 13 unique characters. --- **Original version** ``` <?${[]}.=[];${![]}.=${[]}{!![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${ ![]};++${![]};${![]}.=${[]}{![]+![]+![]};++${![]};++${![]};++${![]};++${![]};${![ ]}.=${![]}{![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${![]};${ ![]}.=${![]}{![]+![]}.${![]}{![]+![]};++${![]};++${![]};++${![]};${![]}.=${[]}^${ []}{![]+![]+![]};${![]}.=${![]}{!![]};++${![]};++${![]};++${![]};++${![]};++${![] };++${![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${![]};++${![] };++${![]};${![]}.=${![]}{![]+![]+![]+![]}.${![]}{![]+![]+![]+![]};++${![]};++${! []};++${![]};${![]}.=${![]}{![]+![]}.${[]}{![]+![]+![]};++${![]};++${![]};++${![] };${[]}=${[]}{!![]};++${[]};++${[]};++${[]};${![]}.=${[]}^${![]}{![]}?><?=${![]}; ``` 14 unique characters. I could make a script to generate these and dub it "PHPFuck", but I don't think it would be very useful. --- **How it works** > > When an array - including the empty array - is cast to string, the result is always the amazingly helpful string "Array". I'm not sure who thought that was a good idea. PHP supports the increment operator (but not decrement) for strings, for example "++A" → "B". The original string contains both "A" and "a", so all latin characters can be produced, brainfuck style. Space is produced with "A" ^ "a", and exclamation with "D" ^ "e". > > > [Answer] ## PHP Here's a simple PHP script that outputs `Hello World!`: ``` <?php function SGVsbG8gV29ybGQh($_ = 0) {( $___=__FUNCTION__ )&& !$_ and list($_,$__) = array_values(array_filter($___(42), $___)) and !$_($__($___)) and $___($___); return $_ &42 ?current(get_defined_functions()):( !(( $_=md5($_))-42*2)or !(md5($_ = md5($_))-42/2 *3) );}; SGVsbG8gV29ybGQh(); ``` [Click here for the demo.](http://sandbox.onlinephpfunctions.com/code/4b555319e9696e8d4e835f9bb18a8505509f4f5c) [Answer] ## Whitespace ```                                                                                                                                   ``` [Wikipedia: Whitespace (programming language)](http://en.wikipedia.org/wiki/Whitespace_(programming_language)) [Online Interpreter to Test Answer](http://whitespace.kauaveel.ee/) The program pushes the ASCII character codes through the following steps (taken from the interpreter debug sidebar): ``` push 72 printc push 101 printc push 108 printc push 108 printc push 111 printc push 32 printc push 87 printc push 111 printc push 114 printc push 108 printc push 100 printc push 33 printc end ``` [Answer] # Bash (under Linux) I hope your shell scripts don't look like this: ``` :; ______=$? __=${#______} ____=$[__+__] ________=$[__+____] _____=$[____+____] __________=$[____+_____] _________=$[__+__________] ______________=( /????/$$/????) ____________=${______________[$______]} _____________=${____________##*/} _______________=(${____________//\// }) ________________=${_______________: -$__:$__}$_____________ ___________________=${________________:$______:$________} ___________=${_____________:$______:$__} _________________=${___________^} . <($___________________<<<__________________=\({$_________________..\ ${___________}}\))&&_______=(${__________________[@]:$______:$____$__________}) ___=(${_______[@],,})&&${___[$_____]}${___[$____]}${___[$_________]}${___[ $__$_____]} -${___[$_____]} ${_______[ $_________]}${___[${_____}]}${___[$__$__ ]}${___[$__$__]}${___[$__$_____]} ${_______[$____$____]}${___[$__$_____]}${___[ $__$_________]}${___[ $__$__]}${___[$________]}\\$______$[$_____#$____$____$__] ``` * Not a single alphanumeric character - given this restriction, it hardly seems worth doing further obfuscation * No strings (no quotes, anyway) * There is a dependency on Linux - specifically that the `attr` file is the first file in `/proc/$PID` with a 4-character filename See if you can spot the hidden `eval`. [Answer] ## GolfScript ``` [' '(..4/++][' '(3*)))))][6`(2*.]['1'..++~][8 2?2/][' '(4/.(`\`\+~]['1'.+~2?10-][13(1)?8((0)))))*-][6`(1)*]['('(4/2?][' '()]+++++++++++ ``` It was quite challenging to create and debug this. It doesn't contain strings, only chars. It outputs: > > Hello World! > > > [Test online](http://golfscript.apphb.com/?c=WycgJyguLjQvKytdWycgJygzKikpKSkpXVs2YCgyKi5dWycxJy4uKyt%2BXVs4IDI%2FMi9dWycgJyg0Ly4oYFxgXCt%2BXVsnMScuK34yPzEwLV1bMTMoMSk%2FOCgoMCkpKSkpKi1dWzZgKDEpKl1bJygnKDQvMj9dWycgJygpXSsrKysrKysrKysr) ### Explanation How this works: 1. `[' '(..4/++]` 1. `' '(` converts the space to its ASCII code: `32`. 2. `..` duplicates `32` twice. Now you have three times `32`. 3. `4/` divides the top `32` by 4. Now you have twice `32` and once `8`. 4. `++` adds up the `32`, `32` and `8`. You get `72`, which is the ASCII code for `H`. 2. `[' '(3*)))))]` 1. `' '(` converts the space to `32`. 2. `3*` multiplies the `32` with `3`: `96` 3. `)))))` increases `96` with 5, you get `101`, which is the ASCII code for `e`. 3. `[6`(2*.]` 1. `6`(` gives the ASCII code of the char `6`: `54` 2. `2*` multiplies it with 2, you get `108`, which is the ASCII code for `l`. 3. `.` duplicates the `l` 4. `['1'..++~]` 1. `'1'..` puts the char `1` on the stack and duplicates it twice. 2. `++` concatenates the three chars and returns the string `111` 3. `~` converts it to the integer `111`, which is the ASCII code for `o` 5. `[8 2?2/]` 1. `8 2?` calculates 82, you get `64` 2. `2/` divides it by 2, you get `32`, which is the ASCII code for a space. 6. `[' '(4/.(`\`\+~]` 1. `' '(` converts the space to `32`. 2. `4/.` divides it by 4, you get `8`. The `.` duplicates it. 3. `(`` decrements the second `8` and converts it to a string. 4. `\` swaps the top two elements. The `8` becomes the top element. 5. ``` converts the `8` to a string. 6. `\` swaps the top two elements. The `7` becomes the top element. 7. `+` concatenates the two strings. You get `87` (as a string). 8. `~` converts the string `87` to the integer `87`, which is the ASCII code for `W`. 7. `['1'.+~2?10-]` 1. `'1'.` puts the char `1` on the stack and duplicates it. 2. `+~` concatenates the two chars to the string `11` and converts it to an integer. 3. `2?` calculates 112, you get `121`. 4. `10-` decreases `121` with 10, you get the ASCII code for `o`: `111`. 8. `[13(1)?8((0)))))*-]` 1. `13(` puts `12` on the stack. 2. `1)` puts `2` on the stack. 3. `?` calculates 122, you get `144`. 4. `8((` puts `6` on the stack. 5. `0)))))` puts `5` on the stack. 6. `*` multiplies `6` and `5`, you get `30`. 7. `-` substracts `144` with `30`, you get `114`, which is the ASCII code for `r` 9. `[6`(1)*]` 1. `6`(` converts `6` to a char and takes its ASCII code: `54` 2. `1)*` multiplies `54` with `2`, you get `108`, the ASCII code of `l` 10. `['('(4/2?]` 1. `'('(` converts `(` to its ASCII code, `40`. 2. `4/` divides `40` by `4`, you get `10`. 3. `2?` calculates 102, you get `100`, which is the ASCII code for `d` 11. `[' '()]` 1. `' '(` converts the space to its ASCII code: `32` 2. `)` increments the `32`, you get `33`, which is the ASCII code for `!` 12. `+++++++++++` concatenates all ASCII codes to one string. [Answer] ## Brainf\*\*\* Not sure if this really counts as obfuscated, but it never uses more than four plus or minus symbols in a row. So there's that. ``` >>+++[<+++>-]<+[>+++>>+++[<+++>-]<+[<]>-]<+++[>+++<-]>+[>++++<-]>++.>+.>+++ [<++>-]<+..+++.<<<+++[>+++<-]>+[>----<-]>.>[>+>+<<-]++++[>++<-]>.>.+++.>++[ <--->-]<.>++[<---->-]<.<<<+. ``` [Answer] # Mathematica Simple Algebra I math. ``` a=+x+8x^2+8(x^3+x^9); b=11(x^4+x^7)-68x^5-13x^6; c=-28+14x^8-67x^11; w=ToExpression[Names[__][[1571]]]; v=ToExpression[Names[__][[604]]]; y=Solve[a+b+c,{x},Reals]; w[v[y[[1]],x]+100] ``` > > Hello World! > > > [Answer] ## **C** ``` #define u unsigned char #define v while(*x) #define z(x) putchar(*x); #define y(x) ++*x; #define p(x) ++x; #define e(x) --*x; #define d(x) --x; #define w(x) x x main(){u *x=calloc(12,1);u *l=x;w(w(w(y(x))))w(y(x))v{p(x)w(w(y(x)))w(y(x))y(x)p (x)w(w(w(y(x))))w(y(x))p(x)w(y(x))y(x)p(x)w(w(w(y(x))))y(x)w(w(d(x)))e(x)}p(x)w( y(x))z(x)p(x)y(x)z(x)w(w(y(x)))w(y(x))y(x)w(z(x))w(y(x))y(x)z(x)p(x)w(y(x))z(x)p (x)w(e(x))e(x)z(x)w(d(x))z(x)w(y(x))y(x)z(x)w(w(e(x)))w(e(x))z(x)w(w(w(e(x))))z( x)p(x)y(x)z(x)free(l);} ``` Meta-obfuscated. Running this through the preprocessor gives you this: ``` main(){unsigned char *x=calloc(12,1);unsigned char *l=x;++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x;++*x; ++*x;while(*x){++x;++*x; ++*x; ++*x; ++*x;++*x; ++*x;++*x;++x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x;++*x; ++*x;++x;++*x; ++*x;++*x;++x;++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x; ++*x;++*x;--x; --x; --x; --x;--*x;}++x;++*x; ++*x; putchar(*x);++x;++*x;putchar(*x);++*x; ++*x; ++*x; ++*x;++*x; ++*x;++*x;putchar(*x); putchar(*x);++*x; ++*x;++*x;putchar(*x);++x;++*x; ++*x;putchar(*x);++x; --*x; --*x;--*x;putchar(*x);--x; --x;putchar(*x);++*x; ++*x;++*x;putchar(*x);--*x; --*x; --*x; --*x;--*x; --*x;putchar(*x);--*x; --*x; --*x; --*x; --*x; --*x; --*x; --*x;putchar(*x); ++x;++*x;putchar(*x);free(l);} ``` Output: > > Hello World! > > > **Edit:** added syntax highlighting for clarity. :-P [Answer] # [Sage](http://www.sagemath.org/) ``` for i in 5105882569598991528047304.digits(1+sum(2**j for j in 11382954456.digits(42))): sys.stdout.write(chr(i)) ``` Explanation: `11382954456.digits(42)` converts 11382954456 into base 42 and gives an array of its digits, which is `[6, 1, 0, 5, 4, 3, 2]` So the `sum` actually gives the sum of 1+2+4+...+32+64, which is 127 Then `5105882569598991528047304.digits(...)` converts the number into base 128, which gives the list `[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]` And these are the ASCII codes for the string to be printed. [Answer] ## Javascript (28187 chars) Probably not the shortest way to say hello to this world. ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([][[]]+[])[!+[]+!+[]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+([][[]]+[])[+[]]+([][[]]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(+(!+[]+!+[]+[+!+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+!+[]+[+!+[]])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]])()(([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+[]])[+[]]+(!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]+!+[]+!+[]+!+[]])+[])+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])() ``` Generated with [JSFuck](http://www.jsfuck.com/) [Answer] ## C: ``` #include <stdio.h> #define BING(x,y) ((x)<<y) #define BANG(x) (1<<x) #define BOOM 1 int main () { int x,y,z,w; int V[3] = {BING(x=227380393,BANG(BOOM)+BOOM), x+(w=BOOM+BANG(BANG(BOOM)), BING(47*y=17453197,BOOM)), x+y+BING(w*w*17*185527,BANG(BOOM))}; char *p=V; while(*(p-BOOM)!=BOOM+BING(BOOM,w)) putchar(*p++); return 0; } /* Mind the comma operator! */ ``` **Outputs:** `Hello World!` [Answer] # Malbolge ``` ('&%:9]!~}|z2Vxwv-,POqponl$Hjig%eB@@>}=<M:9wv6WsU2T|nm-,jcL(I&%$#" `CB]V?Tx<uVtT`Rpo3NlF.Jh++FdbCBA@?]!~|4XzyTT43Qsqq(Lnmkj"Fhg${z@> ``` or ``` (=<`#9]~6ZY32Vx/4Rs+0No-&Jk)"Fh}|Bcy?`=*z]Kw%oG4UUS0/@-ejc(:'8dc ``` I have no clue how this works. Source: <http://en.wikipedia.org/wiki/Malbolge#.22Hello_World.21.22_in_Malbolge> [Answer] # Java Here it is. Can you understand how it works? Warning: Very volatile. May break spontaneuosly in the future. ``` import java.io.ByteArrayOutputStream; public class MysteryCode { public static void main(String[] unused) throws Exception { ByteArrayOutputStream stoned = new ByteArrayOutputStream(20480); int[] magic = {104, 116, 116, 112, 58, 47, 47, 98, 105, 116, 46, 108, 121, 47, 49, 98, 87, 119, 51, 75, 111}; for (int weird : magic) stoned.write(weird); int crazy, unknown = 0; java.io.InputStream wtf = new java.net.URL(stoned.toString()).openStream(); while((crazy = wtf.read()) != -1) stoned.write(crazy); for (int strange : stoned.toByteArray()) { if (unknown == 2) { if (strange == 38) break; System.out.print((char) strange); } else if (17 + (unknown + 1) * 21 == strange) { unknown++; } } } } ``` [Answer] **Befunge** Code that says "Hello, World!": ``` >55+7*2+, v >4*4+v , v,+1*+55+55< +v55<>55+3*2+,v >55+55+*8+,v 5+ +v,+7*8+55< v,+8*+55+55< 5* 5>55+55+*56++,v >55+55+*56++,^8 5v,++59*+55+55< v+55,*+55+55,+< ^< >3*3+,@ ``` Code that says "Hello World!": ``` >55+7*2+, v > v v,+1*+55+55< v55<>55+3*2+,v >55+55+*8+,v + +v,+7*8+55< v,+8*+55+55< * 5>55+55+*56++,v >55+55+*56++,^8 5v,++59*+55+55< v+55,*+55+55,+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/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+, '/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+'/'[\/+,@ ``` Based on my answer here: <https://codegolf.stackexchange.com/a/15736/9498> As a bonus, this answer does not use any numbers and contains no redundant characters (that is there is no combination of characters that could be removed such that it produces the same output). Try it out here (paste code, replace every instance of `'/'[` with `"/["`): <http://www.quirkster.com/iano/js/befunge.html> How it works: > > `'/'[\/` is equivalent to 1, so all this does is increment to the corresponding ASCII Values, then prints. > > > Extra bonus: this post is so long that it takes ~1 second before stackexchange recognizes the changes in writing this post. [Answer] # Brainf\*\*k It's obfuscated, and yet, it couldn't be simpler. ``` + + +++++ + [ >++ + + [ > + + > +++>+ ++>+< < < < - ] > + > + > - > > + >+[<] <-]>> .>--- .++ + + + ++. .+++ . >>.< - W . < . + + + . - - - - - - . - ---- - - - . > > + . > + + . < >>> < < >>><< <><> > ``` Because when you look closely: ``` H H EEEEE L L OOO H H E L L O O HHHHH EEEEE L L O O H H E L L O O , H H EEEEE LLLLL LLLLL OOO , W W OOO RRRR L DDDD ! W W W O O R R L D D ! W W W O O RRRR L D D ! W W O O R R L D D OOO R R LLLLL DDDD ! ``` [Answer] ## JavaScript **No number literals, no string literals, and only one function (not including `console.log`)!** ``` var ________________ = [] + []; var _ = +[]; _++; var _____ = _ + _; var ___ = _____ + _____; var __ = ___ + ___; var ____ = __ + __; var ______ = ____ + ____; var _______ = ______ + _; var ___________ = ______ + ______ + __; var ______________ = ___________ + ____ - _; var ____________ = _ + _____; var ________ = _______ * ____________ + _; var _________ = ________ + _; var _____________ = ______________ + ______ - ___ - _; var __________ = _____________ - ____________; var _______________ = __________ - ____________; console.log(________________ + String.fromCharCode(___________, _________, _______________, _______________, __________, ______, ______________, __________, _____________, _______________, ________, _______)); ``` Demonstration [here](https://www.khanacademy.org/cs/obfuscated-code/5989035086446592). [Answer] # Python 2.6+ ``` p = lambda x: ( -13214 * x**11 + 956318 * x**10 - 30516585 * x**9 + 564961485 * x**8 - 6717043212 * x**7 + 53614486464 * x**6 - 291627605005 * x**5 + 1074222731065 * x**4 - 2606048429424 * x**3 + 3927289106268 * x**2 - 3265905357360 * x + 1116073728000 ) / 19958400 print bytearray(map(p, range(1, 13))) ``` No strings, just [a simple polynomial function](https://en.wikipedia.org/wiki/Polynomial_interpolation). [Answer] # [This](https://www.khanacademy.org/computer-programming/two-dimensional-programming-language/6252487852687360) Programming Language ``` 'Alice'++++7/4+v v -9/3++'was' < > 'beginning'++++++++9/3+v v -5/2+'to' < > 'get'++3/5+v v -&81/9+++'very' < > 'tired'++++6/2-v v +5/2+'of' < > 'sitting'++++++7/4+v v -1/2+'by' < > 'her'++3/6-v v-&14/9+++++'sister' < > 'on'~~v v ~~~'the' < > 'bank.'~~~~~s; ``` Can you guess what it does? Perhaps you'll have to go deeper into the rabbit-hole to find out. **DISCLAIMER:** Programming language is newer than challenge. [Answer] # C ``` int main() { // Some floating point numbers for testing float b[] = {1.1431391224375825e+27, 6.6578486920496456e+28, 7.7392930965627798e-19, 3.2512161851627752e-9}; // Print all numbers in array b[] puts(b); return 0; } ``` The comments are there just to mislead uninformed readers. The constants are constructed so that its representation in the memory (for little-endian systems) is the same as the string `"Hello World!"`. Then the array (decays to pointer) is passed to `puts`, where `puts` blindly treats it as a `char*` and print everything until it hits `NUL` (which is coded in the last number). The code compiles (with warnings) and prints the expected output with gcc 4.7.0, Windows 7 32-bit. [Answer] # Java ``` class M‮{public static void main(String[]a‭){System.out.print(new char[]{'H','e','l','l','o',' ','W','o','r','l','d','!'});}} ``` [Test here.](http://ideone.com/t1W5Vm) I know, kind of lame to use characters instead of strings. Weird that it runs correctly. Isn't it? [Answer] C (honestly, 90% C preprocessor): ``` #if __COUNTER__ == 0 #define Y #define X(a) a##ng a##ng #define values(a,b,c,d) _ d c = b 5237610348992605899, -8965656808041882953, -3202399561689361469, -7073034487879198273, -7020069900579512688, -33906882022564967 a #define W(a) (){ #define _Q(a,b,c,d,e) e##a##d##e##c 0; b #define Q(a,b,c,d) _Q(a,b,c,d,r) #define K (char main W(lo) X(lo) values(},{,],[); #endif #ifndef T #undef W #define W _- #define Z 35 #define T Y+0 #endif putchar((*_=(X(lo))(K*)(_+((*W 1)&-(*W 0)|!T))+__COUNTER__),~*K*)(*W 1))); #if __COUNTER__ <= Z #include "main.c" #else Q(e,},n,tu) #endif ``` Only with gcc or another compiler that supports the `__COUNTER__` macro. [Answer] (I know it's not really *weird*.) ## dc ``` dc<<<"8 9*P101P108P108P111P4 8*P81 6+P111P114P108P100P33P" ``` Output: ``` Hello World! ``` [Answer] # C# No string or character literals, although string functions **are** used. Obfuscation via rot13. ``` using System; using System.IO; namespace CodeGolf { /// <summary> /// Jevgrf "Uryyb Jbeyq!" gb gur pbafbyr. /// </summary> /// <remarks> /// <para>Guvf cebtenz vf n cebcbfrq fbyhgvba gb dhrfgvba /// ahzore 22533 ng pbqrtbys.fgnpxrkpunatr.pbz:</para> /// <para>Perngr na boshfpngrq cebtenz gung cevagf Uryyb /// Jbeyq! (rknpgyl yvxr gung). Lbhe cebtenz znl abg unir /// nal fgevatf va vg.</para> /// <para>Fnyhgba Zbaqb vf Rfcrenagb sbe Uryyb Jbeyq.</para> /// </remarks> class FnyhgbaZbaqb { class Genafyngbe { int bssfrg = 0; public char Genafyngr(string vachg) { return vachg.Length < 6 ? (char)(37 + (bssfrg -= bssfrg) - vachg.Length) : vachg.ToCharArray()[bssfrg++]; } } enum UryybJbeyq { Hoover, Denver, WillowPrimus, WillowSecundus, WillowTertius, Fnord, Wintergreen, Copacetic, Pursuing, Follicle, Remedies, Bang } void Terrg(TextWriter tw) { Genafyngbe gf = new Genafyngbe(); foreach (var enumVal in Enum.GetNames(typeof(UryybJbeyq))) { tw.Write(gf.Genafyngr(enumVal)); } tw.WriteLine(); tw.Flush(); } static void Main(string[] args) { FnyhgbaZbaqb urryb = new FnyhgbaZbaqb(); urryb.Terrg(Console.Out); Console.ReadLine(); } } } ``` [Answer] # C ``` #include <stdio.h> #define o stdout #define p fputs int main(_){int*I=&_,_I=2113,l1=3271;_=14557;_I*=503;_<<=3;_*='=';_I<<=0==0;_I=7*'Y'*853<<2; p(I,o);I=&_I;p(I,o);I=&_; _+= l1*11*11; _I += 0xF5<<8;p(I,o);I=&_I;p(I,o);} ``` No strings, no arrays, no characters, very few obvious "data-storing large constants". [Answer] # ><> [(Fish)](http://esolangs.org/wiki/Fish) I made a little maze for the instruction pointer in ><> ``` >v ^3::+7:\v-< /8< v>6c*aa*1+/>!^:!/3 \ >l?\;| !:6!+-!3:!<^>,r \ o/+:&84*:3*9-&:^ ``` [Online ><> interpreter here](http://fishlanguage.com/) [Answer] # C++ ``` #include<iostream> int main() { char g=16777288, r=16777317, e=16777324, t=16777327, sp=16777248, w=16777303, o=16777327, R=16777330, l=16777324, d=16777316, ex=16777249; std::cout <<g <<r <<e <<e <<t <<sp//space <<w <<o <<R <<l <<d <<ex;//exclamatory return 0; } ``` ### Output ``` Hello World! ``` ]
[Question] [ Inspired by a task for Programming 101, here's a challenge that hopefully isn't too easy (or a duplicate). ## Input: * A positive integer `n >= 1`. ## Output: * `n` lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line. ## Test case (n=5): ``` * ** *** **** ***** ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # Vim, 8 bytes ``` o <Esc><C-V>{r*J ``` Takes input in the readahead buffer, so if input is 15, you would type that and then the code above. This is a silly rule, but *seems* to be [allowed](http://meta.codegolf.stackexchange.com/a/8580/60590). If you got input in a register like `"a`, you'd just stick `@a` in front (10). If you got it from the start file, you'd prepend `D@"` instead (11). Relies on abuse of `:set autoindent`, which is default in [vimgolf.com](https://www.vimgolf.com/) rules and default in Vim 8 (and everyone uses it anyway). * `o <Esc>`: With its number argument, if your text starts with whitespace, and you have `:set autoindent`, Vim glitches out and creates a cascade of indent. * `<C-V>{r*`: Turn all those spaces into `*`s. I'm using block visual so that, even if your lousy indent settings silently group your spaces into tabs, you'll still get the right number of `*`s. * `J`: Starting with `o` unfortunately left a blank line at the top. This removes it. [Answer] # JavaScript (ES6), 31 bytes This one includes both a leading and a trailing line-break. We start with a string `s` containing only a line-break. Then we process `n` recursive calls, adding an asterisk on the left side of this string at each iteration. The concatenation of all intermediate strings leads to the expected result. ``` f=(n,s=` `)=>n?s+f(n-1,'*'+s):s ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6fYNoErQdPWLs@@WDtNI0/XUEddS127WNOq@H9yfl5xfk6qXk5@ukaahqmm5n8A "JavaScript (Node.js) – Try It Online") ### Without asterisk, 36 bytes ``` f=(n,s=` `)=>n?s+f(n-1,atob`Kg`+s):s ``` [Try it online!](https://tio.run/##FczLDsIgEEDRfb9idkD6iom60FATtyZu/AFoCy0GmYbB19ej3d9z7/qlaYhuSXXA0eS2hQX91zrvwWIEnbDnooL37IYZRjQUWALzcZTABbj@TbE2IIFAdnB@WmtiYyM@OEEJjFXAek1mv2WiSXhL0YWJi2O2koeKpCqUkF04UWl5qDfVOlOXSZUkDpQHDITeNB4nbvlOiPwD "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes Uses [CP-1252](http://www.cp1252.com/) encoding. ``` '*×.p» ``` **8 byte no-asterisk version:** ``` žQTè×.p» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=JyrDly5wwrs&input=NQ) **Explanation** Example using input `n = 5` ``` '* # push "*" # STACK: "*" × # repeat input number times # STACK: "*****" .p # get prefixes of string # STACK: ['*', '**', '***', '****', '*****'] » # join by newlines # implicit print ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~21~~ 20 bytes ``` 1.."$args"|%{'*'*$_} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPT0klsSi9WKlGtVpdS11LJb72////pgA "PowerShell – Try It Online") Loops from `1` to input `$args`, each iteration using string multiplication to construct a string of that many `$_` asterisks. Default behavior for the implicit `Write-Output` at the end is with a newline for separator, so we get that for free. ``` PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 5 * ** *** **** ***** PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 2 * ** PS C:\Tools\Scripts\golfing> .\draw-asterisk-pattern.ps1 7 * ** *** **** ***** ****** ******* ``` *-1 byte thanks to Veskah.* [Answer] # Python 2, ~~37~~ 34 bytes ``` i=1;exec"print'*'*i;i+=1;"*input() ``` **[Ideone](http://ideone.com/DQccQT)** `i` is initialised to `1`; then `exec` commands to execute the following string of code, so it must be constructed; the string is `"print'*'*i;i+=1;"` but the `*` following the string takes precedence over the `exec` and instructs to first repeat the string `input()` times; the `exec` command now executes the long string which acts like a loop, `print`ing another string of increasing length, again using `*` to repeat the character `'*'`, then incrementing `i` with `i+=1`. **Python 3, 41 bytes:** `def f(n):i=1;exec("print('*'*i);i+=1;"*n)`; or `lambda n,i=1:exec("print('*'*i);i+=1;"*n)` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ”*ẋþY ``` **[TryItOnline](http://jelly.tryitonline.net/#code=4oCdKuG6i8O-WQ&input=&args=MTk)** ### How? ``` ”*ẋþY - Main link: n ”* - literal string "*" þ - form outer product with the dyadic function: ẋ - repeat list (right input is an implicit range(n), Jelly defaults to 1-based) so the outer product is like: [[i*'*' for i in range(1,len("*")+1)] for x in range(1,n+1)] Y - join with line feeds - implicit print ``` --- Bounty: I'm not sure what the no ordinals clause is, since a character *is* a lookup of an ordinal. Direct lookup would just be `42Ọẋþ³Y` for **[7 bytes](http://jelly.tryitonline.net/#code=NDLhu4zhuovDvsKzWQ&input=&args=MTk)** - where the `³` gets us the input) A short slightly indirect method would be, for **[8 bytes](http://jelly.tryitonline.net/#code=4oCcKeKAmeG7jOG6i8O-wrNZ&input=&args=MTk)**, `“)’Ọẋþ³Y` - where we lookup `')'` in jelly's code page, which is 1-indexed so `“)’` yields 42. [Answer] # C#, 42 bytes ``` f=n=>n<1?"":f(n-1)+"\n"+new string('*',n); ``` Full program with test case: ``` using System; namespace DrawAnAsteriskPattern { class Program { static void Main(string[] args) { Func<int,string>f= null; f=n=>n<1?"":f(n-1)+"\n"+new string('*',n); Console.WriteLine(f(5)); } } } ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 6 bytes ``` j._*"* ``` [**Try it here**](http://pyth.herokuapp.com/?code=j._%2a%22%2a&input=5&debug=0). ### Explanation ``` j Join by newlines ._ all prefixes of * the result of repeating "* the string "*" as many times as the implicit input ``` [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~25~~ ~~24~~ 20 + 1(n flag) = 21 bytes *Edit:* 4 bytes less based on [Riley](/users/57100/riley)'s comments ``` x;G;:;P;s:\n.:*\n:;t ``` **[Try it online!](http://sed.tryitonline.net/#code=eDtHOzo7UDtzOlxuLjoqXG46O3Q&input=MDAwMDA&args=LW4)** **Run example:** the input is in unary format, which for sed is allowed based on this [consensus](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary "unary") ``` me@LCARS:/PPCG$ sed -nf draw_triangle.sed <<< "0000" * ** *** **** ``` A leading newline is present in the output, but this is allowed by the OP. **Explanation:** ``` x;G # prepend a newline to unary string : # start loop P # print first line only s:\n.:*\n: # shift one unary char from 2nd line to 1st, converted to a '*' t # repeat ``` [Answer] # Matlab, 26 23 bytes Good old Matlab... ``` @(n)tril(repmat('*',n)) ``` Has trailing whitespaces. `tril` gives you the lower triangular matrix. edit: saved 2 bythes thanks to Luis Mendo [Answer] # C++ - 92 96 Bytes ``` #include<string> int main(){int n;std::string s;scanf("%d",&n);for(;n--;)puts((s+="*").data());} ``` [Try it online](https://ideone.com/LiziXt) Ungolfed: ``` //this one hurts, but c++ strings are mutable #include<string> int main(){ int n; //this one hurts as well std::string s; //read input to n //longer than 'std::cin>>n', but no #include<iostream> needed scanf("%d",&n); // same as 'while(n--)', also characterwise, but way cooler for(;n--;) //add a '*' the string //data() does the same as c_str() //puts automatically adds an '\n' puts((s+="*").data()); } ``` [Answer] ## [Jellyfish](http://github.com/iatorm/jellyfish), ~~12~~ ~~11~~ 9 bytes ``` \P$'* i ``` [Try it online!](http://jellyfish.tryitonline.net/#code=XFAkJyoKICBp&input=NQ) ### Explanation The above program is equivalent to the following functional pseudocode: ``` \ P $ i '* map_prefixes(print, reshape(input(), '*')) ``` The `$` (reshape) creates a string of `N` asterisks. `\P` creates a function which takes a list (or string) and passes each of its prefixes to `P` (print). Hence, this successively prints strings of `1` to `N` asterisks. [Answer] ## R, 45 bytes For loop approach: ``` for(i in 1:scan())cat(rep("*",i),"\n",sep="") ``` [Answer] # Haskell, 35 ~~38~~ bytes List comprehension thanks to nimi: ``` f x=unlines[[1..n]>>"*"|n<-[1..x]] ``` Old version: ``` f 0="" f n=f(n-1)++([1..n]>>"*")++"\n" ``` Alternate version: ``` g n=([1..n]>>"*")++"\n" f n=[1..n]>>=g ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 12 bytes ``` yke:"*"rj@w\ ``` [Try it online!](http://brachylog.tryitonline.net/#code=eWtlOiIqInJqQHdc&input=NQ) This assumes that a trailing new line is acceptable ### Explanation ``` yk The range [0, …, Input - 1] e Take one element I of that range :"*"rj Juxtapose "*" I times to itself @w Write that string followed by a new line \ False: backtrack to another element of the range ``` ### No trailing new line, 15 bytes ``` -:"*"rj:@[f~@nw ``` [Try it online!](http://brachylog.tryitonline.net/#code=LToiKiJyajpAW2Z-QG53&input=) This one works by taking all prefixes of `"*" × Input`. [Answer] # Pyth, 7 Bytes ``` VQ*\*hN ``` Knocked off a byte thanks to **@ETHproductions** [Try it online](https://pyth.herokuapp.com/?code=VQ%2a%5C%2ahN&input=5&debug=0) # **using @PIetu1998's Technique** **6, bytes** ``` j*L*\*S ``` [Answer] # [2sable](http://github.com/Adriandmen/2sable), ~~24~~ 11 bytes ``` >G')Ç>çJN×, ``` [Try it online!](http://2sable.tryitonline.net/#code=PkcnKcOHPsOnSk7Dlyw&input=NA&debug=on) And no sign of any asterisks! Golfed from 24 to 11 thanks to [@Emigna](https://codegolf.stackexchange.com/users/47066/emigna). Explanation: ``` >G')Ç>çJN×, > Push input+1 G For N in range (1,input+1) ')Ç>çJ Push '*' by getting ascii code for ')' and adding 1 Nx, Print '*' repeated N times ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) 75 Bytes Includes +3 for `-A` ``` {(({})[()]<{({}[()]<(((((()()()){}()){})){}{})>)}{}((()()()()()){})>)}{} ``` [Try it online!](http://brain-flak.tryitonline.net/#code=eygoe30pWygpXTx7KHt9WygpXTwoKCgoKCgpKCkoKSl7fSgpKXt9KSl7fXt9KT4pfXt9KCgoKSgpKCkoKSgpKXt9KT4pfXt9&input=MTA&args=LUE) --- **Explanation:** ``` {(({})[()]< >)} #reduce the top element by one until it is 0 after doing the following #Push this element back on to act as a counter for the next step. #(counts down from input to 0 we'll call this counter) {({}[()]< >)} #reduce the top element by one until it is 0 after doing the following #(counts down from counter to 0) (((((()()()){}()){})){}{}) #push 42 (the ASCII code for *) {} #pop the counter used to push #the right number of *s ((()()()()()){}) #push a 10 (newline) {} #pop the null byte ``` [Answer] # [Dyalog APL](https://dyalog.com), 8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ↑'*'⍴⍨¨⍳ ``` `↑` matrify the list consisting of `'*'` the string "\*" `⍴⍨` reshaped by `¨` each of `⍳` the integers 1 through the argument. [TryAPL online!](http://tryapl.org/?a=f%u2190%u2191%27*%27%u2374%u2368%A8%u2373%20%u22C4%20f%A81%202%203%204%205&run) [Answer] # [V](http://github.com/DJMcMayhem/V), 8 bytes ``` Àé*hòlÄx ``` [Try it online!](http://v.tryitonline.net/#code=w4DDqSpow7Jsw4R4&input=&args=NQ) [Answer] # JavaScript (ES6), 34 bytes ``` f=x=>x?f(x-1)+` `+'*'.repeat(x):'' ``` [Answer] # [Perl 6](https://perl6.org), 23 bytes ``` {.put for [\~] '*'xx$_} ``` ( If the output is allowed to be a list of "lines" without newlines `.put for` can be removed ) ## Explanation: ``` # bare block lambda with implicit parameter 「$_」 { .put # print with trailing newline for # for every one of the following [\~] # produce using concatenation operator '*' xx $_ # list repeat '*' by the input } ``` ( See documentation for [`produce`](https://docs.perl6.org/routine/produce) if you don't understand what `[\~] ...` is doing ) [Answer] # Perl 5, 22 20 bytes ``` say"*"x$_ for 1..pop ``` Run it with the `-E` switch to get `say`. ``` $ perl -E 'say"*"x$_ for 1..pop' 5 * ** *** **** ***** ``` Written out as a full program it would look like this: ``` use strict; use feature 'say'; # get the argument my $limit = pop @ARGV; foreach my $i (1 .. $limit) { say "*" x $i; } ``` * `shift` and `pop` implicitly work on `@ARGV` (the list of arguments) outside of subs * `..` is the [range operator](http://perldoc.perl.org/perlop.html#Range-Operators) * [`say`](http://perldoc.perl.org/functions/say.html) includes a newline * `x` is an operator to repeat strings and is [explained in perlop](http://perldoc.perl.org/perlop.html#Multiplicative-Operators) [Answer] ## Perl, 19 bytes *-4 bytes thanks to [@Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) and his rework of the solution!* ``` eval"s//*/;say;"x<> ``` Needs free `-E` (or `-M5.010`) flag to run. Takes a number from input : ``` perl -E 'eval"s//*/;say;"x<>' <<< "5" ``` [Answer] # J, ~~11~~ 8 bytes *Saved 3 bytes thanks to miles!* ``` ]\@#&'*' ``` Here is a decomposition: ``` (]\@#&'*') x x (]\@#) '*' ]\ (x # '*') ``` Now, this last one reads as "the prefixes (`]\`) of the string consisting of `x` copies of `'*'`". Observe: ``` 5 ]\@# '*' * ** *** **** ***** ]\ 5# '*' * ** *** **** ***** ]\ 5 # '*' * ** *** **** ***** ]\@#&'*' 5 * ** *** **** ***** ``` ## Test case ``` f =: ]\@#&'*' f 3 * ** *** f 5 * ** *** **** ***** f 1 * f 2 * ** f &. > ;/1+i.10 +-+--+---+----+-----+------+-------+--------+---------+----------+ |*|* |* |* |* |* |* |* |* |* | | |**|** |** |** |** |** |** |** |** | | | |***|*** |*** |*** |*** |*** |*** |*** | | | | |****|**** |**** |**** |**** |**** |**** | | | | | |*****|***** |***** |***** |***** |***** | | | | | | |******|****** |****** |****** |****** | | | | | | | |*******|******* |******* |******* | | | | | | | | |********|******** |******** | | | | | | | | | |*********|********* | | | | | | | | | | |**********| +-+--+---+----+-----+------+-------+--------+---------+----------+ ``` ## Older, 11-byte solutions ``` '*'#~"+1+i. ``` This is equivalent ``` '*' #~"0 1 + i. ``` `1 + i.` is the range `[1, x]`. Then, `'*' #~"0` applied to this range shapes (element) copies of `'*'`. Bonus program: ``` [:#&'*'\#&1 ``` This is a capped fork `#&'*'\` applied to the result of `#&1` of the input. `#&1` gives an array of `x` ones, and `#&'*'\` shapes `'*'` to the prefixes of this array. ### Test cases ``` f1 =: '*'#~"+1+i. f2 =: [:#&'*'\#&1 f1 1 * f2 2 * ** f1 3 * ** *** f2 4 * ** *** **** f2 5 * ** *** **** ***** f1 5 * ** *** **** ***** (f1;f2)3 +---+---+ |* |* | |** |** | |***|***| +---+---+ f1;f2 f1 ; f2 (f1;f2)5 +-----+-----+ |* |* | |** |** | |*** |*** | |**** |**** | |*****|*****| +-----+-----+ (f1;f2)10 +----------+----------+ |* |* | |** |** | |*** |*** | |**** |**** | |***** |***** | |****** |****** | |******* |******* | |******** |******** | |********* |********* | |**********|**********| +----------+----------+ ``` [Answer] # Vim, ~~22~~, 18 keystrokes ``` O <esc>J:h r<cr>lyEZZ<C-v>{@" ``` Huge credit to [@Udioica](https://codegolf.stackexchange.com/a/95900/31716) for coming up with an awesome vim answer that I expanded on. This answer does not contain any asterisks, in hopes of winning the bounty. Explanation: Input is typed before the rest of the program. Udioica came up with this awesome trick. Typing `<n>O <esc>` will create a pyramid of spaces and one empty line, as long as you have `:set autoindent` enabled. This option comes on by default in vim 8 and neovim, though not older versions of vim. Since this also creates an extra line, we use `J` to join this line with the next one, which effectively just removes the line below us. Now at this point, we need to replace all of these spaces with asterisks. If I was not worried about using asterisks in my code, I would just visually select the whole thing `<C-v>{` and type `r*`, which replaces each character of the selection with an asterisk. But I can't do that. So we open up the help pages to `:h r`. The interesting thing about this is that in the vim-window, this page is displayed as: ``` r r{char} Replace the character under the cursor with {char}. ... ``` With the cursor on the first 'r'. However, the file itself actually contains this text: ``` *r* r{char} Replace the character under the cursor with {char}. ... ``` Pretty convenient. So we move over one character with `l`, and yank the text `r*` with `yE` ([y]ank to the [E]nd of this word). To close this buffer, we use the shortcut to save a file `ZZ`. Now, we visually select our spaces, and run the yanked text as if we had typed it by doing `@"`. This works because "@" runs the following register as vim-keystrokes, and " is the default register for yanking. [Answer] # C, ~~47~~ ~~46~~ ~~45~~ 43 bytes Takes input from the command line ``` f(n){for(n&&f(n-1);~n;putchar(n--?42:10));} ``` Basically if n is not 0 recurse on n-1. at the top of the recursion where n is 0 it just prints a newline, the for loop terminates when n is -1 or ~n is zero, otherwise it prints ASCII 42 which is '\*'. Try it on [ideone](http://ideone.com/CArPHN) # C++ 58 Bytes + 19 for including iostream is 77 ``` #include<iostream> int f(int n){for(n&&f(n-1);~n;std::cout<<(n--?"*":"\n"));} ``` ``` main(c,v)char**v; { f(atoi(v[1])); } ``` ``` a.exe 3 * ** *** ``` [Answer] # Commodore 64/VIC-20 BASIC (and compatible C= 8-bits), ~77 tokenized BASIC bytes ``` 0 INPUT"NUMBER OF *";A:ON-(A<1)GOTO1:J=1:FORI=1TOA:FORX=1TOJ:PRINT"*";:NEXTX:J=J+1:PRINT:NEXTI 1 : ``` Technically line 1 isn't required, but I'm mis-using the `ON...GOTO` command as a conditional `GOTO` in line zero so I added in the shortest possible line 1 to end it gracefully. You will need to use Commodore keyword abbreviations to fit line zero on a C64, see the screen shot below (Note that the C128 in 128 mode might have different keyword abbreviations, but then you can enter more characters so you probably won't need it): [![Commodore 64 asterisk printing simulator](https://i.stack.imgur.com/DYdSj.png)](https://i.stack.imgur.com/DYdSj.png) [Answer] ## [Retina](http://github.com/mbuettner/retina), 14 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $** . $`$&¶ ``` [Try it online!](http://retina.tryitonline.net/#code=LisKJCoqCi4KJGAkJsK2&input=NQ) ### Explanation ``` .+ $** ``` Turn the input `N` into `N` asterisks. ``` . $`$&¶ ``` Replace each asterisk with everything up to and including that asterisk (this is the `$`$&`) and a linefeed (this the `¶`). [Answer] # MATL, ~~9~~ 8 bytes *1 byte saved thanks to @Luis* ``` :"42@Y"c ``` [**Try it Online**](http://matl.tryitonline.net/#code=OiI0MkBZImM&input=NQ) ]
[Question] [ ![xkcd π comic](https://i.stack.imgur.com/kIiLp.jpg) Happy π Day. The goal of this question is to calculate the area for a circle of radius 3, where A = πr². The catch is that you have to use the constant π that is defined in a different language than the one you are programming in. For example, you can write a C program that uses Fortran's `MATH::PI`, or a Python program that uses Java's `java.lang.Math.PI`. Rules: * Your code must use a stored value of π from a different language for the calculation. (i.e. it must be stored in a constant or math library.) * All of the code for your program must fit in a single file. For example, You cannot write one program in C to print π, then another in Java to run the C program. (However, you *can* write a Java program that writes and compiles a C program by itself.) * You cannot download π from a webpage and claim that your constant came from PHP/ASP/HTML. Here is an example that runs in Bash, and uses Python's stored `math.pi` value: ``` #!/bin/bash PI=`python -c 'import math; print math.pi'` bc -l <<< "3 * 3 * $PI" ``` Output: ``` 28.27433388231 ``` This is a Popularity Contest, so the entry with the most votes after a week wins. **Edit:** After one week, the prize goes to DigitalTrauma with 93 points. Thanks for the awesome assembler tip - I did not know that the the FPU stored the constant in hardware. I expected this contest to be about finding funny ways to throw clock cycles away, but that one could actually save a few. \* Image courtesy of: <http://xkcd.com/10/> [Answer] # C + x86 assembly Not satisfied with a constant defined in the software of your language? Why not use a language that can access a constant value of PI right from your FPU hardware: ``` #include <stdio.h> int main (int argc, char **argv) { double pi; __asm__("fldpi" : "=t" (pi)); printf("%g\n", 3 * 3 * pi); return (0); } ``` [Answer] ### Python, bash, C, J, PHP and Python3 ``` import subprocess p = subprocess.Popen(""" echo ' #define _USE_MATH_DEFINES #include <stdio.h> #include <math.h> int main(int pi) { if (pi == 1) printf("%.5f", M_PI); if (pi == 2) printf("o. 1"); if (pi == 3) printf("<?php printf(\\"%%.5f\\", pi()); ?>"); if (pi == 4) printf("import math; print(\\" %%.5f\\" %% math.pi)"); return 0; } ' > gcc -o pi ./pi ./pi J | jc ./pi and PHP | php ./pi and Python 3 | python3 """, shell=True, stdout=subprocess.PIPE) values_of_pi = map(float, map(str.strip, p.stdout.read().split())) pi = max(values_of_pi, key=values_of_pi.count) print pi * 3 * 3 ``` Just to be safe, this program retrieves pi from a few different languages, taking the most agreed upon value. More languages can easily be added for greater reliability. [Answer] # PHP/MYSQL ``` $link = mysqli_connect("localhost", "user", "password", "dbname"); $query = mysqli_query($link, 'SELECT PI() AS pi'); $row = mysqli_fetch_assoc($query); echo 3*3*$row['pi']; ``` [Answer] ## Perl/Tk with C, Pascal, Java, JavaScript, LaTeX3, Prolog, Perl, Scheme, Lua, Python, TeX/PGF The following Perl script displays a windows that lists the values of π and the calculated area. The value of π is taken from different languages as shown below. ![Result](https://i.stack.imgur.com/K6poJ.png) The one-file script: ``` #!/usr/bin/env perl use strict; $^W=1; use Tk; use Tk::Font; use Tk::HList; use Tk::ItemStyle; use Tk::PNG; # Function to calculate the area of the circle with radius 3 sub A ($) { use bignum; return 9*$_[0]; } my $title = 'Pi Day'; # Configuration of external program names my %prg = qw[ Pascal fpc Perl perl Prolog swipl Scheme guile1 TeX tex LaTeX latex ]; sub prg ($) { my $prg = shift; return $prg{$prg} // $prg; } # Column headers my @header = ( '', 'Language', "\N{U+03C0}", "A(3) = A(r) = \N{U+03C0}\N{U+2009}r\N{U+00B2}", ); my $mw = MainWindow->new( -title => $title, ); # Font setup (larger font) my $font_size = '22'; my $font = $mw->Font(); $font->configure(-size => $font_size); # --------- # Utilities # --------- # Run program in backticks, quote arguments if needed and some error checking sub backticks_pi (@) { my @cmd = map{/[ ()$;<>|\x22]/ && length > 1 ? "'$_'" : $_} @_; print "[@cmd]\n"; my $catch = `@cmd`; if ($? == -1) { warn "Failed to execute: $!\n"; } elsif ($? & 127) { warn sprintf "Child died with signal %d!\n", $? & 127; } elsif ($?) { warn sprintf "Child exited with value %d!\n", $? >> 8; } else { return $1 if $catch =~ /^\s*(\d+\.\d+)\s*$/ or $catch =~ /\bpi\s*=\s*(\d+\.\d+)/; } warn "Could not find pi in the output of \"@cmd\"!\n"; return 0; } # Run a program with error checking sub run_cmd (@) { print "[@_]\n"; system @_; if ($? == -1) { warn "Failed to execute: $!\n"; } elsif ($? & 127) { warn sprintf "Child died with signal %d!\n", $? & 127; } elsif ($?) { warn sprintf "Child exited with value %d!\n", $? >> 8; } else { return $1; } return undef; } # Create a bitmap logo sub make_logo ($$$@) { my $name = shift; my $logo = shift; my $contents = shift; my $file = "piday-logo-$name.tmp"; if ($contents) { open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!"; print OUT $contents; close(OUT); } foreach (@_) { run_cmd @$_; } return $mw->Photo( -file => $logo, ) if -f $logo; return undef; } # Call foreign language to calculate pi sub make_pi ($$@) { my $file = shift; my $source = shift; if ($source) { open(OUT, '>', $file) or die "!!! Error: Cannot write `$file': $!"; print OUT $source; close(OUT); } my $cmd_last = pop; foreach (@_) { run_cmd @$_; } return backticks_pi @$cmd_last; } # Add result list table my $h = $mw->HList( -header => 1, -columns => scalar @header, -width => 100, -height => 20, -font => $font, )->pack( -expand => 1, -fill => 'both', ); # Add header for the result list table for (0 .. @header-1) { $h->header('create', $_, -text => $header[$_], ); } # Exit button my $quit = $mw->Button( -text => 'Quit', -command => sub {exit}, -font => $font, )->pack; my @list; my @cmd; my $pi; my $source; my $img; # GNU C # ----- $img = make_logo( 'C', 'piday-logo-c.png', '', [ prg('wget'), '-O', 'piday-logo-c-gccegg.png', 'http://gcc.gnu.org/img/gccegg-65.png', ], [ prg('convert'), '-scale', '54x64', 'piday-logo-c-gccegg.png', 'piday-logo-c.png', ], ); $source = <<'END_SOURCE'; #define _GNU_SOURCE #include <math.h> #include <stdio.h> #define xstr(s) str(s) #define str(s) #s int main() { long double pi = M_PI; printf("pi=%s", xstr(M_PIl)); return 0; } END_SOURCE $pi = make_pi( 'piday-c.c', $source, [ prg('gcc'), '-o', 'piday-c', 'piday-c.c', ], [ prg('./piday-c') ], ); push @list, { language => 'GNU C', pi => $pi, image => $img, }; # Java # ---- $img = make_logo( 'Java', 'piday-java.png', '', [ prg('wget'), '-O', 'piday-java.svg', 'https://upload.wikimedia.org/wikipedia/commons/a/a4/Java_logo_and_wordmark.svg', ], [ prg('convert'), '-scale', '35x64', 'piday-java.svg', 'piday-java.png', ], ); $source = <<'END_SOURCE'; public class PiDayJava { public static void main(String args[]) { System.out.println(Math.PI); } } END_SOURCE $pi = make_pi( 'PiDayJava.java', $source, [ prg('javac'), 'PiDayJava.java', ], [ prg('java'), 'PiDayJava', ], ); push @list, { language => 'Java', pi => $pi, image => $img, }; # Perl # ---- # Math/Complex.pm: sub pi () { 4 * CORE::atan2(1, 1) } @cmd = (prg('Perl'), '-e', 'use Math::Complex; print pi'); $pi = backticks_pi @cmd; my $img = Tk->findINC('Camel.xpm'); $img = $mw->Photo( -file => $img, ); push @list, { language => 'Perl', pi => $pi, image => $img, }; # Python # ------ @cmd = ( prg('echo'), 'import math;print math.pi', '|', prg('python'), ); $pi = backticks_pi @cmd; $img = make_logo( 'python', 'piday-logo-python.png', '', [ prg('wget'), '-O', 'piday-logo-python-master.png', 'http://www.python.org/static/community_logos/python-logo-master-v3-TM.png', ], [ prg('convert'), '-crop', '111x111+79+33', 'piday-logo-python-master.png', 'piday-logo-python-crop.png' ], [ prg('convert'), '-scale', '64x64', 'piday-logo-python-crop.png', 'piday-logo-python.png', ], ); push @list, { language => 'Python', pi => $pi, image => $img, }; # TeX # --- @cmd = ( prg('TeX'), '\input pgf \pgfmathparse{pi}\message{pi=\pgfmathresult}\end', ); $pi = backticks_pi @cmd; my $img = make_logo( 'tex', 'piday-logo-tex.png', '', [ prg('pdftex'), '\mag=4000 \nopagenumbers\font\sc=cmcsc10 \sc pgf\bye' ], [ prg('pdfcrop'), 'texput.pdf', 'piday-logo-tex.pdf', ], [ prg('convert'), 'piday-logo-tex.pdf', 'piday-logo-tex.png', ] ); push @list, { language => 'TeX/PGF', pi => $pi, image => $img, }; # LaTeX3 # ------ my $logo_source = <<'END_LOGO'; \mag=4000 \documentclass{article} \usepackage{hologo} \pagestyle{empty} \begin{document} \hologo{LaTeX3} \end{document} END_LOGO $img = make_logo( 'latex3', 'piday-logo-latex3.png', $logo_source, [ prg('pdflatex'), 'piday-logo-latex3.tmp' ], [ prg('pdfcrop'), 'piday-logo-latex3.pdf', 'piday-logo-latex3-crop.pdf', ], [ prg('convert'), 'piday-logo-latex3-crop.pdf', 'piday-logo-latex3.png', ] ); $source = <<'END_LATEX3'; \documentclass{article} \usepackage{expl3} \ExplSyntaxOn \msg_term:n { pi=\fp_eval:n { pi } } \ExplSyntaxOff \stop END_LATEX3 $pi = make_pi( 'piday-latex3.tex', $source, [ prg('LaTeX'), 'piday-latex3.tex', ], ); push @list, { language => 'LaTeX3', pi => $pi, image => $img, }; print "****************\n"; # Lua # --- $img = make_logo( 'Lua', 'piday-logo-lua.png', '', [ prg('wget'), '-O', 'piday-logo-lua.gif', 'http://www.lua.org/images/lua-logo.gif', ], [ prg('convert'), '-scale', '64x64', # '50x50', 'piday-logo-lua.gif', 'piday-logo-lua.png', ], ); $source = 'print(math.pi)'; $pi = make_pi( 'piday-lua.lua', $source, [ prg('texlua'), 'piday-lua.lua', ] ); push @list, { language => 'Lua', pi => $pi, image => $img, }; # JavaScript # ---------- $img = make_logo( 'JavaScript', 'piday-logo-javascript.png', '', [ prg('wget'), '-O', 'piday-logo-rhino.jpg', 'https://developer.mozilla.org/@api/deki/files/832/=Rhino.jpg', ], [ prg('convert'), '-scale', '127x64', 'piday-logo-rhino.jpg', 'piday-logo-javascript.png', ], ); $source = 'print(Math.PI)'; $pi = backticks_pi( prg('java'), '-cp', prg('js.jar'), 'org.mozilla.javascript.tools.shell.Main', '-e', $source, ); push @list, { language => 'JavaScript', pi => $pi, image => $img, }; # Scheme # ------ $img = make_logo( 'Scheme', 'piday-logo-scheme.png', '', [ prg('wget'), '-O', 'piday-logo-lambda.svg', 'https://upload.wikimedia.org/wikipedia/commons/3/39/Lambda_lc.svg', ], [ prg('convert'), '-scale', '64x64', 'piday-logo-lambda.svg', 'piday-logo-scheme.png', ], ); $source = '(display (* 2 (acos 0)))'; $pi = backticks_pi( prg('Scheme'), '-c', $source, ); push @list, { language => 'Scheme', pi => $pi, image => $img, }; # Prolog # ------ $img = make_logo( 'Prolog', 'piday-logo-prolog.png', '', [ prg('wget'), '-O', 'piday-logo-swipl.png', 'http://www.swi-prolog.org/icons/swipl.png', ], [ prg('convert'), '-scale', '78x64', 'piday-logo-swipl.png', 'piday-logo-prolog.png', ], ); $source = ":- format('~15f~n', [pi]).\n"; $pi = make_pi( 'piday-prolog.pro', $source, [ prg('Prolog'), '-c', 'piday-prolog.pro', ] ); push @list, { language => 'Prolog', pi => $pi, image => $img, }; # Pascal # ------ $img = make_logo( 'Pascal', 'piday-logo-pascal.gif', '', [ prg('wget'), '-O', 'piday-logo-pascal.gif', 'http://www.freepascal.org/pic/logo.gif', ] ); $source = <<'END_PASCAL'; program piday_pascal; uses sysutils, math; begin writeln(format('%.16f', [pi])); end. END_PASCAL $pi = make_pi( 'piday-pascal.pas', $source, [ prg('Pascal'), 'piday-pascal.pas', ], [ prg('./piday-pascal'), ] ); push @list, { language => 'Pascal', pi => $pi, image => $img, }; # Sort and fill the table rows @list = sort { my $diff = (length $b->{'pi'} <=> length $a->{'pi'}); return $diff if $diff; return "\L$a->{'language'}\E" cmp "\L$b->{'language'}\E"; } @list; foreach my $x (@list) { my $e = $h->addchild(""); my $col = 0; if ($x->{'image'}) { $h->itemCreate($e, $col++, -itemtype => 'image', -image => $x->{'image'}, ); } else { $col++; } $h->itemCreate($e, $col++, -itemtype => 'text', -text => $x->{'language'}, ); $h->itemCreate($e, $col++, -itemtype => 'text', -text => $x->{'pi'}, ); $h->itemCreate($e, $col++, -itemtype => 'text', -text => A $x->{'pi'}, ); } MainLoop; __END__ ``` ## Languages The following list shows the languages and the code that is used to get π. * **GNU C:** GNU extensions are used to get a higher precision of π. ``` #define _GNU_SOURCE #include <math.h> #include <stdio.h> #define xstr(s) str(s) #define str(s) #s int main() { long double pi = M_PI; printf("pi=%s", xstr(M_PIl)); return 0; } ``` * **Pascal:** Compiled with [Free Pascal](http://www.freepascal.org/). ``` program piday_pascal; uses sysutils, math; begin writeln(format('%.16f', [pi])); end. ``` * **Java:** ``` public class PiDayJava { public static void main(String args[]) { System.out.println(Math.PI); } } ``` * **JavaScript:** [Rhino](https://developer.mozilla.org/en-US/docs/Rhino) is used for executing JavaScript. ``` print(Math.PI) ``` * **LaTeX3:** ``` \documentclass{article} \usepackage{expl3} \ExplSyntaxOn \msg_term:n { pi=\fp_eval:n { pi } } \ExplSyntaxOff \stop ``` * **Prolog:** [SWI Prolog](http://www.swi-prolog.org/) is used as Prolog compiler. ``` :- format('~15f~n', [pi]). ``` * **Perl:** For fun and completeness. ``` use Math::Complex; print pi; ``` * **Scheme:** The uses Scheme implementation is [GNU Guile](https://www.gnu.org/software/guile/). ``` (display (* 2 (acos 0))) ``` * **Lua:** [`texlua`](http://www.luatex.org/) is used as Lua interpreter. ``` print(math.pi) ``` * **Python:** ``` import math print math.pi ``` * **TeX/PGF:** π is taken from its definition of package [pgf](http://www.ctan.org/pkg/pgf) and plain TeX is used as TeX format: ``` \input pgf \pgfmathparse{pi} \message{pi=\pgfmathresult} \end ``` [Answer] # [dg](http://pyos.github.io/dg/) ``` print ((import '/math/pi')*3**2) ``` How it works: dg is a language that compiles to CPython bytecode. Conveniently, it's compatible with python libraries. `import` statements in dg return the object they're importing, so this program basically does this: ``` print (<PYTHON'S MATH.PI>*3**2) ```     No, I don't expect any upvotes. :) [Answer] ## C++ & Lua 5.2 Nothing says overkill quite like embedding an entire language interpreter to access the pi constant. ``` #include <lua.hpp> #include <cmath> #include <iostream> #define R 3 int main( void ) { lua_State* vm = luaL_newstate(); luaL_openlibs( vm ); luaL_dostring( vm, "function get_pi() return math.pi end" ); lua_getglobal( vm, "get_pi" ); lua_call( vm, 0, 1 ); lua_Number PI_ = lua_tonumber( vm, -1 ); std::cout << PI_ * pow( R, 2 ) << std::endl; lua_close( vm ); return 0; } ``` [Answer] # bash + PHP + bc A fairly simple one-liner: ``` echo "scale=14;3*3*`php -r 'echo pi();'`"|bc ``` Output: ``` 28.274333882308 ``` [Answer] # MATLAB + Java (21 bytes) Not sure if MATLAB is cheating, but here we go ``` java.lang.Math.PI*3^2 ``` Output: `Format Short` ``` 28.2743 ``` Output: `Format Long` ``` 28.2743338823081 ``` Formatting type does not affect the value that is stored, it only impacts how it is printed out into the console [Answer] # Bash, Node, Ruby, Python ``` #!/bin/bash node -pe 'Math.PI' \ | ruby -e 'puts ARGF.read.to_f * 3' \ | python -c 'import sys; print(float(sys.stdin.read()) * 3)' ``` [Answer] # perl ``` perl -ne '/M_PI\s*([\d.]*)/&&print $1*3*3' < /usr/include/math.h ``` [Answer] ## Powershell + MS SQL Server Here is one for Powershell and SQL server (from 2005 up) ``` add-pssnapin sqlserverprovidersnapin100 add-pssnapin sqlservercmdletsnapin100 $pi=Invoke-Sqlcmd -query "select PI() as sql" $pi.sql *3*3 ``` and here as a single liner: ``` add-pssnapin sqlserverprovidersnapin100;add-pssnapin sqlservercmdletsnapin100;(Invoke-Sqlcmd -query "select PI() as sql").sql*3*3 ``` Will post some more later on:) [Answer] # JavaScript/PHP Has to be saved as a \*.php file and called in a browser from some server which interprets PHP. ``` <script type="text/javascript"> alert(3*3*<?php echo M_PI;?>); </script> ``` Could be golfed by using short tags and substituting 3\*3 with 9 (is this allowed?): ``` <script type="text/javascript"> alert(9*<?=M_PI?>); </script> ``` pi() has the same length as M\_PI, so there's no winner. [Answer] ## Emacs Lisp: writing, compiling, and running C ``` (with-temp-buffer (with-temp-file"/#rad.c"(insert"#include<math.h>\n#include<stdio.h>\nint main(void){printf(\"%f\",M_PI*3*3);}")) (shell-command"gcc /#rad.c -o /#rad && /#rad"(current-buffer))(string-to-number(buffer-string))) ``` ungolfed ``` (with-temp-buffer (with-temp-file "/#rad.c" (insert" #include<math.h> #include<stdio.h> int main(void){ printf(\"%f\",M_PI*3*3); }")) (shell-command "gcc /#rad.c -o /#rad && /#rad" (current-buffer)) (string-to-number(buffer-string))) ``` bonus: You could triple language this one by running emacs in batch using -eval and surrounding the expression in `(print)`. This would result in Bash running lisp which writes compiles and runs C reads the output and prints it out to your shell in bash. [Answer] For this question, I created my own language,called Digits. The syntax consists of p, a constant representing pi, and digits. When run, it returns all of the digits (and p) multiplied together. Here is my interpreter and code, written in Python: ``` def interpret(kode): out=1.0 for i in kode: if(i=='p'): out*=3.14159265 else: out*=int(i) return out print(interpret("p33")) ``` [Answer] # bc + dc + bash (30 chars for the golfers) Here's a golfy little one: ``` $ dc<<<"3d*`bc -l<<<'a(1)*4'`*p" 28.27433388230813914596 $ ``` * `bc -l<<<'a(1)*4'` produces pi (it is stored as a constant in the bc math lib for the a() (arctan) function. * `dc<<<"3d*`pi`*p"` pushes 3 to the stack, duplicates the value on the top of the stack (3) and multiples, then pushes pi to the stack and multiples, then prints the top of the stack. [Answer] # OCaml + awk Nobody likes OCaml? * Use OCaml to *compute* Pi * `awk` to calculate Pi\*r2 Here it is: ``` ocaml <<< "4.0 *. atan 1.0;;" | awk '/float/{printf("%.12f", 3*3*$NF)}' ``` The answer is: ``` 28.274333882308 ``` [Answer] # C++/C ``` #include <math.h> #include <iostream> int main(int argc, char** argv) { std::cout << 3*3*M_PI << std::endl; return 0; } ``` [Answer] Very simple, uses bash to access the C math library: ``` bc -l <<< "3 * 3 * `grep -w M_PI /usr/include/math.h | awk '{ print $4 }'`" ``` [Answer] # VimScript + Python ``` :py import math :ec pyeval("math.py")*3*3 ``` result: ``` 28.274334 ``` [Answer] Since Fortran does not actually have an intrinsic value for pi (which is was OP seems to indicate with the statement "Fortran's `MATH::PI`"), I had to write one for C. I opted, rather than actually defining it, that I'd just determine it using [some fast algorithm](http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm): ``` #include <math.h> double pi_eval(){ double a = 1.0; double b = 1.0/sqrt(2.0); double t = 0.25; double x = 1.0; double y; int i; for(i=0; i<4; i++){ y = a; a = 0.5*(a+b); b = sqrt(b*y); t -= x*(y-a)*(y-a); x *= 2.0; } return (a+b)*(a+b)/(4.0*t); } ``` (saved as `pi_calc.c`) Which is then used in `area_calc.f90`: ``` program area_calc use, intrinsic :: iso_c_binding implicit none interface function pi_eval() bind(c) use, intrinsic :: iso_c_binding real(c_double) :: pi_eval end function pi_eval end interface real(c_double) :: pi, area pi = pi_eval() print *,"area=",3.0*3.0*pi end program area_calc ``` This outputs the required ``` area= 28.2743338823081 ``` One compiles this using ``` gcc -c pi_calc.c gfortran -o area pi_calc.o area_calc.f90 ``` [Answer] # R & C++ Requires the `inline` and `Rcpp` packages in R. ``` get.pi <- inline::cxxfunction(plugin="Rcpp", includes="#include <cmath>", body="return wrap(M_PI);") get.pi() * 3 ^ 2 ``` `cxxfunction` creates, compiles and links a C++ function behind the scenes. Yes, there is quite a lot of code generation happening, and `return wrap(M_PI);` is C++ code (along with the `#include` part). [Answer] # Java + JavaScript ``` class Pi { public static void main(String... args) throws Throwable { System.out.println((double) new javax.script.ScriptEngineManager() .getEngineByName("JavaScript").eval("Math.PI") * Math.pow(3, 2)); } } ``` ``` 28.274333882308138 ``` [Answer] # Julia using Python ``` julia> using PyCall julia> @pyimport math julia> math.pi*3^2 28.274333882308138 ``` That was fun, I'd never used PyCall before. The interface is super easy to use. [Answer] # R + grep + awk + dc ``` echo pi | R --no-save --quiet | grep -v '^>' | awk '{print $2}' | dc -e '?3 3 **p' ``` Output: ``` 28.274337 ``` [Answer] ## Using Lua's π in Java This program uses the library LuaJ to evaluate Lua in Java and get π. It also squares the area with Lua. Enjoy! ``` ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine se = sem.getEngineByName("luaj"); se.eval("pi = math.pi"); double pi = (double) se.get("pi"); int r = 3; se.eval("radius = "+r); se.eval("rsquared = math.pow(radius, 2)"); int rsquared = (int) se.get("rsquared"); double area = pi * rsquared; System.out.println("For a circle with a diameter of "+r+", the area is "+area+"."); ``` The output: `For a circle with a diameter of 3, the area is 28.274333882308138.` [Answer] # Jython + Java This should work in Jython. I'm not sure, as I have no way to test it ATM. ``` from java.lang import Math print Math.PI * 3 ** 2 ``` Jython can access the Java libraries, so I can just import the Math class from java.lang and use its PI constant to calculate the area of the circle. Golfed: ``` import java.lang.Math.PI;print PI*3*3 ``` Or, if I'm allowed to code in 3^2: ``` import java.lang.Math.PI;print PI*9 ``` [Answer] # bash (PI from perl,python,c) Maybe if we combine everything we've got, we get a more accurate result? :) ``` #!/bin/bash exec >&>(bc -l|tail -n1) perl <<EOF use Math::Trig; print pi EOF echo -n + python <<EOF import sys from math import pi sys.stdout.write(str(pi)) EOF echo -n + cat > pi.c <<EOF #include <math.h> main(){printf("%.16f",M_PI);} EOF gcc pi.c -o pi &>/dev/null ./pi rm -f pi pi.c echo ";" echo "(last/3)*3.^2" ``` [Answer] ## Ruby+Python ``` puts `python -c "from math import pi; print pi"`.to_f * 3**2 ``` [Answer] HTML + PHP ``` <html><body> value of area of circle is <br> <?php echo 3*3*M_PI; ?> </body></html> ``` Confused whether it satisfy the 3rd rule. but since M\_PI is already used so it should count. [Answer] # **ACTIONSCRIPT3 + javascript(using parse.com)** ``` Parse.CFunction('getPi',{},function(returned){trace(3*3*returned.result)}); ``` parse class link <https://github.com/camdagr8/AS3-Parse-Class/blob/master/com/illumifi/Parse.as> with code: ``` public static function CFunction(className:String, params:Object = null, success:Function = null, error:Function = null) { var url:String = Parse.api + "functions/" + className; Parse.Call(url, URLRequestMethod.POST, params, null, success, error); } ``` parse main.js: ``` Parse.Cloud.define("getPi", function(request, response) { response.success(Math.PI); }); ``` result: ``` 28.274333882308138 ``` ]
[Question] [ You may have heard of the "Hacker Logo", also called the "Hacker Emblem". It looks like this: [![hacker logo](https://i.stack.imgur.com/RlIUZ.png)](http://3.bp.blogspot.com/_-4G7w0aTpbg/Ss6YxNNOJ6I/AAAAAAAAAXA/rSmdVWvSZqM/s400/Symbol+Hacker.jpg) This is a pattern from a mathematical simulation called the Game of Life. The glider is the simplest Life pattern that moves, and the most instantly recognizable of all Life patterns. # The challenge The challenge is pretty simple: Display the hacker logo. This is defined as: * A 3x3 grid with a border, a white background and gray gridlines. * Five black dots arranged in the GoL glider pattern. * Nothing else. # The rules * The black dots must fill **40%**-**80%** of their individual grid-boxes. * You will display the emblem with graphical output but **no ASCII art**. * The output must be at least **30x30 pixels**. * The output must only have the colors **gray, black and white**. * Each grid-box in the grid will be the same size. The grid will be a **regular 3x3 square**. * You may not pull the logo from the internet or your filesystem. * Your program will display the logo on an empty screen/window. If it terminates it must do so normally. * Note that "dots" does not necessarily mean "circles". A "dot" is a single geometric shape centered in the middle of the grid-box with one surface. For example, while a circle or square will qualify as a dot, two triangles or a checkerboard will not. # The winner As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in each language wins! Please include a screenshot of the output of your program in your answer. [Answer] # CSS+HTML, ~~56+84=140 bytes~~ 52+84=136 bytes Saved 4 bytes by incorporating suggestions from the comments. ``` td{border:1px solid#888;line-height:.4;font-size:3em ``` ``` <table cellspacing=0><tr><td><td>•<td><tr><td><td><td>•<tr><td>•<td>•<td>• ``` This uses the UTF-8 character `•` which is 2 bytes long and takes advantage of the graciousness of HTML syntax. [Answer] # Mathematica, 62 bytes ``` Grid[{{,a=██,},{,,a},{a,a,a}},Frame->All,FrameStyle->Gray] ``` [![enter image description here](https://i.stack.imgur.com/wBDct.jpg)](https://i.stack.imgur.com/wBDct.jpg) # Mathematica, 71 bytes ``` Grid[{{,l=Graphics@Disk[],},{,,l},{l,l,l}},Frame->All,FrameStyle->Gray] ``` [![enter image description here](https://i.stack.imgur.com/vo4q8.jpg)](https://i.stack.imgur.com/vo4q8.jpg) [Answer] # GLSL (fragment shader), ~~278~~ ~~235~~ 256 bytes ``` precision highp float;void main(){vec2 a=gl_FragCoord.xy/20.-.2;ivec2 b=ivec2(a);a-=vec2(b)+.5;if(b.x>2||b.y>2)discard;gl_FragColor=a.x<-.5||a.y<-.5||a.x>.3||a.y>.3?vec4(.5,.5,.5,1.):length(a+.1)<.4&&(b.x+b.y-3)*b.y==0?vec4(0.,0.,0.,1.):vec4(1.,1.,1.,1.);} ``` [![enter image description here](https://i.stack.imgur.com/gKrwI.png)](https://i.stack.imgur.com/gKrwI.png) See it in action: <http://glslsandbox.com/e#40717.2> [Answer] # [Python 2](https://docs.python.org/2/), ~~ 169 140 ~~ 137 bytes ``` from turtle import* up() shape("square") color("gray",[1]*3) i=9 while i:i-=1;goto(20-i/3*20,i%3*20-20);stamp();209&2**i or dot(15,0,0,0) ``` Actual size, 61 by 61, plotted within a much larger canvas of 300 by 400: [![actual size](https://i.stack.imgur.com/HHWOq.png)](https://i.stack.imgur.com/HHWOq.png) Showing the pixel grid: [![pixel grid version](https://i.stack.imgur.com/2JFBS.png)](https://i.stack.imgur.com/2JFBS.png) The dots use 177 pixels within the range of 40%-80% whether considering the 19 by 19 white fill (144.4-288.8) or the 21 by 21 including both borders (176.4-352.8). *Note:* the program terminates and closes the canvas window as soon as the drawing has been finished, to allow manual window closure append the line `done()`. `turtle` is a Python package developed for introductory graphical programming. A pen starts at `x,y=0,0` in the middle of a 300 by 400 pixel canvas (by default), `up` lifts the pen, `goto` moves the pen, `shape` sets the shape of the pen to a named shape (`"square"` is a predefined shape with a default pixel-width of 21), `color` sets the colour, where two parameters set stroke (with default a width of 1) and fill; a byte is saved by using the `(r,g,b)` tuple option to replace `"white"` with `[1,1,1]` using the list multiplication `[1]*3`. Finally `dot` draws a dot with the given width in pixels and colour. The dot's default width value is too small to qualify, as is `9` so I made it an aesthetic and qualifying `15`. The dot's colour could be `"black"` but the unpacked `(r,g,b)` tuple of `0,0,0` is shorter by two bytes. The pen must move away from any dot at the end since otherwise the gray/white pen hides the dot. The grid is traversed using a div (`/`) and mod (`%`) of `i` starting at `8` (`i` is initialised to `9` but is decremented at the beginning of the `while` loop) and working down to `0`, offsetting the results of `2,1,0` to `-1,0,1` using `(1-...)` and scaling each up to the grid size using a factor of 20 (note that `20-i/3*20` is actually a byte less than `20*(1-i/3)`, same goes for `%`). This produces the order [bottom-left, centre-left, top-left, bottom-middle, centre-middle, top-middle, bottom-right, centre-right, top-right], and requires a "`hasDot`" evaluation of `[1,0,0,1,0,1,1,1,0]`, which is `302` in binary so may be accessed by inspecting the `i`th power of two component of `302` with using a bitwise-and, `302&2**i`. This can then be inverted to `209&2**1` enabling the use of `or` rather than `and`. [Answer] # HTML & CSS, 155 bytes Turns out HTML is ***really*** forgiving about syntax errors. *1 byte saved thanks to @Octopus* · *1 byte saved thanks to @Downgoat* · *2 bytes saved thanks to @StephenS* *2 bytes saved thanks to @Ryan* · *3 bytes saved thanks to @styfle* · *4 bytes saved thanks to @Ferrybig* *13 bytes saved thanks to @SteveBennett* ``` p{height:33px;width:33px;border-radius:50%;background:#000;margin:0 ``` ``` <table cellspacing=0 border=1><td><td><p><td><tr><td><td><td><p><tr><td><p><td><p><td><p ``` [Answer] # [Applesoft BASIC](https://en.wikipedia.org/wiki/Applesoft_BASIC), ~~479~~ ~~476~~ ~~516~~ ~~515~~ ~~483~~ 482 bytes -32 by using unreadable variable names :P -1 because Apple decided to be magical and let me use an implicit/nonexistent GOTO Here is my own (very beatable) program for an example of an output that does not use circles: ``` 1GR:POKE49234,0:COLOR=15:FORI=0TO39:VLIN0,47ATI:NEXT:COLOR=5:S=21:W=S:H=27:X=INT((40-W)/2):Y=INT((48-H)/2):D=INT(W/3):DX=D:C=Y+H:G=X+W:FORI=0TO3:VLINY,C ATX+I*D:NEXT:D=INT(H/3):FORI=0TO3:HLINX,G ATY+I*D:NEXT:YH=INT(D/2):Z=Y+H-YH:XH=INT(DX/2):COLOR=0:FORI=0TO2:B=Z:A=X+XH+I*DX:GOSUB5:NEXT:B=B-D:GOSUB5:B=B-D:A=A-DX:GOSUB5:K=PEEK(-16384):IFK<128THEN2:K=PEEK(-16368):TEXT:HOME:END 5VLINB+2,B-3ATA:VLINB+2,B-3ATA-1:VLINB+2,B-3ATA+1:VLINB+2,B-3ATA+2:VLINB,B-1ATA-1:VLINB,B-1ATA+2:RETURN ``` Output: [![](https://i.stack.imgur.com/Hqlde.png)](https://i.stack.imgur.com/Hqlde.png) [Answer] # IA-32 machine code, ~~81~~ 80 bytes Hexdump: ``` 60 8b f9 b8 50 35 20 20 ab b8 32 35 36 20 ab ab ab fe 4f fe 33 c9 66 49 51 8a c1 d4 55 50 8a c5 d4 55 5b b2 80 84 c0 74 1f 84 db 74 1b b2 ff 2c 10 3c 35 77 13 93 2c 10 3c 35 77 0c 8d 0c 58 8a cd b0 e4 d2 e0 79 01 42 92 aa 59 e2 cb aa 61 c3 ``` It's a `fastcall` function called `doit` that returns the image in PGM format in the supplied buffer. Usage: ``` char buf[256 * 256 + 256]; doit(buf); FILE* f = fopen("k.pgm", "wb"); fwrite(buf, 1, sizeof buf, f); fclose(f); ``` Output: [![hacker's logo](https://i.stack.imgur.com/Ak6MU.png)](https://i.stack.imgur.com/Ak6MU.png) I used 256x256 resolution because ~~it's cool~~ it lets me split the pixel's index in `ecx` automatically into coordinates `y` in `ch` and `x` in `cl`. Also, the PGM file format requires the number 255 in the image header. The inner squares are 54x54 (41% of the cell by area). Source code (can be compiled by Visual Studio): ``` pushad; // save all registers mov edi, ecx; // edi is now the pointer to output mov eax, ' 5P'; // PGM file header stosd; // store it mov eax, ' 652'; // the number 256 and a space stosd; // store the width stosd; // store the height stosd; // store maximum brightness dec byte ptr [edi-2]; // fix maximum brightness to 255 xor ecx, ecx; // initialize the counter of pixels dec cx; // to 65535 myloop: push ecx; mov al, cl; // al = cl = x coordinate in the image _emit 0xd4; // divide by 85 _emit 85; // ah = x cell number, al = x coordinate in cell push eax; mov al, ch; // al = ch = y coordinate in the image _emit 0xd4; // divide by 85 _emit 85; // ah = y cell number, al = y coordinate in cell pop ebx; // bh = x cell number, bl = x coordinate in cell mov dl, 0x80; // gray pixel value test al, al // is cell boundary (y)? je output1; test bl, bl; // is cell boundary (x)? je output1; mov dl, 255; // white pixel value sub al, 16; cmp al, 53; ja output1; // if outside the inner square, output white xchg eax, ebx; // exchange the registers to shorten following code sub al, 16; cmp al, 53; ja output1; // if outside the inner square, output white lea ecx, [ebx * 2 + eax]; // cell index = y * 2 + x mov cl, ch; mov al, 0xe4; // load the bitmap for the glider pattern shl al, cl; // shift the needed but into SF jns output1; // the bit was 0? - output white inc edx; // the bit was 1? - change to black output1: xchg eax, edx; stosb; // output the byte pop ecx; loop myloop; stosb; // output an additional gray pixel popad; ret; ``` The cell pattern ``` 0 1 0 0 0 1 1 1 1 ``` can be represented by an "optimized" bitmap of 7 bits. The bits are indexed by the expression `y * 2 + x`, where `(x,y)` is the location of the cell. This expression gives the same index to 2 pairs of cells. It's a lucky coincidence that the bit values there are the same. [Answer] # PNG, ~~105~~ 100 bytes ![PNG image](https://i.stack.imgur.com/UkWtc.png)    (i.e. this image file) Considering that HTML and other [non-programming languages are allowed](https://codegolf.meta.stackexchange.com/a/10426/8478), I was curious to see how much I could golf a plain browser-displayable image, to serve as a baseline comparison. The result is compressed with the open-source tools [optipng](http://optipng.sourceforge.net) (`-o7 -zm1-9 -strip all`) and [pngwolf](https://github.com/jibsen/pngwolf-zopfli). I also experimented with [zopflipng](https://github.com/google/zopfli), but the results were bigger. Other closed-source compression tools might be able to shave off a couple more bytes. Image data in base64: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAA fCAAAAAA6xUnlAAAAK0lEQVR42mM4gB8wHPgPAwf+M0DAf4TYqDwp 4Ydp0qg8ofBDqMXKGpXHDwDDq0qBspApTgAAAABJRU5ErkJggg== ``` ``` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAA fCAAAAAA6xUnlAAAAK0lEQVR42mM4gB8wHPgPAwf+M0DAf4TYqDwp 4Ydp0qg8ofBDqMXKGpXHDwDDq0qBspApTgAAAABJRU5ErkJggg=="> ``` **Edit** I made the dots touch the cell top and bottom, to cause more repetitiveness in the pixel pattern and thus improve the compression ratio. But don't worry, a dot still only fills (7*9)/(9*9) ≈ 78% of its cell. # Non-standard PNG, 88 bytes As pointed out by [@anatolyg](https://codegolf.stackexchange.com/users/25315), there is some golfing potential by removing the IEND chunk (12 bytes). Technically, IEND is [required by the standard](https://www.w3.org/TR/PNG/#11Critical-chunks). However, each PNG chunk includes its own size and checksum information. It is therefore not absolutely necessary to have an end-marker. And indeed, all browsers I tested can display the image without issue. Unfortunately (or fortunately), this non-standard image is rejected by imgur, so I cannot actually upload it. This is the base64 encoding: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAA fCAAAAAA6xUnlAAAAK0lEQVR42mM4gB8wHPgPAwf+M0DAf4TYqDwp 4Ydp0qg8ofBDqMXKGpXHDwDDq0qBspApTg== ``` ``` <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAA fCAAAAAA6xUnlAAAAK0lEQVR42mM4gB8wHPgPAwf+M0DAf4TYqDwp 4Ydp0qg8ofBDqMXKGpXHDwDDq0qBspApTg=="> ``` [Answer] ## R (~~130~~ ~~119~~ 113 bytes) ``` plot(c(2,4,6,4,6),c(2,2,2,6,4),an=F,ax=F,xli=(l=c(1,7)),yli=l,xaxs="i",yaxs="i",pch=16,cex=19);grid(3,lt=1);box() ``` [![enter image description here](https://i.stack.imgur.com/rExSZ.png)](https://i.stack.imgur.com/rExSZ.png) [Answer] ## Python 2.7, ~~214~~ ~~311~~ 309 bytes ``` from matplotlib.pyplot import* f,x=subplots() j=(0,0),(1,0),(2,0),(1,2),(2,1) for i in j:x.add_artist(Circle((i),.4,color='k')) x.tick_params(labelbottom='off',labelleft='off') for o in x.spines.values():o.set_edgecolor('gray') for s in 'xy':exec"x.set_"+s+"ticks((.5,1.5,2.5));"+s+"lim(-.5,2.5);" grid() ``` This is my first attempt here at code golf, so I'm sure this can be improved upon. I would have liked to not established the limits, but it appears that matplotlib can't detect that I plotted circles where I did. Without setting xlim() and ylim() it only shows the bottom two circles. Output: [![Edit](https://i.stack.imgur.com/Y7MxR.png)](https://i.stack.imgur.com/Y7MxR.png) Edit:Fixed the color of the borders and removed the tick numbers. I must say matplotlib is very densely worded, and not too friendly with changing axis colors. Shaved off 3 bytes thanks to @DJMcMayhem Edit:Took off two bytes by setting my ticks as a tuple inside of set\_ticks functions. [Answer] # Bash + ImageMagick, ~~233~~ 226 characters ``` convert xc: +antialias -resize 31 -draw "stroke gray fill none ${r=rectangle} 0,0 10,30$r 20,0 30,30$r 0,0 30,10$r 0,20 30,30stroke #000 fill #000 ${c=circle} 15,5 15,8$c 25,15 25,18$c 5,25 5,28$c 15,25 15,28$c 25,25 25,28" x: ``` Sample output: ![Glider drawn with Bash and ImageMagick](https://i.stack.imgur.com/4mIUi.png) ### Bash + ImageMagick, 215 characters ``` convert xc: -resize 31 -draw "stroke gray fill none ${r=rectangle} 0,0 10,30$r 20,0 30,30$r 0,0 30,10$r 0,20 30,30stroke #000 fill #000 ${c=circle} 15,5 15,8$c 25,15 25,18$c 5,25 5,28$c 15,25 15,28$c 25,25 25,28" x: ``` The question owner not answered yet the [anti-aliasing question](https://codegolf.stackexchange.com/questions/123797/display-the-hacker-logo/124152#comment304123_123797) and some other solutions also have additional gray shades added by the anti-aliasing, so for now this shorter one looks also acceptable. Sample output: ![Glider drawn with Bash and ImageMagick - with anti-aliasing](https://i.stack.imgur.com/WuBSX.png) [Answer] # Ruby, 144 166 164 148 144 bytes ``` require'ruby2d' set background:'grey' c=482;g=2,13,24;d=0 g.map{|y|g.map{|x|Square.new(x,y,9);Square.new(x+2,y+2,5,"black")if c[d]>0;d+=1}} show ``` Output: [![output](https://i.stack.imgur.com/Jhspj.png)](https://i.stack.imgur.com/Jhspj.png) Edit: Now has grey gridlines. [Answer] # Tikz, ~~193~~ ~~175~~ 170 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\def\a{)rectangle(}\def~{)circle(1)(}\draw(4,6\a2,0)(0,\a6,6)(0,2\a6,4);\fill(1,1~3,1~5,1~5,3~3,5~,)}\end{document} ``` Here is the output: [![Output](https://i.stack.imgur.com/XAn6R.png)](https://i.stack.imgur.com/XAn6R.png) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~127~~ 124 bytes Removed 3 bytes thanks to Luis. `grid` is sufficient (instead of `grid on`). ``` spy([0,1,0;0,0,1;1,1,1],'.k',300),set(gca,'XTick',.5:4,'XTickLabel','','YTick',.5:4,'YTickLabel',''),axis(.5+[0,3,0,3]),grid ``` Outputs (after saving): Note that the output shows grey grid lines in the plot window. They turn black when saving it (for some reason). [![enter image description here](https://i.stack.imgur.com/HLuA1.jpg)](https://i.stack.imgur.com/HLuA1.jpg) Well, that was long and messy! Had to go through **a lot** of modifications to make this adhere to the specs. Explanation and hopefully some golfing coming up... [Answer] # Processing, 212 198 bytes ``` background(-1);noFill();stroke(99);rect(0,0,99,99);rect(0,33,99,33);rect(33,0,33,99);fill(0);int f=25;ellipse(15,83,f,f);ellipse(50,83,f,f);ellipse(83,83,f,f);ellipse(83,50,f,f);ellipse(50,15,f,f); ``` Basically, we are using simple Processing to draw a white Background, then setting the transparency of the rectangles used for the grid and drawing their strokes in gray. We continue by defining the rectangle, setting the fill value again to fill the circles black and defining fives circles. Voilà! [![enter image description here](https://i.stack.imgur.com/Il7lE.png)](https://i.stack.imgur.com/Il7lE.png) You could add ``` strokeWidth(2); ``` or more to see the color of the strokes better. (That's my first Code-Golf, I hope I did everything right.) EDIT: Thanks to Kritixi Lithos! Removed the newlines, changed to int f=25 and used -1 in background(float) [Answer] # SmileBASIC, 125 bytes ``` GCLS-1GCOLOR #GRAY GBOX.,8,30,38GBOX 10,8,20,38GBOX.,18,30,28G.,1G 1,2G-1,3G.,3G 1,3DEF G X,Y GPUTCHR X*10+12,Y*10,58081,.END ``` 58081 (U+E2E1, which is in the "Private Use Area" block) is the character code for a circle symbol. Putting it in a string would work too, but since it is encoded as 3 bytes in UTF-8, it would be the same length (and not show up correctly here). [![markdown is awful](https://kland.smilebasicsource.com/i/xnmnr.png)](https://kland.smilebasicsource.com/i/xnmnr.png) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~74~~ ~~69~~ ~~68~~ ~~64~~ 62 bytes ``` 4:6B&f,.5+w]'k.'5Y08W5$XG7lZG1$3ZG1tZG4:"@th1Kh'k'3$XG1Mbw3$XG ``` Try it at [**MATL Online!**](https://matl.io/?code=4%3A6B%26f%2C.5%2Bw%5D%27k.%275Y08W5%24XG7lZG1%243ZG1tZG4%3A%22%40th1Kh%27k%273%24XG1Mbw3%24XG&inputs=&version=20.0.0) (It takes a few seconds.) Output from the online interpreter: [![enter image description here](https://i.stack.imgur.com/5XQd2.png)](https://i.stack.imgur.com/5XQd2.png) [Answer] ## Processing, 134 bytes Inspired by @Zep, here's my Processing one-liner (and also my first code golf): ``` stroke(127);for(int i=0;i<9;i++){int x=i%3*30;int y=i/3*30;fill(255);rect(x+5,y+5,30,30);if(i==1||i>4){fill(0);ellipse(x+20,y+20,23,23);}}; ``` Thanks for @Kritixi Lithos for his brilliant tips on shaving a few bytes off! [![glider in Processing](https://i.stack.imgur.com/ORrJm.png)](https://i.stack.imgur.com/ORrJm.png) [Answer] # LaTeX + Tikz, 155 bytes ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\draw(0,0)grid(3,3);\foreach\x/\y in{0/0,1/0,2/0,2/1,1/2}\fill(\x+.5,\y+.5)circle(.5);}\end{document} ``` [![result](https://i.stack.imgur.com/4PkN4.png)](https://i.stack.imgur.com/4PkN4.png) [Answer] # Desmos, 90 characters/bytes Nobody saw that one coming. ``` (x-3)^2+(y-1)^2<=1 (x-1)^2+(y-1)^2<=1 (x-5)^2+(y-1)^2<=1 (x-5)^2+(y-3)^2<=1 (x-3)^2+(y-5)^2<=1 ``` [Graph link](https://www.desmos.com/calculator/lxzizsxfcp) Thanks pydude for reminding me about inequalities! If needed, I can crop the exported Desmos PNG to remove the axis/unneeded graph space [![Desmos exported PNG](https://i.stack.imgur.com/q33f7.png)](https://i.stack.imgur.com/q33f7.png) [![Desmos graph](https://i.stack.imgur.com/Nb24u.png)](https://i.stack.imgur.com/Nb24u.png) [Answer] # C#, 333 bytes ``` using System.Drawing;_=>{var b=new Bitmap(31,31);var g=Graphics.FromImage(b);g.FillRectangle(Brushes.White,0,0,31,31);for(int x=0,y;x<3;++x)for(y=0;y<3;++y){g.DrawRectangle(Pens.Gray,x*10,y*10,10,10);if(x==1&y<1|x>1&y==1|y>1)g.FillEllipse(Brushes.Black,x*10+1,y*10+1,8,8);}b.Save("t.png");System.Diagnostics.Process.Start("t.png");}; ``` Full/Formatted version: ``` using System.Drawing; Action<int> a = _ => { var b = new Bitmap(31, 31); var g = Graphics.FromImage(b); g.FillRectangle(Brushes.White, 0, 0, 31, 31); for (int x = 0, y; x < 3; ++x) for (y = 0; y < 3; ++y) { g.DrawRectangle(Pens.Gray, x * 10, y * 10, 10, 10); if (x == 1 & y < 1 | x > 1 & y == 1 | y > 1) g.FillEllipse(Brushes.Black, x * 10 + 1, y * 10 + 1, 8, 8); } b.Save("t.png"); System.Diagnostics.Process.Start("t.png"); }; ``` Idea is simple we create a graphics object from the image and use that to make the image all white. Then loop over each square of the image drawing the bounding rectangle. If it is one of the locations for a dot we draw that too. Lastly we save the image to file and let windows decide how to open it, in my case it opens with Windows Photo Viewer. Using a `Process` to show the image and saving to file is a lot shorter than creating a windows forms or WPF app because of all the different classes and extra fluff needed to create them. Output: [![Output](https://i.stack.imgur.com/iSEFM.png)](https://i.stack.imgur.com/iSEFM.png) [Answer] # PHP, 221+2 bytes ``` <?imagefill($i=imagecreatetruecolor(31,31),0,0,~0);function q($i,$x,$y,$f){imagerectangle($i,$x*=10,$y*=10,$x+10,$y+10,5e6);$f?:imagefilledellipse($i,$x+5,$y+5,8,8,0);}for($p=16;$p--;)q($i,$p&3,$p>>2,53>>$p&1);imagepng($i); ``` Save to file; call in browser. Should your browser display gibberish, insert `header("Content-Type:image-png");` before `imagepng($i);`. [![output](https://i.stack.imgur.com/Pj3Hn.png)](https://i.stack.imgur.com/Pj3Hn.png) The dots aren´t very round; that´s due to the small proportions. **breakdown** ``` function q($i,$x,$y,$f){ # function to draw quadrant: imagerectangle($i,$x*=10,$y*=10,$x+10,$y+10,5e6); # draw lines in 0x4c4b40 $f?:imagefilledellipse($i,$x+5,$y+5,8,8,0); # if bit not set, draw dot } imagefill($i= imagecreatetruecolor(31,31) # create image ,0,0,~0); # fill with 0xffffff (white) for($p=16;$p--;)q($i, # loop through positions, call function $p&3, # $x=lower two bits $p>>2, # $y=upper two bits 53>>$p&1 # $f=one bit from %0000 0000 0011 0101 ); # (reversed inverted bit mask for dots) imagepng($i); # output image ``` I think that `0x4c4b40` qualifies as approximated gray. If not, add four bytes. [Answer] # R 313 236 bytes ``` l=c(1,7) bmp('r',400,400) plot(x=c(4,6,2,4,6),c(6,4,2,2,2),cex=14,pch=19,xlim=l,ylim=l,xlab='',ylab='',xaxs='i',yaxs='i',axes=F) a=function(s,...){axis(s,labels=F,tck=1, col="gray",lwd=9,...)} a(1,xaxp=c(l,3)) a(2,yaxp=c(l,3)) dev.off() ``` Revised Code, based mostly on comments from @user2390246 saved 77 bytes. Much appreciate the help. Also, want to add a call-out to the shorter R solution by @mschilli. It shows an elegant way of addressing the problem of the R graphical defaults. # Output Goes to a file names "r". Omitting and extension saved me four bytes. But then I had to edit the file extension back to "bmp" to get it to upload. So maybe I should not get credit for those four bytes. [![The Hacker Logo](https://i.stack.imgur.com/fxVCY.png)](https://i.stack.imgur.com/fxVCY.png) # Commentary I thought to myself, "That graphic's nothing but a simple graph with five dots. Should be a simple matter to implement in a language with robust data graphics capabilities. Let's try it in R." But then I had to spend on the order of 80% of the bytes just working around R's graphic defaults. Kinda the wrong tool for the job.... I could not find a less verbose way of guaranteeing the size and aspect ratio of the graphic than by calling the bmp constructor and then dev.off(). The combination accounts for 25 bytes. If your R session is set up right, you might get a graphic that looks more or less correct without spending those bytes, but it's not reliable or consistent. [Answer] # TI-BASIC, ~~218~~ ~~140~~ 137 bytes Note: this byte count is a bit inflated. The program only uses 85 tokens, but that's saved in 137 bytes. Also, if you're using a non-color calculator, you could save another 4 tokens because you don't have to specify the color (which is blue by default), but I don't know if their screens are large enough for this challenge because I don't own one. prgmHACKER (138 bytes, 86 tokens): ``` {0,1,2,1,2}→L1 {0,0,0,2,1}→L2 .3→R For(I,0,5 L₁(I)+.5→A L₂(I)+.5→B For(N,0,R,dX √(R²-N² Line(A+N,B-Ans,A+N,B+Ans,BLACK Line(A-N,B-Ans,A-N,B+Ans,BLACK End End ``` For proper display, this program requires that Xmin = Ymin = 0, Xmax = Ymax = 3, Xscl = Yscl = 1. dX also needs to be properly set, but the calculator does that for you when you set any other window variable. I couldn't see how much space these variables used in RAM. Furthermore, the format settings should be { RectGC, CoordOff, GridLine, GridColor:MEDGRAY, Axes:OFF, ExprOff, BorderColor:1, Background:OFF } but these are toggled values and don't consume any extra space depending on the setting. [Answer] # R, ~~119~~ ~~114~~ 111 bytes (Thans to [@JayCe](https://codegolf.stackexchange.com/users/80010) for saving me 3 bytes) Not shorter than the [other R solution](https://codegolf.stackexchange.com/a/123925/6741), but a completely different approach: ``` layout(matrix(c(1,9,2:8),3,,T)) par(mar=0*1:4) for(i in 1:9){frame();if(i>4)points(.5,.5,,19,cex=29);box(fg=8)} ``` Uses a layout in which the 4 first plots are the empty cells, and the 5 others the ones with dots in them. [![Glider](https://i.stack.imgur.com/OJJNN.png)](https://i.stack.imgur.com/OJJNN.png) [Answer] # Excel VBA, 180 bytes An anonymous VBE Immediate window function that takes no input and outputs to the default worksheet object (`Sheet1`). ``` Cells.RowHeight=48:Cells.Interior.Color=-1:[B2:D4].Borders.Color=7434613:For Each s In[{21,32,13,23,33}]:Sheet1.Shapes.AddShape(9,48*(s\10)+4,Mid(s,2)*48+4,40,40).ShapeStyle=8:Next ``` **Commented Version** ``` Cells.RowHeight=48 '' Make the Cells square Cells.Interior.Color=-1 '' Remove the default grid [B2:D4].Borders.Color=7434613 '' Create the 3x3 gray grid at range `B2:D4` For Each s In [{21,32,13,23,33}] '' Assign and iterate over a list of where '' to place the dots; This list is a range that '' is coerced into a numeric array Sheet1.Shapes.AddShape( _ '' Add a shape to the Sheet1 object 9, _ '' An Oval (msoShapeOval) 48*(s\10)+4, _ '' At the calculated value from the left Mid(s,2)*48+4, _ '' At the calculated value from the top 40, _ '' that is 40 units wide 40 _ '' and is 40 units tall ).ShapeStyle=8 '' and is black filled with a black outline Next '' repeat to end of list ``` **Output** [![Hacker Logo](https://i.stack.imgur.com/J2Bpe.png)](https://i.stack.imgur.com/J2Bpe.png) -6 bytes for using `[{21,32,13,23,33}]` over `Split("21 32 13 23 33")` -2 bytes for using `Mid(s,2)` over `Right(s,1)` -3 bytes for using `(s\10)` over `Left(s,1)` [Answer] # Octave ~~107~~ ~~94~~ 103 bytes ``` scatter([1:3,3,2],[1,1,1:3],1e5,zeros(5,3),'.');axis off;a=[1,7]/2;for i=.5:3.5;line(a,i);line(i,a);end ``` or ``` plot([1:3,3,2],[1,1,1:3],'k.','markersize',250);axis off;a=[1,7]/2;for i=.5:3.5;line(a,i);line(i,a);end ``` both solutions are 103 bytes. ![](https://i.stack.imgur.com/CpKbR.png) [Answer] # gnuplot, ~~158~~ 156 bytes ``` se si ra-1 se xti 2 se yti 2 se st l 9 lc"gray"lt 1 se gr xt ls 9 yt ls 9 se bor ls 9 uns k se form"" p'-'w cir fc"black"fs s 3 5 1 5 3 1 1 1 1 3 1 1 5 1 1 ``` Because the radii are the same, I tried the following: ``` [... first eight lines same as above ...] p'-'u 1:2:(1) w cir fc"black"fs s 3 5 5 3 1 1 3 1 5 1 ``` But that lead to the same byte count. Ungolfed with comments: ``` set size ratio -1 # make it a square. set xtics 2 # vertical lines every 2 units set ytics 2 # horizontal lines every 2 units set style line 9 linecolor rgb "gray" linetype 1 # define line type 9 as solid gray set grid xtics linestyle 9 ytics linestyle 9 # make internal lines of type 9 set border linestyle 9 # make outside lines of type 9 unset key # no legend please set format "" # no numbers next to axes please plot '-' with circle fillcolor rgb "black" fill solid # plot black circles 3 5 1 # at these locations 5 3 1 1 1 1 3 1 1 5 1 1 end ``` [![](https://i.stack.imgur.com/UVVh4.png)](https://i.stack.imgur.com/UVVh4.png) [Answer] ## Apple Swift (iOS - CoreGraphics/QuartzCore) - 832 Bytes I drew the shape entirely using Quartz for an Apple iOS device. Unfortunatly this isn't a particularly size mindful language so the result is quite large, but this is as small as I can get it. ``` UIGraphicsBeginImageContext(CGSize(width:60,height:60));let c=UIGraphicsGetCurrentContext()!;UIColor.lightGray.setStroke();c.addRect(CGRect(x:0,y:0,width:60,height:60));c.move(to: CGPoint(x:20,y:0));c.addLine(to: CGPoint(x:20,y:60));c.move(to: CGPoint(x:40,y:0));c.addLine(to: CGPoint(x:40,y:60));c.move(to: CGPoint(x:0,y:20));c.addLine(to: CGPoint(x:60,y:20));c.move(to: CGPoint(x:0,y:40));c.addLine(to: CGPoint(x:60, y:40));c.strokePath();UIColor.black.setFill();c.addEllipse(in:CGRect(x:22,y:2,width:16,height:16));c.addEllipse(in:CGRect(x:42,y:22,width:16,height:16));c.addEllipse(in:CGRect(x:2,y:42,width:16,height:16));c.addEllipse(in:CGRect(x:22,y:42,width:16,height:16));c.addEllipse(in:CGRect(x:42,y:42,width:16,height:16));c.fillPath();let i=UIGraphicsGetImageFromCurrentImageContext();sub.addSubview(UIImageView(image:i)) ``` A more readable version for anyone that is interested: ``` UIGraphicsBeginImageContext(CGSize(width: 60, height: 60)) let c = UIGraphicsGetCurrentContext()! UIColor.lightGray.setStroke() c.addRect(CGRect(x: 0, y: 0, width: 60, height: 60)) c.move(to: CGPoint(x: 20, y: 0)) c.addLine(to: CGPoint(x: 20, y: 60)) c.move(to: CGPoint(x: 40, y: 0)) c.addLine(to: CGPoint(x: 40, y: 60)) c.move(to: CGPoint(x: 0, y: 20)) c.addLine(to: CGPoint(x: 60, y: 20)) c.move(to: CGPoint(x: 0, y: 40)) c.addLine(to: CGPoint(x: 60, y: 40)) c.strokePath() UIColor.black.setFill() c.addEllipse(in: CGRect(x: 22, y: 2, width: 16, height: 16)) c.addEllipse(in: CGRect(x: 42, y: 22, width: 16, height: 16)) c.addEllipse(in: CGRect(x: 2, y: 42, width: 16, height: 16)) c.addEllipse(in: CGRect(x: 22, y: 42, width: 16, height: 16)) c.addEllipse(in: CGRect(x: 42, y: 42, width: 16, height: 16)) c.fillPath() let i = UIGraphicsGetImageFromCurrentImageContext() sub.addSubview(UIImageView(image: i)) ``` Here is the output produced in the iOS Simulator: [![Output](https://i.stack.imgur.com/W4LNm.png)](https://i.stack.imgur.com/W4LNm.png) [Answer] # Ruby with Shoes, 118 characters ``` Shoes.app{9.times{|i| stroke gray fill white rect x=i%3*w=10,y=i/3*w,w,w stroke fill black oval x+2,y+2,7if 482[i]>0}} ``` Bit checking borrowed from [RJHunter](https://codegolf.stackexchange.com/users/14775/rjhunter)'s [comment](https://codegolf.stackexchange.com/questions/123797/display-the-hacker-logo#comment304648_123827) made on [Mark Thomas](https://codegolf.stackexchange.com/users/3743/mark-thomas)'s [Ruby solution](https://codegolf.stackexchange.com/a/123827). Sample output: ![Glider drawn with Ruby with Shoes](https://i.stack.imgur.com/Hm5xT.png) ]
[Question] [ In the [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), the following is [forbidden](https://codegolf.meta.stackexchange.com/a/1071/48934): > > Claiming that your answer is written in "MyOwnLanguage", where the command `x` means "read a sequence of numbers, split them into groups of three, and print the last numbers of those groups where the second number is less than the first" > > > Here, we are going to do the exact same thing. # Task Given a sequence of positive integers, whose length is divisible by 3, split them into groups of three, and print the last numbers of those groups where the second number is less than the first. # Testcases ``` Input Output [] [] [1,2,3,4,5,6,7,8,9] [] [2,1,3,5,4,6,8,7,9] [3,6,9] [3,1,4,1,5,9,2,6,5] [4] [100,99,123] [123] [123,123,456] [] [456,123,789] [789] ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply, so remember not to have a built-in command `x` that does this task. [Answer] # Octave, 32 bytes ``` @(L)L(x=3:3:end)(diff(L)(x-2)<0) ``` [Try it online!](https://tio.run/nexus/octave#@@@g4aPpo1Fha2xlbJWal6KpkZKZlgYU06jQNdK0MdD8n2arkJhXbM2VphFtpGOoY6xjqmOiY6ZjoWOuYxmryfUfAA "Octave – TIO Nexus") or [Verify test cases!](https://tio.run/nexus/octave#Zc9RCoMwDADQ/5yiny1kYFtbV52wA3gD6cdAC@LmxnQgiGd3qYMxWCAfeSQh2c68EhWfS53rvB0awZsuBDI@H5Q4JWILJbsMYwFTO06sZEvt2V9ALVGhxhQNWszwiM4TKpSEhtgSZR/UhCmlQUczFk1EmSToHEql/c9OpaNgaqz/IhU7Zkfn1wIg3J@sp7tkzobXrb3yeKeA2Nx044OHHZZ@FQLoP9je "Octave – TIO Nexus") ``` L3 = L(3:3:end) %extract last elements of groups d= diff(L) % first difference of the list y=d(1:3:end) %extract first elements of each subgroup of the difference idx = y<0 %check for negative numbers result = L3(idx) ``` [Answer] # Haskell, 30 29 bytes ``` x(a:b:c:l)=[c|b<a]++x l x d=d ``` My first attempt at golfing Haskell, so I may have missed an optimization or two -1 byte thanks to @JulianWolf [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes ``` >Ḋm3T×3ị ``` [Try it online!](https://tio.run/nexus/jelly#@2/3cEdXrnHI4enGD3d3/z/c/qhpjfv//9HRsTpcCtGGOkY6xjomOqY6ZjrmOhY6lmBRIx1DoKgpUNwMKGYOFTUGipoAsamOJVCXmY4pxAQDAx1LSx1DI2MI18gYxNYxMTUD84E0mG9uYRkbCwA "Jelly – TIO Nexus") ### How it works ``` >Ḋm3T×3ị Main link. Argument: A (array) Ḋ Dequeue; yield A without its first element. > Compare the elements of A with the elements of the result. m3 Select each third element, starting with the first. T Truth; get all indices of truthy elements. ×3 Multiply those indices by 3. ị Unindex; retrieve the elements at the redulting indices. ``` [Answer] # Mathematica, 37 bytes *Assuming this does satisfy the spec, ngenisis gets credit for this approach leading to a 1-byte saving!* ``` BlockMap[If[#>#2,Print@#3]&@@#&,#,3]& ``` Pure function. `BlockMap[...,#,3]&` splits the input list into sublists of length 3 and then operates on each sublist with the function `If[#>#2,Print@#3]&@@#&`. The result is that each qualifying last number is printed. The function also returns a value (namely a list of `Null`s a third as long as the input list), which seems to be allowed behavior. ## Mathematica, ~~42~~ 38 bytes *Thanks to Martin Ender for saving 4 bytes!* ``` Cases[#~Partition~3,{a__,b_}/;a>0:>b]& ``` Pure function. `#~Partition~3` does what you think. `Cases[X,P:>Q]` selects all the elements of `X` matching the pattern `P`, and returns the result of the transformation rule `:>Q` applied to each instance. Here, the pattern being matched is `{a__,b_}/;a>0`: `b_` will match the last element of the list and `a__` all the other elements (in this case, the first two); call them `y` and `z` for now. The sneaky `a>0` then expands to `y>z>0`, which is the test we want to apply (valid because the spec says everything will be a positive integer). And the transformation rule is `:>b`, which simply replaces each matching ordered triple with its last element. Original submission: ``` Last/@Select[#~Partition~3,#.{1,-1,0}>0&]& ``` Pure function; pretty much a straightforward implementation, other than `#.{1,-1,0}` which calculates the difference between the first and second elements of each 3-element sublist. [Answer] # R, 35 bytes ``` (x=matrix(scan(),3))[3,x[2,]<x[1,]] ``` [Answer] # Pyth, 10 bytes ``` eMf>FPTcQ3 ``` [Test suite](https://pyth.herokuapp.com/?code=eMf%3EFPTcQ3&test_suite=1&test_suite_input=%5B%5D%0A%5B1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%5D%0A%5B2%2C1%2C3%2C5%2C4%2C6%2C8%2C7%2C9%5D%0A%5B3%2C1%2C4%2C1%2C5%2C9%2C2%2C6%2C5%5D%0A%5B100%2C99%2C123%5D%0A%5B123%2C123%2C456%5D%0A%5B456%2C123%2C789%5D&debug=0) ``` eMf>FPTcQ3 cQ3 Chop the input into groups of size 3 f Filter on PT All but the last element >F Apply the greater than function eM Map to the last element ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (2), 14 bytes ``` ~c{Ṫ}ᵐ{k>₁&t}ˢ ``` [Try it online!](https://tio.run/nexus/brachylog2#@1@XXP1w56rah1snVGfbPWpqVCupPb3o//9oYx1DHRMgNtWx1DHSMQPSZkBoHvs/CgA "Brachylog – TIO Nexus") Brachylog rather struggles with this sort of problem. Note that this program has horrible computational complexity, as it brute-forces splitting the input into groups of 3 (having no "split into groups" builtin); it runs quickly with four groups but very slowly with five. ## Explanation ``` ~c{Ṫ}ᵐ{k>₁&t}ˢ ~c Split into groups { }ᵐ such that each group Ṫ has three elements { }ˢ then on each element, skipping that element on error: k with the list minus its last element >₁ assert that it's strictly decreasing & and with the original list t keep only its last element ``` [Answer] # JavaScript (ES6), ~~46~~ ~~44~~ ~~42~~ ~~41~~ 39 bytes ``` a=>a.filter((_,y)=>y%3>1&a[y-1]<a[y-2]) ``` * Saved 2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil). --- ## Try It Input a comma separated list of numbers, without any spaces. ``` f= a=>a.filter((_,y)=>y%3>1&a[y-1]<a[y-2]) i.oninput=_=>o.innerText=JSON.stringify(f(i.value.split`,`.map(eval))) console.log(JSON.stringify(f([]))) // [] console.log(JSON.stringify(f([1,2,3,4,5,6,7,8,9]))) // [] console.log(JSON.stringify(f([2,1,3,5,4,6,8,7,9]))) // [3,6,9] console.log(JSON.stringify(f([3,1,4,1,5,9,2,6,5]))) // [4] console.log(JSON.stringify(f([100,99,123]))) // [123] console.log(JSON.stringify(f([123,123,456]))) // [] console.log(JSON.stringify(f([456,123,789]))) // [789] ``` ``` <input id=i><pre id=o> ``` --- ## Explanation ``` a=> :Anonymous function taking the input array as an argument via parameter a a.filter((_,y)=> :Filter the array by executing a callback function on each element, with the index of the current element passed through parameter y. If the function returns 0 for any element, remove it from the array. y%3>1 :Check if the modulo of the current index is greater than 1. (JS uses 0 indexing, therefore the index of the 3rd element is 2; 2%3=2) & :Bitwise AND. a[y-1]<a[y-2] :Check if the element at index y-1 in array a is less than the element at index y-2 ) :End filtering method ``` [Answer] ## [J](http://jsoftware.com/), 14 bytes ``` _3&(>`[/\#]/\) ``` This evaluates to a monadic verb. [Try it online!](https://tio.run/nexus/j#@5@mYGulEG@spmGXEK0foxyrH6P5PzU5I18hTcFYwVDBBIhNFSwVjBTMgLQ5EBv9BwA "J – TIO Nexus") ## Explanation ``` _3&(>`[/\#]/\) Input is y. _3&( \ ) For each non-overlapping 3-element chunk of y, >`[/ check if first element is greater than second. Call the resulting array x. _3&( \) For each non-overlapping 3-element chunk of y, ]/ take the last element. # Keep those where the corresponding element of x is 1. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` 3ôʒR`‹i, ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@298eMupSUEJjxp2Zur8/x9tpGOoY6xjqmOiY6ZjoWOuYxkLAA "05AB1E – TIO Nexus") [Answer] ## [Alice](https://github.com/m-ender/alice), ~~12~~ 11 bytes *Thanks to Leo for saving 1 byte.* ``` I.h%I-rI~$O ``` [Try it online!](https://tio.run/nexus/alice#@@@pl6HqqVvkWafi//9/cmJKYmpmUloqAA "Alice – TIO Nexus") Uses the [code points of a string as the input list](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values) and outputs the character corresponding to the outputs that should be kept. ### Explanation ``` I Read x. Pushes -1 on EOF. .h% Compute x%(x+1). This terminates the program due to division by zero at EOF, but does nothing for non-negative x. I Read y. - Compute x-y. We only want to output z is this is positive. r Range. Pushes 0 1 ... n for positive n, and -n ... 1 0 for negative n (and simply 0 for n = 0). So this results in a positive number on top of the stack iff x-y is positive. I Read z. ~ Swap it with x-y > 0. $O Output z iff x-y > 0. Then the IP wraps to the beginning of the program to process the next triplet. ``` [Answer] ## [Husk](https://github.com/barbuz/Husk), 8 bytes ``` ṁΓȯΓ↑<C3 ``` [Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/D3c2npt8Yv25yY/aJto4G////z86livaUMdIx1jHRMdUx0zHXMdCxxIoZqRjCBQzBYqaAUXMwWLGQDETIDbVsQTqMNMxBek1MNCxtNQxNDIGcYyMQSwdE1MzIA9IgnnmFpaxAA "Husk – Try It Online") ## Explanation This program is a bit involved, so bear with me. ``` ṁΓȯΓ↑<C3 Implicit input (list of integers). C3 Split into slices of length 3. ṁ Map over slices and concatenate results ΓȯΓ↑< of this function, explained below. ``` The function `ΓȯΓ↑<` takes a list of length 3, `x = [a,b,c]`. The first `Γ` splits `x` into `a` and `[b,c]`, and feeds them as arguments to the function `ȯΓ↑<`. This should be equivalent to `((Γ↑)<)`, but due to a bug/feature of the interpreter, it's actually equivalent to `(Γ(↑<))`, interpreted as a composition of `Γ` and `↑<`. Now, `a` is fed to the latter function using partial application, the resulting function `↑<a` is given to `Γ`, which deconstructs `[b,c]` into `b` and `[c]`. Then `b` is fed to `↑<a`, resulting in a function that takes the first `b<a` elements from a list. This function is finally applied to `[c]`; the result is `[c]` if `a>b`, and `[]` otherwise. These lists are concatenated by `ṁ` to form the final result, which is printed implicitly. Without the "feature", I would have 9 bytes: ``` ṁΓoΓo↑<C3 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~43~~ 42 bytes 1 byte thanks to xnor. ``` f=lambda a,b,c,*l:(b<a)*(c,)+(l and f(*l)) ``` [Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCok6STrKOVY6WRZJOoqaWRrKOprZGjkJiXopCmoZWjqfk/xzbaSMdQx1jHVMdEx0zHQsdcxzKWq6AoM69EA6oEAA "Python 3 – TIO Nexus") [Answer] # [dc](http://enwp.org/dc_(computer_program)), 30 bytes ``` [???sAz1[[lAps.]s.<.dx]s.<.]dx ``` I/O: one number per line. [Answer] # [Perl 5](https://www.perl.org/), 31 bytes 30 bytes of code + `-p` flag. ``` s/\d+ (\d+) (\d+)/$2if$1<$&/ge ``` [Try it online!](https://tio.run/nexus/perl5#JYpLCgIxEET3OUWJYVBEMp2kO9PgUVzOB8HFoPcnlrqo36OOh315PXHd@zvd5wtOtPPfU8yPNcotDmlbehdkFFQoDA0TPGQIiZIZdyMpJJVSON8GDTKOcIfkEqhvoqoFrfbrbfIP "Perl 5 – TIO Nexus") Replaces each group of 3 numbers (`\d+ (\d+) (\d+)`) by the third (`$2`) if the second (`$1`) is less than the first (`$&`), and nothing otherwise. [Answer] # [CJam](https://sourceforge.net/p/cjam), 15 bytes ``` {3/{)\:>{;}|}%} ``` Anonymous block which expects argument on the stack, and leaves the result on the stack. [Try it online!](https://tio.run/nexus/cjam#HcsxDoMwEATAnldsQ5E0YJ/P5oyUJ/ABgsQXqB3n62ZNcavbkfbapvxvRaby@uZPWeuvjrWN@dzebT@G3cFDEKCISFhgNA9HU2qkpMeEFngK4yJC@3aeYQbnpRcv/UPQyMZ8WlrsuAE "CJam – TIO Nexus") (Runs all test cases) **Explanation** ``` 3/ e# Split the list into length-3 chunks. { e# For each chunk: ) e# Remove the last element. \:> e# Reduce the first 2 elements by greater than. {;}| e# If the first is not larger than the second, delete the third. }% e# (end for) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 82 bytes ``` {([({}[{}()]<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}((<({}<>)<>>))}{}{}}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#FYrJCQAxDAP/rkR@7pGFBeNGQioRqj2xH0LMSJuYoCYFXwG4py9EuhPtPFIUgaCyiSruYs0INJSurX8q2vuxy97KsN9u@2wc "Brain-Flak – TIO Nexus") ``` # Until the stack is empty (input is guaranteed to not contain 0) { # Push 1 for greater than or equal to 0 ([({}[{}()]<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} # ^------^ This part is Top - (Second + 1) # If the second number was less than the first... {{} # Get ready to push 2 zeros ((< # Move the next number to the other stack ({}<>)<> # Push those 2 zeros >))} # Pop 2 values. # This is either 2 zeros, or a 0 and a "last number" that shouldn't be printed {}{} # End loop } # Switch to the stack where we stored the numbers to be printed <> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` s3µṪWx>/µ€ ``` [Try it online!](https://tio.run/nexus/jelly#@19sfGjrw52rwivs9A9tfdS05v///8Y6hjomQGyqY6ljpGOmYwoA "Jelly – TIO Nexus") or [Verify test cases](https://tio.run/nexus/jelly#HcuxDYAwDATAhV6CxHGCG9agQJmChpqGXRAtBS1MAouED4Vf/pO@THIdz7kNc99cx7vs5V5rljFjdPAQBCgiEjoYzcPRlBop6TehBZ7CuIjQum1bmMF5qcVL/RA0sjH/ljrLHw "Jelly – TIO Nexus") *-3 bytes thanks to @LeakyNun* **Explanation** ``` s3µṪWx>/µ€ s3 - split into groups of three µ µ€ - on each group, do: ṪW - return the third element as the only element of a list x - repeat each element in that list the number of times >/ - corresponding to 1 if the second element of the group is greater than the first; 0 otherwise. ``` [Answer] ## R, 31 bytes Thanks to @Giuseppe again -1 byte: ``` f=\(x)x[!2:0][x[!-1:1]<x[!0:2]] ``` Thanks to @Giuseppe again -2 bytes: ``` f=\(x)x[!-2:0][x[!-1:1]<x[!0:2]] ``` With the R 4.1 it is a new game play (34 bytes). ;) ``` f=\(x)x[(i<--1:1)>0][x[!i]<x[i<0]] ``` where `\(x)` is a shorthand for the `function(x)`. 37 bytes version with `scan()` which I do not like, but it makes it shorter. ``` x=scan();x[(i<--1:1)>0][x[!i]<x[i<0]] ``` Version with `function()` which is easier to test (41 byte) ``` f=function(x)x[(i<--1:1)>0][x[!i]<x[i<0]] ``` Thanks to the @Giuseppe! Nice idea to use recycling of index. Test: ``` f(c()) f(c(1,2,3,4,5,6,7,8,9)) f(c(2,1,3,5,4,6,8,7,9)) f(c(3,1,4,1,5,9,2,6,5)) f(c(100,99,123)) f(c(123,123,456)) f(c(456,123,789)) ``` Output: ``` > f(c()) NULL > f(c(1,2,3,4,5,6,7,8,9)) numeric(0) > f(c(2,1,3,5,4,6,8,7,9)) [1] 3 6 9 > f(c(3,1,4,1,5,9,2,6,5)) [1] 4 > f(c(100,99,123)) [1] 123 > f(c(123,123,456)) numeric(0) > f(c(456,123,789)) [1] 789 ``` [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` lambda i:[i[c+2]for c in range(0,len(i),3)if i[c+1]<i[c]] ``` [Try it online!](https://tio.run/nexus/python2#HYvLDsIgEEV/hSWNd1Gg0NLol@AssBZDUtEQF/37OnQxj3tybrrdjy2@H88o8hxyWC6a0qeKReQiaiyvVfbY1iJzB9PlJJqi6MqH6Gjm3swQCEFBw2CAhcOICZ6ZhmJmmTom48kMs4HHwnPDwbZu38N7KG1a0KZ9GKzjxPtM4@SJ5m/N5SeS3LvjDw "Python 2 – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` IeI&Y)d0<) ``` The result is displayed as numbers separated by spaces. [Try it online!](https://tio.run/nexus/matl#@@@Z6qkWqZliYKP5/3@0sY6hjgkQm@pY6hjpmOmYxgIA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#Xcu9CoAwDATgvU/hJAg39C@tAccu7i5SCg76/o9Qr44GEu4@yNX3Z5/P5bbb0udSjl7b9B9THTwCIgQJGSu0merhaEJNlPxZoEWuQPmRIDRnLVThfBjFh5EQJbHxfi2v2l4). This displays a string representation of the output, so that an empty array is actually seen as `[]`. Note that in MATL a number is the same as a singleton array, so `[4]` is shown as `4`. ### Explanation ``` Ie % Implicit input. Reshape as a 3-row matrix (column-major order) I&Y) % Split into the third row and a submatrix with the other two rows d % Consecutive difference along each column of the submatrix 0< % True for negative values ) % Use as logical index into the original third row. Implicitly display ``` [Answer] # [Röda](https://github.com/fergusq/roda), 15 bytes ``` {[_3]if[_2<_1]} ``` Röda is nearly as short as the golfing languages... This takes three values from the stream, and pushes the third (`_3`) back, if the second (`_2`) is less than the first (`_1`). The underscores are syntax sugar for `for` loops, so the program could be written as `{{[a]if[b<c]}for a,b,c}` or even `{[a]for a,b,c if[b<c]}`. No TIO link, because it doesn't work on TIO for some reason (although works with the latest version of Röda that predates the challenge). [Answer] # Java 7, ~~86~~ 85 bytes ``` void c(int[]a){for(int i=-1;++i<a.length;)if(a[i++]>a[i++])System.out.println(a[i]);} ``` -1 byte thanks to *@PunPun1000* **Explanation:** [Try it here.](https://tio.run/nexus/java-openjdk#lY/NDoIwEITvPsUeaVgJfwUJ6ht48mg4VERtgoVI1RjCs@NSOXjw0kOzm3a@mWlZi66DXb8A6LTQsoTx2cgTlI5U@lAI1p@b@7SD3CyD3HXlWnh1pS76mjN5dsRBum6x/Q62f3e6unnNQ3vtnaBaTYKC5cMI0D6ONfnPMSblJqRy9pqkF5NFLYCiVfUCE98PLDd3f4znl191gCFGGCPHBFNcYWaHhxgQzskgITi1xSPCYzocM@qRILcs7/uYZRiEkSUXRhOEMU/sQAIMmK7mjw6LYfwA) ``` void c(int[]a){ // Method with integer-array parameter and no return for(int i=-1;++i<a.length;) // Loop over the array in steps of three at a time if(a[i++]>a[i++]) // If the value of the current index is larger than the next: System.out.println(a[i]); // Print the value on the third index // End of loop (implicit / single-line body) } // End of method ``` [Answer] # C#, 126 Bytes ``` using System.Linq;i=>Enumerable.Range(0,i.Length/3).Select(u=>3*u).Where(u=>i[u]>i[u+1]).Select(u=>i[u+2]); ``` If you want a whole program with the method it'd be **175 Bytes**: ``` using System.Linq;namespace S{class P{static System.Collections.IEnumerable X(int[]i)=>Enumerable.Range(0,i.Length/3).Select(u=>3*u).Where(u=>i[u]>i[u+1]).Select(u=>i[u+2]);}} ``` *Saved 7 Bytes with the help of TheLethalCoder* [Answer] # Awk, 27 bytes ``` {a[b=NR%3]=$0}!b&&a[2]<a[1] ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` 3ẇR∩÷<Tİ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCIz4bqHUuKIqcO3PFTEsCIsIiIsIlszLDEsNCwxLDUsOSwyLDYsNV0iXQ==) There are a ton of 8-byters but I haven't been able to find a single 7-byter. ``` 3ẇ # Cut into chunks of length 3 R # Reverse each chunk ∩÷ # Transpose and push each row to the stack < # For each, check if second > first Tİ # Only keep third elements where ^ is truthy ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 16 bytes ``` q~3/{~@@>S{;}?}% ``` The output is shown as numbers separated by spaces. [Try it online!](https://tio.run/nexus/cjam#@19YZ6xfXefgYBdcbV1rX6v6/3@0kYKhgrGCqYKJgpmChYK5gmUsAA "CJam – TIO Nexus") ### Explanation ``` q~ e# Read input list 3/ e# List of sublists of length 3 { }% e# Apply this to each sublist ~ e# Push sublist contents: 3 numbers @@ e# Rotate twice. This moves first two numbers to top > e# Greater than? S{;}? e# If so: push space (used as separator). Else: pop the third number e# Implicitly display ``` [Answer] # PHP, 89 Bytes ``` <?print_r(array_filter($_GET,function($v,$k){return $k%3>1&&$_GET[$k-1]<$_GET[$k-2];},1)); ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUol3dw2xjTbWMdQxAWJTHUsdIx0zHdNY6/8FRZl5JfFFGolFRYmV8WmZOSWpRRpg9TpppXnJJZn5eRoqZToq2ZrVRaklpUV5KtmqxnaGampgNdEq2bqGsTZwtlGsda2Ooaam9f//AA "PHP – TIO Nexus") [Answer] ## JavaScript, ~~108~~ ~~107~~ 108 bytes This is a valid JS anonymous (lambda) function. Add `x=` at the beginning and invoke like `x([5,4,9,10,5,13])`. Outputs as function `return`. ``` a=>(y=[],a.map((c,i)=>(i+1)%3?0:y.push(a.slice(i-2,i+1))),y.map(v=>v[1]<v[0]?v[2]:null).filter(c=>c|c==0)) ``` The snippet takes in the input as a list of comma separated integers. ``` x=a=>(y=[],a.map((c,i)=>(i+1)%3?0:y.push(a.slice(i-2,i+1))),y.map(v=>v[1]<v[0]?v[2]:null).filter(c=>c|c==0)) martin.oninput = e => { dennis.innerHTML = x(martin.value.split`,`.map(c=>parseInt(c,10))) } ``` ``` <input type=text id=martin><pre id=dennis> ``` [Answer] # Perl5.8.9, ~~73~~ 60 bytes ``` while(@F){@b=splice@F,0,3;$b[1]<$b[0]&&print$b[2]}print"-" ``` (58+2 for the 'n' flag to read the whole file and a to autosplit). Assumes the input is lines of space separated numbers Reduction thanks to Dada. Including the print at the end for visibility, that'd save 8 bytes if not. ]
[Question] [ [NetHack](https://en.wikipedia.org/wiki/NetHack) is a roguelike game where a player must retrieve the Amulet of Yendor from the lowest level of the dungeon. Commonly played via telnet, the entire game is represented with ASCII graphics. The game is extremely challenging and requires knowledge of many game mechanics in order to succeed. For the purposes of this challenge, assume that the entire dungeon is a single level and only 5×16 characters. Furthermore, assume that this is a "safe" dungeon or that you are only implementing a prototype—there will be no monsters, concerns about hunger, etc. In fact, you must only track the location of the character and the amulet and the game will effectively end when the player arrives at the same location as the amulet. # Challenge requirements * There will be a 5×16 dungeon (single level). * Give the player a starting location (optionally random) and the amulet a separate random (different each time the program is run) starting square inside the dungeon. That is, the amulet is not allowed to start on the same square as the player. * Accept four input keys which move the player one square at a time (four cardinal directions). Reading/processing other input is allowed (a readline() function that requires pressing 'enter', etc). * Travelling outside the bounds of the dungeon is not allowed. E.g., if the player is on the right edge of the dungeon pressing right should do nothing. * After initial generation and after each movement, print the state of the game. As this is code golf and printing is rather uninteresting, ignore the character count for the print function and function call *assuming no state changes*. Empty cells should be shown as period (`.`), amulet as double quote (`"`) and character as at symbol (`@`). * The game is over when the player "discovers" the amulet (arrives at the same square) # Winning This is a code golf challenege, the shortest code to meet the requirements one week from today will be declared winner. # Example Here is an example solution in C# (ungolfed) to show basic requirements and sample output. ``` using System; namespace nh { class Program { static Random random = new Random(); // player x/y, amulet x/y static int px, py, ax, ay; static void Main(string[] args) { px = random.Next(0, 16); py = random.Next(0, 5); // amulet starts on a position different from the player do { ax = random.Next(0, 16); } while (px == ax); do { ay = random.Next(0, 5); } while (py == ay); print(); do { // reads a single keypress (no need to press enter) // result is cast to int to compare with character literals var m = (int)Console.ReadKey(true).Key; // Move the player. Here standard WASD keys are used. // Boundary checks for edge of dungeon as well. if (m == 'W') py = (py > 0) ? py - 1 : py; if (m == 'S') py = (py < 5) ? py + 1 : py; if (m == 'A') px = (px > 0) ? px - 1 : px; if (m == 'D') px = (px < 16) ? px + 1 : px; // print state after each keypress. If the player doesn't // move this is redundant but oh well. print(); // game ends when player is on same square as amulet } while (px != ax || py != ay); } static void print() { Console.Write('\n'); for (int y=0; y<5; y++) { for (int x = 0; x < 16; x++) { if (x == px && y == py) Console.Write('@'); else if (x == ax && y == ay) Console.Write('"'); else Console.Write('.'); } Console.Write('\n'); } } } } ``` Total character count is 1474, but ignoring calls to the print function and its definition the final character count is `896`. Output when the program is run: ``` ................ ...."........... ..........@..... ................ ................ ``` Output (including above) after the 'a' key is pressed twice: ``` ................ ...."........... ..........@..... ................ ................ ................ ...."........... .........@...... ................ ................ ................ ...."........... ........@....... ................ ................ ``` [Answer] # [CHIP-8](https://en.wikipedia.org/wiki/CHIP-8), 48 bytes This may not be considered legal, but why the hell not. I wrote my program in CHIP-8, a bytecode-based programming language for a virtual game console. You can try the complete program (99 bytes) in your browser using an emulator/debugger I wrote called Octo: ![Screenshot](https://i.stack.imgur.com/uMI59.png) <http://johnearnest.github.io/Octo/index.html?gist=1318903acdc1dd266469> A hex dump of that complete program is as follows: ``` 0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08 0x22 0x36 0xF6 0x0A 0x22 0x52 0x40 0x00 0x12 0x16 0x46 0x07 0x70 0xFC 0x40 0x3C 0x12 0x1E 0x46 0x09 0x70 0x04 0x41 0x00 0x12 0x26 0x46 0x05 0x71 0xFC 0x41 0x10 0x12 0x2E 0x46 0x08 0x71 0x04 0x22 0x52 0x3F 0x01 0x12 0x0A 0x00 0xFD 0xA2 0x58 0xD4 0x54 0x22 0x52 0x62 0xFF 0xA2 0x5B 0xD2 0x34 0x72 0x04 0x32 0x3F 0x12 0x40 0x62 0xFF 0x73 0x04 0x33 0x14 0x12 0x40 0x00 0xEE 0xA2 0x5F 0xD0 0x14 0x00 0xEE 0xA0 0xA0 0x40 0x00 0x00 0x20 0x00 0xF0 0x90 0x90 0xD0 ``` You can move the player with the ASWD keys, or the 7589 keys on the original CHIP-8 keypad. If I remove all the code and data for drawing the background and the player, I instead get this 48 byte dump: ``` 0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08 0xF6 0x0A 0x40 0x00 0x12 0x12 0x46 0x07 0x70 0xFC 0x40 0x3C 0x12 0x1A 0x46 0x09 0x70 0x04 0x41 0x00 0x12 0x22 0x46 0x05 0x71 0xFC 0x41 0x10 0x12 0x2A 0x46 0x08 0x71 0x04 0x3F 0x01 0x12 0x08 0x00 0xFD ``` The ungolfed, complete form of the program was written in a high level assembly language as follows: ``` :alias px v0 :alias py v1 :alias tx v2 :alias ty v3 :alias ax v4 :alias ay v5 :alias in v6 : main px := 20 py := 4 ax := random 0b111100 ay := random 0b001000 draw-board loop in := key draw-player if px != 0 begin if in == 7 then px += -4 end if px != 0x3C begin if in == 9 then px += 4 end if py != 0 begin if in == 5 then py += -4 end if py != 16 begin if in == 8 then py += 4 end draw-player if vf != 1 then again exit : draw-board i := amulet sprite ax ay 4 draw-player tx := -1 i := ground : draw loop sprite tx ty 4 tx += 4 if tx != 63 then jump draw tx := -1 ty += 4 if ty != 20 then again ; : draw-player i := player sprite px py 4 ; : amulet 0xA0 0xA0 0x40 : ground 0x00 0x00 0x20 0x00 : player 0xF0 0x90 0x90 0xD0 ``` Note that the compiled bytes *themselves* are the CHIP-8 programming language; the assembler is simply a more convenient means of composing such programs. [Answer] # TI-BASIC, ~~42~~ ~~41~~ ~~38~~ ~~36~~ 35 bytes For your TI-83 or 84+ series graphing calculator. ``` int(5irand→A //Randomize amulet position 6log(ie^(6→C //15.635 + 4.093i Repeat Ans=A //Ans holds the player pos. (starts bottom right) iPart(C-iPart(C-Ans-e^(igetKey-i //Boundary check, after adjusting player position prgmDISPLAY End ---------- PROGRAM:DISPLAY For(X,0,15 For(Y,0,4 Output(Y+1,X+1,". If A=X+Yi Output(Y+1,X+1,"¨ If Ans=X+Yi Output(Y+1,X+1,"@ End End ``` Which direction the player will go is a function of the [key code](http://tibasicdev.wikidot.com/key-codes) of the key pressed, but four keys that definitely work are these on the top row: ``` Key [Y=] [WINDOW] [ZOOM] [TRACE] [GRAPH] ------------------------------------------- Key code 11 12 13 15 Direction Left Up Right Down ``` The amulet starts on one of the five squares in the first column, and the player starts at the bottom right square. For example, a possible arrangement is: ``` ................ ¨............... ................ ................ ...............@ ``` ## Explanation The player's position is stored as a complex number from `0+0i` to `15+4i`, where the real part goes to the right and the imaginary part goes down. This facilitates easy boundary checking on the top and left: we simply offset the number slightly and round towards zero. For example, if the offset is `0.5` and our position is `-1+3i` (off the screen to the left), then the position will be corrected to `iPart(-0.5+3.5i)=0+3i`, where it should be. Checking for the bottom and right boundaries is slightly more complicated; we need to subtract the number from a constant `C`, which is about `15.635 + 4.093i` (it's the shortest one I could find between `15+4i` and `16+5i`), round, subtract from `C` again to flip the number back, and round again. When a key is pressed, the unadjusted player position will move by 1 unit in some direction, but the integer part only changes when certain keys are pressed. Luckily, the keys that work are all on the top row. Below is a graph of the offsets in cases where keys 11, 12, 13, and 15 are pressed, and when no key is pressed (No press is the point inside the center square, causing the integer parts to be unchanged; the four keypresses' offsets have different integer parts). `C` is the red cross at the center of the circle. ![enter image description here](https://i.stack.imgur.com/BBrom.png) ## Old code (42 bytes): ``` int(9irand→A // 0≤rand≤1, so int(9irand) = i*x where 0≤x≤8 1 //set "Ans"wer variable to 1+0i Repeat Ans=A Ans-iPart(i^int(48ln(getKey-1 //add -i,-1,i,1 for WASD respectively (see rev. history) Ans-int(Ans/16+real(Ans/7 //ensure player is inside dungeon prgmDISPLAY //display on top 5 rows of the homescreen //(for this version switch X+Yi with Y=Xi in prgmDISPLAY) End ``` ### Limitations There is no way to escape a `"` character, so strings with a `"` cannot be generated inside a program. Therefore, this uses the umlaut mark `¨` instead of a quote (if there were an already-existing string with a quote mark, I could display that). To get `¨` and `@` in a program, an outside tool is required; however, it is valid TI-BASIC. [Answer] # Python 3, 86 bytes ``` def d(): import sys for y in range(5): line = [] for x in range(16): line.append('@' if y*16+x == p else \ '"' if y*16+x == a else \ '.') print(''.join(line)) print() sys.stdout.flush() p=79;a=id(9)%p while p-a:d();p+=[p%16<15,16*(p<64),-(p%16>0),-16*(p>15)][ord(input())%7%5] ``` Only counting the bottom two lines, and dropping `d();`. [Answer] # C, ~~122~~ ~~121~~ ~~115~~ ~~104~~ ~~102~~ 101 bytes ``` #define o ({for(int t=0;t<80;++t)t%16||putchar(10),putchar(t^p?t^a?46:34:64);}) p;main(a){for(a=1+time(0)%79;p^a;o,p+=(int[]){-16*(p>15),16*(p<64),-!!(p%16),p%16<15}[3&getchar()/2]);} ``` First time posting here ! I hope you like it :) `o` is the printing, erm, function. Our brave hero can be moved around with 2, 4, 6 and 8, but beware of not sending any other input (no newlines !). **Update 1 :** brought `a` and `i` into `main`'s parameters. **Update 2 :** OP having [confirmed](https://codegolf.stackexchange.com/questions/52547/minimal-nethack/52565#comment125400_52547) that a single string of input is OK, I got rid of `scanf` (which I used to skip the newline). **Update 3 :** Used a compound array literal and modified the input layout. Program now goes haywire if you enter an invalid direction ;) **Update 4 :** Noticed that the call to the printing function does not count. Took note to read rules more carefully. **Update 5 :** one byte saved, thanks to Mikkel Alan Stokkebye Christia. [Answer] # CJam, ~~46~~ ~~45~~ ~~44~~ ~~40~~ ~~39~~ 37 bytes ``` {'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P; 5,G,m*:Dmr~{P_l~4b2fm.+_aD&!$_W$=!}gP]; ``` The first line (defines a function that prints the current game state) and the **P**'s on the second line (call that function) do not contribute to the byte count. Both the starting position and the amulet's position are selected pseudo-randomly. The distribution is as uniform and the underlying PRNG allows. Input is `E`, `6`, `9` and `B` for **Up**, **Down**, **Left** and **Right**, with `Caps Lock` activated, followed by `Enter`. ### Alternate version ``` {'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P; 5,G,m*:Dmr~{P_ZYm*l~(=:(.+_aD&!$_W$=!}gP]; ``` At the cost of four more bytes, the input format is improved significantly: * This version accepts `8`, `2`, `4` and `6` for **Up**, **Down**, **Left** and **Right**, which matches the corresponding arrow keys on the numpad. * It also accepts `7`, `9`, `1` and `3` for the corresponding diagonal moves. ### Testing Since the I/O is interactive, you should try this code with the [Java interpreter](https://sourceforge.net/projects/cjam/files/). Download the latest version and run the program like this: ``` java -jar cjam-0.6.5.jar nethack.cjam ``` To avoid pressing `Enter` after each key, and for in-place updates of the output, you can use this wrapper: ``` #!/bin/bash lines=5 wait=0.05 coproc "$@" pid=$! head -$lines <&${COPROC[0]} while true; do kill -0 $pid 2>&- || break read -n 1 -s echo $REPLY >&${COPROC[1]} printf "\e[${lines}A" head -$lines <&${COPROC[0]} sleep $wait done printf "\e[${lines}B" ``` Invoke like this: ``` ./wrapper java -jar cjam-0.6.5.jar nethack.cjam ``` ### Main version ``` 5,G, e# Push [0 1 2 3 4] and [0 ... 15]. m*:D e# Take the Cartesian product and save in D. mr~ e# Shuffle and dump the array on the stack. e# This pushes 80 elements. We'll consider the bottommost the amulet's e# position and the topmost the player's. { e# Do: P e# Call P. _ e# Copy the player's position. l~ e# Read and evaluate one line of input. e# "6" -> 6, "9" -> 9, "B" -> 11, "E" -> 14 4b e# Convert to base 4. e# 6 -> [1 2], 9 -> [2 1], 11 -> [2 3], 14 -> [3 2] 2f- e# Subtract 2 from each coordinate. e# [1 2] -> [-1 0], [2 1] -> [0 -1], [2 3] -> [0 1], [3 2] -> [1 0] .+ e# Add the result to the copy of player's position. _aD& e# Push a copy, wrap it in an array and intersect with D. ! e# Logical NOT. This pushes 1 iff the intersection was empty. $ e# Copy the corresponding item from the stack. e# If the intersection was empty, the new position is invalid e# and 1$ copies the old position. e# If the intersection was non-empty, the new position is valid e# and 0$ copies the new position. _W$ e# Push copies of the new position and the amulet's position. =! e# Push 1 iff the positions are different. }g e# While =! pushes 1. P e# Call P. ]; e# Clear the stack. ``` ### Alternate version ``` ZYm* e# Push the Cartesian product of 3 and 2, i.e., e# [[0 0] [0 1] [0 2] [1 0] [1 1] [1 2] [2 0] [2 1] [2 2]]. l~ e# Read and evaluate one line of input. (= e# Subtract 1 and fetch the corresponding element of the array. :( e# Subtract 1 from each coordinate. ``` ### Function P ``` '.80* e# Push a string of 80 dots. W$Gb e# Copy the amulet's position and convert from base 16 to integer. '"t e# Set the corresponding character of the string to '"'. 1$Gb e# Copy the player's position and convert from base 16 to integer. '@t e# Set the corresponding character of the string to '@'. G/ e# Split into chunks of length 16. W% e# Reverse the chunks (only needed for the alternate program). N* e# Join the chunks, separating by linefeeds. oNo e# Print the resulting string and an additional linefeed. ``` [Answer] # Java, 231 bytes (196 if function) Here's the full program code at 342: ``` class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}static void p(int p,int y){for(int i=0;i<80;i++){System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":""));}}} ``` Without the print function, 231: ``` class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}} ``` If just a function is okay (I'm unclear from the spec), then I can cut this down a bit further to 196: ``` void m(){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);} ``` And with some line breaks for a bit of clarity... ``` class H{ public static void main(String[]a){ int p=0,y=79,c; y*=Math.random(); y++;p(p,y); do p( (p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0? p-1: c==68&p%16<15? p+1: c>86&p>15? p-16: c==83&p<64? p+16: p) ,y); while(p!=y); } static void p(int p,int y){ for(int i=0;i<80;i++){ System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":"")); } } } ``` Note that I'm not counting the print function `p(p,y)` itself, but I *am* counting the call to it, since I have stuff changing inside the call statement. It works with capital letters `ASDW`. Due to the way it checks for those, some other letters might also work, but the spec doesn't really say anything about what should happen if I press different keys. [Answer] # Java, 574 bytes ``` import java.util.*;public class N{static Random r=new Random();static int v,b,n,m;public static void main(String[] a){v=r.nextInt(16);b=r.nextInt(5);n=r.nextInt(16);m=r.nextInt(5);p();do{Scanner e=new Scanner(System.in);char m=e.next().charAt(0);if(m=='w')b=b>0?b-1:b;if(m=='s')b=b<5?b+1:b;if(m=='a')v=v>0?v-1:v;if(m=='d')v=v<16?v+1:v;p();}while(v!=n || b!=m);}static void p(){System.out.println();for(int y=0;y<5;y++){for(int x=0;x<16;x++){if(x==z && y==x)System.out.print('@');else if(x==n && y==m)System.out.print('"');else System.out.print('.');}System.out.println();}}} ``` Basically the same as the C# version, except obfuscated & minimized. [Answer] # Julia, 161 bytes Uses `w`, `a`, `s`, and `d` to move up, left, down, and right, respectively. Full code, including printing (330 bytes): ``` B=fill('.',5,16) a=[rand(1:5),rand(1:16)] B[a[1],a[2]]='"' c=[1,a==[1,1]?2:1] B[c[1],c[2]]='@' for i=1:5 println(join(B[i,:]))end while c!=a B[c[1],c[2]]='.' m=readline()[1] c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0 c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0 m∈"wasd"&&(B[c[1],c[2]]='@') for i=1:5 println(join(B[i,:]))end end ``` --- Scored code, excludes printing (161 bytes): ``` a=[rand(1:5),rand(1:16)] c=[1,a==[1,1]?2:1] while c!=a m=readline()[1] c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0 c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0 end ``` The difference here is that we don't save the game state as a matrix; all relevant information is contained in the arrays `c` and `a`. And, of course, nothing is printed. The user will no longer be prompted for input once the player reaches the amulet. --- Ungolfed + explanation (full code): ``` # Initialize a 5x16 matrix of dots B = fill('.', 5, 16) # Get a random location for the amulet a = [rand(1:5), rand(1:16)] # Put the amulet in B B[a[1], a[2]] = '"' # Start the player in the upper left unless the amulet is there c = [1, a == [1,1] ? 2 : 1] # Put the player in B B[c[1], c[2]] = '@' # Print the initial game state for i = 1:5 println(join(B[i,:])) end # Loop until the player gets the amulet while c != a # Put a dot in the player's previous location B[c[1], c[2]] = '.' # Read a line from STDIN, take the first character m = readline()[1] # Move the player horizontally within the bounds if m == 'a' && c[2] > 1 c[2] -= 1 elseif m == 'd' && c[2] < 16 c[2] += 1 end # Move the player vertically within the bounds if m == 'w' && c[1] > 1 c[1] -= 1 elseif m == 's' && c[1] < 5 c[1] += 1 end # Set the player's new location in B if m ∈ "wasd" B[c[1], c[2]] = '@' end # Print the game state for i = 1:5 println(join(B[i,:])) end end ``` [Answer] # Batch, 329 Bytes ``` @echo off set e=goto e set f= set/a %f%a=0 %f%b=0 %f%c=%random%*3/32768+1 %f%d=%random%*16/32768+1 :et call:p %a% %b% %c% %d% if %a%%b% EQU %c%%d% exit/b choice/C "wasd" goto %errorlevel% :1 %f%a-=1 %e% :2 %f%b-=1 %e% :3 %f%a+=1 %e% :4 %f%b+=1 :e if %a% GTR 4%f%a=4 if %a% LSS 0%f%a=0 if %b% GTR 15%f%b=15 if %b% LSS 0%f%b=0 %e%t :p setlocal enabledelayedexpansion ::creating a new line variable for multi line strings set NL=^ :: Two empty lines are required here cls set "display=" for /l %%r in (0,1,4) do ( set "line=" for /l %%c in (0,1,15) do ( set "char=." if %3 EQU %%r ( if %4 EQU %%c ( set char=" ) ) if %1 EQU %%r ( if %2 EQU %%c ( set "char=@" ) ) set "line=!line!!char!" ) set "display=!display!!line!!NL!" ) echo !display! exit /b ``` [Answer] # Perl, ~~228~~ 222 characters (not counting the newlines that are not integral to the working of the code) — 207 if not counting the `print` and `print if` statement parts which are used for printing, but don't add to the game logic; 144 if also considering the field representation generation code as part of printing, as suggested by Yakk in the comments) This code uses lowercase wasd for control; input must be confirmed with Enter. Tested with Perl 5.14.2. ``` ($a=$==rand(79))+=($a>=($==rand(80))); print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr; %r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/); while(/"/){print if eval $r{getc STDIN}} ``` Note that for this code, it is impossible to separate calculation and printing, since the operations are done directly on the printed representation using regular expressions. Explanation: ``` ($a=$==rand(79))+=($a>=($==rand(80))); ``` This line determines the position of the player and the amulet. The player position is determined by `$==rand(80)` and is actually easy to understand: On a 5×16 board, there are 80 distinct positions where the player can be. The position is stored in the `$=` variable which forces the stored value into integer; this saves a few bytes for not needing to explicitly cast the result to integer (`rand` delivers a floating point value). Since one of the positions is already occupied by the player, there are only 79 positions left for the amulet, therefore for the amulet's position, `$a=$==rand(79)` is used. Again, the assignment to `$=` forces a conversion to integer, however I further assign it to `$a` in order to reuse `$=` for the player's position. Now to avoid the amulet to occupy the same position as the player, it is advanced by one position if its position is at least as large as the player's, giving an uniform distribution on the places not occupied by the player. This is achieved by `$a = ($a >= $=)` where `$=` here holds the player's position. Now the first line is generated by inserting the two initial assignments instead of the first `$a$ and the only`$=` in this expression. ``` print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr; ``` This generates the initial field, and afterwards prints is. `("."x80)` just generates a string of 80 dots. `=~s/(.{$=})./\1@/r` then replaces the `$=`th character with `@`, and `=~s/(.{$=})./\1@/r` the `$a`th character with `"`. Due to the `r` modifier they don't try to modify in place, but return the modified string, that's why they can be applied to the previous expressions. Finally, `=~s/(.{16})/\1\n/gr` inserts a newline every 16 characters. Note that the field is stored in the special variable `$_` which can be used implicitly in later statements. ``` %r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/); ``` This creates a hash containing the replacement rules for the different moves. A more readable version of this is ``` %r = ( 'w' => 's/.(.{16})@/@\1./s', 'a' => 's/.@/@./', 's' => 's/@(.{16})./.\1@/s', 'd' => 's/@./.@/' ); ``` The keys are the characters for the moves, and the values are strings containing the corresponding replacement rule. ``` while(/"/){print if eval"\$_=~$r{getc STDIN}"} ``` This is the main loop. `while(/"/)` checks if there is still a `"` character in `$_` (that is, in the field). If we move onto the amulet, its character gets replaced with the player character so it disappears from the field. `eval $r{getc STDIN}` reads a character from standard input, looks up the corresponding replacement rule from the has `%r` and applies it to `$_`, that is, the field. This evaluates to true if a replacement was actually made (that is, the key was found in the hash *and* the move was possible; an impossible move won't match in the replacement rule). In that case `print` is executed. Since it is called without argument, it prints `$_`, that is, the modified field. [Answer] ## C#, 256 248 234 227 226 225 bytes Uses the NumPad arrows with NumLock turned on to move. Indented and commented for clarity: ``` using System; class P{ static void Main(){ int a=0,b=0,c,d,e; var r=new Random(); while(0<((c=r.Next(16))&(d=r.Next(5)))); Draw(a,b,c,d); // Excluded from the score. while(a!=c|b!=d){ e=Console.ReadKey().KeyChar-48; a+=e==4&a>0?-1:e==6&a<15?1:0; b+=e==8&b>0?-1:e==2&b<4?1:0; Draw(a,b,c,d); // Excluded from the score. } } // The following method is excluded from the score. static void Draw(int a, int b, int c, int d){ Console.Clear(); for (int y = 0; y < 5; y++) { for (int x = 0; x < 16; x++) { Console.Write( x == a && y == b ? '@' : x == c && y == d ? '"' : '.' ); } Console.WriteLine(); } } } ``` [Answer] # Html+JavaScript(ES6), score maybe 217 Too looong, but playable online in the snippets below. Line 6 (T.value ...) is for output and not counted (but for simplicity I counted the textarea open and close tags, even if it's output too) As for randomness: the amulet is always in the right half of the grid and the player always start in the left half. Click on the textArea (after enlarging it) to start and restart the game. ``` <textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea> <script> R=n=>Math.random()*n|0, s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8), m=k=>(x+=(x<15&k==39)-(x>0&k==37),y+=(y<4&k==40)-(y>0&k==38),p=y*17+x, T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='X',t[p]='@',t.join('')):t='Well done!' ) </script> ``` EcmaScript 6 Snippet (Firefox only) ``` R=n=>Math.random()*n|0 s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8) m=k=>( x+=(x<15&k==39)-(x>0&k==37), y+=(y<4&k==40)-(y>0&k==38), p=y*17+x, T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='"',t[p]='@',t.join('')):t='Well done!' ) ``` ``` <textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea> ``` EcmaScript 5 snippet (tested in Chrome) ``` function R(n) { return Math.random()*n|0 } function s() { m(y=R(5),x=R(8),a=R(5)*17+R(8)+8) } function m(k) { x+=(x<15&k==39)-(x>0&k==37) y+=(y<4&k==40)-(y>0&k==38) p=y*17+x T.value=p-a?(t=('.'.repeat(16)+'\n').repeat(5).split(''),t[a]='"',t[p]='@',t.join('')):t='Well done!' } ``` ``` <textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea> ``` [Answer] # Actionscript 3: 267 bytes A working example is [online](http://www.fastswf.com/iZ2UH4U) `var a:int,p:int,t;function g(){var r=Math.random;while(p==a){a=r()*80;p=r()*80}addEventListener("keyDown",function(e){if(a==p)return;if(e.keyCode==87&&p>15)p-=16if(e.keyCode==83&&p<64)p+=16if(e.keyCode==65&&p%16>0)p--if(e.keyCode==68&&(p+1)%16>0)p++print()});print()}` Here's a complete (whitespaces included for readability) program using the game function: ``` package { import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; public class MiniRogue extends Sprite { var a:int, p:int, t; public function MiniRogue() { g(); } function g(){ var r=Math.random; while(p==a){ a=r()*80; p=r()*80 } addEventListener("keyDown",function(e){ if(a==p) return; if(e.keyCode==87&&p>15) p-=16 if(e.keyCode==83&&p<64) p+=16 if(e.keyCode==65&&p%16>0) p-- if(e.keyCode==68&&(p+1)%16>0) p++ print() }); print() } var old:int = -1; private function print():void { if (!t) { t = new TextField() t.defaultTextFormat = new TextFormat("_typewriter", 8) t.width=500; t.height=375; addChild(t) } var board:String = ""; for (var i:int=0; i<80;i++) { if (i == p) { board += "@"; } else if (i == a) { board += '"'; } else { board += "."; } if ((i + 1) % 16 == 0) { board += "\n"; } } if (a==p) { board += "Win!"; } if (p == old) { board += "Bump!"; } old = p; t.text = board; } } } ``` [Answer] # Javascript: 307 216 You can play in the snippet below! The numbers on the left are just so the console (chrome one at least) doesn't merge the rows. To run the code: 1. hit "run code snippet" 2. hit ctrl-shift-j to open the console 3. click in the result section 4. use arrow keys and play ``` var x=y=2,m=Math,b=m.floor(m.random()*5),a=14,i,j,t,c=console,onload=d;function d(){c.clear();for(i=0;i<5;i++){t=i;for(j=0;j<16;j++){t+=(i==y&&j==x)?"@":(i==b&&j==a)?'"':".";if(a==x&&b==y)t=":)";}c.log(t);}}onkeydown=function(){switch(window.event.keyCode){case 37:if(x>0)x--;break;case 38:if(y>0)y--;break;case 39:if(x<15)x++;break;case 40:if(y<4)y++;break;}d();}; ``` Un-golfed: ``` var px=py=2,m=Math,ay=m.floor(m.random()*5),ax=14,i,j,t,c=console,onload=draw; function draw() { c.clear(); for(i=0;i<5;i++) { t=i; for(j=0;j<16;j++) { t+=(i==py&&j==px)?"@": (i==ay&&j==ax)?'"':"."; if(ax==px&&ay==py)t=":)"; } c.log(t); } } onkeydown=function() { switch (window.event.keyCode) { case 37: if(px>0)px--; break; case 38: if(py>0)py--; break; case 39: if(px<15)px++; break; case 40: if(py<4)py++; break; } draw(); }; ``` **Edit 1:** Read rules more carefully and rewrote my code accordingly * amulet y value is now randomized * player can no longer escape room * I no longer count the characters in the draw function or calls to it [Answer] # SpecBAS - ~~428~~ 402 (excluding printing, ~~466~~ 425 when counted) Uses Q/A/O/P to move up/down/left/right respectively. The line to print the dungeon at line 1 is the only line that can be ignored, but have golfed that down a bit as well. ``` 1 PRINT ("."*16+#13)*5 2 LET px=8: LET py=3 3 LET ax=INT(RND*16): LET ay=INT(RND*5): IF ax=px AND ay=py THEN GO TO 3 4 PRINT AT ay,ax;#34;AT py,px;"@": LET ox=px: LET oy=py: PAUSE 0: LET k$=INKEY$ 5 LET px=px+(k$="p")-(k$="o") 6 IF px<0 THEN LET px=0 7 IF px>15 THEN LET px=15 8 LET py=py+(k$="a")-(k$="q") 9 IF py<0 THEN LET py=0 10 IF py>4 THEN LET py=4 11 PRINT AT oy,ox;"." 12 IF SCREEN$(px,py)<>#34 THEN GO TO 4 ``` The reference to #34 is just a short-hand way of putting CHR$(34) in the code. Thanks @Thomas Kwa, I hadn't noticed player start position being random was optional. Also used separate IF statements to shave off a few characters. [Answer] ## Another C#, ~~221~~ ~~171~~ 170 Here is another way in C# with both positions random. Wanted to show this even if this part is 7 bytes longer than Hand-E-Food's solution. Hand-E-Food's answer will be shorter of course as soon as he will use Console.Read(). The downside of Consol.Read is, that pressing the needed Enter causes the field to be printed 2 more times. But I don't think there is a requirement to print just on (real) input. Navigation is done by 8426 as in Hand-E-Foods solution. ``` using System; class P { static void Main() { Func<int> n=new Random().Next; int x=n()%16,y=n()%5,a=n()%16,b,m; while(y==(b=n()%5)); while(x!=a|y!=b) { Printer.Print(a, b, x, y); // Excluded from the score. m=Console.Read()-48; y+=m==8&y>0?-1:m==2&y<4?1:0; x+=m==4&x>0?-1:m==6&x<15?1:0; } } } ``` **Edit:** (added new solution and moved PrinterClass to the end) **Edit2:** (changed a 14 to a 15 and saved the byte by starting on right-bottom) Adapting the technique of Mauris it is possible to melt it down to 171 bytes in C# (of course now without both positions random): ``` using System; class P { static void Main() { int p=79,a=new Random().Next()%p,m; while(p!=a){ Printer.Print(p,a); // Excluded from the score. m=Console.Read()-48; p+=m==4&p/5>0?-5:m==6&p/5<15?5:m==8&p%5>0?-1:m==2&p%5<4?1:0; } } } ``` The Printer Class is nearly the same, just a new overload of print... ``` class Printer { public static void Print(int ax, int ay, int px, int py) { Console.Write('\n'); for (int y = 0; y < 5; y++) { for (int x = 0; x < 16; x++) { if (x == px && y == py) Console.Write('@'); else if (x == ax && y == ay) Console.Write('"'); else Console.Write('.'); } Console.Write('\n'); } } public static void Print(int p, int a) { Print(p/5,p%5,a/5,a%5); } } ``` [Answer] ## Ruby, 185 Here is a Ruby example too. I'm very new to Ruby, maybe someone knows how to do that better :) I have counted lineFeeds as 1 since the Program will crash otherwise... Navigation is done by 8462. You need to send input each time with enter. ``` def display(ax,ay,px,py) puts for y in 0..4 for x in 0..15 if (x == px && y == py) print "@" elsif (x == ax && y == ay) print '"' else print '.' end end puts end end x=y=0 a=Random.rand(16) while y==(b=Random.rand(5)) while x!=a or y!=b display(a,b,x,y) # Excluded from the score. m=gets.chomp.to_i y-=m==8?1:0 if y>0 y+=m==2?1:0 if y<4 x-=m==4?1:0 if x>0 x+=m==6?1:0 if x<15 end ``` [Answer] # QBasic, 103 bytes Per the rules of the challenge, the `Show` subprogram is not included in the byte-count, nor is the `Show p, q, a, b` call (with the following newline). ``` b=1+TIMER MOD 9 1Show p, q, a, b INPUT m p=p-(m=2)*(p>0)+(m=4)*(p<4) q=q-(m=1)*(q>0)+(m=3)*(q<15) IF(p<>a)+(q<>b)GOTO 1 SUB Show (playerRow, playerCol, amuletRow, amuletCol) CLS FOR row = 0 TO 4 FOR col = 0 TO 15 IF row = playerRow AND col = playerCol THEN PRINT "@"; ELSEIF row = amuletRow AND col = amuletCol THEN PRINT CHR$(34); ' Double quote mark ELSE PRINT "."; END IF NEXT PRINT NEXT END SUB ``` To move, input a number and press Enter: `1` to go left, `2` to go up, `3` to go right, and `4` to go down. This code does not output the game state at the end, when the player has found the amulet. To make it do so, add another `Show p, q, a, b` after the `IF` statement. ## Explanation Let `a`, `b` represent the coordinates of the amulet and `p`, `q` the coordinates of the player. The player starts at (0, 0), and the amulet starts on row 0, with a column between 1 and 9, inclusive, based on the 1's digit of the current time. The rest is just a bunch of math with conditionals. The important thing to remember is that conditionals in QBasic return `0` for false, `-1` for true. Let's look at the player row update statement: ``` p=p-(m=2)*(p>0)+(m=4)*(p<4) ``` If `m=2`, we want to move up by subtracting 1 from `p`, as long as `p>0`. Similarly, if `m=4`, we want to move down by adding 1 to `p`, as long as `p<4`. We can obtain the desired behavior by multiplying. If both factors are `-1`, their product will be `1`, which we can subtract from or add to `p`. If either conditional is `0`, the product will be `0`, with no effect. Similarly, the condition to determine whether the player has found the amulet is: ``` IF(p<>a)+(q<>b)GOTO 1 ``` If either of the conditionals is true, their sum will be nonzero (either `-1` or `-2`) and thus truthy, and the program returns to line 1. Once `p` equals `a` and `q` equals `b`, both conditionals will be `0`, so their sum will be `0` and control flow can reach the end of the program. ]
[Question] [ This isn't very widely known, but what we call the Fibonacci sequence, AKA ``` 1, 1, 2, 3, 5, 8, 13, 21, 34... ``` is actually called the *Duonacci* sequence. This is because to get the next number, you sum the previous 2 numbers. There is also the *Tribonacci* sequence, ``` 1, 1, 1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201... ``` because the next number is the sum of the previous 3 numbers. And the *Quadronacci* sequence ``` 1, 1, 1, 1, 4, 7, 13, 25, 49, 94, 181, 349, 673... ``` And everybody's favorite, the *Pentanacci* sequence: ``` 1, 1, 1, 1, 1, 5, 9, 17, 33, 65, 129... ``` And the *Hexanacci* sequence, the *Septanacci* sequence, the *Octonacci* sequence, and so on and so forth up to the N-Bonacci sequence. The N-bonacci sequence will always start with **N** 1s in a row. # The Challenge You must write a function or program that takes two numbers *N* and *X*, and prints out the first *X* N-Bonacci numbers. N will be a whole number larger than 0, and you can safely assume no N-Bonacci numbers will exceed the default number type in your language. The output can be in any human readable format, and you can take input in any reasonable manner. (Command line arguments, function arguments, STDIN, etc.) As usual, this is Code-golf, so standard loopholes apply and the shortest answer in bytes wins! # Sample IO ``` #n, x, output 3, 8 --> 1, 1, 1, 3, 5, 9, 17, 31 7, 13 --> 1, 1, 1, 1, 1, 1, 1, 7, 13, 25, 49, 97, 193 1, 20 --> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 30, 4 --> 1, 1, 1, 1 //Since the first 30 are all 1's 5, 11 --> 1, 1, 1, 1, 1, 5, 9, 17, 33, 65, 129 ``` [Answer] ## Boolfuck, 6 bytes ``` ,,[;+] ``` > > You can safely assume no N-Bonacci numbers will exceed the default number type in your language. > > > The default number type in Boolfuck is a bit. Assuming this also extends to the input numbers N and X, and given that N>0, there are only two possible inputs - 10 (which outputs nothing) and 11 (which outputs 1). `,` reads a bit into the current memory location. N is ignored as it must be 1. If X is 0, the loop body (surrounded by `[]`) is skipped. If X is 1, it is output and then flipped to 0 so the loop does not repeat. [Answer] ## Python 2, 79 bytes ``` n,x=input() i,f=0,[] while i<x:v=[sum(f[i-n:]),1][i<n];f.append(v);print v;i+=1 ``` [Try it online](http://ideone.com/fork/fHjGyW) [Answer] ## Haskell, 56 bytes ``` g l=sum l:g(sum l:init l) n#x|i<-1<$[1..n]=take x$i++g i ``` Usage example: `3 # 8`-> `[1,1,1,3,5,9,17,31]`. How it works ``` i<-1<$[1..n] -- bind i to n copies of 1 take x -- take the first x elements of i++g i -- the list starting with i followed by (g i), which is sum l: -- the sum of it's argument followed by g(sum l:init l) -- a recursive call to itself with the the first element -- of the argument list replaced by the sum ``` [Answer] # Pyth, 13 ``` <Qu+Gs>QGEm1Q ``` [Test Suite](http://pyth.herokuapp.com/?code=%3CQu%2BGs%3EQGEm1Q&input=3%0A8&test_suite=1&test_suite_input=3%0A8%0A7%0A13%0A1%0A20%0A30%0A4%0A5%0A11&debug=0&input_size=2) Takes input newline separated, with `n` first. ### Explanation: ``` <Qu+Gs>QGEm1Q ## implicit: Q = eval(input) u Em1Q ## read a line of input, and reduce that many times starting with ## Q 1s in a list, with a lambda G,H ## where G is the old value and H is the new one +G ## append to the old value s>QG ## the sum of the last Q values of the old value <Q ## discard the last Q values of this list ``` [Answer] # Javascript ES6/ES2015, ~~107~~ ~~97~~ ~~85~~ 80 Bytes Thanks to @user81655, @Neil and @ETHproductions for save some bytes --- ``` (i,n)=>eval("for(l=Array(i).fill(1);n-->i;)l.push(eval(l.slice(-i).join`+`));l") ``` [try it online](https://jsfiddle.net/n83n11ej/12/) --- Test cases: ``` console.log(f(3, 8))// 1, 1, 1, 3, 5, 9, 17, 31 console.log(f(7, 13))// 1, 1, 1, 1, 1, 1, 1, 7, 13, 25, 49, 97, 193 console.log(f(5, 11))// 1, 1, 1, 1, 1, 5, 9, 17, 33, 65, 129 ``` [Answer] ## ES6, 66 bytes ``` (i,n)=>[...Array(n)].map((_,j,a)=>a[j]=j<i?1:j-i?s+=s-a[j+~i]:s=i) ``` Sadly `map` won't let you access the result array in the callback. [Answer] # Jelly, 12 bytes ``` ḣ³S; b1Ç⁴¡Uḣ ``` [Try it online!](http://jelly.tryitonline.net/#code=4bijwrNTOwpiMcOH4oG0wqFV4bij&input=&args=Nw+MTM) ### How it works ``` b1Ç⁴¡Uḣ Main link. Left input: n. Right input: x. b1 Convert n to base 1. ¡ Call... Ç the helper link... ⁴ x times. U Reverse the resulting array. ḣ Take its first x elements. ḣ³S; Helper link. Argument: A (list) ḣ³ Take the first n elements of A. S Compute their sum. ; Prepend the sum to A. ``` [Answer] ## Python 2, 55 bytes ``` def f(x,n):l=[1]*n;exec"print l[0];l=l[1:]+[sum(l)];"*x ``` Tracks a length-`n` window of the sequence in the list `l`, updated by appending the sum and removing the first element. Prints the first element each iteration for `x` iterations. A different approach of storing all the elements and summing the last `n` values gave the same length (55). ``` def f(x,n):l=[1]*n;exec"l+=sum(l[-n:]),;"*x;print l[:x] ``` [Answer] # [Haskell](https://www.haskell.org/), 47 bytes ``` q(h:t)=h:q(t++[h+sum t]) n?x=take x$q$1<$[1..n] ``` [Try it online!](https://tio.run/##BcFBCoMwEAXQfU/xF1koCeI0LRVpmBP0BCGLLISIJpg6BW@fvpfiuS373lrt0iy9S3PtRGuf9PnLkNDfCl9O4rbgUlXRW3kahhJajmuBQ47HB8d3LQIFb3kyeDFZA@L7aGBHfhg8mSi0Pw "Haskell – Try It Online") `<$` might have been introduced into Prelude after this challenge was posted. --- **[Haskell](https://www.haskell.org/), 53 bytes** ``` n%i|i>n=sum$map(n%)[i-n..i-1]|0<1=1 n?x=map(n%)[1..x] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P081sybTLs@2uDRXJTexQCNPVTM6UzdPTy9T1zC2xsDG0NaQK8@@whYmZ6inVxH7PzcxM0/BVgEo6KtQUJSZV6KgohBtbG@ho2Bub2iso2Bob2Sgo2BsYG@io2Bqb2gY@x8A "Haskell – Try It Online") Defines the binary function `?`, used like `3?8 == [1,1,1,3,5,9,17,31]`. The auxiliary function `%` recursively finds the `i`th element of the `n`-bonacci sequence by summing the previous `n` values. Then, the function `?` tabulates the first `x` values of `%`. [Answer] # [Husk](https://github.com/barbuz/Husk), 9 bytes ``` ↑§¡ȯΣ↑_B1 ``` [Try it online!](https://tio.run/##yygtzv7//1HbxEPLDy08sf7cYiAz3snw////5v8NjQE "Husk – Try It Online") Starts from the `B`ase-`1` representation of *N* (simply a list of *N* ones) and `¡`teratively sums (`Σ`) the last (`↑_`) *N* elements and appends the result to the list. Finally, takes (`↑`) the first *X* numbers in this list and returns them. [Answer] # C#, 109 bytes ``` (n,x)=>{int i,j,k;var y=new int[x];for(i=-1;++i<x;y[i]=i<n?1:k){k=0;for(j=i-n;j>-1&j<i;)k+=y[j++];}return y;} ``` [Try it online!](https://tio.run/##fU/RSsMwFH3vV1z6MFp6O5ZlddY080HwQRQEH3wYfahdHGm3VJN2rox9e02HA4duHMK9yT3n5J7chHmlRdcYqZbw0pparJnz@zZ8lOqTOfkqMwaedbXU2XrnAHw0byuZg6mz2pZNJRfwlEnl@f0Q4L5ReSJVjT9nns5gAbzzFG59PtvZJ5BYYMk2mYaWK/EFPW2bsvdKe5KHhAWBTLasncuUy0TdkpvS35V8dCAUXIaKFbOQDIpEMr8MeDsvgiBley3qRito2b5jjnNXKVOtxPBVy1rYLMI77GdqbTMOHyq7sosuwsKjCNe@D5yDS7AHxQhjJFOkxIXB4JxuikDoifCIKRKK4wgnMca2j@klG4IwHv1rcxaX7OgIYXJqd4ke2RDkz@/H/BSvIiTj2HV85uwtum8 "C# (.NET Core) – Try It Online") --- ``` (n, x) => { int i, j, total; var result = new int[x]; for (i = -1; ++i < x; ) { //calculate each term one at a time total = 0; //value of the current term for (j = i - n; j > -1 & j < i;) //sum the last n terms { total += result[j++]; } result[i] = i < n ? 1 : total; //first n terms are always 1 so ignore the total if i < n } return result; } ``` [Answer] # [Haskell](https://www.haskell.org), 46 bytes ``` g _ 0=[] g(h:t)n=h:g(t++[sum$h:t])(n-1) ``` ``` g.g[1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNw3SFeIVDGyjY7nSNTKsSjTzbDOs0jVKtLWji0tzVYAisZoaebqGmlxptul66dGGsVB9YbmJmXkKtgop-VwKCrmJBb4KBUWZeSVAjkK0QpqCsYIFiKkDZJorGBrD2IYKRgYwtrGBggmMbapgaAhiQ02HuQ4A) This is based on [xnor's answer](https://codegolf.stackexchange.com/a/70522/) but it employs 1 clever trick. The \$n\$-bonacci sequence always start with \$n\$ `1`s. A more general version of this might start with just any \$n\$ values. And this more general version is what we implement with `g`. `g` takes a list of \$n\$ integers and a value \$m\$ and gives us a list of the first \$m\$ terms of this generalized \$n\$-bonacci sequence. The trick is then that `g[1]` is a cheap way to generate \$n\$ `1`s. Since the sequence starting with `[1]` is just an endless stream of `1`s. So we use `g` in two ways, and even though `g` might be slightly longer because it implements something a little more general, it saves bytes because it serves two purposes. [Answer] # Java, 82 + 58 = 140 bytes Function to find the *ith* **n**-bonacci number (**82 bytes**): ``` int f(int i,int n){if(i<=n)return 1;int s=0,q=0;while(q++<n)s+=f(i-q,n);return s;} ``` Function to print first *k* **n**-bonacci number (**58 bytes**): ``` (k,n)->{for(int i=0;i<k;i++){System.out.println(f(i,n));}} ``` [Answer] # C++11, 360 bytes Hi I just like this question. I know c++ is a very hard language to win this competition. But I'll thrown a dime any way. ``` #include<vector> #include<numeric> #include<iostream> using namespace std;typedef vector<int>v;void p(v& i) {for(auto&v:i)cout<<v<<" ";cout<<endl;}v b(int s,int n){v r(n<s?n:s,1);r.reserve(n);for(auto i=r.begin();r.size()<n;i++){r.push_back(accumulate(i,i+s,0));}return r;}int main(int c, char** a){if(c<3)return 1;v s=b(atoi(a[1]),atoi(a[2]));p(s);return 0;} ``` I'll leave this as the readable explanation of the code above. ``` #include <vector> #include <numeric> #include <iostream> using namespace std; typedef vector<int> vi; void p(const vi& in) { for (auto& v : in ) cout << v << " "; cout << endl; } vi bonacci(int se, int n) { vi s(n < se? n : se, 1); s.reserve(n); for (auto it = s.begin(); s.size() < n; it++){ s.push_back(accumulate(it, it + se, 0)); } return s; } int main (int c, char** v) { if (c < 3) return 1; vi s = bonacci(atoi(v[1]), atoi(v[2])); p(s); return 0; } ``` [Answer] [Uiua](https://www.uiua.org/) (version 0.0.7), 34 bytes ``` →(;;)⍥(⊂∶/+↙∶→,⇌.)∶→(-,,)[⍥.-1∶1]. ``` [Answer] # APL, 21 ``` {⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1} ``` This is a function that takes *n* as its left argument and *x* as its right argument. Explanation: ``` {⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1} ⍺/1 ⍝ begin state: X ones + ⍝ identity function (to separate it from the ⍵) ⍺{ }⍣⍵ ⍝ apply this function N times to it with X as left argument ⍵, ⍝ result of the previous iteration, followed by... +/ ⍝ the sum of ⍺↑ ⍝ the first X of ⌽ ⍝ the reverse of ⍵ ⍝ the previous iteration ⍵↑ ⍝ take the first X numbers of the result ``` Test cases: ``` ↑⍕¨ {⍵↑⍺{⍵,+/⍺↑⌽⍵}⍣⍵+⍺/1} /¨ (3 8)(7 13)(1 20)(30 4)(5 11) 1 1 1 3 5 9 17 31 1 1 1 1 1 1 1 7 13 25 49 97 193 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 9 17 33 65 129 ``` [Answer] # Python 3, 59 Saved 20 bytes thanks to FryAmTheEggman. Not a great solution, but it'll work for now. ``` def r(n,x):f=[1]*n;exec('f+=[sum(f[-n:])];'*x);return f[:x] ``` Also, here are test cases: ``` assert r(3, 8) == [1, 1, 1, 3, 5, 9, 17, 31] assert r(7, 13) == [1, 1, 1, 1, 1, 1, 1, 7, 13, 25, 49, 97, 193] assert r(30, 4) == [1, 1, 1, 1] ``` [Answer] # C, 132 bytes The recursive approach is shorter by a couple of bytes. ``` k,n;f(i,s,j){for(j=s=0;j<i&j++<n;)s+=f(i-j);return i<n?1:s;}main(_,v)int**v;{for(n=atoi(v[1]);k++<atoi(v[2]);)printf("%d ",f(k-1));} ``` ## Ungolfed ``` k,n; /* loop index, n */ f(i,s,j) /* recursive function */ { for(j=s=0;j<i && j++<n;) /* sum previous n n-bonacci values */ s+=f(i-j); return i<n?1:s; /* return either sum or n, depending on what index we're at */ } main(_,v) int **v; { for(n=atoi(v[1]);k++<atoi(v[2]);) /* print out n-bonacci numbers */ printf("%d ", f(k-1)); } ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~144~~ ~~124~~ 122 bytes -20 bytes thanks to [Nitroden](https://codegolf.stackexchange.com/users/69059/nitrodon) This is my first Brain-Flak answer, and I'm sure it can be improved. Any help is appreciated. ``` (([{}]<>)<{({}(()))}{}>)<>{({}[()]<<>({<({}<({}<>)<>>())>[()]}{})({}<><({({}<>)<>}<>)>)<>>)}{}<>{({}<{}>())}{}{({}<>)<>}<> ``` [Try it online!](https://tio.run/##TYwxCoAwDEV3T/IzOIiDS8hFSoc6CKI4uIacPSYVwaGFn/d46932a9zOdrgDRa2yECvUACIytZiSu4Aqs0A5Rn9JJCxJFCb1Y6AP5t@l7LwVjiB692@5L8M0Pw "Brain-Flak – Try It Online") [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), 46 bytes The generating function of the sequence is: $$\frac{(n-1)x^n}{x^{n+1}-2x+1}-\frac{1}{x-1}$$ ``` (n,m)->Vec(n--/(x-(2-1/x)/x^n)-1/(x-1)+O(x^m)) ``` [Try it online!](https://tio.run/##FckxCsMwDIXhq4hMEpVwHLc0S3OFbl2CAyY0JeAYETq4p3ft7fvf03Du8tGywaNg4oNker1XTCIGs@Ag1mQyeUlUVRdLlyfm5SAqQTX@MIBMoOeevpVdiw7WECNuDIGIYZ4dw@gr7gzWNViGoW9wPcO14VYv6z2VPw "Pari/GP – Try It Online") [Answer] # [R](https://www.r-project.org/), 60 bytes ``` function(n,m){for(i in 1:m)T[i]=`if`(i>n,sum(T[i-1:n]),1);T} ``` [Try it online!](https://tio.run/##Lcw9CoAwDEDh3VM4JhDBWEVR9BRuIohCIUNT8GcSz15Fun284e1BV699sJdup3gFJYe39TtIKppy63CcZO4XsQvIoHRcDr6ScaszEmM3Pv8CDDWY/KqJTSRTkUeanMrIipgxvA "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) , 8 bytes ``` 1ẋ?‡W∑*Ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyI1IiwiIiwiMeG6iz/igKFX4oiRKuG4niIsIiIsIjIiXQ==) ``` 1ẋ # [1] * input ‡W∑ # Function summing its inputs ? * # Set the arity to the input Ḟ # Generate an infinite list from the function and the vector of 1s. ``` [Answer] # Julia, 78 bytes ``` f(n,x)=(z=ones(Int,n);while endof(z)<x push!(z,sum(z[end-n+1:end]))end;z[1:x]) ``` This is a function that accepts two integers and returns an integer array. The approach is simple: Generate an array of ones of length `n`, then grow the array by adding the sum of the previous `n` elements until the array has length `x`. Ungolfed: ``` function f(n, x) z = ones(Int, n) while endof(z) < x push!(z, sum(z[end-n+1:end])) end return z[1:x] end ``` [Answer] ## Perl 6, ~~52~72~~ 47~67 bytes ``` sub a($n,$x){EVAL("1,"x$n~"+*"x$n~"...*")[^$x]} ``` Requires the module `MONKEY-SEE-NO-EVAL`, because of the following error: > > ===SORRY!=== Error while compiling -e > > EVAL is a very dangerous function!!! (use MONKEY-SEE-NO-EVAL to override, > > but only if you're VERY sure your data contains no injection attacks) > > at -e:1 > > > ``` $ perl6 -MMONKEY-SEE-NO-EVAL -e'a(3,8).say;sub a($n,$x){EVAL("1,"x$n~"+*"x$n~"...*")[^$x]}' (1 1 1 3 5 9 17 31) ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 22 ~~26~~ bytes ``` 1tiXIX"i:XK"tPI:)sh]K) ``` This uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1) of the language/compiler. [**Try it online!**](http://matl.tryitonline.net/#code=MXRpWElYImk6WEsidFBJOilzaF1LKQ&input=NwoxMwo) A few extra bytes :-( due to a bug in the `G` function (paste input; now corrected for next release) ### Explanation ``` 1tiXIX" % input N. Copy to clipboard I. Build row array of N ones i:XK % input X. Build row array [1,2,...X]. Copy to clipboard I " % for loop: repeat X times. Consumes array [1,2,...X] t % duplicate (initially array of N ones) PI:) % flip array and take first N elements sh % compute sum and append to array ] % end K) % take the first X elements of array. Implicitly display ``` [Answer] # [Perl 6](http://perl6.org), 38 bytes ``` ->\N,\X{({@_[*-N..*].sum||1}...*)[^X]} # 38 bytes ``` ``` -> \N, \X { ( { @_[ *-N .. * # previous N values ].sum # added together || # if that produces 0 or an error 1 # return 1 } ... * # produce an infinite list of such values )[^X] # return the first X values produced } ``` ### Usage: ``` # give it a lexical name my &n-bonacci = >\N,\X{…} for ( (3,8), (7,13), (1,20), (30,4), (5,11), ) { say n-bonacci |@_ } ``` ``` (1 1 1 3 5 9 17 31) (1 1 1 1 1 1 1 7 13 25 49 97 193) (1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1) (1 1 1 1) (1 1 1 1 1 5 9 17 33 65 129) ``` [Answer] # J, 31 bytes ``` ]{.(],[:+/[{.])^:(-@[`]`(1#~[)) ``` Ungolfed: ``` ] {. (] , [: +/ [ {. ])^:(-@[`]`(1 #~ [)) ``` ## explanation Fun times with [the power verb in its gerund form](http://code.jsoftware.com/wiki/Vocabulary/hatco#Gerund_n): ``` (-@[`]`(1 #~ [)) NB. gerund pre-processing ``` Breakdown in detail: * `] {. ...` Take the first `<right arg>` elements from all this stuff to the right that does the work... * `<left> ^: <right>` apply the verb `<left>` repeatedly `<right>` times... where `<right>` is specified by the middle gerund in `(-@[`]`(1 #~ [)`, ie, `]`, ie, the right arg passed into the function itself. So what is `<left>`? ... * `(] , [: +/ [ {. ])` The left argument to this entire phrase is first transformed by the first gerund, ie, `-@[`. That means the left argument to this phrase is the *negative* of the left argument to the overall function. This is needed so that the phrase `[ {. ]` takes the *last* elements from the return list we're building up. Those are then summed: `+/`. And finally appended to that same return list: `] ,`. * So how is the return list initialized? That's what the third pre-processing gerund accomplishes: `(1 #~ [)` -- repeat 1 "left arg" number of times. [Try it online!](https://tio.run/##jY/BasMwEETv@oqhPdimsq214iYWpIR8QC89GoeEYJGU0EKcW0h@3R1bOaSlhYoVvJFmlt333neYOxjw9s05ixtdu6e8PmdNsnJxuqjXzTqWx2udJH2iHjJEfu4iaFwcfKfU6zKD1cAMSNMXiL4V30qNijylkNFHgtjvvvvivzBXMDhhshp0Zccof1GYv6P/qjCsYfcfwwrCyfO3/ce2xWnXwu@P3YlubI4tNocDJOrGBuWwhfw2yt3CXOOZUopKqXa7@4SFxyzglCg2sJALc7MYikngcvBI/wU "J – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 41 bytes ``` ->a,b{r=[1]*a;b.times{z,*r=r<<r.sum;p z}} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6m6yDbaMFYr0TpJryQzN7W4ukpHq8i2yMamSK@4NNe6QKGqtvZ/WrSxjkUsV0FpSbGCuq6urjpXWrS5jqExmpChjpEBmpCxgY4JmpCpjqFh7H8A "Ruby – Try It Online") [Answer] # [R](https://www.r-project.org/), 68 bytes ``` function(n,x){a=1+!1:n;for(i in n+1:x){a[i]=sum(a[(i-n:1)])};a[1:x]} ``` [Try it online!](https://tio.run/##FcnBCoMwDADQ@76iuyUYwdgNR9UvKT2UQSCHRdAJg@G3V3t6h7cWcVNbZLf3VxcDox/@88zNnYONsqygTs1Zw6FG1DRv@wdyBG0tMCY8xhyvTEcR8PTCm8BA7KtMfVf1HT2qT2LGcgI "R – Try It Online") [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~26~~ 24 bytes ``` {(y-x){y,+/x#y}[-x]/x#1} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlqjUrdCs7pSR1u/QrmyNlq3IhbIMKz9nxZtbm1oFPsfAA "K (ngn/k) – Try It Online") ]
[Question] [ If you've ever played [Spacewar!](https://en.wikipedia.org/wiki/Spacewar_(video_game)), you know it was a fun game. If you haven't, know this: it was (and is) one of the very first and most important computer games. And it's still fun! The clone I grew up on is [this one](http://www.peterhirschberg.com/csw/index.htm), which is, apparently and unfortunately, Windows only. So I recreated it! **The KotH is hosted here: [PPCG - Spacewar! King of the Hill](http://play.starmaninnovations.com/spacewar/).** I encourage you to play as a human against at least one other bot to get a feel for how the game works. ## The Game * One frame is 30 milliseconds (thus, about 33 frames per second). * The field is 800 pixels wide and 600 pixels tall. * The field is toroidal, meaning that spaceships and missiles that move outside of the field reappear on the opposite side. * There are two spaceships, red and blue. + Red is positioned at x=50 and random y between 50, (field height - 50) pixels. + Blue is positioned at x=(field width - 50) and random y between 50, (field height - 50) pixels. + Both face x = (field width)/2. * The available controls are: + Turn left - 5 degrees per frame counterclockwise. + Turn right - 5 degrees per frame clockwise. + Fire missile - travels at an extra 10 pixels per frame in addition to the velocity of the ship, in the direction the ship was pointing. + Fire engine - accelerates the spaceship at 0.30 pixels per frame in the direction the spaceship is pointing. + Hyperspace jump - teleports to some random coordinates in the field, with a 25% chance of exploding. These random coordinates may be on top of the sun. * The maximum speed for ships is 15 pixels per frame under engine power and 40 pixels per frame when gravity-boosted. + When traveling faster than 15 pixels per frame, engine thrust may only change direction or slow down. * Regarding missiles: + Missiles travel in a straight line. + Missiles may be fired at a maximum rate of 1 per 0.1 seconds. + Missiles have a lifetime of 2.25 seconds. + Ships have a maximum of 20 missiles each. + Missiles are point particles internally. * There is a sun in the very center that is extremely hazardous to your ship. The *slightest* contact is fatal. This sun also destroys missiles. * The sun has gravity. The resultant acceleration is 5000/(distance^2) pixels/frame^2, where distance is in pixels. Spaceships and missiles are affected. * Both ships have three strike zones: the nose, the left wing, and the right wing. + A hit on the nose is instant death. + A hit on either wing reduces the spaceship's turn rate and engine acceleration by half. + If both wings are destroyed, the spaceship cannot be maneuvered and can only fire missiles. * Ships may collide with each other. + A nose-nose impact is fatal for both ships. + A nose-wing impact destroys the wing. + A wing-wing impact destroys both wings. * Dead ships are solid and frozen until they explode 1 second later. * After at least one ship has died, the field is reset 3 seconds later. Until then, the sun and any remaining missiles are still hazardous. The original game also has deadly and indestructible asteroids, but I won't include those. ## The Rules * Your bot must be written in JavaScript. * Your bot should limit its decision to about 10 milliseconds. If I notice consistent lag *because of your bot*, I'll disqualify it and let you know so you can fix it. * Bots will have access to the following: + Field width and field height + Sun position and radius + The position, rotation, velocity, shape, missile stock, and in-hyperspace status of both ships + The position and velocity of all missiles * When prompted, your bot should return a list of strings. + These strings should be one of the following: `turn left`, `turn right`, `fire engine`, `fire missile`, `hyperspace`. Any other string will be ignored. + If there are any duplicates, only the first will be noted. + `hyperspace` takes precedence over all others. + `turn left` and `turn right` at the same time will have no effect. + `fire engine` will have no effect if the ship only has the nose or is dead. + `fire missile` will have no effect if a missile was fired too recently. * In a change from the usual, **your bot is allowed to exploit the behavior of other bots.** I want to encourage a metagame. + Bots **may not** emulate other bots. (I.e., no mind-reading.) + Bots **may not** set any variables used by the game and physics code. (I.e., no cheating.) ## Bot Implementation Details I will be storing your bot in its own JavaScript file that is automatically included, with the filename `bot_<name>.js`. So don't put any spaces or characters that would interfere with this or with naming a function in JavaScript. That's because you should define the following functions: `<name>_setup(team)` and `<name>_getActions(gameInfo, botVars)`. Further down the page, there exist textareas for the **userbot**, which you can edit to test your code. ### `<name>_setup(team)` This function is for you to define any variables that you want to persist. `team` will be either `"red"` or `"blue"`. This function must return an object. Define variables like so: ``` var vars = {}; vars['example'] = "example"; return vars; ``` This `vars` object will be passed in to the other function: ### `<name>_getActions(gameInfo, botVars)` `botVars` is the object returned by `<name>_setup(team)`. `gameInfo` is an object containing the following variables: ``` redScore blueScore timeLeft fieldWidth fieldHeight sun_x sun_y sun_r //sun's radius gravityStrength //acceleration in pixels/frame^2 at 1 pixel away from the sun's center engineThrust //acceleration in pixels/frame^2 speedLimit //maximum speed under engine power maxSpeed //maximum speed from gravity boosts red_x red_y red_rot //rotation in degrees red_xv //x velocity red_yv //y velocity red_shape //one of "full ship", "left wing", "right wing", "nose only" red_missileStock //the number of missiles red has left red_inHyperspace //true if red is in hyperspace red_exploded //until red explodes, it is still solid and hazardous red_alive // likewise for blue // numMissiles missiles //this is a list of objects, each with the following variables x y xv yv ``` Your bot has full access to these. I'm *pretty sure* that you can write to them and not affect the original variables, but don't do it anyway. **A note on rotations:** ships *point* in the +y direction, downwards, so anything that you want to align with the ship needs to be offset by 90 degrees. Also, positive rotation is clockwise. This function must return a list of strings, representing your bot's actions. For example, `["turn right","thrust"]`. More details on this are in the **Rules** section. ## Additional Details You may also make use of the following: ### `LineIntersection(L1, L2)` L1 and L2 are two-element arrays of two-element arrays. That is, `L1 := [[x1,y1],[x2,y2]]` and `L2 := [[u1,v1],[u2,v2]]`. This function computes the intersection of two lines and returns this: `[[x,y], [a,b]]`. `[x,y]` are the coordinates of the intersection point and `[a,b]` is a pair of ratios that express how far along each line the intersection point is. As in, `a = 0.25` would mean that the intersection point is a quarter of the way from `[x1,y1]` to `[x2,y2]`, and likewise for `b`. **If there is no intersection, an empty array is returned.** ### `window["shipShapes"]` ``` var shipShapes = { 'full ship': [[-8,16],[0,-8],[8,16]], 'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]], 'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]], 'nose only': [[-4,4],[0,-8],[4,4],[0,8]] }; ``` These are the coordinates of the ships' polygons. To make getting the current coordinates easier, you may also use... ### `getShipCoords(<color>)` `getShipCoords("red")` will return the current coordinates of the vertices of Red's ship, and likewise for `getShipCoords("blue")` and Blue. These coordinates are in a list like so: `[[x1,y1],[x2,y2],[x3,y3],...]`. Polygons are implicitly closed, so there is a line between the first and last coordinate pairs. **You may not access or alter any other variables or functions in use by the game/website.** And definitely don't name your functions the same. I don't foresee that this will be a problem, but if your bot breaks the game code, that's one possibility. There is no logging or catching of exceptions. ## Winning * Every pairing of bots shall be played at least 10 times, both ways. (So, at least 20 games total.) * Aim to have the highest win/loss ratios *overall*. If your bot does super well against one other bot, but loses against the other three, that's not as good as winning against two and losing against two (as a general rule of thumb). * For every bot, the ratios (wins+1)/(losses+1) will be calculated, then the mean and standard deviation of these ratios will be calculated. A higher mean will have priority, and in case means are within 1 unit of each other, the lower variance will have priority. * Scoring will begin either in a week from today or after three days of no new submissions. This is so I don't have to repeat any pairing of bots. **Above all, have fun!** --- ## Leaderboard (2016-01-08 05:15): ``` # Name Mean StdDev 1. Helios 13.625 6.852 2. EdgeCase 8.335 8.155 3. OpponentDodger 8.415 8.186 4. OrbitBot 5.110 6.294 5. SunAvoider 5.276 6.772 6. DangitBobby 3.320 4.423 7. SprayAndPray 3.118 4.642 8. Engineer 3.903 6.315 9. RighthandedSpasms 1.805 2.477 10. AttackAndComeBack 2.521 2.921 11. PanicAttack 2.622 3.102 12. FullSpeedAhead 2.058 3.295 13. UhhIDKWhatToCallThisBot 2.555 3.406 14. MissilesPlusScore 0.159 0.228 15. Hyper 0.236 0.332 16. RandUmmm 0.988 1.329 17. Kamikaze 0.781 1.793 ``` **Note:** This is subject to change as I run more games. Plus, the ordering of ranks 9-13 bothers me, so I may tweak the scoring method to better match one's intuition of how they should be ranked. (Means and standard deviations were rounded to three decimal digits. Also, `Hyper` should be `HYPER` but that messes up the highlighting. :P) [Answer] # Helios This bot is the center of the universe, or at least he thinks he is. The first thing he makes is to correct a grave error and place himself in the center of the coordinate system. Then he rotates anything around himself. He doesn't like the other (fake) sun, therefore he tries to stay away from it. He also doesn't like other bots, therefore he shoots at them, if he is in a good shooting position. ``` function Helios_setup(team) { var botVars = {}; botVars.myPrefix = team + "_"; botVars.enemyPrefix = team == "red" ? "blue_" : "red_"; return botVars; } function Helios_getActions(gameInfo, botVars) { var actions = []; var halfPi = Math.PI / 2; var engageAngle = Math.PI / 8; var field = {}; field.width = gameInfo.fieldWidth; field.height = gameInfo.fieldHeight; field.halfWidth = field.width / 2; field.halfHeight = field.height / 2; field.posOffsetX = field.width * 3 / 2 - gameInfo[botVars.myPrefix + "x"]; field.posOffsetY = field.height * 3 / 2 - gameInfo[botVars.myPrefix + "y"]; field.posAngle = (450 - gameInfo[botVars.myPrefix + "rot"]) % 360 * Math.PI / 180; field.posSin = Math.sin(-field.posAngle); field.posCos = Math.cos(-field.posAngle); field.movOffsetXV = -gameInfo[botVars.myPrefix + "xv"]; field.movOffsetYV = gameInfo[botVars.myPrefix + "yv"]; field.movAngle = Math.atan2(-field.movOffsetYV, -field.movOffsetXV); field.movSin = Math.sin(-field.movAngle); field.movCos = Math.cos(-field.movAngle); function zeroIfUndefined(v) { return v === undefined ? 0 : v; } function sqr(x) { return x * x } function getEntity(source, prefix) { var tmpX = (field.posOffsetX + zeroIfUndefined(source[prefix + "x"])) % field.width - field.halfWidth; var tmpY = field.halfHeight - (field.posOffsetY + zeroIfUndefined(source[prefix + "y"])) % field.height; var tmpXV = zeroIfUndefined(source[prefix + "xv"]); var tmpYV = -zeroIfUndefined(source[prefix + "yv"]); var e = {}; e.posX = tmpX * field.posCos - tmpY * field.posSin; e.posY = tmpX * field.posSin + tmpY * field.posCos; e.posR = Math.sqrt(sqr(e.posX) + sqr(e.posY)); e.posPhi = Math.atan2(e.posY, e.posX); e.posXV = tmpXV * field.posCos - tmpYV * field.posSin; e.posYV = tmpXV * field.posSin + tmpYV * field.posCos; e.posV = Math.sqrt(sqr(e.posXV) + sqr(e.posYV)); e.movX = tmpX * field.movCos - tmpY * field.movSin; e.movY = tmpX * field.movSin + tmpY * field.movCos; e.movR = Math.sqrt(sqr(e.movX) + sqr(e.movY)); e.movPhi = Math.atan2(e.movY, e.movX); e.movXV = (tmpXV + field.movOffsetXV) * field.movCos - (tmpYV + field.movOffsetYV) * field.movSin; e.movYV = (tmpXV + field.movOffsetXV) * field.movSin + (tmpYV + field.movOffsetYV) * field.movCos; return e; } function getShip(prefix) { var ship = getEntity(gameInfo, prefix); ship.missileStock = gameInfo[prefix + "missileStock"]; ship.inHyperspace = gameInfo[prefix + "inHyperspace"]; ship.exploded = gameInfo[prefix + "exploded"]; ship.alive = gameInfo[prefix + "alive"]; return ship; } var myShip = getShip(botVars.myPrefix); myShip.movAngle = (field.posAngle - field.movAngle + 3 * Math.PI) % (2 * Math.PI) - Math.PI; var enemyShip = getShip(botVars.enemyPrefix); var sun = getEntity(gameInfo, "sun_"); enemyShip.intersectionLine = [[enemyShip.movX - enemyShip.movXV * 30, enemyShip.movY - enemyShip.movYV * 30], [enemyShip.movX + enemyShip.movXV * 30, enemyShip.movY + enemyShip.movYV * 30]]; var intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle) * 10 * 30, Math.sin(myShip.movAngle) * 10 * 30]], enemyShip.intersectionLine); if (intersection.length == 2) { myShip.intersection = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]); } intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle - 0.001) * 10 * 30, Math.sin(myShip.movAngle - 0.001) * 10 * 30]], enemyShip.intersectionLine); if (intersection.length == 2) { myShip.intersectionLeft = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]); } intersection = LineIntersection([[0, 0], [Math.cos(myShip.movAngle + 0.001) * 10 * 30, Math.sin(myShip.movAngle + 0.001) * 10 * 30]], enemyShip.intersectionLine); if (intersection.length == 2) { myShip.intersectionRight = Math.abs(intersection[1][0] / 2 + 0.5 - intersection[1][1]); } function danger() { var tmp1 = sqr(sun.movXV) + sqr(sun.movYV); var tmp2 = tmp1 == 0 ? 0 : Math.max(0, Math.min(1, ((-sun.movX) * sun.movXV + (-sun.movY) * sun.movYV) / tmp1)); var dis = Math.sqrt(sqr(sun.movX + tmp2 * sun.movXV) + sqr(sun.movY + tmp2 * sun.movYV)); if (dis < 30) { return true; } var shipLine1 = [[-16, 8], [-16, -8]]; var shipLine2 = [[-16, 8], [8, 0]]; var shipLine3 = [[-16, -8], [8, 0]]; if (gameInfo.missiles !== undefined) { for (var i = 0; i < gameInfo.missiles.length; i++) { var missile = getEntity(gameInfo.missiles[i], ""); var missileLine = [[missile.movX + missile.movXV * 0.5, missile.movY + missile.movYV * 0.5], [missile.movX + missile.movXV * 3, missile.movY + missile.movYV * 3]]; if (LineIntersection(shipLine1, missileLine).length == 2 || LineIntersection(shipLine2, missileLine).length == 2 || LineIntersection(shipLine3, missileLine).length == 2) { return true; } } } return false; } function fire() { return enemyShip.alive && !enemyShip.inHyperspace && myShip.intersection !== undefined && myShip.intersection < 0.1 + myShip.missileStock / 200; } function evadeSun() { if ((sun.movPhi >= 0 && myShip.movAngle < 0) || (sun.movPhi <= 0 && myShip.movAngle > 0)) { actions.push("fire engine"); } if (sun.movPhi > 0) { if (Math.abs(myShip.movAngle) < halfPi) { actions.push("turn right"); } else { actions.push("turn left"); } } else { if (Math.abs(myShip.movAngle) < halfPi) { actions.push("turn left"); } else { actions.push("turn right"); } } } function aim() { if (myShip.intersection !== undefined && myShip.intersectionLeft !== undefined && myShip.intersectionLeft < myShip.intersection) { actions.push("turn left"); } else if (myShip.intersection !== undefined && myShip.intersectionRight !== undefined && myShip.intersectionRight < myShip.intersection) { actions.push("turn right"); } else { if (enemyShip.posPhi > 0) { actions.push("turn left"); } else { actions.push("turn right"); } } if (myShip.posV < 2 || (enemyShip.alive && (enemyShip.movXV >= 0 || myShip.missileStock == 0))) { actions.push("fire engine"); } } function brake() { if (myShip.movAngle > 0) { actions.push("turn left"); } else { actions.push("turn right"); } if (Math.abs(myShip.movAngle) > Math.PI * 3 / 4) { actions.push("fire engine"); } } function engage() { if (enemyShip.missileStock > 0) { if ((enemyShip.posPhi > 0 && enemyShip.posPhi < engageAngle) || enemyShip.posPhi < -engageAngle) { actions.push("turn right"); } else { actions.push("turn left"); } } else { if (enemyShip.posPhi > 0) { actions.push("turn left"); } else { actions.push("turn right"); } } actions.push("fire engine"); } if (myShip.alive && !myShip.inHyperspace) { if (danger()) { actions.push("hyperspace"); } if (fire()) { actions.push("fire missile"); } if (enemyShip.exploded || enemyShip.inHyperspace || sun.movR < 150 || (sun.movR < 300 && Math.abs(sun.movPhi) < Math.PI)) { evadeSun(); } else if (enemyShip.posR < 300 || myShip.intersection !== undefined) { aim(); } else if (myShip.posV > 10) { brake(); } else { engage(); } } return actions; } ``` [Answer] ## SunAvoider This one just tries to stay away from the sun. It does so pretty well...until it gets one or both wings destroyed, then it's usually only a matter of time before it falls in. ``` function SunAvoider_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function SunAvoider_getActions(gameInfo, botVars) { var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { var shipx = gameInfo[botVars["color"]+"_x"]; var shipy = gameInfo[botVars["color"]+"_y"]; var sunx = gameInfo["sun_x"]; var suny = gameInfo["sun_y"]; var dx = shipx - sunx; var dy = shipy - suny; var dis = Math.sqrt(dx*dx+dy*dy); var fireEngineChance = (dis-100)/(gameInfo["fieldHeight"]/2); if (Math.random() > fireEngineChance){ actions.push("fire engine") } var ang1 = gameInfo[botVars["color"]+"_rot"]+90; var ang2 = Math.degrees( Math.atan2(dy, dx) ); var angDiff = ang2 - ang1; if (angDiff < -180) { //http://stackoverflow.com/a/7869457/1473772 angDiff += 360; } else if (angDiff > 180) { angDiff -= 360; } if (angDiff >= 0) { actions.push("turn left"); } else if (angDiff < 0) { actions.push("turn right"); } } return actions; } ``` [Answer] # EdgeCase Flies at full speed away from the sun towards the edge of the map! When it finds itself pointed towards the sun it will start shooting while turning itself away to get back to the edge. It also enters hyperspace when it's about to hit the sun. ``` function EdgeCase_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function EdgeCase_getActions(gameInfo, botVars) { var actions = []; // Get our ship's position var rotation, x, y, opponentAlive; if(botVars.color == "red") { rotation = gameInfo.red_rot; x = gameInfo.red_x; y = gameInfo.red_y; opponentAlive = gameInfo.blue_alive; } else if(botVars.color == "blue") { rotation = gameInfo.blue_rot; x = gameInfo.blue_x; y = gameInfo.blue_y; opponentAlive = gameInfo.red_alive; } // Calculate our rotation compared to the sun in degrees var sunX = gameInfo.sun_x, sunY = gameInfo.sun_y, angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI, rotationToSun = (rotation - angle + 360) % 360; // Check if we need to hyperspace to avoid the sun var rX = x - sunX, rY = y - sunY, distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r; if(distanceFromSun < 30) actions.push("hyperspace"); else { // Turn away from the sun if(rotationToSun > 90 && rotationToSun < 270) { actions.push("turn right"); } else actions.push("turn left"); // Fire engines if we're pointing away from the sun if(rotationToSun > 180) { actions.push("fire engine"); } // If we shoot while our opponent's dead we can only kill ourself else if(opponentAlive) actions.push("fire missile"); } return actions; } ``` [Answer] # OrbitBot Currently has no targeting ~~or collision avoidance~~. It tries to orbit the sun. **Edit: Now goes into hyperspace when impact is imminent.** ``` function OrbitBot_setup(team) { var botVars = {}; botVars.color = team; return botVars; } function OrbitBot_getActions(gameInfo, botVars) { var actions = []; function getVar(name) { return gameInfo[botVars.color + "_" + name]; } function getEnemyVar(name) { var eColor; if (botVars.color == 'blue') { eColor = 'red'; } else { eColor = 'blue'; } return gameInfo[eColor + "_" + name]; } function distance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } function toroidDistance(x1, y1, x2, y2) { dx = Math.abs(x1 - x2); while (dx > gameInfo.fieldWidth) { dx -= gameInfo.fieldWidth; } dx = Math.min(dx, gameInfo.fieldWidth - dx); dy = Math.abs(y1 - y2); while (dx > gameInfo.fieldHeight) { dx -= gameInfo.fieldHeight; } dy = Math.min(dy, gameInfo.fieldHeight - dy); return Math.sqrt(dx*dx+dy*dy); } function angleDistance(theta1, theta2) { var d = theta1 - theta2; while (d < 0 || d > Math.PI) { if (d < 0) { d += Math.PI * 2; } if (d > Math.PI * 2) { d -= Math.PI * 2; } else if (d > Math.PI) { d = Math.PI * 2 - d; } } return d; } function toRad(degrees) { return degrees / 180 * Math.PI; } function cap(x, y, limit) { var r = x*x+y*y; if (r < limit * limit) { r = Math.sqrt(r); x = x * r / limit; y = y * r / limit; } return [x,y]; } var shape = getVar('shape'); if (shape != 'nose only') { var broken = shape != 'full ship'; var sunX = gameInfo.sun_x, sunY = gameInfo.sun_y, sunG = gameInfo.gravityStrength; function desirability(x, y, vx, vy) { //Borrowed from a useless bot. var lowest = distance(x, y, sunX, sunY) - 5; var missiles = gameInfo.missiles; for (var i = 0; i < missiles.length; i++) { var mx = missiles[i].x + missiles[i].xv / 2; var my = missiles[i].y + missiles[i].yv / 2; lowest = Math.min(lowest, toroidDistance(x, y, mx, my) - distance(0, 0, missiles[i].xv, missiles[i].yv)); } return lowest - 16; } var x = getVar("x"), y = getVar("y"), vx = getVar("xv"), vy = getVar("yv"); function desirabilityByAcceleration(ax, ay) {//Borrowed from a useless bot. var x1 = x, y1 = y, vx1 = vx, vy1 = vy; var speed = distance(0,0,vx1,vy1); var limit = Math.max(gameInfo.speedLimit, speed); vx1 += ax; vy1 += ay; var temp = cap(vx1, vy1, limit); vx1 = temp[0]; vy1 = temp[1]; var dx = x1 - sunX; var dy = y1 - sunY; var dis = Math.sqrt(dx*dx+dy*dy); if (dis > 5){ var force = sunG / (dis * dis); } else { var force = sunG /5; } vx1 -= force*dx/dis; vy1 -= force*dy/dis; var temp = cap(vx1, vy1, 40); vx1 = temp[0]; vy1 = temp[1]; x1 += vx1; y1 += vy1; return desirability(x1, y1, vx1, vy1); } var r = distance(sunX, sunY, x, y); var theta = Math.atan((y - sunY) / (x - sunX)); var sunA = sunG/r/r, sunAx = -Math.cos(theta) * sunA, sunAy = -Math.sin(theta) * sunA; var dv = Math.sqrt(sunG / r); var dvx = -dv * Math.sin(theta); var dvy = dv * Math.cos(theta); if (distance(-dvx, -dvy, vx, vy) < distance(dvx, dvy, vx, vy)) { dvx = -dvx; dvy = -dvy; } var dax = dvx - vx; var day = dvy - vy; var dAngle = Math.atan(day / dax); if (dax < 0) { dAngle += Math.PI; } var cAngle = toRad(getVar('rot') - 90); var dLeft = angleDistance(cAngle - toRad(broken ? 2.5 : 5), dAngle); var dRight = angleDistance(cAngle + toRad(broken ? 2.5 : 5), dAngle); var dNeither = angleDistance(cAngle, dAngle); if (dLeft < dRight && dLeft < dNeither) { actions.push('turn left'); } else if (dRight < dLeft && dRight < dNeither) { actions.push('turn right'); } var cax = Math.cos(cAngle) * (broken ? .15 : .3); var cay = Math.sin(cAngle) * (broken ? .15 : .3); var ax = 0; var ay = 0; if (distance(cax, cay, dax, day) < distance(0, 0, dax, day)) { actions.push('fire engine'); ax = cax; ay = cay; } if (desirabilityByAcceleration(ax, ay) <= 16) { actions.push('hyperspace'); } } return actions; } ``` [Answer] ## RighthandedSpasms The name is pretty descriptive. Chooses `turn right` with 0.5 probability, `fire engine` with 0.5 probability, and `fire missile` with 0.8 probability. Surprisingly difficult, mainly because it's really unpredictable. ``` function RighthandedSpasms_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function RighthandedSpasms_getActions(gameInfo, botVars) { var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { if (Math.random() > 0.5) { actions.push("turn right") } if (Math.random() > 0.5) { actions.push("fire engine") } if (Math.random() > 0.8) { actions.push("fire missile") } } return actions; } ``` [Answer] # RandUmmm This challenge needed a random bot. Bonus points for golfiness? ``` function RandUmmm_setup(t){ function P(n,t,r,o,e,f,g){for(o=[e=1<<(f=n.length)];e;)for(t=e.toString(2),r=g=t.length,o[--e]=[];r;)~-t[--r]||o[e].push(n[r+f-g]);return o}var q=P(["fire missile","turn right","fire engine","turn left"]);q.pop(); return {color:t,m:function(){return q[Math.random()*q.length|0]}}; } function RandUmmm_getActions(g,b){ return b.m(); } ``` [Answer] # Engineer Likes to use hyperspace when in danger. To see it's true power, open up your browser's console and type `overideHyperspace = 0;`. If you forget the semicolon, you'll get ASI for Christmas. ``` function Engineer_setup(t){ return{c:t,C:"red0blue".split(0)[+(t=="red")]}; } function Engineer_getActions(gameInfo,botVars){ var actions = []; function d(x1,y1,x2,y2){return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))} function hS(g){return d(g.sun_x,g.sun_y,g[botVars.c+"_x"],g[botVars.c+"_y"])<50} function enemyDist(g){return d(g[botVars.c+"_x"],g[botVars.c+"_y"],g[botVars.C+"_x"],g[botVars.C+"_y"]);} function hSm(g){ // get closest missile var r = (g.missiles||[{x:10000,y:10000}]).reduce(function(p,c){return Math.min(d(c.x,c.y,g[botVars.c+"_x"],g[botVars.c+"_y"]),p)},Infinity); return r<18; } function dF(g){ var a = Math.degrees(Math.atan2(g[botVars.C+"_y"]-g[botVars.c+"_y"],g[botVars.C+"_x"]-g[botVars.c+"_x"])); var tP = (g[botVars.c+"_rot"]+360-a)%360; return [a,tP]; } function lOr(g){ var tP = dF(g)[1]; return 90<tP&&tP<270?"turn left":"turn right"; } function thrust(g){ return Math.abs(dF(g)-g[botVars.c+"_rot"]); } // are we too close to the sun or a missile? if(hS(gameInfo)||hSm(gameInfo))actions.push("hyperspace"); // should we fire? if(enemyDist(gameInfo)<200)actions.push("fire missile"); // direction function actions.push(lOr(gameInfo,botVars)); if(Math.random()<.7)actions.push("fire engine"); return actions; } ``` [Answer] # SprayAndPray ``` function SprayAndPray_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function SprayAndPray_getActions(gameInfo, botVars) { var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { actions.push("turn left"); if (Math.random() > 0.5) { actions.push("fire engine")}; actions.push("fire missile"); } return actions; } ``` Fires wildly in every direction. It's not very effective! [Answer] # Kamikaze Not very competitive but I thought it would be fun! Just flies straight towards it's opponent while shooting. ``` function Kamikaze_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function Kamikaze_getActions(gameInfo, botVars) { var actions = []; // Get our ship's position var us, them, red = { rotation: gameInfo.red_rot, x: gameInfo.red_x, y: gameInfo.red_y, alive: gameInfo.blue_alive }, blue = { rotation: gameInfo.blue_rot, x: gameInfo.blue_x, y: gameInfo.blue_y, alive: gameInfo.blue_alive }; if(botVars.color == "red") { us = red; them = blue; } else if(botVars.color == "blue") { us = blue; them = red; } // Turn towards our opponent's position var angle = Math.degrees(Math.atan2(them.y - us.y, them.x- us.x)), rotationToOpponent = (us.rotation - angle + 360) % 360; if(rotationToOpponent > 90 && rotationToOpponent < 270) { actions.push("turn left"); } else actions.push("turn right"); actions.push("fire missile", "fire engine"); return actions; } ``` [Answer] # UhhIDKWhatToCallThisBot Just random stuff. ``` function UhhIDKWhatToCallThisBot_setup(team) { var botVars = {}; botVars['t'] = 0; botVars["color"] = team; return botVars; } function UhhIDKWhatToCallThisBot_getActions(gameInfo, botVars) { var actions = []; //when i need it: "turn left", //Use missiles sparingly! var WCID = [ "fire engine", "turn right", "fire engine", "fire missile", "turn right", "fire engine"] if (gameInfo[botVars["color"]+"_alive"]) { botVars['t']++; actions.push(WCID[botVars[t]%(WCID.length)]); } return actions; } ``` [Answer] # OpponentDodger GET AWAY FROM ME OPPONENT!!! ``` function OpponentDodger_setup(t){b={};b["c"]=t;b['o']=(t=="red")?"blue":"red";return b;}function OpponentDodger_getActions(g,b){a=[];o=b["c"];j={r:g[o+"_rot"],x:g[o+"_x"],y:g[o+"_y"]};o=b["o"];p={r:g[o+"_rot"],x:g[o+"_x"],y:g[o+"_y"]};l=Math.degrees(Math.atan2(p.y-j.y,p.x-j.x)),x=(j.r-l+360)%360;if(x > 90 && x < 270)a.push("turn right");else a.push("turn left");a.push("fire engine");return a;} ``` Thanks to user81655 for some code! [Answer] # Spy ## The story The prototype to this bot was a bot that had two modes: crazy mode and normal mode. When it was in crazy mode, it stayed there for a constant number of ticks. There was a contant probability of entering crazy mode. It also hyperspaced when it was close to the sun. In crazy mode, it aimed to the other bot and fired constantly. In normal mode, it flew away from the other bot, not firing. I tweaked that prototype so that it would be in crazy mode if and only if the enemy was close enough. Then I had a crazy idea: what if it only stayed in crazy mode? After some experimentation (I added making the bot fire randomly when it was in normal mode) I found me new bot beat every bot but Helios. [This](https://gist.github.com/CrazyPython/16be557152f13c4fc6d4a99fd541d613) is my code at the end of this process, but before cleaning up. I wrote my entire bot in the KotH textarea or the JS beautifier. (I did briefly use the Atom editor when cleaning up - but for like two lines of code) ## The bot This bot contains a lot of code borrowed from other bots. It flips the code from Kamikaze to run away from the other bot instead of running to the other bot and it takes code from EdgeCase for hyperspacing when it's close to the sun. It's arch nemesis is Helios. It being the odd one out and long chats with a martini. It runs away from the other bot with a 70% chance of firing a missile and hyperspaces when it's close to the sun. As simple as that. Yep. Edit: I tested my bot with the new code and it fails for every other bot. I'm working on fixing it. I just confirmed this is only for my new bot. ## The code ``` function Spy_setup(team) { // Typical setup. Nothing to see here. ;) var botVars = {}; botVars["color"] = team; return botVars; } function Spy_getActions(gameInfo, botVars) { var actions = []; var us, them, red = { rotation: gameInfo.red_rot, x: gameInfo.red_x, y: gameInfo.red_y, alive: gameInfo.blue_alive }, blue = { rotation: gameInfo.blue_rot, x: gameInfo.blue_x, y: gameInfo.blue_y, alive: gameInfo.blue_alive }; if (botVars.color == "red") { us = red; them = blue; } else if (botVars.color == "blue") { us = blue; them = red; } function distance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } // Get our ship's position var rotation, x, y, opponentAlive; if (botVars.color == "red") { rotation = gameInfo.red_rot; x = gameInfo.red_x; y = gameInfo.red_y; opponentAlive = gameInfo.blue_alive; } else if (botVars.color == "blue") { rotation = gameInfo.blue_rot; x = gameInfo.blue_x; y = gameInfo.blue_y; opponentAlive = gameInfo.red_alive; } // Calculate our rotation compared to the sun in degrees var sunX = gameInfo.sun_x, sunY = gameInfo.sun_y, angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI, rotationToSun = (rotation - angle + 360) % 360; // Check if we need to hyperspace to avoid the sun var rX = x - sunX, rY = y - sunY, distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r; if (distanceFromSun < 30) { actions.push("hyperspace"); console.log("Command Module is Hyperspacing.") } if (gameInfo[botVars["color"] + "_alive"]) { var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)), rotationToOpponent = (us.rotation - angle + 360) % 360; if (rotationToOpponent > 90 && rotationToOpponent < 270) { actions.push("turn right"); } else { actions.push("turn left"); }; actions.push("fire engine"); if (Math.random() > 0.3) { actions.push("fire missile") } } return actions; } ``` ## The misc Note: I might've broke something when cleaning up the code because I didn't test the bot after cleaning up the code. It's also much much much better than all my other bots - it actually beat every other bot except for Helios **(edit)** , SetCourseFor30Degrees, and OrbitBot! It ties with SunAvoider. Side note: I'm horrible at javascript, don't know why. [Answer] # AttackAndComeBack Instead of swirling, it comes in at the top and exits at the bottom (returning at the top), firing very quickly. Generally avoids the sun. ``` function AttackAndComeBack_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function AttackAndComeBack_getActions(gameInfo, botVars) { var actions = []; actions.push("fire missile"); if (Math.random()>0.4){actions.push("turn right");} else {actions.push("turn left");} actions.push("fire engine"); return actions; } ``` [Answer] ## FullSpeedAhead Always fires both the engines and the missiles without turning ever. Sometimes lasts surprisingly long before hitting the sun. ``` function FullSpeedAhead_setup(team){ return {color: team}; } function FullSpeedAhead_getActions(gameInfo, botVars){ var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { actions.push("fire engine"); actions.push("fire missile"); } return actions; } ``` [Answer] # PanicAttack Has a 50% chance of firing, and an 80% chance of turning left; but if it doesn't turn left, it'll turn right. After it runs out of missiles, time will eventually make it stop due to the sun. **EDIT:** Added some logic to not fire when the enemy is alive because it could get killed by its own missiles. ``` function PanicAttack_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function PanicAttack_getActions(gameInfo, botVars) { var actions = []; actions.push("fire engine"); if(botVars.color == "red") { var opponentAlive = gameInfo.blue_alive; } else if(botVars.color == "blue") { var opponentAlive = gameInfo.red_alive; } if ((Math.random()>0.5)&&opponentAlive) { actions.push("fire missile"); } if (Math.random()>0.2) { actions.push("turn left"); } else { actions.push("turn right"); } return actions; } ``` [Answer] # DangitBobby Bobby Hill doesn't care what others think about him- he's quite content to swing lazily around the field and patiently wait for his opponent to run out of steam before striking like a "husky" cobra. ``` function DangitBobby_setup(team) { var botVars = {}; botVars["color"] = team; if (team == 'red'){ botVars['them'] = "blue"; } else{ botVars['them'] = 'red'; } return botVars; } function DangitBobby_getActions(gameInfo, botVars) { var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { actions.push('turn right'); actions.push('fire engine'); if (gameInfo[botVars['them']+'_missileStock'] == 0){ actions.push('fire missile'); } } } ``` "THAT'S MY PURSE! I DON'T KNOW YOU!" [Answer] # Sniper I've been playing with prediction for a bit to create a sniper bot that snipes his enemies. My javascript is too large to fit in an answer so here is a link, [bot\_Sniper](https://drive.google.com/file/d/0ByilzkL7-U2RUUg1RVRkcmxNSzg/view?usp=sharing). [Answer] ## SmartArrow Like Arrow, but smart ``` function SmartArrow_setup(team) { var botVars = {}; botVars['mpref'] = team + '_'; botVars['epref'] = team == 'red' ? 'blue_' : 'red_'; botVars['ecolor'] = team == 'red' ? 'blue' : 'red'; return botVars; } function SmartArrow_getActions(gameInfo, botVars) { var actions = []; var x = gameInfo[botVars['mpref'] + 'x'], y = gameInfo[botVars['mpref'] + 'y'], rot = gameInfo[botVars['mpref'] + 'rot']; // SmartArrow position and rotation var ex = gameInfo[botVars['epref'] + 'x'], ey = gameInfo[botVars['epref'] + 'y']; // Enemy position var sunx = gameInfo.sun_x, suny = gameInfo.sun_y; // Sun position var Dsunx = Math.abs(x - sunx), Dsuny = Math.abs(y - suny); // Sun position delta var dex = Math.abs(x - ex), dey = Math.abs(y - ey); // Enemy position delta var sangle = Math.degrees(Math.atan2(suny - y, sunx - x)), snrot = (rot - sangle + 360) % 360; if (Dsunx < 40 && Dsuny < 40) // If SmartArrow is too close from sun, hyperspace ! return ['hyperspace']; var missiles = gameInfo.missiles; for (var i = 0; i < missiles.length; i++) { // Avoid all these silly missiles var dx = Math.abs(x - missiles[i].x), dy = Math.abs(y - missiles[i].y); if (dx < 10 && dy < 10) return ['hyperspace']; } if (gameInfo[botVars['epref'] + 'alive']) { // If his enemy is alive, SmartArrow try to kill him (logic) var angle = Math.degrees(Math.atan2(ey - y, ex - x)), nrot = (rot - angle + 360) % 360; if (nrot > 90 && nrot < 270) actions.push('turn left'); else actions.push('turn right'); if (nrot > 80 && nrot < 100 && Math.random() > 0.5) actions.push('fire missile'); // If SmartArrow is in a good spot, shot this silly oponnent if (Math.random() > 0.5) actions.push('fire engine'); } else { // Simply (try to) act like SunAvoider if his enemy is dead if (snrot > 90 && snrot < 270) actions.push('turn right'); else actions.push('turn left'); if (Dsunx < 300 && Dsuny < 300) actions.push('fire engine'); if (dex < 40 && dey < 40) actions.push('hyperspace'); // Dying on the corpse of his opponent is dumb. } return actions; } ``` [Answer] # Kamikaze- **Also not designed to be competitive.** Just for fun. It hyperspaces when close to the sun and chases the player without firing bullets. It's fun to watch this bot chase an unarmed version of Spy, but you can't have more than one userbot, unfortunately. El'endia: ever considered adding more than one userbot ;) ``` function KamikazePlus_setup(team) { // Typical setup. Nothing to see here. ;) var botVars = {}; botVars["color"] = team; return botVars; } function KamikazePlus_getActions(gameInfo, botVars) { var actions = []; var us, them, red = { rotation: gameInfo.red_rot, x: gameInfo.red_x, y: gameInfo.red_y, alive: gameInfo.blue_alive }, blue = { rotation: gameInfo.blue_rot, x: gameInfo.blue_x, y: gameInfo.blue_y, alive: gameInfo.blue_alive }; if (botVars.color == "red") { us = red; them = blue; } else if (botVars.color == "blue") { us = blue; them = red; } function distance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } // Get our ship's position var rotation, x, y, opponentAlive; if (botVars.color == "red") { rotation = gameInfo.red_rot; x = gameInfo.red_x; y = gameInfo.red_y; opponentAlive = gameInfo.blue_alive; } else if (botVars.color == "blue") { rotation = gameInfo.blue_rot; x = gameInfo.blue_x; y = gameInfo.blue_y; opponentAlive = gameInfo.red_alive; } // Calculate our rotation compared to the sun in degrees var sunX = gameInfo.sun_x, sunY = gameInfo.sun_y, angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI, rotationToSun = (rotation - angle + 360) % 360; // Check if we need to hyperspace to avoid the sun var rX = x - sunX, rY = y - sunY, distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r; if (distanceFromSun < 30) { actions.push("hyperspace"); console.log("Command Module is Hyperspacing.") } if (gameInfo[botVars["color"] + "_alive"]) { var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)), rotationToOpponent = (us.rotation - angle + 360) % 360; if (rotationToOpponent > 90 && rotationToOpponent < 270) { actions.push("turn left"); } else { actions.push("turn right"); }; actions.push("fire engine"); } return actions; } ``` Just took Kamikaze+'s code and got rid of the missile firing part. [Answer] # MissilesPlusScore Some strange idea I came up with that takes that the absolute value of difference of the scores and uses a list of moves in a random based of the game way. It works well against bots with a strategy but fails against storms of missiles. Also my first [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'"). ``` function MissilesPlusScore__setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function MissilesPlusScore_getActions(gameInfo, botVars) { var actions = []; var moves=["fire missile","hyperspace","turn right","turn left","fire engine","fire missile","turn right","hyperspace","turn left","fire missile","hyperspace","turn right","turn left","hyperspace","fire engine","fire missile","turn right","turn left","hyperspace","fire missile","turn right","turn left","fire engine","hyperspace","fire missile","turn right","turn left","hyperspace"]; if(gameInfo[botVars["color"]+"_alive"]){ var num=gameInfo["redScore"]-gameInfo["blueScore"]; if(num<0){num=num*-1;} if(num===0){actions.push(moves[Math.round(Math.random()*4)]);} else{ actions.push(moves[num+gameInfo["numMissiles"]]); } } return actions; } ``` # HYPER HYPERSPACE IS COOL!!!!!!!!!!!!!!!! ``` function HYPER_setup(team){var botVars={};botVars["color"]=team;return botVars}function HYPER_getActions(gameInfo,botVars){var actions=[];if(gameInfo[botVars["color"]+"_alive"]){actions.push(["fire engine","fire missile","hyperspace"][Math.round(Math.random()*2)])};return actions} ``` # CoordinateInfluence Based off the Coordinates, surprisingly effective: ``` function CoordinateInfluence_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function CoordinateInfluence_getActions(gameInfo, botVars) { var actions = []; if (gameInfo[botVars["color"]+"_alive"]) { if(gameInfo["blue_x"]>gameInfo["red_x"]){ if(gameInfo["blue_y"]<gameInfo["red_y"]){actions.push("turn right");} else{actions.push("fire engine");} } else if(gameInfo["blue_y"]<gameInfo["red_y"]){ if(gameInfo["blue_x"]>gameInfo["red_x"]){actions.push("turn left");} else{actions.push("fire missile");} } else{actions.push("hyperspace");} } return actions; } ``` [Answer] # SetCourseFor30Degrees No idea why the captain is so insistent on setting the ship on a course of 30 degrees, but hey, as a lowly ensign, who are you to question? At least you have been given permission to avoid the sun! And you are allowed to fire the missiles... just not allowed to aim them... ``` function SetCourseFor30Degrees_setup(team) { var botVars = {}; botVars["color"] = team; return botVars; } function SetCourseFor30Degrees_getActions(gameInfo, botVars) { var actions = []; var ang1 = gameInfo[botVars["color"]+"_rot"]+0; var fireChance=0.95; // sun avoidance var x = gameInfo[botVars["color"]+"_x"]; var y = gameInfo[botVars["color"]+"_y"]; var sunX = gameInfo["sun_x"]+0; var sunY = gameInfo["sun_y"]+0; var dx = sunX- x; var dy = sunY - y; var shortRangeAvoidanceDistance = (dx * dx + dy * dy ) ; x = gameInfo[botVars["color"]+"_x"]+gameInfo[botVars["color"]+"_xv"]*10; y = gameInfo[botVars["color"]+"_y"]+gameInfo[botVars["color"]+"_yv"]*10; dx = sunX- x; dy = sunY - y; var longRangeAvoidanceDistance = (dx * dx + dy * dy ) ; var vel = Math.sqrt(gameInfo[botVars["color"]+"_xv"]*gameInfo[botVars["color"]+"_xv"]+ gameInfo[botVars["color"]+"_yv"]*gameInfo[botVars["color"]+"_yv"]); var close=vel*1.5; if (shortRangeAvoidanceDistance <= close* close) { actions.push("hyperspace"); } else { if (longRangeAvoidanceDistance <= 200*200) { x = x+Math.cos((ang1-5)*Math.PI/180)*vel ; y = y+Math.sin((ang1-5)*Math.PI/180)*vel ; dx = sunX- x; dy = sunY - y; if (( dx * dx + dy * dy ) > longRangeAvoidanceDistance ) { actions.push("turn right") } else { actions.push("turn left") } } else { var course = botVars["color"]=="red"?30:-30; if (ang1>course ) {actions.push("turn left")} if (ang1<course ) {actions.push("turn right")} } if (Math.random() > fireChance){ actions.push("fire missile") } actions.push("fire engine") } return actions; } ``` [Answer] ## Arrow Simply chase his enemy, hyperspace when he is in danger and idle when his enemy is dead. ``` function Arrow_setup(team) { var botVars = {}; botVars['mpref'] = team + '_'; botVars['epref'] = team == 'red' ? 'blue_' : 'red_'; return botVars; } function Arrow_getActions(gameInfo, botVars) { var actions = []; var x = gameInfo[botVars['mpref'] + 'x'], y = gameInfo[botVars['mpref'] + 'y'], rot = gameInfo[botVars['mpref'] + 'rot']; // My position and rotation var ex = gameInfo[botVars['epref'] + 'x'], ey = gameInfo[botVars['epref'] + 'y']; // Enemy position var Dsunx = Math.abs(x - gameInfo.sun_x); var Dsuny = Math.abs(y - gameInfo.sun_y); if (Dsunx < 30 && Dsuny < 30) // If Arrow is too close from sun, hyperspace ! return ['hyperspace']; var missiles = gameInfo.missiles; for (var i = 0; i < missiles.length; i++) { var dx = Math.abs(x - missiles[i].x); var dy = Math.abs(y - missiles[i].y); if (dx < 10 && dy < 10) return ['hyperspace']; } if (gameInfo[botVars['epref'] + 'alive']) { var angle = Math.degrees(Math.atan2(ey - y, ex - x)), nrot = (rot - angle + 360) % 360; if (nrot > 90 && nrot < 270) actions.push('turn left'); else actions.push('turn right'); if (Math.random() > 0.5) actions.push('fire missile'); } if (Math.random() > 0.5) actions.push('fire engine'); return actions; } ``` [Answer] # Kamikaze+ **Not designed to be competitive.** Just for fun. Technically, it does the opposite of Spy: chase the player, hyperspace when close to the sun, fire missile 70% of the time. I sorta just want to see KamikazePlus chasing Spy and Spy running away like a madman. ``` function KamikazePlus_setup(team) { // Typical setup. Nothing to see here. ;) var botVars = {}; botVars["color"] = team; return botVars; } function KamikazePlus_getActions(gameInfo, botVars) { var actions = []; var us, them, red = { rotation: gameInfo.red_rot, x: gameInfo.red_x, y: gameInfo.red_y, alive: gameInfo.blue_alive }, blue = { rotation: gameInfo.blue_rot, x: gameInfo.blue_x, y: gameInfo.blue_y, alive: gameInfo.blue_alive }; if (botVars.color == "red") { us = red; them = blue; } else if (botVars.color == "blue") { us = blue; them = red; } function distance(x1, y1, x2, y2) { return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } // Get our ship's position var rotation, x, y, opponentAlive; if (botVars.color == "red") { rotation = gameInfo.red_rot; x = gameInfo.red_x; y = gameInfo.red_y; opponentAlive = gameInfo.blue_alive; } else if (botVars.color == "blue") { rotation = gameInfo.blue_rot; x = gameInfo.blue_x; y = gameInfo.blue_y; opponentAlive = gameInfo.red_alive; } // Calculate our rotation compared to the sun in degrees var sunX = gameInfo.sun_x, sunY = gameInfo.sun_y, angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI, rotationToSun = (rotation - angle + 360) % 360; // Check if we need to hyperspace to avoid the sun var rX = x - sunX, rY = y - sunY, distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r; if (distanceFromSun < 30) { actions.push("hyperspace"); console.log("Command Module is Hyperspacing.") } if (gameInfo[botVars["color"] + "_alive"]) { var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)), rotationToOpponent = (us.rotation - angle + 360) % 360; if (rotationToOpponent > 90 && rotationToOpponent < 270) { actions.push("turn left"); } else { actions.push("turn right"); }; actions.push("fire engine"); if (Math.random() > 0.3) { actions.push("fire missile") } } return actions; } ``` Basically just took Spy's code and flipped "left" and "right". ]
[Question] [ It is simple. I cannot stand when people use spaces when naming files. It sometimes wrecks console commands and makes the output of ls ugly. The challenge is to write a program (only ascii characters) which 1. renames all files (including directories) in the current directory to versions with spaces removed or replaced by '\_' 2. on collision, you need to append a unique identifier (up to you) 3. descends recursively into all subdirectories You can assume UNIX-style path names. Who would need this program on a Windows machine anyways? This is code golf, the shortest program wins (#ascii characters). Since I hate spaces so much, each space has to be counted twice. Please provide your language, score, program and a short description of how to run it. The program must compile and execute with reasonable effort on my linux machine. EDIT: As Etan requested a file structure for testing, here is the script I currently use to create a suitable file tree: ``` #!/bin/bash rm -r TestDir touchfiles() { touch my_file touch my__file touch "my file" touch "my file" touch " my_file " } mkdir TestDir cd TestDir touchfiles for dir in "Test Sub" Test_Sub "Te stSub" Te_stSub do mkdir "$dir" cd "$dir" touchfiles cd .. done ``` [Answer] ## Bash 116 bytes, 16 spaces ``` find . -depth -exec bash -c 'B=${0##*/} M="${0%/*}/${B// /_}" while [ -e "$M" ] do M=$M. done mv "$0" "$M"' {} \; ``` I didn't suppress errors to gain a couple more bytes. This will not have any collisions. If non-posix GNU `find` can be expected, this can be shortened further: ## Bash 110 bytes, 15 spaces ``` find -d -exec bash -c 'B=${0##*/} M="${0%/*}/${B// /_}" while [ -e "$M" ] do M=$M. done mv "$0" "$M"' {} \; ``` Removing spaces instead of replacing them uses two less bytes: ## Bash 108 bytes, 15 spaces ``` find -d -exec bash -c 'B=${0##*/} M="${0%/*}/${B// }" while [ -e "$M" ] do M=$M. done mv "$0" "$M"' {} \; ``` Note: if tabs can be used instead of spaces, only 1 space is needed (the one in the match rule for substitution at line 2). Thanks to Dennis for finding bug on double quote (and providing solution) [Answer] ## Zsh + GNU coreutils — 48 bytes (1 space) ``` for x (**/*(Dod))mv -T --b=t $x $x:h/${${x:t}// } ``` It's weird that you hate (ASCII) spaces but are fine with tabs and newlines, but I guess it takes all kinds. [zmv](http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#index-zmv) solves [a lot of file renaming problems](https://unix.stackexchange.com/search?q=zmv) concisely (and only slightly obscurely). However, it insists on the targets being unique; while you can easily add unique suffixes, adding a suffix only if it would be needed pretty much requires re-doing all the work. So instead I loop manually and rely on [GNU mv](http://www.gnu.org/software/coreutils/manual/coreutils.html#mv-invocation) to append a unique identifier in case of collision (`--backup` option, plus `--no-target-directory` in case a target is an existing directory, as otherwise `mv` would move the source inside that directory). `(od)` is a [glob qualifier](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Qualifiers) to sort the output with directories appearing after their content (like find's `-depth`). `D` includes dot files in the glob. `:h` and `:t` are [history modifiers](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Modifiers) similar to `dirname` and `basename`. `mv` complains that it's called to rename files to themselves, because the glob includes file names without spaces. C'est la vie. Ungolfed version: ``` for x in **/*\ *(Dod); do mv --no-target-directory --backup=numbered $x ${x:h}/${${x:t}// /} done ``` [Answer] # Python 180 bytes ``` from os import* t,c,h='.',chdir,path def g(p): c(p) for x in listdir(t): if h.isdir(x):g(x) n=x.replace(' ','') while h.exists(n):n+=t if' 'in x:rename(x,n) c(t*2) g(t) ``` only 2 spaces if you use tab for indentation :-) [Answer] If the order of collided file suffixes does not need to give precedent to the pre-existing file then the following works for me: ## bash/find/mv 84 bytes, 16 spaces ``` find -depth -execdir bash -c '[ "${0//[^ ]}" ] && mv -{T,--b=t} "$0" "${0// }"' {} \; ``` ## bash/find/mv 82 bytes, 14 spaces ``` find -depth -execdir bash -c '[ "${0//[^ ]}" ]&&mv -{T,-b=t} "$0" "${0// }"' {} \; ``` Cuddled `&&` to save two space bytes. ## bash/find/mv 60 bytes, 11 spaces ``` find -d -execdir bash -c 'mv -{T,-b=t} "$0" "${0// }"' {} \; ``` Drops error protection so it gets errors from mv on files which have no spaces to start with. Edit: Dropped the quotes from `{}` as reminded by Dennis. Also allowed `find` to scream about portability and deprecation in the shortest version where `mv` is already screaming about moving a file on top of itself. Edit 2: Added `-T` to `mv` command to avoid nesting directories instead of renaming as pointed out by pqnet. Used brace expansion at cost of one character over just using one space. [Answer] ## NodeJS – 209 bytes, 3 Whitespaces ``` s=require('fs');function a(d){s.readdirSync(d).forEach(function(f){f=d+'/'+f;i=0;r=f;if(/ /.test(f)){r=f.replace(' ','');while(s.existsSync(r))r+=i++;s.renameSync(f,r)}s.statSync(r).isDirectory()&&a(r)})}a('.'); ``` [Answer] ## POSIX `sh` + GNU `find` + GNU `mv` 67 ASCII bytes + one *(literal)* space ``` find -d -exec sh -cf 'IFS=\ ;IFS=_ set $0;mv --b=t "$0" "$*"' {} \; ``` I don't know if it fits, but with this any *sequence* of spaces is elided to a single `_` - I like it anyway. Actually any *sequence* but leading/trailing spaces that is - those are automatically truncated *(which is also, I think, a beneficial behavior)*. Thanks to Gilles for pointing this out. This just uses the internal field separator to separate fields. It's fairly... *chatty*... ...oh man. I knew the tab thing was cheap, but I thought it was at least clever. Now I'm just late to the party... [Answer] # Bash - 86 bytes ``` find . -d|while IFS="" read f;do t=${f##*/};mv --b=t -T "$f" "${f%/*}"/${t// /};done ``` [Answer] ## Bash + Perl `rename` 64 (`rename` is the Perl script on Debian and derivatives, not the util-linux command.) ``` find . -depth -name "* *" -execdir rename 'y/ /_/' * \; ``` [Answer] # PHP, ~~147~~ 145 bytes, ~~2~~ 1 space~~s~~ -> 146 ``` function s(){foreach(glob("*")as$n){is_dir($n)&&chdir($n)&s()|chdir("..");if($n<$r=strtr($n," ",_)){while(file_exists($r))$r.=_;rename($n,$r);}}} ``` recursive function. Run with `s(".");` Loop through `glob` results for given path: * if directory, recurse * replace spaces with underscore * if strings differ + while new filename is taken, append underscore + rename file/directory [Answer] # Python, 187 165, plus 22 penalty points for the spaces. ``` from os import* u='_';j=path.join for t,d,f in walk('.',0): for z in f+d: n=z.replace(' ',u) if n!=z: while path.exists(j(t,n)):n+=u rename(j(t,z),j(t,n)) ``` # 166, using [Emanuele's](https://codegolf.stackexchange.com/a/35853/14947) \t trick: Only a single space in this one! ``` from os import* u='_';j=path.join for t,d,f in walk('.',0): for z in f+d: n=z.replace(' ',u) if n!=z: while path.exists(j(t,n)):n+=u rename(j(t,z),j(t,n)) ``` [Answer] # LiveScript - 166 (Replace spaces with tabs.) ``` (a=->(s=require \fs)readdirSync(it)map (f)->f=it+'/'+f;r=f.replace /\s/g,i='';(while f!=r&&s.existsSync r=>r+=i++);s.statSync(f)isDirectory(s.renameSync f,r)&&a r) \. ``` Based on [nderscore's](https://codegolf.stackexchange.com/users/20160/nderscore) [optimized version](http://pastie.org/9456328) of [c.P.u1](https://codegolf.stackexchange.com/users/21777/c-p-u1)'s [answer](https://codegolf.stackexchange.com/a/35870/344). [Answer] **POSIX(Tested on zsh) + basic Linux commands 151** ``` export IFS=' ' for f in $(ls -R1);do export n=$(echo $f|tr ' ' '_');yes n|mv $f $n || yes n|mv $f `echo $n;echo $f|md5sum` done ``` [Answer] ## Ruby 194 ``` require'find' require'fileutils' Find.find(?.).sort{|a,b| b.length<=>a.length}.each {|f| if f.match(/ /) o=f.tr(' ',?_) begin raise if File.exist? o FileUtils.mv f,o rescue o+=?_ retry end end} ``` [Answer] **Bash 4+ 111 bytes** ``` shopt -s dotglob globstar for f in ** do n=${f// /} while [[ $f != $n && -e $n ]] do n+=1 done mv "$f" $n done ``` [Answer] **Groovy, 139 characters** ``` def c c={ f-> def g=new File(f.parent,f.name.replaceAll('\\s','')) f.renameTo(g) !g.directory ?: g.eachFile(c) } new File('.').eachFile(c) ``` according to @edc65 comment **Groovy, handle collisions, 259 characters** ``` def c c={ p,l,f-> def g=new File(p,f.name.replaceAll('\\s','')) f==g?: (g.exists()?f.renameTo(g.toString()+l.indexOf(f.name)):f.renameTo(g)) !g.directory?:g.eachFile(c.curry(g,g.list().toList())) } def r=new File('.') r.eachFile(c.curry(r,r.list().toList())) ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 8 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Recreate '99 bottles of beers on the wall'. The desired output is this: ``` 99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down and pass it around, 96 bottles of beer on the wall. 96 bottles of beer on the wall, 96 bottles of beer. Take one down and pass it around, 95 bottles of beer on the wall. 95 bottles of beer on the wall, 95 bottles of beer. Take one down and pass it around, 94 bottles of beer on the wall. .... 3 bottles of beer on the wall, 3 bottles of beer. Take one down and pass it around, 2 bottles of beer on the wall. 2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. Go to the store and buy some more, 99 bottles of beer on the wall. ``` Show me how you would solve this with your favorite programming language. Most creative use of a language wins. [Answer] ## Brainf\*\*\* (1,509) I figured I could trump [this](https://codegolf.stackexchange.com/questions/2/99-bottles-of-beer/422#422) answer by not only making 9 beer bottles instead of 1, but also by only using 7 different characters in the code. ``` +++ +++ +++ [>+ +++ ++> +++ +++ <<- ]>+ ++> +++ >++ +++ +++ ++> +++ +++ +++>+ +++++ +++++ [>+++ >++++ >++++ <<<-] >->>+ +>+++ +++++ [>+++ +++++ ++++> +++++ +++++ ++>++ +++++ +++++ >++++ +++++ +++>+ +++++ +++++ +>+++ +++++ +++++ >++++ +++++ ++++> +++++ +++++ +++>+ +++++ +++++ ++>++ +++++ ++++++> +++++++ ++++++> +++++++ +++++++ >++++++ +++++++ +>+++++ +++++++ ++>++++ +++++++ +++>+++ +++++++ ++++>++ +++++++ +++++<< <<<<<<< <<<<<<< <-]>+>+ +>++++> +++++>+ +++++>> +>+++>+ +++>+++ +++>+++ ++++>>+ +>+++>+ +++>+++++ >+++++++< <<<<<<<<< <<<<<<<<< <<<<[>[<< <.>.>>>>. >>>>>.>>> >>>>>>.>> >>..<<<<< <.<<<<<.>>> >>>>>>>.<<< <<<<<<<<<<< <<<.>>>>>>> >>>>>>>.<<< <<<.<<<<<<< <.>>>>>.>>. .>>>>>>>>>. <<<<<<<<<<< <<<<<.>>>>> >>>>>>>>>.< .<<<<<<<<<< <<<.>>>>>>> >>>>>>>>>>> .<<<<<<<<<. <<.<<<<<<<. >>>>>>>>>>> >>>>>>>>>.< <<<<<<<<<<< <<<<.>>>>>> >>..<<<<<<< <<<<.<.<<<< <.>.>>>>.>> >>>.>>>>>>> >>.>>>>..<< <<<<.<<<<<. >>>>>>>>>>. <<<<<<<<<<< <<<<<<.>>>> >>>>>>>>>>. <<<<<<.<<<< <<<<.>>>>>. >>..>>>>>>> >>.<<<<<<<< <<<<<<<.<.> >>>>>>>>>>> >>>>>>.<<<< <<<<<<<<<<. >>>>>>>.<<< <.<<<<<<<.> >>>>>>>>>>> >>.<.<<<<<< .<<<<<<<.>> >>>>.>>>>>> >>.>>>>>>.< <<<<<<.<<<< <<<<<<<<<.> >>>.>>>>>>> >>.<<<<<<<. <<<<<<.>>>> >>>>>>>>>>> .<<<<<<<<<< <.>>>>>>>>> >>>>..<<<<< <<<<<<<<<<< <.>>>>>>>>> >.>>>>>>>>. <<<<<<<<<<< <<<<<<<.>>> >.>>>>>>>>> >>>.<<.>>>> >.<<<<<<.<< <<<<<.<<<<< .<.<<<<<.>- .>>>>.>>>>> .>>>>>>>>>. >>>>..<<<<< <.<<<<<.>>> >>>>>>>.<<< <<<<<<<<<<< <<<.>>>>>>> >>>>>>>.<<< <<<.<<<<<<< <.>>>>>.>>. .>>>>>>>>>. <<<<<<<<<<< <<<<<.>>>>> >>>>>>>>>.< .<<<<<<<<<< <<<.>>>>>>> >>>>>>>>>>> .<< < <<< <<< . <<. <<< < <<< .>> > >>> >>> > >>> >>> > >>> .<< < <<< <<< < <<< <<< . >>> >> >>>. .<<< << <<<< <. << . << -]+ +++ ++ + ++ << + ++ ++ + ++ +<->>-] ``` I do have to admit though, there is a bug in the code (maybe you can figure out how to fix it for me?) and it does not print the final sentence, `Go to the store and buy some more, 99 bottles of beer on the wall.` But other than that, it functions just as well as any of the programs made in those sissy programming languages everyone else seems to like to use. [Answer] ## [Funciton](http://esolangs.org/wiki/Funciton) I wrote this just the other day. :) (Screenshots: [start](http://content.screencast.com/users/Timwi/folders/Jing/media/c3c9f9c0-23c1-4d08-9042-a4235dff077b/2011-05-08_1350.png) and [finish](http://content.screencast.com/users/Timwi/folders/Jing/media/d3378d56-9db7-4b31-9569-00cbe71afaa8/2011-05-08_1351.png)) Since this looks ugly in StackExchange due to the extra line spacing, consider running the following code in your browser’s JavaScript console to fix that: `$('pre').css('line-height',1)` ``` ╓┬────╖ ╔════╗ ┌───╖ ╟┘99b ║ ║ −1 ╟──┤ + ╟──┐ ╙──┬──╜ ╚════╝ ╘═╤═╝ ├──────────────────────────┴─────────────────────────────┐ ╔════╗ ┌─┴─╖ │ ╔════════════════════════════════════════════════════╗│ ║ 99 ╟──┤ ? ╟──┘ ║ 93438979891487426396059469986395555362079573844971 ║│ ╚════╝ ╘═╤═╝ ║ 71377306928718494179034460561943201885027745835961 ║│ ┌──┴───╖ ║ 98129935108241412387473531261660077880505710501626 ║│ ╔════╗ │ 99bp ║ ║ 32694396343717333192558234646820019070451056711 ║│ ║ 99 ║ ╘══╤═══╝ ╚══════════════════════════╤═════════════════════════╝│ ╚═╤══╝ ┌─┴─╖ ┌───╖ ┌─┴─╖ ╔═════════════════╗ │ ┌──┴──╖ │ ‼ ╟───────────────────────┤ ‼ ╟──┤ ? ╟──╢ 445551776368547 ║ │ │ 99b ║ ╘═╤═╝┌─────────────────────┐╘═╤═╝ ╘═╤═╝ ║ 925186328623383 ║ │ ╘══╤══╝ │ │╔═══════════════════╗│ │ │ ║ 851314944882510 ║ │ │ │ │║ 15177132563375318 ║│ │ │ ║ 812246570019017 ║ │ ╔════════╗ │ │║ 07655616350359109 ║│ │ │ ║ 240477365113929 ║ │ ║ 318287 ║ │ │║ 82597577171382437 ║│ │ │ ║ 659548419629671 ║ │ ║ 023073 ║ │ │║ 18150105146396039 ║│ │ │ ║ 952755268258505 ║ │ ║ 603558 ║ │ │║ 2022986808360992 ║│ │ │ ║ 759402210908648 ║ │ ║ 743780 ║ │ │╚══════════╤════════╝│ │ │ ║ 737406010882693 ║ │ ║ 068900 ║ │ │ ┌─┴─╖ ┌───╖ │ │ │ ║ 018745757193818 ║ │ ║ 028319 ║ │ │ │ ‼ ╟─┤ ‼ ╟─┘ │ │ ║ 597439618635403 ║ │ ║ 948400 ║ │ │ ╘═╤═╝ ╘═╤═╝ │ │ ║ 821854707881243 ║ │ ║ 620075 ║ │ │ ┌─┴─╖ │ ┌─┴─╖ │ ║ 92049082452 ║ │ ║ 955580 ║ │ └─────┬───┤ ‼ ╟────────┤ ‼ ║ │ ╚═════════════════╝ │ ║ 347161 ║ │ │ ╘═══╝┌──────┐╘═╤═╝ └─────────────┐ │ ║ 651333 ║ │ ╔═══╗│┌──────╖│╔════╗│ ╔╧═════════╗ │ │ ║ 590970 ║ │ ║ 0 ║└┤ 99bp ╟┘║ −1 ║└┐║ 20971566 ║ ├────────────┘ ║ 678045 ║ │ ╚══╤╝ ╘══════╝ ╚══╤═╝ │╚══════════╝ │ ║ 336290 ║ ┌─┴─╖ ┌─┴─╖ ┌─────╖ ┌┴──╖├──────────────────────┘ ║ 721824 ╟──┤ ‼ ╟──┤ ? ╟──┤ 99b ╟──┤ + ║│ ╚════════╝ ╘═══╝ ╘═╤═╝ ╘═════╝ ╘═╤═╝│ ╓┬──────╖ └───────┬───────┘ │ ╟┘ 99bp ║ └──────────┘ ╙───┬───╜ ┌────────────────────────────────────────────────┴──────────────┐ │╔══════════════════════════════════════════╗╔═══════════╗ │ │║ 8592134145756414358602136806465202028576 ║║ 232783950 ║ │ │╚══════════════════════════════╤═══════════╝╚╤══════════╝ │ │ ┌───╖ ╔═══╗ ┌─┴─╖ ┌───╖ ┌─┴─╖ ┌─────────╖ │ └───────────────┤ = ╟──╢ 1 ║ │ ‼ ╟──┤ ‼ ╟──┤ ? ╟──┤ int→str ╟──┴┐ ╘═╤═╝ ╚═══╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═════════╝ │ ╔═══╗ ┌─┴─╖ ┌─┴─╖ │ └──────────────────┘ ║ 0 ╟──┤ ? ╟─────────┤ ‼ ╟──┐ ╚═══╝ ╘═╤═╝ ╘═══╝ │ ╔════╧╗╔════════════════╧════════════════════════════════╗ ║ 115 ║║ 20338288213193790107412311132593873016630280224 ║ ╚═════╝╚═════════════════════════════════════════════════╝ ``` [Answer] # Perl (410 characters) There's [already a website dedicated](http://99-bottles-of-beer.net/tophits.html) to this contest: One of the Perl solutions would be very very hard to beat in terms of creativity, it reads: [bottles.pl] ``` $a= "cpuu \bmft p \bg cff \bs";$b ="po ui \bf xbm \bm";$c=" Ypv ublf p \bof epxo qb \btt ju bspvoe"; $a =~ s/\n//;$a =~ s/\s+/ /g; $b =~ s/\n// ; $b =~ s/\s+/ /g;$c =~ s/\n// ; $c =~ s/\s+/ /g;$a =~ y/b-z/a-z/;$b =~ tr/b-z/a-z/;$c =~ tr/b-z/a-z/ ; for( $d=100;$d>0;$d--){ print"$d $a $b $d" ;print" $a,\n$c, " ;print($d-1);print " $a $b.\n";} $x = "cjc"; $y="dobbz"; $z="com";print"\n" ;print "- $x\@$y." ;print"$z \n\n"; ``` Here's the link to the [original file](http://99-bottles-of-beer.net/download/658). [Answer] # jQuery + FireBug Console ``` $('code:first').text() ``` ;) [Answer] **HQ9+ (1 character)** ``` 9 ``` Admittedly its not a Turing complete language, but this still counts [Answer] Who said C# had too much ceremony? Whoever it was, they have never been so right. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _99Bottles { class Program { static void Main(string[] args) { PrintSong(99); } static void PrintSong(int bottleCount) { Func<int, string> sOrBlank = howMany => howMany > 1 ? "s" : ""; PrintBottles(howManyBottles => { Console.WriteLine("{0} bottle{1} of beer on the wall, {0} bottle{1} of beer.", howManyBottles, sOrBlank(howManyBottles)); if (howManyBottles > 1) { Console.WriteLine("Take one down and pass it around, {0} bottle{1} of beer on the wall.", --howManyBottles, sOrBlank(howManyBottles)); } else { Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall.", --howManyBottles); } }, bottleCount); } static void PrintBottles(Action<int> printBottles, int count) { printBottles(count); if (count > 1) { PrintBottles(printBottles, --count); } } } } ``` [Answer] # C This program is generating the complete song text as single string using the preprocessor. The actual C code just outputs the string thus constructed. Calling `strings` on the generated executable will reveal the complete song text in the executable. ``` #define BOTTLES(n) n " bottles of beer" #define BOTTLE "1 bottle of beer" #define OTW " on the wall, " #define TAKE "Take one down, pass it around, " #define BUY "Go to the store and buy some more, " #define STOP "." #define NL "\n" #define LINE1(n) BOTTLES(n) OTW BOTTLES(n) STOP NL #define LINE1A BOTTLE OTW BOTTLE STOP NL #define LINE2(n) TAKE BOTTLES(n) STOP NL #define LINE2A TAKE BOTTLE STOP NL #define LINEX BUY BOTTLES("99") NL #define MIDDLEPART(n) LINE2(n) NL LINE1(n) #define MIDDLELAST LINE2A NL LINE1A #define EIGHT_TO_TWO(S, M) M(S "8") M(S "7") M(S "6") M(S "5") M(S "4") M(S "3") M(S "2") #define EIGHT_TO_ONE(S, M) EIGHT_TO_TWO(S, M) M(S "1") #define EIGHT_TO_TWO_AGAIN(S, M) M(S "8") M(S "7") M(S "6") M(S "5") M(S "4") M(S "3") M(S "2") #define EIGHT_TO_ONE_AGAIN(S, M) EIGHT_TO_TWO_AGAIN(S, M) M(S "1") #define NINE_TO_TWO(S, M) M(S "9") EIGHT_TO_TWO(S, M) #define EIGHT_TO_ZERO(S, M) EIGHT_TO_ONE(S, M) M(S "0") #define NINE_TO_ZERO(S, M) M(S "9") EIGHT_TO_ZERO(S, M) #define NINETIES EIGHT_TO_ZERO("9", MIDDLEPART) #define NTIES(n) NINE_TO_ZERO(n, MIDDLEPART) #define EIGHTIES_TO_TENS EIGHT_TO_ONE_AGAIN("", NTIES) #define NAUGHTIES NINE_TO_TWO("", MIDDLEPART) #define SONG LINE1("99") NINETIES EIGHTIES_TO_TENS NAUGHTIES MIDDLELAST LINEX #include <stdio.h> int main() { puts(SONG); return 0; } ``` [Answer] **C# (312 310 304 characters)** ``` class P{static void Main(){string b=" bottle",w=" on the wall",o=" of beer",p=".\n",s="s";for(int i=99;i>0;i--)System.Console.Write(i+b+(i>1?s:"")+o+w+", "+i+b+(i>1?s:"")+o+p+(i>1?"Take one down and pass it around, "+(i-1)+b+(i-1>1?s:"")+o+w+p+"\n":"Go to the store and buy some more, "+99+b+s+o+w+p));}} ``` [Answer] ## C# Not intended to be short, but perhaps this counts as creative? ``` using System; using System.Linq; class Program { static void Main() { Console.WriteLine(string.Join(Environment.NewLine, Enumerable.Range(0, 100).Select(i => string.Format( string.Format( "{0} {1} {{3}} {{4}},{{9}}{0} {1} {{3}}.{{9}}{2},{{9}}{3} {4} {{3}} {{4}}.{{9}}", i == 99 ? "{0}" : "{7}", i == 98 ? "{1}" : "{2}", i == 99 ? "{6}" : "{5}", i == 98 ? "{0}" : "{8}", i == 97 ? "{1}" : "{2}" ), "No", "bottle", "bottles", "of beer", "on the wall", "Take one down, pass it around", "Go to the store, buy some more", 99 - i, (198 - i) % 100, Environment.NewLine )))); } } ``` Note this is just a single statement :) [Answer] Definitely doesn't qualify as creative, but it gets'r done from the command line with a single command. ``` perl -e '$i=99;while($i>1){print("$i bottles of beer on the wall, $i bottles of beer.\nTake one down and pass it around, ".--$i." bottles of beer on the wall\n\n");}print("1 bottle of beer on the wall, 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n");' ``` [Answer] ## Haskell, 272, 250, 243 characters ``` (&)=(++) b 1=" bottle" b _=b 1&"s" w=" on the wall" p n=show n&b n&" of beer" f n=putStrLn$p n&w&","&p n&".\n"&c(n-1) c 0="Go to the store and buy some more, "&p 99&w&"." c n="Take one down and pass it around, "&p n&w&"\n" main=mapM f[99,98..1] ``` [Answer] ## Windows PowerShell (198) ``` filter b{"$_ bottle$('s'*!!--$_) of beer"}(99..1|%{($_|b)+($w=' on the wall')+", $($_|b)." "Take one down and pass it around, $(--$_|b)$w. "})[0..196] "Go to the store and buy some more, $(99|b)$w." ``` Fairly straightforward. I'm using a filter for the bottles of beer, since `function` is longer and invocation needs parentheses in any case. The plural detection (`!!--$_`) first decrements the number of bottles by one (so plural is anything non-zero), casts it to boolean and negates it with the first `!` and negates it again so we now have a boolean describing whether the number needs a plural or not. This is then implicitly casted to an integer when multiplying the string. Inline line breaks are fun. Spawning more lines than needed and cutting back afterwards, too. [Answer] ## Curl 19 characters (requires internet connection) ``` curl -L j.mp/eGv9K5 ``` [Answer] Almost-correct anti-golf from the uber-eager new C programmer who's learning Perl? ``` #!/usr/bin/perl # ^ # | # | # That's the Perl interpreter. # You might need to change this line based on # your Linux/Unix distribution. # Pragmas for debugging! use strict; use warnings; # Library dependencies...none! lolz # Main implementation my $number_of_bottles_of_beer_on_the_wall = 99; #start with 99 bottles LOOP: while( $number_of_bottles_of_beer_on_the_wall > 0 ) { printf( "%d bottles of beer on the wall, %d bottles of beer\n", $number_of_bottles_of_beer_on_the_wall, $number_of_bottles_of_beer_on_the_wall, ); if( $number_of_bottles_of_beer_on_the_wall > 1 ) { $number_of_bottles_of_beer_on_the_wall -= 1; printf( "Take one down and pass it around, %d bottles of beer on the wall.\n\n", $number_of_bottles_of_beer_on_the_wall, ); } else { printf( "Go to the store and buy some more, %d bottles of beer on the wall\n", 99 ); last LOOP; } } ``` [Answer] # JavaScript (216 228 215) ``` for(a=99,c=" on the wall";a;)document.write((d=eval(b="(a||99)+' bottle'+(a-1?'s':'')+' of beer'"))+c+", "+d+".<br>"+(--a?"Take one down and pass it around, ":"Go to the store and buy some more, ")+eval(b)+c+".<p>") ``` Edit: Had a single "1 bottles of beer" in initial version, 3rd version is completely rewritten, notice cool tricks like `(a||99)` to get 99 in the last line, `(a-1?'s':'')` making plural for every case but `a==1` though without need for the wasteful `==`, and setting the value of `b` inside a statement where it is used. [Answer] **C** I must have missed this question, so here's a version I posted as an answer elsewhere. It's a C quine based version. Compile and run to get next line of song. Repeat until bored. If code says "Time to go..." then enter number of beers next time you run as a command line argument. ``` // Time to go to the shop and get some beer // // // // // #####.#####.#####.#####.#####.#####.##### // ##.#####.#####.#####.#####.#####.#####.## // #####.#####.#####.#####.#####.#####.##### // ##.#####.#####.#####.#####.#####.#####.## char *z [] = { "void l(char *s,int b){int i;printf(\"// \");for(i=0;i<b;++i)printf(s);", "printf(\"\\n\");}\nint main(int argc, char *argv[]){\nint i,j,k,x=%d;", "char*p;\nif(!x&&argc==2)x=atoi(argv[1]);\nif(!x){printf(\"// Time to ", "go to the shop and get some beer\\n//\\n//\\n//\\n//\\n\");k=7;\n", "}else{printf(\"// %%d bottles of beer on the wall, %%d bottles of beer", ".\\n\",x,x);printf(\"// Take one down and pass it round, \");\n", "if(x>1)printf(\"%%d bottles of beer on the wall.\\n//\\n\",x-1);\n", "else printf(\"no more bottles of beer on the wall.\\n//\\n\");\n", "k=x>2?x:2;l(\" ^ \",x);l(\" / \\\\ \",x);l(\"/ \\\\ \",x);", "l(\"| | \",x);l(\"|Duf| \",x);l(\"| | \",x);l(\"----- \",x);}\n", "for(i=0;i<4;++i){\nprintf(\"// %%s\", i&1 ? \"##.\" : \"\");\n", "for(j=i&1;j<k;++j)\nprintf(\"%%s#####\",j!=(i&1)?\".\":\"\");\n", "printf(\"%%s\\n\",i&1?\".##\":\"\");}\nprintf(\"\\nchar *z [] = {\\n\");\n", "for(i=0;i<sizeof z/sizeof z[0];++i){\nprintf(\"\\\"\");\n", "for(p=z[i];*p;++p)\nswitch (*p){\ncase '\\n':printf(\"\\\\n\");break;\n", "case '\\\\':printf(\"%%c%%c\",92,92);break;\n", "case '%%':printf(\"%%c\",37);break;\ncase '\"':printf(\"%%c%%c\",92,'\"');break;\n", "default:printf(\"%%c\", *p);break;}\nprintf(\"\\\",\\n\");}\n", "printf(\"};\\n\");\nfor(i=0;i<sizeof z/sizeof z[0];++i)\n", "printf(z[i],x?x-1:0);}\n", }; void l(char *s,int b){int i;printf("// ");for(i=0;i<b;++i)printf(s);printf("\n");} int main(int argc, char *argv[]){ int i,j,k,x=0;char*p; if(!x&&argc==2)x=atoi(argv[1]); if(!x){printf("// Time to go to the shop and get some beer\n//\n//\n//\n//\n");k=7; }else{printf("// %d bottles of beer on the wall, %d bottles of beer.\n",x,x);printf("// Take one down and pass it round, "); if(x>1)printf("%d bottles of beer on the wall.\n//\n",x-1); else printf("no more bottles of beer on the wall.\n//\n"); k=x>2?x:2;l(" ^ ",x);l(" / \\ ",x);l("/ \\ ",x);l("| | ",x);l("|Duf| ",x);l("| | ",x);l("----- ",x);} for(i=0;i<4;++i){ printf("// %s", i&1 ? "##." : ""); for(j=i&1;j<k;++j) printf("%s#####",j!=(i&1)?".":""); printf("%s\n",i&1?".##":"");} printf("\nchar *z [] = {\n"); for(i=0;i<sizeof z/sizeof z[0];++i){ printf("\""); for(p=z[i];*p;++p) switch (*p){ case '\n':printf("\\n");break; case '\\':printf("%c%c",92,92);break; case '%':printf("%c",37);break; case '"':printf("%c%c",92,'"');break; default:printf("%c", *p);break;} printf("\",\n");} printf("};\n"); for(i=0;i<sizeof z/sizeof z[0];++i) printf(z[i],x?x-1:0);} ``` [Answer] # Javascript (285) This assumes there is a function called print, to output a string. ``` b=' of beer on the wall';n=100;while(--n>1)if(n>1)print(n+" bottles"+b+', '+n+" bottles of beer.\nTake one down and pass it around, "+(n-1)+' bottle'+(n-1>1?'s':'')+b+'.\n\n');print("1 bottle"+b+", 1 bottle of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.") ``` [Answer] # Scheme (270) No whitespace: ``` (let l((i 99))(let((b" bottle")(c" on the wall")(d"Take one down and pass it around,")(e".\n")(f", ")(g" of beer"))(if(= i 1)(map display`(1,b,g,c,f,1,b,g,e"Go to the store and buy some more, 99",b,c,e))(begin(map display`(,i,b,g,c,f,i,b,e,d,i,b,c,e"\n"))(l(-1+ i)))))) ``` With whitespace: ``` (let l ((i 99)) (let ((b" bottle") (c" on the wall") (d"Take one down and pass it around, ") (e".\n") (f", ") (g" of beer")) (if (= i 1) (map display`(1 ,b ,g ,c ,f ,1 ,b ,g ,e "Go to the store and buy some more, 99" ,b ,c ,e)) (begin (map display `(,i ,b ,g ,c ,f ,i ,b ,e ,d ,i ,b ,c ,e "\n")) (l (-1+ i)))))) ``` [Answer] # Python - a lot Amidoinitrite? ``` print"""99 bottles of beer on the wall, 99 bottles of beer. Take one down and pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down and pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down and pass it around, 96 bottles of beer on the wall. 96 bottles of beer on the wall, 96 bottles of beer. Take one down and pass it around, 95 bottles of beer on the wall. 95 bottles of beer on the wall, 95 bottles of beer. Take one down and pass it around, 94 bottles of beer on the wall. .... Ok, this is stupid. First of all, what the brainfuck are the bottles doing on the wall? They're not spiders nor picture frames. And how are they sitting on the wall? 94 bottles of beer on the wall, 9.. oops, they fell down. 94 bottles of beer on the floor, 94 bottles of beer. Second.. who the HQ9+ wants to keep track? I think I lost count after drinking the 2nd one... Take one ... um... up, and pass it around, ..... er.. a lot of bottles of beer still on the floor. Fourthly, what's with this passing around scheme? They're not j..I mean letters, yeah, or boxes of chocolate. We all can just take one and drink it. It's healthier too. A pile of bottles of beer on the floor, a pile of bottles of beer. Everyone take one up and drink it, still a whole bunch of bottles of beer on the floor. Um.. seventhly, are we really that many in this assembly that we can finish 200 or however many bottles we had in the beginning? Without passing out? Go to the store and buy some more Yeah and who's gonna pay for it? Definitely not me. And how are you going to bring 300 bottles back from the store? In your car? Buddy, you're so drunk, you can't even C anything. Go home dude, go home. Take a cab.""" ``` Additional reference (helped me a lot with the code): <http://www.youtube.com/watch?v=Y0Z0raWIHXk> [Answer] ## Python (318) I found this way of making a Python program shorter :) ``` exec'eJxtjrFqwzAQQHd/xVVgLCVqSbq5RHO2TtlcgyX7Qk3luyAphP59ZA0thGzi9O7es0bUERyn5DE/+AwOMdTxi0TljLeLmyzQB4GlaaCBg/hkWDigqMb/76aZz0CHHaCPCLaWTpLSTWw2kl7MXmkBTJC+EW7Wey3U9hmzzqU42R/MNMLEt6KFi40R5gQ28JUmndO0ODIkLhdjyjWFc9dfiLxg6Vsx1ZExu36Vddn2miVD2w59R4d9/6d+f8h7Wze3Y+GrS5gpwSjbVlV3Y1BZCg=='.decode('base64').decode('zip') ``` [Answer] ## [Rebmu](http://hostilefork.com/rebmu/) — 167 characters `M N 99 Bdz[cb[n{ bottle}egN 1{s}{}{ of beer}]]loN[cb[b W{ on the wall}C{, }b P{.}lfEZ--n[Nm{Go to the store and buy some more}]{Take one down and pass it around}cBwPlf]]` Could probably shave a few characters off, this was just a first try. :) Here's equivalent [Rebol](https://stackoverflow.com/tags/rebol/info) which has the shorthand boiled out. Still pretty competitive especially considering the clarity: ``` m: n: 99 b: does [ combine [n { bottle} either n > 1 {s} {} { of beer}] ] loop n [ print combine [ b w: { on the wall} c: {, } b p: {.} newline either 0 == -- n [ n: m {Go to the store and buy some more} ] [ {Take one down, and pass it around} ] c b w p newline ] ] ``` Commented source code [available on GitHub](https://github.com/hostilefork/rebmu/blob/master/examples/99bottles.rebmu) [Answer] ## PHP: 285 240 233 231 Characters ``` $i=99;$b=" bottles of beer";$o=" bottle of beer";$c=" on the wall";while($i>1){echo"$i$b$c, $i$b.\nTake one down and pass it around, ".--$i.(($i>1)?$b:$o).$c.".\n\n";}echo"$i$o$c, $i$o.\nGo to the store and buy some more, 99$b$c."; ``` Output here: <http://ideone.com/5fQmcd> [Answer] ## Python, 241 chars ``` s="" i=99 b="%d bottl%s of beer" w=" on the wall" t="Take one down and pass it around, " p=q="es" while i:s+=b%(i,p)+w+", "+b%(i,p)+".\n";i-=1;p=p[:i];s+=t+b%(i,p)+w+".\n\n" print s[:-64]+"Go to the store and buy some more, "+b%(99,q)+w+"." ``` [Answer] ## Ruby, 274 bytes Still pretty new to Ruby, really just playing around ``` o =" bottles of beer";w=" on the wall";t="Take one down and pass it around, ";s=" bottle of beer" 99.downto(3){|b|puts"#{b}#{o+w}, #{b}#{o}.\n#{t}#{b-1}#{o+w}.\n\n"} puts"2 #{o+w}, 2 #{o}.\n#{t}1#{s}#{w}.\n\n1#{s+w}, 1#{s}.\nGo to the store and buy some more, 99#{o+w}." ``` [Answer] # C# (299 characters) ``` using System;class D{static void Main(){string a="s",z="",w=" on the wall",q=", ",p=".\n",b=" bottle",c=" of beer";for(int O=99;O>=1;)Console.WriteLine(O+b+(O>1?a:z)+c+w+q+O+b+(O>1?a:z)+c+p+(--O>0?"Take one down and pass it around, "+O:"Go to the store and buy some more, 99")+b+(O==1?z:a)+c+w+p);}} ``` [Answer] ## JavaScript (7 functions) Not golfed. This is intended as a (mostly) functional implementation of the song. ``` function firstUpper(s) { return s.slice(0, 1).toUpperCase() + s.slice(1); } function bottles(x) { return (x || "no more") + " " + (x == 1 ? "bottle" : "bottles") + " of beer"; } function wall(x) { return bottles(x) + " on the wall"; } function line1(x) { return wall(x) + ", " + bottles(x) + "."; } function line2(x, max) { return (x ? "take one down and pass it around, " + wall(x - 1) : "go to the store and buy some more, " + wall(max)) + "."; } function verse(x, max) { return [line1(x), line2(x, max)].map(firstUpper).join("\n") + "\n\n"; } function song(max) { var text = ""; for(var x = max; x >= 0; x--) { text += verse(x, max); } return text; } print(song(99)); ``` [Answer] # Go (263) ``` package main import "fmt" func main(){b,i,e,r:=fmt.Println,99,"bottles","of beer on the wall" for i>0{b(i,e,r+",",i,e,r[:7]+".") if i--;i<2{e=e[:6]} if i>0{b("Take one down and pass it around,",i,e,r+`. `)}} b("Go to the store and buy some more,",99,e+"s",r+".")} ``` [Answer] ## PHP - 252 bytes ``` $a=" bottles of beer";$b=str_replace("s","",$a);$c=" on the wall";for($i=98;$i;)echo($j=$i+1).$a.$c.", ".$j.$a.". Take one down and pass it around, ".$i.($i-->1?$a:$b).$c.". ";echo"1".$b.$c.", 1".$b.". Go to the store and buy some more, 99".$a.$c."."; ``` I hope I'll compress some more tomorrow. [Answer] ## Ruby 1.9.2p136 : 223 I'm no coward, you can read mine ;p ``` b="%d bottle%s of beer" w=' on the wall' 99.downto(1){|z|s=b%[z,z>1?'s':''] puts s+w+", "+s+". "+(z>1?"Take one down and pass it around, "+b%[z-1,z>2?'s':'']+w+". " :'Go to the store and buy some more, '+b%[99,'s']+w+".")} ``` [Answer] # (Oracle) SQL No character count, I didn't golf it. Just found this a fun way to do it. ``` WITH bottles AS ( SELECT LEVEL - 1 AS bottle FROM dual CONNECT BY LEVEL <= &number_of_bottles + 1 ), fragments AS ( SELECT 'no more ' AS none, 'bottles of beer' AS supply, ' on the wall' AS wall, 'Take one down and pass it around' AS drink, 'Go to the store and buy some more' AS refill, CHR(13) || CHR(10) AS newline FROM dual ), combined AS ( SELECT b.bottle, DECODE( b.bottle, 1, b.bottle || ' ' || REPLACE(f.supply, 's'), 0, f.none || f.supply, b.bottle || ' ' || f.supply ) AS supply FROM bottles b CROSS JOIN fragments f ), two_lines AS ( SELECT LEVEL AS line FROM dual CONNECT BY LEVEL <= 2 ) SELECT CASE l.line WHEN 1 THEN REPLACE(c1.supply, 'n', 'N') || f.wall || ', ' || c1.supply || '.' WHEN 2 THEN DECODE(b.bottle, 0, f.refill, f.drink) || ', ' || c2.supply || f.wall || '.' END AS song FROM bottles b LEFT JOIN combined c1 ON (c1.bottle = b.bottle) LEFT JOIN combined c2 ON (c2.bottle = DECODE(b.bottle - 1, -1, &number_of_bottles, b.bottle - 1)) CROSS JOIN two_lines l CROSS JOIN fragments f ORDER BY b.bottle DESC, l.line; ``` ]
[Question] [ Long-time lurker, first-time poster. So here goes. In the Wikipedia page for [quine](https://en.wikipedia.org/wiki/Quine_%28computing%29#.22Cheating.22_quines), it says that "a quine is considered to be 'cheating' if it looks at its own source code." Your task is to make one of these "cheating quines" that reads its own source code. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes - *in each language* - wins. This means that a 5-byte Pyth script would not beat a 21-byte Python script - but a 15-byte Python script would. You must use file I/O to read the source code, so the following JavaScript code, taken from the official Wikipedia page, is invalid: ``` function a() { document.write(a, "a()"); } a() ``` It must access the source code of the file *on disk*. **You are not allowed to specify the file name. You must make it detect the filename itself.** Everyone clear? Go! [Answer] # [Zsh](https://www.zsh.org/), 4 bytes ``` <$0 ``` The Z shell has feline functionalities built in. The fourth character is a linefeed. [Try it online!](https://tio.run/nexus/zsh#@2@jYsD1/z8A "Zsh – TIO Nexus") The code does not depend in any way on the file name; it works even if the file name contains special character, such as spaces or newlines. ### Test run ``` $ cat "my quine.sh" <$0 $ zsh "my quine.sh" <$0 $ diff -s <(zsh "my quine.sh") <(cat "my quine.sh") Files /dev/fd/63 and /dev/fd/62 are identical ``` [Answer] # Bash, 6 bytes ``` cat $0 ``` Basically. [Answer] # UNIX executable loader, 10 bytes ``` #!/bin/cat ``` If you don't care about spam on standard error, you can make it one byte shorter: ``` #!/bin/dd ``` [Answer] # C, 52 ``` s[99];main(){read(open(__FILE__,0),s,99);printf(s);} ``` Of course, this reads the source code and not the compiled program - I assume that's within spec. [Answer] # [Vyxal 2.4.0](https://github.com/Lyxal/Vyxal/releases/tag/v2.4.0), 50 bytes ``` `\");VY_print(chr(96)+code.split('\n')[3][15:-4])# ``` Vyxal doesn't have a way to read files, but in v2.4.0 and prior, there was an ACE exploit that allowed for arbitrary python to be executed. --- ### The ACE: Vyxal is a transpiled language, meaning that every command in a program is converted to some python code, and then all of the python code is combined together and executed. When pushing a string, all that was done to the string in transpilation was changing `"` to `\\\"`, then appending it to the stack. This meant that a string `\"); #` would become `\\");#`. On its own, this means nothing, but when considered in the transpiled code, it is much more useful. When viewing the transpiled code (which you can do for any Vyxal program using the `c` flag), you can see that the snippet ``\\"); #` is transpiled to the following python code: ``` stack.append("\\"); #\n") ``` Instead of pushing the string that we told it to, it simply pushed `\`, followed by a comment. In theory, we could put any python code between the `;` and the `#`, which is what we do in this program. --- ### The program: In this program, the payload (the python code that we actually care about) is the following: ``` VY_print(chr(96)+code.split('\n')[3][15:-4]) ``` This has several parts to it, so lets pick it apart bit by bit. `VY_print` is the printing function that is defined internally in Vyxal. I used this function instead of `print` because it disables the implicit output that Vyxal normally has. This prints the final string, which will hopefully be the same as the program. When the program is transpiled, the transpiled code is saved in the `code` variable. This variable is used in the program to read the source code, which makes this a cheating quine. However, the `code` variable also contains a header that initializes a few variables, such as the stack. To combat this, we `split` the code on newlines and get only the fourth line, which is where our code is. Unfortunately, this line also has the `stack.append...`, and the comment at the end, neither of which are part of our quine. Because of this, we need to take only the 16th through 5th-to-last characters in the string, which we do with `[15:-4]`. Finally, our code has a backtick at the beginning to start the string, so we add one to the beginning of the output with `chr(96)`, since the ASCII value of ``` is 96. [Answer] ## Perl, 15 bytes ``` open 0;print<0> ``` Saved 3 bytes thanks to @[ThisSuitIsBlackNot](https://codegolf.stackexchange.com/users/31388/thissuitisblacknot)! [Answer] # PHP, 21 Bytes ``` <?=file(__FILE__)[0]; ``` `file` reads a file line by line into an array and the file only has one line. This saves a byte in comparison to `readfile(__FILE__)`. [Answer] # Perl 6, 20 bytes ``` print slurp $?FILE ``` I haven't worked with Perl 6 very long so I'm not sure if there are any tricks to make this shorter. [Answer] # osascript (AppleScript from the command line), ~~40~~ ~~33~~ 32 bytes ``` (read path to me)'s paragraph 1 ``` Executing on a file called a with `osascript a`. Gets the first paragraph (line) of the file and prints it to STDOUT with a trailing newline, therefore the newline in the code. [Answer] # Python 2, 32 bytes There's a newline at the end of the file. ``` print open(__file__).readline() ``` # Python 3, 33 bytes There's a newline at the end of the file. ``` print(open(__file__).readline()) ``` Thanks to [feersum](https://codegolf.stackexchange.com/users/30688/feersum) for catching a problem and supplying `__file__`, [Loovjo](https://codegolf.stackexchange.com/users/34543/loovjo) for a new approach to the Python 2 solution that saved 17 bytes, and [Skyler](https://codegolf.stackexchange.com/users/45727/skyler) for a solution that saved yet another byte and worked in both Python 2 and 3 (pending `print` being a function in Python 3)! [Doc link for `readline`](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) [Answer] # Python 2.7, 30 bytes ``` print open(__file__).read(29) ``` Edit: Just to be clear, the code above is supposed to have a newline at the end as the 30th byte. I'm not familiar with markdown enough to figure out how to display it in the code block. I'm using the same trick here as the one in my C submission. This reads the whole source file excluding the trailing newline to account for the additional newline which `print` will append to the output. [Answer] # Batch, ~~9~~ 8 Bytes ``` @type %0 ``` Saved a byte thanks to @Joshua [Answer] # AutoIt, 34 bytes Outputs itself to the clipboard: ``` ClipPut(FileRead(@ScriptFullPath)) ``` [Answer] # Ruby, 14 ``` $>.<<IO.read$0 ``` [Answer] # Go, ~~111~~ 105 bytes ``` package main import("io" ."os" ."runtime") func main(){_,p,_,_:=Caller(0) f,_:=Open(p) io.Copy(Stdout,f)} ``` My first code-golf in Go – just a few tricks you can use here I guess. [Answer] # C, 49 bytes ``` s[];main(){read(open(__FILE__,0),s,48);puts(s);} ``` Edit: To clarify, the 49th byte is a newline. This reads the source code minus the newline at the end to account for the newline which `puts` will append to the end of the output. [Answer] ## C, 31 bytes ``` main(){system("cat "__FILE__);} ``` [The bash solution](https://codegolf.stackexchange.com/a/62143/3544) is so short, so why not base a C solution on it? [Answer] # PowerShell, 39 36 31 25 Bytes About as tight as I can get it: `gc $MyInvocation.MyCommand.Path | oh` Backed by popular demand this has been changed to: ``` gc $PSCommandPath|echo -n ``` prints to host shell current standard output. [Answer] # Ruby, 15 bytes ``` $><<IO.read($0) ``` Source: <https://stackoverflow.com/questions/2474861/shortest-ruby-quine> [Answer] # Pyth, 25 bytes ``` $import sys$h'e$sys.argv ``` This reads its file name. Essentially, it looks up argv, opens the file corresponding to its last argument, and prints its first line. [Answer] # Mathematica, 16 bytes ``` FilePrint@$Input ``` Run it in [script mode](http://reference.wolfram.com/language/tutorial/WolframLanguageScripts.html). [Answer] ## [><>](http://esolangs.org/wiki/Fish), 13 Bytes ``` 0:0go:c=?;1+! ``` Tested both on the online and offline interpreters. The `g` command is the closest to being able to read from the source file and if it doesn't count for the purpose of this challenge I'll mark my entry non-competing; I do believe it normally considered "cheating" for quines. [Try it online.](http://fishlanguage.com/playground) [Answer] # Haskell, 63 bytes For science! ``` import System.Environment main=getProgName>>=readFile>>=putStr ``` [Answer] # [Haskell](https://www.haskell.org/), 49 bytes ``` {-#LANGUAGE CPP#-}main=putStr=<<readFile __FILE__ ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v1pX2cfRzz3U0d1VwTkgQFm3NjcxM8@2oLQkuKTI1samKDUxxS0zJ1UhPt7N08c1Pv7/fwA "Haskell – Try It Online") (GHC) Haskell has an extension to use the C preprocessor (commonly used for portability between versions and architectures.) Hopefully self-explanatory. [Answer] # [Rust](https://www.rust-lang.org/), 45 bytes ``` fn main(){print!("{}",include_str!(file!()))} ``` [Try it online!](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDqbpWSSczLzmnNCU1vrikSFEjLTMnVVFDU1Oz9v9/AA "Rust – Try It Online") The file macro expands to the file it's invoked in's file path, the include\_str macro expands to a string literal containing the contents of the file at the specified path, and the print macro prints. [Answer] # Go, 133 Bytes > > Everyone clear? Go! > > > ``` package main import("fmt" "io/ioutil" "runtime") func main(){_,f,_,_:=runtime.Caller(0) s,_:=ioutil.ReadFile(f) fmt.Print(string(s))} ``` [Answer] # Node.js, ~~66~~ 63 bytes ``` p=process;p.stdout.write(require('fs').readFileSync(p.argv[1])) ``` Doesn't use `console.log`, which appends a newline. [Answer] # Java 8, ~~133~~ 125 Bytes (or ~~150~~ 142 slightly cleaner) Based on @VoteToClose's answer but choosing Files.copy and thus avoiding the intermediate String creation needed to call System.out: ``` import java.nio.file.*;interface A{static void main(String[]a) throws Exception{Files.copy(Paths.get(A.class.getName()+".java"),System.out);}} ``` or hard-coding the class-name even more: ``` import java.nio.file.*;interface A{static void main(String[] a)throws Exception{Files.copy(Paths.get("A.java"),System.out);}} ``` Cleaned up: ``` import java.nio.file.*; class A { public static void main(String[] a) throws Exception { Files.copy(Paths.get("A.java"), System.out); } } ``` [Answer] # HTML with JavaScript, 115 bytes (doesn't really count) ``` <!DOCTYPE html><html><title>x</title><script>alert(new XMLSerializer().serializeToString(document))</script></html> ``` Does this count? I don't mind, it was fun :) Technically it doesn't open a file. It's also a well-formed HTML5 document. The XMLSerializer was the only tool which also returned the DOCTYPE portion, but is non-standard. Still, it works on chrome and firefox, and I bet other browsers. And as a bonus: # JavaScript, 41 bytes ``` alert(document.currentScript.textContent) ``` [Answer] # [𝔼𝕊𝕄𝕚𝕟](https://github.com/molarmanful/ESMin/), 2 chars / 6 bytes ``` ℹ⬮ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin//interpreter.html?eval=false&input=&code=%E2%84%B9%E2%AC%AE)` The ℹ function both returns and pushes to the stack the source code. There is automatic outputting, so the contents of the stack will be outputted. Therefore, the source code will be outputted. ]
[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/104323/edit). Closed 2 years ago. [Improve this question](/posts/104323/edit) Your task is to write a full program or function that takes no input and runs any type of loop (`while`, `for`, `foreach`, `do`, `do-while`, `do-loop`, `goto`, recursion, etc) that will end in causing an error, which means that the program must stop itself running and exit. **Rules:** 1. The error must be a run-time error, unhandled exception, or anything that makes the program end itself. 2. The error must produce the stop and exit from the program without calling explicitly `exit;` (or equivalent) at some point. 3. Messages like `Warning:`, `Notice:`, etc, that do not cause the program to end itself are not valid. For example in PHP divisions by zero produces a `Warning` message but the program will not stop and will still run, this is not a valid answer. 4. The loop must run at least one full cycle. In other words the error can happen starting at the second cycle and further. This is to avoid to cause the error using incorrect code syntax: the code must be syntactically correct. 5. The loop can be even infinite (example `for(;;);`) if it respects the above said rules, but must take no longer than 2 minutes to end itself in a run-time error. 6. Recursion without Tail Call Optimization is invalid ([1](https://stackoverflow.com/a/33930/2096343),[2](https://stackoverflow.com/a/310980/2096343)). 7. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins. 8. [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/59718) are forbidden. **C# example ([test online](https://dotnetfiddle.net/oIM5Ds)):** ``` using System; public class Program { public static void Main() { int i; int[] n; n = new int[5]; for(i=0; i<7; i++) { n[i] = i; Console.WriteLine(n[i]); } } } Output: 0 1 2 3 4 Run-time exception (line 9): Index was outside the bounds of the array. Stack Trace: [System.IndexOutOfRangeException: Index was outside the bounds of the array.] at Program.Main(): line 9 ``` **Leaderboard:** ``` var QUESTION_ID=104323,OVERRIDE_USER=59718;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;font-family:Arial,Helvetica; font-size:12px}#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> ``` Thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) for the [Leaderboard Snippet](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet) [Answer] # Python, 16 bytes The non-interesting 0 division approach: ``` for x in 1,0:x/x ``` The first iteration computes `1 / 1`, which works fine. The second iteration tries to compute `0 / 0`, resulting in a `ZeroDivisionError` being thrown. ## 17 bytes (personal favourite) ``` i=1 while i:del i ``` Initially, `i=1` which is truthy, so the loop is entered. The first time the loop is run, the variable `i` is deleted. This means that, the second time, `i` is no longer a variable and therefore its evaluation fails with `NameError: name 'i' is not defined.` --- Another 15 byte solution would be `def _():_()` (newline) `_()`, because Python does not optimize tail recursion. However, this violates rule #6. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~5~~ 1 byte *Idea taken from @MartinEnder's [CJam answer](https://codegolf.stackexchange.com/a/104330/36398)* ``` ` ``` [Try it online!](https://tio.run/nexus/matl#@5/w/z8A) ``` ` % Do...while loop % Implicit end. The loop continues if the top of the stack is true. % After the first iteration, since the stack is empty, the program % implicitly tries to take some non-existing input, and finishes % with an error ``` --- ### Old version ``` 2:t"x ``` [Try it online!](https://tio.run/nexus/matl#@29kVaJU8f8/AA "MATL – TIO Nexus") ``` 2: % Push [1 2] t % Duplicate " % For each (i.e. do the following twice) x % Delete top of the stack. Works the first time. The second it tries to % implicitly take some non-existing input, and finishes with an error ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 bytes ``` Ṿß ``` Kills itself by running out of memory. Locally does so after ~100 seconds. [Try it online!](https://tio.run/nexus/jelly#@/9w577D8///BwA "Jelly – TIO Nexus") (death certificate in *Debug* drawer) ### How it works ``` Ṿß Main link. Argument: x. Implicit first argument: 0 Ṿ Uneval; yield a string representation of x. ß Recursively call the main link. Jelly uses TCO, so the first cycle finishes successfully before entering the next one. ``` The first few iterations yield: ``` '0' '”0' '””,”0' '””,””,”,,””,”0' '””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0' '””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”,,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0' ``` After that, it gets real ugly, real fast. [Answer] # [V](https://github.com/DJMcMayhem/V), 2 bytes ``` òl ``` [Try it online!](https://tio.run/nexus/v#@394U87//xmpOTn5igA "V – TIO Nexus") This is the *perfect* challenge for V because I already do that all the time! In fact, V doesn't even have any conditionals, it only has functions that break on an error. In this case, the `ò` means "repeat forever" and the `l` means "move right". In an empty buffer (no input) this will break on the first pass and produce no output. If there *is* input, it will break once we move post the last character of input, and output all of the input (making this also a cat program) [Answer] # JavaScript (ES6), 13 bytes ``` f=_=>f(_?a:1) ``` This is a recursive function that runs fine once, then throws `ReferenceError: a is not defined` and quits. Here's a 15-byte non-ES6 version: ``` for(i=0;;)i=i.a ``` This runs fine once, then throws `TypeError: i is undefined` and quits. [Answer] # [GNU sed](https://www.gnu.org/software/sed/), ~~15 13~~ 5 bytes -2 Thanks to [seshoumara](https://codegolf.stackexchange.com/users/59010/seshoumara) -8 Thanks to [zeppelin](https://codegolf.stackexchange.com/users/61904/zeppelin) ``` H;G;D ``` 1. Appends a newline and the hold space to the pattern space. 2. Appends a newline and the pattern space to the hold space. 3. Deletes up to the first newline and starts over. This quickly runs out of memory: ``` $ time (echo|sed 'H;G;D') sed: couldn't re-allocate memory real 0m1.580s user 0m0.545s sys 0m1.012s ``` [Answer] # Bash 4.2, 22 bytes ``` exec $0 $@ $[2**$#%-1] ``` Doesn't work in TIO because it has Bash 4.3, and the bug I'm relying on was *finally* fixed. ### Verification ``` $ xxd -c 22 -g 22 self-destruct 0000000: 6578656320243020244020245b322a2a2423252d315d exec $0 $@ $[2**$#%-1] $ ./self-destruct Floating point exception ``` This crashes once the program tries to compute **263 mod -1**, which crashes in Bash 4.2 and older versions due to a known bug. [Answer] # Befunge-93, 3 bytes (possibly 1 or 0) ``` !%! ``` [Try it online!](http://befunge.tryitonline.net/#code=ISUh&input=) On the first iteration of the loop, the stack is empty, which is the equivalent of all zeros. The `!` (not) operation thus converts the stack top to 1, and the `%` (modulo) operation calculates 0 mod 1, leaving 0. The next `!` operation converts that 0 to a 1 before the program counter wraps around and begins the loop again. On the second iteration, the first `!` operations converts the 1 that is now at the top of the stack to a 0. The `%` operation then calculates 0 mod 0, which produces a division by zero error on the reference interpreter, and thus terminates the program. There's also the more boring 1 byte answer, although I'm not sure if this is considered valid. ``` " ``` [Try it online!](http://befunge.tryitonline.net/#code=Ig&input=) This `"` command starts a string, thus every space on the rest of the line is pushed onto the stack until the program counter wraps around and encounters the `"` again closing the string. It'll then need to wrap around a second time to repeat the process starting another string and pushing another 79 spaces onto the stack. Eventually this will either run out of memory (the reference interpreter behaviour) or produce a stack overflow. Now if you want to really push the rules there's also technically a zero byte solution. ``` ``` If you take [this ruling](http://meta.codegolf.stackexchange.com/a/7833/62101) to mean that *any* interpreter defines the language (as many here do), then we can assume for the moment that the Befunge language is defined by [this interpreter](http://kermit.kishwaukeecollege.edu/~dklick/cis119/Befunge93.html). And one of the "features" of that interpreter is that it pushes an *Undefined* value onto the stack for each loop of the playfield when executing a blank program. Given enough time it will eventually run out of memory. How fast that happens will depend on the speed of the computer, the available memory, and the browser being used. On my machine I found that Microsoft Edge worked best, but even then it was "only" using 500MB after two minutes. It wasn't until around the fifteen minute mark (with several gigabytes used) that Edge decided to kill the process and refresh the tab. So it's unlikely to make it under the two minute time limit, but with the right conditions that wouldn't necessarily be out of the question. [Answer] # PHP, ~~22~~ ~~21~~ ~~20~~ 18 bytes This relies on PHP allowing one to give a function name to a variable and try to run it. This simply concatenate the name of the `pi` function twice. This kills PHP with a `Fatal Error: Uncaught Error: Call to undefined function pipi() in [...][...]`. ``` while($x.=pi)$x(); ``` This works similar to my old answer. --- **Old answer, 20 bytes** PHP allows you to increment characters, using the increment operator. It only works on the `a-z` range, but is enough. ``` for($x=pi;;)$x=$x(); ``` I believe this fulfills all the required points and the loop does run once. You can see if because you will get the error `Fatal error: Function name must be a string`. --- How this works, step by step: * Assign `pi` to `$x`. Since `pi` is being used as a constant, PHP will check if exists. Since it doesn't, PHP shows a warning saying `Use of undefined constant pi - assumed 'pi'` (Basically: since the constant doesn't exist, it is assumed to be a string) * Loop the first time + Run the function `$x()`. Since `$x` has the value `pi`, it will run the function `pi()`. * Store the value in `$x`. `$x` now has π, instead of `pi` * Loop for the second time + Run the function `$x()`. Since `$x` has π, it will run the function `3.14159...()`. + π isn't a string, killing the program at this point with a `Fatal Error`. --- Thanks to [@Titus](https://codegolf.stackexchange.com/users/55735/titus) for finding the `pi()` function, saving me **1** byte! [Answer] ## C, 21 bytes ``` i;f(){for(;1/!i++;);} ``` Here `i` is guaranteed to start off as `0`. It can be confirmed that this runs once like so: ``` i;f(){for(;1/!i++;)puts("hi");} main(){f();} ``` Which, on my machine, results in: ``` llama@llama:...code/c/ppcg104323loop$ ./a.out hi zsh: floating point exception (core dumped) ./a.out ``` The shortest recursive solution I can find is **22 bytes**: ``` f(i){f(i-puts(""-i));} ``` `gcc` only does tail call elimination at `-O2` or higher, at which point we need to call a function like `puts` to prevent the entire thing from being optimized away. Confirmation that this works: ``` llama@llama:...code/c/ppcg104323loop$ cat loop.c main(){f();} f(i){f(i-puts(""-i));} llama@llama:...code/c/ppcg104323loop$ gcc -O2 -S loop.c 2>/dev/null llama@llama:...code/c/ppcg104323loop$ grep call loop.s call puts call f ``` The following is a full program, which assumes that it is called with no command line arguments, at **22 bytes**: ``` main(i){for(;1/i--;);} ``` which is equivalent to the function of the same length: ``` f(i){for(i=1;1/i--;);} ``` [Answer] ## R, 22 25 22 20 18 bytes Edit: Thanks to @Mego for pointing out that R does not support tail call optimization. Edit4: Found an even shorter solution which simple yet quite intricate. ``` repeat(ls(T<-T-1)) ``` The answer uses the builtin boolean truthy variable, `T` which is decremented indefinitely in the repeating loop. The function `ls()` is called each iteration which lists all objects in the current environment. However, the first argument `name` specifies from which environment from which to list objects. From the R-documentation we find that: > > The name argument can specify the environment from which object names are taken in one of several forms: as an integer (the position in the `search` list); as the character string name of an element in the search list; or as an explicit `environment` (including using `sys.frame` to access the currently active function calls). > > > This principally means that in the first iteration we run `ls(-1)` which would return `character(0)` (standard when trying to access the non-existent `everything-except-the-first` element of any character type object). During the second iteration, `T` is decremented by two and we subsequently call `ls(-3)` which in turn returns the error: ``` Error in as.environment(pos) : invalid 'pos' argument ``` This is because we try to list `everything-except-the-third` element but the local environment only contains the variable `T` at this point (as such, `ls()` would return a list of length `1` at this iteration) and an error is returned. [Answer] # FALSE, 8 bytes I really like this language. ``` 1[$][.]# ``` This pushes a `1`, then `[$][.]#` loops while `$` is true (duplicate top of stack) and (`.`) outputs it. [This interpreter](http://morphett.info/false/false.html) crashes after the single `1` is printed (evidence of the loop running at least once.) It seems to be a bug in this interpreter. The following 9-byte program should work in all compliant interpreters: ``` 1[$][..]# ``` [Answer] # QBasic, 17 bytes This code is very weird. ``` DO i=11+a(i) LOOP ``` ### How it works In QBasic, variables are preinitialized. A regular variable without any type suffix, like `i` here, is preinitialized to zero. Except if you try to subscript into that variable like an array... in which case, it's an array of 11 zeros.\* On the first time through the loop, therefore, `i` is `0` and `a` is an array. `a(i)` gives the zeroth element of the array (which is `0`). All well and good. We set `i` to `11` and loop. But now `11` is not a valid index for the array `a`, and the program halts with `Subscript out of range`. A 19-byte version that better shows what's going on: ``` DO ?a(i) i=i+1 LOOP ``` This will print `0` eleven times before erroring. --- *\* Conceptually, it's a 10-element array. Most things in QBasic are 1-indexed, but arrays aren't, possibly for implementation reasons. To make things work as expected for programmers, QBasic throws in an extra entry so you can use indices 1 to 10. Index 0, however, is still perfectly accessible. Go figure.* [Answer] # **MATLAB, 18 bytes** This can be run as a script: ``` for j=1:2;j(j);end ``` The first iteration is fine, since `j(1)` is just `1`. The second iteration crashes with an array out of bounds error, as `j(2)` exceeds the dimensions of `j`, which is a 1x1 array. This also can be run as a script, but it only works the first time you run it. Still, it's a hilarious enough abuse of MATLAB's predefined constants that I thought I'd include it. It's also 18 bytes. ``` while i/i;i={};end ``` When run in a workspace that the variable `i` hasn't been defined in yet, this assumes `i` is the imaginary unit, so `i/i = 1`. In the first loop, the assignment `i={}` creates an empty cell array called `i`. On the second iteration, the loop exits with "Undefined operator '/' for input arguments of type 'cell'." [Answer] # [Perl 6](http://perl6.org/), 13 bytes ``` loop {5[$++]} ``` Indexes an integer literal in an infinite loop. Relies on fact that on scalar values, the array indexing syntax can be used with index `0` (returning the value itself), but throws an `Index out of range` error for any other index. [Answer] ## [CJam](https://sourceforge.net/p/cjam), 4 bytes ``` 1{}g ``` [Try it online!](https://tio.run/nexus/cjam#@29YXZv@/z8A "CJam – TIO Nexus") The first iteration of the empty `{}g` loop pops the `1`, which tells it to continue. The second iteration tries to pop another conditional, but the stack is empty, so the program crashes. [Answer] ## Haskell, 15 bytes ``` f(a:b)=f b f"a" ``` `f"a"` runs recursively through the string "a" by dropping the first char and eventually fails at its end with a `Non-exhaustive patterns in function f` exception, because `f` is only defined for non-empty strings. [Answer] # Pyth, 3 bytes ``` W1w ``` [Try it online.](https://pyth.herokuapp.com/?code=W1w&debug=1) `W1` is just `while 1:` in Python. The loop body prints a line read from STDIN, which crashes for the second iteration when the code is run with empty input. If loops using `#` (loop-until-error) are banned (I assume so), I think this is the shortest it can get. [Answer] # C#, ~~71~~ 38 bytes Since you provided an example in C# here another version golfed And thanks to pinkfloydx33 ``` void c(){checked{for(uint i=1;;i--);}} ``` Shorter than `Parse.ToString()` and even than `Parse($"{c--}")` I mentally dumped `checked` for it being too long of a keyword. Tough it certainly is shorter than `Parse(c.ToString())` # Original answer ``` class p{static void Main(){for(int c=0;;c--)uint.Parse(c.ToString());}} ``` This will start `c=0` then decrement it, when `c=-1` the `uint.Parse` will cause an: ``` Unhandled Exception: System.OverflowException: Value was either too large or too small for a UInt32. ``` Ungolfed version and verifying that loop runs at least once ``` class p { static void Main() { for(int c=0;;c--) { System.Console.Write(c); uint.Parse(c.ToString()); } } } ``` [Answer] # CJam, 4 bytes ``` P`:~ ``` `P`` generates the string `3.141592653589793`. `:~` evaluates each character. `3` is valid code in CJam which simply returns 3. In the next iteration, `.` causes an error because it requires a digit or an operator following it. [Answer] # JavaScript, 9 bytes ``` for(;;i); ``` This runs once, then throws `ReferenceError: i is not defined` which stops the loop. ``` // With a console.log(1) to see that it runs once. for(;;i)console.log(1); ``` --- Taking the following as an example, is the `<increment>` the end of the first cycle or the beginning of the second cycle ? ``` 0:for(<init>;<test>;<increment>) 1:{ 2: <statement>; 3:} ``` ### 1/ I see it After going from lines 0 to line 3 then going **back** to line 0, it feels like a full cycle has been completed. That would make the `<increment>` the beginning of the second cycle. - First cycle : `<init>` -> `<test>` -> `<statement>` - Second cycle : `<increment>` -> `<test>` -> `<statement>` ### 2/ `While` equivalent ``` 0:<init>; 1:while(<test>) 2:{ 3: <statement>; 4: <increment>; 5:} ``` In this equivalent `while` the `<increment>` is the end of the first cycle and it feels like it's the same with the `for`. That would make the `<increment>` the end of the first cycle. - First cycle : `<test>` -> `<statement>` -> `<increment>` - Second cycle : `<test>` -> `<statement>` -> `<increment>` ### 3/ A statement is encountered twice A full cycle is completed when a statement is encountered twice. The first statement encountered twice is `<test>`. That would make the `<increment>` the end of the first cycle. - First cycle : `<test>` -> `<statement>` -> `<increment>` - Second cycle : `<test>` -> `<statement>` -> `<increment>` ### 4/ It's a setup The `<init>` is just setting up whatever is needed for the first cycle. The `<increment>` is just setting up whatever is needed for the second cycle. That would make the `<increment>` the beginning of the second cycle. - First cycle : `<init as a setup>` -> `<test>` -> `<statement>` - Second cycle : `<increment as a setup>` -> `<test>` -> `<statement>` --- [The ECMAScript® 2016 Language Specification](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-for-statement-runtime-semantics-labelledevaluation) Runtime of `for(<init>;<test>;<increment>)<statement>;` > > Let varDcl be the result of evaluating `<init>`. > > ReturnIfAbrupt(varDcl). > > Return ? ForBodyEvaluation(`<test>`, `<increment>`, `<statement>`, « », labelSet). > > > There are three forms, so I took the shortest one here, there's no difference: - Whatever the `<init>` it isn't part of the first iteration. - What's relevant is in ForBodyEvaluation. [Details of ForBodyEvaluation(`<test>`, `<increment>`, `<statement>`, « », labelSet)](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-forbodyevaluation) > > 0 Let V be undefined. > > 1 Perform ? CreatePerIterationEnvironment(perIterationBindings). > > 2 Repeat > > 3  If is not [empty], then > > 4   Let testRef be the result of evaluating `<test>`. > > 5   Let testValue be ? GetValue(testRef). > > 6   If ToBoolean(testValue) is false, return NormalCompletion(V). > > 7  Let result be the result of evaluating `<statement>`. > > 8  If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)). > > 9  If result.[[Value]] is not empty, let V be result.[[Value]]. > > 10  Perform ? CreatePerIterationEnvironment(perIterationBindings). > > 11  If is not [empty], then > > 12   Let incRef be the result of evaluating `<increment>`. > > 13   Perform ? GetValue(incRef). > > > ### 6/ I see it A full cycle a full run of the repeat part. That would make the `<increment>` the end of the first cycle. - First cycle : `<test>` -> `<statement>` -> `<increment>` / In other words from line 3 to line 13 - Second cycle : `<test>` -> `<statement>` -> `<increment>` / In other words from line 3 to line 13 ### 7/ A cycle is an iteration A cycle begin with `CreatePerIterationEnvironment`. So when `CreatePerIterationEnvironment` is encountered a new cycle begins, thus ending the previous one. That would make the `<increment>` the beginning of the second cycle. - First cycle : `<test>` -> `<statement>` / In other words from line 1 to line 9 - Second cycle : `<increment>` -> `<test>` -> `<statement>` / In other words from line 10 looping until line 9 --- Is the `<increment>` the end of the first cycle or the beginning of the second cycle? > > The right explanation is either 6 or 7. > > > [Answer] ### x86 assembly (AT&T syntax), 40 bytes ``` f: mov $1,%eax A: div %eax dec %eax je A ``` Declares a function f which divides 1 by 1 on its first iteration then attempts to divide 0 by 0 and errors. [Answer] ## Ruby, 14 Bytes ``` loop{$./=~$.} ``` Exits due to `ZeroDivisionError: divided by 0` `$. The current input line number of the last file that was read` [Ruby Docs](http://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/variable.html#colon) [Answer] ## [><>](https://esolangs.org/wiki/Fish), 3 bytes ``` !]! ``` [Try it here!](https://fishlanguage.com/playground/PPsETZDu8a5nMwLic) ### Explanation ``` ! skip next instruction ] close stack (crash) ! skip next instruction (jumping to close stack) ``` [Answer] # Batch, ~~22~~ 20 bytes ``` :a set i=%i%1 goto a ``` **Explanation** This is an infinite loop that appends a `1` onto an initially empty string. Eventually this will pass the maximum string length of 8192 and crash. On my machine, this takes about 30 seconds. [Answer] # [INTERCAL](http://esolangs.org/wiki/INTERCAL), 12 bytes ``` (1)DO(1)NEXT ``` [Try it online!](https://tio.run/nexus/intercal#@69hqOniDyT8XCNC/v8HAA "INTERCAL – TIO Nexus") `NEXT` is INTERCAL-72's main control flow command. (Later revisions introduced `COME FROM`, which became more famous, but it wasn't in the original version of the language; and all finished INTERCAL implementations I'm aware of support `NEXT` for backwards compatibility, with all but one enabling support for it by default. So I don't feel the need to name INTERCAL-72 specifically in the title.) When using `NEXT` to form a loop, you're supposed to use `RESUME` or `FORGET` in order to free up the space that it uses to remember where the program has been; `RESUME` retroactively makes the `NEXT` into something akin to a function call (although you can return from functions other than the one you're in) whereas `FORGET` makes it into something more similar to a GOTO statement. If you don't do either (and this program doesn't), the program will crash after 80 iterations (this behaviour is actually specified in the INTERCAL specification). It's somewhat ambiguous whether this counts as unbounded recursion (disallowed in the question); you can certainly use this sort of `NEXT` to implement a function call, in which case it would effectively be a recursive function, but there's not enough information here to determine whether we're doing a function call or not. At least, I'm posting this anyway because it doesn't unambiguously violate the rules, and an INTERCAL implementation that optimized out the "tail call" would not only violate the specification, but also cause most existing programs to break, because returning from the "wrong function" is the main way to do the equivalent of an IF statement. Here's the resulting error message, as generated by C-INTERCAL: ``` ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON ON THE WAY TO 1 CORRECT SOURCE AND RESUBNIT ``` (Note that the second line is indented with a tab, and the third with eight spaces. This looks correct in a terminal, or in pretty much any program that has tab stops at multiples of 8. However, Markdown has tab stops at multiples of four, violating the assumptions that most older programs make about tabs, so the error message is a little malformatted here.) [Answer] # Rust, 23 bytes ``` ||for i in 0..{[()][i]} ``` [Try it online!](https://tio.run/##FYwxDoAgEAT7e8WWd4XGWg0lnyAWFhApxAQxFsjbEarNJDsTnztVF3DuPrAgE5Dsnbh@n7siPHzANI7ZsGzGb6UCslAhak4/rlqxm6GF3sNG23TdqKcGBRbqQde21B8 "Rust – Try It Online") Similar to [TehPers's answer](https://codegolf.stackexchange.com/a/208913/97519), but using a unit type array instead of a string gets rid of the `&`, `..` and `;` [Answer] ## Python 3, 29 bytes ``` i=1 def x(n):del i;x(i) x(i) ``` Really simple. On the second call to x, i isn't there, and Python complains about it. [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 3 bytes ``` #(/ ``` [Try it online!](https://tio.run/nexus/labyrinth#@6@sof//PwA "Labyrinth – TIO Nexus") Like most 2D languages, Labyrinth doesn't have any explicit looping constructs. Instead, any code that is laid out such that it is executed multiple times in a row is a loop in these languages. For the case of Labyrinth, a simple linear program acts as a loop, because the instruction pointer will bounce back and forth on it. If the program is `abc` (for some commands `a`, `b` and `c`), then the actual execution will be `abcbabcbabcb...` so it runs `abcb` in an infinite loop. As for why this particular program crashes on the second iteration of this loop, here is what the individual commands do. Note that Labyrinth's stack contains an implicit infinite amount of zeros at the bottom: ``` # Push stack depth. [... 0] ( Decrement. [... -1] / Divide. [... 0] ( Decrement. [... -1] # Push stack depth. [... -1 1] ( Decrement. [... -1 0] / Divide. Crashes with division-by-zero error. ``` [Answer] # Bash, 11 (Borderline non-competing) ``` exec $0 1$@ ``` This script recursively execs itself, appending `1` to the args passed on each iteration. I think this counts as TCO because exec reuses the process space but doesn't eat up stack. It is borderline non-competing because it took about 10 minutes before being killed on my machine - YMMV. ]
[Question] [ In Haskell the list notation: ``` [a,b,c] ``` Is just syntactic sugar for: ``` a:b:c:[] ``` And the string notation: ``` "abc" ``` Is just syntactic sugar for: ``` ['a','b','c'] ``` This means that the string: ``` "abc" ``` Is the same as: ``` 'a':'b':'c':[] ``` # Task Given a string you should output what the de-syntaxed version would look like in Haskell. # Rules * You will receive a string by any valid input method, you should output a string ending with `:[]` with every character from the input surrounded by `'` and separated by `:`. The empty string should output `[]`. * You can assume that you will not receive any characters that require escaping (e.g. `'`, newlines, tabs ...) and that input will be in the printable ascii range * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") you should aim to minimize the byte count of your answer ## Test Cases ``` "" -> [] "a" -> 'a':[] "Hello, World" -> 'H':'e':'l':'l':'o':',':' ':'W':'o':'r':'l':'d':[] ``` [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` (++"[]").((++":").show=<<) ``` [Try it online!](https://tio.run/##y0gszk7NyflfrftfQ1tbKTpWSVNPA8SyAjKKM/LLbW1sNP/r1nLlJmbmKdgqZOaVpBYlJpcoqCjgUZ@YlAwA "Haskell – Try It Online") **Explanation:** In non-pointfree notation and using `concatMap` instead of `=<<`, this becomes ``` f s = concatMap(\c-> show c ++ ":")s ++ "[]" ``` Given a string `s`, we map each char `c` to a string `"'c':"` using the `show` function which returns a string representation of most Haskell types. Those strings are concatenated and a final `[]` is appended. Although not requested by the challenge, this answer even works with proper escaping, because `show` takes care of it: `f "'"` yields `"'\\'':[]"`. [Answer] ## Haskell, ~~33~~ ~~28~~ 26 bytes ``` foldr((.(':':)).shows)"[]" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P802LT8npUhDQ09D3UrdSlNTrzgjv7xYUyk6Vul/bmJmnoKtQko@l4JCQWlJcEmRT56CikKagpIHUHO@EoZwIqaQ0n8A "Haskell – Try It Online") `fold` the given pointfree function from the right into the input string starting with `[]`. The function is: show char as a Haskell char, i.e. surrounded with `'` and concatenate with the result so far after putting a `:` in front of it. Edit: @Ørjan Johansen saved two bytes. Thanks! [Answer] # [Python 3](https://docs.python.org/3/), 32 bytes ``` lambda s:"%r:"*len(s)%(*s,)+"[]" ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYSkm1yEpJKyc1T6NYU1VDq1hHU1spOlbpf3lGZk6qgqEVl0JBUWZeiUaaRmZeQWmJhqam5n@uRC6P1JycfB2F8PyinBQA "Python 3 – Try It Online") [Answer] ## JavaScript ES6, ~~42~~ ~~40~~ 31 bytes ``` s=>s.replace(/./g,"'$&':")+"[]" ``` Replaces each char with `'<char>':`, then adds `[]` to the end [Try it online!](https://vihan.org/p/tio/?l=javascript-node&p=K0ssUki0VSi2tSvWK0otyElMTtXQ19NP11FSV1FTt1LS1FaKjlXi4krOzyvOz0nVy8lP10jUUPJIzcnJ11EIzy/KSVFU0tREl0/EIgYU@g8A) [Answer] # Common Lisp, ~~50~~ 42 bytes ``` (format t"~{'~a':~}[]"(coerce(read)'list)) ``` [Try it online!](https://tio.run/##S87JLC74/18jLb8oN7FEoUSprlq9LlHdqq42OlZJIzk/tSg5VaMoNTFFUx2oskRT8/9/JY/UnJx8HYXw/KKcFCUA) Reduced thanks to the comment of @coredump, by using `read` instead of defining a function. [Answer] # [V](https://github.com/DJMcMayhem/V), 11 bytes ``` Í./'&': A[] ``` [Try it online!](https://tio.run/##K/v//3Cvnr66mroVl2N07P//iUnJKakA "V – Try It Online") Uses a regex to surround every input character with `'':` and then `A`ppends `[]` to the end. [Answer] # C, ~~55~~ ~~54~~ 53 bytes ``` s(char*h){while(*h)printf("'%c':",*h++);puts("[]");} ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~41~~ ~~38~~ 36 bytes -2 bytes thanks to ovs ``` print(*map(repr,input()),[],sep=':') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQys3sUCjKLWgSCczr6C0RENTUyc6Vqc4tcBW3Upd8/9/j9ScnHwdhfD8opwUAA "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15 12 11~~ 10 bytes -3 bytes thanks to carusocomputing -1 byte thanks to Adnan -1 byte thanks to Erik the Outgolfer's genius idea ``` ʒ"'ÿ':"?}, ``` [Try it online!](https://tio.run/##MzBNTDJM/V9W@f/UJCX1w/vVrZTsa3X@/49WV9dRTwRij9ScnHwdhfD8opwU9VgA "05AB1E – Try It Online") ``` ʒ # Filter out every character that the following code doesn't return 1 for "'ÿ':"? # Print the string 'ÿ': with ÿ replaced by this character } # End for , # No character returned 1 so an empty array is left on the stack. Print that ``` [Answer] # R, 51 bytes ``` f<-function(x)(paste0(gsub("(.)","'\\1':",x),'[]')) ``` [Answer] # Pyth, ~~14~~ ~~10~~ 8 bytes ``` j\:a`MQY ``` [Try this!](https://pyth.herokuapp.com/?code=j%5C%3Aa%60MQY&input=%22%22&test_suite=1&test_suite_input=%22%22%0A%22a%22%0A%22abcd%22&debug=0) *-2 bytes thanks to @isaacg* Finally, pyth is good at something. ### explanation ``` j\:a`MQY `MQ # map the representation over the input string: ["'a'","'b'",...] a Y # append the empty list j\: # join on : ``` [Answer] # Retina, 12 * 3 bytes saved thanks to @FryAmTheEggman ``` . '$&': $ [] ``` 2 stages: * for each remaining character put `'` `':` around it * add `[]` to the end [Try it online](https://tio.run/##K0otycxL/K@q4Z7wX49LXUVN3YpLhSs69v9/rkSuxKRkLo/UnJx8HYXw/KKcFAA@UU5KUoA). [Answer] # [Perl 6](http://perl6.org/), 19 bytes ``` {S:g|.|'$/':|~'[]'} ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~48~~ ~~46~~ ~~44~~ 37 bytes *-2 bytes thanks to Rod. -7 bytes thanks to Wheat Wizard.* ``` lambda s:':'.join(map(repr,s)+['[]']) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYSt1KXS8rPzNPIzexQKMotaBIp1hTO1o9OlY9VvN/QVFmXolCmoa6uiYXnJ2IzPFIzcnJ11EIzy/KSVHX/A8A "Python 2 – Try It Online") [Answer] # [Befunge](https://github.com/catseye/Befunge-93), ~~29~~ 27 bytes ``` <,,,,\_v#`0:~"'':" @,,"[]"< ``` [Try it online!](https://tio.run/##S0pNK81LT/3/30YHCGLiy5QTDKzqlNTVrZS4HHR0lKJjlWz@//dIzcnJVwjPL8pJUQQA "Befunge – Try It Online") [Answer] # JavaScript (ES6), 36 bytes ``` s=>s?`'${[...s].join`':'`}':[]`:"[]" ``` --- ## Try it ``` f= s=>s?`'${[...s].join`':'`}':[]`:"[]" oninput=_=>o.innerText=f(i.value);o.innerText=f(i.value="abc") ``` ``` <input id=i><pre id=o> ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11 10~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Christian (remove concatenation `;` and utilise implicit printing instead) +0 bytes (fixed for edge case of an empty string - previously the full program: `ŒṘ€j”:“:[]`) -2 thanks to Erik the Outgolfer (use `p` in place of `;€` since `”:` is effectively length 1; use `Ø[` since it has become shorthand for `⁾[]`) ``` ŒṘ€p”:Ø[ ``` **[Try it online!](https://tio.run/##y0rNyan8///opIc7ZzxqWlPwqGGu1eEZ0f///1fyAErl6yiE5xflpCgqAQA "Jelly – Try It Online")** A full program printing the result (as a link it returns a list of lists of characters). ...but is there a way to save using STDIN? ### How? ``` ŒṘ€p”:Ø[ - Main link: list of characters, s e.g. "Hey" ŒṘ€ - Python representation for €ach [["'",'H',"'"],["'",'e',"'"],["'",'y',"'"]] ”: - literal character = ':' p - Cartesian product [["'",'H',"'",':'],["'",'e',"'",':'],["'",'y',"'",':']] - implicit print (no newline): 'H':'e':'y': Ø[ - literal list of characters ['[',']'] - implicit print (no newline): [] ``` [Answer] # [PHP](https://php.net/), 41 bytes ``` <?=preg_filter("#.#","'$0':",$argn)."[]"; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwJVaVJRfFF@UWpBfVJKZl65R5xrv5x/i6eyqac2lkliUnmer5JGak5OvoxCeX5STomTNZW8H1GpbUJSaHp@WmVOSWqShpKynrKSjpK5ioG6lpAPWpamnFB2rZP3//9e8fN3kxOSMVAA "PHP – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 22 bytes 19 bytes of code + `-p` flag. ``` s/./'$&':/g;$\="[]" ``` Or, for the same bytecount, `s/./'$&':/g;s/$/[]/`. Quite straight forward: `s/./'$&':/g` surrounds each characters with quotes and add a `:` after. `$\` is implicitly printed after each print, so setting it to `[]` outputs the final `[]`. [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@F@vr6aurqKlb6adbq8TYKkXHKv3/75Gak5OvoxCeX5STAgA "Perl 5 – Try It Online") [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~86~~ ~~83~~ 76 bytes *-3 bytes thanks to @KevinCruijssen* *-7 bytes thanks to @FlorianSchaetz* ``` s->{String b="";for(char c:s.toCharArray()){b+="'"+c+"':";};return b+"[]";}; ``` [Try it online!](https://tio.run/##hY0xb4MwEIXn8CtOXmKLxD8glEhVpapLpwwdogyHgcTUsS37iIQQv506hT1vee/efbrr8IF75xvb1b@z7yujFSiDMcI3agtjBklrHwkp2cPpGu5py08UtL2eL4DhGkWCN106J3vSRra9VaSdlZ9reFvoHSx@hBZKmOP@OC4FVCVjResCVzcMoA5RkvtI8T0EHLgQY5WXbMtylbPtgRVTERrqg4UqZ@fLc55hVZFtTkOk5i5dT9Kn62QsbyV6bwbOmBAvCHyNfDXGuB38uGDqf/r5eMqm@Q8 "Java (OpenJDK 8) – Try It Online") [Answer] # brainfuck, 68 bytes ``` +[-->+[<]>-]>>,[<.>.<.>>-[>+<+++++++++]>+.[-]<<,]-[+[+<]>>+]<+++.++. ``` [Try it online!](https://tio.run/##NYo7CoBADESvovVscoIwtTewCCn8gri4IHj@dS0c3qvezPd0XPuznLXCRQi3oASZ3JTapDhh@BeEuoRZCnE42p2Ir2uj1mHLuaRuLHde@xc "brainfuck – Try It Online") [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~135~~, 131 bytes ``` {({}<>)<>}(((((((()()()()()){})){}{}())){}{})[()()])<>{<>(((((((()()()){}()){}){}()){})[(((()()()){})){}{}()])<>)({}<({}<>)>)<>}<> ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjutbGTtPGrlYDCjRhULO6FoSra4FMMK0ZDRKOBSqutrFDUa4JVgRUAaOjkaVgpoB0aoLsg9gJttXG7v9/J4R7dJMB "Brain-Flak – Try It Online") `+1` byte for the `-c` flag. Thanks to WheatWizard for removing very obvious NOOPs that I had for no reason XD. [Answer] # [Standard ML](http://www.mlton.org/), ~~52~~ 50 bytes Saved 2 bytes thanks to @Laikoni! ``` fn s=>String.translate(fn c=>"'"^str c^"':")s^"[]" ``` [Try it online!](https://tio.run/##DcpBCoMwEAXQq3xnkwjWA1TiunuXpYGgiQhjUjJDPX7q9vHk5MfJWnL7BUaCQ0sZ4uZF65H3UWvIwkGjvXl1MxnyohWrJ/OkXjy9P9QmfO@tsAn0isxlwFUqbx31U/sD "Standard ML (MLton) – Try It Online") `String.translate` is an unfortunately long name, but was 5 bytes shorter than using `concat`, `map`, and `explode`. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~31~~ 29 bytes ``` uo@[)o'U);!A?ro;o;o;os:'/u:'' ``` `A` can also be substituted for `i`; ~~trying to figure out if there's a good way to squeeze another byte or two out of this.~~ -2 bytes thanks to MickyT! Also [outgolfed by MickyT](https://codegolf.stackexchange.com/a/126778/67312)! Fits on a 3x3x3 cube: ``` u o @ [ ) o ' U ) ; ! A ? r o ; o ; o ; o s : ' / u : ' ' . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Watch it online!](http://ethproductions.github.io/cubix/?code=ICAgICAgdSBvIEAKICAgICAgWyApIG8KICAgICAgJyBVICkKOyAhIEEgPyByIG8gOyBvIDsgbyA7IG8KcyA6ICcgLyB1IDogJyAnIC4gLiAuIC4KLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=YWJj&speed=10) [Try it online!](https://tio.run/##Sy5Nyqz4/7803yFaM189VNNa0dG@KN8aDIut1PVLrdTV//9PTEoGAA "Cubix – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 47 bytes ``` lambda a:`list(a)+[[]]`.replace(', ',':')[1:-1] ``` [Try it online!](https://tio.run/##DcNBCoQgFADQfaf4uFEZJ3CWwuznBi1M6DcZCX9UzIg5vfXg5X/dUny19T02wt@8IKCZKOxVoHxY69zUF58Jv15wBVxxw6XV5qldO7dAHrTpIJcQK6wixHxUIWVjrGN4/3iipGBIhRZ2AQ "Python 2 – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~21~~ 19 bytes ``` '[]',⍨'.'⎕R'''&'':' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR2wT16Fh1nUe9K9T11B/1TQ1SV1dXU1e3UgdKKqircwGJRDDpkZqTk6@jEJ5flJOiDgA "APL (Dyalog Unicode) – Try It Online") `'[]',⍨` the brackets appended to `'.'` every character `⎕R` PCRE **R**eplaced with `'''&'':'` a quote, the match, a quote and a colon [Answer] # [sed](https://www.gnu.org/software/sed/), ~~19~~ 18 bytes -1 byte thanks to [Jordan](https://codegolf.stackexchange.com/users/11261/jordan) ``` s/./'&':/g;s/$/[]/ ``` [Try it online!](https://tio.run/##K05N@f@/WF9PX11N3Uo/3bpYX0U/Olb///@M1JycfAA "sed – Try It Online") [Answer] # PHP, 39 bytes ``` <?while(~$c=$argn[$i++])echo"'$c':"?>[] ``` Run as pipe with `-F`. [Answer] # [Convex](https://github.com/GamrCorps/Convex), 10 bytes ``` {`':`}%"[] ``` [Try it online!](https://tio.run/##S87PK0ut@P@/OkHdKqFWVSk69v9/j9ScnHwdhfD8opwUAA "Convex – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 27 bytes ``` uosW?U.iv":'"^soso;os@o[]'/ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/780vzjcPlQvs0zJSl0prji/ON86v9ghPzpWXf///5LU4hKukozMYgA "Cubix – Try It Online") ``` u o s W ? U . i v " : ' " ^ s o s o ; o s @ o [ ] ' / . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgdSBvIHMKICAgICAgVyA/IFUKICAgICAgLiBpIHYKIiA6ICcgIiBeIHMgbyBzIG8gOyBvIHMKQCBvIFsgXSAnIC8gLiAuIC4gLiAuIC4KLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=dGVzdAoxLi4yLi4z&speed=15) A slightly different variation from Guiseppe's [answer](https://codegolf.stackexchange.com/a/126620/31347). This puts the colon and quote on the stack. Then it loops through the input, swapping and outputting the stack. Only the input is scrapped and the colon and quote are retained. Once the end of the input is reached the IP wonders around the cube a bit, adding and outputting the brackets. There are a couple of redundant commands in the mix. ]
[Question] [ Your challenge is to find the smoothest number over a given range. In other words, find the number whose greatest prime factor is the smallest. A [smooth number](http://en.wikipedia.org/wiki/Smooth_number) is one whose largest prime factor is small. Numbers of this type are useful for the fast Fourier transform algorithm, cryptanalysis, and other applications. For instance, over the range `5, 6, 7, 8, 9, 10`, 8 is the smoothest number, because 8's greatest prime factor is 2, whereas all of the other numbers have a prime factor of 3 or greater. **Input:** The input will be two positive integers, which define a range. The minimum allowable integer in the range is 2. You may choose whether the range is inclusive, exclusive, semi-exclusive, etc, as long as an arbitrary range can be specified within the bounds of your language. You may take the numbers via function input, stdin, command line argument, or any equivalent method for your language. No encoding extra information in the input. **Output:** Return, print or equivalent one or more integers in the input range which are maximally smooth (minimal greatest factor). Returning multiple results is optional, but if you choose to do so the results must be clearly delimited. Native output format is fine for multiple results. Please state in your answer how you are taking input and giving output. **Scoring:** Code golf. Count by characters if written in ASCII, or 8\*bytes/7 if not in ASCII. **Test cases:** Note: These are Python-style ranges, including the low end but not the high end. Change as appropriate to your program. Only one result is necessary. ``` smooth_range(5,11) 8 smooth_range(9,16) 9, 12 smooth_range(9,17) 16 smooth_range(157, 249) 162, 192, 216, 243 smooth_range(2001, 2014) 2002 ``` [Answer] # CJam - 13 ``` q~,>{mfW=}$0= ``` Try it at <http://cjam.aditsu.net/> Example input: `2001 2014` Example output: `2002` **Explanation:** `q~` reads and evaluates the input, pushing the 2 numbers on the stack (say min and max) `,` makes an array [0 1 ... max-1] `>` slices the array starting at min, resulting in [min ... max-1] `{‚Ķ}$` sorts the array using the block to calculate the sorting key `mf` gets an array with all the prime factors of a number, in order `W=` gets the last element of the array (W=-1), thus obtaining the largest prime factor to be used as a sorting key `0=` gets the first element of the (sorted) array [Answer] ## Regex (~~.NET~~ PCRE flavour), ~~183~~ 129 bytes Don't try this at home! This is not really a contender for the win. But Eric Tressler suggested solving this problem with nothing but a regex, and I couldn't resist giving it a go. This ~~might be~~ is possible in PCRE as well (and even shorter, see below), but I chose .NET because my solution needs arbitrary-length lookbehinds. Here we go: ``` (?<=^(1+),.*)(?=\1)(?=((11+)(?=.*(?=\3$)(?!(11+?)\4+$))(?=\3+$)|(?!(11+)\5+$)1+))(?!.+(?=\1)(?:(?!\2)|(?=((11+)(?=.*(?=\7$)(?!(11+?)\8+$))(?=\7+$)|(?!(11+)\9+$)1+)).*(?=\2$)(?=\6)))1+ ``` The input is encoded as an inclusive comma-separated range, where both numbers are given in unary notation using `1`s. The match will be the trailing `S` 1s where `S` is the smoothest number in the range. Ties are broken in favour of the smallest number. So the second example from the question would be the following string (match underlined) ``` 111111111,1111111111111111 ========= ``` It is based on the (by now rather well-known) [prime-checking regex](https://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex), variations of which are embedded in there a whopping 6 times. Here is a version using free-spacing and comments for those who want to know what's going on. ``` # Note that the beginning of the match we're looking for is somewhere # in the second part of the input. (?<=^(1+),.*) # Pick up the minimum range MIN in group 1 (?=\1) # Make sure there are at least MIN 1s ahead # Now there will be N 1s ahead of the cursor # where MIN <= N <= MAX. (?=( # Find the largest prime factor of this number # store it in group 2. (11+) # Capture a potential prime factor P in group 3 (?= # Check that it's prime .*(?=\3$) # Move to a position where there are exactly # P 1s ahead (?!(11+?)\4+$) # Check that the remaining 1s are not composite ) (?=\3+$) # Now check that P is a divisor of N. | # This does not work for prime N, so we need a # separate check (?!(11+)\5+$) # Make sure that N is prime. 1+ # Match N )) (?! # Now we need to make sure that here is not # another (smaller) number M with a smaller # largest prime factor .+ # Backtrack through all remaining positions (?=\1) # Make sure there are still MIN 1s ahead (?: (?!\2) # If M is itself less than P we fail # unconditionally. | # Else we compare the largest prime factors. (?=( # This is the same as above, but it puts the # prime factor Q in group 6. (11+) (?= .*(?=\7$) (?!(11+?)\8+$) ) (?=\7+$) | (?!(11+)\9+$) 1+ )) .*(?=\2$) # Move to a position where there are exactly # P 1s ahead (?=\6) # Try to still match Q (which means that Q is # less than P) ) ) 1+ # Grab all digits for the match ``` You can test it online [over here](http://regexhero.net/tester/?id=c01109dc-6236-4f04-a8dd-02d6a1f9b0b4). Don't try too large inputs though, I make no guarantees about the performance of this monster. **Edit:** I ended up porting this to PCRE (which only requires two steps), and shortening the regex by almost a third. Here is the new version: ``` ^(1+),.*?\K(?=\1)(?=((11+)(?=.*(?=\3$)(?!(11+?)\4+$))(?=\3+$)|(?!(11+)\5+$)1+))(?!.+(?=\1)(?:(?!\2)|(?=((?2))).*(?=\2$)(?=\6)))1+ ``` This is essentially the same, with two changes: * PCRE does not support arbitrary-length lookbehind (which I used to get the `MIN` into group `1`). However, `PCRE` does support `\K` which resets the beginning of the match to the current cursor position. Hence `(?<=^(1+),.*)` becomes `^(1+),.*?\K`, which already saves two bytes. * The real savings come from PCRE's recursion feature. I'm not actually using recursion, but you can use `(?n)` to match group `n` again, similar to a subroutine call. Since the original regex contained the code for finding a number's largest prime factor twice, I was able to replace the whole bulk of the second one with a simple `(?2)`. [Answer] # Regex (Perl / PCRE), ~~66~~ 65 (64üêå) bytes Inspired by seeing that both [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) and [jaytea](https://codegolf.stackexchange.com/users/75057/jaytea), two regex geniuses, wrote regex solutions to this code golf, I wrote my own from scratch. The famous prime-checking regex does not appear anywhere in my solution. Do not read this if you don't want some unary regex magic spoiled for you. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex: 1. Match prime numbers (if you aren't already familiar with doing this in regex) 2. Match powers of 2 (if you haven't already done so). Or just work your way through [Regex Golf](https://alf.nu/RegexGolf), which includes Prime and Powers. Make sure to do both the Classic and Teukon problem sets. 3. > > Find the shortest way to match powers of N where N is some constant (i.e. specified in the regex, not the input) which can be composite (but is not required to be). For example, match powers of 6. > > > 4. > > Find a way of matching Nth powers, where N is some constant >=2. For example, match perfect squares. (For a warmup, match [prime powers](https://oeis.org/A000961).) > > > 5. > > Match correct multiplication statements. Match triangular numbers. > > > 6. > > Match Fibonacci numbers (if you're as crazy as I am), or if you want to stick to something shorter, match correct statements of exponentiation (for a warmup, return as a match the logarithm in base 2 of a power of 2 ‚Äì bonus, do the same for any number, rounding it however you like), or factorial numbers (for a warmup, match [primorial numbers](https://oeis.org/A002110)). > > > 7. > > Match abundant numbers (if you're as crazy as I am) > > > 8. > > Calculate an irrational number to requested precision (e.g. divide the input by the square root of 2, returning the rounded result as a match) > > > (The [regex engine I wrote](https://github.com/Davidebyzero/RegexMathEngine) may be of help, as it is very fast at unary math regexes and includes a unary numerical mode which can test ranges of natural numbers (but also has a strings mode which can evaluate non-unary regexes, or unary with delimiters). By default it is ECMAScript compatible, but has optional extensions (which can selectively add subsets of PCRE, or even molecular lookahead, something that no other regex engine has).) Otherwise, read on, and also read [this GitHub Gist](https://gist.github.com/Davidebyzero/9090628) (warning, many spoilers) which chronicles the journey of pushing ECMAScript regex to tackle natural number functions of increasing difficulty (starting with teukon's set of puzzles, not all of them mathematical, which sparked this journey). As with the other regex solutions to this problem, the input is given as two numbers in bijective unary, separated by a comma, representing an inclusive range. Only one number is returned. The regex could be modified to return all of the numbers that share the same smallest largest prime factor, as separate matches, but that would require variable-length lookbehind and either putting `\K` in a lookahead or returning the result as a capture instead of a match. The technique used here of repeated implicit division by smallest prime factor is identical to that used in the [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/a/21951/17216) answer I posted a while back. With no further ado: ``` ((.+).*),(?!.*(?=\1)((?=(..+)(\4+$))\5)*(?!\2)).*(?=\1)\K(?3)*\2$ ``` [Try it online!](https://tio.run/##RZDfasIwFMbv@xSxBHOOpjWpdn@MtZU5GIy5G@8WKduoIHTqWgcO6S73AHvEvUiXRmU3@c73nV8@QrZZkYf12yehhSKHfPP6nBPaU8ZGo@lkPhlXznJTEKBlJNRorJAcHEKSPCq3@WoHjDNefryUuwJoyj3JJWbvrl678X8qTI5DmqIyN7fFar0DUxc31NB10U/yJ7HwTVMzSTOR3@8fwiy@WgIA27O9hdBSZy8XiNFXjxY9PNjaxDPMKLJou510jYyticGKZ4FTiV17x9w872QboMryMjs2stkjeZjMb@5aTFXmC6Sq0vR2Nk3TGsDvot9BDnHL70AcaYlgBHyTgx50KaIO0WxaOkA8I/oe4j52dEDrOuRSONdchs1x4cjwkgeDKycQQvJAyP4f "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XVBfa9swEH/3p3CEIXepolhO3Db1jBnrxsLaDta@VUG4rhKb2Y6QNSiUve4D7CPui2TnQF/6cjp@/@50trbHD4WtbRi5nC2YsM7stTO2LSsD04WYFVrXZet1dehs0xqnQGGmfiyGKZ9O@Y4gvTcj3XvT@wG0/rK5@aw1comCErOg6Rs9GA/MVs6Ip7L66R0V3TZd4xlnq2S9Wp9fJOuUYRbsDg6iIY@zqM13lDzA/cP15g4zAiW@BmHY7CBqHwfvWtNTh3O5zXOmeoZkGX49EUMwj/lcYhYSZl5se3g2QLM46TPKMFV9oDHFaLtiDAUlxltBirGT1IX//vwNmYDTQbrSVzVEjlP2eB1TepD85MGT6T0ut8ijDou3LbtRecXuvoe3Hx8@fZ3QT3@/OyxgdgQQZyhmyKGYiBkUuZII9IAgHNTqLEJUKRIzUQnim0R9g2KJM5VEx2PKZRysuUzHch7I9IInq8sgiWPJk1gu/wM "PHP ‚Äì Try It Online") - PCRE [Try it on regex101](https://regex101.com/r/BmJzgw/2) And the free-spacing version, with comments: ``` # No ^ anchor needed, because this algorithm always returns a # match for valid input (in which the first number is less than # or equal to the second number), and even in /g mode only one # match can be returned. You can add an anchor to make it reject # invalid ranges. ((.+).*), # \1 = low end of range; \2 = conjectured number that is the # smallest number in the set of the largest prime factor of each # number in the range; note, it is only in subsequent tests that # this is implicitly confined to being prime. # We shall do the rest of our work inside the "high end of range" # number. (?! # Assert that there is no number in the range whose largest prime # factor is smaller than \2. .*(?=\1) # Cycle tail through all numbers in the range, starting with \1. # Subroutine call (?3) - defines one loop iteration, and needs to be called as (?3)* # Finds the largest prime factor of tail, and leaves it in tail. It will both be # evaluated here as-is, and later as a subroutine call. Here, it's followed by an # assertion that tail is less than something; if this fails to match, the regex # engine will try to backtrack, but that will never result in a match because # backtracking will only make tail larger. ( # Repeatedly divide tail by its smallest prime factor, leaving # only the largest prime factor at the end. (?=(..+)(\4+$)) # \5 = tool to make tail = \4 = largest nontrivial factor of # current tail, which is implicitly the result of dividing it # by its smallest prime factor. \5 # tail = \4 )* (?!\2) # matches iff tail < \ 2 ) # At this point, \2 is guaranteed to be less than or equal to the smallest number in the # set containing the largest prime factor of each of the numbers in the inputted range. # The first time the regex engine reaches this point, \2 will be equal to the smallest # number in that set, but if it backtracks, \2 will become smaller. # now, pick a number in the range whose largest prime factor is \2 .*(?=\1) # Cycle tail through all numbers in the range, starting with \1. \K # Set us up to return tail as the match. (?3)* # tail = largest prime factor of tail \2$ # Match iff tail == \2, then return the number whose largest # prime factor is \2 as the match. If this fails to match, the # regex engine will try to backtrack, but that will never result # in a match, because backtracking makes tail a composite number # that is larger than the largest prime factor of the currently # marked return value, which makes it larger than any value \2 # can have. ``` Note that `((.+).*)` can be changed to `((.+)+)`, dropping the size by 1 byte (from 65 to **64 bytes**) with no loss of correct functionality ‚Äì but the regex exponentially explodes in üêå slowness: ``` ((.+)+),(?!.*(?=\1)((?=(..+)(\4+$))\5)*(?!\2)).*(?=\1)\K(?3)*\2$ ``` [Try it online!](https://tio.run/##RZDfSsMwFMbv9xRZCcs5a9o10wou65/hBEGcN7szo6h0UIjbbCtMRr30AXxEX6Sm2YY3@c73nV8@QnZ5qcP27ZPQUpKD3r4@a0JH0thoOp8tZ3HTW29LArSKAjmNJZJDj5BUR9VOFzUwznj18VLVJdCMe4ILzN8dtXGS/zQwOU5ohtLc3JXFpgZTl3TUxHHQT/VTsPJNUzcJM5Hf7x/CLF6sAYDt2d5CaKmzFyvE6GtEyxEebG3qGWYaWXQwSF0jsTUJWPEscCqxa@@Ym@edbAc0ua7yYyNbPJKH2fLmrs9kY75AyCbLbhfzLGsBfBdd5JD0/SEkkRIIRsA3MahLlyKqEM2mr8aIZ0TdQ3KBQzWmbRtyEfSuuQi74@oP "Perl 5 ‚Äì Try It Online") - Perl [Try it online!](https://tio.run/##XVDNSsNAEL73KdIl0Jl23XZrq9QYgviDxT9Qb25ZYtw2wSRdNisI4tUH8BF9kTop9NLL7PD9zezY3G5OE5vbIHQxGzJhnVlpZ2yZZgZ6Q9FPtM7T0utsXdmiNE6Bwkg9Dpse7/X4kiC9Mi1de1P7BrS@mt9eao1coqDEqFPUhW6MB2YzZ8Rrmr17R0WXRVV4xtlkPJvMjo7HsynDqLNcOwibeBSFZbyk5Aaeni/m9xgRKPGrEwTFEsLypfGuNDV1eCAXccxUzZAszccrMQTzET@QGAWEmU9brt8M0CxO@ogyTJavaUzS2k4YQ0GJo4UgRdtJ6oK/n9@ACdgepEp9lkPoOGW31zGpB8m3Htya9nG5QB5WmOy2rFrlCbt/CO7Ons@vu/TT773DAkYbADHAAXJIuqIPSawkAj0gCAY1GYSIaorEdNUYcSdRN5AcYl@Nw81myuWoM@Ny2pajfw "PHP ‚Äì Try It Online") - PCRE # Regex (ECMAScript), 80 (79üêå) bytes The algorithm can be easily ported to ECMAScript by replacing the subroutine call with a copy of the subroutine, and returning the match as capture group `\6` instead of using `\K`. The result is **80 bytes** in length: ``` ((x+)x*),(?!.*(?=\1)((?=(xx+)(\4+$))\5)*(?!\2)).*(?=\1)(((?=(xx+)(\8+$))\9)*\2$) ``` [Try it online!](https://tio.run/##TU/dTsIwFL7fU2yGZOeMObcJCDaVGGOiF2Ki3jEvKnSj2pWlKzoRbn0AH9EXwaoYvDk9/X5Ovu@RPbN6okVl9utKTLku5@qJv240VfzFveHFeVMBLOnJQbABaNrYBBjC0IsCGNIsQbAPNBaHrNNuIWZdtIyXpYg7yU7T/9EMMMjSFm6CgyVGZn5rtFAFYFRLMeHQC/c7iCSfa8hpQkBSzdlUCsUB0aNqISXJaYxvIgcvx8qaDSBx7BcKKqO6ksKAH/o2guSqMDOPpquVqEdsBIxWTNf80lqKcXyP@Ec8/CcSS@BbtTC10bB3qZ6ZFFNXKIsc7yHZEhLJZK6MUAtO1k5JwW/8SPOKMwMM2zZB@x/yYOOUzExmoG3Y3YntVtKfZkPf/Xz/cEfX7tXp3dmF5x//Aj4S26/8rY9/nnHvflsRyXrTDZPYGYRJ93v0nKR7FKadvpPGcRKmcXL4BQ "JavaScript (SpiderMonkey) ‚Äì Try It Online") - **80 byte** version [Try it online!](https://tio.run/##TU9LTsMwEN3nFEmFlJkmhCQ0hWKZCiEkWFAkYEdYmNZJDY4TOS4UClsOwBG5SDGlqN2Mx@8zeu@RPbN2rEVjdttGTLiuavXEX5eaKv7iXvPybN4AvNHjve4SYB5ggCEMvagLQ5onCPaBuYUh7wU7iHmGlvHyFHEj2WgOV5oBdvN0B5fdvTeMTH1jtFAlYNRKMebQD3d7iKSoNRQ0ISCp5mwiheKA6FE1k5IUNMaFKMArsLFmA0gc@4WSyqhtpDDgh76NILkqzdSj6fu7aEdsBIw2TLf8wlrKu/ge8Z942CYSS@CimZnWaOhcqGcmxcQVyiJHHSRrQiIZ18oINePkw6ko@HM/0rzhzADDwCYItpAHG6diZjwFbcNuTqy3iq6aDX33@/PLHV25lye3p@eef/QH@Ehsv@qvPv577vr364pIPpZZmMTOIEyy39F3kuwgTHuHThrHSZjGyf4P "JavaScript (SpiderMonkey) ‚Äì Try It Online") - **79 byte** exponential-slowdown üêå version (amazingly, this can handle all the test cases in 49 seconds) [Answer] # Python 2, 95 ``` i=input() for a in range(*i): s=a;p=2 while~-a:b=a%p<1;p+=1-b;a/=p**b if p<i:i=p;j=s print j ``` Finds the smoothness of the the numbers by trial division until the number is 1. `i` stores the smallest smoothness so far, `j` stores the number that gave that smoothness. Thanks to @xnor for the golfs. [Answer] ## Mathematica, ~~61~~ ~~45~~ 39 characters ``` Range@##~MinimalBy~Last@*FactorInteger& ``` Very straightforward implementation of the spec as an unnamed function. * Get the range (inclusive). * Factor all integers. * Find the minimum, sorted by largest prime factor. [Answer] ## J, ~~22 20~~ 19 chars ``` ({.@/:{:@q:)@(}.i.) ``` E.g. ``` 2001 ({.@/: {:@q:)@(}. i.) 2014 2002 ``` (Functions taking two arguments are infix in J.) [Answer] # Haskell, ~~96~~ ~~94~~ ~~93~~ ~~86~~ 80 characters ``` x%y|x<2=y|mod x y<1=div x y%y|0<1=x%(y+1) a#b=snd$minimum$map(\x->(x%2,x))[a..b] ``` usage via GHCi (a Haskell shell): ``` >5 # 9 8 >9 # 15 9 ``` **EDIT:** now a much simpler algorithm. this solution includes both numbers in the range (so `8 # 9` and `7 # 8` are both 8) explanation: the (%) function takes two parameters, x and y. when y is 2, the function returns the smoothness of x. the algorithm from here is simple - get the combined list of all smoothnesses of numbers in the input with each smoothness storing a reference to it's original number, sort then to get the smallest, and return it's referenced number. here is an ungolfed javascript version with the same algorithm: ``` function smoothness(n,p) { p = p || 2 if (x == 1) return p if (x % p == 0) return smoothness(x/p, p) else return smoothness(x,p+1); } function smoothnessRange(a, b) { var minSmoothness = smoothness(a); var min=a; for(var i=a+1;i <= b;i++) if(minSmoothness > smoothness(i)) { minSmoothness = smoothness(i) min = i } return min; } ``` [Answer] # Lua - 166 chars *I ~~don't~~didn't have (yet!) enough reputation to comment on [AndoDaan's solution](https://codegolf.stackexchange.com/a/36392/30855), but here are some improvements on his code* ``` a,b=io.read("*n","*n")s=b for i=a,b do f={}n=i d=2 while n>1 do while n%d<1 do f[#f+1]=d n=n/d end d=d+1 end p=math.max(unpack(f))if p<s then s=p c=i end end print(c) ``` Changes : * The `n%d==0` by `n%d<1` which is equivalent in this case * Removed a space * Replaced `table.insert(f,d)` by `f[#f+1]=d` (`#f` is the number of elements of f) [Answer] # Bash+coreutils, 56 bytes ``` seq $@|factor|sed 's/:.* / /'|sort -nk2|sed '1s/ .*//;q' ``` Input is from from exactly two command-line arguments (Thanks @nyuszika7h !!!). Output is a singular result printed to STDOUT. * `seq` provides the range of numbers, one per line, from the command-line arguments. * `factor` reads those numbers and outputs each number followed by a colon and the sorted list of prime factors of that number. So the largest prime factor is at the end of each line. * The first `sed` removes the colon and all but the last/largest prime factor, so leaves a list of each number (column 1) and its largest prime factor (column 2). * `sort` numerically in increasing order by the column 2. * The final `sed` matches line 1 (number whose largest prime factor is the smallest in the list), removes everything including and after the first space, then quits. `sed` automatically prints the result of this substitution before quitting. ### Output: ``` $ ./smooth.sh 9 15 12 $ ./smooth.sh 9 16 16 $ ./smooth.sh 157 249 162 $ ./smooth.sh 2001 2014 2002 $ ``` Note ranges in this context are *inclusive* of both endpoints. [Answer] # Python 2, 67 ``` f=lambda R,F=1,i=2:[n for n in range(*R)if F**n%n<1]or f(R,F*i,i+1) ``` Thinking about another golf gave me an idea for a new algorithm to check smoothness, hence the late answer. The prime factorization of the factorial `i!` includes exactly the primes at most `i`. So, if `n` is a product of distinct primes, its smoothness (largest prime factor) is the smallest `i` for which `n` is a divisor of `i!`. To account for repeated prime factors in `n`, we can instead use a sufficiently high power of `i!`. In particular, `(i!)**n` suffices. The code tries increasing factorials `F=i!`, updated recursively. We filter for the divisors of `F` in the input range, and output them if there are any, and otherwise move on to `(i+1)!`. Test case: ``` >> f([157, 249]) [162, 192, 216, 243] ``` [Answer] ## C, ~~149~~  95 **Edited answer:** I cannot claim credit for this solution. This updated answer borrows the beautiful method used by *isaacg* in his Python solution. I wanted to see if it was possible to write it in C as a nested `for`/`while` loop with no curly braces, and it is! ``` R(a,b,n,q,p,m){for(;a<b;m=p<q?a:m,q=p<q?p:q,n=++a,p=2)while(n>1)if(n%p)p++;else n/=p;return m;} ``` **Explanation:** * Function `R(a,b,n,q,p,m)` scans the range `a` to `b-1` and returns the first smoothest number found. Invocation requires adherence to the following form: `R(a,b,a,b,2,0)` so that variables inside the function are effectively initialized as follows: `n=a;q=b;p=2;m=0;`. --- **Original answer**: This was my original answer... ``` P(n,f,p){for(;++f<n;)p=p&&n%f;return p;} G(n,f){for(;--f>1;)if(n%f==0&&P(f,1,1))return f;} R(a,b,p,n){for(;++p;)for(n=a;n<b;n++)if(G(n,n)==p)return n;} ``` **Explanation:** * Function `P(n,f,p)` tests value `n` for primality and returns true (nonzero) if `n` is prime or false (zero) if `n` is non-prime. `f` and `p` must both be passed as 1. * Function `G(n,f)` returns the greatest prime factor of `n`. `f` must be passed as `n`. * Function `R(a,b,p,n)` scans the range `a` to `b-1` and returns the first smoothest number found. `p` must be passed as 1. `n` can be any value. **Test driver:** ``` test(a,b){printf("smooth_range(%d, %d)\n%d\n",a,b,S(a,b,1,0));} main(){test(5,11);test(9,16);test(9,17);test(157,249);test(2001,2014);} ``` **Output:** ``` smooth_range(5, 11) 8 smooth_range(9, 16) 9 smooth_range(9, 17) 16 smooth_range(157, 249) 162 smooth_range(2001, 2014) 2002 ``` [Answer] # Haskell - 120 ``` import Data.List import Data.Ord x!y=(minimumBy(comparing(%2)))[x..y] x%y|x<y=y|x`mod`y==0=(x`div`y)%y|otherwise=x%(y+1) ``` Example usage: ``` > 5 ! 10 8 > 9 ! 15 9 > 9 ! 16 16 > 157 ! 248 162 > 2001 ! 2013 2002 ``` [Answer] ## Q, 91 characters K, 78 characters ``` {(x+{where x=min x}{(-2#{x div 2+(where 0=x mod 2_til x)@0}\[{x>0};x])@0}'[(x)_til y+1])@0} ``` k would probably shave a dozen characters edit: indeed, treating the upper bound as non inclusive this time ``` {*:x+{&:x=min x}{*:-2#{6h$x%2+*:&:x={y*6h$x%y}[x]'[2_!x]}\[{x>0};x]}'[(x)_!y]} ``` [Answer] # Note: This answer is not allowable. This answer uses multiple features of Pyth added after the challenge was asked. I added another new feature, calling unary range on a 2 element tuple, which shortens the solution by two characters, to this: # [Pyth](https://github.com/isaacg1), 7 ``` hoePNUQ ``` Input is now taken comma separated. The rest is the same. --- This answer uses a feature of Pyth that was added after this question was asked, specifically after seeing @aditsu's wonderful CJam solution. That being said, I wanted to demonstrate what adding that feature has made possible. The feature is `P`, which is an arity-1 function which on integer input returns a list of all prime factors of the input, sorted smallest to largest. # [Pyth](https://github.com/isaacg1), 9 ``` hoePNrQvw ``` Uses Python-style ranges, newline separated on STDIN. Outputs smallest solution to STDOUT. **Explanation:** ``` Q = eval(input()) Implicit, because Q is present. h head( First element of o order_by( Sort, using lambda expression as key. lambda N: Implicit in o e end( Last element of PN pfact(N)), List containing all prime factors of N. r range( Python-style range, lower inc, upper exc. Q Q, A variable, initialized as shown above. vw eval(input())))) The second entry of the range, same way. ``` **Tests:** ``` $ newline=' ' $ echo "9${newline}16" | ./pyth.py -c 'hoePNrQvw' 9 $ echo "9${newline}17" | ./pyth.py -c 'hoePNrQvw' 16 $ echo "157${newline}249" | ./pyth.py -c 'hoePNrQvw' 162 $ echo "2001${newline}2014" | ./pyth.py -c 'hoePNrQvw' 2002 ``` [Answer] # Lua - 176 characters ``` a,b=io.read("*n","*n")s=b for i=a,b do f={}n=i d=2 while n>1 do while n%d==0 do table.insert(f, d)n=n/d end d=d+1 end p=math.max(unpack(f))if p<s then s=p c=i end end print(c) ``` I really should stop golfing in Lua. There's no point. [Answer] ## Clojure - 173 170 chars I'm a Clojure newbie. Golfed: ``` (defn g[x,d](if(and(= 0(mod x d))(.isProbablePrime(biginteger d) 1))d 0))(defn f[i](apply max-key(partial g i)(range 2(inc i))))(defn s[a,b](first(sort-by f(range a b)))) ``` Sample runs: Ranges include low-end, exclude high-end: [a,b) Only prints one of the smoothest numbers, if multiple occur. ``` (println (s 5 11)) (println (s 9 16)) (println (s 9 17)) (println (s 157, 249)) (println (s 2001, 2014)) ``` yields: ``` bash$ java -jar clojure-1.6.0.jar range.clj 8 9 16 192 2002 ``` Ungolfed: ``` (defn g [x,d] (if (and (= 0(mod x d)) (.isProbablePrime (biginteger d) 1)) d 0)) (defn f [i] (apply max-key (partial g i) (range 2 (inc i)))) (defn s [a,b] (first (sort-by f (range a b)))) ``` [Answer] # Ruby, ~~65~~ 62 ``` require'prime' s=->a,b{(a..b).min_by{|x|x.prime_division[-1]}} ``` With apologies to <https://codegolf.stackexchange.com/a/36484/6828>, this is the golfed (and slightly simplified) version of that. Uses an inclusive range since it's a character shorter. ``` 1.9.3-p327 :004 > s[157,249] => 192 1.9.3-p327 :005 > s[5,11] => 8 1.9.3-p327 :006 > s[9,15] => 12 1.9.3-p327 :007 > s[9,16] => 16 ``` And thanks to YenTheFirst for saving three characters. [Answer] ## C# LINQ: ~~317~~ ~~303~~ ~~289~~ 262 ``` using System.Linq;class P{static void Main(string[]a){System.Console.Write(Enumerable.Range(int.Parse(a[0]),int.Parse(a[1])).Select(i=>new{i,F=F(i)}).Aggregate((i,j)=>i.F<j.F?i:j).i);}static int F(int a){int b=1;for(;a>1;)if(a%++b<1)while(a%b<1)a/=b;return b;}} ``` Ungolfed: ``` using System.Linq; class P { static void Main(string[]a) { System.Console.Write( Enumerable.Range(int.Parse(a[0]), int.Parse(a[1])) //create an enumerable of numbers containing our range (start, length) .Select(i => new { i, F = F(i) }) //make a sort of key value pair, with the key (i) being the number in question and the value (F) being the lowest prime factor .Aggregate((i, j) => i.F < j.F ? i : j).i); //somehow sort the array, I'm still not entirely sure how this works } static int F(int a) { int b=1; for(;a>1;) if(a%++b<1) while(a%b<1) a/=b; return b; } } ``` It takes in the start and the length from the command line and will return the largest smooth number. I used answers from [here](https://stackoverflow.com/a/2736385/1492861) and [here](https://stackoverflow.com/a/5873129/1492861) to make my answer. Thanks to VisualMelon for tweaking it and shaving 12 bytes off! I also got rid of the braces in the if saving 2 bytes, and CodeInChaos pointed out some obvious stuff I missed (thanks again). [Answer] ## R, 83 ``` library(gmp) n=a:b n[which.min(lapply(lapply(lapply(n,factorize),max),as.numeric))] ``` where the bottom of the input range is assigned to `a` and the top (inclusive) is assigned to `b`. `gmp` is a package that is available on CRAN. It felt dirty until I saw that absurd `mf` function in CJam. Install by typing `install.packages("gmp")` in the console. [Answer] ## PowerShell - 85 ``` ($args[0]..$args[1]|sort{$d=2 while($_-gt1){while(!($_%$d)){$m=$d;$_/=$d}$d++}$m})[0] ``` This will sort a range of numbers (inclusive) based on each number's max prime factor. It returns the lowest sorted element. ``` > smooth 5 10 8 > smooth 9 15 12 > smooth 9 16 16 > smooth 157 248 243 > smooth 2001 2013 2002 ``` [Answer] # J - 16 char Using the (*start*, *length*) style of range, as allowed by the comments. ``` (0{+/:{:@q:@+)i. ``` To be used as a dyadic verb: left argument is *start*, right is *length*. ``` 5 (+)i. 6 NB. range 5 6 7 8 9 10 5 (q:@+)i. 6 NB. prime factorizations 5 0 0 2 3 0 7 0 0 2 2 2 3 3 0 2 5 0 5 ({:@q:@+)i. 6 NB. largest prime factors 5 3 7 2 3 5 5 (+/:{:@q:@+)i. 6 NB. sort range by smallest factors 8 6 9 5 10 7 5 (0{+/:{:@q:@+)i. 6 NB. take first entry 8 f=:(0{+/:{:@q:@+)i. NB. can also be named 2001 f 13 2002 ``` A (*start*, *end*) solution is +2 chars, and excludes the end; including the end is +2 more. But on the bright side, it looks rather nice since we match up all the {braces}. ``` (0{}./:{:@q:@}.)i. NB. excluding (0{}./:{:@q:@}.)1+i. NB. including ``` [Answer] ## Seriously, 8\*14/7 = 16 (non-competitive) ``` ,x;`yM`M;m@√≠@E ``` Seriously was created after this challenge, but I wanted to post this answer because it exemplifies the type of challenges Seriously is good at. [Try it online!](http://seriously.tryitonline.net/#code=LHg7YHlNYE07bUDDrUBF&input=NSwxMQ) Explanation: ``` ,x;`yM`M;m@√≠@E ,x; make two copies of range(a,b) (a,b = input()) ` `M; make two copies of the result of the map: yM push maximum prime factor m@√≠ push index of minimum element from prime factors @E push element from range with given index ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 7 bytes ``` .mePbrF ``` [Try it here!](https://pyth.herokuapp.com/?code=.mePbrF&input=9%2C+16&debug=0) Outputs all smooth integers in the range \$[a, b)\$. For the smooth integers in \$[a, b]\$, just use `}` in place of `r`. ``` .mePbrF ‚Äì Full program with arguments a and b. rF ‚Äì Fold by half-inclusive range. Yields the integers in [a, b). .m ‚Äì Values b in that list which give minimal results when applied f. ePb ‚Äì function / block f. Pb ‚Äì Prime factors of b. e ‚Äì Last element. This is guaranteed to yield the largest, as they're sorted. ``` [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 183 bytes ``` > Input > Input >> 1‚Ķ2 >> ‚à§L >> L‚Äô >> Each 4 3 >> Select‚àß 5 L >> Each 7 6 >> L‚Åø10 > -1 >> Each 9 8 >> L‚ÄñR >> Each 12 11 3 >> 13·¥∫ >> Each 9 14 > 0 >> 15‚Åø16 >> Output 17 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYPmpYZgRiPOpY4gOifR41zATRronJGQomCsYgdnBqTmpyyaOO5QqmCj5wSXMFM4iGxv2GBkAzdQ3hUpYKFlCzpgXBBQ2NFAwNIQYaGj/csgtJtaEJUL8BWMYUZBzYYP/SEqAjFQzN//83NDXnMjKxAAA "Whispers v2 ‚Äì Try It Online") Aside from revamping the algorithm, the only real golfing opportunity can be found on lines **9** and **10**, but swapping them. When they're the other way round, the code is [1 byte longer](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYPmpYZgRiPOpY4gOifR41zATRronJGQomCsYgdnBqTmpyyaOO5QqmCj5wSXMFM6BJuoYQXY37LeEyhgYKFlCzpgUhRI0UDA0hBhoaP9yyC1m5oQnQKAOwlCnQKEMzENO/tAToSgVD8///DU3NuYxMLAA), due to the repeated use of `9` or `10`. The structure tree for this program is: [![tree](https://i.stack.imgur.com/Y6FuS.png)](https://i.stack.imgur.com/Y6FuS.png) Red represents nilad lines, green represents function arguments. Arrows from \$a \to b\$ show the use of line \$a\$ as an argument for line \$b\$. ## How it works. We start at lines **1**, **2** and **3**. The first two simply take and store the inputs \$\alpha\$ and \$\beta\$ on lines **1** and **2** respectively. There two values are then passed to line **3**, `1‚Ķ2`, which form the range $$R := [\alpha, \alpha+1, ..., \beta-1, \beta]$$ As you can see from the tree above, \$R\$ is used in two places: line **6** and line **13**. As line **6** eventually leads to line **13**, we'll take the path down **6**. Line **6** is an `Each` statement, that maps a function (the first line reference) over an array (the second line reference). Here, the function is defined on line **4** as \$f(x) = \{i \: | \: (i | x), (i \le x), i \in \mathbb{N}\}\$ i.e. the array of \$x\$'s divisors. The array is \$R\$, so line **6** iterates over \$R\$, returning the divisors of each integer, forming a new array $$D := [f(\alpha), f(\alpha+1), ..., f(\beta-1), f(\beta)]$$ We then get more complicated as we skip down to line **8**. Line **8** is also an `Each` statement, but its function argument, line **7** is split over two lines, **7** and **5**: ``` >> L‚Äô >> Select‚àß 5 L ``` Mathematically, this is the function \$g(A) = \{i \: | \: (i \in \mathbb{P}), (i \in A)\}\$, that takes a set \$A\$ and returns all the primes in \$A\$. Line **8** is iterating over \$D\$, essentially filtering all composite numbers from each subarray in \$D\$, to form $$A := [g(f(\alpha)), g(f(\alpha+1)), ..., g(f(\beta-1)), g(f(\beta))]$$ Then, we encounter yet another `Each` statement on line **11**, which iterates line **9** over \$A\$. Line **9** takes an array and returns the final element of that array. As \$g(A)\$ returns the array sorted, this is equivalent to return the largest value in that array. At this point, we remember that \$g(f(x))\$ returns the list of prime factors of \$x\$, so line **9** maps each \$x\$ to its largest prime factor, returning $$B := [\max(g(f(\alpha))), \max(g(f(\alpha+1))), ..., \max(g(f(\beta-1))), \max(g(f(\beta)))]$$ Once we have \$B\$, we now have an array we can sort \$R\$ by, e.g. we sort each value \$x\$ in \$R\$ by the resulting value of \$\max(g(f(x)))\$. However, we do not have a sort-by command in Whispers, only the simple Python `sort(list)`. Luckily, due to how `sort` sorts lists of lists, we can concatenate each \$x\$ with \$\max(g(f(x))\$ and sort by the first element, what Python does naturally. Lines **12** and **13** perform this concatenation, by iterating a concatenate function (line **12**) over \$B\$ and \$R\$. This forms an array of pairs of numbers, in the form \$[\max(g(f(x))), x]\$. Next, we sort this array on line **14**, which, due to the way Python compares lists, places the numbers with the lowest largest prime factor towards the end. Almost finished. The only things left to do are to extract \$R\$, sorted by \$B\$ (we'll call this array \$R\_B\$. This is done simply by taking the last element of each subarray (line **9** already does this for us, so we simply need `Each 9 14` on line **15**, rather than defining a new function). Once that's done, we simply take the first element in \$R\_B\$, which will be (one of) the number with the lowest largest prime factor i.e. the smoothest number. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ‚ü¶‚ÇÉ·∏ã·µíh ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1snlP9/NH/Zo6bmhzu6H26dlPH/f3S0qY6hYaxOtKWOoRmEMgdShqbmOkYmlkCWkYGBoY6RgaFJbCwA "Brachylog ‚Äì Try It Online") Takes input as a list of two (or more, actually) values in no particular order, and outputs a single value through the output variable of the predicate (if you try to run it as a full program, it'll just print `true.` at you, unless you stick a `w` on the end). The input is interpreted as a Python-style range because to feed `‚ü¶` multiple values I need to give it a subscript no matter whether it's `‚ÇÇ`, `‚ÇÉ`, or `‚ÇÑ` so I may as well choose the one that matches the test cases. ``` h The first item of ‚ü¶‚ÇÉ the range represented by the input ·µí after it's been sorted by ·∏ã prime factorization. ``` Saves three bytes over the more obvious `‚ü¶‚ÇÉ{·∏ãh}·µíh` by taking advantage of that Brachylog sorts its lists by elements first rather than lengths, such that the first step of sorting by prime factorizations is sorting by largest prime factors. [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes = 5.71 characters ``` ‚óÑo‚ñ≤p‚Ķ ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8f@j6S35j6ZtKnjUsOz////R0aY6hgaxOtGWOoamEMoMSBmamusYmVgAWUYGBoY6RgaGxrGxAA "Husk ‚Äì Try It Online") **How?** ``` ‚óÑ # element that minimizes result of o # combining these 2 functions: ‚ñ≤ # maximum of p # prime factors ‚Ķ # for the range from arg 1 ... arg 2 ``` [Answer] # Cobra - 150 ``` def f(r as vari int) x,y=r c,o=y,0 for n in x:y,for m in n:0:-1 p=1 for l in 2:m,if m%l<1,p=0 if n%m<=0<p if m<c,c,o=m,n break print o ``` Not even sure why I bothered, cobra just can't compete here. [Answer] # Ruby - 113 chars Using the stdlib. Returns one result. Tested on ruby 2.1.2. ``` require 'prime' def smooth_range(a,b) (a...b).sort_by{|e|e.prime_division.flat_map{|f,p|[f]*p}.uniq.max}[0] end ``` [Answer] ## Perl (5.10+), 83 ``` for(<>..<>){$n=$_;$p=2;$_%$p&&$p++or$_/=$p while$_>1;$m=$p,$r=$n if$p<$m||!$m} say$r ``` (linebreak can be removed). Takes two endpoints of an inclusive range on two lines of stdin (because `<>` is cheaper than accessing `ARGV`) and outputs the smoothest to stdout. If there's a tie for smoothest, prints the smallest. Could print the biggest at the cost of one character. The algorithm is basically isaacg's way of finding the greatest prime factor, although we came up with it independently. That part golfs down beautifully to a single statement in perl, the rest has more overhead than I'd like though. Should be run under `perl -E` or with a `use 5.012` preamble. If you can't do that, replace `say$r` with `print$r,$/`. [Answer] # Python 2 (84) ``` f=lambda n,p=2:n>1and f(n/p**(n%p<1),p+(n%p>0))or p print min(range(*input()),key=f) ``` [@isaacg's solution](https://codegolf.stackexchange.com/a/36391/20260), but with a `min` by function key in place of explicit min-finding, and a recursive function playing the role of the iteration. Run in [Stackless Python](http://www.stackless.com/) to avoid recursion limits. It looks wasteful to use the paranthesized condition `(n%p<1)`, then repeat its negation also in parantheses `(n%p>0)`, but that was the best I got. I tried things a bunch of things, but they turned out worse. ``` f(n/p**(n%p<1),p+(n%p>0)) # Current for comparison f(*[n/p,n,p,p+1][n%p>0::2]) n%p and f(n,p+1)or f(n/p,p) f(*n%p and[n,p+1]or[n/p,p]) ``` I welcome any improvements you can think of. ]
[Question] [ ## Task Create a program that calculates the factorial of a number using no built-in factorial functions. Easy? The catch is that you must write your entire program (including testing it) in [haiku](http://en.wikipedia.org/wiki/Haiku) form. [![Not enough work](https://i.stack.imgur.com/x8DgR.png "It's even harder if you're an asshole who pronounces <> brackets.")](https://xkcd.com/554/) You can use as many haikus as you need, but when pronounced, they must follow the 5-7-5 syllable format. ### Scoring This is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), so you must get the most upvotes to win. Your program must consist of at least one full haiku, and all haikus must be complete. When reading code, the first line of each haiku will have 5 syllables, the second will have 7, and the third will have 5. [Answer] # Smalltalk (evaluate in a workspace; opens a dialog, asks for a number and prints the result on stdout): ``` "in" "this" 'poem,' "you" "must" "pronounce" "characters" "like" "these:" "return(^)," "and" "times(*);" "please". "but" 'never' "in" "here" "tell" "anyone" "about" "those" "few" "parentheses". "otherwise" "these" "words" "are" "stupid" "and" "this" "coded" "rhyme" "is" "wasted" Time. "let" "us" "now" "begin" "by" "defining," "in" Object "and" compile: "the" "rhyme:" 'fac: "with" arg"ument" "to" "compare" arg <"against" 2 ">" "and" ifTrue: [ ^"return" "["1] "or" ifFalse: "then" ["return"^ arg *"times" "the" "result" "of" ("my"self ")getting" "the" fac:"torial" "of" "the" "number" arg "minus"- 1 "[(yes," "its" "easy")]'. ("Let" "me" "my"self "ask" "for" "a" "number," "to" "compute" "the" fac:"torial" ("by" "opening" "a" "nice" Dialog "which" "sends" "a" request: "asking" "for" 'the Number to use' "(which" "is" "(" "treated" ) asNumber) "then" print "the" "result". ``` I tried to bring in some reflection ("in this poem") and kigo as well. Also, some western style rhyme elements are included (please->these, time->rhyme); however, being neither native speaker of Japanese, nor of English, forgive any stylistic details ;-) [Answer] ## Haskell ``` fact :: Int -> Int -- fact is Int to Int fact x = product (range x) -- fact x is product range x range x = [1..x] -- range x is 1 [pause] x ``` Haskell education time: * The `range x` function creates a list of integers from 1 up to the value of `x`. * The `fact x` function multiplies all the values of the list `range x` together to compute the result. * The first line says that the `fact` function takes an integer and returns an integer. [Answer] # Java - 2 haikus ``` protected static int factorial(int n) { if (n == 0) { return n + 1; } return factorial(n - 1) * n;} ``` Even when the question isn't [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), I often catch myself golfing the answer. In this case, I golfed the number of haikus. I pronounce it so: > > protected static > > int factorial int n > > if n is zero > > > return n plus one > > return factorial n > > minus one times n > > > --- Test program: ``` class Factorial { // class Factorial public static void main(String[] // public static void main string command_line_run_args) { // command line run args int i = 0; // int i is zero while (7 != 0) // while seven is not zero System.out. // System dot out dot println(i + "!" // print line i plus not + " = " + factorial( // plus is plus factorial i += 1));} // i plus equals 1 protected static int factorial(int n) { if (n == 0) { return n + 1; } return factorial(n - 1) * n;}} ``` Note that this program starts outputting `0`s fast; that is a result of overflow. You could easily get larger correct numbers by changing each `int` to `long`. Standard pronunciations for `System.out.println` and `public static void main(String[] args)` are reflected in the program. [Answer] # APL ``` factorial←{×/⍳⍵} ``` > > Factorial is— > > the product of naturals > > up to omega > > > [Answer] # Shakespeare ``` The Products of Love: A haiku tragedy with mathy undertones. Romeo, a man. Juliet, a maiden fair. Friar John, a monk. Act I: A Cycle. Scene I: Pertinent Values. [Enter Romeo] [Enter Friar John] Romeo: Listen to thy heart. Thou art thyself. Friar John: Thou art as forthright as a songbird. [Exit Friar John] [Enter Juliet] Romeo: Thou art as fair as a violet. Scene II: Questioning Themselves. [Exit Juliet] [Enter Friar John] Friar John: Art thou as just as the sum of me and a nobleman? Romeo: If so, let us proceed to scene III. [Exit Friar John] [Enter Juliet] Romeo: Thou art as good as the product of thyself and myself. Juliet: Thou art as fierce as the sum of an eagle and thyself. We must return to scene II. Scene III: A Lengthy Title for a Brief Dénouement; Or, The Last Word. [Exit Friar John] [Enter Juliet] Romeo: Open your heart. [Exit Romeo] ``` An (imagined) test case: Despite its length, this program just takes a single integer as input and provides a single integer as output. So: ``` 6 ↵ 720 7 ↵ 5040 0 ↵ 1 1 ↵ 1 ``` ("Six, seven-twenty. / Seven, five thousand forty. / Zero, one. One, one.") [Answer] # Python 2, 4 Haikus A complete Python 2 program `haifac.py`. Run as `python haifac.py <n>` ``` #run this full program import operator as\ op; import sys#tem #please provide an arg n = sys.argv[1] def haifac (n): if n < 1: return 1#to me at once else:#do something else return op.mul( n, haifac(n - 1)) print haifac(int(n)) ``` Pronounciation: > > run this full program > > import operator as > > op import system > > > > > please provide an arg > > n equals sys arg v 1 > > define hai fac n > > > > > if n less than 1 > > return 1 to me at once > > else do something else > > > > > return op dot mul > > n hai fac n minus 1 > > print hai fac int n > > > > > [Answer] ## GolfScript, 2 Haikus ``` ),{0>},{,,*}* ``` Read as haiku, enumerating each keystroke: ``` #close parenthesis #comma open-brace zero #greater-than close-brace #comma open-brace #comma comma asterisk #close-brace asterisk ``` With test case (5 haikus): ``` [1 2 3]4+ #generate the array [1 2 3 4] { #start creating block ),{0>},{,,*}* #actual factorial code }% #close block and map across array (so that we should have [1! 2! 3! 4!]) [1 2 6]2.3**12++= #generate the array [1 2 6 24] and check for equality ``` Read as haiku: ``` #open-bracket one #space two space three close-bracket #four plus open-brace #close parenthesis #comma open-brace zero #greater-than close-brace #comma open-brace #comma comma asterisk #close-brace asterisk #close-brace percent-sign #open-bracket one space two #space six close-bracket #two period three #asterisk asterisk one #two plus plus equals ``` [Answer] # [Whitespace](http://compsoc.dur.ac.uk/whitespace/download.php) This makes uses of one of the [most famous](https://whrarchives.wordpress.com/2011/09/01/a-contrarian-view-of-bashos-frog/) *haiku*s, and [a great deal](http://www.ahapoetry.com/AHI%20frog%20art.html) has been written about it. No idea why nobody has done this before, [it doesn't even take any effort!](http://compsoc.dur.ac.uk/whitespace/examples.php) First of all, before reading the poem, I want you to lean back, relax, and enjoy the tranquility created by the great void surrounding the poem. It emphasizes the pond, surrounded by a vast landscape. ``` 古池や 蛙飛びこむ 水の音 ``` [source code on filebin](http://filebin.ca/1tdvROHWP8cN) In case you do not speak Japanese, this [is pronounced](http://en.wikipedia.org/wiki/Hepburn_romanization) as follows: > > fu ru i ke ya > > > ka wa zu to bi ko mu > > > mi zu no o to > > > Naturally, it is counted by morae. The [*kireji* is や (*ya*)](http://kogumaza.jp/1410haikujihyuu.html), the [*kigo* (seasonal reference) is 蛙 (*kawazu*, frog, -> spring)](http://kobun.weblio.jp/content/%E3%81%B5%E3%82%8B%E3%81%84%E3%81%91%E3%82%84). Using the linux interpreter from the official page, you can use it like this: > > $ echo 5 | ./wspace .ws > > > [Answer] # PHP, 4 haikus *All-in-rhyme* haikus! ``` function haiku($can) { // function haiku can (5) if ($can == 1) // if can is equal to one (7) return ++$stun; // return increase stun (5) if ($can == 0) { // if can equals ou (5) echo "It is one, you know! "; //echo "It is one, you know! " (7) return 1+$blow; } //return one plus blow (5) if ($can > $fun) { //if can exceeds fun (5) return haiku($can-1) //return haiku can less one (7) *$can; }} //multiplied by can (5) if (null == $knee) { // if null equals knee (5) $free=0+3; // free equals zero plus three (7) echo haiku($free); } // echo haiku free (5) ``` [Answer] # Forth ``` : fugu 1 \ colon fugu one = 5 swap 1 + 1 ?do \ swap one plus one question do = 7 i * loop ; \ eye star loop semi = 5 ``` *Fugu* is the function and my attempt at *kigo*: blowfish is a winter reference. I intend `?do` to be *kireji*, the turning point, before the counted loop. [Answer] # Mathematica ``` f[x_]:= (* f of x defined *) x f[x-1] (* x times f of x less 1 *) f[1]=1 (* Mogami River *) ``` Pedants may read the last line as "f of 1 is 1", but I couldn't resist the shout-out to Basho. ### Testing: ``` Table[f[n], (* Table f of n *) {n, 1, 10, 1}] (* n from 1 to 10 by 1 *) ListLogPlot[%] (* ListLogPlot output *) ``` ### Returning: ``` (1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800) ``` ![log plot of values](https://i.stack.imgur.com/erXAA.jpg) ### Linguistic Distinctiveness Bonus Haiku (inspired by @cormullion) ``` Rewrite any term High-level functions abound — Mathematica ``` [Answer] ## Batch ``` @set /a t=1 &^ for /L %%a in (2, 1, %1) ^ do @set /a t*=%%a ``` **Pronunciation**; ignores mathematical expressions as well as these symbols `@ / % ^ , ( )`: > > set a t 1 and > for L a in 2 1 1 > do set a t a > > > Note; this calculates the factorial, it doesn't output it - the variable `t` contains the factorial. The following Haiku / code can be appended to the same batch file to output the factorial (the `|`'s are pronounced as pipe): ``` @echo %t% ||^ When will you learn, unclemeat ^ Why must you use Batch? ``` [Answer] # Clojure ``` (->> *command-line-args* ; thrush com-mand line args seq last read-string range (map inc) ; seq last read string range map inc (reduce *) println) ; re-duce times print-lin ``` [Answer] # F# ``` let fact n = [1..n] |> Seq.fold (*) 1 ``` > > let fact of n be > > from one up to n, apply > > Seq dot fold star one > > > [Answer] ### newLISP The parentheses are not pronounced: ``` (define (fac n (so)) ; define fac n so (if (= n 0) 1 ; if equals n zero 1 (* n (fac (dec n))))) ; times n fac dec n (for (n 0 10) ; for n zero ten ; let's test from zero to ten (println (fac n thus))) ; printline fac n thus ``` > > Lisp code consists of > > > numerous parentheses > > > and a few functions > > > [Answer] # [LiveScript](http://livescript.net/) This one's medieval: ``` prelude = ^^ do # prelude is clone do require \prelude-ls # require prelude dash ls { product } = prelude # product is prelude story = (ah) -> # story is ah such: ones-misery = (one) -> # one's misery is one such let death = product # let death be product fight = [1 to one] # fight is one to one why = (one) -> death <| fight # why is one such death take fight ones-misery ah # one's misery ah room = console.log # room is console log room <| (story 10)! # room take story three bang [null of { use : this }] # no of use is this ``` Prints `3628800`, which is `10!`. It's a little roundabout: The function `story` returns a function `ones-misery`, which always returns the answer. It's artsier that way. No filler comments or unnecessary strings! --- Bonus debugging story: > > I burst out laughing > > when informed that a bug was > > "`death` is `undefined`" > > > [Answer] ## Haskell This one will be a **rhyming** haiku! ``` fact 0=1 --fact zero is one fact ton=ton * (fact stun) --fact ton is ton times fact stun where stun=pred ton --where stun is pred ton ``` Yeah! Note: Pred means the previous number. Also in haskell, you can have multiple definitions of a function, and the first one that makes sense is used. [Answer] **Ruby - One Haiku** ``` ARGV.first.to_i. tap do |please| puts 1.upto( please ).inject( :*) end ``` Read (ignoring punctuation, but including one emoticon) like this: ``` arg vee first to i tap do please puts one up to please inject smile end ``` [Answer] # Perl ``` $r = 1; for(1 # r gets one for one .. pop @ARGV) { $r *= # to pop arg v r splat gets $_; } print $r; # the default print r ``` Toss this into a file named `f.pl` And the output: ``` $ perl f.pl 3 6$ perl f.pl 1-1 1$ perl f.pl 10 3628800$ ``` Which is read as: ``` perl f p l three perl f p l one less one perl f p l ten ``` [Answer] In SML: ``` fun fact 0 = 1 | fact n = n*fact(n-1) ; ``` read as: ``` "fun fact 0 is one, bar that, fact n is n times fact of n less one" ``` [Answer] ## Perl I know it's against the rules to use ready-made functions, but here's what I get. Imagine your task is to instruct an over-sized rodent: ``` use Math::BigRat; use feature 'say'; use warnings; say new Math::BigRat($_)->bfac ``` I can only guess what the last word means and how it's pronounced, but I assure you it is one syllable. Apparently he doesn't understand what you want from him, so you have to elaborate (easing on quality standards as you loose patience): ``` use Math::BaseConvert ':all'; no strict subs; no warnings; reset and say fact($_) ``` still to no avail. Then you have to explain it in plain English: ``` no strict; no warnings; use Math::Combinatorics; say factorial($_) ``` What happened next I don't know, but code is valid: ``` perl -nE 'use Math::BigRat; use feature "say"; use warnings; say new Math::BigRat($_)->bfac' 42 1405006117752879898543142606244511569936384000000000 ``` and ``` perl -nE 'use Math::BaseConvert ":all"; no strict subs; no warnings; reset and say fact($_)' 33 8683317618811886495518194401280000000 ``` and ``` perl -nE 'no strict; no warnings; use Math::Combinatorics; say factorial($_)' 16 20922789888000 ``` [Answer] ### Python ``` lambda n: reduce( lambda a, b: a * b, range(1, n), n) ``` The way I read it: > > > ``` > lambda n: reduce > lambda a b: a times b > range 1 to n, n > > ``` > > ` [Answer] **C** ``` #include <std\ io.h> #include \ <stdlib.h> int main(int argc , char** argv) { // iteratively // compute factorial here long int n = \ 0, i \ = 0, r = \ 1 /* product starts at one*/; if (argc > 1) { n = strtol(argv[\ 1], NULL, 10) ; if (n < 0) { printf("Arg must\ be >= 0\n"); exit(- 1);} } i = n; while (i) { r = r * i; i --; } /* print the result*/ printf( "%d factorial\ equals %d\ \n", n , r); /*done*/} ``` **Pronounciation:** pound include standard I/O dot h pound include standard lib dot h int main int arg c comma char star star arg v open brace comment iteratively compute factorial here long int n equals zero comma i equals zero comma r equals one comment product starts at one semicolon if arg c is greater than one open brace n is str-to-l of arg v sub one comma NULL comma ten semicolon if n less than zero begin printf arg must be greater than or equal to zero backslash n semicolon exit negative one semicolon end brace end brace i equals n semicolon while i open brace r equals r times i semicolon i decrement semicolon close brace comment print the result printf percent d factorial equals percent d whack n comma n comma r semicolon comment done end brace [Answer] # Python Uses a single haiku to do the job! ``` f = lambda x: \ # f is lambda x: 0**x or x * \ # zero pow x, or x times f(x-1) # f(x minus 1) ``` This defines a recursive lambda which calculates the factorial - `0**x` handles the case of 0 as it evaluates to `1`. [Answer] ## C# - 3 haikus I removed the usual C# using, namespace and class definition clutter, which would be a 4th haiku. ``` public static void Main(){int num = Convert. ToInt32 (Console.ReadLine()); Console.WriteLine(num == 0 ? 1 : Enumerable. Range(1, num).Aggregate ((i, j) => i * j));} ``` which I read as ``` public static void Main int num equals Convert To int thirty-two Console dot Read line Console Write line num equals zero? then one, else Enumerable Range 1 to num aggregate i j i times j ``` [Answer] ## Haskell ``` module Haiku where -- read literally. fac x = let in do -- = is read as 'equals' product [1..x] -- product one to x ``` note that the module .. where is added automatically to any Haskell code without it at compilation, so not writing it is practically cheating. [Answer] **JAVA:** In response to the question and to the Dwaiku (Double-Haiku or whatever you wanna call it) posted by Quincunx in Java, here's the correct Haiku: ``` public static int factorial(int n) { return (n==0) ? (n+1) : (factorial(n-1) * n); } ``` [Answer] ### Javascript - Two Haikus ``` function factor (a) { // function factor a if(!a){ return 1 || // if not a return 1 or a & 17} // a and seventeen else if (a + 1){ // else if a plus one return a * factor // return a into factor (a + ( - 1) ) }} // a plus minus one ``` I am not a native speaker. So, I used a dictionary to count the syllables. Hopefully, it's good enough. Any feedback is welcome :) [Answer] **Powershell, 2 Haikus** ``` function facto ($num){ # function facto num $i = 1; 1..$num| # i equals one; i to num foreach { $i = # for each i equals $i * $_}; write $i} # i times this write i $answer = facto $args[ # answer equals facto args 0]; write $answer # zero write answer ``` [Answer] Are we allowed to use filler? Python 2 haikus: ``` number = num + 1 a = 13 + 4 b = 14 nuum = len([1]) for i in range(1, number): nuum *= i ``` ]
[Question] [ # Introduction [The Nineteenth Byte](https://chat.stackexchange.com/rooms/240/the-nineteenth-byte) is [CGCC](https://codegolf.stackexchange.com)'s official chatroom (go check it out!). Its name is a play on [the nineteenth hole](https://en.wikipedia.org/wiki/Nineteenth_hole), and it also refers to golf, which is appropriate for [CGCC](https://codegolf.stackexchange.com)'s chatroom's name. The name is also precisely \$19\$ bytes long, as its name states. # Challenge Your task is to write a program that outputs `Stack Exchange Chat - The Nineteenth Byte` exactly. However, if the nineteenth byte and only the nineteenth byte of your source code is removed, it should output only `Stack Exchange Chat`. Because of this, the best score you can get will be \$19\$ bytes. For example, if your code is `abcdefghijklmnopqrstuvwxyz`, then `abcdefghijklmnopqrstuvwxyz` must output `Stack Exchange Chat - The Nineteenth Byte` and `abcdefghijklmnopqrtuvwxyz` must output `Stack Exchange Chat`. # Rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Trailing whitespace is allowed. * If possible, please link to an online interpreter (e.g. [TIO](https://tio.run)) to run your program on. * Please explain your answer. This is not necessary, but it makes it easier for others to understand. * Languages newer than the question are allowed. This means you could create your own language where it would be trivial to do this, but don't expect any upvotes. * You are scored by the length of the program that outputs `Stack Exchange Chat - The Nineteenth Byte`. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` “¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC0OOTbQ8stHo4c62IDD/UeOOQ4vMHu5sPbFe6@Hurcreh3ZnHmt/1DA34/@hRf8B "Jelly – Try It Online") or [Try it without `#`](https://tio.run/##y0rNyan8//9Rw5xDC0OOTbQ8stHo4c62IDD/UeOOQ4vMHu5sPbFe6@Hurd6Hdmcea3/UMDfj/6FF/wE) # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` “¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC0OOTbQ8stHo4c62IAj/4Y753pG2Jzce3lF3aHfJsYnH2h81bvP@f2jRfwA "Jelly – Try It Online") or [Try it without `~`](https://tio.run/##y0rNyan8//9Rw5xDC0OOTbQ8stHo4c62IAj/4Y753pG2Jzce3nFod8mxicfaHzVu8/5/aNF/AA) ## How they work ``` “¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K»iƇ”h - Main link. No arguments “¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵ#K» - Pair of compressed strings ["Stack Exchange Chat", " - The Nineteenth Byte"] Ƈ - Keep those for which the following is True: i ”h - They contain "h"; ["Stack Exchange Chat", " - The Nineteenth Byte"] Smash together and output “¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK»iƇ”h - Main link. No arguments “¡TƑ9ı2ṆR“¡⁸¢6ṅȯ*ỵK» - Pair of compressed strings ["Stack Exchange Chat", "^Backets reamyappenzell"] Ƈ - Keep those for which the following is True: i ”h - They contain "h"; ["Stack Exchange Chat"] Smash together and output ``` And the second one: ``` “¡TƑ9ı2ṆR“¡TḟKY=ɱø~»tƑƇ⁶K - Main link. No arguments “¡TƑ9ı2ṆR“¡TḟKY=ɱø~» - Pair of compressed strings ["Stack Exchange Chat", "- The Nineteenth Byte"] ƑƇ - Keep those where the following has no effect: t ⁶ - Removing spaces from the front and end; ["Stack Exchange Chat", "- The Nineteenth Byte"] K - Join with spaces; "Stack Exchange Chat - The Nineteenth Byte" “¡TƑ9ı2ṆR“¡TḟKY=ɱø»tƑƇ⁶K - Main link. No arguments “¡TƑ9ı2ṆR“¡TḟKY=ɱø» - Pair of compressed strings ["Stack Exchange Chat", " Backets reamyappenzell"] ƑƇ - Keep those where the following has no effect: t ⁶ - Removing spaces from the front and end; ["Stack Exchange Chat"] K - Join with spaces; "Stack Exchange Chat" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 24 bytes ``` “ÆçƲBnƥẈṛⱮ_ỴȷOṘỵḊĊ»»ḣ19$ ``` [Try it online!](https://tio.run/##ATsAxP9qZWxsef//4oCcw4bDp8ayQm7GpeG6iOG5m@Kxrl/hu7TIt0/huZjhu7XhuIrEisK7wrvhuKMxOST//w "Jelly – Try It Online") ## Without the nineteenth byte ``` “ÆçƲBnƥẈṛⱮ_ỴȷOṘỵḊĊ»ḣ19$ ``` [Try it online!](https://tio.run/##ATkAxv9qZWxsef//4oCcw4bDp8ayQm7GpeG6iOG5m@Kxrl/hu7TIt0/huZjhu7XhuIrEisK74bijMTkk//8 "Jelly – Try It Online") It works no matter if you index from 0 or 1! ## Explanation ``` “ÆçƲBnƥẈṛⱮ_ỴȷOṘỵḊĊ»»ḣ19$ Main niladic link “ÆçƲBnƥẈṛⱮ_ỴȷOṘỵḊĊ» "Stack Exchange Chat - The Nineteenth Byte" » [Calculate the byte-wise maximum with]* $ ( ḣ19 Get the first 19 characters $ ) ``` \*When indexing from 1, it's actually the first `»` that is removed, but the result is the same. [Answer] # [JavaScript (V8)](https://v8.dev/), 66 bytes The nineteenth byte is the `X`. ``` print("Stack",(s="X"&&" - The Nineteenth Byte","Exchange Chat"+s)) ``` [Try it online!](https://tio.run/##BcGxCoAgEADQXzluECXdW1qK1pYaWg850gIRPaS@3t67qVH1JWZxbew9l5hE4y7kH7S6TniiUggOjsCwxcTCnCTA/AmjxfX1gdLFsAQSHKoxvf8 "JavaScript (V8) – Try It Online") [Try it online!](https://tio.run/##BcHBCoAgDADQXxk7hJLeu3QpunapHxgy0gIRHVJfv967qVMLNRXxfVItNWUxeAiFB51pM@IwIHg4I8OeMgtzlgjLJ4wOtzdEyhfDGklwbNaq/g "JavaScript (V8) – Try It Online") (nineteenth byte removed) ### Commented ``` print( // print: "Stack", // the first word followed by an implicit space ( // s = "X" && // define s as either " - The Nineteenth Byte" " - The Nineteenth Byte", // or an empty string if the 'X' is removed "Exchange Chat" + s // append "Exchange Chat" followed by s ) // ) // end ``` [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` s,y='Stack Exch',01 print s+'ange Chat'+' - The Nineteenth Byte'*y ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v1in0lY9uCQxOVvBtSI5Q13HwJCroCgzr0ShWFs9MS89VcE5I7FEXVtdQVchJCNVwS8zL7UkNTWvJEPBqbIkVV2r8v9/AA "Python 2 – Try It Online") Not really a smart answer. :p The nineteenth byte here is the `1`. y is `0` or `1` depending on if the nineteenth byte is removed. *thanks to pxeger for -2 bytes* [Answer] # [Zsh](https://www.zsh.org/), 54 bytes ``` set Exchange Chat \ - The Nineteenth Byte <<<Stack\ $@ ``` [Try it online!](https://tio.run/##qyrO@P@/OLVEwbUiOSMxLz1VwTkjsUQhhktXISQjVcEvMy@1JDU1ryRDwamyJJXLxsYmuCQxOTtGQcXh/38A "Zsh – Try It Online") `set` assigns the given words to the default variable `$@`. As with the previous one, `\` joins the two lines into one call to set, instead of treating `- The Nineteenth Byte` as a command (which does nothing). --- ## [Zsh](https://www.zsh.org/), 55 bytes ``` 1=" Exchange Chat"\ " - The Nineteenth Byte" <<<Stack$1 ``` [Try it online!](https://tio.run/##qyrO@P/f0FZJwbUiOSMxLz1VwTkjsUQphktJQVchJCNVwS8zL7UkNTWvJEPBqbIkVYnLxsYmuCQxOVvF8P9/AA "Zsh – Try It Online") Idea boringly copied from [@xnor's genius answer](https://codegolf.stackexchange.com/a/221334). The `\` escapes the newline, which concatenates the two strings; without it, the second line is ignored as an undefined command. --- ## [Zsh](https://www.zsh.org/), 58 bytes ``` 1=Stack\ Exchang 2=" - The Nineteenth Byte" <<<$1e\ Chat$2 ``` [Try it online!](https://tio.run/##qyrO@P/f0Da4JDE5O0bBtSI5IzEvncvIVklBVyEkI1XBLzMvtSQ1Na8kQ8GpsiRVicvGxkbFMDVGwTkjsUTF6P9/AA "Zsh – Try It Online") The 19th byte is the second `=`, which changes that line from a variable assignment to an undefined command which does nothing. Then, when printing, `$2` defaults to empty. [Answer] # [Emotion](https://github.com/Quantum64/Emotion), 34 [bytes](https://quantum64.github.io/EmotionBuilds/1.1.0///?state=JTdCJTIybW9kZSUyMiUzQSUyMmNvZGVwYWdlJTIyJTdE) ``` 😇😘🧖🚵🧖💫😋🧖💙🤙💁🤹☝🍓🧖💖🍸😚🤕😔😘😉💚🙌🙎🥥🤤👨🤑💇👱💔😯😨 ``` The nineteenth byte is 🤕. [Try it online!](https://quantum64.github.io/EmotionBuilds/1.1.0///?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJTk4JTg3JUYwJTlGJTk4JTk4JUYwJTlGJUE3JTk2JUYwJTlGJTlBJUI1JUYwJTlGJUE3JTk2JUYwJTlGJTkyJUFCJUYwJTlGJTk4JThCJUYwJTlGJUE3JTk2JUYwJTlGJTkyJTk5JUYwJTlGJUE0JTk5JUYwJTlGJTkyJTgxJUYwJTlGJUE0JUI5JUUyJTk4JTlEJUYwJTlGJThEJTkzJUYwJTlGJUE3JTk2JUYwJTlGJTkyJTk2JUYwJTlGJThEJUI4JUYwJTlGJTk4JTlBJUYwJTlGJUE0JTk1JUYwJTlGJTk4JTk0JUYwJTlGJTk4JTk4JUYwJTlGJTk4JTg5JUYwJTlGJTkyJTlBJUYwJTlGJTk5JThDJUYwJTlGJTk5JThFJUYwJTlGJUE1JUE1JUYwJTlGJUE0JUE0JUYwJTlGJTkxJUE4JUYwJTlGJUE0JTkxJUYwJTlGJTkyJTg3JUYwJTlGJTkxJUIxJUYwJTlGJTkyJTk0JUYwJTlGJTk4JUFGJUYwJTlGJTk4JUE4JTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjIlMjIlMkMlMjJtb2RlJTIyJTNBJTIyaW50ZXJwcmV0ZXIlMjIlN0Q=) [Answer] # [C (gcc)](https://gcc.gnu.org/), 69 bytes Without the removal of the 19th byte, the full string (which is much less than 119 characters) is printed; if the 19th byte is removed, only 19 characters are printed instead. ``` main(){printf("%.119s","Stack Exchange Chat - The Nineteenth Byte");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0lVz9DQslhJRym4JDE5W8G1IjkjMS89VcE5I7FEQVchJCNVwS8zL7UkNTWvJEPBqbIkVUnTuvb/fwA "C (gcc) – Try It Online") With the 19th byte removed: [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0lVz9CyWElHKbgkMTlbwbUiOSMxLz1VwTkjsURBVyEkI1XBLzMvtSQ1Na8kQ8GpsiRVSdO69v9/AA "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` s="Exchange Chat "\ "- The Nineteenth Byte" print"Stack",s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWybUiOSMxLz1VwTkjsURBKYZLSVchJCNVwS8zL7UkNTWvJEPBqbIkVYmroCgzr0QpuCQxOVtJp/j/fwA "Python 2 – Try It Online") ([no 19th byte](https://tio.run/##K6gsycjPM/r/v9hWybUiOSMxLz1VwTkjsURBiUtJVyEkI1XBLzMvtSQ1Na8kQ8GpsiRViaugKDOvRCm4JDE5W0mn@P9/AA "Python 2 – Try It Online")) The 19th byte is the `\` at the end of the first line. It acts as a line continuation character to make the full line be `"Exchange Chat ""- The Nineteenth Byte"` using Python's automatic concatenation of adjacent string literals. Without the `\`, the line ends there, and the second line is lonely string value that doesn't do anything. The truncated string ends in a space, which is fine because the challenge allows for trailing whitespace. --- **[Python 2](https://docs.python.org/2/), 61 bytes** ``` s="Exchange Chat"+--1*" - The Nineteenth Byte" print"Stack",s ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v9hWybUiOSMxLz1VwTkjsURJW1fXUEtJQVchJCNVwS8zL7UkNTWvJEPBqbIkVYmroCgzr0QpuCQxOVtJp/j/fwA "Python 2 – Try It Online") ([no 19th byte](https://tio.run/##K6gsycjPM/r/v9hWybUiOSMxLz1VwTkjsURJW9dQS0lBVyEkI1XBLzMvtSQ1Na8kQ8GpsiRViaugKDOvRCm4JDE5W0mn@P9/AA "Python 2 – Try It Online")) The 19th byte is a `-`. Originally we append `--1` (so, `1`) copies of the string `" - The Nineteenth Byte"`, with the 19th byte is removed, this is `-1` copies which is nothing. [Answer] # [Husk](https://github.com/barbuz/Husk), ~~25~~ 23 bytes ``` ΣüL½¨ḟKȦΞ×ėCȧt-ξḟ%Nhβ/y ``` [Try it online!](https://tio.run/##AS4A0f9odXNr///Oo8O8TMK9wqjhuJ9LyKbOnsOXxJdDyKd0Lc6@4bifJU5ozrIvef// "Husk – Try It Online") [Try it online without the 19th byte!](https://tio.run/##AS0A0v9odXNr///Oo8O8TMK9wqjhuJ9LyKbOnsOXxJdDyKd0Lc6@4bifJWjOsi95//8 "Husk – Try It Online") ### Explanation `¨ḟKȦΞ×ėCȧt-ξḟ%Nhβ/y` is a compressed string, equivalent to `"Stack Exchange Chat - The Nineteenth Byte"`. If we remove `N` (the nineteenth byte of the program) we get `¨ḟKȦΞ×ėCȧt-ξḟ%hβ/y`, which is equivalent to `"Stack Exchange Chat - Thefischer\n Byte"` (`\n` being a newline character). Now, starting from one of these two strings: ``` "Stack Exchange Chat - The Nineteenth Byte" "Stack Exchange Chat - Thefischer\n Byte" ½ Split the string in half ["Stack Exchange Chat -", ["Stack Exchange Chat", " The Nineteenth Byte"] " - Thefischer\n Byte"] üL nub by length: remove strings with the same length as previous ones ["Stack Exchange Chat -", ["Stack Exchange Chat"] " The Nineteenth Byte"] Σ Join the strings together "Stack Exchange Chat - The Nineteenth Byte" "Stack Exchange Chat" ``` [Answer] # Scala 3, 90 bytes ``` val x="Stack Ex"+a/*/ */+" - The Nineteenth Byte" def a="change Chat" @main def m=print(x) ``` [Try it in Scastie!](https://scastie.scala-lang.org/RIMt9dBVSaGLXFopkJpO3Q) With the nineteenth byte removed: ``` val x="Stack Ex"+a// */+" - The Nineteenth Byte" def a="change Chat" @main def m=print(x) ``` [Try it in Scastie!](https://scastie.scala-lang.org/dlYCNGoWRmCBsKFUxvUclw) The syntax highlighting should show what happens. This would be a byte shorter in a language without nested comments, since the space in `/*/ */` wouldn't be needed, but I just like Scala :P A possible solution with a newline that doesn't work because of parsing rules: ``` val x="Stack E"+a// +" - The Nineteenth Byte" def a="xchange Chat" @main def m=print(x) ``` [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` b='Stack Excha' n=88 print b+'nge Chat - The Nineteenth Byte'[:n] ``` **[Try all of it](https://tio.run/##K6gsycjPM/r/P8lWPbgkMTlbwbUiOSNRnSvP1sKCq6AoM69EIUlbPS89VcE5I7FEQVchJCNVwS8zL7UkNTWvJEPBqbIkVT3aKi/2/38A "Python 2 – Try It Online")** **[Try it without the 19th byte](https://tio.run/##K6gsycjPM/r/P8lWPbgkMTlbwbUiOSNRnSvP1oKroCgzr0QhSVs9Lz1VwTkjsURBVyEkI1XBLzMvtSQ1Na8kQ8GpsiRVPdoqL/b/fwA "Python 2 – Try It Online")** Works in Python 3 trivially for [66 bytes](https://tio.run/##K6gsycjPM7YoKPr/P8lWPbgkMTlbwbUiOSNRnSvP1sKCq6AoM69EI0lbPS89VcE5I7FEQVchJCNVwS8zL7UkNTWvJEPBqbIkVT3aKi9W8/9/AA "Python 3.8 – Try It Online") [Answer] # Scratch 3.0, 10 blocks/160 bytes ``` define set[outpuuut v]to[Stack Exchange Chat - The Nineteenth Byte set[outpuuu v]to[Stack Exchange Chat if<(outpuuut)>(0)>then say(outpuuut else say(outpuuu end ``` This outputs `Stack Exchange Chat - The Nineteenth Byte` Because Scratch is a block-based language, it may not seem obvious on how to remove a byte at first. But thankfully, there exists a text format called ScratchBlocks which [we seem to allow for scoring](https://codegolf.meta.stackexchange.com/a/5013/78850). The above ScratchBlocks corresponds to the following real blocks: [![This actually wasn't as painful as I thought it'd be](https://i.stack.imgur.com/FvKCN.png)](https://i.stack.imgur.com/FvKCN.png) [Try it on Scratch!](https://scratch.mit.edu/projects/506212911/) Removing the 19th byte of this program gives ``` define set[outpuuu v]to[Stack Exchange Chat - The Nineteenth Byte set[outpuuu v]to[Stack Exchange Chat if<(outpuuut)>(0)>then say(outpuuut else say(outpuuu end ``` This outputs `Stack Exchange Chat` [![enter image description here](https://i.stack.imgur.com/Pt11k.png)](https://i.stack.imgur.com/Pt11k.png) [Try it on Scratch!](https://scratch.mit.edu/projects/506216881/) Explanation coming soon [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 72 bytes ``` print('Stack Exch{1}'.format(x:='ange Chat',x+' - The Nineteenth Byte')) ``` [Try it online!](https://tio.run/##K6gsycjPM7YoKPr/v6AoM69EQz24JDE5W8G1Ijmj2rBWXS8tvyg3sUSjwspWPTEvPVXBOSOxRF2nQltdQVchJCNVwS8zL7UkNTWvJEPBqbIkVV1T8/9/AA "Python 3.8 (pre-release) – Try It Online") Different approach than @ManishKundu solution Nineteenth byte is `1` removing it will result `0` to only suffix `hange Chat` Thanks to @ZaelinGoodman for insight -6 bytes to @Makonede [Answer] # [><>](https://esolangs.org/wiki/Fish), 62 bytes ``` "Stack Exch"\" - "< " tahC egna"/r>o<r/ eeteniN ehT"\"etyB htn ``` [Try it online!](https://tio.run/##S8sszvj/Xym4JDE5W8G1IjlDKUZJQVdByYZLSaEkMcNZITU9L1FJv8gu36ZInys1tSQ1L9NPITUjBKgutaTSSSGjJO//fwA "><> – Try It Online") [Try it without the Nineteenth byte](https://tio.run/##S8sszvj/Xym4JDE5W8G1IjlDKUZJQVdBiUtJoSQxw1khNT0vUUm/yC7fpkifKzW1JDUv008hNSMEqCy1pNJJIaMk7/9/AA "><> – Try It Online") I've been playing around with ><> this week and this one was kind of a freebie, although it still turned out to be an interesting packing problem that ended up getting quite lucky at the end. The Nineteenth byte is unsurprisingly the `<` at the end of the first row. With or without it, we'll execute `"Stack Exchange Chat "`, pushing that string onto the stack (in reverse order; usually we want to push strings backwards but here it's convenient to start with the prefix so we'll just reverse the stack later instead). At this point, the program encounters the `/` at the end of the second row, hitting it from the right and heading down, *conveniently going through the space between "Nineteenth" and "Byte"*, then wrapping around vertically and either heading leftwards on the first or second row. With the `<`, we execute `"The Nineteenth Byte"`, pushing that string on the stack and then head to the output gadget, and without it we head directly to the output. The output is done by first reversing the stack with `r`, and then heading into the bottomless pit of `>o<` which executes the output instruction `o` endlessly until the stack is emptied and the program exits via error. [Answer] # [Factor](https://factorcode.org/), ~~95 94~~ 87 bytes Saved 1 precious byte thanks to @OriginalOriginalOriginalVI! Saved 7 more bytes thanks to @Bubbler! ``` "Stack Exchange C"f " - The Nineteenth Byte""hat"rot [ prepend nip ] [ glue ] if* print ``` [Try it online!](https://tio.run/##HY0xDsIwEAS/sroSiQ9AB0KIJk2giigss46tRBfjXCTyehPoZpqZ4LxNpT7aW3M9YGBRjsiFZmsuSQ0z3wvVc0aacKzSmvMDLh8fnfbEWQIEe9wj0SSlkWoRp9UoEp1JmQzdr5ipL2jKeG7ejws3SGGH/6bWLw "Factor – Try It Online") Explained: ``` "Stack Exchange C"f " - The Nineteenth Byte""hat" ! push items on the stack, ! f (false) value is 19th char rot ! rotate, f now at top of stack ! if f is missing, "Stack Exchange C" ! is at the top [ prepend nip ] [ glue] if* print ! if* f is found, glue the strings and print. ! if* a string is found, it is considered to ! be true, retain it on the stack, swap & glue ! the top strings, drop the "19th Byte" string, ! append and print. ``` Old version: ``` "Stack Exchange C"f "hat"" - The Nineteenth Byte"rot [ nip swap append ] [ 3append ] if* print ``` [Try it online!](https://tio.run/##Pc2xCgIxEEXRX3mkFKzstFNEbLZZrcRiiC8mrMxmkxHdr49iYXc5zQ3ibSzt3B@7wxoDi/KBXGg255LUUDk9qZ4VacSmud7ED9i/fRS9EzsX4KKYc1jiFIkuKY1Ui9jORldGwwWaMupLMiRn6g3Xr63@ncICv1trHw "Factor – Try It Online") Explained: ``` "Stack Exchange C"f "hat"" - The Nineteenth Byte" ! push items on the stack, ! f (false) value is 19th char rot ! rotate, f now at top of stack ! if f is missing, "Stack Exchange C" ! is at the top [ nip swap append ] [ 3append ] if* print ! if* f is found, append the strings and print. ! if* a string is found, it is considered to ! be true, retain it on the stack, drop the ! "19th Byte" string, swap stack strings, ! append and print. ``` [Answer] # PowerShell 7, 60 bytes ``` 'Stack Exchange'+(!0 ?' Chat - The Nineteenth Byte':' Chat') # ^ # 19th byte ``` No TIO because the ternary operator is not supported in powershell 6 and below ## Alternate Solutions ### PowerShell 7, 60 bytes ``` "Stack Exchan$($x=!0 ?' - The Nineteenth Byte':'')ge Chat$x" # ^ # 19th byte ``` ### PowerShell, 61 58 bytes -3 bytes thanks to @mazzy!! ``` "Stack Exchange {01}"-f'Chat','Chat - The Nineteenth Byte' # ^ # 19th byte ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fKbgkMTlbwbUiOSMxLz1VodrAsFZJN03dOSOxRF0HTCnoKoRkpCr4ZeallqSm5pVkKDhVlqSqc2FqJVLn//8A) [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 90 bytes ``` Y =1 X =GT(Y) ' - The Nineteenth Byte' OUTPUT ='Stack Exchange Chat' X END ``` [Try it online!](https://tio.run/##VcGxDkAwFAXQuf2Ku5XBILF2QWNDohLGkhcVUoM38PU1O@cO13KdRYz4maFzKSboxiZzCoUM1hPaPRATBfYoXyYlRTfafrTQamC3HjDP6l3YCJV3rDBJ09Yxfg "SNOBOL4 (CSNOBOL4) – Try It Online") The nineteenth byte here is the `1`. SNOBOL treats an empty string as `0`, and an empty right-hand assignment as an empty string. So when the byte is removed, the program assigns a value of `0` to `Y`, and the comparison `Y GT` (implicit 0) fails, hence `X` is assigned an empty value as well. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 27 bytes ``` ” -€€¥ŠteenthÄÁ” õs”‚‹ºŠÆÿ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcNcBd1HTWuA6NDSowtKUlPzSjIOtxxuBEkc3loMpA43PWqY9ahh56FdRxccbju8//9/AA "05AB1E – Try It Online") and [Try it without `s`](https://tio.run/##yy9OTMpM/f//UcNcBd1HTWuA6NDSowtKUlPzSjIOtxxuBEkc3gokDzc9apj1qGHnoV1HFxxuO7z//38A) ``` ” -€€¥ŠteenthÄÁ” # Compressed string " - The Nineteenth Byte" õ # push the empty string (s) # (swap back to the other string) ”‚‹ºŠÆÿ # push compressed string "Stack Exchange Chatÿ" # where ÿ is replaced by the string on the top of the stack ``` [Answer] # Java, ~~104~~ ~~83~~ 72 bytes ``` $->"Stack ExchangeA Chat".replaceAll("A(.*)","$1 - The Nineteenth Byte") ``` The nineteenth byte is `A`. *Saved 21 bytes thanks to [79037662](https://codegolf.stackexchange.com/users/89930).* *Saved 11 bytes thanks to [Olivier Grégoire](https://codegolf.stackexchange.com/users/16236).* [Try it online!](https://tio.run/##PU09a8MwEN3zKw6RQSqxoHPagBOSLV1cuoQOV0W25VxkYZ1CTclvd1Vi@pb3uHsfHd6w6M6XKaQvcgYMYYxwROfhZwEZ8z0ycqZb785wzV9Z8eB8c/oEHJqoZvMfutyoEzvSdfKGXe/1YRYvHzm@eiQ3UL9Oy2IjKkZzgf23adE3toRdiyz0YAOhsSWRFKXUT0qsxPIZCnhvLbw5b9lazy1sR7ZCTev/@WqMbK@6T6xD3mHystYYAo3SJyKlHtb74j79Ag) [Try it online (without the nineteenth byte)!](https://tio.run/##PU09T8MwEN37K05WBxs1lpiBSi2CDZYgFsRwuJfE6dWx4nNFhPrbg1Ej3vKe7t5Hj2es@sNxjvmLvQPHmBK8oA/ws4KC5Z4EpdB58Ac4la@uZfSh/fgEHNtkFvMf@tJos3i2TQ5O/BDs8yLu30t8c01uoXmY19VW1YLuCE/frsPQEjx2KMqOFBkd7Zi12ml7Y9RGrW@hgreO4NUHEqIgHewnIWXmu//1ekpCJztksbHMCAfdWIyRJx0yszFX62V1mX8B) [Answer] # [shortC](https://github.com/aaronryank/shortC), 54 bytes ``` Ds"Exchange Chat\x20- The Nineteenth Byte" AJ"Stack "s ``` [Try it online!](https://tio.run/##K87ILypJ/v/fpVjJtSI5IzEvPVXBOSOxJKbCyEBXISQjVcEvMy@1JDU1ryRDwamyJFWJy9FLKbgkMTlbQan4/39DAA "shortC – Try It Online") ### Without the Nineteenth byte ``` Ds"Exchange Chat\x0- The Nineteenth Byte" AJ"Stack "s ``` [Try it online!](https://tio.run/##K87ILypJ/v/fpVjJtSI5IzEvPVXBOSOxJKbCQFchJCNVwS8zL7UkNTWvJEPBqbIkVYnL0UspuCQxOVtBqfj/f0MA "shortC – Try It Online") `\x20` denotes a space character, removing the `2` we get `\x0` (null character) which in C is the string terminator. [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~68~~ 63 bytes -4 bytes thanks to Dominic van Essen. ``` cat(scan(,"",3+0004)) Stack Exchange Chat - The Nineteenth Byte ``` [Try it online!](https://tio.run/##K/r/PzmxRKM4OTFPQ0dJScdY28DAwERTkyu4JDE5W8G1IjkjMS89VcE5I7FEQVchJCNVwS8zL7UkNTWvJEPBqbIk9f9/AA "R – Try It Online") The 19th byte is the `4`. In the unaltered version, `scan` will read 7 words from the next line, and then print them. If you remove the `4`, `scan` will read only 3 words and then print them. [Answer] # Excel, ~~73~~ 70 bytes *Updated thanks to @EngineeringToast* ``` =LET(a,"Stack ",b,1,a&"Exchange Chat"&IF(b," - The Nineteenth Byte",)) ``` *Original* ``` =LET(s,"Sta",n,30--11,LEFT(s&"ck Exchange Chat - The Nineteenth Byte",n)) ``` Shows all characters as is; the left 19 characters if the 19th byte (-) is deleted. [Answer] # [Foo](https://esolangs.org/wiki/Foo), 46 bytes ``` "Stack Exchange Ch"at"at - The Nineteenth Byte ``` [Try it online!](https://tio.run/##S8vP//9fKbgkMTlbwbUiOSMxLz1VwTlDKbEEiBR0FUIyUhX8MvNSS1JT80oyFJwqS1L//wcA "Foo – Try It Online") [Try it online!](https://tio.run/##S8vP//9fKbgkMTlbwbUiOSMxLz1VwTkjsUQpsURBVyEkI1XBLzMvtSQ1Na8kQ8GpsiT1/38A "Foo – Try It Online") Output the quoted strings, which don't have to be closed. Other commands don't matter. [Answer] # [Haskell](https://www.haskell.org/), 63 bytes ``` main=putStr$take 119"Stack Exchange Chat - The Nineteenth Byte" ``` [Try it online!](https://tio.run/##LcY7CoAwDADQq4TiWrD@HVwUVxe9QCjBlGoRjaCnr4tveoyXp22LWudFWdVNm5rsX9zRhe64ZZYzEfQExrRqFrQexscyhpVgYBTQsDDB5AIJURCG/hVSMX4 "Haskell – Try It Online") The 19th byte is the center `1` in `119`. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes ``` "Stack Exc"~Print~##&["hange Chat"," - The Nineteenth Byte"] ``` [Try it online!](https://tio.run/##VYyxCsIwEEB3vyJcxakOjg6CqB1cREi30OEIlyZILyE9oSL216Po5PLgweMNKJ4GlGCxuN1S2xySnDndRUsO3Jfrh2Jct2hjM6VM4xgi792//tpTjsm4@rnZvrpSQAvam2omC/N3MlfVyoBH7kkdPQrUoNaq9aQugUmIWLw6PISgewM "Wolfram Language (Mathematica) – Try It Online") The 19th byte is one of the `#`s. `##` represents a sequence of all arguments, but `#` represents only the first argument. [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 61 bytes ``` ¯12⌽∊('ge Chat'{⍺ ⍵}' - The Nineteenth Byte'),'Stack Exchan' ``` ``` ¯12⌽∊ ⍝ Rotate right 12 {⍺ ⍵} ⍝ Concatenate , ⍝ Concatenate ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v//0HpDo0c9ex91dGmop6cqOGcklqhXP@rdpfCod2utuoKuQkhGqoJfZl5qSWpqXkmGglNlSaq6po56cElicraCa0VyRmKeOhe1zMFpCvFGAAA "APL (Dyalog Classic) – Try It Online") [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes ``` Stack Exchange Chat - The Nineteenth Byte ht.* hat ``` [Try it online!](https://tio.run/##K0otycxL/P@fK7gkMTlbwbUiOSMxLz1VwTkjsURBVyEkI1XBLzMvtSQ1Na8kQ8GpsiSVK6NET4sLKP3/PwA "Retina 0.8.2 – Try It Online") Explanation: Tries to insert the whole string, but if the 19th byte (the `a`) is deleted, then replaces everything after the `C` with `hat`. [Answer] # [Pxem](https://esolangs.org/wiki/Pxem), filename: 2 bytes + content: 64 bytes = 66 bytes. Thank you for commenting me that I need to use content of the file. ## Filename ``` .e ``` ## Content ``` Stack Exchange Cha.p.c.c.zt - The Nineteenth Byte.p.d.a.v.st.v.p ``` ## How it works * Every command substring consists of a dot and a char. * Every non-command substring is considered to be a command to push each of the string from backwards. + I.e. literals. * Filename is main routine; content is subroutine. * `.e` calls subroutine. * 19th byte on content is `.` of `.p` --- a command to pop each to putchar(). + Then the stack would be empty. * `.c` is dup() iff not empty; nop() otherwise. * `.z ... .a` is `while size<2 || pop!=pop; do ... ;done`. * `.d` is exit() on filename; `return` on content. * `.v` reverses entire stack. ## Links to TIO * [Try it online!](https://tio.run/##nRhrV@JG9Ht/xTAFMgOEAOKuyzhaRXdLq6xVu90VqCdCkGhIAgkKAvvXt/dOEgTXnj6Ox2Ry5859v4aeGQy@/UgGYegHNcO4tcPB5KbY9YbGh5/1S9@03puPT5Zr@FNrWPS9wJ7awdC4cbwbY2jaEdwuVopD211t/xBYIdGtiZgMzeCelEqVirCmvjcOyUn9@uDkRNYFC2e@RW6tsOu5/WxWfQHXoen2@J7Rsx4Md@I4pLKXLWez8eGzg8ufJU2zGI/ofkJAbfH0HF/52jJa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9VKog4owYrt@U57icq0y4b2fB3TK@Xq2@rO1pvqDlxc4IIEVlEzbjTTmtF177/bGS95kZ3wRfGOmMxPNEEYybaG74/nF1LTkvkPy4cNw5qNcwdeoHi3ZXfk6heTdjvj0YINGds8z2yXpCzHsgaErn4OGMH1cERo24WZJd7uttKlTqQbTm7x0J4gQSQMiB58@ws) [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` a="Exchange Chat" "#";a+=" - The Nineteenth Byte" print"Stack",a ``` The nineteenth byte is the quotation mark before the hashtag. Removing it turns line 2 into a comment. Works in Python 3 for 67 bytes, by adding brackets for the `print()` function. [Answer] # [Rust](https://www.rust-lang.org/), 63 bytes ``` ||print!("Stac{:.105}","k Exchange Chat - The Nineteenth Byte") ``` The nineteenth byte is the `0` in the formatting parameter. Removing it changes the format string in the closure to print 15 characters from the argument instead of up to 105. With the 19th byte: [Try it online!](https://tio.run/##KyotLvmflqeQm5iZp6GpUK2g8b@mpqAoM69EUUMpuCQxudpKz9DAtFZJRylbwbUiOSMxLz1VwTkjsURBVyEkI1XBLzMvtSQ1Na8kQ8GpsiRVSfO/poamNVftfwA "Rust – Try It Online") Without the 19th byte: [Try it online!](https://tio.run/##BcGxDkAwFAXQ3VdcndoEicHCRqwWfqCRRxvxIjwJwbfXOft5SJgYq/WsDR7o8L7b7llirXqx41NmefGpRC1or9FZngmNs4IUgyN0nkmIWBzqW0iZYLSpoi/8 "Rust – Try It Online") *Thanks to @ErikF for his inspiring [C solution](https://codegolf.stackexchange.com/a/221206/101806)* ]
[Question] [ ## Challenge Given a non-empty string *S* of length *L* consisting entirely of printable ASCII chars, output another string of length *L* that consists entirely of printable ASCII chars, but is not equal to *S*. For the purposes of this challenge, a printable ASCII char is one between U+0020 and U+007E, inclusive; that is, from (space) to `~` (tilde). Newlines and tabs are not included. For example, given `"abcde"`, some valid outputs could be: * `"11111"` * `"abcdf"` * `"edcba"` But these would be invalid: * `"abcde"` * `"bcde"` * `"abcde0"` ### Test cases ``` "asdf" "1111" " " "~~~~~" "abcba" "1" " " "~" " ~" "~ " " 0" "!@#$%^&*()ABCDEFGhijklmnop1234567890" " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" ``` ### Rules * You may assume the input consists entirely of printable ASCII chars. * You may not assume that the input does not contain all 95 printable chars. * You may assume the input contains at least one character and is less than 256 chars long. * The output must also consist entirely of printable ASCII chars. You could not, for example, output the byte \x7F for input `"~"`. * The output must be different than the input with probability 1; that is, you may generate random strings until one is different than the input, but you can't just output *L* random characters and hope it's different. * Newlines are disallowed in the output, but you may output one trailing newline which is not counted toward the string. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **the shortest code in bytes in each language wins.** [Answer] # [Python 2](https://docs.python.org/2/), 21 bytes ``` lambda s:`s`[:len(s)] ``` [Try it online!](https://tio.run/nexus/python2#PYzJDoIwFEXX7VeUOpS6EmdJmjj7EVZDEQgoIGkx7vh17JPEu7j3Dee9RMg2V0UYKWL8wAQXP49L1/Br@0mzPCaej5ERWVm9a5djpEVilxgpY2JdE@0I82/gUHMhugcYVTorLdJSZaKEYupZ2SCdbNWAbKrwHioAYAtzSLCG/PixdWfT6w9uw5HLt7v94Xg6p9njmRflq/Im09l8sVytAWMUM8owkxKMSsa@ "Python 2 – TIO Nexus") Takes the string representation of the input string and truncates it to the length of the input string. For a typical string, this puts it in `'` quotes and chops off the end: ``` abc -> 'abc' -> 'ab rep chop ``` Note that the new string starts with `'`. Let's show that the output always differs from the input. * If the input has no `'`, then the output starts with `'` and the input does not. * If the input contains a `'` and but no `"`, then Python will use `"` for the outer quotes, giving a first character `"` that's not in the input string. * If the input has both `'` and `"`, then the outer quotes are `'` and each `'` is escaped as `\'`. Wherever the first `"` appears in the input, it's shifted right by the initial `'` in the output and by any possible escaping. This means it cannot match with a `"` in the corresponding position in the output. Finally, note that quoting the input and possibly escaping characters always increases the number of characters, so truncating the output makes it the same length as the input. Note that it was crucial that Python adaptively switches to `"` in the second case. If it didn't do so, it would fail on the three-character input `'\'`. Or, any longer prefix of the [fix show string](https://tio.run/nexus/haskell#@5@ZW5BfVKLgkliSqOdWmpdckpmfx5WbmJmnYKtQUJSZV6KgopCWWaFQnJFf/v8/AA) using `'`. So, this method won't work for most languages. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes ``` ÇÈJ ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4/XCH1///CopKyiqqauoamlraOrp6@gaGRsYmpmbmFpZW1ja2dvYOjk7OLq5u7h6eXt4@vn7@AYFBwSGhYeERkVHRMbFx8QmJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVdU1tXUGhgA "05AB1E – TIO Nexus") ``` Ç # Convert to ASCII values È # is even? (0 is 48 and 1 is 49 therefore 0 -> 1 and 1 -> 0) J # Join ``` [Answer] # JavaScript (ES6), ~~37~~ ~~33~~ ~~36~~ ~~29~~ ~~26~~ ~~18~~ ~~21~~ 19 bytes ``` s=>s.slice(1)+ +!+s ``` [Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrV6FXnJOZnKphqKmtoK2oXfE/OT@vOD8nVS8nP10jTUPJUElTkwtNzACLWGJuUmpRTmJuQTE2DQbYjDGsAAr@BwA "JavaScript (Node.js) – TIO Nexus") -4 bytes thanks to ETHProductions -7 + -5 + -2 bytes thanks to CalculatorFeline -3 bytes thanks to Rick Hitchcock Moves the first character to the end and sets it to 0 if it's numeric and non-zero, and 1 otherwise. ### Explanation ``` s=> anonymous function with parameter s +s convert s to a number ! not (converts to boolean; relevant: 0->true,1->false) + convert !+s back to number (true->1, false->0) s.slice(1)+ prefix the rest of the string ␣ needed to avoid the +s combining ``` ### Proof Because the second char becomes the first, the third char becomes the second, etc. all chars would have to be identical. The last remaining char can only be a 0 or a 1, so the repeated char would have to be either 0 or 1. But any string of 0s produces a 1 at the end, and vice-versa; therefore, it is impossible to create an input that is equal to its output. -ETHProductions See edits for former versions and explanations. ``` f= s=>s.slice(1)+ +!+s console.log(f("000")) console.log(f("111")) console.log(f("001")) console.log(f("110")) console.log(f("~")) console.log(f("111111111111111111111111111111111111111111111111111")) console.log(f("Hello world!")) console.log(f("23")) console.log(f(" ")) console.log(f("1x")) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ~Ṿṁ ``` Output is a string of digits, commas and hypen-minus characters, whose first character will differ from the first character of the input string. [Try it online!](https://tio.run/nexus/jelly#@1/3cOe@hzsb/x9uf9S0JlLh4Y7tjxrmKPgmFiiUZKQq5GTmZesoFKcWJBYllqQqJFWCRFLTUlNTivX@/4/mUlBKLE5JU9IBMgyBAMxQgAAwuw4EwKzEpOSkRIhCiCqIPIQNoeoUoPoNwLSig7KKapyaloamo5Ozi6ube0ZmVnZObl5@gaGRsYmpmbmFJUShgmKMElCpmrqGppa2jq6evgFcgZW1ja2dvQPUAA9PL28fXz//gMCg4JDQsPCIyKjomJjYuPgEoOtSUtPS4TYUFhWXlJaVV1RWVdfU1ilxxQIA "Jelly – TIO Nexus") ### How it works ``` ~Ṿṁ Main link. Argument: s (string) ~ Map bitwise NOT over the characters c in s. This attempts to cast c to int and then apply bitwise NOT, mapping '0', ..., '9' to 0, ..., 9 (before ~), then -1, ..., -10 (after ~). For non-digits, the attempt fails, mapping c to 0. Ṿ Uneval, yielding a comma-separated string of integers in [-10, ..., 0]. The first character will be '-' if s starts with a digit and '0' if not. ṁ Mold; truncate the result to the length of s. ``` [Answer] # [Haskell](https://www.haskell.org/), 20 bytes ``` map$head.show.(<'M') ``` [Try it online!](https://tio.run/nexus/haskell#@59mm5tYoJKRmpiiV5yRX66nYaPuq675P8c2WilESUfJDYhDwAwwC0S4gbiJxSlpQMoQCICUAgQAWXUgAJJPSk5KBCkAyYLEQTSIqFMAqzcAkooOyiqqcWpaGpqOTs4urm7uGZlZ2Tm5efkFhkbGJqZm5haWBkqxXFy5iZl5CrYKQHf6KmgUlJYElxT55OmlaSrk/AcA "Haskell – TIO Nexus") Converts to a string of `F` and `T`. What matters is that the characters `F` and `T` converts to each other. This is done by checking if the character is less than `M` to get `True` or `False`, then taking the first character of the string representation. --- **[Haskell](https://www.haskell.org/), 23 bytes** ``` q '~'=' ' q _='~' map q ``` [Try it online](https://tio.run/nexus/haskell#@1@ooF6nbquuoM5VqBBvC2RzpdnmJhYoFP7PsY1WSixOSVPSUTIEAiClAAFAVh0IAOnEpOSkRJACkCxIHESDiDoFsHoDIKnooKyiGqempaHp6OTs4urmnpGZlZ2Tm5dfYGhkbGJqZm5haaAUy8WVm5iZp2CrALTcV0GjoLQkuKTIJ08vTVMh5z8A "Haskell – TIO Nexus") Replaces every character with `~`, except `~` becomes a space. [Answer] # Whitespace, 59 bytes Visible representation ``` NSSNSSSTSSSSSNSNSSNSSNSTNTSTTTTSSTNTTSNSNSTSSSNSSSNTNSSNSNN ``` What it does: For every character it reads it prints a space, except when it's a space, then it prints a @. Disassembly: ``` loop: push 32 dup dup dup ichr get sub jn not_32 dup add not_32: pchr jmp loop ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~6~~ 5 bytes ``` Qo!V! ``` [Try it online!](https://tio.run/nexus/matl#@x@Yrxim@P@/uoFBcYpCaoqhoToA "MATL – TIO Nexus") ### Explanation ``` Q % Implicitly input a string. Add 1 to each code point. o % Parity: 0 if odd, 1 if even. Note that '0' has ASCII code 48, so after % having added 1 it now gives 1. Similarly. '1' has ASCII code 49, so it % now gives 0. All other chars give 0 or 1. !V! % Convert each number to the corresponding char. Implicitly display ``` [Answer] # [Haskell](https://www.haskell.org/), 19 bytes An anonymous function which takes and returns a `String`. Use as `(map$(!!1).show.succ) "1111"`. ``` map$(!!1).show.succ ``` [Try it online!](https://tio.run/nexus/haskell#@59mm5tYoKKhqGioqVeckV@uV1yanPw/xzZaKURJR8kNiEPADDALRLiBuInFKWlAyhAIgJQCBABZdSAAkk9KTkoEKQDJgsRBNIioUwCrNwCSig7KKqpxaloamo5Ozi6ubu4ZmVnZObl5@QWGRsYmpmbmFpYGSrFcXLmJmXkKtgpAZ/oqaBSUlgSXFPnk6aVpKuT8BwA "Haskell – TIO Nexus") (Using @xnor's testing harness.) * For each character in the input string, increments the character, then converts that to character literal format, then takes the second character of the literal, which is the character just after the starting `'` quote. * For nearly all printable characters, this results in simply the incremented character. The exceptions are `&` and `~`, which instead give `\`, because their successors `'` and `\DEL` get escaped in character literals. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~9~~ 3 bytes ``` 5%n ``` [Try it online!](https://tio.run/##S8sszvj/31Q17////7rFhkbGJgA "><> – Try It Online") Takes input through the `-s` flag. Mods each digit with 5 and prints the integer, ending when the stack is empty. This results in only 5 possible output characters, 0-4. Each of those numbers when inputted will produce themselves plus 3, as the ASCII value of 0 is 48, which mod 5 is 3. While the output is reversed, no number is equivalent to another. Both 7, 9 and `a`(10) also work as they are not factors of 48 and print single digits. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` žQDÀ‡ ``` [Try it online!](https://tio.run/nexus/05ab1e#@390X6DL4YZHDQv//1d0UFZRjVPT0tB0dHJ2cXVzz8jMys7JzcsvMDQyNjE1M7ewNAAA "05AB1E – TIO Nexus") **Explanation** Replaces each char with the next printable ascii char, wrapping from tilde to space. ``` žQ # push a string of printable acsii chars (space to tilde) D # duplicate À # rotate left ‡ # translate ``` [Answer] # Bash + coreutils, 13 ``` tr \ -~ ~\ -} ``` Transliterates the characters to `~` (0x20 - 0x7e) with `~`, then to `}` (0x7e, 0x20 - 0x7d). [Try it online](https://tio.run/nexus/bash#@19SpBCjoFunUAcka///TyxOSeMyBAIuBQjgqgMBrsSk5KRELqAoVx2XQh1XnQJQ3oBL0UFZRTVOTUtD09HJ2cXVzT0jMys7Jzcvv8DQyNjE1MzcwtKAS0ExRgmoTE1dQ1NLW0dXT98ALmllbWNrZ@8A1ezh6eXt4@vnHxAYFBwSGhYeERkVHRMTGxefALQ9JTUtHW56YVFxSWlZeUVlVXVNbR0A). [Answer] # [V](https://github.com/DJMcMayhem/V), 7 bytes ``` íÁ/a g? ``` [Try it online!](https://tio.run/nexus/v#@3947eFG/USudPv//xOLU9IA "V – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/v#@3947eFG/USudHuP//8Ti1PSuAyBgEsBArjqQIArMSk5KZELKMpVx6VQx1WnAJQ34FJ0UFZRjVPT0tB0dHJ2cXVzz8jMys7JzcsvMDQyNjE1M7ewNOBSUIxRAipTU9fQ1NLW0dXTN4BLWlnb2NrZO0A1e3h6efv4@vkHBAYFh4SGhUdERkXHxMTGxScAbU9JTUuHm15YVFxSWlZeUVlVXVNbBwA) How does it work? Consider all strings consisting of printable ASCII. Every string must either 1) Contain alphabetic characters, or 2) Contain no alphabetic characters. So the way this program works is by first converting one non-alphabetic character into `'a'`, and then performing ROT13 on the input string. ``` í " Substitute: Á " A non-alphabetic character ([^a-zA-Z]) / " with a " the letter 'a' g? " Perform ROT13 on... " (Implicit) the current line. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 22 bytes ``` f(char*s){*s=65+*s%2;} ``` Takes a string pointer and modies the first char in place. [Try it online!](https://tio.run/nexus/c-gcc#@5@mkZyRWKRVrFmtVWxrZqqtVaxqZF37PzOvRCE3MTNPQ5OrmosTpEShODpWwVZBSaFOyZqLM02jWBNIFRQBFaZpKKkWK@kogERq/wMA "C (gcc) – TIO Nexus") [Answer] # [C (gcc)](https://gcc.gnu.org/), 20 bytes Saw Dennis's answer, thought of a 2 byte essential improvement. ``` f(char*s){*s^=*s/3;} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@mkZyRWKRVrFmtVRxnq1Wsb2xd@z8zr0QhNzEzT0OTq5qLE6RAoTg6VsFWQUmhTsmaizNNo1gTSBUUARWmaSipFivpKIBEav8DAA "C (gcc) – TIO Nexus") (Footer by Dennis.) Like the original, modifies the first character of the string in place, but xors it with its value divided by 3 (the smallest number that works. 2 fails on the single character `'U'` which gives 127, not printable.) [Answer] # [Python 2](https://docs.python.org/2/), 25 bytes ``` lambda s:`s<'T'`[0]+s[1:] ``` [Try it online!](https://tio.run/##PYrJDoIwFEXX8BUFB0A3gDOxibM/4A4xFIGAQmn6MMaNv15bTbyLe95w2KstGuqLHJ9FReokJQiCGJbWyYpDNxpC6AWReBZllSEv0DXAJWWP1nZ0jePcBkkCkPEWcQPDf6kyanMHY0XlMF5SqQiTQJqbuunJSKBf5PRWkSTJNSFKUF91V1T1Rl/flW2sOt3epT@wnfVmu9sfjkV5u1c1bZjnj8aT6Wy@kNoH "Python 2 – Try It Online") Anders Kaseorg saved a byte by extracting the first character from `True` or `False`. [Answer] ## Haskell, ~~30~~ 26 bytes ``` f ' '='~' f c=pred c map f ``` [Try it online!](https://tio.run/nexus/haskell#@5@moK6gbqtep86VppBsW1CUmqKQzJVum5tYoJD2PzcxM0/BVqGgKDOvREFFIV1BSUHRyNhE6T8A "Haskell – TIO Nexus") Replaces each char with its predecessor and space with tilde. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~19~~ 18 bytes ``` @(s)['',(s<66)+65] ``` [Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo1gzWl1dR6PYxsxMU9vMNPZ/moaSo6OjkiYXkJFYnJIGYRkCAYSlAAEQTh0IQNUmJSclQhVDVULVQHlQuk4BZo4BhKHooKyiGqempaHp6OTs4urmnpGZlZ2Tm5dfYGhkbGJqZm5hCVT5HwA "Octave – Try It Online") **Explanation:** ``` @(s) % Anonymous function taking a string s as input s<66 % A boolean vector with `1` for all characters below ASCII-66. (s<66)+65 % Add 65 to this, so that all elements that are 32-65 are now 66. % All other elements are 65 ['', ] % Implicitly convert the list of 65 and 66 to the letters A and B ``` [Answer] ## [CJam](https://sourceforge.net/p/cjam), 5 bytes ``` l)iA% ``` [Try it online!](https://tio.run/nexus/cjam#q/6fo5npqPo/Nq/W0Fjrf2JxShqXIRBwKUAAVx0IcCUmJSclcgFFueq4FOq46hSA8gZcig7KKqpxaloamo5Ozi6ubu4ZmVnZObl5@QWGRsYmpmbmFpYGAA "CJam – TIO Nexus") Converts the last character to its code point and takes that modulo 10. This is clearly different for non-digit characters in the last position. But the digits start at code point 48, so taking those mod 10 will shift them left cyclically and hence the last character is always changed. [Answer] # [Retina](https://github.com/m-ender/retina), ~~10~~ 6 bytes *4 bytes golfed thanks to @Neil* ``` T`p`~p ``` [Try it online!](https://tio.run/##K0otycxL/P8/JKEgoa7g/3@FOq7EpOSUYq6k4uyUPK4Crpys4rRsLmMjS5NSCwdlVa7a6hgjYxMA "Retina – Try It Online") This transliterates to `~`, `!` to , `"` to `!`, ..., `~` to `}`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 4 bytes ``` ®c v ``` [Try it online!](https://tio.run/nexus/japt#@39oXbJC2f//SoYGdQpKAA "Japt – TIO Nexus") ## Explanation: ``` ®c v ® At each char: c Convert to its ASCII value v Return 1 if divisible by 2, otherwise return 0 ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 10 bytes ``` ..@|i?2%)O ``` [Try it online!](https://tio.run/nexus/cubix#@6@n51CTaW@kqun//7@BoZGxCQA "Cubix – TIO Nexus") or [Watch it run!](http://ethproductions.github.io/cubix/?code=Li5AfGk/MiUpTw==&input=MDEyMzQ=&speed=10) For each char, prints `1` if the char has an even code point, `2` otherwise; `1` has an odd code point and `2` an even, so the output will never equal the input. ### Explanation This code corresponds to the following cube net: ``` . . @ | i ? 2 % ) O . . . . . . . . . . . . . . ``` The IP (instruction pointer) starts at the top-left corner of the far-left face, heading east. It follows this series of instructions: ``` i Grab a char-code from STDIN and push it to the stack (-1 if there is no more input). ? If the top item is negative, turn left and hit @ which ends the program. If it's positive (any printable ASCII char), turn right. The IP runs through a bunch of no-ops, then hits: ) Increment the top item. | Mirror the IP's direction horizontally (turns it around). ) Increment the top item again. The IP then wraps around again until it hits: ? The top item is positive, so turn right. 2 Push a 2 to the stack. % Push the modulus of the top two items (0 for even char-code, 1 for odd). ) Increment the result (now 1 for even char-code, 2 for odd). O Output as a number. The IP wraps back around to the i and the process starts again. ``` [Answer] # [Alice](https://github.com/m-ender/alice), 9 bytes ``` #oi/ t i@ ``` [Try it online!](https://tio.run/##S8zJTE79/185P1Ofq0Qh0@H//8TilDQA "Alice – Try It Online") ### Explanation The idea was taken from Martin Ender's CJam submission. The first character is taken as a code point, reduced mod 10, and moved to the end of the output. Since exactly one character was changed, permuting the characters cannot result in getting the same string back. ``` # skip next command o (skipped) i push first byte onto stack STACK: [97] / reflect to SE, switch to ordinal mode (implicit reflect to SW) i push remaining input onto stack as string (implicit reflect to NW) STACK: [97, "sdf"] o output top of stack (implicit reflect to SW) STACK: [97] t implicitly convert code point to decimal string, and extract last character (implicit reflect to NE) STACK: ["9", "7"] o output this last digit (implicit reflect to SE) i push empty string, since there is no more input to take (implicit reflect to NE) / reflect to S, switch to cardinal mode @ terminate ``` [Answer] # [Pushy](https://github.com/FTcode/Pushy), 1 byte ``` Q ``` **[Try it online!](https://tio.run/##Kygtzqj8/z/w////So5OzkoA "Pushy – Try It Online")** This converts the given string into list of ASCII character codes, indexes them (modular indexing) into the uppercase alphabet, then prints the result. Essentially, each character `n` is mapped to `chr(ord(n) % 26 + 65)`. You can use **[this program](https://tio.run/##Kygtzqj8/18p3tvITDU@8D@Q6ejkrAQA "Pushy – Try It Online")** to see how the mapping works. The output: * Will always be the same length as the input, as the characters are directly mapped into new ones. * Will always comprise only printable ASCII characters (as it only contains uppercase letters) * Will always be different to the input, as there is no possible input character `n` such that `chr(ord(n) % 26 + 65) == n`, as for this to be true there must be an integer `x` such that `26x = 65`, for which there is no solution. --- # 1 byte ``` q ``` **[Try it online!](https://tio.run/##Kygtzqj8/7/w////SolJyUoA "Pushy – Try It Online")** This answer is exactly the same, except that it maps to *lowercase* alphabet characters rather than *uppercase* alphabet characters. This is still valid as there is no possible input character `n` such that `chr(ord(n) % 26 + 97) == n`. [Answer] ## R, 40 bytes `function(s)substr(shQuote(s),1,nchar(s))` This uses the shell quoting function `shQuote` to place appropriate quotes around a string and escape quotes within the string (similar to @xnor's answer). Then take a substring that's as long as the original string (because the string might have multiple escaped characters, we need to take a substring of the correct length, so we can't just use `substring(...,3)`). `sQuote` is shorter, but converts `‘` to `‘‘’`. Another approach, using more 'core' R stuff is 46 bytes: `function(s)sub(".",letters[grepl("^a",s)+1],s)` Substitute the first character with 'a', unless it is 'a', then substitute it for 'b'. `sub` only substitutes the first match, so we don't need `^`. `letters` is constant and a slightly shorter way of doing `c("a","b")`. `grepl` returns a boolean, and adding 1 converts it to a number that indexes `letters`. The `^` is needed to correctly convert "ba". **Code to test** ``` x = function(s)substr(shQuote(s),1,nchar(s)) test = function(t){ t2 = x(t) t2!=t & nchar(t)==nchar(t2) } testStrings = c("a","b","ab","ba","aa", "'","'\"","\\\\",'"','""', '‘','’',"~","asdf", "1111"," ","~~~~~","abcba", "1"," ","~"," ~","~ "," 0", "!@#$%^&*()ABCDEFGhijklmnop1234567890", " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~") all(sapply(testStrings,test)) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 53 bytes Includes +1 for `-c` ``` ([(((()()()()){}){}){}()]({}())){{}(<({}[()()])>)}{} ``` This will decrement the first character unless it is a space, in that case it will increment the first character. [Try it online!](https://tio.run/nexus/brain-flak#@68RrQEEmhCoWV0LQRqasRogEigCpGyA7GiQfKymnWZtde3//wqJScn/dZMB "Brain-Flak – TIO Nexus") ``` ([(((()()()()){}){}){}()] ) # Push: input + 1 != 33 on top of... ({}()) # input + 1 {{}(< >)}{} # If (input + 1 != 33) ({}[()()]) # Push: (input + 1) - 2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ^1Ṿ€ ``` Outputs a digit string. No output character will be equal to the corresponding input character. [Try it online!](https://tio.run/nexus/jelly#@x9n@HDnvkdNa/4fbgeSkQoPd2x/1DBHwTexQKEkI1UhJzMvW0ehOLUgsSixJFUhqRIkkpqWmppSrPf/fzSXglJicUqakg6QYQgEYIYCBIDZdSAAZiUmJSclQhRCVEHkIWwIVacA1W8AphUdlFVU49S0NDQdnZxdXN3cMzKzsnNy8/ILDI2MTUzNzC0sIQoVFGOUgErV1DU0tbR1dPX0DeAKrKxtbO3sHaAGeHh6efv4@vkHBAYFh4SGhUdERkXHxMTGxScAXZeSmpYOt6GwqLiktKy8orKquqa2TokrFgA "Jelly – TIO Nexus") ### How it works ``` ^1Ṿ€ Main link. Argument: s (string) ^1 XOR each character c in with 1. This attempts to cast c to int, mapping '0', ..., '9' to 0, ..., 9. For non-digits, the attempt fails, mapping c to 0. After XORing with 1, we get 1, 0, 3, 2, 5, 4, 7, 6, 9, 8 for '0', ..., '9', and 1 for all non-digits. Ṿ€ Uneval each; mapping 0, ..., 9 to '0', ..., '9'. This yields a character array, which is Jelly's string type. Note that no character is mapped to itself. ``` [Answer] ## PHP, ~~30~~ 27 ``` <?=strtr($a=$argn,$a,$a^1); ``` Changes every each char equal to the first char with the char that has the least significant bit flipped. [Answer] # [Ruby](https://www.ruby-lang.org/), 20+1 = 21 bytes Uses the `-p` flag. ``` sub(/./){$&=~/1/||1} ``` [Try it online!](https://tio.run/nexus/ruby#U1YsKk2qVNAt@F9cmqShr6evWa2iZlunb6hfU2NY@/9/YnFKGpchEHApQABXHQhwJSYlJyVyAUW56rgU6rjqFIDyBlyKDsoqqnFqWhqajk7OLq5u7hmZWdk5uXn5BYZGxiamZuYWlgZcCooxSkBlauoamlraOrp6@gZwSStrG1s7eweoZg9PL28fXz//gMCg4JDQsPCIyKjomJjYuPgEoO0pqWnpcNMLi4pLSsvKKyqrqmtq6wA "Ruby – TIO Nexus") Replaces the first character in the input with a `0` if it is `1`, or `1` otherwise. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` {¬Ṣ|∧Ịh}ᵐ ``` [Try it online!](https://tio.run/nexus/brachylog2#ASYA2f//e8Ks4bmifOKIp@G7imh94bWQ//8iSGVsbG8sIFdvcmxkISL/Wg "Brachylog – TIO Nexus") ### Explanation This replaces all chars by a space, except spaces which it replaces with `"0"`. ``` { }ᵐ Map on each char of the Input ¬Ṣ The Input char is not " ", and the Output char is " " | Or ∧Ịh The Output char is "0" ``` [Answer] # PHP<7.1, 31 Bytes ``` for(;~$c=$argn[$i++];)echo$c^1; ``` [Try it online!](https://tio.run/nexus/php#s7EvyCjgUkksSs@zzcrPzNMoSsxLT9VQUlDSUapT0tS05kpNzshXACvQU4rJU7L@n5ZfpGFdp5JsCxaMVsnU1o611gQpU0mOM7T@//9rXr5ucmJyRioA "PHP – TIO Nexus") ]
[Question] [ Write a function or program that takes two words as input and outputs variants of the popular English tongue-twister "How much wood would a woodchuck chuck if a woodchuck could chuck wood?". The output will use the first word four times * How much `wood` would a `wood`chuck chuck if a `wood`chuck could chuck `wood`? and the second word four times * How much wood would a wood`chuck` `chuck` if a wood`chuck` could `chuck` wood? with the rest of the output being the same for any inputs. * `How much`wood`would a`woodchuckchuck`if a`woodchuck`could`chuckwood`?` The input and output can be in any format that your language reasonably recognizes as dealing with strings of text. The output must be exactly in the indicated format, including capitalization, spaces and lack thereof, and the ending question mark. An optional trailing newline is acceptable. Ideally your code will handle input containing any printable ASCII characters. However, it is permitted to restrict the input to reasonable subsets of printable ASCII; just indicate this in your answer. Handling larger character sets is of course fine. Example input-output pairs: ``` "wood", "chuck" "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" "ground", "hog" "How much ground would a groundhog hog if a groundhog could hog ground?" "bar", "keep" "How much bar would a barkeep keep if a barkeep could keep bar?" "money", "belt" "How much money would a moneybelt belt if a moneybelt could belt money?" "rain", "fall" "How much rain would a rainfall fall if a rainfall could fall rain?" "hair", "cut" "How much hair would a haircut cut if a haircut could cut hair?" "green", "house" "How much green would a greenhouse house if a greenhouse could house green?" "jabber", "wock" "How much jabber would a jabberwock wock if a jabberwock could wock jabber?" "pine", "apple" "How much pine would a pineapple apple if a pineapple could apple pine?" "Rob", "Lowe" "How much Rob would a RobLowe Lowe if a RobLowe could Lowe Rob?" "code", "golf" "How much code would a codegolf golf if a codegolf could golf code?" "fish", "" "How much fish would a fish if a fish could fish?" "", "fish" "How much would a fish fish if a fish could fish ?" "", "" "How much would a if a could ?" " ", " " "How much would a if a could ?" "would a", "how much" "How much would a would a would ahow much how much if a would ahow much could how much would a?" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins. Answers are welcome in all languages, even if some other language can do it in fewer bytes. (Inspired by [this meme](https://www.facebook.com/movieweb/photos/a.10150200043617199/10157150855317199), which uses one input pair better than this rigid pattern does....) [Answer] # [Python 3](https://docs.python.org/3/), ~~70~~ 67 bytes ``` "How much {0} would a {0}{1} {1} if a {0}{1} could {1} {0}?".format ``` [Try it online!](https://tio.run/##RU7NCsIwDL77FCGnTYpMvAni1XeoO4x2tUXXjK5lyNiz1zUKHsL3R5JvfEdL/pTN5Z7xRjMMSVlYmhVmSi8NXeHLcYUyzvy14piTZr3iwVAYupg32DaDnsB5kBJnIo0CUNmkntgKiUUxeYS@9yjQUpp6dn4v2fs2wbY97wDG4HysTLXn03WdPw "Python 3 – Try It Online") I mean, if the shoe fits.. *Thanks to **manatwork** for catching a typo* *Thanks to **Remco Haszing** for the excellent -3 bytes idea* I am running off of the assumption that this would still be a valid submission (because man, it's too cool not to try). If OP could clarify whether this is acceptable (because I haven't *written* a function, per se), that would be appreciated. Update: Blessing received, all is good :) --- **Previous version:** ``` lambda a,b:f"How much {a} would a {a+b} {b} if a {a+b} could {b} {a}?" ``` [Answer] # T-SQL, 82 bytes ``` SELECT'How much '+w+' would a '+w+c+' '+c+' if a '+w+c+' could '+c+' '+w+'?'FROM t ``` Input is taken from pre-existing table \$t\$ with columns \$w\$ and \$c\$, [per our IO rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). One byte longer, but for some reason slightly more pleasing: ``` SELECT REPLACE(REPLACE('How much 1 would a 12 2 if a 12 could 2 1?',1,w),2,c)FROM t ``` This version works on a subset of inputs that *don't* include the numeral `2` in the first word \$w\$. Because I'm in SQL, I can pre-load all examples into the table, and run them all at once: [![enter image description here](https://i.stack.imgur.com/G31Jp.png)](https://i.stack.imgur.com/G31Jp.png) [Answer] # [Bash](https://www.gnu.org/software/bash/), 50 bytes ``` echo How much $2 {would,$1\ if}\ a\ $2$1 could $@? ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I1/BI79cIbc0OUNBxUihujy/NCdFR8UwRiEzrTZGITEGKKpiqJAMElZQcbD///9/ckZpcvb/8vz8FAA "Bash – Try It Online") -5 bytes due to help from comments below. [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~33~~ ~~31~~ ~~30~~ 29 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) -1 thanks to [recursive](https://codegolf.stackexchange.com/users/527/recursive)! ``` ¢èO∩sP↑å♥|1╧ì}ò♂xb■δå«█Γ╨╦►Q² ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=9b8a4fef73501886037c31cf8d7d950b7862feeb86aedbe2d0cb1051fd&i=wood%0Achuck%0A%0Acode%0Agolf%0A%0A%22%22+%22fish%22%0A%0A%22fish%22+%22%22%0A%0A%22%22+%22%22%0A%0A%22++%22+%22+++++%22%0A%0Awould+a%0Ahow+much&a=1&m=1) Push each component to the stack in reverse order, then join all with spaces. ### Unpacked (35 bytes) and explanation: ``` X'?+;`IM'`x;+Y`~^$`,y`75\`x`Q)("`LJ X Set register X to the first word "wood" '?+ Append a question mark, popping from the input stack "wood?" ; Peek from input stack and push to main stack "chuck" "wood?" `IM'` Literal "could" "could" "chuck" "wood?" x;+Y Peek register x. Peek input. Concatenate. Set register Y. "woodchuck" "could" "chuck" "wood?" et cetera, ad nauseam LJ Listify the stack and join with spaces Implicit print ``` Everything between `` is compressed string literal. That comma is vital. The last time I read from the input stack, I must pop rather than peek to avoid an extra "chuck" on the end of my output. You'll notice that I put both inputs on the same line for a few test cases, and that they're in reverse order. This is necessary in order to take empty strings or strings of spaces as input. ### ~~27~~ 26 bytes with restrictions on input ``` å▓Zf╢7)╪♪²p╞8ó╪l▼]<¡REïSèΣ ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=86b25a66b63729d80dfd70c638a2d86c1f5d3cad52458b538ae4&i=wood%0Achuck%0A%0Acode%0Agolf%0A%0A%22%22+%22fish%22%0A%0A%22fish%22+%22%22%0A%0A%22%22+%22%22%0A%0A%22++%22+%22+++++%22%0A%0Awould+a%0Ahow+much&a=1&m=1) Just like [@dzaima's SOGL](https://codegolf.stackexchange.com/a/190327/73884), this will fail if the first input contains the lowercase letter 'y'. Pushes the string "How much b would a by y if a by could y b?", then makes a pair of replacements. [Answer] # JavaScript, 70 bytes Boring! ``` a=>b=>`How much ${a} would a ${a+b} ${b} if a ${a+b} could ${b} ${a}?` ``` [Try it online!](https://tio.run/##RYo7DoAgEESvQogFxOgN0NZjuC7gD12jIoXx7PhpbOZl3swAB2y49suezaRNtCqCKhpV1BUFNnnsWHLCxQJ5pxm8JW2uB0/09hf47Z9@/2UdkeaNnMkdtcIKHog0l4Jj53HkUsYb) Mildly less boring! ``` a=>"How much 0 would a 01 1 if a 01 could 1 0?".replace(/\d/g,x=>a[x]) ``` [Try it online!](https://tio.run/##JchBDoIwEADAr2z21CYI7QOKV/@AHDbbFtDKErCW39dEb5N50IcO3pftfVnFhxpdJdfjTQq8Ms9goEhOHgiMBQtL/It/acFcsd3DloiD6u6@m5rT9TSco64s6yEptEkmFdWARcRjgzxnfuKodf0C) [Answer] # [SOGL](https://github.com/dzaima/SOGLOnline), ~~32~~ 30 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ^.](9V;⅜‛°@Ε¬tπs%.½Ω‘⁽ b,ŗ y,ŗ ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=JTVFLiU1RCUyODlWJTNCJXUyMTVDJXUyMDFCJUIwQCV1MDM5NSVBQ3QldTAzQzBzJTI1LiVCRCV1MDNBOSV1MjAxOCV1MjA3RCUyMGIlMkMldTAxNTclMjB5JTJDJXUwMTU3,inputs=d29vZCUwQWNodWNr,v=0.12) The first input can't contain the letter `y`, which seems to leave a reasonable subset of ASCII (and unicode) left. `½ouiīZģ9Ο|ΧyΚ⅞ō÷Jeq(‚7‘` is a compressed string of `"how much b would a by y if a by could y b?"` (characters chosen so the required words are all in the top 512 words of the dictionary which compress better), then `b` is replaced with the 1st input and `y` with the 2nd. [Answer] # ZX Spectrum Basic, 87 bytes Just for completeness, straightforward implementation: ``` INPUT a$,b$: PRINT "How much ";a$;" would a ";a$;b$;" ";b$;" if a ";a$;b$;" could ";b$;" ";a$;"?" ``` Using the `IF` keyword (1 byte) golfes it down by 3 bytes, but breaks the "same capitalization" condition: ``` INPUT a$,b$: PRINT "How much ";a$;" would a ";a$;b$;" ";b$;" IF a ";a$;b$;" could ";b$;" ";a$;"?" ``` [Answer] # [R](https://www.r-project.org/), ~~90~~ ~~77~~ 76 bytes -13 thanks to Sumner18 -1 thanks to Giuseppe ``` function(x,y,`[`=gsub)2[y,1[x,"How much 1 would a 12 2 if a 12 could 2 1?"]] ``` [Try it online!](https://tio.run/##Nc2xDoIwEIDh3ae4dIKkDjBrXB2cXAmJbblCtfYI2BSeHluL292X/3LTpuF03LR36mPIFQtf@aN5nPvZy7JuVl41C2dXCvD2aoAKAnnbgYCqhhqMzpP6YQ3VhbXtpgsWiDrGmRq8erHyEEWKKcILccz7mxyuUSTaT5ZJGBdBC2szDMKkG@X3oJ8QUzGQnzHTU0iJKQr0fzQahxHEONo9upOMcKOw74q6VPRkNSu3Lw "R – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), 59 bytes ``` {i,j->"How much $i would a $i$j $j if a $i$j could $j $i?"} ``` [Try it online!](https://tio.run/##VY7NCsIwEITP9imG4iGBWvQqWhERxGu9iYcYrV2bJqWmLVL67LH@grCwM98yw2bGKtKuFgqNMSeZVjKbgsW2JH0J8N4co@gjMXctBddR5G9Mg7ySKYbURyt1gujl8Ip@KPka@bo8KS38ziWVRi5IMzHFsizFffaujThabyDCxJRrIdMWRU@t0uz3FCMb3gpFlvnw@X58CPBPJgfO0Xmdc7E912dszfHmdpRjZUz2AA "Kotlin – Try It Online") [Answer] # [PHP](https://php.net/), 72 bytes ``` [,$a,$b]=$argv;echo"How much $a would a $a$b $b if a $a$b could $b $a?"; ``` [Try it online!](https://tio.run/##K8go@G9jXwAko3VUEnVUkmJtVRKL0susU5Mz8pU88ssVckuTMxRUEhXK80tzUhQSgUyVJAUgykyDcZLBMiDRRHsl6////5fn56f8T84oTc4GAA "PHP – Try It Online") Or: # [PHP](https://php.net/), 72 bytes ``` How much <?=![,$a,$b]=$argv,"$a would a $a$b $b if a $a$b could $b $a?"; ``` [Try it online!](https://tio.run/##K8go@P/fI79cIbc0OUPBxt5WMVpHJVFHJSnWViWxKL1MR0klUaE8vzQnRSFRQSVRJUkBiDLTYJxksAxINNFeyfr////l@fkp/5MzSpOzAQ "PHP – Try It Online") Input from command line, output to `STDOUT`. [Answer] # [JavaScript (V8)](https://v8.dev/), 72 bytes ``` (a,b)=>['How much',a,'would a',c=a+b,b,'if a',c,'could',b,a+'?'].join` ` ``` [Try it online!](https://tio.run/##bc7BDoIwDAbgu0@xWyFUziYGvfoOxISuOhkiNcDg8WfH0dBb/@9P044Wmnj03/m4nKKrYkZo8@pSw01W8wncAhLCKqF/GALkigqLFsG7bUXgRKARFXCFe9mJHxrTRJZhkv5Z9vLKXKYXRFvAbeA35Pn58Oct@TF5mPfU@UkfgT3SeNMdMkbR6CSMPw "JavaScript (V8) – Try It Online") The variable assignment actually saves 0 bytes, but I figured I'd keep it in just to make this *slightly* unique. [Answer] # [Rust](https://www.rust-lang.org/), 75 bytes ``` |a,b|print!("How much {} would a {0}{} {1} if a {0}{1} could {1} {0}?",a,b) ``` [Try it online!](https://tio.run/##fY29DsIgFIX3PsXpnSBhqLMxrr5GpcU2UjAVwkB5doRqHHun8/Pl3NW/XVYGSz8bxhEblNOjg8Ilb724b691Nq5ldLMBi5cTYkKwXg/oEbtUXDwlzOpni5Z7W1UJriTKCs/nfVkxCtYOJEBy8vJJ/JvvT7RpGf9z0g5j5R5WqwOsIgc1UIFqUKkm5Q8 "Rust – Try It Online") Using [this trick](https://codegolf.stackexchange.com/a/188625/85842), which let's you skip the formatting index once per item to format. Also using `print!()`, because it's one byte shorter than building a string with `format!()` and returning it. [Answer] # Applesoft BASIC, ~~77~~ 76 bytes ``` 1INPUTA$,B$:?"How much "A$" would a "A$B$" "B$" if a "A$B$" could "B$" "A$"? ``` The above may not look like proper BASIC, but Applesoft allows for a few shortcuts when using the `PRINT` statement: * Use of `?` in place of `PRINT` when entering the statement * Concatenation characters (either `;` or `+`) may be omitted * If the statement ends in a quoted string, the final quote may be omitted *Thanks, [Mark](https://codegolf.stackexchange.com/users/19365/mark)!* The line number is required, or the `INPUT` statement will cause an `?ILLEGAL DIRECT ERROR` [Answer] # [33](https://github.com/TheOnlyMrCat/33), 78 bytes ``` "How much "p1btpt" would a "ptpz2btp" "ptbtp" if a "ptpbtp" could "ptbtp" "ptp ``` [Try it online!](https://tio.run/##Mzb@/1/JI79cIbc0OUNBqcAwqaSgREmhPL80J0UhEShQUlBlBBRTAjHBdGYaVBzMSwYrhMmBhP///1@en5/yPzmjNDkbAA "33 – Try It Online") Takes the input as command-line arguments. ## Bonus: 91 bytes ``` "How much "p1bztp" would a "p1bztp2bztp" "p2bztp" if a "p1bztp2bztp" could "p2bztp" "p1bztp ``` [Try it online!](https://tio.run/##Mzb@/1/JI79cIbc0OUNBqcAwqaqkQEmhPL80J0UhESZgBBFVgjEy0zDkksE6lBBKwZL///@H0GBhAA "33 – Try It Online") Gives output resembling itself when given inputs `1bztp` and `2bztp` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ ~~35~~ ~~31~~ 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` “Howƒ×1€Þ a ÿ0€¬ a ÿƒˆ01?“T$ú‡ ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcMcj/zyY5MOTzd81LTm8DyFRIXD@w2AzENrwMxjk063GRjaA5WFqBze9ahh4f//0Url@fkpSjpKyRmlydlKsQA) or [verify all test cases](https://tio.run/##NY6xTsMwEIZf5eQ5Q/MEWRmYEFvUwXYujambixKMla1i6IyysCAk9j4BCxKWuvAWeZFwrtOb/u/Tf7qjQSqDy8sY3goB82kCUSzz8eOO/GUK7/n8eg6fICH8bDj@nq/xMv2dNnnBtccxD9/z8WvJlrIUnqgSmdCN03uxzaAUSvYs9ohd4gO1OLJRaJ@T6aVpWdTS2iQaaeKOdmth1yPGRkNuwKSepFIYS55uhzrTIgvZdXYtPZBicU9@ZU1VbOzI1knUZmhYJIgvRL5BCgAcIU5iT85WIK/feDg4zQvbfw). Or alternatively: ``` …a ÿªðì₁“Howƒ×2€Þ65€¬6ƒˆ52?“r‡ ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcOyRIXD@w@tOrzh8JpHTY2PGuZ45Jcfm3R4utGjpjWH55mZAqlDa8yOTTrdZmpkD5QuetSw8P//aKXy/PwUJR2l5IzS5GylWAA) or [verify all test cases](https://tio.run/##LY6hbsMwEIZfxTIOqtTSkIGCodGowHacxKubi5K6VlhW0AcIKZkmjQxMAXuDSbVUsrfwi2T2NSb3f//9d2foGFdyPvUpJf4yEpr2T7Mfvhhxv7dv9@Mmf37zw/sW7H1015U/T@5jsw7lNm3u499lvUpDu/XD55zMWUYtQE4TKioj9nSXZLRswdTRqqBEg7M20F7KBvEAteyDwaU@otEyVQcumNbIFVNxQJjjsk/KGteZTqLzyjiXMWJhudmoWgZmTaMfkRfggZ/BPlBAHvsl6AK5UF0VGHU8HXHRWAkJisSHaMHonDD8hCUHI0J69w8). -5 bytes thanks to *@Grimy*. Takes a list of two items, `wood` as first value and `chuck` as second. **Explanation:** ``` “Howƒ×1€Þ a ÿ0€¬ a ÿƒˆ01?“ # Push dictionary string "How much1 would a ÿ0 if a ÿ could01?", # where the `ÿ` are automatically filled with the (implicit) input-list, # implicitly joined together to a single string # i.e. ["wood","chuck"] → "How much1 would a woodchuck0 if a woodchuck could01?" T # Push 10 $ # Push the input-list and 1 ù # Pad the strings in the input-list with this 1 amount of leading spaces # ["wood","chuck"] → [" wood"," chuck"] ‡ # Transliterate the 10 ([1,0]) to these strings in the sentence # → "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" # (after which the result is output implicitly) …a ÿ # Push dictionary string "a ÿ", # where the `ÿ` are automatically filled with the (implicit) input-list, # implicitly joined together to a single string # i.e. ["wood","chuck"] → "a woodchuck" ª # Append this to the (implicit) input-list: ["wood","chuck","a woodchuck"] ðì # Prepend a space before each string: [" wood"," chuck"," a woodchuck"] ₁ # Push builtin 256 “Howƒ×2€Þ65€¬6ƒˆ52?“ # Push dictionary string "How much2 would65 if6 could52?" r # Reverse the values on the stack ‡ # Transliterate [2,5,6] to [" wood"," chuck"," a woodchuck"] in the string # → "How much wood would a woodchuck chuck if a woodchuck could chuck wood?" # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“Howƒ×1€Þ a ÿ0€¬ a ÿƒˆ01?“` is `"How much1 would a ÿ0 if a ÿ could01?"` and `“Howƒ×2€Þ65€¬6ƒˆ52?“` is `"How much2 would65 if6 could52?"`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 65 bytes ``` param($a,$b)"How much $a would a $a$b $b if a $a$b could $b $a`?" ``` [Try it online!](https://tio.run/##NcxBCsMgEAXQfU4xhKHTQvEGpdseoxMTUaoYTAcXoWe32liYxfz34a8xL2mzi/cFzW0vKycOZ@QrTpfxETME0RaQIUfxM3B9cYJ6zvyD/jVN@Xkfy2cYTmiAcowzAWkr@kUHWXapkbw7GLfZCj1RhyNJUEpR26nzVL4 "PowerShell – Try It Online") The only thing of note is that you have to escape the question mark because those can be valid parts of a PowerShell identifier [Answer] # VBA, 107 bytes ``` Function q(a,b) b=b&" " c="ould " q="How much "&a&" w"&c&"a "&a&b&b&"if a "&a&b&"c"&c&b&a&"?" End Function ``` Should run as VBScript too, I used two shortcuts: "ould " is repeating and "chuck" never appears without an additional space. [Answer] # [C#](https://visualstudio.microsoft.com/), 165 148 133 bytes ``` class P{static void Main(string[]a){System.Console.Write("How much {0} would a {0}{1} {1} if a {0}{1} could {1} {0}?\n",a[0],a[1]);}} ``` Thanks to [Andrew Baumher](https://codegolf.stackexchange.com/users/77057/andrew-baumher) for telling me about interpolated strings!! EDIT: Full class now added EDIT: Thanks to [Kenneth K.](https://codegolf.stackexchange.com/users/3505/kenneth-k) for giving me a few tips for shortening it EDIT: Thanks to Andrew again for telling me that using interpolated string is actually longer in this scenario. [Answer] # [Haskell](https://www.haskell.org/), 76 bytes ``` a?b=a++" "++b a!b="How much"?a?"would a"?a++b?b?"if a"?a++b?"could"?b?a++"?" ``` [Try it online!](https://tio.run/##Pcw9DoAgFAPg3VNg48YZyFsd3DzBA0GN/BiVcHzExa3tl3Tj@7De18qkFUsJASl1x71WGFMRIZsNxISSsl8Et9ycNGF3f4P5EG39Hgg18B7VmZ/5uaY4NF4seqzJO9QX "Haskell – Try It Online") First try, so I hope I didn't break any rules. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ŒPKŒP“µkþ¿µ‘ị“þ>Æƈ)taJṖ;ạʂ\4S%dñl»Ỵ¤ż”? ``` A full program accepting a list of two strings. **[Try it online!](https://tio.run/##AWAAn/9qZWxsef//xZJQS8WSUOKAnMK1a8O@wr/CteKAmOG7i@KAnMO@PsOGxogpdGFK4bmWO@G6ocqCXDRTJWTDsWzCu@G7tMKkxbzigJ0/////Wydncm91bmQnLCAnaG9nJ10 "Jelly – Try It Online")** ...Or (also a full program accepting a list of two strings) ``` ⁽4ṀDBịs€2ṭ€€⁶“þ>Æƈ)taJṖ;ạʂ\4S%dñl»Ỵ¤ż”? ``` **[Try it online!](https://tio.run/##y0rNyan8//9R416ThzsbXJwe7u4uftS0xujhzrVACoQatz1qmHN4n93htmMdmiWJXg93TrN@uGvhqaYYk2DVlMMbcw7tfrh7y6ElR/c8aphr/////2j19KL80rwUdR0F9Yz8dPVYAA "Jelly – Try It Online")** [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes ``` StringRiffle@{How,much,#,would,a,c=#<>#2,#2,if,a,c,could,#2,#<>"?"}& ``` [Try it online!](https://tio.run/##HcwxC8MgFATgPT/jCZleKWROrGPH0o6hg33RKom1BMVB/O3WFG657@CcDEY5GSzJqqf6CLv9vO9W602JfPUJXSSDDJOP24ISaWIjZwO2WH10pP9y0MjhAqWvt/YRZnbiWgj27M8idxmS9wsgkIm0QsEmL7k3WJX6QulK/QE "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 80 bytes ``` lambda n:'How much {0} would a {0}{1} {1} if a {0}{1} could {1} {0}?'.format(*n) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZ6tenp@foq6jnpxRmpytzpVmG/M/JzE3KSVRIc9KPSO/XCG3NDlDodqgVqE8vzQnRSERxK42rFUA4cw0BD8ZLA2WMai1V9dLyy/KTSzR0MrT/F9QlJlXopGmkaep@R8A "Python 3 – Try It Online") when in rome, use str format. **Edited** using squid's trick. [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~66~~ 65 bytes ``` x=>y=>$"How much {x} would a {x+y} {y} if a {x+y} could {y} {x}?" ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrqOAwoHQdnZptv8rbO0qbe1UlDzyyxVyS5MzFKorahXK80tzUhQSgWztylqFaiDOTINzk8GSIEGgUnul/9ZcAUDTSjTSNJTK8/NTlDQ1lJIzSpOzlTQ1kaSC8pNAMj755akgif8A "C# (Visual C# Interactive Compiler) – Try It Online") same as everyone else, except C#. -1 byte by using currying strat a=>b=>c instead of (a,b)=>c [Answer] # [R](https://www.r-project.org/), 95 bytes ``` function(a,b)cat("How much ",a," would a ",a,b," ",b," if a ",a,b," could ",b," ",a,"?",sep='') ``` [Try it online!](https://tio.run/##TYtBCoAgEEWvIrMZhbmCtO0aOiVK5UQlHt9EWrT58N7//2rBtlAyP0myduQNu0fDLFUdhaMCcgSqStkX5Qb5zjAyhZ/iMYGv7qcJ6F5Pi2ha0FhFFiTkWHjr5gU "R – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), 78 bytes ``` #define f(a,b)"How much "#a" would a "#a#b" "#b" if a "#a#b" could "#b" "#a"?" ``` [Try it online!](https://tio.run/##RYkxDsIwDEV3TmE5SyKFE3Rg5Rquk7SR3BhBowyoZw8tSGX5T/89vrJQmXo3IaZcIiRLfnR41wZL5RnQEELTKgHoOGbEHfvk9Bf87fhrhDfsuaywUC7WwfsCj7q@bLJzFFHf9CnBueHUrCH6SSUdcusf "C (clang) – Try It Online") Using stringification --- # [C (gcc)](https://gcc.gnu.org/), 85 bytes ``` f(a,b){printf("How much %s would a %s%s %s if a %s%s could %s %s?",a,a,b,b,a,b,b,a);} ``` [Try it online!](https://tio.run/##NUxLCoMwEN17imGgkEB6Ahfd9hpxYjQwOqKGLMSzp9PQ8obH@wyPnhNRrdF4N9hr29N6RoNvKbBkmuFxQJHMAbxKNXop/g21pqUvdF4xKH5s@7vqGCw@rcbC1YHuziOzoAMssnNA23ew5fMw2KQ@kIQRHU7C8Rvd9QM "C (gcc) – Try It Online") Thanks to @ErikF suggestion to use gcc, btw I've seen that clang accepts f(\*a,\*b){ // which is 2 Bytes expensive anyway Saved 2 thanks to @ceilingcat. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~56~~ 59 bytes ``` {∊'How much '⍺' would a '⍺⍵' '⍵' if a '⍺⍵' could '⍵' '⍺'?'} ``` [Try it online!](https://tio.run/##TdAxagMxEAXQPqdQN5WrHCBFGhsCBjsXkLTSSrG8I9YWwhhXBhMMa5LC50iVxmWOootsZpQE0ozm6QsNjIxh0uxkwHYc9@X1DFPMYp20E1CGG4iMKTRCVpXhE7ih6u3/O10fwV9@gwc4jLac3spwKZfrbF7Ox6@P@3J6Jy0Xj1Sfp7PlCBmxAQvaJb2CO1CyJ62MiYQ1dmZHVCZsib30HcnKEEhOen6qE0dtbwxnDtPGkF@kUobjjPXb6DtDkjEGjheoSE@YGRobzloMlmT9xpGo41GM2lEVdAghqPvdSJ33syr4Bg "APL (Dyalog Unicode) – Try It Online") Pretty straightforward dfn. Saves a byte by cutting `∊` if we're allowed to return an array of strings instead of a single string. 3 bytes added because I'd forgotten to add the question mark. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~41~~ 37 bytes ``` ⁾be,y“Ø[gœıJ9°m.OṚuHlh3Ƥ⁾$ɲ0øḲʂṇHẎṆȥ» ``` [Try it online!](https://tio.run/##AVcAqP9qZWxsef//4oG@YmUseeKAnMOYW2fFk8SxSjnCsG0uT@G5mnVIbGgzxqTigb4kybIww7jhuLLKguG5h0jhuo7huYbIpcK7////Indvb2QiLCJjaHVjayI "Jelly – Try It Online") A full program taking a pair of strings as its argument and printing the processed string. A monadic link could be formed by adding a `F` to the end (thanks to @JonathanAllan for pointing this out). I’ve now switched to using "b" and "e" as placeholders, inspired by [@dzaima’s SOGL answer](https://codegolf.stackexchange.com/a/190327/42248) so be sure to upvote that one too! This does mean that the first word can’t include the letter e. [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~44~~ 39 bytes ``` [`How Û2`U`Ùd a`N=¬V`if a`N`Öd`VU+'?] ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=W2BIb3cg2zJgVWDZAmQgYWBOPaxWYGlmIGFgTmDWAmRgVlUrJz9d&input=Indvb2QiCiJjaHVjayI) [Answer] # [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 116 bytes ``` : x 2over type ; : y 2dup type ; : f ." How much "x ." would a "x y ." "y ." if a "x y ." could "y ." "x ." ?"; ``` [Try it online!](https://tio.run/##TZDBDoMgDIbve4o/XHbaDh71sOteQxGGUQdBmPL0DgpGE0L7fYW0qdTWqcdHprDvNTZU@icsXDACDWoEVL03J0s8Gd56xey5AtsSYtV@6tEmDCRYDoO8Sk6vSin/fLEmNjW4M4h5cNfmh1pMy086hzkMt3GmeMXT3BYWZ9E9Q0y48nxkMEl2rSU3CmGKmvVXBJKdmFyRxCXPcJAcFnWtUp6lyW1pBaRVWU8s7X8 "Forth (gforth) – Try It Online") ### Code Explanation ``` \ x = output the first word : x \ start a new word definition 2over type \ copy the "first" word to the top of the stack and print it ; \ end word definition \ y = output the second word : y \ start a new word definition 2dup type \ copy the "second" word to the top of the stack and print it ; \ end word definition : f \ start a new word definition ." How much "x \ print "How much " followed by the first word ." would a "x \ print " would a " followed by the first word y ." if a "x \ print the second word followed by " if a " and then the first word y ." could "y \ print the second word, then " could " then the second word again ." "x ." ?" \ print a space followed by the first word, followed by "?" ; \ end word definition ``` [Answer] # [Lua](https://www.lua.org), 82 bytes ``` a,b=...print((('How much x would a xy y if a xy could y x?'):gsub('.',{x=a,y=b}))) ``` [Try it online!](https://tio.run/##JchBCoAgEADAr@xNBfEBgXTtG2qUkmVUiy7R2zeo2zAZHbPT3hpj9iNtl5RSDKXCiiFCg1owj@CgERCk6Vf4kqD1QnXziV4KI/TdrNNk/aOUYuZaysghYlhe "Lua – Try It Online") Full program, take input as arguments. Nothing special here. Hope that there's shorter version, but no obvious ways to shorten this at first glance. ]
[Question] [ *Inspired by [this comment...](https://codegolf.stackexchange.com/questions/61115/make-your-language-unusable#comment147104_61115)* *Thanks to users [Step Hen](https://codegolf.stackexchange.com/users/65836/step-hen), [Wheat-Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard), and [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for helping my solidify the specification of this challenge before posting it!* *This is the Cops' thread. For the Robbers' thread, go [here](https://codegolf.stackexchange.com/q/133177/31716)* --- In [this challenge](https://codegolf.stackexchange.com/q/61115/31716), you are tasked with running some code that makes it so that your language no longer satisfies our criteria of being a programming language. In that challenge, that means making it so that the language can no longer... * Take numerical input and output * Add two numbers together * Test if a certain number is a prime or not. This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge, where there are two different challenges with two different objectives: the *Cops* will try to write some code that makes the language *mostly* unusable, and the *robbers* will try to find the hidden workaround that allows the cops to recover their language. As a cop, you must write two snippets of code: 1. One that makes your language mostly unusable, e.g. by removing built-in functions for taking input/output and numerical operations. The more features you remove, the better. This code is **not** allowed to crash or exit. It should be possible to add code to the end of this snippet, and that code *will get evaluated*. And... 2. ...a snippet of code that takes two non-negative integers as input, adds them together, and outputs their sum. This snippet must still correctly function even after running the first snippet. When the two snippets are combined together, they must form a full program that adds two numbers, or define a function that adds two numbers. Ideally, this snippet should rely upon very obscure behavior, so as to be more difficult to find. You may choose any [standard method of input and output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top). However, you must reveal exactly which format (input and output) you are using. A robber cannot crack your answer unless they use the same format as you. After writing both of these snippets, you must post the first one as an answer, without revealing the second one. Your answer should contain all of the following information: * The *first* snippet (obviously not the second). * Language (including minor version, since most submissions will probably rely on strange edge-cases) * IO format, including whether it's a function or full program. Robbers *must* use the same format for their crack to be valid. * Any strange edge cases required for your answer to work. For example, *only runs on linux*, or *requires an Internet connection*. Obviously, this is slightly subjective, but if a cop has some extreme edge case that prevents it from being cracked, and then only reveals this after being safe, I consider this poor sportsmanship. A potential robber should have all information necessary to crack your answer *before* it is cracked. You do not need to reveal your byte count until your answer is safe. Here's an example. For the first snippet, you could submit the following Python 3 program: > > # Python 3 > > > > ``` > print=None > > ``` > > Takes input from STDIN and output to STDOUT > > > And then as your second snippet, you could write: ``` import sys a,b=int(input()),int(input()) sys.stdout.write(a+b) ``` This is valid because it will take two numbers as input, and output their sum even if you join the two snippets together, e.g. ``` print=None import sys a,b=int(input()),int(input()) sys.stdout.write(a+b) ``` However, this will be extremely easy for a robber to find a solution to. Since this would be very easy to crack, you could attempt to patch this particular approach like so: ``` import sys sys.stdout=None print=None ``` However, even this has a very easy workaround: ``` del print a,b=int(input()),int(input()) print(a+b) ``` As a cop, your goal is to make the hidden workaround as obscure as possible, to prevent the robbers from finding it. The *robbers* will look at one of your answers, and attempt to crack it. They may crack it by writing *any* valid snippet that could work as snippet 2 (adding two numbers together after the language is made mostly unusable). This does *not* have to be the same snippet as you originally intended. If a robber cracks your answer, they will leave a comment on your answer, and then you should edit it to indicate that it has been cracked. If your post is cracked, you should edit your answer to show the solution (snippet 2) that you originally intended. This isn't a *rule per se*, just a friendly suggestion to keep the game fun. You do not have to. If an answer remains uncracked for one whole week, you can edit in your second snippet, and indicate that your answer is now *safe*. If you do not edit it after the week is up, other users can still crack it until you do. If you do not reveal your second snippet, you cannot claim points for your answer, or call it safe. The winner of the cops' thread is the shortest safe answer *including both snippets*, counted in bytes, and this answer *will* be accepted after sufficient time has passed. You do *not* need to reveal your byte count until your answer is safe, since byte count is irrelevant to your score until your answer is safe. In the event that sufficient time has passed and no answers remain uncracked, the winner will be the answer that remained uncracked for the longest period of time. Have fun! # Rule clarifications * The first snippet must run correctly *without taking any input*. It may output whatever you like, and this output will be ignored - as long as after the snippet is done, the second snippet runs correctly. * The second snippet *must actually be executed* for your answer to be valid. This means an answer like ``` import sys sys.exit() ``` is not valid because it doesn't break the language. It simply quits. Similarly, entering an infinite loop is not valid, since the second snippet will never be executed. * After being safe, your score is the byte count *of both snippets*. * This goes back to *Please reveal any strange edge cases required for your answer to work*... Your submission must contain enough information *before* being revealed to be reproducible *after* being revealed. This means that if your answer becomes safe, and then you edit in: *Here's my answer. Oh ya, BTW this only works if you run it on Solaris, joke's on you!* your answer is invalid and will be deleted and not considered eligible for winning. * The second snippet is allowed to crash after outputting the sum - as long as the output is still correct (for example, if you choose to output to STDERR, and then you get a bunch of crash information, this is invalid). * You may not edit your code after submitting an answer. * You may not rely on cryptographic functions like encryption, hash functions, CSPRNGs etc. ### Snippet to find uncracked submissions: ``` <script>site='meta.codegolf';postID=5686;isAnswer=false;QUESTION_ID=133174;</script><script src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='//api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # Haskell, cracked by Christian Sievers ``` import Prelude(getLine,print) a=a ``` Full program, reading two integers (including negative ones) from stdin and writing to stdout. I've just disabled the Prelude so almost nothing is in scope, and then added a definition; further imports are syntactically invalid. I gave you `getLine` and `print` though. --- Edited to add my original solution. Christian's crack was different, but exploits the same basic features (you can get a surprising amount of computation done by accessing functions that have syntactic sugar, even when you can't call anything builtin directly or even name the types involved). ``` import Prelude(getLine,print) a=a (x:l)!0=x (x:l)!n=l!d[0..n] d[x,y]=x d(x:l)=d l x^y=[x..]!y x+y=f[0..y](x^y)(-((-x)^(-y))) f[]x y=y f _ x y=x f.g= \x->f(g x) f&0= \x->x f&n=f.(f&d[0..n]) x*y=((+x)&y)0 x%[]=x x%('-':s)= -(x%s) x%(c:s)=x*10+i c%s i c=l['1'..c] l[]=0 l(x:s)=1+l s main=do x<-getLine y<-getLine print((0%x)+(0%y)) ``` Which probably isn't super-golfed anyway, but here it is more readibly: ``` import Prelude(getLine,print) a=a -- List indexing (x : _) !! 0 = x (_ : xs) !! n = xs !! (sndLast [0..n]) -- sndLast [0..n] lets us decrement a positive integer sndLast [x, _] = x sndLast (_ : xs) = sndLast xs -- Pseudo-addition: right-operator must be non-negative x +~ y = [x..] !! y -- Generalised addition by sign-flipping if y is negative x + y = switch [0..y] (x +~ y) (-((-x) +~ (-y))) where switch [] _ empty = empty -- [0..y] is null if y is negative switch _ nonempty _ = nonempty f . g = \x -> f (g x) -- compose a function with itself N times composeN f 0 = \x -> x composeN f n = f . (composeN f (sndLast [0..n])) -- multiplication is chained addition x * y = composeN (+x) y 0 strToNat acc [] = acc strToNat acc ('-' : cs) = -(strToNat acc cs) strToNat acc (c : cs) = strToNat (acc * 10 + charToDigit c) cs charToDigit c = length ['1'..c] length [] = 0 length (_ : xs) = 1 + length xs main = do x <- getLine y <- getLine print (strToNat 0 x + strToNat 0 y) ``` [Answer] # [Python 2](https://docs.python.org/2/), [Cracked](https://codegolf.stackexchange.com/questions/133177/make-your-language-mostly-unusable-robbers-thread/133209#133209) *Implements addition as a named function* ``` import sys c="".join(open(__file__).read().split('\n')[4:]) if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1) f=lambda\ ``` [Try it online!](https://tio.run/##JY1PC8IgHEDvfgrxkAolFLVgsE@yDTOn9Bv@Q@2wS1/dFp3e5fFe2uorhktr4FPMFZetID0QItYIgcVkApPSgjNScpGNWhgXJTmojE6B8vHazxyBxcVUpvnpB4oPnB1FP87qoRcLq48h1w/lMZP/hUDAut9XYvez0e9cIAYHfs@eObKDU/65qAm1dutQd/8C "Python 2 – Try It Online") ## What does this do? For the purposes of helping you out a bit I'll explain what this does. This code opens the source file and checks if the remainder of the code fits the following criteria: * Does not contain the string `import` * Is made solely of the characters `&)(,.:[]a`cdfijmonrt~` If it fails either criterion the recursion limit is set to `1` meaning that any code you write will hit the recursion limit. There are no tricks here, I have written a solution that uses only these characters and no imports, I'm not doing anything subversive, but I will say that I think this will be pretty hard to crack. To save you some time here is a short list of useful things you cannot do with this restriction * `+` well duh, * `eval`/`exec` Wasn't going to let you get away with that * Numbers, They might be more useful than you think * String literals * `len` * `=`, No assigning variables * `>`,`<`,`==`. . . I have left you with no comparisons * `*`,`-`,`/`,`%`,`^`,`|`,`>>`,`<<` The only operators available are `~` and `&` * `__foo__`, None of those fancy double underscore methods are allowed. [Answer] # [Python 2](https://docs.python.org/2/), Cracked This is the fourth iteration of this answer. Each of the last answers has was cracked via reseting the recursion depth. *Implements addition as a named function* ``` import sys if set("".join(open(__file__).read().split('\n')[4:]))-set(' &)(,.:[]a`cdfijmonrt~'):sys.setrecursionlimit(1) for m in sys.modules:sys.modules[m]=None del sys;f=lambda\ ``` [Try it online!](https://tio.run/##TY2xDoMgFEV3v4I4VEhakjadbPyF/oAaauWRPgM8Aji49Nepbt3ucM65Ycsf8rdS0AWKmaUtVWhYgszrWi6EnlMAz5UyaEEpISNMmguZgsXMm8E3or@3oxCXw2nYSfCzbPtxes3a4OLIx/xtRLuH5U5EmNeYkLxFt/tXURmKzDH0x7V0pFcLqf3bvRu7J3moNNiDeZjOTu6tp6Eq5Qc "Python 2 – Try It Online") ## What does this do? For the purposes of helping you out a bit I'll explain what this does. This code opens the source file and checks if the remainder of the code is made solely of the characters `&)(,.:[]a`cdfijmonrt~` If it fails the recursion limit is set to `1` meaning that any code you write will hit the recursion limit. I've also disabled all of the modules, so you can't import anything. There are no tricks here, I have written a solution that uses only these characters and no imports, I'm not doing anything subversive, but I will say that I think this will be pretty hard to crack. To save you some time here is a short list of useful things you cannot do with this restriction * `+` well duh, * `eval`/`exec` Wasn't going to let you get away with that * Numbers, They might be more useful than you think * String literals * `len` * `=`, No assigning variables * `>`,`<`,`==`. . . I have left you with no comparisons * `*`,`-`,`/`,`%`,`^`,`|`,`>>`,`<<` The only operators available are `~` and `&` * `__foo__`, None of those fancy double underscore methods are allowed. # My solution So now that xnor has cracked it in a way I am sufficiently satisfied with I am going to reveal my solution ``` r,o:(o and f(~(~r&~o)&~(r&o),int(`r`[:r&~r].join([`dict()`[r&~r],`r&~r`,`dict([(r&~r,r&~r)])`[int(`~([]in[[]])`[[]in[[]]:])],`min`[[]in[[]]],`dict()`[~(r&~r)],`r&~r`]).format(r&o),int(`~([]in[[]])`[[]in[[]]:]))))or r ``` Surprise, surprise its a hulking pile of gibberish. Rather than break this down I'm going to go through the process of how I made this. I started with a pretty standard addition algorithm ``` r,o:(o and f(r^o,r&o<<1))or r ``` Then I used a bitwise trick for representing `^` with `|`,`&`,`~`. ``` r,o:(o and f((r|o)&~(r&o),r&o<<1))or r ``` I used another bitwise trick to get rid of the `|` ``` r,o:(o and f(~(~r&~o)&~(r&o),r&o<<1))or r ``` Now all thats left is the `<<`, shouldn't be too hard, right? Well get ready for a bumpy ride. To replace the bitshift I used strings to append a zero to the end of its binary representation ``` r,o:(o and f(~(~r&~o)&~(r&o),int(bin(r&o)[2:]+"0",2)))or r ``` This has a few problems but the primary one is *using addition*, so I worked around this by using a format instead ``` r,o:(o and f(~(~r&~o)&~(r&o),int("{}0".format(bin(r&o)[2:]),2)))or r ``` We are not allowed to use bin, so I used string formatting to convert to binary. ``` r,o:(o and f(~(~r&~o)&~(r&o),int("{0:b}0".format(r&o),2)))or r ``` Since string literals are forbidden I have to build the string `{0:b}0` out of parts made with back ticks and `join` them together. ``` r,o:(o and f(~(~r&~o)&~(r&o),int("".join(["{","0",":","b","}","0"]).format(r&o),2)))or r ``` The empty string is pretty easy, you can just do ``` `r`[:0] ``` The zeros were ``` `0` ``` and the `{:}` were all grabbed from dictionaries. ``` r,o:(o and f(~(~r&~o)&~(r&o),int("".join([`dict()`[0],`0`,`dict([(0,0)])`[2],"b",`dict()`[-1],`0`]).format(r&o),2)))or r ``` `b` seems pretty hard to get, its not in our character set, so how are we supposed to get an object that has a `b` in its `repr`? Well here's how: When you use `repr` on a builtin function you get something that looks like ``` <built-in function name> ``` And thats from where we'll get our `b`. ``` r,o:(o and f(~(~r&~o)&~(r&o),int("".join([`dict()`[0],`0`,`dict([(0,0)])`[2],`min`[1],`dict()`[-1],`0`]).format(r&o),2)))or r ``` Now all thats left are numbers, I only need -1, 0, 1, and 2 so here's how I represented them: ``` -1 = ~(r&~r) 0 = r&~r 1 = []in[[]] 2 = `~([]in[[]])`[[]in[[]]:] ``` 2 could actually be a byte shorter as ``` ```r&~r```.find(`r&~r`) ``` based on @Blender's suggestions in the comments, but I didn't think of this until after the fact. So we substitute these numbers in ``` r,o:(o and f(~(~r&~o)&~(r&o),int(`r`[:r&~r].join([`dict()`[r&~r],`r&~r`,`dict([(r&~r,r&~r)])`[int(`~([]in[[]])`[[]in[[]]:])],`min`[[]in[[]]],`dict()`[~(r&~r)],`r&~r`]).format(r&o),int(`~([]in[[]])`[[]in[[]]:]))))or r ``` And thats the crack. [Answer] # [Haskell](https://www.haskell.org/), [cracked by Ben](https://codegolf.stackexchange.com/a/133244/56433) ``` main=main-- ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM88WROjq/v9vxGUCAA "Haskell – Try It Online") This should be a full program reading two numbers from stdin and outputting the sum to stdout. Each full program starts by running the `main` function, but here `main` calls itself and causes an infinite loop. To make matters worse, a line comment is started with `--` directly behind the recursive call to prevent changing it to e.g. `main2` and then defining that to do the summation. --- **Intended solution:** ``` main=main--$() _ --$ _ = do x <- readLn y <- readLn print $ x+y ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM88WROjqqmhocsUrAGmFeAVbhZR8LgUQqFCw0VUoSk1M8cmDCFSiCxQUZeaVKKgoVGhX/v9vxGUCAA "Haskell – Try It Online") `--` starts a line comment *unless* it can also be parsed as part of an operator. (The syntax highlighting seems to be unaware of this fact.) `--$` is a valid infix operator which takes `main` as first argument and some dummy second argument `()`. It is then defined to ignore both arguments and to perform the required task instead. [Answer] # [C (gcc)](https://gcc.gnu.org/) [Cracked!](https://codegolf.stackexchange.com/a/133221/31957) ``` #define D(f)void f(void); D(printf)D(fprintf)D(putc)D(puts)D(getchar)D(putc)D(fputc)D(ferror)D(feof)D(read)D(fclose)D(fread)D(wr1te)D(fgets)D(fgetc)D(popem)D(gets)D(read)D(scanf)D(setbuf)D(execl)D(execlp)D(putchar)D(execle)D(execv)D(malloc)D(execvp)D(execvpe)D(exec)D(system)D(close)D(fwrite)D(open)D(free) int stdin; int main(){ //your code goes here...hehe } ``` [Try it online!](https://tio.run/##RZDNbsMgEITvfgqkXsyhjpL2lmtehC6LjWSzaBcnjao@uwP4J6dvdoDZEfDZAyzLh0XnA6pb6/SdvFWuLdDX5tZG9iE5nY8OFecEKySjxwSD4bfvdiIzcRVUnjEaWyYYSbCIzXjwOdU5J8nGmk8Rp3WBvJ8LmFDSBNPPXAT@Iow741ZjLVQt3MQ9czLjSLAb8RD7nZL7lFTXHjUf7Gu/XCestVE3@SuUJOvDtcrJ@NDqv@Z0etLMCsii6glFDcjYdd2AAzb/y3K@qK/vFw "C (gcc) – Try It Online") Input from STDIN and output to STDOUT. This runs without error. Hahaha this is quite evil. I've only tested it on TIO's gcc. Per usual, you must append your code after this snippet in order for it to work :) The comment is a mean one, don't listen to it. Tested on `gcc (GCC) 6.3.1 20161221 (Red Hat 6.3.1-1)`. Should work on any linux system. ## Original solution ``` #define D(f)void f(void); D(printf)D(fprintf)D(putc)D(puts)D(getchar)D(putc)D(fputc)D(ferror)D(feof)D(read)D(fclose)D(fread)D(wr1te)D(fgets)D(fgetc)D(popem)D(gets)D(read)D(scanf)D(setbuf)D(execl)D(execlp)D(putchar)D(execle)D(execv)D(malloc)D(execvp)D(execvpe)D(exec)D(system)D(close)D(fwrite)D(open)D(free) int stdin; int main(){ //your code goes here...hehe } void __attribute__ ((destructor)) dtor() { int a,b,c,d;a=b=c=0; struct FILE* z = popen("cat", "r"); #define q(x)for(;(c=getc(z))^32&&c^-1;)x=10*x+c-48; q(a);q(b); char*y=calloc(c=a+b,1); for(a=0;c;){y[a++]=(48+(c%10));c=c/10;} for(b=0;b<a/2;b++){d=y[b];y[b]=y[a-b-1];y[a-b-1]=d;} write(1,y,a); } ``` [Answer] # C (GCC on Linux) (cracked) Instead of using silly file-reading sandboxing techniques, we do it the proper way - with SECCOMP whitelisting! Your task: implement addition with input from STDIN and output to STDOUT. ``` #include <stdlib.h> #include <unistd.h> #include <sys/prctl.h> #include <linux/seccomp.h> #include <syscall.h> #include <stdio.h> void sandbox(); __attribute__ ((constructor(0))) int s() { close(0); close(1); close(2); prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT); } int main() { sandbox(); syscall(SYS_exit, EXIT_SUCCESS); } void sandbox() { // Your code here! } ``` [Try it online!](https://tio.run/##ZY9NSwMxEIbPza@IeEmgurbXipe4hx5KS7OCPYXd2WAH0qTkQ1akv33N1kpdPQy8PMw8zAt3bwB9f4sWTGo1fQyxNdjc75/IlSWLGY9Z@AjF0UM0Y2zQpq4IGsAdjv8uoDZ/9rMX3YDeHbY01LZtXMf4gihVx@ixSVErRRkDZ0P0CaLz7IFzTtFGGhinn2QCxgWd6eInzq5xPsTzo2yzVbKs8gixXm2m9BLUav1cKlltl6LKyycymA812m/5r58mlwpM7qTSHcYpLV@X2fgiRCnl@XjcYxAUBd255Cm4XHivvb4hp76fkfkX) ## WTF is this!? To help you in your insurmountable task I'll explain what this code does. `__attribute__ ((constructor(0)))` ensures the `s` function is run first. The function closes all open file descriptors for STDIN, STDOUT and STDERR. Then the program restricts itself with a strict SECCOMP whitelist, which limits your system calls to the following: ``` read(2) write(2) _exit(2) sigreturn(2) ``` Therefore you cannot open any new files (or basically do anything). We then come to main and call your code, nicely wrapped in the `sandbox` function. The `syscall(SYS_exit, EXIT_SUCCESS);` at the end is just to ensure the program exits cleanly - by default GCC will exit with `exit_group(2)` which is not allowed by the SECCOMP whitelist. This exiting function is called *after* your code is run. So you have no open file descriptors, and you can't open anything new. Impossible, right? ;) [Answer] # x86 16 bit real mode Assembly ([Cracked](https://codegolf.stackexchange.com/a/133710/31716)) ``` _main: call l cli hlt l: pop si xor ax, ax mov bp, cs mov es, ax mov di, 12 mov [di], si mov [di + 2], bp pushf mov bp, sp or word [bp], 256 popf ``` Easy if you know the trick. [Answer] # cQuents, [cracked by Mayube](https://codegolf.stackexchange.com/a/133388/65836) ``` #|1,1:A ``` This should be fairly easy, but you never know. The "problem" was that without `C` in your code, you got an error. Mayube's solution: ``` #|1,1:A+BC ``` Each item in the sequence is the first input plus the second times the third (aka 1) My solutions: ``` #1,1:A+B,C ``` The sequence cycles between the first input plus the second input, and the third input (1). The first item in the second is `A+B`. ``` #1,1:A+B+C-C ``` Similar to Mayube's solution - instead of multiplying `B*C`, just adds `C` and then subtracts it. [Try it online!](https://tio.run/##Sy4sTc0rKf7/X7nGUMfQyvH/fwA "cQuents – Try It Online") ### Explanation ``` #|1,1 Append 1 and 1 to the end of the user's input : Set mode to : (sequence 1: if given n, output nth term in sequence; if given no n, output whole sequence) A Each item in the sequence equals the first input ``` Currently, this program outputs `1`, since with no user input, the first input is the first `1` in the default input (`#`). [Answer] # Javascript, [Cracked](https://codegolf.stackexchange.com/a/133463/72421) This challenge builds off of [Grant Davis's](https://codegolf.stackexchange.com/a/133383/72421), but fixes the solution he had in mind (which creates an iframe and uses the iframe's `window`). The solution runs in the javascript console on chrome's `about:blank page`, and takes two `input()`s, adds them together, and `console.log`s the result. Put your code after: ``` d=prompt=console=document;new MutationObserver(s=>s.forEach(e=>{t=e.target;t.parentNode.removeChild(t)})).observe(d,{"childList":d, "subtree":d}) ``` First, we clobber `prompt` and `console` and set the shortcut `d`. Then, we create a mutation observer with a callback which removes every target mutated. We set that mutation observer to observe the document, and notify on `childList` and `subtree` modifications. Instead of the literal `true`, we use our shortcut to the truthy value `document` (the [spec](https://dom.spec.whatwg.org/#dictdef-mutationobserverinit) doesn't allow this, but chrome does). After I posted this, I realized a much more elegant clobber. My intended solution still works, but the crack posted does not: ``` h=document.querySelector("html");h.parentNode.removeChild(h); ``` [Answer] ## Perl 5, cracked by [Ilmari Karonen](https://codegolf.stackexchange.com/a/133665/9365) ``` $_=<DATA>; s/[+'{dPz|K.UD!_ iJ;o}e6tjWb7253k@%&Iq4l0AN:?\$8B`Yywn9^pfmZQTF"M#-]//g; eval; print@_,$!,pop,shift,<>,eval"@>",$\,@ARGV,eval"@$",$@,eval"@@",$,,eval"@,",$/ __DATA__ ``` Input is received on separate lines of `STDIN` and output is printed to `STDOUT`. All code goes after the `__DATA__` marker. This uses a similar method to [@WheatWizard's solution](https://codegolf.stackexchange.com/a/133198/9365) in that the code is parsed and unusable chars are removed. This has been tested on versions 5.8, 5.10 and 5.16, and requires no command-line flags. [Try it online!](https://tio.run/##K0gtyjH9/18l3tbGxTHE0c6aq1g/Wlu9OiWgqsZbL9RFMV4h08s6vzbVrCQrPMncyNQ420FVzbPQJMfA0c/KPkbFwikhsrI8zzKuIC03KjDETclXWTdWXz/dmiu1LDHHmqugKDOvxCFeR0VRpyC/QKc4IzOtRMfGTgckq@Rgp6SjEqPj4BjkHgYVUQGKOEDZDkC2DpStA2Trc8XHg1wZH8/1/78JlykA "Perl 5 – Try It Online") [Answer] # Python 3, cracked by zbw ``` import sys for mod in sys.modules.values():mod.__dict__.clear() 1+1 ``` All modlues have been deleted, which means there are no builtins available and not much else can be done. Output to STDOUT, input from STDIN. This is the second iteration of this answer after the previous one was broken by a trivial crack by adding a break statement. [Answer] # [APL (ngn-apl)](https://github.com/ngn/apl), cracked by [ngn](https://codegolf.stackexchange.com/users/24908/ngn) Made in cooperation with my colleague [Marshall](http://dyalog.com/meet-team-dyalog.htm#Marshall). Input through left and right arguments to `+`. I.e. your goal is to insert code after the the following, so that your last line reads `⎕←3+2` and outputs `5` to STDOUT. ``` +←-←−←⍴←≢←≡←⊥←⊤←⍟←○←⍳←⌹←~←∈←∊←⍷←<←≤←=←≥←>←≠←,←⍪←⌷←⌽←⍉←⊖←{}⋄⍣←∘ ``` [Try it online!](https://tio.run/##PY3NDgExFIX3nqLWQyJs8S7DiDRqOtFiIaxExs@ISBgb8b@xJZlYWHmTvki1Z8SiX056v3uuG7C83/S1dtRklTdPhWvL6Gk5PYMny9kNvGJ6sIznyA/LxctwhP0QnGGWGJbRYfcqSLaninQ0zMG7oyMB3/iZ4trWcDBU87GKLqjdabXcmFRyikRFe@J6HpWU@4QKUuvwVsPPpELBKfxS6ROnbrvLJA0YrbvYEJIyRvq80xJ/M0lNj/aosI7kPKu/ "APL (ngn-apl) – Try It Online") Works by setting all useful functions to `{}` which takes one or two arguments and returns an empty numeric list. Also sets `⍣` to just compose functions. --- ### Crack ``` +←{⌈/⍋⍺⍵1/0} ``` `⍺⍵1/0` replicate 0 by the left argument and the right argument and 1 `⍋` get the indices that would sort that (since all elements are zero, it gives 0 1 2…(a+b) `⌈/` the maximum value (a+b) [Answer] # [Python 2](https://docs.python.org/2/), Cracked This is the second iteration of an answer that has been cracked once by @HyperNuetrino using a method I had not expected. I've now patched it so hopefully the only solutions left will have to abide by the restrictions I intended. *Implements addition as a named function* ``` import sys c="".join(open(__file__).read().split('\n')[4:]) if set(c)-set(' &)(,.:[]a`cdfijmonrt~')or"import"in c:sys.setrecursionlimit(1) sys.modules['sys'],sys.modules['os']=None,None;del sys;f=lambda\ ``` [Try it online!](https://tio.run/##VY5BDoMgEEX3noK4KJBYkjZd2XiFXkCNtYDpGGAI4MJNr04xXXXzJ//NZP73e3qju@YM1mNIJO6xkl1dixXBMfTasWlawOhp4iLoWTEuojeQGB0c5f2tHXkFC4k6McnPx6DkxFkj2n6cn1ItsFp0IX0ox1D/UmpwRLYlSpT7oOUWIqAzYMvbC6@OhUW1GR17Wgwdmz@EhXQPdLo55K60OWrfl87M9qXmIecv "Python 2 – Try It Online") [Answer] # Java 8, [Cracked by @OlivierGrégoire](https://codegolf.stackexchange.com/questions/133177/make-your-language-mostly-unusable-robbers-thread/133364#133364) Here's my attempt. Pretty much, the idea is to just overload all the namespaces you can use to output (and reflect, I hope). Output is intended to sdout (System.out). ``` class java { public static void main(String[]s){ //there is no executable code in snippet one. //your code here. } class Class{} class Method{} class System{} class FileDescriptor{} class Logger{} class Runtime{} class Scanner{} } ``` Blacklisting is typically a worse approach than whitelisting, so I'm sure it's just a matter of time before someone comes up with an approach I didn't consider. [Answer] # Node.JS version 7.3.0 (Cracked by Dom Hastings) ``` var p=process,f;(_=>{var w=p.stdout.write,n='f'+(Math.random()*1e7|0),l=1 f=p.stdout.write=a=>eval(`(function ${n}(a){while(l&&((typeof a)[0]!='s'||'f'+a!=n));a=l?l="":a;w.apply(p.stdout,arguments);})`)(a)})(); ``` Place the second code block after the first. Disclaimer: the second code block will not function on its own (without being placed after the first). If this is not allowed however I can modify the second snippet. This is a full program. Output is `process.stdout` (STDOUT), input is `process.argv` (command line arguments) This is my first cops and robbers, hopefully this is a good challenge :) [Try it online!](https://tio.run/##XY9BTsMwEEX3OUVaoWYGQlqzQSKacgIOgBCio8QmQa5t2U6iKsnZTbtgw/ZL7z39Hx45NL538dHYVqY0ss8dOW8bGUKpavii43wbJ3JViK0dYjX5PsrSUKGKB3jj2FWeTWvPgPdCPi8HLDWJTP0DiOkoR9ZwAjWYJvbW5HezWYFxnrpeS9C7HUC8OGlVzvhx@NxQEYpluXV4QwaxZtKvmrbbF66nip3TF/irlOy/h7M0MWC94gmv3hUB6yzb79/t4PPmejDvpJdZSkmIJJ5@AQ "JavaScript (Node.js) – Try It Online") ## The challenge explained Generates a random variable `n` from 0 to 1e7. If you call write with the correct `n`, doesn't print anything but sets `l` to 0 which "unlocks" the write function, allowing you to print anything. If you try to call write with a non-string, sends you into an infinite loop. If you try to call write with anything other than the correct `n` while write is "locked", sends you into an infinite loop to prevent guessing. ## The intended solution Sneaks past the typeof that seemingly checks for strings only by using a Symbol, which also starts with s. This throws an error in the function resulting from the eval call because you can't add the string "f" to a Symbol. We catch the error and use regex to recover `n` from the stack trace, where it is in the function's name. Then we try to write `n` which doesn't print anything, but sets the "lock" variable `l` to 0 to "unlock" the write function. Now that the write function is unlocked we just print the sum. ``` try{f(Symbol())}catch(e){f(e.stack.match(/f(\d+)/)[1]) f(+p.argv[2]+ +p.argv[3]+"")} ``` [Answer] # [RProgN2](https://github.com/TehFlaminTaco/RProgN-2), [Cracked](https://codegolf.stackexchange.com/questions/133177/make-your-language-mostly-unusable-robbers-thread/133543#133543) by [Arnold Palmer](https://codegolf.stackexchange.com/users/72137/arnold-palmer) ``` "+-/*÷^"{²[[\=}; ``` Writes over all the math operators, with no way to restore them. In particular, it replaces them with a function that removes the top two items on the stack. [Try it online!](https://tio.run/##Kyooyk/P0zX6/19JW1df6/D2OKXqQ5uio2Nsa63/GykYK2j/BwA "RProgN 2 – Try It Online") ## Original Solution ``` {S]‘[L}`d={0RL}`i=«x=y=x{xd`x=yi`y=x}:y»`+= {S]‘[L}`d={0RL}`i=«x=y=x{xd`x=yi`y=x}:y»`+= { }`d= #Define a function, "d", which returns n-1 S #Convert the input to a stack, which, as a number, makes a stack of 1 - n. ]‘ #Duplicate the stack, and pop the top value off it. [ #Discard the popped'd value. L #Get the length of the stack, which now is n-1. { }`i= #Define a function, "i", which returns n+1 0R #Get the range of numbers between 0 and n. L #Get the length of that stack, which is n+1 « »`+= #Define a function, "+", which takes two numbers, and outputs their sum. We use «» here, because it localises references, instead of globalising them. x= #Set the first input to the value of "x", which by default, is x. y= #Ditto for y. x{ x}: #While x is truthy, which in this case, is non-zero. xd #Get x - 1 `x= #Set x to it. yi`y= #And set y to y + 1 y #Push y to the output. And we're done. ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/19JW1df6/D2OKXqQ5uio2Nsa625uKqDYx81zIj2qU1Isa02CALSmbaHVlfYVtpWVFekJAAZmQlAdq1V5aHdCdq2/40UjBW0/wMA "RProgN 2 – Try It Online") [Answer] ## Haskell, ~~161~~ 144 bytes, [Cracked](https://codegolf.stackexchange.com/a/135321/43037) by [BlackCap](https://codegolf.stackexchange.com/users/43037/blackcap) ``` {-#OPTIONS_GHC -fth -w#-} module M where ``` Input to STDIN, output to STDERR. Add to the end of the program. Edit: Intended to be compiled with no extra GHC arguments, just the normal `ghc --make prog.hs`. Edited again to lower the byte count. Have fun! [Answer] # [Mascarpone](https://github.com/catseye/Mascarpone), cracked by [Ilmari Karonen](https://codegolf.stackexchange.com/a/135776) ``` [ Make 'i' and 'z' print 'q' ]$ v ['q.]v* 'i<^ v ['q.]v* 'z<^ [ Disable some standard commands ]$ v[]v* '1<^ v[]v* '$<^ v[]v* '@<^ v[]v* '{<^ v[]v* '}<^ v[<:]v* '<<^ v[]v* 'v<^$ ``` Input is church numerals on stdio, using `i` for increment and `z` for zero. For instance, 2+3 would be: ``` iiziiiz ``` With a trailing newline Output should be a number on stdout, in the same format as on stdio. For example, if the answer is five you should output: ``` iiiiiz ``` (mascarpone has no concept of numbers) --- # Intended solution: ``` : '[/''/'i/'./' /':/',/'>/'!/']/* 'i<^ : '[/':/',/'>/'!/']/* 'z<^ : ,>! 'z. ``` It is not immediately apparent from the documentation, but as @IlmariKaronen stated in his crack, string literals in Mascarpone are actually syntactic sugar for pushing a sequence of characters. I deliberately wrote comments like `[this]$` to make it look like I am pushing a string and popping it immediately afterwards. A naive cracker might have tried something like `[:,>!]/*` to push a string, swap it with the interpreter, and interpret it. I also pretend to pop the interpreter I left on the stack with `$`, but `$` has already been redefined to a NOP. You are left with this interpreter on the stack, and you have to carry it with you trough the entire program; trough each character of every string. [Answer] # [Gforth 0.7.3 (TIO)](https://tio.run/#forth-gforth), 231 bytes [SAFE] This code redefines as useless some necessary output methods, as well as addition and something crucial for declaring functions. Good luck! ``` : . ; : dec. ; : u. ; : .r ; : u.r ; : d. ; : ud. ; : d.r ; : ud.r ; : emit ; : type ; : + postpone 2drop ; : ; + + + postpone exit reveal postpone [ ; ``` Input will be two signed integers taken from the top of the stack as function parameters. Output to STDOUT. So you should fix the damage done, and define a function that takes the top two values from the stack and prints the result as an integer (not a float) to STDOUT without additional output (no trailing space). Here's a [template](https://tio.run/##S8svKsnQTU8DUf@tFPQUrLmsFFJSkyGMUgilVwTlQegUqCSUToFJwxipuZklYEZJZUEqmKGtUJBfXFKQn5eqYJRSlF8AFrQGCmsjS6VWAPUVpZalJuYgBKMVrP//NzSAAwVdQyNjE1MzcwtLA4W0/wA), if your goal function is named `f`. ### Solution: > > **79 bytes** > > > > I actually removed the `immediate` keyword from the end of the redefinition of `;`, so it was necessary for an answer to include it at the start. The function I defined is mostly equivalent to the internal definition of `.`, but it doesn't print the space at the end, and the addition is performed first, by moving the numbers to the floating point stack and back. > > > > > > [Answer] # C# (.NET Core) [Cracked](https://codegolf.stackexchange.com/questions/133177/make-your-language-mostly-unusable-robbers-thread/133409#133409) by [Ilmari Karonen](https://codegolf.stackexchange.com/users/3191/ilmari-karonen) Also [cracked](https://codegolf.stackexchange.com/a/133412/42502) by [Joshua](https://codegolf.stackexchange.com/users/14306/joshua). ``` namespace System { class Console { static void Main() { //Your code goes here } } } ``` Reads the two values from stdin and writes the result to stdout. Tested on Windows with Framework Version 3, 4.6 and on [TIO](https://tio.run/##Sy7WTc4vSv2fl5ibWlyQmJyqEFxZXJKay1XNpQAEyTmJxcUKzvl5xfk5qWARiDgIFJcklmQmK5TlZ6Yo@CZm5mlowqWq/ysgAX39yPzSIoXk/JRUhfT81GKFjFSgjTDZWi4IWfvfhMuYCwA "C# (.NET Core) – Try It Online"). Here is the full program I had intended. ``` namespace System { class Console { static void Main() { var t = Reflection.Assembly.Load("mscorlib").GetType("System.Console"); var r = t.GetMethod("ReadLine"); int a = int.Parse((string)r.Invoke(null, null)); int b = int.Parse((string)r.Invoke(null, null)); var w = t.GetMethod("WriteLine", new[] { typeof(int) }); w.Invoke(null, new object[] { a + b }); } } } ``` [Try it online!](https://tio.run/##pZFBS8QwEIXv@RVDTwlqLnoTD@JBhF2QVfAgHtLsrEbTZMnEllL62@u0lT2UenIOE5jwvveYsXRhY8IhmArpaCzCU0sZK9EJ4LLeEMFdDBQ9TpN5PhZlk52FOro9bI0LUp2@ugEWVZsEGW5ghwePNrsY9C0RVqVv9SaavSwq4iDelYXS95if2yPKYs6if/0LdS3WuIm5eRRtMX9ERu3Q7DcurApcyGBYwK9@NIlQSsrJhXeV9EOo4xfK8O39OYxd/QEo/wMYIzfLyC/JZZwysxCb1zfoIPMO4kGykYJ@BdQs/LCBWH7ydie1gTPOybrTLXox9364EpfiBw "C# (.NET Core) – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), [cracked by Dennis](https://codegolf.stackexchange.com/a/133458) ``` {}' !$%&()*+,-./<=>?@[\]^`|~'':'*~; ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPlfXauuoKiiqqahqaWto6unb2NrZ@8QHRMbl1BTp65upa5VZ81laGSsYGJqpqCgrGCjq6uQmJKiUJKRWpyqkFeam5RaVKxQkp@eChQp@q@sEJlfWqSQnJ@SqgDkp@rp6f3/DwA) This *is* a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, after all, so why not try GolfScript? A valid solution should be a snippet that reads two integers off the stack, adds them together and returns the result on the stack. The catch is that it should still work even after the code above has redefined almost all of the [built-in GolfScript operators](http://www.golfscript.com/golfscript/builtin.html) to do abolutely nothing. At least I left `;` untouched, so you can still pop values off the stack. ;-) Your code should work on the standard GolfScript interpreter, as implemented e.g. on TIO (see link above). --- [Dennis' solution](https://codegolf.stackexchange.com/a/133458), like [my own](https://tio.run/##S8/PSStOLsosKPlfXauuoKiiqqahqaWto6unb2NrZ@8QHRMbl1BTp65upa5VZ81laGSsYGJqpqCgrGCjq6uQmJKiUJKRWpyqkFeam5RaVKxQkp@eChQp@q@kXF2WWKQer66jnl5QWpyhkKidpK6XnGxUq2Qd//8/AA), relies on the rarely used [feature](http://www.golfscript.com/golfscript/syntax.html) of GolfScript that allows interpolated Ruby code in double quoted strings. We use this feature to define a new addition operator that works exactly like the built-in `+` operator, and then call it. (One reason why the Ruby interpolation feature in GolfScript is so rarely used is that, awkwardly, the interpolated Ruby code is executed *during parsing*, and its output is cached by the GolfScript interpreter. Thus, if you e.g. have a string with interpolated Ruby code in a loop, the code will run only once *before the actual program starts* and thereafter always return the same value on every iteration of the loop. You can [work around that using string eval](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript#comment65711_31462) to defer parsing, but that makes the already awkward syntax even more ugly and verbose, and in any case, for this challenge I disabled the eval operator `~`, too. However, it turns out that [defining new built-in GolfScript operators](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript/133548#133548) is one thing this feature actually does quite nicely and cleanly.) [Answer] # Node.js v8.2.0, [Cracked by Dom Hastings](https://codegolf.stackexchange.com/questions/133177/make-your-language-mostly-unusable-robbers-thread/133586#133586) ``` let mess = ctx => f => new Proxy (f, { has: (t, p) => p in t || p in ctx , get: (t, p) => { let k = p in t? t[p]: ctx[p]; if (k instanceof Function) return ( function fetch (_k) { return mess (ctx) ( x => ( q => q instanceof Function ? fetch (q) : t (q) ) ( _k(x) ) ) })(k); return k; } }); with (mess (global) (x => x)) { dot = f => a => b => f(a(b)) ap = f => g => x => f (x) (g (x)) flip = f => x => y => f (y) (x) Const = a => b => a id = x => x num = n => n (x => x + 1) (0) log = console.log let x = flip (Const . id . id) , y = flip (Const . id . id . id) for (let i = 0; i < process.argv[2]; i++) x = ap (dot) (x) for (let i = 0; i < process.argv[3]; i++) y = ap (dot) (y) process.argv = []; logic = x => y => /* Your code here */; log . id . num ( logic (ap (dot) (x)) (f => z => (( y(flip (id) . id . flip (dot (id)) (f)) ) (Const (z))) (id) ) ); } ``` You are to implement the `logic` function. Input is the arguments provided (from stdin), output is whatever your function returns (is printed to stdout). --- My code [church encodes](https://en.wikipedia.org/wiki/Church_encoding) the numbers from the input. The rest of the code is just there to intimidate you. The mess function does some trickery to implement [point-free notation](https://en.wikipedia.org/wiki/Function_composition#Composition_operator) (`a . b == dot (a) (b)`), which I primarely use to add `. id .` to random places, which doesn't do anything, but will confuse anyone unfamiliar with functional programming. The transformation applied to the numbers before I pass them to the `logic` function is `x+1` and `y-1`, which adds up to 0, so it's another NOP to add to the obscurity. The intended solution was: ``` logic = x => y => f => z => x (f) (y (f) (z)) ``` [Answer] # [Inform 7](http://inform7.com/), [cracked by ppperry](https://codegolf.stackexchange.com/a/133934) ``` For reading a command: rule fails. [Your code here.] ``` The input should be typed by the player as an interactive command, e.g. `add 17 to 25` or `sum 17 25`. You're free to choose the exact form of the command that should be entered, as long as it includes two numbers. The sum of the numbers (e.g. `42`) should be printed in response to the command. The challenge, of course, is doing that while the entire ["reading a command"](http://inform7.com/learn/man/WI_18_33.html) activity is replaced by a no-op. There are probably several ways to solve this problem, but at least it should require some familiarity with the language. The one I came up with is actually quite simple, if a bit unexpected. I've tested my solution in the GNOME Inform 7 IDE, [version 6L38](http://inform7.com/download/release/6L38/), on Ubuntu Linux. The intended solution works on both the Glulx and the Z-machine back-ends, and should work on other recent versions of Inform 7, too. Note that (without a suitable work-around) the code above will cause the interpreter to busy-loop when it tries to read a command; the Z-machine interpreter seems to become completely unresponsive when this happens, and can't be stopped from within the IDE, so I recommend using Glulx for testing. [Answer] # CPython 3 (again), cracked by Sisyphus ``` import sys,os,functools def p(f,e,a,_=os._exit): if e == "c_call":_(1) sys.setprofile(p) ``` You can do anything you want -- as long as it isn't implemented in C. This means no `print`, no `input` -- all of those will hit the `_(1)` line and terminate. Input from STDIN with the numbers on two seperate lines, output to STDOUT. I wonder how long this is going to last ... Took me quite a while to find the second working snippet after coming up with this disabling trick. Explicitly specifying Cpython to avoid being cracked based non some alternative implementation of sys.setprofile. [Answer] # Java 8 ([Cracked](https://codegolf.stackexchange.com/a/133373/31716)) Second attempt. This time I invested two minutes of testing. ``` static { try { System.setIn(null); System.setOut(null); System.setErr(null); for (Method m : System.class.getMethods()) { m.setAccessible(false); } System.class.getMethod("getSecurityManager", new Class[0]).setAccessible(false); for (Method m : Class.class.getMethods()) { m.setAccessible(false); } SecurityManager mngr = new SecurityManager() { @Override public void checkPermission(Permission p) { if (p.getName().equals("createSecurityManager")) throw new SecurityException(); if (p.getActions().startsWith("read")) throw new SecurityException(); } }; System.setSecurityManager(mngr); // Your code goes here. } catch (Throwable t) { } } ``` Most things *shouuuld* be covered. [Answer] # Python 2 [cracked](https://codegolf.stackexchange.com/a/133217/12012) ``` import sys,hashlib c=open(__file__).read().split()[-1] if c!='#'and hashlib.sha256(c).hexdigest()!='e6400dd63733d10ec042e3c28033cfa85e1d25fbef80020810c354d7c942e843':sys.exit() # ``` [Try it online!](https://tio.run/##Lc5LCoMwFIXhuatIcaBCG655aFpwJaVITG6agFUxDnT1NoXOv59zlmPz88TOM3yWed1IPOLV6@jHMGSmmxecyr53YcS@r@iK2pYVjcsYtrJ63upXFhwxl67ICz1Z8g9p9JrJpjQV9bjb8MaYeFLYCABrG95ybmtAA4IhN0wB58ZpJbG2TLoBnQJgoGowXArbmntySvDike5R3H/rJD9PwTLZfgE) I'll preface this by saying this answer is a jerk move, intended as a lower-bound answer. --- Inspired by [Wheat Wizard's](https://codegolf.stackexchange.com/a/133198/6972) and [HyperNeutrino's](https://codegolf.stackexchange.com/a/133203/6972) answers. The snippet reads the source file and refuses to continue if the last whitespace-separated chunk of code does not sha256 into `e6400dd63733d10ec042e3c28033cfa85e1d25fbef80020810c354d7c942e843`. **EDIT**: Edited slightly in response to [this comment](https://codegolf.stackexchange.com/questions/133174/make-your-language-mostly-unusable-cops-thread/133210#comment326874_133210). The core problem does not change, any crack attempt is not invalidated. [Answer] # Java 8 [Cracked by *@OlivierGrégoire*](https://codegolf.stackexchange.com/a/133353/52210) I tried to make it as hard as possible! :) And, unlike the other Java answer so far, you'll have to follow the exact rules of the challenge, by placing it after this entire snippet (so no, you don't put your code in the `public static void main(String[] args)` method, you put it after the entire class. :) Good luck! I've added comments to show what is being restricted. ([Inspired by this post, which is less restrictive and beatiable with the same approach I could use for my answer.](https://codegolf.stackexchange.com/a/61124/52210)) ``` import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.FilePermission; import java.io.PrintStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class Main { // Put everything in a static block so it is run before the static main method // and any trailing (static) initializer-blocks: static { try { initializing(); } catch (final Exception e) { } } static void initializing() throws Exception { // Overwrite System.out, System.err and System.in: System.setOut(new PrintStream(new ByteArrayOutputStream())); System.setErr(new PrintStream(new ByteArrayOutputStream())); System.setIn(new ByteArrayInputStream(new byte[0])); // Enable reflection for System.out, System.err and System.in: final Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); final Class<?> fdClass = java.io.FileDescriptor.class; final Field outField = fdClass.getDeclaredField("out"); outField.setAccessible(true); modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL); final Field errField = fdClass.getDeclaredField("err"); errField.setAccessible(true); modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL); final Field inField = fdClass.getDeclaredField("in"); inField.setAccessible(true); modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL); // Replace existing System.out FileDescriptor with a new (useless) one: outField.set(null, new FileDescriptor()); // Replace existing System.err FileDescriptor with a new (useless) one: errField.set(null, new FileDescriptor()); // Replace existing System.in FileDescriptor with a new (useless) one: inField.set(null, new FileDescriptor()); // Disable reflection for System.out, System.err, System.in again: modifiersField.setInt(outField, outField.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(errField, errField.getModifiers() & ~Modifier.FINAL); modifiersField.setInt(inField, inField.getModifiers() & ~Modifier.FINAL); inField.setAccessible(false); errField.setAccessible(false); outField.setAccessible(false); modifiersField.setAccessible(false); // Overwrite the SecurityManager: System.setSecurityManager(new SecurityManager() { private boolean exitAllowed = false; @Override public void checkExec(final String cmd) { throw new SecurityException(); } @Override public void checkPermission(final java.security.Permission perm) { final String name = perm.getName(); // You're not allowed to read/write files: if (name.equals("setIO") || name.equals("writeFileDescriptor") || name.equals("readFileDescriptor") || ((perm instanceof FilePermission) && name.startsWith("/proc/self/fd/"))) { throw new SecurityException(); } // You're not allowed to overwrite the Security settings: if (name.equals("setSecurityManager") || name.equals("suppressAccessChecks")) { throw new SecurityException(); } // You're not allowed to use reflection anymore: if (name.equals("getModifiers") || name.equals("get") || name.equals("set") || name.equals("setBoolean") || name.equals("setByte") || name.equals("setChar") || name.equals("setShort") || name.equals("setInt") || name.equals("setLong") || name.equals("setFloat") || name.equals("setDouble") || name.equals("setFieldAccessor") || name.equals("setFieldAccessor")) { throw new SecurityException(); } // When you try to leave the current VM it will stop the program: if (name.startsWith("exitVM") && !this.exitAllowed) { this.exitAllowed = true; System.exit(0); } // You know what, nothing is allowed! throw new SecurityException("Mhuahahahaha!"); } }); } public static void main(String[] args) { // Overwritting all given arguments: args = new String[0]; // Exit the program before you can do anything! System.exit(0); } } // Your code goes below: ``` [Try it here.](https://ideone.com/HCdFsW) (ideone.com instead of TIO, since it doesn't seem to work there.. Testing has been done in the Eclipse IDE, but my intended solution does work if you use ideone.com) [Answer] # Jelly: CRACKED This will be insanely easy compared to Wheat Wizard's awesome Python answer, but here we go :P ``` “for c in code_page: if c in atoms:atoms[c].call=None”ŒVø<insert code snippet here> ``` The sha256 hexdigest of my workaround solution, including the first snippet, is `cfeb1e193ad77f66f039c0d6a792a3e4c311490f6412698e019ca1fae10c0e0a`. # Note You may not have any newlines in the code except for strings otherwise this code will not even be run, which defeats the purpose of this challenge. # [Cracked by DJMcMayhem](https://codegolf.stackexchange.com/a/133213/68942) To be fair, this uses a newline, so I'd like to see a solution that doesn't use a newline. # [Also a solution by Jonathan Allan](https://tio.run/##y0rNyan8//9Rw5y0/CKFZIXMPIXk/JTU@ILE9FQrLoXMNIhYYkl@brEVmIxOjtVLTszJsfXLz0t91DD36KSwwzs0tf///2/x3xIA) This doesn't use a newline, so it's been cracked. :P My solution is this: ``` “for c in code_page: if c in atoms:atoms[c].call=None”ŒVø“print(int(input())+int(input()))”ŒV ``` The first snippet only deletes single character atoms which means that Python eval still works :))) [Answer] # JavaScript, [Cracked](https://codegolf.stackexchange.com/a/133385) Input: `prompt()` twice Output: `console.log()` My solution does not work in jsfiddle. Works on the about:blank page with Google chrome's JS console. ``` prompt=console=0 ``` My solution: ``` x=document.createElement("iframe") x.src="data:text/html,<script>console.log(prompt()-0+(prompt()-0))</script>" document.body.appendChild(x) ``` Explanation: I removed prompt and console by setting them equal to 0. In my solution I create an iframe, which creates a sandbox, and a new instance of window where prompt and console work properly. [Answer] ## Java, [Cracked](https://codegolf.stackexchange.com/a/133274/64109) ``` import java.lang.reflect.*; public class Main{ public static void main(String... args){ System.setOut(null); System.setErr(null); /*Your code here*/ } } ``` This ~~should be~~ was very easy to crack. ## Intended solution ``` import java.lang.reflect.*; public class Main{ public static void main(String... args){ System.setOut(null); System.setErr(null); try{ Class<?> cistream = Class.forName("java.io.InputStream"); Class<?> cfostream = Class.forName("java.io.FileOutputStream"); Class<?> costream = Class.forName("java.io.OutputStream"); Class<?> cfdescriptor = Class.forName("java.io.FileDescriptor"); Object sout = cfostream.getConstructor(cfdescriptor).newInstance(cfdescriptor.getField("out").get(null)); Class<?> csys = Class.forName("java.lang.System"); Field mod = Field.class.getDeclaredField("modifiers"); mod.setAccessible(true); Field stdout = csys.getField("out"); mod.set(stdout,Integer.class.cast(mod.get(stdout) )&~ Modifier.FINAL); stdout.set(null,Class.forName("java.io.PrintStream").getConstructor(costream).newInstance(sout)); Class<?> cscanner = Class.forName("java.util.Scanner"); Object scanner = cscanner.getConstructor(cistream).newInstance(System.in); Method nextInt = cscanner.getMethod("nextInt"); int f = Integer.class.cast(nextInt.invoke(scanner)); int s = Integer.class.cast(nextInt.invoke(scanner)); int sum = s + f; System.out.println(sum); }catch(Throwable t){t.printStackTrace();} } } ``` [Try it online](https://tio.run/##nVPLbtswELz7KwgfCqpNCbRX94EgqQEDdVJA@QGaWsm0KVIgV04NI/11dykxSuxEDVDoIHF3ZvYx1Ebu5EfXgN0U2@NR143zyDYUFEbaSngoDSgU72eTpl0ZrZgyMgS2lNoeHkMBJdJr53TBakrwHL0mshBM@ipkhwlj@T4g1CIA3rbIbWtMNjsJ//D@KYx@f5hcxUpfvn9jSgf0IGv2lXUxUTp/I2vg065R7cTCNi3mHWhKAk/M0r1FnWsD1NII/036OLUsICivG3T@39WvB1wUuF1taOEsuBaJNgwgKsArZ@nQKkLy5/KZsHC/oJy0Ck4ykTXXYAo@Jb1pFs/9lk9aDfsw0mJ3CXqTYnOdFqtdQfDuW3TXIcpeA316KFI5wuhSgw@RRodo8aVSEIJeGeA0Bgx6AYs0LTVy3vLA5j3sYmERKvCpspIBeURUAyJj2bs/bJkaEPPFzeVPkumTnVLcwMWII7/o6g5@vth6cuN049Grs4UqaS2M@d6iNiLvIc8tH0iP/Bfl9Wvl0z@kLUktAdfkjoXfSHs6k@qTfJqysTTNykqCvbLUhCLdndvSkL1Olkjhv0ht/JMC@8DK2SS1HT1p4s6N5ZQn5IOSqNb8bu3dvaTLwjA7JEyOUm3vvKSps9nDhJ7j8RP7/Bc) ]
[Question] [ # Challenge description On some channels on a popular streaming site [twitch.tv](https://www.twitch.tv) a common message people tend to spam in chats to bait people into spamming "LUL" is ``` One more LUL and I'm out ``` [LUL](http://files.gamebanana.com/img/ico/sprays/57822c19e1ad1.png) is a popular emote used to express that something funny happened on stream. Soon dank memes showed their potential and a parody of the copy-pasta ensued: ``` One more "One more LUL and I'm out" and I'm out ``` Which is the same message nested in itself. Given a non-negative integer `N`, output the LUL-pasta nested `N` times in itself following the pattern below. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply, the shortest code in bytes wins. # Sample input / output ``` 0: One more LUL and I'm out 1: One more "One more LUL and I'm out" and I'm out 2: One more "One more "One more LUL and I'm out" and I'm out" and I'm out ... 7: One more "One more "One more "One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out ``` # Notes * Leading/trailing newlines are allowed * Capitalization must be preserved * Your code may be a full program or a function * Instead of printing, you may return a string or its equivalent in your language of choice * You may index from `1` instead of `0` [Answer] # [Python 2](https://docs.python.org/2/), 56 bytes ``` lambda x:('"One more '*x+'LUL'+' and I\'m out"'*x)[1:-1] ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQYaWhruSfl6qQm1@UqqCuVaGt7hPqo66trpCYl6LgGaOeq5BfWqIElNCMNrTSNYz9X1CUmVeikKaRmVdQWqKhqfnfGAA "Python 2 – TIO Nexus") It is 1-indexed [Answer] # JavaScript, ~~57~~ ~~56~~ ~~54~~ 52 bytes ``` f=q=>`One more ${q?`"${f(q-1)}"`:"LUL"} and I'm out` ``` Test Snippet: ``` f=q=>`One more ${q?`"${f(q-1)}"`:"LUL"} and I'm out` ``` ``` <input type=number min=0 oninput=o.textContent=f(+this.value)> <p id=o> ``` For some reason the snack snippet is being buggy when the input is `0`, but this works otherwise. Call it like `f(4)`. ### Explanation ``` f=q=> //declares a function f with argument q `One more ... and I'm out` //hardcoded string ${q?`"${f(q-1)}"`:"LUL"} // does recursion based on q // if q is true, ie not 0, recurse // else return "LUL" ``` [Answer] # Befunge, 91 bytes ``` &:00p10p>"tuo m'I dna "1v 09p00-1<^g09p01-1_v#:g0<<vg >>00g:#^_$>:#,_@ >$"LUL">" erom enO" ``` [Try it online!](http://befunge.tryitonline.net/#code=JjowMHAxMHA+InR1byBtJ0kgZG5hICIxdgowOXAwMC0xPF5nMDlwMDEtMV92IzpnMDw8dmcKPj4wMGc6I15fJD46IyxfQCAgPiQiTFVMIj4iIGVyb20gZW5PIg&input=Nw) This is a breakdown of the source code with the various component parts highlighted. ![Source code with execution paths highlighted](https://i.stack.imgur.com/ABz0G.png) ![*](https://i.stack.imgur.com/jmV4j.png) We start by reading the repeat count *N*, and storing two duplicates of it in memory. ![*](https://i.stack.imgur.com/z4eIY.png) We then countdown the first *N*, pushing multiple copies of " and I'm out" onto the stack in reverse. Each additional copy is separated from the one before with a quote. The quote is generated with the sequence `90g` (basically reading a copy from the first line of the source), since that's the shortest way to do so. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ 29 bytes ``` …LULIF“"One€£ ÿ€ƒ I'm€Ä"“}}¦¨ ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYZlPqI@n26OGOUr@eamPmtYcWqxweD@QPjZJwVM9F8g43KIElK2tPbTs0Ir//40B "05AB1E – TIO Nexus") Different string-types doesn't seem to mix well, so for some reason I need to end the loop twice. [Answer] # C++, 118 + 16 = 134 bytes ``` auto L(int x){std::string k="One more LUL and I'm out",r=k;for(int i=0;i++<x;)r.replace(i*10-1,3,'"'+k+'"');return r;} ``` `#include<string>` - +16 replaces "LUL" to the whole string N times. Anyone has better golfs? [Try it online!](https://tio.run/nexus/cpp-gcc#TY/BboMwDIbveQqLHYDBaKveGuBeKdJOPEBG3M4DnCokUqeqz84CO2wXy/5kf/q9vBD3YzAI9ewd8bUVf4RsZKinVujgLaiM2MM9f8zenE6/6zA0yTsjTNYhqE6BZgPndAIbfFK6ZpAX67Y7avaSiqK@y9xVDm@j7jGj18P@7VAeyzRJi6GINZcOfXAMTj5ht/OfCJfAvSfLYtVMmjjLxUPAOnVKCtji9MTQtv9BTAB1HVN3Kl@bjSKbUUbvN84laPiw2xNfdsAqCg2iqcRzWY4/) Massive thanks to **Kritixi Lithos** and **hvd**, for, uh, Massive help. [Answer] # Javascript (ES6), 68 Bytes ``` f=(x,y="LUL")=>~x?f(--x,`"One more ${y} and I'm out"`):y.slice(1,-1) ``` Call like `f(n)`. You can also call it like `f(n, "LUL")` and replace LUL with any word you wish. [Answer] # [V](https://github.com/DJMcMayhem/V), ~~39~~ 37 bytes Two bytes with the help of @KritixiLithos for coming up with the substitution method ``` iOne more LUL and I'm outÀñÓLUL/"." ``` [Try it online!](https://tio.run/nexus/v#@5/pn5eqkJtflKrgE@qjkJiXouCpnquQX1oifbjh8MbDk4Gi@kpCekr///83AwA "V – TIO Nexus") Hexdump: ``` 00000000: 694f 6e65 206d 6f72 6520 4c55 4c20 616e iOne more LUL an 00000010: 6420 4927 6d20 6f75 741b c0f1 d34c 554c d I'm out....LUL 00000020: 2f22 122e 22 /".." ``` [Answer] # Java, 79 77 bytes Golfed: ``` String f(int l){return"One more "+(l<1?"LUL":'"'+f(l-1)+'"')+" and I'm out";} ``` Ungolfed, with test: ``` public class OneMoreLulAndImOut { public static void main(String[] args) { OneMoreLulAndImOut obj = new OneMoreLulAndImOut(); for (int i = 0; i < 8; ++i) { System.out.println(Integer.toString(i) + ": " + obj.f(i)); } } String f(int l) { return "One more " + (l < 1 ? "LUL" : '"' + f(l - 1) + '"') + " and I'm out"; } } ``` Program output: ``` 0: One more LUL and I'm out 1: One more "One more LUL and I'm out" and I'm out 2: One more "One more "One more LUL and I'm out" and I'm out" and I'm out 3: One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out 4: One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out 5: One more "One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out 6: One more "One more "One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out 7: One more "One more "One more "One more "One more "One more "One more "One more LUL and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out" and I'm out ``` [Answer] # Python, 79 bytes I just wanted to do a recursive solution, even though it's longer than other answers. ``` x='"One more %s and I\'m out"' f=lambda n,s=x:n and f(n-1,s%x)or(s%"LUL")[1:-1] ``` [**Try it online**](https://tio.run/nexus/python2#@19hq67kn5eqkJtflKqgWqyQmJei4BmjnquQX1qipM6VZpuTmJuUkqiQp1NsW2GVB5ZP08jTNdQpVq3QzC/SKFZV8gn1UdKMNrTSNYz9X1CUmVcCVGGgyQVjGiKYRgimueZ/AA) [Answer] ## C#, 125 bytes ``` n=>{string f="One more {0} and I'm out",s=f;for(int i=0;i++<n;)s=string.Format(s,$"\"{f}\"");return string.Format(s,"LUL");}; ``` [Answer] # C, 140 111 bytes My first attempt at a golfing question.. Golfed: ``` #define F printf( #define P 1&&putchar(34) int a=0;void q(n){a=a?a:n,n?n>0?F"One more "),n-P:n?n+P,F" and I'm out"):0:F"LUL"),n+a?q(n-1):0;} ``` I have come to realise is the wrong output since q(0) just gives LUL. The next attempt: ``` #define o(Q) O(Q,n?34:0); #define O printf void q(int n){o("One more %c")n?q(n-1):O("LUL"),o("%c and I’m out")} ``` Example program (tested with GCC on OSX): ``` #define o(Q) O(Q,n?34:0); #define O printf void q(int n) {o("One more %c")n?q(n-1):O("LUL"),o("%c and I’m out")} int main() { q(0),putchar('\n'); q(1),putchar('\n'); q(2),putchar('\n'); q(3),putchar('\n'); return 0; } ``` Gives output ``` One more LUL and I’m out One more "One more LUL and I’m out" and I’m out One more "One more "One more LUL and I’m out" and I’m out" and I’m out One more "One more "One more "One more LUL and I’m out" and I’m out" and I’m out" and I’m out ``` [Answer] # Mathematica, ~~69~~ 68 bytes *Thanks to Martin Ender for saving 1 hard-to-find byte!* ``` ""<>Nest[{q="\"",{"One more ",#," and I'm out"},q}&,"LUL",#+1][[2]]& ``` Unnamed function taking a nonnegative integer argument and returning a string. `Nest` applies a function repeatedly to an initial argument; in this case, the function is to surround its argument by the appropriate words and quotation marks. We start from `"LUL"` and iterate `N+1` times; that results in unwanted quotation marks enclosing the entire phrase, but `[[2]]` keeps only the stuff between them. At the end, `""<>` turns the resulting heavily nested list into a single string. Previous submission: ``` ""<>Nest[{o,q="\"",#,q,a}&,{o="One more ","LUL",a=" and I'm out"},#]& ``` [Answer] ## C#, ~~119~~ ~~85~~ 71 bytes ``` string m(int n)=>$"One more {(n<1?"LUL":$"\"{m(--n)}\"")} and I'm out"; ``` *Saved 14 bytes thanks to @Luc* [Answer] ## [Retina](https://github.com/m-ender/retina), 51 bytes ``` .+ $*00LUL1$&$* 0 "One more 1 and I'm out" ^"|"$ ``` [Try it online!](https://tio.run/nexus/retina#U9VwT/ivp82lomVg4BPqY6iipqLFZcCl5J@XqpCbX5SqwGXIpZCYl6LgqZ6rkF9aosQVp1SjpML1/78BUMaIy5jLhMsUAA "Retina – TIO Nexus") [Answer] ## R, 97 bytes ``` function(n){s="One more LUL and I'm out";while(n){s=sub("LUL",paste0('"',s,'"'),s);n=n-1};cat(s)} ``` Ungolfed: ``` function(n) { s = "One more LUL and I'm out"; while(n) { s = sub("LUL", paste0('"', s, '"'), s); n = n - 1 }; cat(s) } ``` [Answer] ## R, 100 97 92 bytes *"One more recursive function and I'm out"* ``` f=function(n)paste("One more",`if`(n<1,"LUL",paste0('"',f(n-1),'"')),"and I'm out");cat(f(scan())) ``` Edit: Turns out that a non-recursive approach is slightly shorter: ``` x="One more ";y=" and I'm out";cat(x,rep(c('"',x),n<-scan()),"LUL",rep(c(y,'"'),n),y,sep="") ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 39 bytes *Thank you @ETHproductions for helping.* ``` `"O Ú `p°U +"LUL"+` d I'm t"`pU)s1J ``` [Try it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=YCJPmiDakCBgcLBVICsiTFVMIitgIIRkIEknbSCMdCJgcFUpczFK&input=Nw==) [Answer] # Ruby, 51 bytes One-indexed. [Try it online](https://repl.it/FOl9) ``` ->n{['One more ']*n*?"+'LUL'+[" and I'm out"]*n*?"} ``` [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), ~~72~~ 67 bytes ``` "$('"One more '*($c=1+"$args"))LUL$(' and I''m out"'*$c)".Trim('"') ``` [Try it online!](https://tio.run/nexus/powershell#@6@koqGu5J@XqpCbX5SqoK6loZJsa6itpJJYlF6spKnpE@oDVKCQmJei4KmunquQX1qipK6lkqyppBdSlJkL1Kuu@f//fyMA "PowerShell – TIO Nexus") [Answer] ## Lua, 101 bytes ``` i,f,g='"One more ',' and I\'m out"',io.read()+1 print((i:rep(g).."LUL"..f:rep(g)):sub(2,g*24-(g-2))) ``` Obvious string attempt. Repeats `"One more` and `and I'm out"` exactly input + 1 times, with a `LUL` inbetween, then removes first and last quote. [Answer] # Haskell, 51 bytes Indexes from 1. ``` f 0="LUL";f n="One more \""++f(n-1)++"\" and I'm out" ``` [Answer] # Ruby, 70 bytes ``` def l x,t="LUL";x.times{t='"One more %s and I\'m out"'%t};t[1..~1];end ``` Simply loops for the amount it's given, surrounding the last string via a format string each time. Index starts at one. [Answer] # Stacked, 54 bytes ``` ('"One more ' ' and I''m out"')*'LUL'join'^.|.$'εrepl ``` [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) Example usage of "function": ``` 1 ('"One more ' ' and I''m out"')*'LUL'join'^.|.$'εrepl out ``` --- One for 56 bytes: ``` @n'One more LUL and I''m out':@o['LUL' '"'o'"'+ +repl]n* ``` [Answer] # Python 3, 68 Bytes `def f(a):return('"One more '*a+'LUL'+(' and I%sm out"'%"'")*a)[1:-1]` [Answer] # CJam, ~~51~~ 49 bytes ``` " and I'm out\"""\"One more "li1+_@*"LUL"+1>@@*W< ``` [Try it online](https://tio.run/nexus/cjam#@6@kkJiXouCpnquQX1oSo6SkFKPkn5eqkJtflKqglJNpqB3voKXkE@qjpG1o5@CgFW7z/78hAA) ### Ungolfed: ``` " and I'm out\"" "\"One more " // Push two strings to the stack l i 1 + // Read a number and add 1 _ @ // Copy number and rise '"One more ' to the top * // Multiply '"One more ' by a number "LUL" + // Add "LUL" 1> // Chop the first quote @@ // Push the result down * // Multiply ' and I\'m out"' by a number W< // Chop the last quote ``` [Answer] ## Groovy, 54 bytes ``` {x->('"One more '*x+'LUL'+' and I\'m out\"'*x)[1..-2]} ``` Pretty straightforward, same as the python answer but 2 bytes shorter. It is also 1-indexed. [Try it Online!](https://tio.run/#5e255) [Answer] ## Mathematica, ~~65~~ 63 Bytes ``` Nest["\"One more "<>#<>" and I'm out\""&,"LUL",#]~StringTrim~_& ``` Two bytes off by noticing the challenge allows 1-indexing. [Answer] # PHP Hello, i found so far two ways for doing this. The replacement way 1-indexed **(121 bytes)**. ``` function f($x){$v='One more LUL and i\'m out';$t=$v;for($i=1;$i<=$x;$t=str_replace('LUL','"'.$t.'"',$v),$i++);return $t;} ``` The recursive way **(86 bytes)**. ``` function r($n){$v=($n==0)?'LUL':'"'.r($n-1).'"';return'One more '.$v.' and i\'m out';} ``` [Answer] # C++, 80 + 16 = 96 bytes ``` std::string L(int c){return"One more "+(c?'"'+L(--c)+'"':"LUL")+" and I'm out";} ``` `#include<string>` - +16 Ungolfed: ``` std::string LUL(int count) { return "One more " + (count? ('"' + LUL(--count) + '"') : "LUL") + " and I'm out"; } ``` Calls itself recursively and uses string addition. Pretty straight forward. I mean what else can I say? Even the ungolfed version is essentially a one liner. [Try it online!](http://cpp.sh/4mcgj) [Answer] # [Cheddar](http://cheddar.vihan.org/), 71 bytes ``` i->('One more "'*i).slice(0,-1)+'LUL '+('and I\'m out" '*i).slice(0,-2) ``` [Try it online!](https://tio.run/nexus/cheddar#K0ssUkiz/Z@pa6eh7p@XqpCbX5SqoKSulampV5yTmZyqYaCja6ipre4T6qOgrq2hnpiXouAZo56rkF9aoqSAqs5I839BUWZeiUaahqmm5n8A "Cheddar – TIO Nexus") ]
[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 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. # The 9 Hole Challenge * 9 code golfing challenges of varying difficulty. * Penalties for using the same language more than once. * The question will be updated with pars, hole champions and trophy winners. *This comes from a competition I have with some friends, it's not the usual format, but I hope some of you will appreciate the different spin on it. Challenges, rules and trophies below.* # Holes 1. # Greenway (24) `f(c:string, n:integer)` Prints a line containing `n` instances of `c`. 2. # Somewhere in the Rough (73) `f(t:string, s:string, n:integer) -> i` Where `i` is the index of the `nth` instance of `s` in `t`. 3. # Curry for Dinner (6235) `f(x:function, y: function) -> g` Where `g` is a function that will call `y`, `n` times; where `n` is the return value of `x` 4. # Spew (92) `f(p:string)` Writes to file at `p` and fills it with a randomly sized rectangle of random characters (ascii). 5. # Treasure Hunt (75) `f(p:string, c:char) -> (x, y)` Reads file at `p` which contains a grid of symbols and returns the `x` and `y` coordinates of the first instance of that symbol within the grid, assume it exists. 6. # Bridge on the River Kwai (179) `f(l:list[int])` Prints difference bridges diagram for `l`. E.g for `[1,7,3,17,1]` ``` /+6\ /-4\ /+14\ /-16\ 1 7 3 17 1 ``` Make sure that the spaces are created according to the size of the number above. For a 3 digit long number, you are going to need 4 spaces between the digits on the line below. Catch: Somewhere, your code must spell trousers (Must have at least 1 non-alphanumeric delimiters. E.g. `tr(ou,se)(rs)` 7. # Time Flies When You're Playing Golf (1157) `f(p:string) -> [h, m]` Reads file at `p` which contains an ASCII representation of an analogue clock, where the hour hand is represented with one lines, and the minutes by two. Output a list containing two elements: the hours and minutes shown on the clock. If only one hand is visible, assume both point to that position. Here are all the possible combinations for a hand. ``` \ | / \|/ --o-- /|\ / | \ ``` These positions, respectively are (12, 1, 3, 5, 6, 7, 9, 11). Assume that the other characters within the clock face are spaces. 8. # Timber! () `f(p:string) -> b:boolean` Where p is the path to a file with an ascii building in. Blocks with white space underneath them will fall. (Except from slashes, which stay in place if there is a stable block in the opposite direction to the way they face). If the building is structurally integral return true, otherwise return false. All non whitespace blocks are counted as being solid and other than slashes, they all fall. Structurally safe ``` ____ |/\| | | ``` Not Safe ``` |__ | | ``` Safe version ``` |__ \\| | ``` 9. # Slacker News (218) `f(s:string, r:string, p:string)` Gets the titles of the top 20 stories on Hacker News and changes all instances of `s` to `r`, then writes the new titles to a html file at `p`, where each title is contained within a h1 element. The outputted file should something like this `<h1>Some title</h1></h1>Some other title</h1>...etc` **Catch**: * You may not use the HN api. * You may not use Regex. * You may not use angle braces anywhere in your code. --- # Scoring * Character count is the length of the function that will compile & run correctly. However you still need to submit the full code, including imports. * **+10%** for every repeated language in your submission. (E.g. If you use Ruby for 3 solutions, then your final score will be multiplied by 1.2). Different versions of the same language count still count as the same language. * Par will be average score for each hole. * Submit your solutions in one answer. * Your overall score is your character count + your language penalty, then round it up. --- # Trophies * **Gold Jacket** - ([@Sprigyig](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16782) - 1290) Lowest overall score * **Shooter** - ([@Sprigyig](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16782) - 9) Most languages used * **Bunker** - Most above par score on any hole * **Snakes on a Plane** - ([@AsksAnyway](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16736) - 1727) Highest python character submission in a single solution * **Good Parts** - ([@AsksAnyway](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16736) - 255) Highest JS character count in a single solution * **Shakey Steve** - Shortest solution that uses interfaces * **You're Not From Round Here** - Shortest unique language solution that's language has the shortest wikipedia page. * **Happy Gilmoore** - ([@AsksAnyway](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16736) - 31) Shortest solution that has the word 'alligator' in the code. * **Unicycling Dwarf Magic** - The default extensions of your 9 submission source files are a perfect anagram of a word in the Oxford Dictionary. *You are only eligible for a trophy once you have completed all 9 holes* --- # Submissions 1. [@Sprigyig](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16782) 1290 2. [@Firefly](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16811) 1320 3. [@grc](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#16770) 1395 4. [@Trevor M](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-17022) 1465 5. [@C Gearhart](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16898) 1654 6. [@Guy Sirton](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16739) 1719 7. [@AsksAnyway](https://codegolf.stackexchange.com/questions/16707/9-hole-challenge#answer-16736) 4651 [Answer] # Score: 4651 *2907 + 60% penalty* ### 1. GolfScript - 14 characters ``` {*}:a;lligator ``` Usage: `c n a` e.g. `"test" 3 a` -> `testtesttest` ![star](https://i.stack.imgur.com/tIZQP.png) Happy Gilmoore ### 2. Python - 72 characters ``` def f(t,s,n,p=-1): while n:p=t.find(s,p+1);n-=1 if p+1 else n return p ``` ### 3. Javascript - 255 characters ``` /* Curry for Dinner f(x:function, y: function) -> g Where g is a function that will call y, n times; where n is the return value of x */ function f(x, y) { var g = function() { var n = x(); for (var i = 0; i < n; ++i) { y(); } }; return g; } ``` ![star](https://i.stack.imgur.com/tIZQP.png) Bunker ![star](https://i.stack.imgur.com/tIZQP.png) Good Parts ### 4. Python - 132 characters ``` from random import randrange as r def f(p):l=range(r(9));open(p,'w').writelines([''.join([chr(r(94)+33)for _ in l])+'\n'for _ in l]) ``` ### 5. Python - 89 characters ``` def f(p,c): for y,d in enumerate(open(p).readlines()): x=d.find(c) if x+1:return x,y ``` ### 6. Python - 189 characters ``` def f(l): for i in 0,1: for n,u in enumerate(l): o=l[n+1] if len(l)>n+1 else id if i:print u,' '*4, elif o!=id:print' /'+('+' if o-u>0 else '')+str(o-u)+'sers'*0+'\\ ', print ``` ### 7. Python - 1727 characters ``` def f(p): lines = open(p).read().split('\n') # preprocess lines to ensure correct format if len(lines) < 5: for i, line in enumerate(list(lines)): if 'o' in line: if i == 0: lines.insert(0, ' ' * 5) lines.insert(0, ' ' * 5) elif i == 1: lines.insert(0, ' ' * 5) while len(lines) < 5: lines.append(' ' * 5) # find characters that can only be the hour hand for i, line in enumerate(lines): if i == 0: if '\\' in line: hour = 11 elif '|' in line: hour = 12 elif '/' in line: hour = 1 elif i == 2: if '--o' in line: hour = 9 elif 'o--' in line: hour = 3 elif i == 4: if '/' in line: hour = 7 elif '|' in line: hour = 6 elif '\\' in line: hour = 5 # find characters that might represent the minute hand possible_minutes = [] for i, line in enumerate(lines): if i == 1: if '\\' in line: possible_minutes.append(55) if '|' in line: possible_minutes.append(0) if '/' in line: possible_minutes.append(5) elif i == 2: if '-o' in line: possible_minutes.append(45) if 'o-' in line: possible_minutes.append(15) elif i == 3: if '/' in line: possible_minutes.append(35) if '|' in line: possible_minutes.append(30) if '\\' in line: possible_minutes.append(25) HOUR_MINUTES = { 12: 0, 1: 5, 3: 15, 5: 25, 6: 30, 7: 35, 9: 45, 11: 55, } # remove minute hand that is actually hour hand if len(possible_minutes) > 1: not_minute = HOUR_MINUTES[hour] if not_minute in possible_minutes: possible_minutes.remove(not_minute) assert(len(possible_minutes) == 1) minute = possible_minutes[0] h, m = hour, minute return [h, m] ``` ![star](https://i.stack.imgur.com/tIZQP.png) Snakes on a Plane ### 8. Python - 226 characters ``` def f(p): e=set;q,t=e(),True for l in open(p).readlines(): r,b,q=e(q),e(),e() for i,c in enumerate(l): if c.strip():b.add(i);q.add(i-1 if c == '/' else i+1 if c == '\\' else i) if not r.issubset(b):t=False return t ``` ### 9. Python - 203 characters ``` import urllib def f(s,r,p):f,l,g=open(p,'w'),'\74','\76';[f.write(l+'h1'+g+t.replace(s,r)+'h1'+g)for i,t in enumerate(urllib.urlopen('http://x.co/3WYln').read().split('title'+g))if(i in range(2,42))&i%2] ``` [Answer] ## Score: 1320 I've plenty to do to improve this score... Oh well, at least I avoided repeated-language penalties. :-) ### 1. Python (21 chars) ``` def f(c,n):print(c*n) ``` The "obvious" solution. ### 2. ECMAScript 6 (47 chars) ``` f=(t,s,n)=>t.split(s).slice(0,n).join(s).length ``` Finds the index in a bit of an unconventional way, by counting the length of the substring before it. ### 3. J (12 chars) ``` f=:2 :'v^:u' ``` The built-in conjunction `^:` raises a function to a power (i.e. repeats a function a given number of times). That is, `f^:3 y = f (f (f y)))`. However, it's overloaded to alos accept functions rather than integers, in which case it runs the function on the input to get the number of repetitions. Unfortunately we need to flip the operands for the task, otherwise we'd have the consise answer `f=:^:`. ### 4. C (95 chars) ``` #include <stdio.h> #include <stdlib.h> f(char*p){FILE*f=fopen(p,"a");for(int n=rand(),y=n*n;y--;y%n||putc(10,f))putc(rand()%94+32,f);} ``` This task leaves quite a bit of room for interpretation and abuse: is it okay to just output a random printable ASCII character and say it's a randomly-dimensioned rectangle with dimensions from the set {1}? Probably not. Anyway, I went with plain `rand()` but in reality you probably want to add `%9` or something if you want to test it. On my linux box I didn't have to flush the file in order for it to be written (I guess it flushes automatically on program exit), but I'm pretty sure you have to flush it to be standards-compliant, so feel free to add `fflush(f);` to the count here. ### 5. Haskell (100 chars) ``` import Control.Arrow import Data.List import Data.Tuple import Control.Applicative h p c=head.filter(p c.snd).zip[1..] g c=swap.(id***fst.h(==)c).h elem c.lines f p c=g c<$>readFile p ``` I like the repeated pattern between finding the row and the column (abstracted via `h`). ### 6. Lua (261 chars) ``` function f(s,m,y,...)if s and m then for i,v in pairs(m)do io.write(v,(" "):rep(#tostring(s[i])))end print()elseif s then r=unpack f(s,{"",f(trouse,r(s))})f({f(nil,r(s))},s)elseif y then return ("/%s%d\\"):format(m<y and"+"or"-",math.abs(m-y)),f(s,y,...)end end ``` Makes use of multiple return values and recursion to deal with computing the differences. It cost me a few characters to match the sample output exactly (adding the right amount of spaces everywhere). ### 7. Go (307 chars) ``` func f(p string)[]int{var l[]string g,_:=os.Open(p) H,M,s,m:=0,0,bufio.NewScanner(g),[][]int{{-1,-1,11},{-1,0,12},{-1,1,1},{0,-1,9},{0,1,3},{1,-1,7},{1,0,6},{1,1,5}} for s.Scan(){l=append(l,s.Text())} for _,a:=range m{if l[2+a[0]*2][2+a[1]*2]!=' '{M=a[2]} if l[2+a[0]][2+a[1]]!=' '&&(H==0||M!=a[2]){H=a[2]}} return[]int{H,M}} ``` Could probably be golfed a lot more; I barely know Go. ### 8. CoffeeScript (+ node.js) (223 chars) ``` f=(p)-> a=require('fs').readFileSync(p).toString().split "\n" U=(i,j)->a[i]?[j]and a[i][j]==' ' for l,i in a for c,j in l m = "/":[i+1,j-1] "\\":[i+1,j+1] a:[i+1,j] return if U.apply(0,m[c]or m.a) 1 ``` A bit of a cheap-shot since I already have JS. Oh well. Returns a falsy value (namely, `undefined`) or a truthy value (namely, `1`) to indicate the answer. ### 9. Bash (254 chars) ``` f(){ curl https://news.ycombinator.com/rss| awk -Ftitle '{OFS="h1\76\n\74h1";ORS="";print substr(OFS,4);print$2,$4,$6,$8,$10,$12,$14,$16,$18,$20,$22,$24,$26,$28,$30,$32,$34,$36,$38,$40;print substr(OFS,0,3)}'| while read l;do echo ${l//$1/$2};done| tee $3 } ``` (Newlines after pipes added for readability.) Working around the restrictions with the shell was fun. I realise there's probably a better way to do `$2,$4,$6,...`, but this was what I came up with anyway. [Answer] # Score: 1,394.4 *996 characters + 40% penalty* **1. Greenway - Haskell, 19 chars** ``` f c n=replicate n c ``` Usage: ``` > f "hello" 5 ["hello","hello","hello","hello","hello"] ``` **2. Rough - PHP, 72 chars** ``` <? function f($t,$s,$n){for($i=-1;$n--;$i=strpos($t,$s,++$i));return$i;} ``` **3. Curry - JavaScript 1.8, 45 chars** ``` f=function(x,y)function(){for(i=x();i--;)y()} ``` **4. Spew - J, 43 chars** ``` f=:3 :'((33+?(1+?2#100)$1#93){a.)fwrites y' ``` Usage: ``` f 'file.txt' ``` **5. Treasure - J, 64 chars** ``` f=:4 :0 a=.freads x b=.1+a i.u:10 c=.a i.y d=.<.c%b e=.d,c-b*d ) ``` Usage: ``` 'file.txt' f 'c' ``` **6. Bridge - Python, 166 chars** ``` def f(l):J=''.join;t=map;r=lambda n:' '*len(n);s=t(str,l);o=['/%+d\\'%(y-x)for x,y in zip(l,l[1:])];print J(t(J,zip(t(r,s),o)))+'\n'+J(t(J,zip(s,t(r,o)+['users'*0]))) ``` **7. Time - Python, 205 chars** ``` def f(p): s=open(p).read();a=[s[:12],s[18:],s[11:15],s[15:18]];z=[0]*3 for l in(0,1): for c in'/|\\':z[a[l].count(c)]=('|/'.find(c)+6*l)%12or 12 z[a[2+l].count('-')]=3+6*l print[z[1]or z[2],z[2]*5%60] ``` Assumes lines are space padded to be five characters wide. Uses tabs for second indentation level. **8. Timber - Python, 190 chars** ``` def f(p):g=open(p).readlines();C='\\/ ';return all(1-[x+2>len(g[y])or g[y][x+1]in C,x<1or g[y][x-1]in C,0,' '==g[y+1][x]][C.find(g[y][x])]for y in range(len(g)-1)for x in range(len(g[y])-1)) ``` **9. Slacker - Python, 192 chars** ``` import urllib def f(s,r,p):F=open(p,'w');d=urllib.urlopen('http://x.co/3WYmQ').read()[37:];o,c='\x3c\x3e';exec"d=d[d.find(o+'t')+7:];F.write(o+'h1'+c+d[:d.find(o)].replace(s,r)+o+'/h1'+c);"*20 ``` Thanks to Tyzoid for the url shortener idea. [Answer] Edit: Think I'll just submit this as is: 1290 total, no language repeats. **Greenway, C#** 53 ``` void g(string s,int n){while(n-->0)Console.Write(s);} ``` I decided to swap languages with #1 and #9. Totally worth 30 here for hundreds later. **Somewhere In The Rough, Python** 59 I really shouldn't have used up such a good language on an easy problem. Also, how is this not part of any language's indexOf family of functions? I seem to always need this... ``` def f(t,s,n):return sum(map(len,t.split(s))[:n+1])+n*len(s) ``` **Curry For Dinner, Lisp** 61 I haven't touched lisp since that one week in college.... ``` (defun f (c g)(loop for i from 1 to(funcall c)do(funcall g))) ``` **Spew, Bash/shell utils** 102 My bash-foo was never that good to begin with. I'll fiddle with this one later. BTW if you want it to finish faster, switch it over to /dev/urandom. ``` f(){ c=$(($RANDOM%9+9)) for i in $(seq $c);do echo `tr -cd [:print:]</dev/random|head -c$c`>>$1 done } ``` **Treasure Hunt, C** 113 Probably one of the more C friendly problems. I interpreted "return two integers" as take a return array pointer as an argument. Warnings? What warnings? An int\* is just as good as a FILE\* =p. ``` void f(int*p,int c,int*r){int*f,t;*r=r[1]=0;f=fopen(p,"r");while(c-(t=fgetc(f))){*r=t-'\n'?*r+1:0;r[1]+=*r?0:1;} ``` **Bridge on the River Kwai, Perl** 207 I started learning perl while writing this one. (Better late than never!) I came into this wanting to do regex heroics, so I form the string as both layers of the bridge together, then use regexes with space replacements to form the two different lines. ``` sub f{@trouse=0..$#_-1;foreach $i(@trouse){$r.=sprintf("%d/%+d\\",$_[$i],$_[$i+1]-$_[$i])}$r.=$_[$#_]."\n";print$r=~s/(^|\\)(\d+)(\/|$)/$1.' 'x length($2).$3/egr;print$r=~s/(\/[+-]\d+\\)/' 'x length($1)/egr} ``` **Time Flies When You're Playing Golf, Java** 297 You can only do so much to make java terse... It assumes the clock is space padded so each line is 5 spaces long. ``` public boolean p(int r,int m,String s){int c[]={1,1,0,-1,-1,-1,0,1};return s.charAt(6*c[(r+6)%8]*m+14+c[(r)%8]*m)!=' ';} public int[]time(String c){int h=9,m=0,t[]={3,5,6,7,9,11,12,1};for(int i=0;i<8;i++)if(p(i,1,c))if(p(i,2,c))m=i;else h=i;if(h==9)h=m;m=(t[m]*5)%60;h=t[h];return new int[]{h,m};} ``` **Timber! Javascript** 201 It runs in chrome's console. I make no guarantees elsewhere =p. It requires that the lines be space padded out to the length of the longest line. I feel like this is a reasonable request of ASCII art. ``` function f(s) {s=s.split("\n") d={};m={'/':-1,'\\':1};r=1 s.forEach(function(x){t={} for(i=0;i<x.length;i++){if(x[i]!=' '){j=m[x[i]]?i+m[x[i]]:i t[j]=1}}for(n in d){if(x[n]==' '){r=0}}d = t}) return r} ``` **Slacker News, Ruby** 197 ``` def s(f,s,t) l=60.chr r=62.chr IO.write(f,l+"h1"+r+URI.parse("https://news.ycombinator.com").read().split('mhead')[0,20].map{|x|x[0,x.length-19].split(r).last.sub(s,t)}.join(l+"/h1#{r+l}h1"+r)) end ``` [Answer] Had fun touching a few languages for a little bit... Character counts obtained after removing unnecessary spaces/newlines but submission mostly kept readable. Since the question is a mix of functions and programs I included only the body of the function where required... Also some liberty taken with what the meaning of "return" is... Total **~1719** 1- **Python** (~20) ``` def f(c, n): print c*n ``` 2- **C** (~109) ``` int f(char*t,char*s,int n){int i;char*q=t;int l=strlen(s);for(i=0;i<n;++i){t=strstr(t, s)+l;}return(t-q-l);} ``` Readable version: ``` #include <string.h> int f(const char *t, const char *s, int n) { int i; char *start = t; int l = strlen(s); for(i = 0; i < n; ++i) { t = strstr(t, s) + l; } return(t - start - l); } ``` 3- **Javascript** (~56) ``` function(x, y) {return function() {for(i=0; i<x(); i++) y();}} ``` 4- **Rexx** (~136) ``` f: Procedure Parse arg p w = random(1, 9) h = random(1, 9) Do y = 1 to h Do x = 1 to w Call CHAROUT p, d2c(random(32, 99)) End Call LINEOUT p, "" End ``` 5- **Scala** (~290) ``` def f(p: String, c: Char) { def sc(w: String, c: Char, x: Int, y:Int ): Boolean = { if(w.isEmpty) false else if(w.head==c) {println(x, y); true} else sc(w.tail, c, x+1, y) } def sr(w: Array[String], c: Char, x: Int, y: Int) { if(!sc(w.head, c, 0, y)) sr(w.tail, c, 0, y+1) } sr(io.Source.fromFile(p).mkString.split('\n'), c, 0, 0) } ``` 6- **C++** (~355) ``` void b(list<int> l) // trouser+s { auto i = l.begin(); auto j = i; j++; list<int> d; while(j!=s.end()) d.push_back(*j++ - *i++); j = d.begin(); ostringstream o[2]; for(auto i : l) { while(o[0].tellp()!=o[1].tellp()) o[1] << " "; o[1] << i; if(j != d.end()) { while(o[0].tellp()!=o[1].tellp()) o[0] << " "; o[0] << "/" << (*j>=0 ? "+" : "") << *j++ << "\\"; } } cout << o[0].str() << endl << o[1].str() << endl; } ``` 7- **Go** (~301) Note this requires the clock to be padded (i.e. all lines are same length). ``` func f(p string)(h int,m int) { var a=[8]int {0, 2, 4, 12, 16, 24, 26, 28} var b=[8]int {7, 8, 9, 13, 15, 19, 20, 21} var d=[8]int {11, 12, 1, 9, 3, 7, 6, 5} h=9 c, e := ioutil.ReadFile(p) if e==nil { for i:=range a { if c[a[i]]>32 { m=i } } for i:= range b { if c[b[i]]>32 { if i!=m { h=i } } } if h==9 { h=m } h=d[h] m=d[m]*5%60 } return } ``` 8- **Ruby** (~259) ``` def f(p) a,b = File.read(p).split(/\n/).reverse,Hash.new(1) a.each_with_index { |l,i| l.split("").each_with_index {|k,j| case k when ' ' b[j] = 0 when '/' b[j] = b[j]|b[j-1] when '\\' b[j] = b[j]|b[j+1] end unless k==' ' if b[j]==0 return 0 end end } } return 1 end ``` 9- **bash/Unix hack** (~193) ``` wget -qO - http://news.ycombinator.com/rss | tr "\074\076" "\n" | grep -B1 /title | awk 'NR % 3 == 1' | head -21 | tail -20 | sed 's/$1/$2/' | awk '{ print "\074h1\076" $0 "\074/h1\076"}' > $3 ``` [Answer] Not really here to golf, but here's some Tcl, since the language needs more love: ``` set holes { greenway rough curry spew hunt bridge time timber slacker } proc greenway {c n} { puts [string repeat $c $n] } proc rough {t s n} { set i [string first $s $t] ;# a bit wet while {[incr n -1]} { incr i [string first $s $t $i] } return $i } proc curry {x y} { set n [uplevel 1 $x] set body [string repeat "$y;" $n] return [list apply [list args $body]] } proc spew {p} { set w [expr {int(rand()*80)}] set h [expr {int(rand()*80)}] set f [open $p w] for {set y 0} {$y<$h} {incr y} { set ln "" for {set x 0} {$x<$h} {incr x} { append ln [format %c [expr {int(rand()*96+32)}]] } puts $f $ln } close $f } proc hunt {p c} { set f [open $p r] set y 0 while {[gets $f line]>=0} { set x [string first $f $c] if {$x != -1} { return [list $x $y] } incr y } } proc bridge {l} { set l [lassign $l m] set top "" set btm $m foreach n $l { set t "/[expr {$n>$m?"+":""}][expr {$n-$m}]\\" append top "[string repeat \ [string length $m]]$t" append btm "[string repeat \ [string length $t]]$n" set m $n } # trousers return $top\n$btm } proc time {p} { set f [open $p r] while {[gets $f line] >= 0} { set line [format %-.5s $line] lappend c [split $line {}] } close $f foreach {x y h} { -1 -1 0 0 -1 1 1 -1 3 1 0 5 1 1 6 0 1 7 -1 1 9 -1 0 11 } { set 2x x; incr 2x $x set 2y y; incr 2y $y if {[lindex $c $2y $2x] != " "} { set hh $h } elseif {[lindex $c $y $x] != " "} { set mm $h } } if {![info exists $mm]} { set mm $hh } set mm [expr {$mm*5}] if {$hh == 0} {set hh 12} list $hh $mm } proc timber {p} { set f [open $p r] set must {} while {[gets $f line] >= 0} { set line [format %-.5s $line] foreach i $must { if {[string index $line $must] eq " "} { close $f return false } } set must {} set i 0 foreach c [split $line] { switch $c { "\\" {lappend must [expr {$i+1}]} "/" {lappend must [expr {$i-1}]} " " { } default {lappend $must $i} } incr i } } close $f return true } proc slacker {s r p} { package require tdom set f [open $p w] set h [::http::geturl https://news.ycombinator.com/] set html [string trim [::http::data $h]] ::http::cleanup $h set dom [dom parse $html] lappend map , [string index $html 0] lappend map . [string index $html end] set root [$dom documentElement] foreach n [$root selectNodes {//td[@class=title]/a}] { set x [$n text] set x [string map [list $s $r] $x] puts $f [string map $map ",h1.$x,/h1."] } close $f } ``` Mostly untested because writing these procs in half an hour is much more interesting than trying to properly engineer golf code. Enjoy! [Answer] Only had time to work on 1/2 of these. You seem to want them in the form of a function and not a one liner. So all of these are functions. Testing code below the function. In Perl. **Greenway:** ``` sub f{print$_[0]x$_[1]} #test &f("abc",5); ``` **Rough:** ``` sub f{$i=-1;$n=$_[2];do{$i=index$_[0],$_[1],$i+1;$n--}while($n>0 && $i>-1);print$i+1} #test &f("abcefgacefgabcefgabcefgabcefg","cef",4); ``` **Curry:** ``` use Sub::Curried; curry f($x,$y){$q=0;foreach(1..&$x){$q=&$y};return $q;} #test sub fy { return 1;} sub fx { return 10;} print&f(\&fx,\&fy); ``` **Spew:** ``` use Crypt::PRNG qw(random_string_from irand); sub f{open($o,">$_[0]");$m=(irand)%10+1;map{printf $o "%s\n",random_string_from(['A'..'z'],$m)}(1..$m)} #test &f('/tmp/t'); ``` **Treasure:** ``` sub f{open($i,"<$_[0]");$x=$y=0;@l=<$i>;while($y<=$#l){$x=1+index$l[$#l-$y],$_[1];@a=($x,$y+1)if($x);$y++;}return\@a} #test @b=@{&f('/tmp/t','f')}; print join(",",@b); ``` I'll work on 6-9 tomorrow. [Answer] # WIP. Note, character counts may be off due to `'\n'` and `wc` ### [1 Greenway] Mindf\*ck, 54 characters ``` >>+[+>,-]<[<]>,<<++++++++[>>------<<-]>>[>[.>]<[<]>-] ``` Usage: Once the code is written, input your string, and terminate your string with a ^a (ctr+a), then immediately after, enter your number. One caveat: the number given must only be from 0-9 (if you wish a larger one, the ascii value-48 of whatever character you input will be used as `n`) Screenshot: ![Screenshot](https://i.stack.imgur.com/8287i.png) ### [3 Curry for Dinner] Javascript, 59 characters ``` function f(x,y){return function(){n=x();while(--n!=0)y();}} ``` ### [4 Spew] BASH, 56 characters ``` f(){ dd if=/dev/urandom of="$1" count=$((RANDOM%30+2));} ``` ### [7 Time Flies When You're Playing Golf] C, 334 Characters (412 with macro definition) ``` #define E(A) else if(s[A]== #define G(A) else if(A)m= #define M(A) &&m!=A)h=A int (*f(char* s)){short h=0,m=0;if(s[0]=='\\')m=11;G(s[2]=='|')12;G(s[4]='/')1;G(s[11]=='-')9;G(s[15]=='-')3;G(s[22]=='/')7;G(s[24]=='|')6;G(s[26]=='\\')5;if(s[7]=='\\'M(11);E(8)'|'M(12);E(9)'/'M(1);E(12)'-' M(9);E(14)'-'M(3);E(18)'/'M(7);E(19)'|'M(6);E(20)'\\'M(5);int* i=malloc(sizeof(int)*2);i[0]=(h==0)?m:h;i[1]=m*5;return i;} ``` Note: this function returns a pointer to a two dimensional integer array, formatted like so: {3, 55} (for a clock position of hour on 3, minute on 11) ### [9 Slacker News] PHP, 246 characters ``` function f($a,$b,$c){$t=file_get_contents("http://x.co/3WQoY");$g=explode('d class="t',$t);$f=fopen($c,"w");for($i=1;++$i!=count($g)-10;){$e=explode("\x3e",$g[$i]);fwrite($f,"\x3ch1\x3e".str_replace($a,$b,s ubstr($e[2],0,-3))."\x3c/h1\x3e\n");}} ``` **Seperate/Original implementation in BASH+AWK, 218 characters** ``` f(){ wget -qO- x.co/3WQoY|grep "e_"|awk '{n=split($0,a,"d class=\"t");for(q=1;++q!=n-10;){split(a[q],b,"\x3e");m=substr(b[3],0,index(b[3],"\x3c/")-1);gsub("'"$1\",\"$2"'",m);print "\x3ch1\x3e"m"\x3c/h1\x3e" }}'>"$3";}; ``` [Answer] # 1654 ## 1. Greenway (Haskell - 37) ``` f x y=do print(concat(replicate x y)) ``` ## 2. Somewhere in the Rough (Mathematica - 43) ``` f[t_,s_,n_]:=StringPosition[t, s][[n+1, 1]] ``` ## 3. Curry for Dinner (Lisp - 58) ``` (defun f(x y)(lambda()(dotimes(c(funcall x))(funcall y)))) ``` ## 4. Spew (Matlab/Octave - 83) ``` function x(f) save f arrayfun(@char,randi(255,randi(255),randi(255))) endfunction ``` ## 5. Treasure Hunt (C - 176) ``` char* f(char* s,char c){FILE* n;char* r;int i=0,j=0,k=0;n=fopen(s,"r");while(!feof(n)){k=fgetc(n);if(k==(int)c)break;j++;if(k=='\n'){i++;j=0;}}sprintf(r,"%d %d",i,j);return r;} ``` ## 6. Bridge on the River Kwai (Ruby - 192) ``` def f(l) trouse="\n%s" rs = l[0].to_s for i in 1..l.length-1 s = "/%+d\\"%(l[i]-l[i-1]) print " "*l[i-1].to_s().length+s rs += " "*s.length+"%d"%l[i] end puts trouse%rs end ``` ## 7. Time Flies When You're Playing Golf (Node.js - 406) ``` function f(n){var g,h,m,q;fs.readFile(n,'ascii',function(e,d){l=d.split('\n');g=function(x,y){try{return l[x][y].trim()&&1;}catch(e){return 0;}};h=g(0,0)*11||g(0,2)*12||g(0,4)*1||g(2,0)*9||g(2,4)*3||g(4,0)*7||g(4,2)*6||g(4,4)*5;m=(g(1,1)&&h!=11)*55||(g(1,2)&&h!=12)*0||(g(1,3)&&h!=1)*5||(g(2,1)&&h!=9)*45||(g(2,3)&&h!=3)*15||(g(3,1)&&h!=7)*35||(g(3,2)&&h!=6)*30||(g(3,3)&&h!=5)*25||h*5%60;return [h,m];});} ``` ## 8. Timber! (Go - 329) ``` func f(p string)bool{ x,_:=ioutil.ReadFile(p) b:=strings.Split(string(x),"\n") for j:=0;j<len(b)-2;j++{ for i:=0;i<len(b[j]);i++{ r,o:=1,0 switch string(b[j][i]){ case " ": continue case "/": r,o=0,-1 case "\\": r,o=0,1 } if i+o<len(b[j]) && b[j+r][i+o]==' ' { return false } } } return true } ``` ## 9. Slacker News (Python - 330) ``` def f(s,r,p): w=urllib2.urlopen('http://news.ycombinator.com') a=[l.get_text() for l in BS(w).body("a") if l.find_parent("td", class_="title")] t=lambda x:u"\x3c{}\x3e{}\x3c/{}\x3e".format(x,'{}',x) m=''.join(t("h1").format(l.replace(s,r)) for l in a[:20]) with open(p,'w') as h: h.write(t("html").format(m).encode('utf8')) ``` [Answer] I’m a cheater & I ain’t played all 9 holes … *yet*. Nonetheless, here’s my hole 8, “Timber” solution in Perl (149 char). One of my coworkers put this up as as a challenge at work. We’ve been having fun with it, especially me, since I have the lowest par solution so far! Our rules were that it had to be a stand alone script that outputted `true` or `false` followed by a newline to `STDOUT`, and that no “shebang” was OK. Below is the “minified” solution. I also put up a “[gist](https://gist.github.com/roosto/9bac5ad8bad9441bdee0)” of the same that includes non-“minified” code & (often tortuously long) explanations of the reasoning behind my approach. --- ``` $r=tru;open F,pop;while(<F>){y/0/6/;s/^|\s|$/0/g;s#\\(?=0)|(?<=0)/|[^\\/0]#6#g;@n=split//;for(0..@n){!$n[$_]&&$l[$_]==6?$r=fals:1}@l=@n;}print$r,'e ' ``` [Answer] I am too lazy to modify it according to the competition rules Meh, but it works fine... ``` from numpy import * import sys def greenway(c,n): print c*n def somewhereintherough(t,s,n): i=-1 count=0 while(count<n): i = t.find(s,i+1) count+=1 return i def curryfordinner(x,y): def g(): for i in range(x()): y() return g def spew(p): f = open(p,'w') n = random.randint(1,28) for i in range(n): if(i>0): f.write('\n') str1 = ''.join([chr(random.randint(32,126)) for _ in range(n)]) f.writelines(str1) f.close() print "Grid size: ",n,'x',n def treasurehunt(p,c): f = open(p,'r') arr = f.readlines() n = len(arr) f.close() f = open(p,'r') found=False for i in range(n): line = f.readline() #print line loc = line.find(c) if(loc!=-1): print c,"found in",p,"at",i,loc found=True break if(not found): print c,"not in",p f.close() def bridgeontheriverkwai(l): str_list = [] for i in range(len(l)-1): sign = '+' if l[i+1]-l[i]>0 else '-' str_1 = '/'+sign+str(abs(l[i+1]-l[i]))+'\\' sys.stdout.write(' '*(len(str(l[i])))+str_1) str_list.append(str_1) print for i in range(len(l)): if i<len(l)-1: print str(l[i])+' '*(len(str_list[i])-1), else: print l[i] def timeflieswhenyoureplayinggolf(p): f = open(p,'r') #clock = [[0]*5,[0]*5,[0]*5,[0]*5,[0]*5] line1 = f.readline() line2 = f.readline() line3 = f.readline() line4 = f.readline() line5 = f.readline() h = 0 m = 0 if line1.find('\\')!=-1: h = 11 m = 55 elif line1.find('|')!=-1: h = 12 m = 0 elif line1.find('/')!=-1: h = 1 m = 5 elif line5.find('/')!=-1: h = 7 m = 35 elif line5.find('|')!=-1: h = 6 m = 30 elif line5.find('\\')!=-1: h = 5 m = 25 elif line3[4]=='-': h = 3 m = 15 elif line3[0]=='-': h = 9 m = 45 if line2[1]=='\\' and h!=11: m = 55 elif line2[3]=='/' and h!=1: m = 5 elif line3[1]=='-' and h!=9: m = 45 elif line3[3]=='-' and h!=3: m = 15 elif line4[1]=='/' and h!=7: m = 35 elif line4[3]=='\\' and h!=5: m = 25 elif line2[2]=='|' and h!=12: m = 0 elif line4[2]=='|' and h!=6: m = 30 print h,m def timber(p): f = open(p,'r') linecount=0 line_size = 0 line = f.readline() while(line): linecount+=1 line_size = max(line_size,len(line)-1) line = f.readline() block = array([[0]*line_size]*linecount) f.seek(0) for i in range(linecount): line = f.readline() for j in range(len(line)-1): if(line[j]==' '): block[i][j]=0 elif(line[j]=='/'): block[i][j]=1 elif(line[j]=='\\'): block[i][j]=2 else: block[i][j]=3 f.close() for i in range(linecount): for j in range(line_size): if(block[i][j]==1 and j!=0 and block[i][j-1]==3): block[i][j]=4 for j in range(line_size-1,0,-1): if(block[i][j]==2 and j!=line_size-1 and block[i][j+1]==3): block[i][j]=4 for i in range(linecount): for j in range(line_size): if(block[i][j]==3 and i<linecount-1 and block[i+1][j]==0): print "Unsafe Structure" return print "Safe Structure" def slackernews(s,r,p): import urllib2 response = urllib2.urlopen('https://news.ycombinator.com') html = response.read() titles_list = [] ix = -1 count = 0 index_list = [] while(count<21): ix = html.find("<td class=\"title\"",ix+1) index_list.append(ix) count+=1 for i in range(len(index_list)-1): line = html[index_list[i]:index_list[i+1]] line = line[line.find("a href"):] start = line.find('>') end = line.find('<') titles_list.append(line[start+1:end]) f = open(p,'w') for title in titles_list: title = title.replace(s,r) f.write('<h1>'+title+'</h1>') print "Done writing, Check : ",p f.close() greenway('test!',2) s='this is a cat. this is a dog. dog is an animal, animal is a beast in disguise.' t='is' ix=somewhereintherough(s,t,8) print ix,s[ix:] def x(): return 4 def y(): print ' !y_called! ' g = curryfordinner(x,y) g() spew('test.dat') treasurehunt('test.dat','a') bridgeontheriverkwai([-7,-22,6,9]) timeflieswhenyoureplayinggolf('clock.dat') timber('block.dat') slackernews('a','b','slacker.html') ``` [Answer] First code golf! (Still a work in progress...) # 1. Greenway Language: Python 3.2.3 File size: 23 bytes Code: ``` def f(c,n): print(c*n) ``` # 3. Curry for Dinner Language: Python 3.2.3 File size: 64 bytes Code: ``` def f(x,y): def g(): for i in [1]*x(): y() return g ``` [Answer] Another work in progress here, and I'm at work so I'll head back later. **Greenway** in Ruby (14 characters, 24 with *#alligator*), call with `f.(c, n)` ``` f=->c,n{p c*n}#alligator ``` ***Screenshot*** ![Greenway](https://i.stack.imgur.com/t2d6P.png) **Somewhere in the Rough** in CoffeeScript (38 characters) ``` f=(t,s,n)->t.split(s,n).join(s).length ``` ***Screenshot*** ![Somewhere in the Rough](https://i.stack.imgur.com/a4Zv5.png) **Curry for Dinner** in JavaScript (54 characters) ``` f=function(x,y){return function(){for(i=x();i--;)y()}} ``` ***Screenshot*** ![Curry for Dinner](https://i.stack.imgur.com/jtKeF.png) **Spew** in PHP (111 characters) This requires `short_open_tag` in the PHP configuration file to be enabled. Otherwise the opening delimiter should be `<?php`, the `@` symbols are used to silence `PHP_NOTICE` errors that are thrown for avoiding enclosing `rand` in quotes, and for not explicitly declaring the `$s` variable. This will generate a square grid of ascii characters between 4 and 30 characters on both axis. ``` <? @$r=rand;$x=$r(4,30);for($i=$x*$x;--$i;){@$s.=$i%$x!=0?chr($r(33,126)):"\n";}file_put_contents($argv[1],$s); ``` ***Screenshot*** ![Spew](https://i.stack.imgur.com/fzLi7.png) [Answer] # 1. Greenway (Python 2: 20) ``` def a(x,n):print x*n ``` Example input: `a("asdf",3)` -> string(`asdfasdfasdf`) # 2. Somewhere in the Rough (Python 2: 47) ``` def b(t,s,n):return len(s.join(t.split(s)[:n])) ``` Example input: `b("1,2,333,4,5,6",",",3)` -> int(7) # 3. Curry for Dinner (Javascript: 61) ``` function c(a,b){d=a();return function(){while(d){d--;b()}};}; ``` Example input: `function z(){ return 3; }; function y(){ console.log( '1' ) }; myfunc = c(z,y); myfunc();` -> logs `string(1)` to the console... 3 times. As per the specs, `c` returns a function, and doesn't actually execute that function itself. # 4. Spew (C++11: 171) ``` #include<fstream> using namespace std;void d(string f){ofstream o;int i=rand()%10;int j=rand()%10;o.open(f);for(int x=0;x<i;x++){for(int y=0;y<j;y++){o.put(rand()%256);}}} ``` Not actually tested this, but should work. [Answer] Some indentation is left intact for readability but it was taken out when counting characters. The total is around ~~1227~~. Or not, I forgot a problem. ~~1486~~ 1465 characters. **1. MIPS ASM (55 chars)** ``` #a0 : the address of the null terminated string. #a1 : the repetition count. f: li $v0,4 syscall addi $a1,$a1,-1 bne $a1,$0,f jr $ra ``` **2. Scheme (52 chars)** ``` (define (f t s n)(list-ref(string-search-all s t)n)) ``` **3. F# (39 chars)** ``` let f x y=fun()->for i in 1..x() do y() ``` **4. Powershell (133 chars)** ``` Function f($p){ $r=(Get-Random)%100 $z="";for($b=$r*$r;$b -gt 0;$b--){$z+=[char](33+(Get-Random)%94);if($b%$r -eq 1){"$z">>$p;$z=""}} } ``` **5. C++ (~~184~~ 152 chars)** ``` #include <istream> #include <string> int*f(std::string p,char c){int*x=new int[2]();std::ifstream i(p);for(;i>>p;x[1]++)if((x[0]=p.find(c))>0)return x;} ``` **6. C# (~~291~~ 282 chars)** ``` static void f(List<int> l) { var z = ""; var o = l[0].ToString(); for (int j = 1; j < l.Count;j++) { int p = l[j-1]; int i = l[j]; var q = "/"+(i-p<0?"":"+")+(i-p).ToString()+"\\"; o += new String(' ',q.Length)+i.ToString(); z+=new String(' ',p.ToString().Length)+q; } Console.Out.Write(z+"\n"+o); } ``` **7. Haskell (~~318~~ 306 chars)** I was looking for an excuse to try out Haskell. I thought I was clever by generating the list of positions via combinations of numbers, but with the number of characters it took I could have hard coded the damn thing. Oh well. The code is atrocious but it was fun to write anyway. edit: Fixed so it correctly returns minutes. ``` w i s=[s!!(j!!1)!!(j!!0)/=' '|j<-mapM(const i)[1,2],j/=[2,2]] k[e,r](i,o,n)|i&&o=[e, n]|i&&not o=[n, r]|not$o||i=[e, r] g s=let[h,m]=foldl k[0,0](zipWith3(\x y z->(x,y,z))(w[1,2,3]s)(w[0,2,4]s)[11,9,7,12,6,1,3,5])in let u=mod(m*5)60 in if h==0 then[m,u]else[h,u] f p = do s<-readFile p return$g$lines s ``` **8. Lua (259 chars)** I was surprised to find that strings didn't support array style indexing, so I had to rely on sub. ``` function f (p) s=' ' g='' for l in io.open(p):lines() do l=l..s:rep(#g-#l) for v=1,#g do d=({['/']=v-1,['\\']=v+1,[s]=0})[g:sub(v,v)] or -1 if l:sub(v,v)==s and (d<0 or d>0 and g:sub(d,d)==s and l:sub(d,d)==s) then return false end end g=l end return true end ``` **9. Python (187 chars)** Thanks to grc/Tyroid for the url shortener. ``` import urllib2 def f(s,r,p):[open(p,'a').write('\074h1\076'+i.split("\074")[0].replace(s,r)+'\074/h1\076') for i in urllib2.urlopen("http://x.co/3WYmQ").read().split("\074title\076")[2:]] ``` ]
[Question] [ ## Background Hello golfers! I would like to learn all the programming languages! But I kinda have a short attention span... and copying all the Hello World examples gets boring... but I like fire! ^w^ ## Challenge So here is the plan! I want you all to write the smallest code that will compile, print `Goodbye Cruel World!`, and then crash. Or, as a bonus twist challenge, print `Hello World!` and crash with `Goodbye Cruel World!` ## Rules * Your score will be total character count used. The answer must be a whole executable program. * Your program must print `Goodbye Cruel World!` to output, and then crash (unexpected error). + For a score bonus, you must print `Hello World!` to output instead, but the error message must also contain `Goodbye Cruel World!`. If you complete the bonus challenge, you may divide your score by 2. (Include a ! at the end of your score if you are claiming the bonus!) * As long as the standard output still prints, and standard error still prints, the order doesn't matter. Just as long as neither can block the other from happening. * The output must contain the contents of the above; `"` shouldn't appear in the output. * The output should contain the specified string, and nothing else. * The crash report can contain anything, but to claim the bonus, the following regex should match `/Goodbye Cruel World!/mi` (aka, contains, ignore case/surrounding text)) * The strings `Hello World!` and `Goodbye Cruel World!` are case insensitive, but otherwise should appear exactly as above. * If the language is capable of crashing (it cannot change its exit code), it needs to crash. Otherwise use the standard "error report" (i.e., `STDERR`) for the language. I can crash Python 3, so I have included an [example](https://codegolf.stackexchange.com/a/125283/61474) Python 3 answer! Now lets all set the world on fire! ^W^ ``` var QUESTION_ID=125282,OVERRIDE_USER=0;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:+r.match(SCORE_REG)[0],language:r.match(LANG_REG)[0].replace(/<\/?[^>]*>/g,"").trim(),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=/\d+((?=!?$)|(?= Bytes))/i,OVERRIDE_REG=/^Override\s*header:\s*/i;LANG_REG=/^[^,(\n\r\|]+/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/Sites/codegolf/all.css?v=617d0685f6f3"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{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] # C, 43 bytes ``` main(){puts(puts("Goodbye Cruel World!"));} ``` Prints the string and then tries to use the return value as a pointer to another string to be printed, which causes a segmentation fault. [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oLSkWANMKLnn56ckVaYqOBeVpuYohOcX5aQoKmlqWtf@/w8A) # C, 42 bytes *Thanks to @Ruslan!* ``` main(i){i=puts("Goodbye Cruel World!")/0;} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1OzOtO2oLSkWEPJPT8/JakyVcG5qDQ1RyE8vygnRVFJU9/Auvb/fwA) **Just for fun: C (on 64-bit Linux), 149 bytes** Modified from [this Hello World -program here](http://jroweboy.github.io/c/asm/2015/01/26/when-is-main-not-a-function.html). ``` const int main[]={-443987883,440,113408,-1922629632,4149,1358336,84869120,15544,266023168,1869563654,1702453860,1970422560,1461742693,1684828783,33}; ``` [Try it online!](https://tio.run/##Fc0xCgMxDETRq@wBtGBpxrJEyEmWFMFF2CKbItuFnN1xuuHzYPr66H2M/jre57If5/K878d2u35WEhktAkIWUQVLyKpp5pYOEypTFDUAl2B4qk1YKynmXgzqITp7dXilaCvGivCpshWa1f@ka6N5QqZn2DyFAN/LGD8) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` “¿µƝɓṭỵae»Ȯ: ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4oCcwr/CtcadyZPhua3hu7VhZcK7yK46//8 "Jelly – Try It Online") Explanation: ``` “¿µƝɓṭỵae»Ȯ: Ȯ Print “¿µƝɓṭỵae A string... » Decoded from base-250 : Integer division ``` As the integer division is a dyad, it will implicitly take the chain's current value as both arguments - which is a string. Crashes because it expects integers. [Answer] # sed, 32 bytes ``` iGoodbye Cruel World! w/dev/full ``` `i` inserts a line, and `w` writes to a file. `/dev/full` in this case because all writes to it return `ENOSPC` ("No space left on device"). It still needs a single line of input to work, though. ``` $ echo 1 | sed -f crash.sed Goodbye, cruel world! sed: couldn't flush /dev/full: No space left on device ``` [Answer] # R, ~~22~~ 20! bytes ~~(44/2)~~ (40/2) ``` cat("Hello World!") `Goodbye Cruel World!` ``` [Try it online!](https://tio.run/##K/r/PzmxREPJIzUnJ18hPL8oJ0VRSZMrwT0/PyWpMlXBuag0NQcqnvD/PwA "R – Try It Online") ### Output: > > Hello World! > > > Error: object 'Goodbye Cruel World!' not found > > > Saved two points thanks to [digEmAll](https://codegolf.stackexchange.com/users/41725/digemall) [Answer] ## [><>](https://esolangs.org/wiki/Fish), 25 bytes ``` "!dlroW leurC eybdooG">o< ``` Basically it adds the string to the stack (Backwards, last in first out) and then does the equivalent of: ``` while(1): pop the stack print the character ``` When there are no characters left on the stack (The whole string has been printed) popping the stack gives an error [Answer] # Python 3 | Score: ~~24.5!~~ ~~23~~ 22! ``` print("Hello World!")+"Goodbye Cruel World!" ``` Print "Hello World", than use invalid operator '+' on "Goodbye Cruel World!" to the NoneType return element. (cut out \n\r from previous version) [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8kjNScnXyE8vygnRVFJU1vJPT8/JakyVcG5qDQ1Byb@/z8A "Python 3 – Try It Online") # Python 3 | Score: ~~34~~ 30 ``` +print("Goodbye Cruel World!") ``` Print Goodbye, than do an invalid unary + operation on print result (NoneType) [Try it online!](https://tio.run/##K6gsycjPM/7/X7ugKDOvREPJPT8/JakyVcG5qDQ1RyE8vygnRVFJk@v/fwA "Python 3 – Try It Online") [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~15~~ ~~25~~ 17 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) / 2 = 8.5! ``` Q7┌θ/²?‘■←#c℮‘o0n ``` Explanation: ``` ...‘ push "goodbye cruel world!" ...‘ push "hello world!" o output "Hello World!" 0n attempt to make an array where each line is 0 characters long, making the array required to be infinite, which crashes (OutOfMemoryError) ``` (Ab)uses the fact that SOGL uses STDERR as a debug output, so in it there is a lot of text, along with the line ``` `∑`@22: ["goodbye cruel world!"] ``` If you piped the STDOUT of the Processing sketch to a file, the "Goodbye Cruel World!" would be there. [Answer] ## Lua, ~~31~~, 30 bytes ``` a=-print'Goodbye Cruel World!' ``` first prints out 'Goodbye Cruel World!' and then crashes when trying to add a nil value and 0. **Output:** ``` Goodbye Cruel World! input:1: attempt to perform arithmetic on a nil value ``` *Credit to [GalladeGuy](https://codegolf.stackexchange.com/questions/125282/goodbye-cruel-world/125371#comment412585_125371) for 1 byte less* [Answer] # C Preprocessor, 27 bytes ``` #error Goodbye Cruel World! ``` Output: ``` fatal error C1189: #error: Goodbye Cruel World! ``` [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 45/2 = 22.5 bytes ``` f={hint"Hello World!";a Goodbye Cruel World!} ``` **Call with:** ``` call f; ``` **Output:** [![](https://i.stack.imgur.com/J7xL1.jpg)](https://i.stack.imgur.com/J7xL1.jpg) [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 72 bytes, Score 36! ``` BEGIN{print"Hello World!";print"Goodbye Cruel World!">"/dev/stderr";0/0} ``` [Try it online!](https://tio.run/##SyzP/v/fydXd06@6oCgzr0TJIzUnJ18hPL8oJ0VRyRoi5p6fn5JUmargXFSamgOTs1PST0kt0y8uSUktKlKyNtA3qP3/HwA "AWK – Try It Online") `AWK` isn't fond of trying to divide by 0. [Answer] # [CJam](https://sourceforge.net/p/cjam), 34 bytes, score 17! ``` "Goodbye Cruel World!"D>"Hello"ooo ``` [Try it online!](https://tio.run/##S85KzP3/X8k9Pz8lqTJVwbmoNDVHITy/KCdFUcnFTskjNScnXyk/P///fwA "CJam – Try It Online") (See Debug panel for STDERR) ### Explanation ``` "Goodbye Cruel World!" e# Push "Goodbye Cruel World!". D> e# Slice after index 13: " World!". "Hello"o e# Push "Hello" and print it. o e# Print " World!". o e# Attempt to print from an empty stack. Crashes. ``` On TIO, it generates this error message: ``` "Goodbye Cruel World!"D>"Hello"ooo ^ RuntimeException: The stack is empty Java exception: java.lang.RuntimeException: The stack is empty at net.aditsu.cjam.CJam.pop(CJam.java:75) at net.aditsu.cjam.Op1.run(Op1.java:10) at net.aditsu.cjam.Block.run(Block.java:304) at net.aditsu.cjam.CJam.runCode(CJam.java:210) at net.aditsu.cjam.CJam.main(CJam.java:240) ``` [Answer] # C#, 116 / 2 = 58 bytes! ``` using System;class P{static void Main(){Console.Write("Hello World!");throw new Exception("Goodbye Cruel World!");}} ``` Normal version for ~~94~~ 87 bytes: ``` class P{static void Main(){System.Console.Write("Goodbye Cruel World!");int n=0;n/=n;}} ``` *Saved 7 bytes thanks to @KevinCruijssen.* [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 17.5 bytes ### Without bonus, 20 bytes ``` Goodbye Cruel World! ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b97fn5KUmWqgnNRaWqOQnh@UU6KIkjmfxoA "APL (Dyalog Unicode) – Try It Online") Note that the code is unquoted, so APL tries to execute it but `World` is not defined, causing a VALUE ERROR crash with the offending line of code included in the error message. ### With bonus, 35 ÷ 2 = 17.5 bytes ``` 'Hello World!' Goodbye Cruel World! ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@6R2pOTr5CeH5RToqiOpd7fn5KUmWqgnNRaWoOVBSk8H8aAA "APL (Dyalog Unicode) – Try It Online") First prints the required string, then crashes like the above program. ### More sofisticated bonus version, 35 ÷ 2 = 17.5 bytes ``` ⍎'Goodbye Cruel',5↓⎕←'Hello World!' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@j3j519/z8lKTKVAXnotLUHHUd00dtkx/1TX3UNkHdIzUnJ18hPL8oJ0VRHaThfxoA "APL (Dyalog Unicode) – Try It Online") Prints the first string, then drops the first five characters from that (`5↓`), then concatenates that (`,`) to a new prefix, and then attempts to execute (`⍎`) that, causing the same error as above. [Answer] # TeX, 19! ``` Hello World!#\bye Goodbye Cruel World! ``` To force TeX to actually produce a dvi/pdf file without manual intervention, compile with `-interaction=nonstopmode`. It prints `Hello World!`, throws an error for using `#` when you're not supposed to and then stops compilation with `\bye`. However, whatever's after `\bye` is still output in the error message, so it applies for the bonus. [Answer] # WinDBG (Windows XP/Vista Local Kernel Debugging), 33 bytes ``` .echo Goodbye Cruel World!;.crash ``` Warning: This will crash the entire machine, not just the program. Local kernel debugging is only allowed on Windows XP and Vista (but not enabled by default in Vista). The WinDBG dialog on local kernel debugging does't mention any other Windows OS so I assume it can't even be enabled for those. Presumably for other Windows OS's you can attach to a remote machine for kernel debugging, but it's the remote machine that will crash so I don't think this solution counts there. [Answer] # JS (ES5), 46 / 2 = 23 bytes! ``` alert("Hello, World!")["Goodbye Cruel World!"] ``` Alerts `Hello, World!`, then errors with `Uncaught TypeError: Cannot read property 'Goodbye Cruel World!' of undefined` [Answer] **Bash ~~20.5!~~ 18.5!** I am not going to bash jelly, but I am a little bashful of my bash at bashing out a quick bash script. 18.5 isn't too bad for a non-golfing language. (Note this has to be a script, interactive bash will try to interpret `!` as a history lookup) ``` echo Hello World! Goodbye\ Cruel\ $_ ``` Returns with error code 127 and: ``` Hello World! bash.sh: line 2: Goodbye Cruel World!: command not found ``` As requested no `"`'s... anywhere `:)`. As suggested by `apricot boy` I now lookup the last argument of the previous command to save 4 bytes. [Answer] # PowerShell, 26 Bytes ``` 'Goodbye Cruel World!';1/0 ``` I think dividing by 0 is the easiest way to throw an error. # PowerShell, 35/2 = 17.5 Bytes ``` "Hello World!";Goodbye Cruel World! ``` by [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler), throws the error like so: ``` PS C:\Users\Connor> "Hello World!";Goodbye Cruel World! Hello World! Goodbye : The term 'Goodbye' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:16 + "Hello World!";Goodbye Cruel World! ``` [Answer] # [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 58/2=29 bytes! ``` PRINT*,'Hello World!' ERRORSTOP 'Goodbye Cruel World!' END ``` [Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8PCPL0C9HSUfdIzcnJVwjPL8pJUVTncg0K8g8KDvEPUFB3z89PSapMVXAuKk3NQSjwc/n/HwA "Fortran (GFortran) – Try It Online") [Answer] ## Node.js, Score: ~~25.5~~ 24.5! *Saved 1 point thanks to ETHproductions* A syntactically correct full program which crashes at runtime because `console.log()` is not returning a function. ``` console.log('Hello World!')`Goodbye Cruel World!` ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/OT@vOD8nVS8nP11D3SM1JydfITy/KCdFUV0zwT0/PyWpMlXBuag0NQcqnPD/PwA "JavaScript (Node.js) – Try It Online") [Answer] # [Aceto](https://github.com/aceto/aceto), score: 21.5! ``` yeru b Ce+ do l"d GoWorl "!dl p"or HeW "llo ``` Prints `Hello World!`, then crashes with ``` Traceback (most recent call last): File "/Users/l3viathan/bin/aceto", line 230, in _plus self.push(y+x) TypeError: unsupported operand type(s) for +: 'int' and 'str' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/l3viathan/bin/aceto", line 811, in <module> A.run() File "/Users/l3viathan/bin/aceto", line 104, in run raise e File "/Users/l3viathan/bin/aceto", line 98, in run self.step() File "/Users/l3viathan/bin/aceto", line 152, in step method(self, cmd) File "/Users/l3viathan/bin/aceto", line 233, in _plus raise CodeException(f"Can't add {x!r} to {y!r}") __main__.CodeException: Can't add 'Goodbye Cruel World' to 0 ``` [Answer] # Pyth, ~~28~~ 24 bytes ``` "GOODBYE CRUEL WORLD!"hY ``` Prints a string, then tries to get the first element of the empty list. [Try this!](https://pyth.herokuapp.com/?code=%22GOODBYE+CRUEL+WORLD%21%22hY&debug=0) [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 bytes ``` °Oo`!dlžW ¤¨C eybºoG`w ``` ``` °Oo`!dl&#158;W ¤¨C eybºoG`w Oo output `!dl&#158;W ¤¨C eybºoG` the compressed string "!dlroW leurC eybdooG" w reversed. ° ° transpiles to ++, causing an error; a string can't be incremented ``` [Try it online!](https://tio.run/##y0osKPn//9AG//wExZScQ/PCFQ4tObTCWSG1MunQrnz3hPL//wE "Japt – Try It Online") Saved 3 bytes thanks to obarakon and ETHproductions [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10.5! bytes ``` “,ḷṅḳȦ»¹“¿µƝɓṭỵae»+/R ``` [Try it online!](https://tio.run/##ATQAy/9qZWxsef//4oCcLOG4t@G5heG4s8imwrvCueKAnMK/wrXGncmT4bmt4bu1YWXCuysvUv// "Jelly – Try It Online") This exploits undefined behavior, using Python strings (strings) instead of Jelly strings (list of 1-char strings). The conversion is done by reducing the Jelly string by addition, and Python's `+` concatenates two strings, so two strings added together are concatenated Python-wise. Then, it uses the appropriate monad (range) so that Python's `int` is called on the string, resulting in an error that would always contain `Goodbye Cruel World!`. Explanation: ``` “,ḷṅḳȦ»¹“¿µƝɓṭỵae»+/R Main Link, niladic. “,ḷṅḳȦ»¹ Print "Hello World!" “¿µƝɓṭỵae»+/ Convert "Goodbye Cruel World!" to a Python string R Make a range out of it ``` [Answer] # x86-64 Binary Code (with Linux system calls), 43 bytes ## Disassembly: ``` 0: 31 c0 xor eax,eax 2: ff c0 inc eax ; write syscall number = 1 4: 31 ff xor edi,edi 6: ff c7 inc edi ; stdout file descriptor = 1 8: 48 8d 35 07 00 00 00 lea rsi,[rip+0x7] ; load the string at offset 16 into rsi f: 31 d2 xor edx,edx 11: b2 15 mov dl,0x15 ; 21 byte string 13: 0f 05 syscall 15: f4 hlt 16: 47 6f 6f 64 62 79 65 20 43 72 75 65 6c 20 57 6f 72 6c 64 21 0a .ascii "Goodbye Cruel World!\n" Note: 0x16 code bytes + 0x15 string bytes = 0x2B = 43 total bytes ``` This program bundles the data it needs (the string `"Goodbye Cruel World!\n"`) into its own code. It loads a pointer to that string using `rip` relative addressing, and calls the `write` syscall directly rather than through a glibc wrapper, so it's entirely position-independent, and we can easily test it by embedding the code into a `const` string and casting that string to a function pointer. To crash the program, I end it with a `hlt` instruction, which with ring 0 privileges would silence the processor forever (or at least until the next interrupt comes in), but with ring 3 privileges (typical for user programs) we get a far less dramatic `Segmentation Fault`. ## Test Program: ``` #include <stdio.h> const char code[43] = "\x31\xC0\xFF\xC0\x31\xFF\xFF\xC7\x48\x8D\x35\x07\x00\x00\x00\x31\xD2\xB2\x15\x0F\x05\xF4Goodbye Cruel World!\n"; int main() { printf("Code bytes: %zi\nNow running the code:\n\n", sizeof(code)); ((void(*)())code)(); printf("Failed to crash, now exiting!\n"); return 0; } ``` ## Output: ``` Code bytes: 43 Now running the code: Goodbye Cruel World! Segmentation fault ``` Note that the 43 byte code *is* a complete program as specified by the challenge, not just a function. It doesn't depend on the `main` function of the test program to function correctly; it would still print the string and crash if loaded and jumped-to by the loader directly. [Answer] # [LOLCODE](http://www.lolcode.org/ "I CAN HAZ LOLCODE"), I CAN HAZ 21 BYTES ``` :Goodbye Cruel World! ``` Simply places an invalid operator in front of the string. [You can give it a go online here.](https://repl.it/IflN/2 "online demo") [Answer] # OCaml, 28.5! (57 Bytes / 2) The [OCaml](http://ocaml.org/) version: ``` print_string"Hello World!";failwith"Goodbye Cruel World!" ``` The output is: ``` Hello World!Fatal error: exception Failure("Goodbye Cruel World!") ``` [Answer] # Rust, 66 bytes / 2 = 33 ``` fn main(){println!("Hello World!");panic!("Goodbye Cruel World!")} ``` [Try it online!](https://play.rust-lang.org/?gist=e6bf2a3b63dbc12beceb9c038236566d&version=stable&mode=debug&edition=2015) Prints "Hello World!" and makes the the program panic with message "Goodbye Cruel World!" The panic! macro doesnt need a semicolon because it returns () just like the main function. [Answer] # x86 and x64\_64 machine language on Linux, ~~38 61 bytes/2=30.5!~~ 60 bytes/2=30! ``` 00: e8 20 00 00 00 call 0x25 05: 48 65 6c 6c 6f 20 57 "Hello World!Goodbye Cruel World!" 6f 72 6c 64 21 47 6f 6f 64 62 79 65 20 43 72 75 65 6c 20 57 6f 72 6c 64 21 25: 59 pop %ecx 26: 6a 01 push $0x1 28: 5b pop %ebx 29: 6a 0c push $0xc 2b: 5a pop %edx 2c: 6a 04 push $0x4 2e: 58 pop %eax 2f: cd 80 int $0x80 31: 01 c0 add %eax,%ecx 33: b3 02 mov $0x2,%bl 35: b2 14 mov $0x14,%dl 37: 2c 08 sub $0x8,%al 39: cd 80 int $0x80 3b: 6e outsb %ds:(%esi),(%dx) ``` Prints `Hello World!` to `stdout` and `Goodbye Cruel World!` to `stderr`. Crashing is easy in machine language. To [Try it online!](https://tio.run/##NYlBCsIwFESvEru20MYuCuLKhd7A1n4Xyc9vbYwJJBWihzdGUIZ5DG@wnBBTQmfDwvAqPLuL2Q6XXQGRWgbVN0cyxrGT80atDs4p@SS29w8yP9drqAcN41lD00FEBbGtoM4rV26AZ3LgzRrk/7XFNqU3jkZMIZUvioRhEXj7AA "C (gcc) – Try It Online"), compile and run the following C program. ``` const char main[]="\xe8 \0\0\0Hello World!Goodbye Cruel World!Yj\1[j\fZj\4X\xcd\x80\1\xc1\xb3\2\xb2\24,\b\xcd\x80n"; ``` EDIT: TIO link now works again. ]
[Question] [ What general tips do you have for golfing in C++? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C++ (e.g. "remove comments" is not an answer). Please post one tip per answer. (Tips that apply to C as well can be found in [Tips for golfing in C](https://codegolf.stackexchange.com/q/2203) - but note that some C tips don't work in C++. For example, C++ *does* require function prototypes and return values.) [Answer] The ternary conditional operator `?:` can often be used as a stand in for simple `if`--`else` statements at considerable savings. It is of special value in that it can be used to select alternate lvalues as in ``` #include <iostream> #include <cstdlib> int main(int c, char**v){ int o=0,e=0,u; while(--c) ((u=atoi(v[c]))%2?o:e)+=u; std::cout << "Sum of odds " << o <<std::endl << "Sum of evens " << e <<std::endl; } ``` [Answer] Sometimes you can save two characters by using the fact that static storage duration variables (that especially includes all global scope variables) are automatically zero-initialized at the beginning (unlike automatic variables where you have no such guarantee). So instead of ``` int main() { int a=0; // ... } ``` you can write ``` int a; int main() { // ... } ``` [Answer] Some compilers (e.g. GCC) support [multi-character constants](https://web.archive.org/web/20161010172930/http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx). This can save a few characters when a large integer value is required. Example: ``` int n=' '; ``` The value is implementation-specific. Usually the value of `'ab'` is `256*'a'+'b'` or `'a'+256*'b'`. You can specify up to 4 characters between the quotation marks. [Answer] # Shorter header This is GCC specific, it may be extensible to other compilers. ### Precompiled header. In G++ `bits/stdc++.h` is the precompiled header consists of all other headers. If you need to `import` 2 different ones you can just use this. ### Shorter header. This is all headers listed on <http://en.cppreference.com/w/cpp/header>: ``` $("#a").text(pako.inflate(atob('eJx9VkuW1DAM3HON2cOGx4o3V8lzK0q3wZ9gy90TTo+dDKCyM710yT9VqWS/2ECuzPzdhO3108vfUeCHGmUWNfJmVSMbsxo5m/VUEutZjaWsTo9NSkYfO/OvouNZDP1U4xqFOHkjNzVORmzU8YXDXcf5ym86lSIwvljBXOmWYtA7evYxbXCEi0aAAl930TM4JdiDSLYV0njQzSQNlA7Ikmy4KuDOJDFB6mGOHoVZHrPeNMsM7LhIBuWQ6C1pvW6Jjd5jKVKSXtII/qwlaIoA0EoAgHYPZy+A2GswDhCWH37tVpmkKShinZWtmzPzomkyyZoAika/GkiBRsUaU7jK5MxJULNexUGkdpaDAgvFcwKKq2Eqx1q4OCDLgOQBsdGbYIGxQV+KM9NdnmvRsgK99vIFZC95QPbSAmSvYEAeA0Jy7QxMNsdvX789RdoFbVh0Jce1+r6roHoYRXC/Fa4NAlxzN67vQXbk/xAfrn7UDEI73UjLXsUI7aXek1cru4dqIQ8Uh4H1Kl4HtRrseB8kpbEyDylg1sH84N1LjG6QY4bNqN604dpU/Ea8y4QJHLAm211jsnLzsJapDGvTaIsduBTdAt5TxTTOsCaDq+rg/Vq2WPwl0FBteQs02tY6zlsWBp++MzNUQDsaG2edNkky2JsOgae7xRe6brA3b9x2P3yqBoaiX2J6mDRP3WOdq2N4nvo3sYSYZm4RfBr/4/ghOF7IKXGOJRFD6lZszfM3p+FsimvdybhmIrQov621ZXoOYtwX/KVACG8BIbw4hPoPSwyzbepO+8txgfYJC/uvCgT7fwgGu08IBPsfEgSH3whEh7cZ6ek/LshQ/3RBdPhsQHR80yA8PtMQPmndqPhpO9Bpn7msI+bEsSfp96ZCYU7diOec+wpPOrckMvaBsz6Y9KS6//Xcp3f62LHdZu9NeFqjs7S9/gHXxXg4'), {to: 'string'})); ``` ``` <script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre id="a"> </pre> ``` sorted in increasing order of length. Some of them are already longer than `bits/stdc++.h`, and some of them requires C++17 support. Some others are not supported by TIO G++ (for reasons I don't know of). Filter out them we have: ``` $("#a").text(pako.inflate(atob('eJx9VcuS3CAMvOc39p5Tak+p/MoUI2SbhIcDYrz++4BdW6WG1B7VYI36IebNRfLV8s/Ix69vb59VYVFVMLuqXCqq8q7oqyQusKql7l7XJmdzqtry36rPixj6o+p2CucUjGyqzkZc0ucLx5c+55U/NJUqUD+dIFfacoq6Y+CQ8gk/4ZMRkCC0LvoG5ww9iOTcgcZBm8kaqANQJLu4KuDFJCkD9WhTQGOWw+qmRSyo4xMZtENScKT92jIb3WOpUrP+pAv8XVvQHQGgRwCAPod3T0DcGo0HhOV32IevTNYSVHHeyTncsbxoZHajqxDBY1MKZ0E/RocmAyiFlmUdnlgDZ5CvLUPTT5uSJmSZkDIhLgUTHagxeUfJMr3ka507K/DiiiYgV5wBuWIDyJVOQI4JIVmH5SRX0vuP9y+RPqCLi06pE25rDVl/GT++HG5W9rYVhrrTgNAlJBK+sofQFdBRlpbHEWrxm8SLk57NlgHq6RoUncyiOXO3yHDr1nTauGdKfhLaQjNqk3Zcrwt/EO/tUY1I4Ia12H5N2ckWkNUc7gt4VljSmxaO/D+sS+6bEzhLZ4YRrpH6yPCifHKbPOwN8cFq1x6SDb4b5SzC4dEWBqK4pHyYbB/DH19p68D2cf+//APa+54V'), {to: 'string'})); ``` ``` <script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre id="a"> </pre> ``` It may happens that some of them can be replaced by shorter ones. Just binary search whether the one you need can be replaced. In particular: ``` cstdio -> ios (-3 bytes) algorithm -> regex (-4 bytes) vector -> queue (-1 byte) string -> map (-3 bytes) bitset -> regex (-1 byte) numeric -> random (-1 byte) ``` [Answer] One that I found handy: Taking advantage of the fact that non-zero values evaluate to `true` in boolean expressions, and that `x&&y` evaluates to `x*y` when dealing with booleans ``` (x!=0 && y!=0) ``` evaluates to ``` (x*y) ``` You just have to be aware of overflows, as pointed out below. [Answer] Instead of using `while(1)`, use `for(;;)`, saving one character :) [Answer] When possible, change `&&` and `||` to `&` and `|` respectively. When using simple if statements: ``` if(<condition>)<stuff>; ``` can be changed to: ``` <condition>?<stuff>:<any single character variable or literal>; ``` which saves a character. [Answer] Using the comma operator in lieu of open and close braces can save a few characters, if you have a situation where your clauses have more than one statement in them: ``` if(c){x=1;cout<<"Hi";y=2;}else{x=2;cout<<"Bye";y=3;} ``` vs. ``` if(c)x=1,cout<<"Hi",y=2;else x=2,cout<<"Bye",y=3;### ``` Two characters saved on a plain IF, or three total for an IF/ELSE. As a point of distinction between C and C++, the result of a comma expression in C++ as a whole may be used as an lvalue...FWIW. [Answer] Use the following types: ``` u64, s64, u32, s32 (or int) ``` For repetitive words/types, use `#defines`: ``` #define a while ``` It's only worth it if you use `while` a lot to make up for the extra 10 characters. ([About 4](http://www.google.ca/search?sourceid=chrome&ie=UTF-8&q=There%20were%20about%20three%20other%20customers%20in%20the%20place,%20sitting%20at%20tables,%20nursing%20beers.%20About%20three.%20Some%20people%20would%20say%20there%20were%20exactly%20three,%20but%20it%20wasn%27t%20that%20kind%20of%20a%20place,%20not%20the%20kind%20of%20a%20place%20that%20you%20felt%20like%20being%20that%20specific%20in.).) [Answer] If you're willing to use C++0x, you can use new features like [lambdas](http://www2.research.att.com/~bs/C++0xFAQ.html#lambda). [Answer] Quite an obvious one, but it you are using a lot of the standard library, `using namespace std;` might save a few characters. [Answer] Since array elements are stored directly after one another in memory, instead of something like this: ``` for(int x = 0; x < 25; x++) { for(int y = 0; y < 25; y++) array[x][y] = whatever; } ``` You can do something like this: ``` int* pointer = array; for(int i = 0; i < 25*25; i++, pointer++) *pointer = whatever; ``` Obviously neither of the above are golfed, for readability, but explicitly using pointers can save you a lot of space. [Answer] # Use GCC builtins instead of importing If you are using a GCC compiler, it sometimes helps to use their builtin functions, such as `__builtin_puts` or `__builtin_clz`. For example, 44 bytes: ``` int main(){__builtin_puts("Hello, world!");}` ``` 50 bytes: ``` #import<cstdio> int main(){puts("Hello, world!");} ``` [Answer] Instead of writing big powers of 10, use **e notation**. For example, `a=1000000000` is longer than `a=1e9`. This can be extended to other numbers like `a=1e9+24` is better than `a=1000000024`. [Answer] You may use the ternary operator `?:` without any expressions in the true-block (it saves a byte) ``` #include <iostream> int foo() { std::cout << "Foo\n"; } int main() { 1?foo():0; // if (true) foo() 0?:foo(); // if (!false) foo() } ``` [Check it here](http://ideone.com/2iUeaH) [Answer] Functions in `<algorithm>` often requires passing `a.begin(),a.end()` which is really long, instead you can use `&a[0],&*end(a)` to save a byte or two if `a` is `vector` or `string`. ``` std::sort(a.begin(),a.end()); std::sort(&a[0],&*a.end()); // with using namespace std; sort(begin(a),end(a)); sort(&a[0],&*end(a)); ``` ``` [Answer] `#import` instead of `#include` gives you one more byte. Also, the space character between `#import` and header is not necessarily: ``` #include <map> // vs #import<map> ``` And if you need something from `stdlib` header, you may import any header with STL container (preferable `set` or `map`) instead of `cstdlib`. [Answer] If you want to swap two integer variables a and b then , ``` a^=b^=a^=b; ``` can be used , saving 5 characters than the standard way ``` a+=b; b=a-b; a-=b; ``` [Answer] Arithmetic operations on Booleans: Although ``` a*=b>0?.5:-.5 ``` is better than ``` if(b>0)a*=.5;else a*=-.5; ``` it is not as good as ``` a*=(b>0)-.5 ``` Also, using #define on anything that is used a lot. It is often shorter than using functions, since type names are not necessary. Combine things as much as possible: ``` a+=a--; ``` is the same as ``` a=2*a-1; ``` [Answer] It is useful to remember is that `a[i]` is the same as `*(a+i)`. Replace `a[0]` with `*a` for two character savings. Also, `a[i][0]` is equivalent to `*a[i]` and `a[0][i]` shrinks down to `i[*a]`. So if you are hard-coding a `0` index in your array, a better way probably exists. [Answer] # Use generic lambdas as cheap templates For types other than `int`, using them as function arguments can be expensive. However, generic lambdas were introduced (in C++14?) and allow any lambda to be a template - using `auto` for the argument types can save bytes. Compare: ``` double f(double x, double y) [](auto x, auto y) ``` Generic lambdas are also very convenient for accepting iterators - probably the best way to accept array inputs in C++ is `[](auto a, auto z)`, where `a` and `z` are passed as `begin()` and `end()` of the array/vector/list/etc. [Answer] If you're doing C++11 or newer (which should always be the case now), use `auto` for complex types, if possible. Example: 54 Bytes instead of 66 ``` #include<vector> std::vector<int> f(std::vector<int> l){return l;} ``` ``` #include<vector> auto f(std::vector<int> l){return l;} ``` Also, as performance does not matter, for some challenges a `std::list` may just do the job for a few bytes less: ``` #include<list> auto f(std::list<int> l){return l;} ``` [Answer] It's rather straightforward to cacluate when replacing something with a `#define` results in shorter code. ``` #define a blabla ``` Where `a` is a single letter name and `blabla` is the replacement of length \$x\$ has in total \$10+x\$ characters. If you have \$n\$ times `blabla` in the code then the `#define` pays off when $$10 + x + n < nx$$ With the define you have \$10 + x\$ to define it and \$n\$-times a single character. Without it you have \$n\$-times `blabla` of length \$x\$. The following table lists how often `blabla` has to appear given its length for the define to make the code shorter: | \$x\$ | \$n\$ | | --- | --- | | 2 | 13 | | 3 | 7 | | 4 | 5 | | 5 | 4 | Because the inequality is symmetric, the same table applies when \$n\$ and \$x\$ are swapped, ie if `blabla` appears \$n = 2\$ times in the code then the `define` results in shorter code when `blabla` is of length \$x \ge 13\$. The formula is $$n > \frac {10 + x} {x - 1}$$ or $$x > \frac {10 + n} {n - 1}$$ PS: Sometines the single letter named preprocessor symbol has to be followed by a space. This shifts the matters a little towards not using the define, but just a little. [Answer] G++ allows for variable-sized arrays, so there is no need to go through the lengthy pointer-malloc-new stuff. ``` int* array = new int[array_size]; ``` becomes ``` int array[array_size]; ``` Saves 9 bytes minimum with int. [Answer] Use `auto` instead of complex type names. This can be done with generic lambdas and C++20 [abbreviated function templates](https://en.cppreference.com/w/cpp/language/function_template#Abbreviated_function_template) ``` int x(std::set<std::string>y){} template<class T>int x(T&y){} int x(auto&y){} [](auto&x){} ``` This also allows you to avoid most includes. Note that g++ on TIO requires `-fconcepts`. [Answer] When writing a full program you can use argc to initialize an integer variable to 1: ``` main(a){ ``` is the same as: ``` main(){int a=1; ``` [Answer] In my first attempt at code golf for [task "Subtract the next numbers"](https://codegolf.stackexchange.com/questions/91903/subtract-the-next-numbers/91916) I have started from function (58 bytes) ``` int f(int N, int P){int F;for(F=N;P;F-=++N,P--);return F;} ``` then safe 5 bytes with shifting to lambda and moving initialization out of `for` (53) ``` [](int N,int P){int F=N;for(;P;F-=++N,P--);return F;} ``` and finally after switching from `for` to `while` I got 51 bytes: ``` [](int N,int P){int F=N;while(P--)F-=++N;return F;} ``` The ungolfed test code is something like: ``` #include <iostream> int main(void) { int N, P; std::cin >> N >> P; auto f = [](int N,int P) { int F = N; while (P--) F -= ++N; return F; }; std::cout << f(N, P) << std::endl; return 0; } ``` **UPDATE:** Actually `for` can reach the same length as `while`: ``` [](int N,int P){int F=N;for(;P--;F-=++N);return F;} ``` [Answer] Kind of late to the party I guess... If you want to turn an expression into -1 and 1 instead of 0 and 1, instead of this: ``` int x; if (a * 10 > 5) x = 1; else x = -1; ``` do this: ``` int x = (a * 10 > 5) * 2 - 1; ``` It can save some bytes depending on usage. [Answer] If you need a type alias, `using` is two bytes shorter than `#define`: ``` #define T ... // newline using T=...; ``` [Answer] Don't use `string("")`, use `""`. It saves 8 bytes. ]
[Question] [ You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a [truthy or falsy](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value, and IO can be in any [reasonable format](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). # Rules and definitions: * For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`. * A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as ``` () []{} ``` Or if every subelement inside of it is also matched. ``` [()()()()] {<[]>} (()()) ``` Subelements can also be nested several layers deep. ``` [(){<><>[()]}<>()] <[{((()))}]> ``` * A string is considered "Fully matched" if and only if: 1. Every single character is a bracket, 2. Each pair of brackets has the correct opening and closing bracket and in the right order, and 3. Each bracket is matched. * You may assume the input will only contain [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters). # Test IO Here are some inputs that should return a truthy value: ``` () [](){}<> (((()))) ({[<>]}) [{()<>()}[]] [([]{})<{[()<()>]}()>{}] ``` And here are some outputs that should return a falsy value: ``` ( Has no closing ')' }{ Wrong order (<)> Each pair contains only half of a matched element (()()foobar) Contains invalid characters [({}<>)> The last bracket should be ']' instead of '>' (((())) Has 4 opening brackets, but only 3 closing brackets. ``` As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~1101, 1085~~, 981 bytes ``` {(<(({}))((((()()()()()){}){}){})({}[{}]<(())>){((<{}{}>))}{}>{({}<>)(<>)}{}<(({ }))((((()()()()()){}){}){}())({}[{}]<(())>){((<{}{}>))}{}>{({}<>)({}[{}](<()>)){ {}{}(<(())>)}{}{<>{{}}<>{{}}((<()>))}{}(<>)}{}<(({}))(((((()()()()()){}){})){}{} )({}[{}]<(())>){((<{}{}>))}{}>{<({}()<>)>()(<>)}{}<(({}))(((((()()()()()){}){})( )){}{})({}[{}]<(())>){((<{}{}>))}{}>{<({}()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{ <>{{}}<>{{}}((<()>))}{}(<>)}{}<(({}))((((()()()){}){}()){({}[()])}{})({}[{}]<(() )>){((<{}{}>))}{}>{<({}()()<>)>()(<>)}{}<(({}))((((((()()()()()){})){}{}())){}{} )({}[{}]<(())>){((<{}{}>))}{}>{<({}()()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{<>{{ }}<>{{}}((<()>))}{}(<>)}{}<(({}))((((((()()()()()){}){}){}())){}{})({}[{}]<(())> ){((<{}{}>))}{}>{<({}()()()<>)>()(<>)}{}<(({}))((((((()()()()()){}){}){}())()){} {})({}[{}]<(())>){((<{}{}>))}{}>{<({}()()()<>)>()({}[{}](<()>)){{}{}(<(())>)}{}{ <>{{}}<>{{}}((<()>))}{}(<>)}{}<{}>[()]){<>{{}}(<()>)<>{{}}(<()>)}{}}<>([]<>)({}< (())>){((<{}{}>))}{} ``` [Try it online!](https://tio.run/##rZNBDsIgFESvM7PoDQgXaVjgwsRoXLj94ew4QDU11Uq1pYVfGCZvUnq4xdN1OF7iOWeDAyyRKBcfjZpqtxZHS0Eq0tMAZ8mSJ0tvWnWe0KPXdSeVXV5NIyxJaEWAaYNKc15TqfWYRFWyIFggsHh9YXAooDLzYI8ntrvulW@GUcbiCwb20qylfI1ZE6rsT7p71g/naQtRf97naf3N/6/McqxfcdI1wbxOdTfG0H6Vt1A5o7I7P4aYh3gH "Brain-Flak – Try It Online") This is 980 bytes of source code, and `+1` for the `-a` flag allowing ASCII input (but decimal output) This is an answer I've been wanting to write for a *very very* long time. At least 6 months. I waited to post this because I knew that answering this challenge would be extra hard in brain-flak. But it's worth it for one very important reason: The source code itself is a truthy input, which is the entire point of this language itself. And as I wrote about [here](http://meta.codegolf.stackexchange.com/a/9957/31716), this question was what inspired me to write brain-flak. > > Shortly after I wrote Are the brackets fully matched?, it made me wonder how much information you can store with only matched brackets. One thing that stood out to me, was that even though you only have 4 "atoms" of sorts: > > > > ``` > (){}[]<> > > ``` > > you really have 8 units of information to convey, since each of these bracket types can be empty, or have other brackets in between, which are fundamentally different pieces of information. So, I decided to write a language that only allowed for matched brackets, and where empty brackets convey something different than brackets with other brackets inside of them. > > > This answer took roughly two hours to write. I'll admit it's pretty poorly golfed, mostly because a lot of the code is repeated for each bracket type. But I'm mostly amazed that I was able to write an answer at all, especially given that Brain-Flak is > > A minimalist esolang designed to be painful to use > > > I'm going to attempt to golf it down later, but I wanted to get this out there anyway. I have a detailed explanation, but it's about 6 thousand characters long, so I think it would not be wise to paste the entire thing into this answer. You can read through it [here](https://gist.github.com/DJMcMayhem/52453a771830a0dcd42323d39396ce54) if you want. I'll add a shorter explanation here. The basic idea, is that we repeat the following steps for every character on the stack: * We check each character to see if it matches any bracket. If it is an opening bracket, we push a number onto the other stack according to the following mapping: ``` ( = 1 < = 2 [ = 3 { = 4 ``` * Then we check to see if it matches any closing bracket. If it does, we push the equivalent number onto the alternate stack, just like for opening brackets. *Then*, we check if the top two numbers are equal. If they are, the both get popped and the program continues as normal. If they are not, we clear both stacks (to stop the looping) and push a one onto the alternate stack. This is essentially a "break" statement. * After checking the 8 bracket types, we push the value of this run through the loop. Since we zero out most of it, the only snippets that have any value are the conditionals when we compare against brackets. So if any bracket is matched, the whole loop has a value of 1. If none of them did, the whole loop has a value of 0. In this case, we will clear both stacks and push a 0 onto the alternate stack. Again, this is like a "break" statement. After this main loop is running, the rest is fairly simple. We are on the (empty) main stack, and the alternate stack is empty (if the brackets were matched) or non-empty if they were not. So we run this: ``` #Toggle to the alternate stack <> #Push this stack-height onto main-stack ([]<>) #Logical not ({}<(())>){((<{}{}>))}{} ``` This will push a 0 or a 1 onto the main-stack, and when the program ends it is implicitly printed. --- * *Thanks to [@WheatWizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard) for coming up with a good stack-clean "equals" and "logical not" snippet, and for regularly updating the [github wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki) with useful examples.* * *Thanks to [@ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) for writing an online [integer metagolfer](https://brain-flak.github.io/integer/) which helped immensely in writing this program* --- *revisions* * *Removed some push pop redundancy* * *Changed my zero counter logic* [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~204~~ ~~196~~ 190 bytes ``` {({}<>)<>((((()()()()()){})(({}){})())({}(({})((({}){})(<()>))))())(({<({}<>[({})])>[()]{()(<{}>)}{}<>}{}()<({}<>[({})]){(<{}({}())>)}{}<>>)){(<({}{}<>[{}]{}<>)>)}{}{<>{{}}}{}}<>((){[()]<>}) ``` [Try it online!](https://tio.run/##1Y5BCsMwDAS/oz3kB0IfKT64h0Bo6KHXRW9PVyIp5AmVwZI1y3qfn7m9l3Wfr@OgMT3gYVW4Dpgwoe6Apn7Zb@eGgKqg0dvlUXBAHYNycWYgi@gy3EQsWrbAqZGdllq1ijk6WEN6kJmasoKC9YNc8ff5l/kF "Brain-Flak – Try It Online") -8 bytes thanks to Wheat Wizard. -6 bytes thanks to Jo King. ### Explanation This program stores the character codes of all current unclosed brackets on the second stack. The bracket pairs `<>`, `[]`, and `{}` each have character codes that differ by exactly 2, so there is no need to check for them specifically. The pair `()` only differs by 1, so we check for `(` specifically, and effectively decrement that byte (actually increment every other byte) before continuing. ``` # While there are bytes left to process { # Move byte to second stack ({}<>)<> # Push 40, 0, 40, 60, 91, 123: (, then null, then all four opening brackets ((((()()()()()){})(({}){})())({}(({})((({}){})(<()>))))()) (( # For each opening bracket type: { # Evaluate as zero < # Compute difference between bracket type and input byte ({}<>[({})]) > # Evaluate loop iteration as -1 if equal, 0 otherwise [()]{()(<{}>)}{}<> } # Remove the 0 that was inserted to terminate that loop {} # Add 1 to result () # Evaluate rest of this expression as zero < # Determine whether the byte is open parenthesis ({}<>[({})]) # If not: { # Add 1 to byte and break if (<{}({}())>) }{} # Return to main stack <> > # Push result twice (0 if matched an opening bracket, 1 otherwise) )) # If byte was not an opening bracket: { # Push zero to break out of if (< # Push (open bracket + 2 - byte) below that zero ({}{}<>[{}]{}<>) >) }{} # If byte was neither an opening bracket nor the appropriate closing bracket: { # Clear alternate stack and stay there to break out of main loop early <>{{}} }{} # End of main loop } # If a prefix was invalid, the top of the other stack is the same nonzero value # that made us break out in the first place. If the string was a valid prefix, # the other stack contains every unclosed bracket. If the string is balanced, # there are none of these. Thus, the other stack is empty if the # brackets are balanced, and has a nonzero value on top otherwise. # Push 1 on other stack if empty, and 0 on current stack otherwise <>((){[()]<>}) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes Input is given in *quotes*. Code: ``` "[](){}<>"2÷)"":g2Q ``` Well crap, a *lot* of bugs and unimplemented features were found. Explanation: ``` "[](){}<>" # Push this string 2÷ # Split into pieces of two ) # Wrap it into an array (which should not be needed) "" # Push an empty string : # Infinite replacement ``` This is actually a tricky part. What this looks like in pseudocode is: ``` input().replace(['[]', '()', '{}', '<>'], "") ``` This is covered by this part from the [05AB1E code](https://github.com/Adriandmen/05AB1E/blob/master/05AB1E.py#L1498): ``` if type(b) is list: temp_string = temp_string_2 = str(a) while True: for R in b: temp_string = temp_string.replace(R, c) if temp_string == temp_string_2: break else: temp_string_2 = temp_string stack.append(temp_string) ``` As you can see, this is **infinite replacement** (done until the string doesn't change anymore). So, I don't have to worry about setting the replacement into a loop, since this is already builtin. After that: ``` g # Take the length of the final string 2Q # Check if equal with 2 (which are the quotes at the end) ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=IltdKCl7fTw-IjLDtCIiOmcyUQ&input=J1soW117fSk8e1soKTwoKT5dfSgpPnt9XSc) (slightly modified because the above version is deprecated). [Answer] ## JavaScript (ES6), ~~52~~ 50 bytes ``` f=s=>(t=s.replace(/\(\)|\[]|{}|<>/,''))==s?!s:f(t) ``` Repeatedly remove brackets until the result is the same as the original, then return false unless the string is now empty. Edit: Saved 2 bytes thanks to @edc65. [Answer] ## Python, 67 bytes ``` lambda s:eval("s"+".replace('%s','')"*4%([],(),{},'<>')*len(s))=='' ``` Generates and evals an expression that looks like ``` s.replace('[]','').replace('()','').replace('{}','').replace('<>','').replace('[]','').replace('()','').replace('{}','').replace('<>','') ``` and checks if the result is empty. Sp3000 saved 8 bytes by pointing out that `[],(),{}` can be subbed in without quotes because they're Python objects, and that two parens were unneeded. [Answer] # Retina, 20 bytes ``` +`\(\)|\[]|{}|<> ^$ ``` [Try it online](http://retina.tryitonline.net/#code=K2BcKFwpfFxbXXx7fXw8PgoKTWBeJA&input=WygpKCkoKSgpXQ) [Answer] ## CJam, ~~25~~ ~~24~~ ~~23~~ 21 bytes *Thanks to Sp3000 for saving 2 bytes.* *Thanks to jimmy23013 for saving 2 bytes.* ``` q_,{()<>}a`$2/*{/s}/! ``` [Test suite.](http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%7B%0A%0AQ_%2C%7B()%3C%3E%7Da%60%242%2F*%7B%2Fs%7D%2F!%0A%0A%7D%26%5DoNo%7D%2F&input=()%0A%5B%5D()%7B%7D%3C%3E%0A(((())))%0A(%7B%5B%3C%3E%5D%7D)%0A%5B%7B()%3C%3E()%7D%5B%5D%5D%0A%5B(%5B%5D%7B%7D)%3C%7B%5B()%3C()%3E%5D%7D()%3E%7B%7D%5D%0A%0A(%0A%7D%7B%0A(%3C)%3E%0A(()()foobar)%0A%5B(%7B%7D%3C%3E)%3E%0A(((()))) Works essentially the same as the other answers: we repeatedly remove `()`, `[]`, `<>` and `{}` from the string and check if we end up with the empty string. To avoid having to check when we're done, we remove the pairs `N` times where `N` is the length of the string, which is always sufficient (since each iteration will remove at least two characters, unless we're done). I'm glad to see that this doesn't beat Retina. :) (Although Pyth or Jelly might...) There's one fun golfing trick here: to get the string `()<>[]{}` we use the following: ``` {()<>}a`$ ``` The, `{()<>}` is just a block (i.e. a function), which contains the other brackets as code. With `a` we wrap the block in an array. The ``` stringifies that array, which gives `"[{()<>}]"`. Finally, we sort the string with `$`, which rearranges the brackets to `()<>[]{}`. [Answer] # Yacc, 119 bytes Does not use regex/replace. ``` %%input:r;r:%empty|'['r']'r|'{'r'}'r|'('r')'r|'<'r'>'r;%%yylex(){return getchar();}main(){return yyparse();}yyerror(){} ``` ## Ungolfed ``` %% # Grammar in BNF input: r; r: %empty | '['r']'r | '{'r'}'r | '('r')'r | '<'r'>'r; %% # Minimal parser invocation and lexer yylex(){return getchar();} main(){return yyparse();} yyerror(){} ``` ## Compilation ``` yacc -o bracket.c bracket.y cc -o bracket bracket.c ``` ## Usage ``` ~/ % echo -n "<()[]>" | ./bracket ~/ % ~/ % echo -n "{" | ./bracket ~/ 1 % :( ``` [Answer] ## Pyth, ~~31~~ ~~25~~ 24 bytes Golfed down to 25 bytes thanks to FryAmTheEggMan Removed 1 byte ``` VQ=:Q"<>|\[]|{}|\(\)"k;! ``` Try it here: [Test suite](https://pyth.herokuapp.com/?code=Vz%3D%3Az%22%3C%3E%7C%5C%5B%5D%7C%7B%7D%7C%5C%28%5C%29%22k%3B%21z&test_suite=1&test_suite_input=%28%29%0A%5B%5D%28%29%7B%7D%3C%3E%0A%28%28%28%28%29%29%29%29%0A%28%7B%5B%3C%3E%5D%7D%29%0A%5B%7B%28%29%3C%3E%28%29%7D%5B%5D%5D%0A%5B%28%5B%5D%7B%7D%29%3C%7B%5B%28%29%3C%28%29%3E%5D%7D%28%29%3E%7B%7D%5D%0A%28%0A%7D%7B%0A%28%3C%29%3E%0A%28%28%29%28%29foobar%29%0A%5B%28%7B%7D%3C%3E%29%3E%0A%28%28%28%28%29%29%29&debug=0) ! I'm still a Pyth newbie, any help is appreciated. ## Explanation ``` VQ For N in range(0, len(z)), with Q being the evaluated input. Optimal solution would be to use range(0, len(z)/2) instead, but it add two bytes. =:Q"<>|\[]|{}|\(\)"k assign Q without {}, [], <> nor () (regex replacement) to Q ; End of For loop ! Logical NOT of Q's length (Q is the input, but has gone several times through y, and Q is implicit). This last operation returns True if len(Q) is 0 (which means all brackets were matched), False otherwise ``` BTW, congrats to the other Pyth answer (which is currently 20 bytes) [Answer] # Pyth, 20 bytes ``` !uuscNTc"[](){}<>"2G ``` Try it online: [Test Suite](http://pyth.herokuapp.com/?code=!uuscNTc%22[]%28%29%7B%7D%3C%3E%222G&input=%22%28[%29]%22&test_suite=1&test_suite_input=%22%28%29%22%0A%22[]%28%29%7B%7D%3C%3E%22%0A%22%28%28%28%28%29%29%29%29%22%0A%22%28%7B[%3C%3E]%7D%29%22%0A%22[%7B%28%29%3C%3E%28%29%7D[]]%22%0A%22[%28[]%7B%7D%29%3C%7B[%28%29%3C%28%29%3E]%7D%28%29%3E%7B%7D]%22%0A%22%28%22%0A%22%7D%7B%22%0A%22%28%3C%29%3E%22%0A%22%28%28%29%28%29foobar%29%22%0A%22[%28%7B%7D%3C%3E%29%3E%22%0A%22%28%28%28%28%29%29%29%22&debug=0) Repeatedly removes occurrences of `[]`, `()`, `<>` and `{}` by splitting and re-merging. Checks if the resulting string is empty or not. [Answer] # Javascript ES6, 54 bytes ``` f=_=>_.match(x=/\(\)|\[]|{}|<>/)?f(_.replace(x,'')):!_ ``` Uses a recursive replace implementation. Simple enough. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 204 bytes ``` (()){{}{({}<>)<>}<>({<(<(({})<>)>)(((((((([(())()()()]){}){}){}())(()))(((())()){}()){})){})(({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{}))<>{}<>{{}({}[({})]<>({})){(<>)(<>)}{}{}(<>)}{}>{}<>}<>)}{}((){<>[()]}) ``` [Try it online!](https://tio.run/##3U9BDsMgDPuOfegPonyk6oEdKlWbdtg1yts7G/aKAUbBdgw8PuN6b@drPO8bIKu6UB3JSO2oQECEjkziN3ZbMedBiXOZEqbJ6qIkGXDSDK7e3cUEyxWiOtmW2mY7BDXbKebwM5wCvcGQTeoqprlXrWsr0pnNP/vNNr4 "Brain-Flak – Try It Online") Not quite as short as [Nitroden's answer](https://codegolf.stackexchange.com/a/142224/76162), but uses a very different approach. This one runs through the input repeatedly, removing neighbouring matching pairs of brackets each time until there are none left. At that point if there is anything left on the stack, then the string was not fully matched. ### Explanation: ``` (()) Push 1 to simulate the check at the start of the loop { While check {} Pop check {({}<>)<>}<> Reverse input ({ Loop over input < Don't push the values of these calculations (<(({})<>)>) Create a copy of the top of the input and push to the other stack ((((( ((([(())()()()]){}){}){}()) (())) (((())()){}()){}) ){}) Push the differences in values of the end brackets (({<(({}<>{}[()]))>(){[()](<{}>)}{}<>}{})) If the copy is the same as any of these, push the difference between the other bracket twice <>{}<> Pop copy { If this character is a start bracket {}({}[({})]<>({})) Check if the next character is the end bracket {(<>)(<>)}{} If not, push a 0 to each stack as buffer {} Pop the top of the input stack, either the start bracket if they matched or the buffer 0 (<>) Push 0 to other stack to end check }{}> {} Pop the top of the other stack If the character was not an end bracket, pop the copy of check, which is 0 If it was, but didn't match the next character, pop the buffer 0 If the brackets matched, pop the end bracket and add it to the loop total <>} Repeat with the rest of the input <>) Push the loop total If any brackets were matched, the loop total is non zero }{} ((){<>[()]}) If there is anything left on the stack, push 0 to the other stack, otherwise push 1 ``` [Answer] # Regex (PCRE flavor), ~~41~~ 37 bytes ``` ^((<(?1)>|{(?1)}|\[(?1)]|\((?1)\))*)$ ``` Just a standard solution with recursive regex. *Thanks jimmy23013 for shaving off 4 bytes* [Answer] ## Brainfuck, 132 bytes ``` +>,[[<->>+>[-]<<-]<[>+>[<+<+>>>+<-]+++++[>--------<-]>[<<+>++++[>-----<-]>[<++++ +[>------<-]>-[<++++[>--------<-]>[,>]]]]<],]<<[>]>. ``` Formatted: ``` +>, [ [<-> >+>[-]<<-] < [ not matching closing bracket >+>[<+<+>> >+<-] +++++[>--------<-] > [ not open paren <<+> ++++[>-----<-]> [ not open angle bracket <+++++[>------<-]>- [ not open square bracket <++++[>--------<-]> [ not open brace ,> ] ] ] ] < ] , ] <<[>] >. ``` Expects input without a trailing newline. Prints `\x00` for false and `\x01` for true. [Try it online.](http://brainfuck.tryitonline.net/#code=Kz4sW1s8LT4-KzwtXTxbPis-PlstXTxbPCs8Kz4-Pis8LV0rKysrK1s-LS0tLS0tLS08LV0-Wzw8Kz4rKysrWz4tLS0tLTwtXT5bPCsrKysrWz4tLS0tLS08LV0-LVs8KysrK1s-LS0tLS0tLS08LV0-Wyw-XV1dXTxdLF08PFs-XT4u&input=WyhbXXt9KTx7WygpPCgpPl19KCk-e31d) Approach: Maintain a stack starting with `\x01`, and push the corresponding closing bracket whenever an opening bracket is encountered. Before checking whether the current character is an opening bracket, first check whether it's equal to the closing bracket at the top of the stack, and if so pop it. If it's neither the proper closing bracket nor an opening bracket, consume the rest of the input while moving the pointer to the right. At the end, check whether the pointer is next to the initial `\x01`. [Answer] # Perl, ~~34~~ 33 bytes Includes +2 for `-lp` Run with input on STDIN: ``` ./brackets.pl <<< "{<>()}" ``` `brackets.pl`: ``` #!/usr/bin/perl -lp s/\(\)|\[]|<>|{}//&&redo;$_=!$_ ``` Finds the first bracket pair without anything between them and removes it as long as there are any. Then checks if the final string is empty. [Answer] # Java 7, ~~156~~ 151 bytes ``` class A{public static void main(String[]a){for(int i=0;i<-1>>>1;++i,a[0]=a[0].replaceAll("<>|\\[]|\\(\\)|\\{}",""));System.out.print(a[0].isEmpty());}} ``` I'm not expecting this to win any awards but I didn't see a Java answer yet. Additionally, I like to lurk around PPCG and I would enjoy being able to vote/comment on other answers. Input is given as program parameters. This follows the same format as many other answers here in that it preforms a regex replacement in a loop. Originally I had it loop N times where N is the length of the original string but looping to `Integer.MAX_VALUE` is shorter :]. This should be ok because `Integer.MAX_VALUE` is the maximum length of a `String` in Java so there's an implicit assumption that the length of input is something that is handle-able by Java. The runtime is pretty bad (took about 20 minutes on my lappytop) on account of the loop but I didn't see any restriction on that. [Answer] # [Haskell](https://www.haskell.org/), 151 bytes ``` infix 1# '(':x#y=x#')':y '<':x#y=x#'>':y '[':x#y=x#']':y '{':x#y=x#'}':y ')':x#')':y=x#y '>':x#'>':y=x#y ']':x#']':y=x#y '}':x#'}':y=x#y ""#""=1 _#_=0 ``` [Try it online!](https://tio.run/##PcuxCsMgFIXh3acoWlDHrkEd@wTd5BIcLJXaUJIWDHKf3ZoLdTnwHfgfYXvGnFtLyz2V00UwqeRUxG6LkFpOO5Nm2JH9MJDrMJL1YWr71@3IbhjIMIxk/Jtzwbm9rd/IZjHba8hbZO0V0mLfa1o@Z@6Vh4raVK@0UdoB9qkIR9h@ "Haskell – Try It Online") [Answer] ## [Grime](https://github.com/iatorm/grime/tree/v0.1) v0.1, 34 bytes ``` M=\(M\)|\[M\]|\{M\}|\<M\>|MM|_ e`M ``` Prints `1` for a match and `0` for no match. [Try it online!](http://grime.tryitonline.net/#code=TT1cKE1cKXxcW01cXXxce01cfXxcPE1cPnxNTXxfCmVgTQ&input=WyhbXXt9KTx7WygpPCgpPl19KCk-e31d) ## Explanation Grime is my 2D pattern-matching language designed for [this challenge](https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching); it can also be used to match 1D strings. This is my first answer with it. I did modify Grime today, but only to change the character of one syntax element (``` instead of `,`), so it doesn't affect my score. ``` M= Define pattern called M that matches: \(M\)|\[M\]|\{M\}|\<M\> a smaller M inside matched brackets, |MM or two smaller Ms concatenated, |_ or the empty pattern. e`M Match the entire input against M. ``` [Answer] # Reng v.3.3, 137 bytes, noncompeting [Try it here!](https://jsfiddle.net/Conor_OBrien/avnLdwtq/) ``` aií0#zl2,q!~1ø :"]"eq!v:"}"eq!v:">"eq!v:")"eq!v)1z+#z ve¤[2-2< < < +1< >]?v$$$zÀ0#z >ðq!vlqv¤l2%[1Ø \$2+)1z+#z/ ~n1/ ``` There's a bit more golfing to be done, but at least it works. I added a command `ð` to keep track of stacks after this challenge in order for this to be remotely possible/easily. I'll explain this in a bit, but it generally keeps track of all strings iterated over and looks for repeats; if there is a repeat, then the string is irreducible. Otherwise, the string will be reduced to the empty string/stack, and will output `1`. Otherwise, no output will be produced. [Answer] ## PowerShell v2+, ~~63~~ 62 bytes ``` param($a)for(;$a-ne$b){$a=($b=$a)-replace"\[\]|\(\)|<>|{}"}!$a ``` Can't quite catch JavaScript, but is currently edging out the other non-esolangs. Similar approach as other answers: a simple loop that continues so long as we can remove one of `[]`, `()`, or `<>` (with several extraneous characters because we need to escape the regex specials). We use `$b` as a helper along the way to remember what our previous loop's `$a` was set as. An uninitialized variable is `$null`, so the first time the loop is encountered, `$a` is obviously not equal to `$null`. At the end of the loop, `$a` is either empty or not, and the Boolean-not of that string is either `True` or `False`. ### Example ``` PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({})]" True PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({])}" False ``` [Answer] # C, ~~121~~ ~~122~~ 114 bytes Shaved of 8 bytes thanks to @xsot! ``` a[99],i,k;main(c){for(;read(0,&c,!k);c%7&2?k|=a[i--]^c/9:(a[++i]=c/9))k|=!strchr("()[]{}<>",c);putchar(48+!k*!i);} ``` Uses a stack. [Answer] ### Python 2.7, 96 bytes ``` def r(s):i=max(map(s.find,['()','[]','{}','<>']));return not len(s)if i<0 else r(s[:i]+s[i+2:]) ``` [Answer] # Julia, 51 bytes ``` ~z=z==(n=replace(z,r"\(\)|\[]|{}|<>",""))?z=="":~n ``` The least insane of several options. Unsurprisingly, leveraging the power of regex is the shortest path to string matching, but this really only applies if the pattern to match is regular. Trying to do PCRE recursive patterns ends up ballooning the size of the code, either by seeing if the whole string is the match or by anchoring the ends and then creating a construct to specify the inner body for regex recursion. Neither of which are pretty or conducive to code golf. ## Explanation: ``` ~z= # Define ~z to be the following: z==( # If z is equal to n=replace(z, # z with the replacement of r"\(\)|\[]|{}|<>", # adjacent matching brackets ((),[],{}, or <>) "" # with empty strings ) # (which is assigned to n) )?z=="" # whether z is an empty string :~n # else ~ applied to the substituted string ``` The function repeatedly removes adjacent pairs of parentheses from its only argument, and returns true if it can derive an empty string this way. [Answer] # R, 298 ``` function(.){s=strsplit;u=paste0;.=s(.,"")[[1]];p=s("><)(}{][","")[[1]];.[!.%in%p]="§";for(i in 1:4*2){.[.==p[i]]=sprintf("S('%s',{",p[i]);.[.==p[i-1]]=sprintf("},'%s');",p[i])};S=function(H,B,T)if(H!=T)stop();r=try(eval(parse(,,u(.,collapse=""))),1);if(inherits(r,"try-error"))FALSE else TRUE} ``` The approach here is to convert the sequence into R code, and then try to parse and evaluate it. If that gives an error, then return `FALSE`. But there is a minor problem ... R's rules for brackets are different, so `<` and `>` are not brackets at all, and the other types have rules of their own. This is solved by a revolutionary approach -- a squeaking function, whose only function is to signal an error if its head and tail squeak in different ways. For example, `[]` is transformed into `S('[', {}, ']')`, where S is defined as ... ``` S=function(H,B,T)if(H!=T)stop() ``` Because the head squeak and tail squeak match, no error is thrown. A few other examples (the left part is a sequence of brackets and right part is its transformation into valid R code that can be evaluated): ``` [} --> S('[', {}, '}') # squeaks an error [()] --> S('[', {S('(',{},'(')}, "[") ({[]}) --> S('(',{S('{',{S('[',{},'[');},'{');},'('); ``` Some other sequences of brackets will result in parse errors: ``` [[) --> S('[',{S('[',{},'('); ``` So the remaining part just catches the errors and returns FALSE if there are any, and TRUE if there are none. The human-readble code: ``` sqk <- function(.){ s=strsplit;u=paste0 .=s(.,"")[[1]] # break the argument up into 1-character pieces p=s("><)(}{][","")[[1]] # vector of brackets .[!.%in%p]="§" # replace anything besides brackets by § (--> error) for(i in 1:4*2){ .[.==p[i]]=sprintf("S('%s',{",p[i]) # '<' --> S('<',{ ... etc .[.==p[i-1]]=sprintf("},'%s');",p[i]) # '>' --> },'<'); ... etc } S=function(H,B,T)if(H!=T)stop() # define the working horse r=try(eval(parse(,,u(.,collapse=""))),1) # evaluate the sequence if(inherits(r,"try-error"))FALSE else TRUE # any errors? } ``` Applying it on sample cases: ``` truthy<-readLines(textConnection("() [](){}<> (((()))) ({[<>]}) [{()<>()}[]] [([]{})<{[()<()>]}()>{}]")) falsy<-readLines(textConnection("( } (<2)> (()()foobar) [({}<>)> (((()))")) > sapply(truthy,sqk) () [](){}<> (((()))) TRUE TRUE TRUE ({[<>]}) [{()<>()}[]] [([]{})<{[()<()>]}()>{}] TRUE TRUE TRUE > sapply(falsy,sqk) ( } (<2)> (()()foobar) [({}<>)> (((())) FALSE FALSE FALSE FALSE FALSE FALSE ``` [Answer] # Lua (92 bytes) The older Lua answer is everything but golfing code. There's my proposal instead: ``` function x(s)m=""return s:gsub("%b<>",m):gsub("%b[]",m):gsub("%b{}",m):gsub("%b()",m)==m end ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~11~~ 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` é:råvm∟&1Γ ``` [Run and debug it](https://staxlang.xyz/#p=823a7286766d1c2631e2&i=%28%29%0A%5B%5D%28%29%7B%7D%3C%3E%0A%28%28%28%28%29%29%29%29%0A%28%7B%5B%3C%3E%5D%7D%29%0A%5B%7B%28%29%3C%3E%28%29%7D%5B%5D%5D%0A%5B%28%5B%5D%7B%7D%29%3C%7B%5B%28%29%3C%28%29%3E%5D%7D%28%29%3E%7B%7D%5D%0A%28%0A%7D%7B%0A%28%3C%29%3E%0A%28%28%29%28%29foobar%29%0A%5B%28%7B%7D%3C%3E%29%3E%0A%28%28%28%28%29%29%29&a=1&m=2) Got lucky, as stax has a literal constant in it with matched pairs of brackets. [Answer] # Curry, ~~64~~ 56 bytes *Tested to work in both [PAKCS](https://www.informatik.uni-kiel.de/%7Epakcs/) and [KiCS2](https://www-ps.informatik.uni-kiel.de/kics2/)* ``` f(x:a++y:b)|elem[x,y]["{}","<>","[]","()"]=f a*f b f""=1 ``` [Try it on Smap!](https://smap.informatik.uni-kiel.de/smap.cgi?browser/80) [Try it online!](https://tio.run/##HcixCoMwEADQ3a84jg5JtYWuIcneSfeQIdocSFUkVjCk@fZUurzhDXsI8ba697CVQuwQrq6j6PnXT342RxOtwZSxQalPjD1hHK0icFeCviJE9SizGxcQArrgp/3l788WGK/@q2AN4/KBCxAgM9akLLWVmqXMOZYf) This returns `1` if string is balanced and nothing otherwise. ## Explanation Our definition of `f` then matches the empty string as balanced for a base case: ``` f""=1 ``` Then we have the main logic: ``` f(x:a++y:b)|[x,y]=:=anyOf["{}","<>","[]","()"]=f a*f b ``` Here `*` is used like a logical and. Since the only value we can get back is `1`, this always gives back `1` when it finds results. But when it doesn't this doesn't give any result. With that this pattern matches strings with a pair of matching brackets so that they divide the input into two balanced strings. [Answer] # C, 258 bytes ``` #define E else if(a== #define D(v) {if (b[--p]!=v)z=1;} #define F b[p++]= main(a, v) char* v[]; {char b[99],p=0,z=0;for(;*v[1];v[1]++) {a=*v[1];if(a=='(')F 0;E '[')F 1;E '{')F 2;E '<')F 3;E '>')D(3)E '}')D(2)E ']')D(1)E ')')D(0)else z=1;}puts(z|p?"0":"1");} ``` ## Degolfed, macro-substituted, commented ``` int main(int a, char* v[]) { // ^ this variable is used as a general purpose int variable and not as its intended purpose (argc) char b[99], // create a 99 byte array for storing bracket types p = 0, // pointer within the array z = 0; // error flag // loop through every byte of input (argv[1]) for(;*v[1];v[1]++) { a=*v[1];// a is the current byte if(a=='(') b[p++] = 0; // record bracket type else if(a== '[') b[p++] = 1; else if(a== '{') b[p++] = 2; else if(a== '<') b[p++] = 3; else if(a== '>') { if (b[--p] != 3) z = 1; // error: bracket type mismatch } else if(a== '}') { if (b[--p] != 2) z = 1; } else if(a== ']') { if (b[--p] != 1) z = 1; }else if(a== ')') { if (b[--p] != 0)z = 1; }else z = 1; // error: invalid character } // if either z or p is not 0 print a '0', otherwise print a '1' // if p is not zero that means not all brackets were closed // if z is not zero that indicates an erro puts(z|p ? "0":"1"); } ``` ``` [Answer] # [Kotlin](https://kotlinlang.org), ~~100~~ ~~89~~ 86 bytes -11 bytes: Use `any` instead of `firstOrNull` -3 bytes: Use `chunked` instead of `split` (thanks to @leo848) ``` fun f(s:String):Boolean="()<>[]{}".chunked(2).any{it in s&&f(s.replace(it,""))}||s=="" ``` [Try it online!](https://tio.run/##bVG7bsMwDNz9FQIRBCTQeOhoyB76Cx0VDWpqt0JcybDlIWD07a4cd6jVchDA4x0fp6sPvXVLNzvxZaxDElyIFMNoXUAA@p0h7XOlkTjKJmOloBQZyko2OuYdGEk2SFFpnVVQaY4kWSUGUpKmh@PK2rXdqyJnUyX92Y6QOu/fzJjvgust9P81CYxFsdq04dYNc6jEa0jZB4l6g3uHcIbDo3gGcWrEgbuNSxHoYXOHU/Ujq16871vjalhdWO@F8vI5u2v7js9UGndjG4R1Yjoek6wc26E3lxZteEo/Q/F@n@oaYFm@AQ "Kotlin – Try It Online") [Answer] # Python 2, 80 bytes ``` def m(s,i=0):exec's=s.replace("[({<])}>"[i%4::4],"");i+=1;'*4*len(s);return"">=s ``` ]
[Question] [ ### Challenge Write the shortest [program or function](https://codegolf.meta.stackexchange.com/a/2422/46231) to calculate the [Luhn Algorithm](http://enwp.org/Luhn_algorithm) for verifying (credit card) numbers. ### Luhn algorithm explained [From RosettaCode](http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers), this algorithm for the purposes of this challenge is specified as such, with the example input of `49927398716`: ``` Reverse the digits, make an array: 6, 1, 7, 8, 9, 3, 7, 2, 9, 9, 4 Double the numbers in odd indexes: 6, 2, 7, 16, 9, 6, 7, 4, 9, 18, 4 Sum the digits in each number: 6, 2, 7, 7, 9, 6, 7, 4, 9, 9, 4 Sum all of the numbers: 6 + 2 + 7 + 7 + 9 + 6 + 7 + 4 + 9 + 9 + 4 = 70 If the sum modulo 10 is 0, then the number is valid: 70 % 10 = 0 => valid ``` ### IO Rules **Input**: A string or number (your choice), in your [language's input/output format of choice](https://codegolf.meta.stackexchange.com/q/2447) **Output**: A [truthy or falsy value](https://codegolf.meta.stackexchange.com/q/2190/46231), respectively, indicating whether or not the input is valid according to the test above. ### Notes / Tips * Try not to accidentally post your own credit card or account numbers, if you use them to test :) * If the input is invalid and impossible to process **with the specified algorithm** (i.e, too short to work with), you can do whatever you want, including blow up my computer. * **However**, the previous bullet does not mean that your language can do whatever it wants with Numbers that are too large for it to handle. If your language isn't capable of handling a test case, then consider taking a string as input. ### Examples The following examples were validated with [this Python script](http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python); if you think one is wrong or have a question, just ping @cat. ``` 49927398716 True 49927398717 False 1234567812345670 True 1234567812345678 False 79927398710 False 79927398711 False 79927398712 False 79927398713 True 79927398714 False 79927398715 False 79927398716 False 79927398717 False 79927398718 False 79927398719 False 374652346956782346957823694857692364857368475368 True 374652346956782346957823694857692364857387456834 False 8 False ** 0 True ** ``` \*\* according to the Python implementation, but you may do anything because these are too short to be eligible by a strict adherence to the specification. --- If any of the above invalidates existing answers (though I believe that should not be possible), then those answers are stil valid. However, **new** answers, in order to be valid, should follow the specification above. ### Leaderboard ``` var QUESTION_ID=22,OVERRIDE_USER=73772;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Golfscript - 24 chars ``` -1%{2+0!:0)*109%+}*10%8= ``` Explanation: 1. `-1%` reverses the string 2. `{` begins a block (which we use as a loop). Each character in the strings is pushed as it's ascii value. 1. `2+` adds 2. (the ascii value of a digit is 48+n, so we have 50+n now and the last digit is n) 2. `0!:0` inverts the value of 0 and stores it (everything is a variable), so we have 1 on the first iteration, 0 on the second, etc. 3. `)*` adds one to this value and multiplies it, so we multiply by 2, then 1, then 2, etc. 4. `109%` is remainder modulo 109. This affects only values 5-9 which have been doubled and reduces them to the correct value. 5. `+` adds this value to the running sum 3. `}*` ends the block and does a 'fold' operation. First, the first character is pushed (since we have reversed, this is the check digit). Then, alternate pushing and executing the block. Thus, we are using the first character's ascii value as the starting value for the running sum. 4. `10%` takes the remainder modulo 10. 5. `8=` will return 1 if the value is 8. We use this because we did not normalize the first pushed character (the check digit). One might think that we could use `8-` instead of `2+` to save a character by changing `109%` to `89%`, except then we would need to add a space so the `-` is subtraction (instead of `-0`). [Answer] ## GolfScript, 44 chars ``` -1%{16%}%2/1,\+{(\.{0=2*.9>9*-+}{;}if+}*10%! ``` --- **Selected commentary** Interestingly, the first two items below demonstrate three completely different uses of the `%` operator: array selection, map, and mod. Most GolfScript operators are "context-sensitive", giving them hugely divergent behaviours depending on what types the arguments are. 1. `-1%` reverses the string. This is important as the digit pairs are counted from the right. 2. `{16%}%` converts all the ASCII digits into numbers, by modding them with 16. 3. `2/` splits the array into groups of 2. 4. `1,` is a cheap way to do `[0]`. 5. `\+` effectively prepends the 0 to the digits array. It does this by swapping then concatenating. The 0 is prepended in preparation for the fold that comes in next. Rather than taking an explicit initial value, GolfScript's fold uses the first item in the array as the initial value. Now, let's look at the actual fold function. This function takes two arguments: the folded value, and the current item on the array (which in this case will be an array of 2 or (uncommonly) 1, because of the `2/` earlier). Let's assume the arguments are `1 [2 3]`. 1. `(\.` splits out the leftmost array element, moves the remaining array to the front, then copies it. Stack now looks like: `1 2 [3] [3]`. 2. The `if` checks if the array is empty (which is the case for the last group when dealing with an odd-sized account number). If so, then no special processing happens (just pop off the empty array). 3. For an even group: 1. `0=` grabs the first (only, in this case) element of the array. `1 2 3` 2. `2*` doubles the number. `1 2 6` 3. `.9>9*-` subtracts 9 from the number if it's greater than 9. Implemented as: copy the number, compare with 9, multiply the result (which is either 0 or 1) with 9, then subtract. `1 2 6` 4. `+` finally adds that to the first number. `1 8` 4. `+` (after the `if`) adds the result of the `if` to the original value, resulting in the new folded value. After the folding completes, we simply mod with 10 (`10%`), and negate the result (`!`), so that we return 1 iff the sum is a multiple of 10. [Answer] ## Python, 73 69 characters ``` def P(x):D=map(int,x);return sum(D+[d-d/5*9for d in D[-2::-2]])%10==0 ``` [Answer] # Python 3, 77 bytes ``` c=lambda a:sum(sum(divmod(int(a[-e-1])<<e%2,10))for e in range(len(a)))%10==0 ``` [Answer] **C# 119 characters:** ``` bool l(string n){return(String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2<1?1:2)+"").ToArray()).Sum(x=>x-48))%10<1;} ``` Not *too* bad for a code golf n00b in a statically typed language, I hope. This can be reduced to **100**: ``` bool l(string n){return String.Join("",n.Reverse().Select((x,i)=>(x-48)*(i%2+1))).Sum(x=>x+2)%10<1;} ``` [Answer] ## Golfscript - 34 chars ``` {15&}%.-2%\);-2%{.+(9%)}%+{+}*10%! ``` Example number from wikipedia page 4992739871 ``` {15&}% does a bitwise and of each ascii digit with 00001111 now I have a list of digits [4 9 9 2 7 3 9 8 7 1 6] . makes a copy of the list, now I have two identical lists [4 9 9 2 7 3 9 8 7 1 6] [4 9 9 2 7 3 9 8 7 1 6] -2% like [::-2] in python takes every second element in reverse [4 9 9 2 7 3 9 8 7 1 6] [6 7 9 7 9 4] \ swap the two lists around [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1 6] ); drop the last digit off the list [6 7 9 7 9 4] [4 9 9 2 7 3 9 8 7 1] -2% same as before [6 7 9 7 9 4] [1 8 3 2 9] { for each item in the list ... .+ ... double it ... ( ... subtract 1 ... 9% ... mod 9 ... )}% ... add 1 ... [6 7 9 7 9 4] [2 7 6 4 9] + join the two lists [6 7 9 7 9 4 2 7 6 4 9] {+}* add the elements up 70 10% mod 10 0 ! invert the result 1 ``` [Answer] # PHP, 108 bytes ``` <?function v($s,$t=0){for($i=strlen($s);$i>=0;$i--,$c=$s[$i])$t+=$c+$i%2*(($c>4)*-4+$c%5);return!($t % 10);} ``` [Answer] ## Ruby - 85 characters ``` def f s l=s.size s.chars.map{|k|(i=k.to_i*((l-=1)%2+1))%10+i/10}.inject(:+)%10==0 end ``` [Answer] # Haskell, 96 bytes There must be a better/shorter way, but here's my **Haskell** solution in **96 characters**: ``` l=(==0).(`mod`10).sum.zipWith($)(cycle[id,\x->x`mod`5*2+x`div`5]).reverse.map((+(-48)).fromEnum) ``` Sadly the `digitToInt` function can only be used if you `import Data.Char` first. Otherwise I could get down to 88 characters by replacing `((+(-48)).fromEnum)` with `digitToInt`. [Answer] ## Windows PowerShell, 82 ``` filter f{!((''+($_[($_.length)..0]|%{+"$_"*($i++%2+1)})-replace'.','+$&'|iex)%10)} ``` History: * 2011-02-13 03:08 (84) First attempt. * 2011-02-13 12:13 (82) I don't need to join, as spaces do not hurt. `+1 + +3` can still be evaluated. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~11~~ 9 bytes ``` ṚḤÐeDFS⁵ḍ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlkPdyw5PCHVxS34UePWhzt6/x9uf7i7@1HDnJCi0lQg5ZaYUwyk5x7a@qhpTeT//9EmlpZG5saWFuaGZjoKCI65joKhkbGJqZm5BZQ2wBCx0FEwh2swQOYYInOMkDnGyBwTZI4pMscMmWOOzEGx1FJHwdjcxMwU6B4zS5CLIAwQbWZpYmFqbmYJZIEYxmYWJuamQJJ4HRbmQE9aGAMdCdRkEAsA "Jelly – Try It Online") ## How it works ``` ṚḤÐeDFS⁵ḍ - Main link. Takes an integer n on the left Ṛ - Cast n to digits and reverse Ðe - To values at even indices: Ḥ - Unhalve; Double D - Cast to digits F - Flatten S - Sum ḍ - Divisible by: ⁵ - 10? ``` [Answer] # Q, 63 ``` {0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]} ``` usage ``` q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398711" 0b q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398712" 0b q){0=mod[(+/)"I"$(,/)($)($)@["I"$'x;1+2*'(!)(_)((#)x)%2;*;2];10]}"79927398713" 1b ``` [Answer] # D, 144 bytes ``` bool f(S)(S s){int t(C)(C c){return to!int(c)-'0';}int n,v;foreach(i,c;array(retro(s))){v=i&1?t(c)*2:t(c);n+=v>=10?v%10+v/10:v;}return n%10==0;} ``` More legibly: ``` bool f(S)(S s) { int t(C)(C c) { return to!int(c) - '0'; } int n, v; foreach(i, c; array(retro(s))) { v = i & 1 ? t(c) * 2 : t(c); n += v >= 10 ? v % 10 + v / 10 : v; } return n % 10 == 0; } ``` [Answer] # APL, 28 [bytes](https://en.wikipedia.org/wiki/APL_(codepage)) ``` {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} ``` **Exploded view** ``` { v←⍎¨⍵} ⍝ turn the string into a numeric vector of its digits, v 2-2|⍳⍴v ⍝ make a vector of the same length, with 2 in every 2nd place v×⌽ ⍝ multiply it with v, starting from the right ∊⍕¨ ⍝ turn each component into a string and collect all the digits +/⍎¨ ⍝ turn each digit again into a number and sum them 0=10| ⍝ check whether the sum is a multiple of 10 ``` **Examples** ``` {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '79927398713' 1 {0=10|+/⍎¨∊⍕¨v×⌽2-2|⍳⍴v←⍎¨⍵} '123456789' 0 ``` [Answer] # [x86-16 machine code](https://software.intel.com/sites/default/files/managed/39/c5/325462-sdm-vol-1-2abcd-3abcd.pdf), 27 bytes Binary: ``` 00000000: bb00 0103 f1fd ac2c 30f6 df78 06d0 e0d4 .......,0..x.... 00000010: 0a02 dc02 d8e2 ef93 d40a c3 ........... ``` Listing: ``` BB 0100 MOV BX, 100H ; running sum (BL) to 0, BH to a positive value 03 F1 ADD SI, CX ; start at end of input string FD STD ; set LODSB direction to decrement DIGIT_LOOP: AC LODSB ; load next digit into AL, decrement SI 2C 30 SUB AL, '0' ; convert ASCII char to binary value F6 DF NEG BH ; flip sign of BH to alternate odd/even index 78 06 JS IS_EVEN ; if not odd index, do not double D0 E0 SHL AL, 1 ; double the value D4 0A AAM ; split digits (ex: 18 --> AH = 1, AL = 8) 02 DC ADD BL, AH ; add tens digit to running sum IS_EVEN: 02 D8 ADD BL, AL ; add ones digit to running sum E2 EF LOOP DIGIT_LOOP 93 XCHG AX, BX ; sum is in BL, move to AL for mod 10 check D4 0A AAM ; ZF = ( AL % 10 == 0 ) C3 RET ; return to caller ``` Uses (abuses) x86's BCD-to-binary instruction `AAM` to handle the individual digit splitting and `modulo 10` check. Callable function, input card num string pointer in `SI`, length in `CX`. Output: `ZF` if valid. **Example test program output:** [![enter image description here](https://i.stack.imgur.com/vOgkr.png)](https://i.stack.imgur.com/vOgkr.png) ## Alternate version, 29 bytes ``` 33 DB XOR BX, BX ; running sum (BL) to 0 03 F1 ADD SI, CX ; start at end of string 4E DEC SI ; align for WORD FD STD ; set LODSB direction to decrement DIGIT_LOOP: AD LODSW ; load next two digits into AH:AL, dec SI by 2 25 0F0F AND AX, 0F0FH ; convert ASCII chars to binary value 02 DC ADD BL, AH ; add ones digit of even index to sum 49 DEC CX ; decrement counter for WORD 74 0A JZ DONE ; if input is odd length, will be 0 at the end D0 E0 SHL AL, 1 ; double the value D4 0A AAM ; split digits (ex: 18 --> AH = 1, AL = 8) 02 DC ADD BL, AH ; add tens digit to sum 02 D8 ADD BL, AL ; add ones digit to sum E2 ED LOOP DIGIT_LOOP DONE: 93 XCHG AX, BX ; move sum to AL for mod 10 check D4 0A AAM ; ZF = ( AL % 10 == 0 ) C3 RET ; return to caller ``` This version loads two digits at the same time, eliminating the flip/flop branch. The issue here is having to check for an odd number of digits on the input and discard the value in memory right before the beginning of the string once it reaches the last word. Obviously not shorter, but perhaps someone clever can golf it more! [Answer] ## PowerShell 123 ``` filter L($x){$l=$x.Length-1;$l..0|%{$d=$x[$_]-48;if($_%2-eq$l%2){$s+=$d}elseif($d-le4){$s+=$d*2}else{$s+=$d*2-9}};!($s%10)} ``` [Answer] # Perl, ~~46~~ ~~42~~ 41 bytes Includes +1 for `-p` Give input on STDIN: ``` luhn.pl <<< 79927398713 ``` `luhn.pl`: ``` #!/usr/bin/perl -p s%.%$=-=-$&-$&*1.2*/\G(..)+$/%eg;$_=/0$/ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes ``` RSāÈ>*SOTÖ ``` [Try it online!](https://tio.run/##yy9OTMpM/f8/KPhI4@EOO61g/5DD0/7/N7G0NDI3trQwNzQDAA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##jc87CgJBDADQPqdYthSF@WTyaXaPILheQMHCykIQFmy28wReaL3XOIOiwcomeYSEJKfzbn885Otl7Ntm1TVtP@bN8JjmW7cY1tv5npcZVQNHFfYEXzP4EDERyzu734IAf7qdsTcOxtEYjZMxGbOx3aUQGSmVI0jrGS/UTIqSmLSoIpIgpxL/HhAuj0lEEHBP) **Explanation** ``` R # reverse input S # split to list of digits ā # push range[1 ... len(input)] È # map isEven on each > # increment * # multiply doubling every other item SO # sum digits TÖ # mod 10 == 0 ``` [Answer] # Powershell, 74 bytes ``` param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)} !($r%10) ``` ## Explanation 1. for each char of an argument string, in reverse order 2. get a digit of double value of a digit 3. a double value of a digit can not be greater then 18. Therefore, we accumulate a value minus 9 if value > 9 4. return true if the remainder of the division by 10 is 0 ## Test script ``` $f = { param($s)$s[$s.Length..0]|%{(1+$i++%2)*"$_"}|%{$r+=$_-9*($_-gt9)} !($r%10) } @( ,("49927398716" , $True) ,("49927398717" , $False) ,("1234567812345670" , $True) ,("1234567812345678" , $False) ,("79927398710" , $False) ,("79927398711" , $False) ,("79927398712" , $False) ,("79927398713" , $True) ,("79927398714" , $False) ,("79927398715" , $False) ,("79927398716" , $False) ,("79927398717" , $False) ,("79927398718" , $False) ,("79927398719" , $False) ,("374652346956782346957823694857692364857368475368" , $True) ,("374652346956782346957823694857692364857387456834" , $False) ,("8" , $False) ,("0" , $True) ) | % { $s, $expected = $_ $result = &$f $s "$($result-eq$expected): $result : $s" } ``` ## Output ``` True: True : 49927398716 True: False : 49927398717 True: True : 1234567812345670 True: False : 1234567812345678 True: False : 79927398710 True: False : 79927398711 True: False : 79927398712 True: True : 79927398713 True: False : 79927398714 True: False : 79927398715 True: False : 79927398716 True: False : 79927398717 True: False : 79927398718 True: False : 79927398719 True: True : 374652346956782346957823694857692364857368475368 True: False : 374652346956782346957823694857692364857387456834 True: False : 8 True: True : 0 ``` [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 31 bytes ``` .,2%0\@{48-..4>+@!:a*++a}/;10%! ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0/HSNUgxqHaxEJXT8/ETttB0SpRS1s7sVbf2tBAVfH/f0MjYxNTM3MLKG0AAA "GolfScript – Try It Online") Golfscript pushes the input as a list of characters to the stack at the start of the program. ``` . Duplicate the top of the stack (input) ,2% Compute the modulo 2 of the length of the input, pushed 1/0 on the stack if the number if odd/even 0 Push an accumulater var on the stack, set to 0 \ Flip the even/odd and accumulator order on the stack @ Bring the 3rd entry forward, input to the top { } Code block... / Apply the block of code to the elements of the list at the top of the stack. Each time through the loop, the next element from the list if pushed to the top of the stack 48- Subtract "0" from the top of stack (which is a codepoint for the current digit/character) .. Duplicate the top of stack (the current digit) twice 4>+ If the current digit is >4 add one to the digit @ Pull the 3rd entry, the even/odd indicator, to the top !:a Flip the value and save in variable "a" * Multiple the top two stack entries, will be "0" or the value of current digit, with or without "1" more for the "+10" rule ++ Add the current digit, to the possible "double" and "even/odd" bump a Push the flipped even/odd indicated to the top ; Drop the stop of stack, the even/odd indicator 10% Find the modulo 10 of the accumulated digits ! Invert the result ``` The only thing on the stack is the answer, which is printed by default [Answer] # [C (clang)](http://clang.llvm.org/), ~~264~~ ~~212~~ ~~196~~ ~~175~~ 172 bytes ``` l,x;main(i){char*s;gets(s);int n[i=l=strlen(s)];for(;i--;)n[i]=s[i]-48;for(;(i+=2)<l;n[i]>9?n[i]=n[i]/10+n[i]%10:0)n[i]*=2;for(;l--;)x+=n[l];printf(x%10<1?"True":"False");} ``` [Try it online!](https://tio.run/##XY7BCoJAEIbvPUUYwa5mqUlp49atJ@gWHjZdbWBawzUQome3tU51mYHv//5hCr8gqethhrqgR6mmmelKbJbX/eQHEV7@WYu6tmygRQ83iZohfxZX2boGatUZZjig7qb6jIKE1Ulpy3KompYB@j5wG@XC2OHHyRcz9ETEM4Ix2qeHjzGOVRh4456HwS74FF0RfTs0nuo9q1EOd/tVV7Heell4cE7tQzk75yjJKIfDaxjiNI226zTZhps3 "C (clang) – Try It Online") Simply the basic way of programming the algorithm, but all whitespace is removed. All I could say is that there are a bunch of for-loops in this one. Thanks to ceilingcat for golfing 52 bytes, another 16 bytes, and another 21 bytes, and another 3 bytes. [Answer] # JavaScript (ES6), 61 bytes Sum of digits of `2*n` is `2*n` if `n in 0..4`, `2*n-9` if `n in 5..9`. That said, all the sum can be computed in one step. ``` s=>!([...s].reduceRight((t,d)=>t-d-i++%2*(d>4?d-9:d),i=0)%10) ``` [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 26 bytes ``` {~10!+//10\(1+2!!#x)*.'|x} ``` [Try it online!](https://tio.run/##lY@7DsIwDEV3voKaoS0VNE8/4FeYy4DUuVKBXw8JIMDqxBLf48TXN5fdeB5TGg7z3Zqq63trTo3tXFVtpna7r6/TLQ11A0HEkRcmi3D8IcpknQ8Rid/VLFsM7aq40GeuPPqSVeQUeUVh4RTVPSoiRaxIitMaPAWMOSVKyfkSpaIEjoSSVREeOVDMJ/wzxJR/zz7AM3PZb6BNDw "K (ngn/k) – Try It Online") Another k variant, with a major debt to [@streetster's answer](https://codegolf.stackexchange.com/a/154051/98547). [Answer] # [Factor](https://factorcode.org/) + `validators`, 5 bytes ``` luhn? ``` [Try it online!](https://tio.run/##jc/NCsIwDADge58iTyDb2iatHjyKFy/iSTyUOXEw5346h4jPXjsUCZ68JB8hIcnJ5f7ahd12vVnNoekK7@9NV9Ye2hH6oh2KOi96uLmqPLrY2cNCtONDKGszktZQiswk0kwqjWQ@OfktGEHf7oQ5Zc6YJbNi1szITMx8lxWSFOp4BNrpjDemjFYZTWijJkg0inSMfw8Yio8ZqYQRiXjCPlTDuV6GA1xcA7PwAg "Factor – Try It Online") [Answer] ### Scala: 132 ``` def q(x:Int)=x%10+x/10 def c(i:String)={val s=i.reverse (s(0)-48)==10-(s.tail.sliding(2,2).map(n=>(q((n(0)-48)*2)+n(1)-48)).sum%10)} ``` invocation: ``` c("79927398713") ``` * reverse ("79927398713") = 31789372997 * s(0), s.tail: (3)(1789372997) * sliding (2,2) = (17 89 37 29 97) * map (q((n(0)-48\*2 + n(1)-48)) => q(('1'-'0')\*2)+ '7'-'0')=1\*2+7 [Answer] ## JavaScript 1.8: 106 characters This is an original solution I came up with before I found this post: ``` function(n){return!(n.split('').reverse().reduce(function(p,c,i){return(+c&&((c*(1+i%2)%9)||9))+p},0)%10)} ``` Readable form: ``` function luhnCheck(ccNum) { return !( // True if the result is zero. ccNum.split(''). reverse(). // Iterate over the string from rtl. reduce(function(prev, cur, idx) { return prev + // Sum the results of each character. (+cur && // If the current digit is 0, move on. ((cur * (1 + idx % 2) // Double cur at even indices. % 9) || 9)); // Sum the digits of the result. }, 0) % 10); // Is the sum evenly divisible by 10? } ``` [Answer] # K4, 35 bytes ``` {~.*|$+/.:',/$x*1+1{y;~x}\|x:|.:'x} ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~43~~ 42 bytes Retina is (much) newer than this challenge. ``` ; r`(.);. $1$& \d $* 1+ $.& . $* $ $._ 0$ ``` The leading empty line is significant. Prints `0` for falsy and `1` for truthy results. [Try it online!](http://retina.tryitonline.net/#code=JShHYAoKOwpyYCguKTsuCiQxJCYKXGQKJCoKMSsKJC4mCi4KJCoKJAokLl8KTWAwJAopR2A&input=NDk5MjczOTg3MTYKMTIzNDU2NzgxMjM0NTY3MAo3OTkyNzM5ODcxMwozNzQ2NTIzNDY5NTY3ODIzNDY5NTc4MjM2OTQ4NTc2OTIzNjQ4NTczNjg0NzUzNjgKMAoKNDk5MjczOTg3MTcKMTIzNDU2NzgxMjM0NTY3OAo3OTkyNzM5ODcxMAo3OTkyNzM5ODcxMQo3OTkyNzM5ODcxMgo3OTkyNzM5ODcxNAo3OTkyNzM5ODcxNQo3OTkyNzM5ODcxNgo3OTkyNzM5ODcxNwo3OTkyNzM5ODcxOAo3OTkyNzM5ODcxOQozNzQ2NTIzNDY5NTY3ODIzNDY5NTc4MjM2OTQ4NTc2OTIzNjQ4NTczODc0NTY4MzQKOA) (Slightly modified to run all test cases at once.) ### Explanation ``` ; ``` Insert `;` in every position to separate digits. ``` r`(.);. $1$& ``` From the `r`ight, we repeatedly match two digits and double the left one. This way we avoid an expensive reversing of the list. ``` \d $* ``` We match each digit and convert it to that many `1`s (that is, we convert each digit to unary). ``` 1+ $.& ``` This matches each unary number and converts it back to decimal by replacing it with its length. Together with the previous stage, this adds the doubled digits. ``` . $* ``` Again, we match every character and turn it into that many `1`s. That is we convert each digit individually back to unary. This also matches the `;` separators, which are treated as zeros in the conversion, which means they're simply removed. Since all the unary numbers are now squashed together we've automatically added the unary representations of the all digits together. ``` $ $._ ``` At the end, we insert the length of the entire string, i.e. the decimal representation of the unary checksum. ``` 0$ ``` Finally we count the number of matches of this regex, i.e. we check whether the decimal representation ends in `0`, printing `0` or `1` accordingly. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~14~~ 13 bytes Takes input as an array of digits. ``` ÔxÈ*ÒYu)ìxÃvA ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1HjIKtJZdSnseMN2QQ==&input=WzQsOSw5LDIsNywzLDksOCw3LDEsNl0KLaE=) ``` ÔxÈ*ÒYu)ìxÃvA :Implicit input of array Ô :Reverse x :Reduce by addition È :After passing each element at 0-based index Y through the following function * : Multiply by Ò : Bitwise increment Yu : Y modulo 2 ) : End multiplication ì : Convert to digit array x : Reduce by addition à :End function v :Test for divisibility by A : 10 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), ~~12~~ 11 bytes *-1 byte thanks to @lyxal reminding me about multibyte lambdas.* ``` ṘÞTf‡d∑ẇ∑₀Ḋ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E1%B9%98%C3%9ETf%E2%80%A1d%E2%88%91%E1%BA%87%E2%88%91%E2%82%80%E1%B8%8A&inputs=1234567812345678&header=&footer=) Explanation: ``` # Implicit input Ṙ # Reverse ÞT # Transpose f # Flatten list ‡ ẇ # For every second element: d # Double ∑ # Sum digits ∑ # Sum all elements ₀Ḋ # x % 10 == 0? # Implicit output ``` ]
[Question] [ So I think we've all probably seen [this xkcd comic](http://xkcd.com/688/): ![http://imgs.xkcd.com/comics/self_description.png](https://i.stack.imgur.com/R0wuP.png "The contents of any one panel are dependent on the contents of every panel including itself. The graph of panel dependencies is complete and bidirectional, and each node has a loop. The mouseover text has two hundred and forty-two characters."): This might either be too general or too difficult, I'm not sure. But the challenge is to create a program in any language that creates a window that has at least 2 colors and displays in English words what percentage of the screen is each color. ex. The simplest solution would be a white background with black letters that read "Percentage of this image that is black: [x]%. Percentage of this image that is white: [y]%" You can go as crazy or as simple as you want; plain text is a valid solution but if you make interesting images like in the xkcd comic that's even better! The winner will be the most fun and creative solution that gets the most votes. So go forth and make something fun and worthy of xkcd! :) So, what do you think? Sound like a fun challenge? :) **Please include a screenshot of your program running in your answer :)** [Answer] # JavaScript with HTML I tried to reproduce the original comic more precisely. A screenshot is taken using the html2canvas library. The numbers are calculated repeatedly, so you can resize the window or even add something to page in real time. Try it online: <http://copy.sh/xkcd-688.html> Here's a screenshot: ![enter image description here](https://i.stack.imgur.com/JYYPb.png) ``` <html contenteditable> <script src=http://html2canvas.hertzen.com/build/html2canvas.js></script> <script> onload = function() { setInterval(k, 750); k(); } function k() { html2canvas(document.body, { onrendered: t }); } function t(c) { z.getContext("2d").drawImage(c, 0, 0, 300, 150); c = c.getContext("2d").getImageData(0, 0, c.width, c.height).data; for(i = y = 0; i < c.length;) y += c[i++]; y /= c.length * 255; x.textContent = (y * 100).toFixed(6) + "% of this website is white"; q = g.getContext("2d"); q.fillStyle = "#eee"; q.beginPath(); q.moveTo(75, 75); q.arc(75,75,75,0,7,false); q.lineTo(75,75); q.fill(); q.fillStyle = "#000"; q.beginPath(); q.moveTo(75, 75); q.arc(75,75,75,0,6.28319*(1-y),false); q.lineTo(75,75); q.fill(); } </script> <center> <h2 id=x></h2> <hr> <table><tr> <td>Fraction of<br>this website<br>which is white _/ <td><canvas width=150 id=g></canvas> <td>&nbsp; Fraction of<br>- this website<br>&nbsp; which is black </table> <hr> 0 <canvas style="border-width: 0 0 1px 1px; border-style: solid" id=z></canvas> <h4>Location of coloured pixels in this website</h4> ``` [Answer] ## [Elm](http://elm-lang.org) Haven't seen anyone use this loophole yet: [demo](http://share-elm.com/sprout/5568959be4b06aacf0e89ff8) ``` import Color exposing (hsl) import Graphics.Element exposing (..) import Mouse import Text import Window msg a = centered <| Text.color a (Text.fromString "half the screen is this color") type Pos = Upper | Lower screen (w,h) (x,y) = let (dx,dy) = (toFloat x - toFloat w / 2, toFloat h / 2 - toFloat y) ang = hsl (atan2 dy dx) 0.7 0.5 ang' = hsl (atan2 dx dy) 0.7 0.5 box c = case c of Upper -> container w (h // 2) middle (msg ang) |> color ang' Lower -> container w (h // 2) middle (msg ang') |> color ang in flow down [box Upper, box Lower] main = Signal.map2 screen Window.dimensions Mouse.position ``` ![enter image description here](https://i.stack.imgur.com/5uLYU.png) [Answer] # Processing, 222 characters ![https://i.stack.imgur.com/tcj1E.png](https://i.stack.imgur.com/tcj1E.png) I've always wanted to make my own version of that comic strip! The simplest (only?) way I could think of doing this was trial and error - draw something, count, draw again... This program settles for an accurate percentage after a few seconds. It's not very pretty, but **it's interactive**; you can resize the window and it will start to recalculate. Added some newlines for readability: ``` float s,S,n; int i; void draw(){ frame.setResizable(true); background(255); fill(s=i=0); text(String.format("%.2f%% of this is white",S/++n*100),10,10); loadPixels(); while(i<width*height)if(pixels[i++]==-1)s++; S+=s/height/width; } ``` It only shows percentage of white pixels; Because of antialiasing of the text, non-white pixels are not necessarily black. The longer it is running the more time it will need to update itself on a resize. #### Edit: So, it's a code-challenge; I sort of golfed it anyways. Maybe I could add some sort of graphs later, but the general principle would remain the same. The interactiveness is the neat part I think. [Answer] Great challenge. Here's my solution. I tried to get as close as possible to the original comic, I even used the [xkcd font](http://forums.xkcd.com/viewtopic.php?f=2&t=22741&p=1678696#p1678696). ![](https://i.stack.imgur.com/6AKne.png) It's a WPF application, but I used `System.Drawing` to do the drawing parts because I'm lazy. Basic concept: In WPF, windows are `Visuals`, which means they can be rendered. I render the entire Window instance onto a bitmap, count up the black and total black or white (ignoring the grays in the font smoothing and stuff) and also count these up for each 3rd of the image (for each panel). Then I do it again on a timer. It reaches equilibrium within a second or two. Download: [MEGA](https://mega.co.nz/#!x0lFFSAZ!3Uv1b8oszofFbkyKhyTzZzRnfWg47GaO6pQVA2in3Rc) Always check files you download for viruses, etc, etc. You'll need to install the font above to your system if you want to see it, otherwise it's the WPF default one. XAML: ``` <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="xkcd: 688" Height="300" Width="1000" WindowStyle="ToolWindow"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="0.3*"/> <ColumnDefinition Width="0.3*"/> <ColumnDefinition Width="0.3*"/> </Grid.ColumnDefinitions> <Border BorderBrush="Black" x:Name="bFirstPanel" BorderThickness="3" Padding="10px" Margin="0 0 10px 0"> <Grid> <Label FontSize="18" FontFamily="xkcd" VerticalAlignment="Top">Fraction of this window that is white</Label> <Label FontSize="18" FontFamily="xkcd" VerticalAlignment="Bottom">Fraction of this window that is black</Label> <Image x:Name="imgFirstPanel"></Image> </Grid> </Border> <Border Grid.Column="1" x:Name="bSecondPanel" BorderBrush="Black" BorderThickness="3" Padding="10px" Margin="10px 0"> <Grid> <TextBlock FontSize="18" FontFamily="xkcd" VerticalAlignment="Top" HorizontalAlignment="Left">Amount of <LineBreak></LineBreak>black ink <LineBreak></LineBreak>by panel:</TextBlock> <Image x:Name="imgSecondPanel"></Image> </Grid> </Border> <Border Grid.Column="2" x:Name="bThirdPanel" BorderBrush="Black" BorderThickness="3" Padding="10px" Margin="10px 0 0 0"> <Grid> <TextBlock FontSize="18" FontFamily="xkcd" VerticalAlignment="Top" HorizontalAlignment="Left">Location of <LineBreak></LineBreak>black ink <LineBreak></LineBreak>in this window:</TextBlock> <Image x:Name="imgThirdPanel"></Image> </Grid> </Border> </Grid> </Window> ``` Code: ``` using System; using System.Drawing; using System.Timers; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using Brushes = System.Drawing.Brushes; namespace WpfApplication1 { public partial class MainWindow : Window { private Timer mainTimer = new Timer(); public MainWindow() { InitializeComponent(); Loaded += (o1,e1) => { mainTimer = new Timer(1000/10); mainTimer.Elapsed += (o, e) => { try { Dispatcher.Invoke(Refresh); } catch(Exception ex) { // Nope } }; mainTimer.Start(); }; } private void Refresh() { var actualh = this.RenderSize.Height; var actualw = this.RenderSize.Width; var renderTarget = new RenderTargetBitmap((int) actualw, (int) actualh, 96, 96, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(this); var visual = new DrawingVisual(); var context = visual.RenderOpen(); // Render the window onto the target bitmap using (context) { context.DrawRectangle(sourceBrush, null, new Rect(0,0, actualw, actualh)); } renderTarget.Render(visual); // Create an array with all of the pixel data var stride = (int) actualw*4; var data = new byte[stride * (int)actualh]; renderTarget.CopyPixels(data, stride, 0); var blackness = 0f; var total = 0f; var blacknessFirstPanel = 0f; var blacknessSecondPanel = 0f; var blacknessThirdPanel = 0f; var totalFirstPanel = 0f; var totalSecondPanel = 0f; var totalThirdPanel = 0f; // Count all of the things for (var i = 0; i < data.Length; i += 4) { var b = data[i]; var g = data[i + 1]; var r = data[i + 2]; if (r == 0 && r == g && g == b) { blackness += 1; total += 1; var x = i%(actualw*4) / 4; if(x < actualw / 3f) { blacknessFirstPanel += 1; totalFirstPanel += 1; } else if (x < actualw * (2f / 3f)) { blacknessSecondPanel += 1; totalSecondPanel += 1; } else if (x < actualw) { blacknessThirdPanel += 1; totalThirdPanel += 1; } } else if (r == 255 && r == g && g == b) { total += 1; var x = i % (actualw * 4) / 4; if (x < actualw / 3f) { totalFirstPanel += 1; } else if (x < actualw * (2f / 3f)) { totalSecondPanel += 1; } else if (x < actualw) { totalThirdPanel += 1; } } } var black = blackness/total; Redraw(black, blacknessFirstPanel, blacknessSecondPanel, blacknessThirdPanel, blackness, renderTarget); } private void Redraw(double black, double firstpanel, double secondpanel, double thirdpanel, double totalpanels, ImageSource window) { DrawPieChart(black); DrawBarChart(firstpanel, secondpanel, thirdpanel, totalpanels); DrawImage(window); } void DrawPieChart(double black) { var w = (float)bFirstPanel.ActualWidth; var h = (float)bFirstPanel.ActualHeight; var padding = 0.1f; var b = new Bitmap((int)w, (int)h); var g = Graphics.FromImage(b); var px = padding*w; var py = padding*h; var pw = w - (2*px); var ph = h - (2*py); g.DrawEllipse(Pens.Black, px,py,pw,ph); g.FillPie(Brushes.Black, px, py, pw, ph, 120, (float)black * 360); g.DrawLine(Pens.Black, 30f, h * 0.1f, w / 2 + w * 0.1f, h / 2 - h * 0.1f); g.DrawLine(Pens.Black, 30f, h - h * 0.1f, w / 2 - w * 0.2f, h / 2 + h * 0.2f); imgFirstPanel.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(b.Width, b.Height)); } void DrawBarChart(double b1, double b2, double b3, double btotal) { var w = (float)bFirstPanel.ActualWidth; var h = (float)bFirstPanel.ActualHeight; var padding = 0.1f; var b = new Bitmap((int)w, (int)h); var g = Graphics.FromImage(b); var px = padding * w; var py = padding * h; var pw = w - (2 * px); var ph = h - (2 * py); g.DrawLine(Pens.Black, px, py, px, ph+py); g.DrawLine(Pens.Black, px, py + ph, px+pw, py+ph); var fdrawbar = new Action<int, double>((number, value) => { var height = ph*(float) value/(float) btotal; var width = pw/3f - 4f; var x = px + (pw/3f)*(number-1); var y = py + (ph - height); g.FillRectangle(Brushes.Black, x, y, width, height); }); fdrawbar(1, b1); fdrawbar(2, b2); fdrawbar(3, b3); imgSecondPanel.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(b.Width, b.Height)); } void DrawImage(ImageSource window) { imgThirdPanel.Source = window; } } } ``` The code isn't cleaned up, but it should be somewhat readable, sorry. [Answer] ## C (with SDL and SDL\_ttf): Grayscale solution Here's a solution that takes advantage of the pie chart form to capture the complete spectrum of grayscale pixel colors, clocking in at just under 100 lines. ``` #include <stdio.h> #include <string.h> #include <math.h> #include "SDL.h" #include "SDL_ttf.h" int main(void) { SDL_Surface *screen, *buffer, *caption; SDL_Color pal[256]; SDL_Rect rect; SDL_Event event; TTF_Font *font; int levels[256], plev[256]; Uint8 *p; float g; int cr, redraw, hoffset, h, n, v, w, x, y; SDL_Init(SDL_INIT_VIDEO); TTF_Init(); screen = SDL_SetVideoMode(640, 480, 0, SDL_ANYFORMAT | SDL_RESIZABLE); font = TTF_OpenFont(FONTPATH, 24); buffer = 0; for (;;) { if (!buffer) { buffer = SDL_CreateRGBSurface(SDL_SWSURFACE, screen->w, screen->h, 8, 0, 0, 0, 0); for (n = 0 ; n < 256 ; ++n) pal[n].r = pal[n].g = pal[n].b = n; SDL_SetColors(buffer, pal, 0, 256); } memcpy(plev, levels, sizeof levels); memset(levels, 0, sizeof levels); SDL_LockSurface(buffer); p = buffer->pixels; for (h = 0 ; h < buffer->h ; ++h) { for (w = 0 ; w < buffer->w ; ++w) ++levels[p[w]]; p += buffer->pitch; } for (n = 1 ; n < 256 ; ++n) levels[n] += levels[n - 1]; redraw = memcmp(levels, plev, sizeof levels); if (redraw) { SDL_UnlockSurface(buffer); SDL_FillRect(buffer, NULL, 255); caption = TTF_RenderText_Shaded(font, "Distribution of pixel color in this image", pal[0], pal[255]); rect.x = (buffer->w - caption->w) / 2; rect.y = 4; hoffset = caption->h + 4; SDL_BlitSurface(caption, NULL, buffer, &rect); SDL_FreeSurface(caption); SDL_LockSurface(buffer); cr = buffer->h - hoffset; cr = (cr < buffer->w ? cr : buffer->w) / 2 - 4; p = buffer->pixels; for (h = 0 ; h < buffer->h ; ++h) { y = h - (screen->h + hoffset) / 2; for (w = 0 ; w < buffer->w ; ++w) { x = w - buffer->w / 2; g = sqrtf(x * x + y * y); if (g < cr - 1) { g = atanf((float)y / (x + g)); v = levels[255] * (g / M_PI + 0.5); for (n = 0 ; n < 255 && levels[n] < v ; ++n) ; p[w] = n; } else if (g < cr + 1) { p[w] = (int)(128.0 * fabs(g - cr)); } } p += buffer->pitch; } } SDL_UnlockSurface(buffer); SDL_BlitSurface(buffer, NULL, screen, NULL); SDL_UpdateRect(screen, 0, 0, 0, 0); if (redraw ? SDL_PollEvent(&event) : SDL_WaitEvent(&event)) { if (event.type == SDL_QUIT) break; if (event.type == SDL_VIDEORESIZE) { SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_ANYFORMAT | SDL_RESIZABLE); SDL_FreeSurface(buffer); buffer = 0; } } } SDL_Quit(); TTF_Quit(); return 0; } ``` As with my previous solution, the path to the font file needs to be either hardcoded in the source or added to the build command, e.g.: ``` gcc -Wall -o xkcdgolf `sdl-config --cflags` -DFONTPATH=`fc-match --format='"%{file}"' :bold` xkcdgolf.c -lSDL_ttf `sdl-config --libs` -lm ``` The output of the program looks like this: ![Pie chart showing full grayscale pixel color distribution](https://i.stack.imgur.com/36cFB.png) This one is fun to watch, because all the math slows down the redraws to where you can see the program zero in on the stable solution. The first estimate is wildly off (since the surface starts out all-black), and then shrinks down to the final size after about a dozen or so iterations. The code works by taking a population count of each pixel color in the current image. If this population count doesn't match the last one, then it redraws the image. The code iterates over every pixel, but it transforms the x,y coordinates into polar coordinates, computing first the radius (using the center of the image as the origin). If the radius is within the pie chart area, it then computes the theta. The theta is easily scaled to the population counts, which determines the pixel color. On the other hand, if the radius is right on the border of the pie chart, then an anti-aliased value is computed to draw the circle around the outside of the chart. Polar coordinates make everything easy! [Answer] ## C (with SDL and SDL\_ttf) Here's a very simple implementation, in about 60 lines of C code: ``` #include <stdio.h> #include "SDL.h" #include "SDL_ttf.h" int main(void) { char buf[64]; SDL_Surface *screen, *text; SDL_Rect rect; SDL_Color black; SDL_Event event; TTF_Font *font; Uint32 blackval, *p; int size, b, prevb, h, i; SDL_Init(SDL_INIT_VIDEO); TTF_Init(); screen = SDL_SetVideoMode(640, 480, 32, SDL_ANYFORMAT | SDL_RESIZABLE); font = TTF_OpenFont(FONTPATH, 32); black.r = black.g = black.b = 0; blackval = SDL_MapRGB(screen->format, 0, 0, 0); b = -1; for (;;) { prevb = b; b = 0; SDL_LockSurface(screen); p = screen->pixels; for (h = screen->h ; h ; --h) { for (i = 0 ; i < screen->w ; ++i) b += p[i] == blackval; p = (Uint32*)((Uint8*)p + screen->pitch); } SDL_UnlockSurface(screen); size = screen->w * screen->h; SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 255, 255, 255)); sprintf(buf, "This image is %.2f%% black pixels", (100.0 * b) / size); text = TTF_RenderText_Solid(font, buf, black); rect.x = (screen->w - text->w) / 2; rect.y = screen->h / 2 - text->h; SDL_BlitSurface(text, NULL, screen, &rect); SDL_FreeSurface(text); sprintf(buf, "and %.2f%% white pixels.", (100.0 * (size - b)) / size); text = TTF_RenderText_Solid(font, buf, black); rect.x = (screen->w - text->w) / 2; rect.y = screen->h / 2; SDL_BlitSurface(text, NULL, screen, &rect); SDL_FreeSurface(text); SDL_UpdateRect(screen, 0, 0, 0, 0); if (b == prevb ? SDL_WaitEvent(&event) : SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) break; if (event.type == SDL_VIDEORESIZE) SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_ANYFORMAT | SDL_RESIZABLE); } } TTF_Quit(); SDL_Quit(); return 0; } ``` To compile this, you need to define `FONTPATH` to point to a .ttf file of the font to use: ``` gcc -Wall -o xkcdgolf `sdl-config --cflags` -DFONTPATH='"/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"' xkcdgolf.c -lSDL_ttf `sdl-config --libs` ``` On most modern Linux machines you can use the `fc-match` utility to look up font locations, so the compile command becomes: ``` gcc -Wall -o xkcdgolf `sdl-config --cflags` -DFONTPATH=`fc-match --format='"%{file}"' :bold` xkcdgolf.c -lSDL_ttf `sdl-config --libs` ``` (Of course you can replace the requested font with your personal favorite.) The code specifically requests no anti-aliasing, so that the window contains only black and white pixels. Finally, I was inspired by @daniero's elegant solution to permit window resizing. You'll see that sometimes the program oscillates between counts, stuck in an orbit around an attractor it can never reach. When that happens, just resize the window a bit until it stops. And, per request, here's what it looks like when I run it on my system: ![This image is 3.36% black pixels and 96.64% white pixels.](https://i.stack.imgur.com/0c2OX.png) Finally, I feel that I should point out, in case anyone here hasn't already seen it, that the MAA published [an interview with Randall Munroe](http://www.maa.org/mathhorizons/MH-Sep2012_XKCD.html) in which he discusses the making of cartoon #688 in some detail. [Answer] ![enter image description here](https://i.stack.imgur.com/Tp0Fe.png) The image is 100x100 and the numbers are exact, and I do mean exact - I chose a 10000 pixel image so that the percentages could be expressed with two decimal places. The method was a bit of math, a bit of guessing, and some number crunching in Python. Seeing as I knew in advance that the percentages could be expressed in 4 digits, I counted how many black pixels were in each of the digits 0 through 9, in 8 pixel high Arial, which is what the text is written in. I wrote a quick function `weight` which tells you how many pixels are needed to write a given number, left padded with zeros to have 4 digits: ``` def weight(x): total = 4 * px[0] while x > 0: total = total - px[0] + px[x % 10] x = x / 10 return total ``` `px` is an array mapping digits to number of required pixels. If B is the number of black pixels, and W is the number of white pixels, we have `B + W = 10000`, and we need: ``` B = 423 + weight(B) + weight(W) W = 9577 - weight(B) - weight(W) ``` Where did the constants come from? 423 is the "initial" number of black pixels, the number of black pixels in the text without the numbers. 9577 is the number of initial white pixels. I had to adjust the amount of initial black pixels several times before I managed to get constants such that the above system even has a solution. This was done by guessing and crossing my fingers. The above system is horribly non-linear, so obviously you can forget about solving it symbolically, but what you can do is just loop through every value of B, set W = 10000 - B, and check the equations explicitly. ``` >>> for b in range(10000 + 1): ... if b == weight(b) + weight(10000 - b)+423: print b; ... 562 564 ``` [Answer] # QBasic Because nostalgia. And because I don't really know any image libraries in modern languages. ``` SCREEN 9 CONST screenWidth = 640 CONST screenHeight = 350 CONST totalPixels# = screenWidth * screenHeight accuracy = 6 newWhite# = 0 newGreen# = 0 newBlack# = totalPixels# DO CLS white# = newWhite# green# = newGreen# black# = newBlack# ' Change the precision of the percentages every once in a while ' This helps in finding values that converge IF RND < .1 THEN accuracy = INT(RND * 4) + 2 format$ = "###." + LEFT$("######", accuracy) + "%" ' Display text LOCATE 1 PRINT "Percentage of the screen which is white:"; PRINT USING format$; pct(white#) LOCATE 4 PRINT white#; "/"; totalPixels#; "pixels" LOCATE 7 PRINT "Percentage of the screen which is black:"; PRINT USING format$; pct(black#) LOCATE 10 PRINT black#; "/"; totalPixels#; "pixels" LOCATE 13 PRINT "Percentage of the screen which is green:"; PRINT USING format$; pct(green#) LOCATE 16 PRINT green#; "/"; totalPixels#; "pixels" ' Display bar graphs LINE (0, 16)-(pct(white#) / 100 * screenWidth, 36), 2, BF LINE (0, 100)-(pct(black#) / 100 * screenWidth, 120), 2, BF LINE (0, 184)-(pct(green#) / 100 * screenWidth, 204), 2, BF newBlack# = pixels#(0) newGreen# = pixels#(2) newWhite# = pixels#(15) LOOP UNTIL black# = newBlack# AND white# = newWhite# AND green# = newGreen# ' Wait for user keypress before ending program: otherwise the "Press any ' key to continue" message would instantly make the results incorrect! x$ = INPUT$(1) FUNCTION pixels# (colr) ' Counts how many pixels of the given color are on the screen pixels# = 0 FOR i = 0 TO screenWidth - 1 FOR j = 0 TO screenHeight - 1 IF POINT(i, j) = colr THEN pixels# = pixels# + 1 NEXT j NEXT i END FUNCTION FUNCTION pct (numPixels#) ' Returns percentage, given a number of pixels pct = numPixels# / totalPixels# * 100 END FUNCTION ``` Pretty straightforward output-count-repeat method. The main "interesting" thing is that the program randomly tries different precisions for the percentages--I found that it didn't always converge otherwise. And the output (tested on [QB64](http://qb64.net)): ![QBasic metagraph](https://i.stack.imgur.com/w3Vdq.png) [Answer] # AWK ## ... with netpbm and other helpers The 'x' file: ``` BEGIN { FS="" n++ while(n!=m) { c="printf '%s\n' '"m"% black pixels'" c=c" '"100-m"% white pixels'" c=c" | pbmtext -space 1 -lspace 1 | pnmtoplainpnm | tee x.pbm" n=m delete P nr=0 while(c|getline==1) if(++nr>2) for(i=1;i<=NF;i++) P[$i]++ close(c) m=100*P[1]/(P[0]+P[1]) print m"%" } } ``` The run: ``` $ awk -f x 4.44242% 5.2424% 5.04953% 5.42649% 5.27746% 5.1635% 5.15473% 5.20733% 5.20733% ``` The picture is written as 'x.pbm', I converted it to png for uploading: ![x.png](https://i.stack.imgur.com/HsiAT.png) ]
[Question] [ Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N. ### Specifically: If N is `0`, no copies of N are used, so there should be no output (or only a single trailing newline). If N is `1`, the output is: ``` 1 ``` If N is `2`: ``` 22 22 ``` If N is `3`: ``` 333 3 3 333 ``` If N is `4`: ``` 4444 4 4 4 4 4444 ``` If N is `5`: ``` 55555 5 5 5 5 5 5 55555 ``` The pattern continues for `6` through `9`. If N is `10`, the output is: ``` 10101010101010101010 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10101010101010101010 ``` **Notice that this is not actually square.** It is 10 rows tall but 20 columns wide because `10` is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. **So all inputs beyond `9` will technically be ASCII rectangles.** For example, if N is `23`, the output is: ``` 2323232323232323232323232323232323232323232323 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 2323232323232323232323232323232323232323232323 ``` Here are Pastebins of the required outputs for [`99`](http://pastebin.com/raw/Qcas2Qmu), [`100`](http://pastebin.com/raw/1wc2FNmL), [`111`](http://pastebin.com/raw/DGZcHSiS), and [`123`](http://pastebin.com/raw/ajYdGhmw) (they may look wrong in a browser but in a text editor they'll look correct). The output for `1000` is to large for Pastebin but it would have 1000 rows and 4000 columns. **Numbers with 4 or more digits must work just like smaller numbers.** ### Details: * N must be written in the usual decimal number representation, with no `+` sign or other non-digits. * The hollow area must only be filled with spaces. * No lines should have leading or trailing spaces. * A single newline after the squares' last line is optionally allowed. * Languages written after this challenge was made are welcome, they just [aren't eligible to win](http://meta.codegolf.stackexchange.com/a/4870/26997). * **The shortest code in bytes wins!** [Answer] # [Shtriped](http://github.com/HelkaHomba/shtriped), 317 bytes While I'm making the question, I may as show off my new "purist" language. ``` @ f x d x f @ f x + x y + i x @ + y h x } x y e 1 i 1 d y d 1 d x } x y e 0 e 2 i 2 i 2 e 6 + 2 2 6 + 2 6 6 e T + 2 2 T + 6 T T e N t N e P + T 0 P e L i L * e x * + P x x @ * T h x ~ } N P 0 d 0 i L * P ~ ~ # p N - s 6 _ @ - L $ # @ _ n # s 2 @ # N e n + N 0 n d n d n s 2 @ $ n @ # N ``` (definitely works in [v1.0.0](https://github.com/HelkaHomba/shtriped/releases/tag/v1.0.0)) There are no math operations built into Shtriped except increment and decrement. There's also no looping or conditionals, so all of these thing need to be built up from scratch in every program. That's what my program does, e.g. `@` is essentially a for loop, `+` is an addition function, `}` is `>=`. The actual output is only produced in the last 8 lines of the program. There are no strings either in Shtriped. You can take in and print out strings, but they are all represented internally as arbitrary precision integers that can only be incremented and decremented. So there's no easy way get the length of the string `10` for filling in the the square center with the right amount of spaces. I had to cobble together the function `~` that effectively computes `floor(log10(N)) + 1` to find the length of N in decimal. This could probably be golfed a bit more by rearranging where and how which variables are used, but not *that* much more. There's no getting around Shtriped's inherent limitations. (It was never meant to be a golfing language anyway.) **Commented code (a backslash is a comment):** ``` @ f x \ function that calls f() x times, returns 0 d x f @ f x + x y \ returns x + y + i x @ + y h x } x y \ returns 1 if x >= y, else 0 e 1 i 1 d y d 1 d x } x y \ declare and set up variables for the numbers 0, 2, 6, 10 e 0 \ 0 is used to help copy values via + e 2 \ 2 is used for printing newlines i 2 i 2 e 6 \ 6 is used for printing spaces + 2 2 6 + 2 6 6 e T \ 10 is used for finding the string length of N + 2 2 T + 6 T T e N \ declare N t N \ and set it to what the user inputs \ all the code from here to the last ~ is for finding the length of N as a string e P \ P is the current power of 10 (10, 100, 1000...), starting with 10 + T 0 P e L \ L will be the length of N in decimal digits i L * \ function that returns P times 10 by adding P to itself 10 times e x * + P x x @ * T h x ~ \ function that increments L and multiplies P by 10 until N < P, at which point L will be the string length of N } N P 0 \ the 0 variable can be used as a dummy now since we don't need it anymore d 0 i L * P \ multiply P by 10 to ~ ~ \ helper functions for displaying the output # \ simply prints N as a decimal integer p N - \ prints a single space s 6 _ \ prints L spaces (L = digit length of N) @ - L $ \ prints one of the central N-2 lines of the square # @ _ n # s 2 \ finally, call these functions to display the output @ # N \ print N copies of N (top line of square) e n \ declare n and set it to N - 2 + N 0 n d n d n \ if N was 0 or 1 the program will end here, having printed nothing if 0 or just the top line if 1 s 2 \ print a newline @ $ n \ print the central line of the square N-2 times @ # N \ print N copies of N (bottom line of square) \ the output always prints without a trailing newline ``` [Answer] ## Seriously, ~~32~~ ~~31~~ ~~30~~ 29 bytes ``` ╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n( ``` [Try it online!](http://seriously.tryitonline.net/#code=4pWp4pWcw7Mk4pWd4pWcRGJ14pWc4pWbKm7ilZzCrDvilZtsKicgKuKVmyvilZtAK24o&input=MTA) Explanation: ``` ╩╜ó$╝╜Dbu╜╛*n╜¬;╛l*' *╛+╛@+n( ╩ push each input to its own register (we'll call register 0 "n") ╜ push n to the stack ó terminate if 0 $╝ push str(n) to register 1 (we'll call register 1 "s") ╜Dbu╜╛*n make min(2,n) copies of s*n (the top and bottom) (this avoids an extra copy if n is 1) ╜¬; push n-2 twice ╛l*' * push (n-2)*len(s) spaces ╛+╛@+ put s on the front and end of the string (a middle piece) n push (n-2) total copies of the middle piece ( bring the top piece to the top ``` [Answer] # C++14, 156 chars I thought it was a pretty cool solution though obviously can not beat most other entries here. ``` #define f for(i=0;i++<n;c<<t); [](string t){auto&c=cout;int n=stoi(t),i;f c<<'\n';for(i=0;++i<n-1;c<<t,c.width(~-n*size(t)+1),c.fill(0),c<<t+'\n');if(n-1)f} ``` Ungolfed: ``` #define f for ( i = 0; i++ < n; c << t ); // print top/bot row [](string t) { auto& c = cout; int n = stoi(t), i; f // print first row c << '\n'; // kind of annoying but no way to get rid of (yes I tried // c << '\n'+t instead of c << t+'\n') for ( i = 0; ++i < n - 1; ) { c << t; // output the number // then we we get the width of necessary spaces c.width(~-n*size(t)+1); // Equivalent to (n-1)*size(t) + 1, but we save // two bytes since ~- takes precedence over // multiplication c.fill(0); // fill with spaces, ' ' == 0 c << t+'\n'; } if ( n-1 ) f // This if statement is dissapointing } ``` And like always, to call the function use `[](string t) { ... }("10");` [Answer] # Jolf, ~~31~~ ~~27~~ ~~25~~ 23 bytes ``` ?=1i1ρρ,aii+*3έέi*li ``` This is encoded in the ISO-8859-7 encoding and contains unprintables, so here's a hexdump: ``` 0000000: 3f3d 3169 31f1 f12c 6169 692b 2a33 dd05 ?=1i1..,aii+*3.. 0000010: dd69 052a 056c 69 .i.*.li ``` [Try this fiddle online](http://conorobrien-foxx.github.io/Jolf/#code=Pz0xaTHPgc-BLGFpaSsqM86tBc6taQUqBWxp&input=Mw) or [verify all test cases at once (use the full run button)](http://conorobrien-foxx.github.io/Jolf/#code=Pz0xaTHPgc-BLGFpaSsqM86tBc6taQUqBWxp&input=MQoKMgoKMwoKNAoKNQoKMTAKCjIz). This exits with an error for n = 0, which is [allowed by default.](http://meta.codegolf.stackexchange.com/a/4781/45151) Massive thanks to Conor for golfing off ~~4~~ 6! bytes. inb4 crossed out four still looks like a four comment ## Explanation ``` ?=1i1ρρ,aii+*3έ\x05έi\x05*\x05li ?=1i1 if input is 1 return 1, otherwise... ,aii+*3έ\x05 draw an input x input hollow box of tabs ρ έi replace all tabs with input ρ \x05*\x05li replace all spaces with spaces * length of input ``` [Answer] # JavaScript (ES6), ~~73 82~~ 78 bytes *Saved a4 bytes thanks to @user81655* ``` n=>(a=n[r='repeat'](n),n<2?a:a+` ${n+' '[r](n.length*(n-2))+n}`[r](n-2)+` `+a) ``` Takes a string, not a number for input. [Try it online](http://vihan.org/p/esfiddle/?code=f%3Dn%3D%3E(a%3Dn%5Br%3D'repeat'%5D(n)%2Cn%3C2%3Fa%3Aa%2B%60%0A%24%7Bn%2B'%20'%5Br%5D(n.length*(n-2))%2Bn%7D%60%5Br%5D(n-2)%2B%60%0A%60%2Ba)%0A%0Aalert(%20f(%20'0'%20)%20)%0Aalert(%20f(%20'1'%20)%20)%0Aalert(%20f(%20'2'%20)%20)%0Aalert(%20f(%20'3'%20)%20)%0Aalert(%20f(%20'10'%20)%20)) (all browsers work) [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~34~~ ~~29~~ 26 bytes ``` :G\2<t!+gQ"@!2GVYX1GVnZ"YX ``` This works with [current release (13.0.0)](https://github.com/lmendo/MATL/releases/tag/13.0.0) of the language/compiler [**Try it online!**](http://matl.tryitonline.net/#code=OkdcMjx0IStnUSJAITJHVllYMUdWbloiWVg&input=MTA) ``` : % array [1,2,...,N], where N is input, taken implicitly G\ % modulo N. Gives [1,2,...,N-1,0] 2< % smaller than 2? Gives [1,0,...,0,1] t! % duplicate, transpose + % addition with broadcast. Gives 2D array with nonzeros in the border % and zeros in the interior gQ % convert to logical, add 1: twos in the border, ones in the interior " % for each column of that array (note the array is a symmetric matrix, % so columns and rows are the same) @! % push column. Transpose into a row 2GVYX % replace twos by the string representation of N, via regexp 1GVnZ"YX % replace ones by as many spaces as length of that string, via regexp % end for each, implicitly % display stack contents, implicitly ``` [Answer] # T-SQL/SQL Server 2012+, 167 161 bytes ``` DECLARE @ INT = 6; SELECT IIF(u IN(1,s),REPLICATE(s,s),CONCAT(s,REPLICATE(' ',s-2*LEN(s)),s)) FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v ``` Output: ``` 666666 6 6 6 6 6 6 6 6 666666 ``` `**[`LiveDemo`](https://data.stackexchange.com/stackoverflow/query/483695?Size=7&opt.textResults=true)**` Enter desired size and click `Run query` to get text representation. Please note that this demo does not display **fixed-width font**. So `7` is thicker than `1`. --- **EDIT:** If we treat input as string: ``` DECLARE @ VARCHAR(10) = '7'; SELECT IIF(u IN(1,s),REPLICATE(s,s),s+REPLICATE(' ',s-2*LEN(s))+s) FROM(SELECT @ s)z CROSS APPLY(SELECT TOP(s+0)ROW_NUMBER()OVER(ORDER BY 1/0)u FROM sys.messages)v ``` `**[`LiveDemo2`](https://data.stackexchange.com/stackoverflow/query/483693?opt.textResults=true)**` [Answer] # Julia, 78 bytes ``` n->(s="$n";(p=println)(s^n);[p(s*" "^(n-2)endof(s)*s)for i=2:n-1];n>1&&p(s^n)) ``` This is an anonymous function that accepts an integer and prints the ASCII rectangle to STDOUT. To call it, assign it to a variable. Ungolfed: ``` function f(n) # Save a string version of n s = "$n" # Print the top line println(s^n) # Print each middle line [println(s * " "^(n-2)endof(s) * s) for i = 2:n-1] # Print the last line if there is one n > 1 && println(s^n) end ``` [Try it online](http://goo.gl/9YDL5L) [Answer] # Ruby, 100 bytes ``` ->n{s="";n.times{|i|s+=(i<1||i>n-2?"#{n}"*n :"#{n}#{' '*[(n-2)*n.to_s.size,0].max}#{n}")+$/};puts s} ``` Too bad I couldn't even manage to beat JS. Any further help golfing it down would be appreciated. Here's a more or less ungolfed version: ``` def f(n) n.times{|num| if num == 0 || num == n-1 s += "#{n}" * n else s += "#{n}"+" "*[(n-2)*n.to_s.length,0].max+"#{n}" end s += "\n" } puts s end ``` [Answer] # Retina, 76 bytes ``` .+ $0$*n$0 n(?=n*(\d+))|. $1_ \d+_ $_¶ T`d` `(?<=¶.*_.*).(?=.*_\d.*¶\d) \`_ [empty line] ``` Explanation maybe comes tomorrow. [Try it online here.](http://retina.tryitonline.net/#code=LisKJDAkKm4kMApuKD89biooXGQrKSl8LgokMV8KXGQrXwokX8K2ClRgZGAgYCg_PD3Cti4qXy4qKS4oPz0uKl9cZC4qwrZcZCkKXGBfCg&input=MTI) [Answer] ## TSQL, ~~112~~ 104 bytes ``` DECLARE @ varchar(10)='12' PRINT REPLICATE(@,@)+ISNULL(' '+REPLICATE(@+ISNULL(SPACE((@-2)*len(@))+@,'')+' ',@-2)+REPLICATE(@,@),'') ``` > > > ``` > 1. generating first line > 2. adding hollow lines + line breaks > 3. adding last line(when needed) > > ``` > > [Answer] ## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), 57 bytes ``` nd?.d1-2&N.$z01FlOz2-[lz6Z" "I2-z2-*Dz6Z$O]01F. z[z6Z]$Of ``` [Try it here!](http://play.starmaninnovations.com/minkolang/?code=nd%3F%2Ed1-2%26N%2E%24z01FlOz2-%5Blz6Z%22%20%22I2-z2-*Dz6Z%24O%5D01F%2E%0Az%5Bz6Z%5D%24Of&input=100) ### Explanation ``` n Read number from input d?. Stop if n=0, continue otherwise d1-2&N. Print 1 and stop if n=1, continue otherwise $z Store top of stack in register (z, which is n) 01F Gosub to second line lO Print newline z2- Push value from register and subtract 2 [ Pop k and run body of for loop k times (Does not run if k <= 0) l Push a newline z6Z Push z and convert to string " " Push a space I2- Push length of stack minus 2 z2- Push z minus 2 * Pop b,a and push a,b D Pop k and duplicate top of stack k times z6Z Push z and convert to string $O Output whole stack as characters ] Close for loop 01F. Gosub to second line and stop after returning. z[ ] For loop that runs z times z6Z Push z and convert to string $O Output whole stack as characters f Return to position called from ``` [Answer] # Perl, ~~79~~ ~~76~~ 74 bytes ``` $_=$.=pop;s/./ /g;print$.x$.,$/,($.,$_ x($.-2),$.,$/)x($.-2),$.>1?$.x$.:'' ``` Pretty straightforward. The first commandline argument is taken as the number. Place the script in a file and run with `perl file.pl 1`. [Answer] ## Perl, ~~62~~ ~~60~~ 58 + 2 = 60 bytes ``` for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_} ``` Requires `-nlE` flags: ``` $ perl -nlE'for$.(1..$_){say$.>1&$.<$_?$_.$"x(y...c*($_-2)).$_:$_ x$_}' <<< 5 55555 5 5 5 5 5 5 55555 ``` With spaces added: ``` for$.(1..$_) { say( $. > 1 & $. < $_ ? $_ . $"x(length$_*($_-2)) . $_ : $_ x $_ ) } ``` [Answer] # R, 90 bytes ``` x=scan();m=matrix(x,x,x);k=2:(x-1)*(x>2);m[k,k]=format("",w=nchar(x));write(m,"",n=x,s="") ``` --- This creates a matrix of `x*x` size and then fills with spaces of size `nchar(x)` . If `x` smaller than 2, then nothing is being filled. [Answer] # Pyth - 26 bytes ``` K*`QQjbm++Q**l`Q;ttQQttQK ``` [Try it online here](http://pyth.herokuapp.com/?code=%0A%0AK%2a%60QQjbm%2B%2BQ%2a%2al%60Q%3BttQQttQK&input=15&debug=0). [Answer] # [Pip](http://github.com/dloscutoff/pip) `-l`, 21 bytes *Uses language features newer than the question, which is allowed per current policy; if the wording of the question is interpreted to override said policy, see 25-byte answer below.* ``` Yq{MN++g%y>1?sMyy}MCy ``` [Try it online!](https://tio.run/##K8gs@P8/srDa109bO1210s7Qvti3srLW17ny/39Dg/@6OQA) Thanks to Luis Mendo's [MATL answer](https://codegolf.stackexchange.com/a/73649/16766) for the `(a+1)%n<2` trick. ### Explanation `Yq` reads a line from stdin and yanks it into `y`. Then: ``` { }MCy Map this function to each coordinate pair in a y-by-y grid (Inside the function, the list of both coords is g) ++g Increment both coordinates %y Take them mod y MN >1? Test whether the min of the resulting list is 2 or greater sMy If so, it's in the center; use len(y) spaces y If not, it's an edge; use the number y Print result with newlines between rows (implicit, -l flag) ``` --- Original 2016 answer, **25 bytes** (plus `-l` flag): ``` Yq{MN++*a%y<2?ysX#y}MMCGy ``` Changelog: * `MC` was added more recently; at the time, I used `MMCG` (map-map + coordinate-grid). * There was a bug in the current interpreter that prevented using `++` on lists, so I had to do `++*` (apply `++` to each element) instead. * `M`ap has been extended: now `<string1> M <string2>` returns a list of `len(<string2>)` copies of `<string1>`; at the time, I used `sX#y`, string-repeating space by `len(y)`. [Answer] ## Pyth, ~~37~~ 30 bytes ``` J*K`QQI>Q1JV-Q2++Q*d-lJ*2lKQ;J ``` [Try it here.](https://pyth.herokuapp.com/?code=J%2aK%60QQI%3EQ1JV-Q2%2B%2BQ%2ad-lJ%2a2lKQ%3BJ&input=5&debug=0) ``` J*K`QQ set K to repr(input); that is, stringified set J to K repeated (input) times I>Q1 ; if input is greater than 1... J output J (stringified input times input) V-Q2 do this (input - 2) times... ++ output the following on one line: Q the input number *d-lJ*2lK n spaces, where n = len(J) - 2*len(K) Q the input number again ; break out of everything J output J (str(input)*input) one last time, regardless of whether input > 1 ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 90 Again, I'm pretty sure this will be greatly golfable by the experts: ``` .+ $&$&$*:$&$*; +`(\d+:): $1$1 +`([\d+:]+;); $1$1 T`d` `(?<=;\d+:)[^;]+(?=:\d+:;\d) : ; ¶ ``` [Try it online.](http://retina.tryitonline.net/#code=LisKJCYkJiQqOiQmJCo7CitgKFxkKzopOgokMSQxCitgKFtcZCs6XSs7KTsKJDEkMQpUYGRgIGAoPzw9O1xkKzopW147XSsoPz06XGQrOjtcZCkKOgoKOwrCtg&input=MjM) [Answer] # Jelly, 28 bytes Grr, can’t tell if Jelly is bad at strings, or if I’m bad at Jelly. ``` ŒṘ©L⁶xWẋWẋ$®W¤1¦€U'Z$$4¡j⁷ȯ⁷ ``` [Try it online.](http://jelly.tryitonline.net/#code=xZLhuZjCqUzigbZ4V-G6i1fhuoskwq5XwqQxwqbigqxVJ1okJDTCoWrigbfIr-KBtw&input=&args=MTI) [Answer] ## [Pyke](https://github.com/muddyfish/PYKE/tree/12c0a12837b2ff44733cf0d401da725572dd31d9), 33 bytes (noncompetitive) ``` QD`i*Djli2*lR-k*iRi]3J"bR+2Q-*jR+ ``` Explanation: ``` - autoassign Q = eval_or_not(input()) QD`i* - Get the input multiplied by itself Q - [Q] D - [Q, Q] ` - [repr(Q), Q] i - i = stack[0] * - [stack[0]*stack[1]] Djli2*lR- - Get number of spaces D - [^,^] j - j = stack[0] l - len(stack[0]) i2* - i*2 l - len(stack[0]) R - rotate_2() - - stack[0]-stack[1] k*iRi - Get middle line k* - " "*^ iRi - [i,^,i] ]3J"bR+ - Join middle line together ]3 - list(stack[:3]) J" - "".join(stack[0]) bR+ - ^+"\n" 2Q- - Get middle lines 2Q-* - Q-2 jR+ - Add end line jR+ - ^+j ``` [Answer] ## CJam, 27 bytes ``` ri:X,_ff{a+[0X(]&XXs,S*?}N* ``` Thanks to @MartinBüttner for suggesting `ff`. The `a+[0X(]&` is pretty fishy, but oh well. [Try it online!](http://cjam.aditsu.net/#code=ri%3AX%2C_ff%7Ba%2B%5B0X%28%5D%26XXs%2CS*%3F%7DN*&input=10) ``` ri:X Read input integer and save as variable X ,_ Range, i.e. [0 1 ... X-1] and make a copy ff{...} Map with extra parameter, twice. This is like doing a Cartesian product between two 1D arrays, but we get a nice X by X array at the end For each coordinate pair, a+ Put the two coordinates into an array [0X(]& Set intersection with the array [0 X-1] X Push X Xs,S* Push a number of spaces equal to the length of X ? Ternary: choose one of the previous two depending on the set intersection N* Join X by X array with newlines ``` [Answer] ## Haskell, 78 bytes ``` i x=unlines$take x$1#s:3#[s++(3#s>>" ")++s]++[1#s]where s=show x;z#s=[z..x]>>s ``` Usage example: ``` *Main> putStr $ i 4 4444 4 4 4 4 4444 ``` The function `>>` comes in handy: `<list> >> <string>` makes `length <list>` copies of `<string>`, e.g. top and bottom lines for `x=10` are `[1..10] >> "10"` -> `"10101010101010101010"`. [Answer] ## Perl, 72 bytes ``` $_=($.=pop)-2;say for($.x$.,($..($.x$_)=~s/./ /rg.$.)x$_,$.x$.)[0..$.-1] ``` Relies on modern Perl features : > > **say** 'something' > > > is automatically available since Perl 5.10 (simply use v5.10 or later). > > str\_expr =~ s/.../.../**r** > > > happily accepts to work on a rvalue (an str\_expr not necessarily reduced to a scalar variable) to yield a **r**esult (the '**r**' option at the end of the regex) without altering the initial str\_expr. [Answer] # PHP, 151 bytes ``` function s($n){for($r=0;$r<$n;$r++){for($c=0;$c<$n;$c++){if($r*$c&&$r!=$n-1&&$c!=$n-1){for($d=0;$d<=log10($n);$d++){echo' ';}}else{echo$n;}}echo"\n";}} ``` Absolute mess, need more time to optimize. `s(Number)` gives you the output. [Answer] ## Java 8, 280 bytes ``` interface A{static<T>void p(T o){System.out.print(o);}static void main(String[]a){long n=new Long(a[0]),l=a[0].length();for(long i=0;i<n;i++,p(a[0]));p("\n"+(n>1?a[0]:""));for(long j=2;j<n;j++,p(a[0])){for(long i=l*2;i<n*l;i++,p(' '));p(a[0]+"\n");}for(long i=1;i<n;i++)p(a[0]);}} ``` It's only about 10 times as long as the shortest answers, which is really good for Java! Example run: ``` $ java A 10 10101010101010101010 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10101010101010101010 ``` [Answer] ## Python 3, ~~108~~ ~~96~~ 148 bytes ``` a=input() b=c=int(a)-2 if a!="1" else 0 print(a*int(a)) while b:print(a+" "*int(len(a))*c+a);b-=1 if a!="1":print(a*int(a)) ``` Ungolfed/explained: ``` number = input() # Gets a number as input iterator = var = int(number) - 2 if number != "1" else 0 # Assigns two variables, one of them an iterator, to the number minus 2 (the amount of middle rows in the square) if the number isn't 1. If it is, it sets the vars to 0 so the while doesn't trigger. print(number * int(number)) # Prints the top row of the square. while iterator != 0: # Loops for the middle rows print(number + " " * int(len(number)) * var + number) # Prints the number, then as many spaces as needed, and the number. iterator -= 1 # De-increments the iterator. if number != 1: # Makes sure the number isn't 1, because 1 should return 1. print(a * int(a)) # Same as the first row, it prints the bottom row. ``` As this is my first [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") answer, some constructive criticism and/or suggestions would be helpful! [Answer] # Rust, 141 137 bytes Abused some formatting stuff, otherwise this would've been a lot longer. ``` |i|{let f=||{for _ in 0..i{print!("{}",i)}println!("")};f();if i>1{for _ in 0..i-2{println!("{}{0:1$}",i,i.to_string().len()*(i-1))}f()}} ``` Unpacked: ``` |i| { let f = || { for _ in 0..i { print!("{}",i) } println!("") }; f(); if i>1 { for _ in 0..i-2 { println!("{}{0:1$}",i,i.to_string().len()*(i-1)) } f() } } ``` [Playground Link](https://play.rust-lang.org/?gist=6ffe943a1b9ae16ffbd9cbc295cd3871&version=stable&backtrace=0) [Answer] # Powershell, ~~98~~ ~~96~~ ~~95~~ ~~83~~ ~~82~~ 75 bytes ``` param($n)($l="$n"*$n) if(($m=$n-2)-ge0){,"$n$(' '*"$n".Length*$m)$n"*$m $l} ``` Ungolfed and explained test script: ``` $f = { param($n) ($l="$n"*$n) # let $l is a string contains N only and return this value as a first line $m=$n-2 if($m-ge0){ # if(N>1) $s=' '*"$n".Length*$m # let $s is spaces inside repeated (length of string represented of n * m) ,"$n$s$n"*$m # return $m strings contains: N, spaces and N $l # retrun the first line again } } &$f 1 &$f 2 &$f 3 &$f 4 &$f 10 ``` Output: ``` 1 22 22 333 3 3 333 4444 4 4 4 4 4444 10101010101010101010 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10101010101010101010 ``` [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~28~~ ~~25~~ 19 bytes ``` ░*k┴╜o\⌡{khí **k++p ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RtIla2Y@mbHk0dU5@zKOehdXZGYfXKmhpZWtrF/z/b8BlyGXEZcxlwmXKZQjkmHKZGvwHAA "MathGolf – Try It Online") ## Explanation This was a fun challenge. Disclaimer: this language is younger than the challenge itself, but the methods used for this answer are not designed for this challenge in particular. I realised that I can save a byte for the 1-case, and by reducing the number of print statements. ``` ░ convert implicit input to string * pop a, b : push(a*b) k read integer from input ┴ check if equal to 1 ╜ else without if o print TOS without popping (handles the 1-case) \ swap top elements ⌡ decrement twice { start block or arbitrary length k read integer from input h length of array/string without popping í get total number of iterations of for loop space character * pop a, b : push(a*b) * pop a, b : push(a*b) (this results in (n-2)*numdigits(n)*" ") k read integer from input + pop a, b : push(a+b) + pop a, b : push(a+b) p print with newline ``` ]
[Question] [ An [abelian sandpile](https://en.wikipedia.org/wiki/Abelian_sandpile_model), for our purposes, is an infinite grid with integer coordinates, initially empty of sand. After each second, a grain of sand is placed at (0,0). Whenever a grid cell has 4 or more grains of sand, it spills one grain of sand to each of its four neighbors simultaneously. The neighbors of (x,y) are (x-1,y), (x+1,y), (x,y-1), and (x,y+1). When a cell spills, it may cause its neighbors to spill. Some facts: * This cascade will eventually stop. * The order in which the cells spill is irrelevant; the result will be the same. ## Example After 3 seconds, the grid looks like ``` ..... ..... ..3.. ..... ..... ``` After 4 seconds: ``` ..... ..1.. .1.1. ..1.. ..... ``` After 15 seconds: ``` ..... ..3.. .333. ..3.. ..... ``` And after 16 seconds: ``` ..1.. .212. 11.11 .212. ..1.. ``` ## The challenge In as few bytes as possible, write a function that takes a single positive integer **t** and outputs a picture of the sandpile after **t** seconds. ## Input A single positive integer **t**, in any format you choose. ## Output A picture of the sandpile after **t** seconds, using the characters ``` . 1 2 3 ``` **Edit: Use any four distinct characters you like, or draw a picture. If you're not using ".123" or "0123", specify in your answer what the characters signify.** **Unlike in the examples, your output should contain the minimal number of rows and columns necessary to show the nonzero part of the sandpile.** That is, for input 3, the output should be ``` 3 ``` For 4, the output should be ``` .1. 1.1 .1. ``` ## Scoring Standard golf scoring applies. ## Rules No language functions or libraries that already know what a sandpile is are allowed. **Edit: The output section has been edited, the character set restriction has been completely lifted. Use any four distinct characters or colors you like.** [Answer] ## R, ~~378~~ ~~343~~ ~~297~~ 291 bytes As usually, the user supplies his/her input via `scan()` (I already used the variable `t`, so let us take `z` instead), so the second line should be launched separately, and then the rest: ``` e=numeric a=1%*%scan() x=1 o=a>3 n=1 while(any(o)){ v=which(o,T) if(any(v==1)){a=rbind(e(n+2),cbind(e(n),a,e(n)),e(n+2));x=x+1;n=n+2;v=which(a>3,T)} q=nrow(v) u=cbind(e(q),1) l=v-u[,1:2];r=v+u[,1:2];t=v-u[,2:1];b=v+u[,2:1] a[l]=a[l]+1;a[r]=a[r]+1;a[t]=a[t]+1;a[b]=a[b]+1 a[v]=a[v]-4 o=a>3} a ``` Outputs an array that contains the values of `a` at `t`th generation (0, 1, 2 or 3). Test cases: ``` z=3 [,1] [1,] 3 z=4 [,1] [,2] [,3] [1,] 0 1 0 [2,] 1 0 1 [3,] 0 1 0 z=16 [,1] [,2] [,3] [,4] [,5] [1,] 0 0 1 0 0 [2,] 0 2 1 2 0 [3,] 1 1 0 1 1 [4,] 0 2 1 2 0 [5,] 0 0 1 0 0 ``` It helps us that this thing is symmetrical both vertcially and horizontally, which means that is the leftmost point gets a height of 4, this means that the topmost, rightmost and lowest points are also 4. Oh, and did I say that you can make beautiful visualisations? After 1000 drops: [![Abelian sandpile after 1000 steps](https://i.stack.imgur.com/6IGcD.png)](https://i.stack.imgur.com/6IGcD.png) After 50000 drops (≈4 seconds): [![Abelian sandpile after 50000 steps](https://i.stack.imgur.com/9awir.png)](https://i.stack.imgur.com/9awir.png) After 333333 drops (≈15 minutes): [![Abelian sandpile after 100000 steps](https://i.stack.imgur.com/gNEDM.png)](https://i.stack.imgur.com/gNEDM.png) You can draw it, too! ``` image(1:n,1:n,a,col=colorRampPalette(c("#FFFFFF","#000000"))(4), axes=F, xlab="", ylab="") ``` This thing took 4 seconds for 10000 iterations but slows down considerably for larger array sizes (e.g. a couple of minutes for 100000 iterations). This is why it gets so slow (I estimated the growth rate as in [![Growth rate](https://i.stack.imgur.com/5h0xt.png)](https://i.stack.imgur.com/5h0xt.png) and obtained τ(i)≈689·i^1.08, so the average time per one additional grain until the whole sandpile settles after `i`th step is slightly larger than one), and the total time as a function of the number of grains grows a little bit slower than quadratically (T(i)≈0.028\*i^1.74): [![Average iteration until the pile settles](https://i.stack.imgur.com/dHfnE.png)](https://i.stack.imgur.com/dHfnE.png) [![Approximate computation time](https://i.stack.imgur.com/cr3zX.png)](https://i.stack.imgur.com/cr3zX.png) And now with a complete explanation: ``` e=numeric # Convenient abbreviation for further repeated use a=1%*%scan() # Creates a 1×1 array with a user-supplied number x=1 # The coordinate of the centre o=a>3 # Remember which cells were overflown n=1 # Array height that is going to change over time while(any(o)){ # If there is still any overflow v=which(o,T) # Get overflown cells' indices if(any(v==1)){ # If overflow occurred at the border, grow the array a=rbind(e(n+2),cbind(e(n),a,e(n)),e(n+2)) # Growing x=x+1 # Move the centre n=n+2 # Change the height v=which(a>3,T) # Re-index the overflowed cells } q=nrow(v) # See how many indices are overflown u=cbind(e(q),1) # Building block for neighbours' indices l=v-u[,1:2];r=v+u[,1:2];t=v-u[,2:1];b=v+u[,2:1] # L, R, T, B neighbours a[l]=a[l]+1;a[r]=a[r]+1;a[t]=a[t]+1;a[b]=a[b]+1 # Increment neighbours a[v]=a[v]-4 # Remove 4 grains from the overflown indices o=a>3} # See if still overflown indices remain a # Output the matrix ``` This is the first time in my life when growing objects (like `a <- c(a, 1)`) works so much faster than pre-allocating a big empty matrix for values and filling it gradually with a ton of zeros unused. **Update.** Golfed 18 bytes by removing `arr.ind` in `which` owing to [Billywob](https://codegolf.stackexchange.com/users/56989/billywob) and replacing `rep(0,n)` with `e=numeric;e(n)` in 5 instances owing to [JDL](https://codegolf.stackexchange.com/users/55516/jdl), and 17 more bytes owing to [JDL](https://codegolf.stackexchange.com/users/55516/jdl). **Update 2.** Since the sandpile is Abelian, it may start with a stack of desired height, so I removed the redundant loop and gained a huge boost in productivity! [Answer] # [MATL](http://github.com/lmendo/MATL), ~~55~~ ~~53~~ ~~48~~ ~~43~~ 42 bytes *Inspired by [@flawr's answer](https://codegolf.stackexchange.com/a/92254/36398).* **Graphical output**: ``` 0i:"Gto~+XytP*+t"t4=t1Y6Z+b+w~*]]tat3$)1YG ``` [Try it at MATL Online!](https://matl.io/?code=0i%3A%22Gto%7E%2BXytP%2a%2Bt%22t4%3Dt1Y6Z%2Bb%2Bw%7E%2a%5D%5Dtat3%24%291YG&inputs=30&version=19.1.0). It takes about 10 seconds for input `30`. You may need to refresh the page and press "Run" again if it doesn't work. Here's an example result for input `100`: [![enter image description here](https://i.stack.imgur.com/eS2xS.png)](https://i.stack.imgur.com/eS2xS.png) **ASCII output (43 bytes)**: ``` 0i:"Gto~+XytP*+t"t4=t1Y6Z+b+w~*]]tat3$)48+c ``` [Try it online!](http://matl.tryitonline.net/#code=MGk6Ikd0b34rWHl0UCordCJ0ND10MVk2WitiK3d-Kl1ddGF0MyQpNDgrYw&input=MTY) ### Explanation ``` 0 % Push a 0. This is the initial array. Will be resized in first iteration i: % Take input n. Generate range [1 2 ... n] " % For each, i.e. repeat n times Gto~+ % Push input and add negate parity. This "rounds up" n to odd number % m = n or n+1 Xy % Identity matrix with that size tP* % Multiply element-wise by vertically flipped copy. This produces a % matrix with a 1 in the center and the rest entries equal to 0 + % Add to previous array. This updates the sandpile array t % Duplicate " % For each column (i.e. repeat m times) t4= % Duplicate. Compare with 4 element-wise. This gives a 2D mask that % contains 1 for entries of the sandpile array that equal 4, and 0 % for the rest t % Duplicate 1Y6 % Predefined literal: [0 1 0; 1 0 1; 0 1 0] Z+ % 2D convolution, maintaining size b % Bubble up to bring sandpile array to top + % Element-wise addition. This adds 1 to the neighbours of a 4 w % Swap to bring copy of mask to top ~* % Multiply bu negated mask. This removes all previous 4 ] % End ] % End t % Duplicate the updated sandpile array a % 1D mask that contains 1 for columns that contain a 1. This will be % used as a logical index to select columns t % Duplicate. This will be used as logical index to select rows (this % can be done because of symmetry) 3$) % Keep only those rows and columns. This trims the outer zeros in the % sandpile array 1YG % Display as scaled image ``` [Answer] # Matlab, ~~160 156~~ 148 bytes ``` n=input('');z=zeros(3*n);z(n+1,n+1)=n;for k=1:n;x=z>3;z=z+conv2(+x,1-mod(spiral(3),2),'s');z(x)=z(x)-4;end;v=find(sum(z));z=z(v,v);[z+48-(z<1)*2,''] ``` First a way too big matrix is created, with the `n` in the middle somewhere. Then the cascading is calculated with a very convenient 2d convolution. At the end the excess is trimmed off and the whole thing is converted to a string. Example output for `t=100` ``` ...121... ..32.23.. .3.323.3. 123.3.321 2.23.32.2 123.3.321 .3.323.3. ..32.23.. ...121... ``` As always: > > Convolution is the key to success. > > > [Answer] # Python 2, ~~195 +1 +24 = 220~~ 217 ``` from pylab import* ifrom scipy.signal import convolve2d as c k=(arange(9)%2).reshape(3,3) def f(n):g=zeros((n,n),int);g[n/2,n/2]=n;exec"g=c(g/4,k,'same')+g%4;"*n;return g[any(g,0)].T[any(g,0)] ``` output for n=16 ``` array([[0, 0, 1, 0, 0], [0, 2, 1, 2, 0], [1, 1, 0, 1, 1], [0, 2, 1, 2, 0], [0, 0, 1, 0, 0]]) ``` there is a LOT of unnecessary padding and iterations, by using `n` as a "good-enough" upper bound, but n=200 still completed in a second and n=500 in about 12 seconds ungolfed ``` from pylab import* from scipy.signal import convolve2d as c k=array([0,1,0], [1,0,1], [0,1,0]) def f(n): g=zeros((n,n)) # big grid of zeros, way bigger than necessary g[n/2,n/2]=n # put n grains in the middle exec"g=c(g/4,k,'same')+g%4;"*n # leave places with <4 grains as is, convolve the rest with the kernel k, repeat until convergence (and then some more) return g[any(g,0)].T[any(g,0)] # removes surrounding 0-rows and columns ``` replacing `return x` by `imshow(x)` adds one character and outputs an ugly interpolated image, adding `imshow(x,'gray',None,1,'nearest')` removes the blurry interpolation bringing the output up to specs [![n=100](https://i.stack.imgur.com/k9WTV.png)](https://i.stack.imgur.com/k9WTV.png) [Answer] ## Python ~~3~~ 2, ~~418~~ ~~385~~ ~~362~~ ~~342~~ 330 bytes ``` w='[(i,j)for i in r(n)for j in r(n)if a[i][j]>3]' def f(z): a,x,r=[[z]],0,range for _ in[0]*z: n=len(a);v=eval(w) if[1for b,c in v if(b==0)+(c==0)]:n+=2;a=[[0]*n]+[[0]+a[i]+[0]for i in r(n-2)]+[[0]*n];x+=1;v=eval(w) for c,d in v:exec'a[c+%s][d+%s]+=1;'*4%(-1,0,1,0,0,-1,0,1);a[c][d]-=4 for i in a:print''.join(map(str,i)) ``` Edit: saved 6 bytes thanks to @Qwerp-Derp All credit to @Andreï Kostyrka, as this is a direct translation of his R code into Python. [Answer] # Perl, ~~157~~ 147 bytes Includes +1 for `-p` Run with the count on STDIN, prints the map using `0123` to STDOUT: ``` sandpile.pl <<< 16 ``` `sandpile.pl`: ``` #!/usr/bin/perl -p map{++substr$_,y///c/2-1,1;/4 /?$.+=s%^|\z%0 x$..$/%eg+!s/\b/0/g:s^.^$&%4+grep{3<substr$\,0|$_+"@+",1}-$.-2,-2,0,$.^eg while/[4-7]/}($\="0 ")x$_}{ ``` [Answer] # JavaScript, ~~418~~ ~~416~~ ~~406~~ ~~400~~ 393 bytes Creates an anonymous function that displays the output on the console. ``` var f = t=>{a=(q,w)=>Math.max(q,w);c=_=>{x=a(p[0],x);y=a(p[1],y);m[p]=(g(p)+1)%4;if(!m[p]){s.push([p[0],p[1]]);}};x=y=0,m={};g=k=>{v=m[k];return!v?0:v;};m[o=[0,0]]=1;s=[];while(--t){m[o]=(m[o]+1)%4;if(!m[o]){s.push(o);}while(s.length){p=s.pop();p[0]++;c();p[0]-=2;c();p[0]++;p[1]++;c();p[1]-=2;c();p[1]++;}}s='';for(i=-x;i<=x;i++){for(j=-y;j<=y;j++){v=g([i,j]);s+=v==0?'.':v;}s+='\n';}console.log(s);} ``` ``` <input id="i" type="number"><input type="button" value="Run" onclick="var v = +document.getElementById('i').value; if (v>0) f(v)"> ``` [Answer] # Nim, 294 characters ``` import os,math,sequtils,strutils var z=parseFloat paramStr 1 y=z.sqrt.toInt+1 w=y/%2 b=y.newSeqWith newSeq[int] y x=0 proc d(r,c:int)= b[r][c]+=1;if b[r][c]>3:b[r][c]=0;d r-1,c;d r,c+1;d r+1,c;d r,c-1 for i in 1..z.toInt:d w,w while b[w][x]<1:x+=1 for r in b[x..< ^x]:echo join r[x..< ^x] ``` Compile and Run: ``` nim c -r sandbox.nim 1000 ``` Notes: 1. I was able to come up with a shorter version which uses a fixed table size, but I edited it out in favor of the dynamic one. 2. Once the sandbox is computed, `x` is calculated as the number of zero columns at the start of the middle row. 3. For display, the table is sliced down by excluding `x` rows and columns from each end. ## Performance ``` nim c --stackTrace:off --lineTrace:off --threads:off \ --checks:off --opt:speed sandbox.nim time ./sandbox 10000 0.053s time ./sandbox 20000 0.172s time ./sandbox 30000 0.392s time ./sandbox 40000 0.670s time ./sandbox 100000 4.421s time ./sandbox 1000000 6m59.047s ``` [Answer] # Scala, 274 bytes ``` val t=args(0).toInt val s=(Math.sqrt(t)+1).toInt val (a,c)=(Array.ofDim[Int](s,s),s/2) (1 to t).map{_=> ?(c,c)} println(a.map{_.mkString}.mkString("\n")) def?(b:Int,c:Int):Unit={ a(b)(c)+=1 if(a(b)(c)<4)return a(b)(c)=0 ?(b+1,c) ?(b-1,c) ?(b,c+1) ?(b,c-1) } ``` Usage: `scala sandpile.scala <iterations>` I don't think there is a lot to explain about this one. Basically it just adds one grain of sand to the center. Then checks if it is larger than 4, if so it'll spill over and check for all neighbours larger than 4, spill over, etc. It's quite fast. Performance: * t=10000 72ms * t=20000 167ms * t=30000 419ms * t=40000 659ms * t=100000 3413ms * t=1000000 about 6 minutes [Answer] # J, 76 bytes ``` p=:0,.~0,.0,~0,] p`(4&|+3 3([:+/@,*&(_3]\2|i.9));._3[:<.4%~p)@.([:*/4>{.)^:_ ``` I define a verb `p` which pads a border of zeros around the input. The main verb takes an array as input. It then checks the first row for any sandpile that contains 4 or more grains. If one does, it outputs the same array except padded using `p`, and otherwise it performs 2d convolution to simulate falling grains. The main verb is repeated until convergence using the power operator `^:_`. ## Usage ``` p =: 0,.~0,.0,~0,] f =: p`(4&|+3 3([:+/@,*&(_3]\2|i.9));._3[:<.4%~p)@.([:*/4>{.)^:_ f 15 0 3 0 3 3 3 0 3 0 f 50 0 0 0 1 0 0 0 0 0 3 1 3 0 0 0 3 2 2 2 3 0 1 1 2 2 2 1 1 0 3 2 2 2 3 0 0 0 3 1 3 0 0 0 0 0 1 0 0 0 timex 'r =: f 50000' 46.3472 load 'viewmat' ((256#.3&#)"0<.255*4%~i._4) viewmat r ``` It takes about 46 seconds to compute the result for *n* = 50000, and the result can be displayed using the `viewmat` addon with a monochrome color scheme. ![figure](https://i.stack.imgur.com/Y4Nzo.png) [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 51 bytes[SBCS](https://github.com/abrudz/SBCS) ``` {m⌿r/⍨m←⌈/×r←(4∘|+{+/⊢/4 2⍴⌊⍵÷4}⌺3 3)0,∘⍉∘⌽⍣4⊢⍵}⍣≡⍪ ``` [Try it online!](https://tio.run/##hY/BSsNAEIbv@xS5rdKW7O5ED75NwESKKZHQi9RcpJQm7hY9iF6tl@JZEQoi2DeZF4n/RogRCl5mZ77/n5md@CIbnV7GWX7W8Op@nPPiVjUp4mzC9rMI2W0mqNguw91Dgewg4uXj1WA2CLleh1Fg2L2yrdm97d6jku2WAjpUQ5jYVT7aD3bPEcywlEi5emL30jRTvwSMq7Wfm7Lbnsg0HmcSGXjBN3OZn8tSCJqig0SEZ/W14cWdVFrJQGqlEX0u9FFPJC8SkRfJi8c9EXYvK6NNOwNDdK/@0YVIAn92fQ2gtAEDTIYdI6MM/WUESO2@jukWkNE91jb69n98@@bt3fv7P8Tu0OQb "APL (Dyalog Unicode) – Try It Online") [Answer] # C 222 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` G[99][99],x,y,a,b,c,d;S(x,y){++G[y][x]>3?G[y][x]=0,S(x+1,y),S(x-1,y),S(x,y+1),S(x,y-1):0;a=x<a?x:a;b=y<b?y:b;c=x>c?x:c;d=y>d?y:d;}F(t){for(a=b=99;t--;)S(49,49);for(y=b;d/y;y+=puts(""))for(x=a;c/x;)printf("%d ",G[y][x++]);} ``` [Try it online!](https://tio.run/##NY7LasMwEAB/pRgK2mhFIhoK8kb2LfmAHI0pepDUhybBUYyEybe7Ek0PC7Mze1gnzs4ty6FTqi@DERMatOjQ05HlDWbOD13qu9g3H@2L9AZz5DLnAuIfMHH5AiGh3pDRcWfaWBuyOu1sm2pLTsfGZefI69T47Dw99yzAfLqOzGirlaIgBMGRbRVuFVAJSVvy60SJ69sj3FlVARQftSG3jgS3cbiEE6ve/VuFf49y3gM9lx8zXNgXTuC@zbhaTTTvmQnXgU2d7KFcLPLzFw "C (gcc) – Try It Online") [Answer] # PHP, 213 bytes ``` function d($x,$y){global$p,$m;$m=max($m,$x);$q=&$p[$y][$x];if(++$q>3){$q=0;d($x+1,$y);d($x-1,$y);d($x,$y+1);d($x,$y-1);}}while($argv[1]--)d(0,0);for($y=-$m-1;$y++<$m;print"\n")for($x=-$m;$x<=$m;)echo+$p[$y][$x++]; ``` recursively creates the pile in `$p`, remembering the size in `$m`; then prints with nested loops. Run with `-r`. ]
[Question] [ In this challenge, your task is to decipher a string. Luckily, the algorithm is pretty simple: reading from left to right, each encountered digit ***N*** (0 to 9) must be replaced with the character which is ***N+1*** positions before it. ### Example The input string `"Prog2am0in6"` would be decoded this way: [![example](https://i.stack.imgur.com/JJ2gJ.png)](https://i.stack.imgur.com/JJ2gJ.png) Hence, the expected output is `"Programming"`. ### Clarifications and rules * The input string will contain ASCII characters in the range 32 - 126 exclusively. You can assume that it will never be empty. * The original deciphered string is guaranteed not to contain any digit. * Once a character has been decoded, it may in turn be referenced by a subsequent digit. For instance, `"alp2c1"` should be decoded as `"alpaca"`. * References will never wrap around the string: only previous characters can be referenced. * You can write either a full program or a function, which either prints or outputs the result. * This is code golf, so the shortest answer in bytes wins. * Standard loopholes are forbidden. ### Test cases ``` Input : abcd Output: abcd Input : a000 Output: aaaa Input : ban111 Output: banana Input : Hel0o W2r5d! Output: Hello World! Input : this 222a19e52 Output: this is a test Input : golfin5 3s24o0d4f3r3y3u Output: golfing is good for you Input : Prog2am0in6 Puz0les7&1Cod74G4lf Output: Programming Puzzles & Code Golf Input : Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d. Output: Replicants are like any other machine. They're either a benefit or a hazard. ``` [Answer] # Java 7, ~~81~~ 80 bytes ``` void a(char[]a){for(int i=0;++i<a.length;)if(a[i]>47&a[i]<58)a[i]=a[i-a[i]+47];} ``` [Try it online!](https://tio.run/nexus/java-openjdk#tY5Na4NAEIbv/oppDmVFKuuqhGAslF56j9BD8DB@L2x2w@7aIsHfbjUpIb3XOcw7X7zPlAKNgQwu05fiFSApO9THHN1LozTh0gJPaeJ5fI@@qGVru8TlDcEjz1@j7fOi@3jnLprO6WUpvGibJ@N07gvBSzAW7SxX@xNySQ5Wc9leGQ78RgYWUpD1N2TETe7j2zNQzLsNFmW18a16n2dvWuPweGh9JMVDfxiMrU@@6q1/nmlWyD/re3FzppSu41ygDIJgHe@PWlAFn0zH1dM6BNtxA4wxDHZ1zNZhtEo0XMYQGhYpWkVNqMMh7P8DNjqjM/0A "Java (OpenJDK 8) – TIO Nexus") Saved 1 byte thanks to [Anders Tornblad](https://codegolf.stackexchange.com/users/68002/anders-tornblad). The first character cannot be a digit so it doesn't need to be checked meaning we can preincrement before checking our terminate condition. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes ``` ~ịṭṭµ@/ ``` [Try it online!](https://tio.run/nexus/jelly#@1/3cHf3w51rgejQVgf9////B6UW5GQmJ@aVFCuYFKUa52Rmm5hY5FUa55dkWBSZ5iYmm2XmWehZhJiZVKoXGZsbZpZYGpubJRommeYZpmWWmOcXGSUaZhhVGZqn6AEA "Jelly – TIO Nexus") ### How it works ``` ~ịṭṭµ@/ Main link. Argument: s µ Combine the four links to the left into a chain (arity unknown). @ Swap the chains arguments. This makes it dyadic. / Reduce s by the chain with swapped arguments. It will be called with right argument r (the result of the previous call, initially the first character) and left argument c (the next character of s). ~ Bitwise NOT of c. This maps a digit 'd' to ~d = -(d+1), but all non-digit characters 'D' to 0. ṭ Tack; append c to r. ị Index; select the character of the result to the right at the index from the result to the left. Indexing is 1-based and modular, so 0 is the last character, -1 the second to last, etc. ṭ Tack; append the resulting character to r. ``` [Answer] ## Haskell, 55 bytes ``` o#c|c>'/',c<':'=o!!read[c]:o|1<2=c:o reverse.foldl(#)[] ``` Usage example: `reverse.foldl(#)[] $ "Prog2am0in6 Puz0les7&1Cod74G4lf"` -> `"Programming Puzzles & Code Golf"`. [Try it online!](https://tio.run/nexus/haskell#BcHBDoIgAADQe1@B2kZtzYagkJO@oFN1cx4IYbIQHFKbzX@39zafyVVe4RmeZANryH2SBCX6Vna1X1FTcFn7neZBfVWYVa697e0hO7bdNgrjAAfTJz5iuDmwBxqkdzVZI4WLMyBBYWvehDC3YB8HFspRyMo4lrNnRRYYMEUmXjCtBHqVDmkTqQ@FQEPxQ7TPU7D9AQ "Haskell – TIO Nexus") Reduce the string to a reverse copy of itself with the numbers replaced by the corresponding chars. "reverse", because this way we have easy access to the string so far when indexing the numbers. Reverse it again. [Answer] # C, 46 bytes ``` f(char*s){for(;*s++;)*s=s[(*s-52)/6?0:47-*s];} ``` [Try it online!](https://tio.run/##XczNToNAFAXgPU9xw8LM0JCLM9OSOCFGW/qTmLYRXBEWhDqVhDJmBhba9NmR6gL1rM7inK/027Lse0XKt8J4lp6VNkR6djKR1LORzYhn/SmjOLsP7kToezaXl75qWjgVVUOoc3ZgyPUNtjVZHrl7o4@sOAVVM4N99xnUrza8uZ3rQyhWolau/H4oMsypfO9a@9P@OOwKHXWtqmYK3DKhg4NQ3PAP3v0G2CiwfwTPcojATdebBBCT9HmzXWGy3r08LXCLuxQeY3hYLuM5IqbxAtAdWT6yQ3Uu/Rc) --- # C, ~~52~~ ~~49~~ 48 bytes *Thanks to @l4m2 for saving a byte!* ``` f(char*s){for(;*s++;)*s>47&*s<58?*s=s[47-*s]:0;} ``` Edits the input string directly. [Try it online!](https://tio.run/##VYyxDoIwFEV3vqJhILSEpEKxxooODq7shIGARRJoTV8ZlPDtCDqodzrDPacKbVXNs/SrW2kI4FFq4wsCQSAwgSPjHoFDsjsRSCFnPCRQ7KmY5lZZ1Jet8rEzOmjZ6iOwJi9SNzO6icqetmqLsuFJuytwb3PWNWcX1klXvA3pL3cs7oOFD/11ojXU6E62KkExREzTmsnYxI94@A1E38KCzjS/AA) **Alternative 50-byte version:** ``` f(char*s){for(;*s++;)*s=abs(*s-57)>9?*s:s[47-*s];} ``` **Recursive version, 48 bytes:** ``` f(char*s){*s>47&*s<58?*s=s[47-*s]:0;*s++&&f(s);} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` vydiÂyèëy}J ``` [Try it online!](https://tio.run/nexus/05ab1e#@19WmZJ5uKny8IrDqytrvf7/D0otyMlMTswrKVYwKUo1zsnMNjGxyKs0zi/JsCgyzU1MNsvMs9CzCDEzqVQvMjY3zCyxNDY3SzRMMs0zTMssMc8vMko0zDCqMjRP0QMA "05AB1E – TIO Nexus") **Explanation** ``` v # for each character y in input ydi # if y is a digit  # push a reversed copy of the string we've built up so far yè # push the character at index y in the reversed string ë # else y # push y } # end if J # join stack to a single string # output top of the stack at the end of the loop ``` [Answer] # JavaScript (ES6), 59 53 bytes ``` f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x ``` Saved 7 bytes thanks to fəˈnɛtɪk. ``` f=x=>/\d/.test(x)?f(x.replace(/\d/,(m,o)=>x[o+~m])):x console.log(f("Prog2am0in6")); console.log(f("abcd")); console.log(f("a000")); console.log(f("ban111")); console.log(f("Hel0o W2r5d!")); console.log(f("this 222a19e52")); console.log(f("golfin5 3s24o0d4f3r3y3u")); console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf")); console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.")); ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 37 bytes Byte count assumes ISO 8859-1 encoding. ``` \d $*«» r1+`(?<=(.)(?<-2>.)*)(«)*» $1 ``` [Try it online!](https://tio.run/nexus/retina#Dc49boMwGIDh3adwpagFqiJ//sFEStqhQztGVaQsGWqwCVYcOzLOQK6UI3TjYpTpHZ7lnY8arYrpMf2hCK@/2cdmm5X5kjf6XuZFnk2PvFhwBfOsmlYjRQhBjfIAgL6NIwEfaBT6CaXeDphSqmBtBEWn4DrrBWYD5YFo3rHIRnZDuxhOVF2I9RXe3e7EmUE@w2fQkn9x16Efc3W2VT4NmEfDnD1zXvuRhdTXUVxUW1lfl/W@4uNLZBJsWjNZKWiEh84mGeJy0NM7SP0P "Retina – TIO Nexus") ### Explanation ``` \d $*«» ``` Replace each digit **d** with **d** `«`s, followed by one `»`. We need the latter a) to be able to recognised positions where **d = 0** and b) as a separator between adjacent digits. ``` r1+`(?<=(.)(?<-2>.)*)(«)*» $1 ``` Repeatedly (`+`) match the regex on the first line from right to left (`r`) and then replace the left-most match (`1`) with the substitution on the second line. The regex itself matches one of our now unary digits and counts the number of `«`s in group 2. The lookbehind then matches **d** characters with `(?<-2>.)*` before capturing the referred-to character in group 1. The string of `«`s and `»` is then replaced with the captured character. [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~21~~ ~~19~~ ~~17~~ 16 bytes ``` "@t4Y2m?UQ$y]]&h ``` Try it at [**MATL Online!**](https://matl.io/?code=%22%40t4Y2m%3FUQ%24y%5D%5D%26h&inputs=%27Hel0o+W2r5d%21%27&version=19.9.0) **Explanation** ``` % Implicitly grab input as a string " % For each character in the input @ % Push that character to the stack t % Make a copy of it 4Y2 % Push the pre-defined array '0123456789' to the stack m % Check if the current character is part of this array (a digit) ? % If it is UQ % Convert it to a number and add 1 (N) $y % Make a copy of the element N-deep in the stack. MATL uses one-based indexing % So 1$y is the element at the top of the stack, 2$y is the next one down, etc. ] % End of if statement % Non-digit characters remain on the stack as-is ] % End of for loop &h % Horizontally concatenate the entire stack to form a string % Implicitly display the result ``` [Answer] ## JavaScript (ES6), 51 bytes ``` f= s=>s.replace(/\d/g,(c,i)=>a[i]=a[i+=~c]||s[i],a=[]) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` `a` is used to store the replaced digits to deal with digits referring to other digits. [Answer] # [Perl 5](https://www.perl.org/), 34 bytes 33 bytes of code + `-p` flag. ``` s/\d/substr$_,-$&-1+pos,1/e&&redo ``` [Try it online!](https://tio.run/nexus/perl5#Dc67bsMgFADQna8gauQOjWMuD@PMHdoxiiJ1qVRhg2NUAtYFD87POzlfcN52s8NA63nLza9t8tLngvu/Q72vaviYUz5A46oKnU3bZvrBEsMYI72JAEC@XWCJ/nBUdkfK5DPlnBs4OcXJLYXRR0VF5jIxK0eBYhULOWO6cXNnPrb0vDxYcFlX8Jmsll8yjOTi5uAHE0umEp0I/l/KLq4ilalDdTdD62N37K6tXN9RaPDlJHRroFcRRl90wtdg4g/Q9vgE "Perl 5 – TIO Nexus") `s/\d/.../e` replace the first digit by `...` evaluated as Perl code. (with `...` being `substr$_,-$&-1+pos,1` in that case. `substr$_,-$&-1+pos,1` returns the substring of `$_` of length `1` at index `-$&-1+pos`, where `$&` is the number just matched, and `pos` is the index of the start of the match. We just need to `redo` if the replace was successful in order to replace every digit. (and the result is implicitly printed thanks to `-p` flag). --- Old approach, 47 bytes: 44 bytes of code + `-F` flag. ``` map{$F[$i]=$F[$i-$_-1]if/\d/;++$i}@F;print@F ``` [Try it online!](https://tio.run/nexus/perl5#Hc5NS8MwGADge37FO1b0MLrlqx@jDAZC9ThE8KBD0jZtX8ySkmRgJ/72Kp6e67NeTdobSOvloqbvpH5L8Hz4J00@UnbGfvfe7arNJsGfY11NHm081kuVIByAVrAGr4OOaAfonQervyJEHSK0KuhFNW1HFKWUNMoyxsiTNtTBK/dZtyJxxACcc8X2OuNkcKZHm4EIXDrayV54MYsrOXk3cHWhaHM4XW/U6FDcsQfXFfJRmp4868lgq2wMIL0WBj@lLO0sXBxLn11Um6Mtt@VLLud7LwqGcS@KXLEms6zHWDj/Nxj5jRXd9hc "Perl 5 – TIO Nexus") Quite straight forward actually. `-F` flag splits the inputs on each character into `@F`. `map{...}@F` iterates through `@F` (ie. every character of the input). If the character if a digit (`/\d/`), then we replace it by the character at index `$i-$_-1`. The `$i` is the current index variable (that we maintain by incrementing at each character seen). [Answer] # JavaScript ES6, ~~61~~ 59 bytes Thanks @Luke for golfing off 8 bytes ``` x=>[...x].map((p,i,a)=>a[i]=/\d/.test(p)?a[i-1-p]:p).join`` ``` [Try it online!](https://tio.run/nexus/javascript-node#bY09T8MwAER3fkXoALZE3fgjcYqUMjDAWCEkhhKpJrETg2Nbtis1/fOhrCjr3Xt3qp7P9Q6I@oAQOjcQjcID4B80rHfioJt689ltUJIxAQ@frskar33z6CH6dtoej3PrbHRGIuN6oMDqTXqjW2FTzFiQ1Ogfxio7UZeGKhSjaEttK1S9l2y6D5RjnbaUlwJ/FRYrnbgLROCBXDDv0ArCm3/z@@B6IsZc2zLbny65kZHf4WfXcfbCjFowemeUtkVGI2Eu75iigU70tECmQceMkOv/VhZkAXiVJnfZBwlFd/tXz78) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~27~~ 17 bytes ``` vyDdiU)DRXèU`X}}J ``` [Try it online!](https://tio.run/nexus/05ab1e#@19W6ZKSGarpEhRxeEVoQkRtrdf//0GpBTmZyYl5JcUKJkWpxjmZ2SYmFnmVxvklGRZFprmJyWaZeRZ6FiFmJpXqRcbmhpkllsbmZomGSaZ5hmmZJeb5RUaJhhlGVYbmKXoA "05AB1E – TIO Nexus") ``` vy } # For each character Dd # Push is_number i } # If it is U # Save save it )DR # Wrap the (reversed) stack into an array Xè # Get the character at the saved index U`X # Flatten the whole stack J # Join ``` [Answer] # CJam, 13 bytes ``` q{_A,s#)$\;}/ ``` [Online demo.](http://cjam.aditsu.net/#code=q%7B_A%2Cs%23)%24%5C%3B%7D%2F%0A&input=Prog2am0in6) This solution uses CJam's built-in "copy *n*-th item on the stack" operator `$` to implement the decoding. It starts by reading the input (with `q`) and then looping over the characters from the input string and dumping them onto the stack (with `{}/`). However, inside the loop body it also duplicates each character after it has been put on the stack (with `_`) and checks if it's a digit by looking up its position with `#` in the string `"0123456789"`, conveniently represented as `A,s`. The result of this lookup is either the digit's numeric value or, if the character is not a digit, -1. The `)` operator then increments that value by one, and `$` replaces it with the character current at that many positions below the top of the stack. Finally, `\;` just removes the copy of the current input character that we made with `_` from the stack, as it's no longer needed. [Answer] # [Befunge-98](https://github.com/catseye/FBBI), ~~45~~ 43 bytes ``` ::::#@~\1p:1g::'9`!\'/`*j;'/--1g\1p\1g#;,1+ ``` [Try it online!](https://tio.run/nexus/befunge-98#@28FBMoOdTGGBVaG6VZW6pYJijHq@glaWdbq@rq6hulAiRjDdGVrHUPt//8TcwqMkg0B "Befunge-98 – TIO Nexus") The idea: 1. For each char in the input string, 1. Write it to line 2 2. If it is not a number, just output it 3. Otherwise, look up the correct value, rewrite it, then output it ``` :::: ; There's a counter on the stack, duplicate it 4 times ; #@~ ; Get the next char of input, exiting if there is none ; \1p ; At the location (counter, 1), write the input char ; :1g ; Re-obtain the char. Stack is now [counter * 4, input] ; :: ; Stack: [counter * 4, input * 3] ; '9`!\'/`* ; If !(input > '9') and (input > '/') ; ; IE If ('0' <= input && input <= '9') ; j;...; ; Then execute the ... ; ; Stack: [counter * 4, input] ; ; The ... branch: ; '/- ; input -> int. (input -= '/') ; - ; counter - int(input) - 1 ; ; Stack: [counter * 3, lookupPosition ] ; 1g ; Get the char that we want to find ; \1p\1g# ; Overwrite the current char (not the old) ; ; Both branches: ; ,1+ ; Print the number and increment the counter ; ``` --- I wasn't able to get this version shorter, but this one is 44 bytes: ``` s #@~\3p:3g::'9`!\'/`*j;'/--3g#;:10g3p,1+::: ``` Thought I'd share it because of the neat trick with `s` - but storing the counter on the stack leads to that 1 char improvement [Answer] # [Python 2](https://docs.python.org/2/), 59 bytes ``` s='' for c in input():s+=c['/'<c<':':]or s[~int(c)] print s ``` [Try it online!](https://tio.run/nexus/python2#DcmxDoMgFEDR3a8gLk/TpA2CQIn@RNPNOFCq8aUWCNDBDv11a3KHk9w99QDF7COxBN1R@OSq1unU2wEu0NkONOjx@Gn4ocuVrccixEMk7Xt5m8KK1ricCI8TW/HFuXIb83lRsX0bK9Cps7oLvkFkkmK@MikMfbSOzpilj42hS/Ol8ln@AQ "Python 2 – TIO Nexus") [Answer] # Python 2, ~~75~~ 71 bytes ``` s='';j=-1 for i in input():s+=s[j-int(i)]if'/'<i<':'else i;j+=1 print s ``` [Try it Online!](https://tio.run/nexus/python2#@19sq65unWWra8iVll@kkKmQmQdEBaUlGppWxdq2xdFZupl5JRqZmrGZaer66jaZNupW6qk5xakKmdZZ2raGXAVFQHmF4v//1QOK8tONEnMNMvPMFAJKqwxyUovN1Qyd81PMTdxNctLUAQ) **Edit:** Fixed for ascii values between 32-47 **;** Fixed for double decoding (eg. "alp2c1" to "alpaca") [Answer] # PHP 7.1 ~~67~~ 59 bytes ``` while(_&$c=$argn[$i++])$t.=($c^"0")<" "?$t[~+$c]:$c;echo$t; ``` Takes input from STDIN; run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/e551b53d933d0cdd0a872a88eaac5d66862dbc2e). * `_&$c=$s[$i++]` loop through string (`_&$c` will result in something that is not `"0"`; so the only character that can break the loop is the empty string = end of input) * `$c^"0"` toggle bits 5 and 6 in the ascii code * `<"\n"` check if result is < chr(10) * if so, it is a digit: print previous character by index (and copy to current index) * else print this character Thanks @Christoph for saving 12% [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~25~~ 23 bytes -2 bytes thanks to @FrownyFrog ``` ((⊂⌷⊢)⍣≡⍳∘≢-11|⎕d∘⍳)⊃¨⊂ ``` [Try it online!](https://tio.run/##hcwxTwIxFMDxnU9RFx4MJG3vkOjqgCObc6HX82Lhmd4xgLqoMYKecTFxFRd3Ykwc/Sjvi5wPGFxQ2@bS9n7/mlPfshPjMW0NvMnzbFDRw1OGdPOoKsffRoPml3T/QfNFk8pXmr1QuaTbZ5otWkqdM7arU7ls0vzq641xVRXcnVH5zjjw1lH5uQ94AnR3Dc5kHviCf4eLGpj@wIL4fRQbwVBK@Q/kwbBvRkop@AOy4Mn0MPESxZEObbsDWykLzwKDZ1GD4jjLhdbaqL2krWFLsBa8jCiSvOAkRe@yUVtEuY5R2thFIZpEY/hJNiJdVSmiFQ6DmOCY217AVJuhzEa7ojeeSp/knbo6QNuJu7F3UKxFMMPhqmcxZSHqgkUiuvwsfAM "APL (Dyalog Classic) – Try It Online") uses `⎕io←1` (`⍵` below stands for an intermediate value in the evaluation) `⎕d` is the string `'0123456789'` `⎕d⍳⍵` finds the (1-based in this case) indices of `⍵`'s chars in `⎕d`; for a non-digit the index is 11 `11|⍵` is modulo - the 11s become 0s `≢⍵` is the length of `⍵` `⍳≢⍵` is `1 2 ...` till `≢⍵` so, `(⍳≢⍵)-11|⎕d⍳⍵` gives us a vector *i* of the indices where we should look to get the resulting characters; however some of those indices may redirect to yet other (smaller) indices. To compute the transitive closure (i.e. the effective indices), we index the vector into itself (`⊂⌷⊢`, a train equivalent to `(⊂i)⌷i` or `i[i]`) and repeat that until it stabilises (`⍣≡` is known as the *fixed point* operator). finally we index into the original string: `(...)⊃¨⊂` [Answer] # Vim macro/keystrokes, ~~49~~ 29 bytes `^M` represent the return character (0x0A, 1 byte). ``` qaqqa/\d^Myl@=@"+1^Mhylnvp@aq@a ``` ## Explanation ``` qaq clear register a qa record into a /\d^M move the cursor to the next digit yl yank the digit @=@"+1^Mh move the cursor left that number of characters plus one yl yank the char n go back to the digit vp replace the digit with the yanked char @a recursive call will execute until the search for a digit fails q stop recording @a run the macro ``` [Answer] # [Python 2](https://docs.python.org/2/),~~83~~ 80 bytes ``` r=input() for i in r: if'/'<i<':':r=r.replace(i,r[r.find(i)+~int(i)],1) print r ``` [Try it online!](https://tio.run/nexus/python2#DcexDoIwFAXQvV/xJl8bCYIhkjQwObiyGwcirXlJbZsrLA7@emU6OQWjxLyt2iifQEISCVaReD7xIANbthhRw@UwP52WCnfUXuKixRx/EtfdR9UalbGHUApPSK/z/G4kXmjavk1wn/7QXtPSd7cueP4D "Python 2 – TIO Nexus") * saved 3 bytes but checking ascii instead of is digit! Thanks to math\_junkie! [Answer] # [Japt](https://github.com/ETHproductions/japt), 24 bytes ``` £Xn >J?U=UhYUgJ+Y-X):PÃU ``` [Try it online!](https://tio.run/nexus/japt#@39ocUSegp2XfahtaEZkaLqXdqRuhKZVwOHm0P//lYJSC3IykxPzSooVTIpSjXMys01MLPIqjfNLMiyKTHMTk80y8yz0LELMTCrVi4zNDTNLLI3NzRINk0zzDNMyS8zzi4wSDTOMqgzNU/SUAA) ### Explanation: ``` £Xn >J?U=UhYUgJ+Y-X):PÃU £ à Iterate through the input (implicit U) X becomes the iterative item, Y becomes the index Xn Try parseInt(X) >J > -1 In this case, this checks if X is a digit ? If true: U= Set U to UhY U with the char at index Y set to: UgJ+Y-X The index at -1+Y-X ): Else: P variable P (just a no-op in this case) U Finally, return U ``` [Answer] # Ruby, ~~56~~ 46 bytes ``` ->s{i=0;s[i]=s[i+~s[i].to_i]while i=s=~/\d/;s} ``` [Try it online!](https://repl.it/HAmP/2) [Answer] # [Python 2](https://docs.python.org/2/), 58 bytes ``` lambda s:reduce(lambda t,c:t+(c+t)['/'<c<':'and~int(c)],s) ``` This is essentially a port of my Jelly answer, plus the digit check from @xnor's Python answer. [Try it online!](https://tio.run/nexus/python2#LcfBDoIgGADgV2FegNlsCAo5e4nWrTrgD06WosO/gx16devQd/t6cib3fbRT5yxZm@TdCzz7Hw/QYM4gR36jR9pCSxtqo/uEiAz447DyfUm/kJ5lF7@MAWzElajk5RieSpm4yRkHk6rJQh2iKcy1VhtNUouAJ6lrK7oqij6gnlNpxVC@hXZFxvcv "Python 2 – TIO Nexus") [Answer] # [Röda](https://github.com/fergusq/roda), 51 bytes ``` f a{x=0;a|{|y|a[x]=a[x+47-ord(y)]if[y=~`\d`];x++}_} ``` [Try it online!](https://tio.run/nexus/roda#HY69bsIwGEXn@ClcBgqKivyXOBRl6tCOqKrUgUblSxwTq4mNHCMRAn11GnW5uvec5d41hvGckw1cx@twhd25yKeIhXxyXi2GZWH0bsh/919qX2zOcXz7vt07MBaPKNLOY2OPp4CVQ1HUB4@fc7yrGvD94l8si4nrxWSWUzl6YwOexnw2Q5Fytka3O5SVQkAIQSVYSil6q1vi8CfziXpAoTE9ZowBXdcJQwfXamMTzHsmHFFCc88HfkJb7w4MOmJsirenC2nrXs7pi1NSvIpWo/f62JoKbOix8DVvzY8QmR24C03mkw6q1NhslX2kYnj0XFIT1lymQMvEUm2CdH560LALlWr1Bw "Röda – TIO Nexus") [Answer] # JavaScript ES6, 54 bytes ``` f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s)) ``` ``` f=r=>[...r].reduce((a,s,i)=>a+(/\d/.test(s)?a[i+~s]:s)) console.log(f("Prog2am0in6")); console.log(f("abcd")); console.log(f("a000")); console.log(f("ban111")); console.log(f("Hel0o W2r5d!")); console.log(f("this 222a19e52")); console.log(f("golfin5 3s24o0d4f3r3y3u")); console.log(f("Prog2am0in6 Puz0les7&1Cod74G4lf")); console.log(f("Replicants 4re3lik448ny3oth8r5mac6in8.8T64y'r371it9376a1b5n1fit7or2a1h2z17d.")); ``` [Answer] # ><> (Fish), 108 bytes (= 9 x 12 grid) ``` 01-r>:0(\ "/"&::;?/ )?\v \ ":/v!?(": ")\ :>:"0 !?\ ${/ \ -1 &>\ ~{:&$ \ \ :"0"= /\- 1}$/? :v&//}~/~ \o}\&$/ ``` Try it [here](https://fishlanguage.com/playground) to see the fish swimming around. * Append -1 to the input stack then reverse the stack. * Loop: If top value is -1 then end (we've cycled through all characters). Otherwise: * Put the top character in the register; check to see whether it's in the range "0" to "9". If so: + rotate the stack the appropriate number of places + get the character being pointed to + rotate back and replace the number with the character from the register * Output; resume loop. [Answer] # 8086 machine code, 35 bytes ``` 00000000 be 82 00 ac 98 50 2c 30 3c 09 77 0c 4e 89 f7 4e |.....P,0<.w.N..N| 00000010 29 c6 58 ac aa 89 fe 50 5a b4 02 cd 21 80 fa 0d |).X....PZ...!...| 00000020 75 e1 c3 |u..| 00000023 ``` [Answer] # oK, 39 bytes ``` {x{x[y 0]:x@-/y}/(!#x),'0|{x*11>x}x-47} ``` [Try it online!](https://tio.run/nexus/k-ok#DY49T8MwGIT/ihsk2iLa@PVHnAYJVWKAsUJIDIjBiePGwrWRk0pOQ3578HR3z91wi66mOMWvEeHvKh53@Tjnm9Vd3D6u8d8UHwCe4xx3TMyLPubVJpN1o7KnTGKMk9TSAUAyb63FHn2SwNUqxaEzPSKESDi0nCRw9lYbxxHtCfNYMU0DHek1Nafgz0ResHEFOl1v2La9uIcXrwR7ZVanxXv7a00j3dAjFlpqzQ9jpRupH7oy8ItsCuPKfflRsHEdqAAzHKgoJNTcgTaD8CH96MgNhNpn2@Uf) [Answer] # [Japt](https://ethproductions.github.io/japt/) v2.0a0, 16 bytes ``` r\d@=hYUgY-°X¹gY ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=clxkQD1oWVVnWS2wWLlnWQ==&input=IlJlcGxpY2FudHMgNHJlM2xpazQ0OG55M290aDhyNW1hYzZpbjguOFQ2NHkncjM3MWl0OTM3NmExYjVuMWZpdDdvcjJhMWgyejE3ZC4i) --- ## Explanation ``` :Implicit input of string U r :Replace \d : RegEx /\d/g @ : Pass each match X at index Y through a function hY : Set the character at index Y in U UgY-°X : To the character at index Y-++X = ¹ : Reassign to U gY : Get the character at index Y ``` [Answer] # [J](http://jsoftware.com/), 20 bytes ``` {~[:{~^:_#\-2+_1".,. ``` [Try it online](https://tio.run/##Dc7LSgMxFADQfb4iKtSFNeTmMZkWdCOoCxdFCi6UlkwenWiaSCazmBb666PnC873PPsHgs@Xz/X5slvvb77u2d0ersmSzM70GfvFIzZjfXvGQ7UhYZh1ZyzSlFLU6QQA6NVFmvEHK9JeodqHATPGNKycZOiQow9JYj4wkakVnhc@8RFtSj4wfaQhNXgznmh0g1rAU7ZKvIjo0bv7jcHoVAcsiuMx/AjRponn2rdFHrVpQmpJu23EdFu4glBXXDUaOpnAh6py@R/07ATKkj8) ``` ,. Each character on a separate row _1". Convert to numbers, replacing non-numbers with -1 (it becomes one row again) 2+ Add 2. #\ Prefix lengths (range 1..length) - Subtract [:{~^:_ Index into itself as long as it changes the result {~ Index into the original string ``` [Credit to ngn for the inspiration.](https://codegolf.stackexchange.com/a/115924/74681) ### 22 bytes ``` (],,{~1{._1-_1".[)/@|. ``` This is a port of the Jelly answer. ``` |. The string backwards, because reduce is right-to-left. _1".[ The next character as a number (d), -1 if it's not a number, and a space character produces an empty array. _1- -1-d 1{. Take 1. If we have a nothing at this point, that makes it a 0. , Prepend the next character to the result of the previous call. {~ Select the character. 0 is the first, _2 is second to last. ], Append the result. ``` In both solutions the version that TIO uses interprets a single `.` as the number 0, so the last test fails. Older versions (≤7) seem to work correctly. [Try it online!](https://tio.run/##Dc7LSgMxFADQfb4idlEVaszNYzJdKIKgLlyUIriQUjJ5dKJpIpnMYlrx10fPF5zPefZ3BF/tVqvzL5zJHm72sCAf17cPP2R2ps/YL@@xGevrEx6qDQnDrDtjkaaUok4nAEAvLtKM31mR9gLVPgyYMaZh7SRDhxx9SBLzgYlMrfC88ImPaFPygekjDanBm/FEoxvUEh6zVeJZRI@27jsGo1MdsCiOx/AlRJsmnmvfFnnUpgmpJe1bI6bLwhWEuuaq0dDJBD5Ulcv/oGcnUJb8AQ "J – Try It Online") ]
[Question] [ Given an image that has only black and white pixels and an (x,y) location that's a white pixel, color the white pixels based on their minimal [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) from (x,y) in a path that only involves traversing other white pixels. The [hue](https://en.wikipedia.org/wiki/Hue) of the colored pixels must be proportional to their distance from (x,y), so the pixel at (x,y) will have a hue of 0° (pure red) and the pixels farthest away from (x,y) will have a hue of 360° (also red), with the other hues blending seamlessly and linearly in between. The [saturation and value](https://en.wikipedia.org/wiki/HSL_and_HSV) must both be 100%. If a white pixel is not [connected](https://en.wikipedia.org/wiki/Connected_space) to (x,y) through other white pixels then it must remain white. ## Details * The input will consist of the file name of the image or the raw image data, plus the x and y integers. * The output image may be saved to a file or piped raw to stdout in any common image file format, or simply displayed. * The x value is 0 on the leftmost pixels, and increases going right. The y value is 0 in the topmost pixels and increases going down. (x,y) will always be in the image bounds. * Both full programs and functions are allowed. **The shortest code in bytes wins.** ## Examples ***All these images have been downsized to save space. Click them to view at full size.*** Input image: [![example 1 input](https://i.stack.imgur.com/qWUeMm.png)](https://i.stack.imgur.com/qWUeM.png) `(x,y) = (165,155)` and `(x,y) = (0,0)` [![example 1 output A](https://i.stack.imgur.com/uN8b5m.png)](https://i.stack.imgur.com/uN8b5.png) [![example 1 output B](https://i.stack.imgur.com/XPAPHm.png)](https://i.stack.imgur.com/XPAPH.png) --- Input image and output with `(x,y) = (0,0)`: [![example 5 input](https://i.stack.imgur.com/yabFom.png)](https://i.stack.imgur.com/yabFo.png) [![example 5 input A](https://i.stack.imgur.com/dxEYwm.png)](https://i.stack.imgur.com/dxEYw.png) --- Input image and output with `(x,y) = (600,350)`: [![example 2 input](https://i.stack.imgur.com/qyT4Xm.png)](https://i.stack.imgur.com/qyT4X.png) [![example 2 output](https://i.stack.imgur.com/9MHJ4m.png)](https://i.stack.imgur.com/9MHJ4.png) --- Input image and output with `(x,y) = (0,0)`: [![example 3 input](https://i.stack.imgur.com/6YQBym.png)](https://i.stack.imgur.com/6YQBy.png) [![example 3 output](https://i.stack.imgur.com/fvKKwm.png)](https://i.stack.imgur.com/fvKKw.png) --- Input image and output with `(x,y) = (0,0)`: [![example 4 input](https://i.stack.imgur.com/NTzYmm.png)](https://i.stack.imgur.com/NTzYm.png) [![example 4 output](https://i.stack.imgur.com/HlqRA.jpg)](https://i.stack.imgur.com/F9vjc.png) --- **Optional -30% bonus:** use Euclidean distance. A suggestion for your algorithm is as follows (general outline): 1. Have a start pixel. 2. Flood-fill from that pixel. 3. For every pixel reached in the flood fill, 4. Move from the start pixel to that pixel in half-unit steps, in a straight line. 5. At each step, apply `int()` to the x and y coordinates. If the pixel at these coordinates is black, stop. Otherwise, continue. (This is a line-of-sight method.) 6. Any reached pixel that borders a white pixel and/or a pixel that was previously labeled with a significantly higher distance (i.e., +10) becomes a start pixel. In a more meta sense, this algorithm spreads out to every pixel reachable in a straight line from start/already-colored pixels, then "inches" around edges. The "significantly higher distance" bit is intended to speed up the algorithm. Honestly, it doesn't really matter *how* you implement Euclidean distance, it just has to look pretty much like this. This is what the first example looks like with Euclidean distance, using the algorithm above: Input image and `(x,y) = (165,155)` [![example 1 input](https://i.stack.imgur.com/qWUeMm.png)](https://i.stack.imgur.com/qWUeM.png) [![enter image description here](https://i.stack.imgur.com/IrJDVm.png)](https://i.stack.imgur.com/Cwp84.png) --- **Many thanks to Calvin'sHobbies and trichoplax for helping write this challenge! Have fun!** [Answer] # Matlab, ~~255 245~~ 231 bytes This expects the image name first, then `y` and then `x`. ``` I=@input;i=imread(I('','s'));[r,c]=size(i);m=zeros(r,c);m(I(''),I(''))=1;M=m;d=m;K=[1,2,1];for k=1:r*c;d(m&~M)=k;M=m;m=~~conv2(m,K'*K>1,'s');m(~i)=0;end;z=max(d(:));v=[1,1,3];imshow(ind2rgb(d,hsv(z)).*repmat(m,v)+repmat(~d&i,v),[]) ``` I implemented the flood filling (or 'dijkstra for 4-neighbourhoods' if you want) roughly by first creating a mask where the seed pixel is set to 1 and with a distance accumulator (both of the size of the image) and then repeating following steps: * convolute the mask with a 4 neighbourhood kernel (this is the very inefficient part) * set all nonzero pixels of the mask to 1 * set all the black pixels of the image to zero * set all values in the accumulator where the mask has changed in this step to `k` * increase `k` * repeat until there are no more changes in the mask (I actually do not check this condition, but just use the number of pixels in the image as an upper bound, which is usually a very bad upper bound, but this is codegolf=) This leaves us with the manhattan distances of every pixel to the seed pixel in the distance accumulator. Then we create a new image by going throu the given range of colours and map the "first" hue to the value zero and the "last" hue to the maximal distance. # Examples [![enter image description here](https://i.stack.imgur.com/v9qFz.png)](https://i.stack.imgur.com/v9qFz.png) [![enter image description here](https://i.stack.imgur.com/uPXJF.png)](https://i.stack.imgur.com/uPXJF.png) [![enter image description here](https://i.stack.imgur.com/aS6z5.png)](https://i.stack.imgur.com/aS6z5.png) [![enter image description here](https://i.stack.imgur.com/C2Sj7.png)](https://i.stack.imgur.com/C2Sj7.png) As a bonus, here a pretty picture of how the distance gets calculated. brighter = farther away. [![enter image description here](https://i.stack.imgur.com/ijhoM.gif)](https://i.stack.imgur.com/ijhoM.gif) [Answer] ## [Blitz 2D/3D](http://www.blitzbasic.com/Products/blitz3d.php), 3068 \* 0.7 = 2147.6 This is the reference implementation for the Euclidean algorithm, golfed. ``` image=LoadImage("HueEverywhere_example1.png") Graphics ImageWidth(image),ImageHeight(image) image=LoadImage("HueEverywhere_example1.png") x=0 y=0 w=ImageWidth(image) h=ImageHeight(image) Type start Field x,y Field dis# Field nex.start End Type Type cell Field x,y Field dis# End Type Type oldCell Field x,y Field dis# End Type initCell.start=New start initCell\x=x initCell\y=y initCell\dis=1 Dim array#(w,h) imgBuff=ImageBuffer(image) LockBuffer(imgBuff) s.start=First start colr=col(0,0,0) colg=col(0,0,1) colb=col(0,0,2) newcol=colr*256*256+colg*256+colb WritePixelFast(s\x,s\y,newcol,imgBuff) While s<>Null c.cell=New cell c\x=s\x c\y=s\y c\dis=s\dis While c<>Null For dy=-1To 1 For dx=-1To 1 If dx*dy=0And dx+dy<>0 nx=c\x+dx ny=c\y+dy ndis#=s\dis+Sqr#((nx-s\x)*(nx-s\x)+(ny-s\y)*(ny-s\y)) If nx >= 0And nx<w And ny >= 0And ny<h If KeyHit(1)End pixcol=ReadPixelFast(nx,ny,imgBuff) If pixcol<>-16777216 If array(nx,ny)=0Or ndis<array(nx,ny) check=1 steps=Ceil(dis)*2 For k=0 To steps r#=k*1./steps offx#=Int(s\x+(c\x-s\x)*r) offy#=Int(s\y+(c\y-s\y)*r) pixcol2=ReadPixelFast(offx,offy,imgBuff) If pixcol2=-16777216 check=0 Exit EndIf Next If check array(nx,ny)=ndis newCell.cell=New cell newCell\x=nx newCell\y=ny newCell\dis=ndis EndIf EndIf EndIf EndIf EndIf Next Next o.oldCell=New oldCell o\x=c\x o\y=c\y o\dis=c\dis Delete c c=First cell Wend For o.oldCell=Each oldCell bordersWhite=0 For dy=-1To 1 For dx=-1To 1 If dx<>0Or dy<>0 nx=o\x+dx ny=o\y+dy If nx>=0And nx<w And ny>=0And ny<h pixcol=ReadPixelFast(nx,ny,imgBuff) If (pixcol=-1And array(nx,ny)=0)Or array(nx,ny)>o\dis+9 bordersWhite=1 Exit EndIf EndIf EndIf Next If bordersWhite Exit Next If bordersWhite ns.start=New start ns\x=o\x ns\y=o\y ns\dis=o\dis s2.start=First start While s2\nex<>Null If ns\dis<s2\nex\dis Exit EndIf s2=s2\nex Wend ns\nex=s2\nex s2\nex=ns EndIf Delete o Next EndIf s2=s s=s\nex Delete s2 Wend maxDis=0 For j=0To h For i=0To w If array(i,j)>maxDis maxDis=array(i,j) Next Next For j=0To h For i=0To w dis2#=array(i,j)*360./maxDis If array(i,j) <> 0 colr=col(dis2,0,0) colg=col(dis2,0,1) colb=col(dis2,0,2) newcol=colr*256*256+colg*256+colb WritePixelFast(i,j,newcol,imgBuff) EndIf Next Next UnlockBuffer(imgBuff) DrawImage image,0,0 Function col(ang1#,ang2#,kind) While ang1>360 ang1=ang1-360 Wend While ang1<0 ang1=ang1+360 Wend While ang2>180 ang2=ang2-360 Wend While ang2<-180 ang2=ang2+360 Wend a3#=ang2/180. If ang1>300 diff#=(ang1-300)/60. r=255 g=0 b=255*(1-diff) ElseIf ang1>240 diff#=(ang1-240)/60. r=255*diff g=0 b=255 ElseIf ang1>180 diff#=(ang1-180)/60. r=0 g=255*(1-diff) b=255 ElseIf ang1>120 diff#=(ang1-120)/60. r=0 g=255 b=255*diff ElseIf ang1>60 diff#=(ang1-60)/60. r=255*(1-diff) g=255 b=0 Else diff#=(ang1-00)/60. r=255 g=255*diff b=0 EndIf If a3>0 r2=r+a3*(255-r) g2=g+a3*(255-g) b2=b+a3*(255-b) Else r2=r+a3*r g2=g+a3*g b2=b+a3*b EndIf If r2>255 r2=255 ElseIf r2<0 r2=0 EndIf If g2>255 g2=255 ElseIf g2<0 g2=0 EndIf If b2>255 b2=255 ElseIf b2<0 b2=0 EndIf If kind=0 Return r2 ElseIf kind=1 Return g2 ElseIf kind=2 Return b2 Else Return 0 EndIf End Function ``` Actually, I kinda hate how unreadable this is compared to the original. (Which is, incidentally, 5305 bytes.) Actually, I could lop off quite a few more bytes by using one-character variable names for everything, but this is kinda ridiculous enough already. And it's not winning any time soon. :P [Answer] ## C++ / SFML : ~~1271~~ ~~1235~~ 1226 bytes -36 bytes thanks to user202729 -9 bytes thanks to Zacharý ``` #include<SFML\Graphics.hpp> #include<iostream> #define V std::vector #define P e.push_back #define G(d,a,b,c) case d:return C(a,b,c); #define FI(r,s)(std::find_if(e.begin(),e.end(),[&a](const T&b){return b==T{a.x+(r),a.y+(s),0};})!=e.end()) using namespace sf;using C=Color;struct T{int x,y,c;bool operator==(const T&a)const{return x==a.x&&y==a.y;}};int max(V<V<int>>&v){int m=INT_MIN;for(auto&a:v)for(auto&b:a)m=b>m?b:m;return m;}C hsv2rgb(int t){int ti=t/60%6;float f=t/60.f-ti,m=(1.f-f)*255,n=f*255;switch(ti){G(0,255,n,0)G(1,m,255,0)G(2,0,255,n)G(3,0,m,255)G(4,n,0,255)G(5,255,0,m)default:throw std::exception();}}void r(Image&a,int x,int y){auto d=a.getSize();V<V<int>>m(d.x,V<int>(d.y));int i=0,j,c=0,t;for(;i<d.y;++i)for(j=0;j<d.x;++j)m[j][i]=a.getPixel(j,i)==C::Black?-1:0;V<T>e{{x,y,1}};while(e.size()){V<T>t=std::move(e);for(auto&a:t){m[a.x][a.y]=a.c;if(a.x>0&&m[a.x-1][a.y]==0&&!FI(-1,0))P({a.x-1,a.y,a.c+1});if(a.y>0&&m[a.x][a.y-1]==0&&!FI(0,-1))P({a.x,a.y-1,a.c+1});if(a.x<m.size()-1&&m[a.x+1][a.y]==0&&!FI(1,0))P({a.x+1,a.y,a.c+1});if(a.y<m[0].size()-1&&m[a.x][a.y+1]==0&&!FI(0,1))P({a.x,a.y+1,a.c+1});}}c=max(m)-1;for(i=0,j;i<d.y;++i)for(j=0;j<d.x;++j)if(m[j][i]>0)a.setPixel(j,i,hsv2rgb(360.f*(m[j][i]-1)/c));} ``` The `sf::Image` parameter is also the output ( will be modified ). You can use it like that : ``` sf::Image img; if (!img.loadFromFile(image_filename)) return -1; r(img, 0, 0); if (!img.saveToFile(a_new_image_filename)) return -2; ``` The first parameter is the image input ( and output ), the second and third parameters are the `x` and `y` parameter where it needs to start [Answer] # Matlab with [DIPimage](https://diplib.org), 118 bytes - 30% = 82.6 ``` function F(f,x,y),a=readim(f);m=a{1}>0;s=m|1;s(x,y)=0;h=gdt(s,[],m);n=~isinf(h);a(n)=lut(h(n),255*hsv(fix(max(h(n))))) ``` DIPimage has a function to compute Euclidean geodesic distance transform (`gdt`). It uses the Fast Marching algorithm, which produces a very reasonable approximation to Euclidean distances. See [the docs](http://diplib.org/diplib-docs/group__distance.html#ga1986c2ee6b30efa387b3d7b22e4d4922). DIPimage automatically displays the image I'm using the idea from [flawr's answer](https://codegolf.stackexchange.com/a/64337/91877) to create a colormap using `hsv`. [![output of code above for one of the test images](https://i.stack.imgur.com/QPIKT.png)](https://i.stack.imgur.com/QPIKT.png) [Answer] # C++, 979 969 898 859 848 bytes ``` #include<cstdio> #include<cstdlib> #define K 400 #define L 400 #define M (i*)malloc(sizeof(i)) #define a(C,X,Y)if(C&&b[Y][X].c){t->n=M;t=t->n;b[Y][X].d=d+1;t->n=0;t->c=X;t->d=Y;} #define A(n,d)case n:d;break; #define F fgetc(f) #define W(A,B) for(A=0;A<B;A++){ struct i{int c;int d;int v;i*n;}b[L][K]={0},*h,*t;float m=0;int main(){FILE*f=fopen("d","r+b");int x,y,d=0;W(y,L)W(x,K)b[y][x].c=F<<16|F<<8|F;}}rewind(f);x=165,y=155;h=M;h->c=x;h->d=y;b[y][x].d=d;t=h;while(h){i*p=b[h->d]+h->c;if(p->v)h=h->n;else{p->v=1;x=h->c;y=h->d;d=p->d;m=d>m?d:m;a(x>0,x-1,y)a(x<K-1,x+1,y)a(y>0,x,y-1)a(y<L-1,x,y+1)}}W(y,L)W(x,K)i p=b[y][x];unsigned char n=-1,h=p.d/(m/n),R=h%43*6,Q=n*(n-(n*R>>8))>>8,t=n*(n-(n*(n-R)>>8))>>8,r,g,b;switch(h/43){A(0,n,t,0)A(1,Q,n,0)A(2,0,n,t)A(3,0,Q,n)A(4,t,0,n)A(5,n,0,Q)}d=h?r|g<<8|b<<16:p.c?-1:0;fwrite(&d,1,3,f);}}} ``` * Input: RGB data file (contained in file: d) * Output: RGBA RGB data file (outputted in file: d) * Example: convert -depth 8 -size "400x400" test.png d.rgb && mv -f d.rgb d && g++ -o test main.c && ./test * NOTE: the image size and start are controlled at a source level, if this is an issue add 50 bytes or something -- I just didn't care to change it to be honest. Not exactly a direct "ungolf" but this was a C prototype I mocked up first: ``` #include "stdio.h" #include "stdlib.h" struct i{ unsigned int c; int d; int v; }b[400][400]={0}; typedef struct q{ int x; int y; struct q *n; }q; q *qu; q *t; float m=0; int get_dist(int x, int y) { int d = 0; } void flood(int x,int y,int d){ qu=malloc(sizeof(q)); qu->x=x;qu->y=y;b[y][x].d=d; t=qu; while(qu){ struct i *p = &b[qu->y][qu->x]; if(p->v){qu=qu->n; continue;} p->v=1;x=qu->x;y=qu->y;d=p->d; #define a(C,X,Y) if(C&&b[Y][X].c){t->n=malloc(sizeof(q));t=t->n;b[Y][X].d=d+1;t->n=0;t->x=X;t->y=Y;} a(x>0,x-1,y); a(x<399,x+1,y); a(y>0,x,y-1); a(y<399,x,y+1); m=p->d>m?p->d:m; } } unsigned int C(int h) { int r=0,g=0,b=0; int s=255,v=255; unsigned char R, qq, t; R = h%43*6; qq = (v * (255 - ((s * R) >> 8))) >> 8; t = (v * (255 - ((s * (255 - R)) >> 8))) >> 8; switch (h / 43){ case 0: r = v; g = t; break; case 1: r = qq; g = v; break; case 2: g = v; b = t; break; case 3: g = qq; b = v; break; case 4: r = t; b = v; break; case 5: r = v; b = qq; break; } return r|(g<<8)|(b<<16)|255<<24; } #define F fgetc(f) int main() { FILE *f=fopen("d", "r+b"); for(int y=0; y<400; y++){ for(int x=0; x<400; x++){ b[y][x].c = (F<<24)|(F<<16)|(F<<8); } } rewind(f); flood(165,155,1); m/=255.f; for(int y=0; y<400; y++){ for(int x=0; x<400; x++){ struct i p = b[y][x]; unsigned int h = C(p.d/m); int o = p.c?-1:255<<24; if(p.d)fwrite(&h,4,1,f); else fwrite(&o,4,1,f); } } } ``` Many concepts remain similar, but there are certainly a myriad of tiny changes. To compile that as C you do need to use C11 (C99 will probably work but I only strictly tested in C11). I quite enjoyed this challenge, thanks for giving me the idea to try something new :). Edit: Golf'd a bit better. Edit2: Merged two structs so my pixel struct and queue are the same, bit more macro abuse, and reflowed uses of 255 such that it can be defined as -1 when defining a series of unsigned chars, and lastly removed a function call. Edit3: Reused a few more variables, operator precedence tweaks, and output converted to RGB saving the alpha channel Edit4: I think I am done with this now, some pointer arithmetic changes and slight control flow tweaks. [Answer] # Python 3 and matplotlib, ~~251~~ 227 bytes ``` from pylab import* def f(i,p): h,w,_=i.shape;o=ones((h,w))/0;q=[p+[0]] while q: x,y,d=q.pop(0) if w>x>=0and h>y>=0and i[y,x,0]:o[y,x]=d;i[y,x]=0;d+=1;q+=[[x-1,y,d],[x+1,y,d],[x,y-1,d],[x,y+1,d]] imshow(i);imshow(o,'hsv') ``` The input is an MxNx3 numpy array as returned by matplotlib's `imread()` function. The input is modified by the function so it should be copied beforehand. It displays the image automatically if matplotlib is in "interactive" mode; otherwise a call to `show()` should be added for another 7 bytes. The output is created by first displaying the original image and then displaying the rainbow image overtop of it. Matplotlib conveniently treats inf and nan as transparent so the black and white image shows through. ]
[Question] [ You probably know *Conway's Game of Life*, the famous cellular automaton invented by mathematician John Conway. *Life* is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and which ones die. With some imagination, you could say that *Life* is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider. ![Glider](https://upload.wikimedia.org/wikipedia/commons/f/f2/Game_of_life_animated_glider.gif) A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 10000 generations. ## Game rules The rules are *almost* the same as normal (B3/S23) Life: * A live cell with fewer than two friendly neighbors dies from starvation. * A live cell with two or three friendly neighbors survives. * A live cell with more than three friendly neighbors dies from overpopulation. * A dead cell with exactly three neighbors of the same player comes alive to fight for that player *provided there are no enemy neighbors*. ...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.) The board is a (x,y) cells square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead. This is is a contest in the spirit of *Battlebots* and *Core Wars*. There is a central server that will run bots and it can be found [here](https://github.com/muddyfish/PPCG-Life) ## Protocol The arena server speaks a simple JSON protocol communicated through argv Where Values is a JSON encoded string * `y_size`: the maximum y coords of tiles before they vanish * `x_size`: the maximum x coords of tiles before they vanish * `tick_id`: the current tick number * `board`: a dictionary with keys in the form '(y,x)' and values in the form `bot_id` (int) * `bot_id`: tiles in the board with this id are yours Example: ``` {"y_size":2000,"x_size":2000,"board":{},"bot_id":1,"tick_id":1} ``` Telling the server your choice: * Send the server a list of tiles to turn to your colour. * Only those that are empty will be changed * Nested coords list format + `[[0,0], [0,1], [100,22]...]` NOTE: Your bot doesn't have to update the tiles at all - the server does the updating itself ## Competition rules * If your implementation fails to follow the protocol, the turn it does will be forfeited; The server will assume no change in state * You are not allowed to willfully take advantage of a fault in the arena server. * Have your AI decide on moves in a sane time. Please send your next move as fast as reasonably possible. * Finally, please be nice to the server. It's there for your enjoyment. * Not following these rules can lead to disqualification. * In the event of a tie, both players have 1 win added to their total ## Running the controller yourself The source for the controller can be found [here](https://github.com/muddyfish/PPCG-Life). There are 2 ways of running the controller: * Competition mode (terminal) + Setup with `python3 get_answers.py` + Run an all v all competition with each bot pitting it against every other. * Testing mode (GUI) + Run `python3 nice_gui.py` + Click `Pull Answers` + If you want to add your own answer to try it before posting, click `File -> Add manual answer` and find the file and choose the language it's written in. + If your language isn't present ping me and I'll try to get it installed on the server I will run it on (installation and running instructions would be nice too!) + Choose 2 bots to pit against each other + Click `Run` + Watch the game... * Installation + Requires python3 + get\_answers requires bs4 and html5lib + controller requires a way of running .sh files (MinGW on windows) [![Example image of app](https://i.stack.imgur.com/oHQPv.png)](https://i.stack.imgur.com/oHQPv.png) ## Scoring The bot with the most wins starting from ~~`12/07/2016` (12th July)~~ `14/07/2016` (14th July, couldn't work out how to run a bot) wins. --- ### Help with the controller/gui can be asked in [this chat room](http://chat.stackexchange.com/rooms/41885/discussion-between-fawful-and-kevin-lau-not-kenny) --- This question has been in development since 2014 and was the most upvoted question in the sandbox. Special Thanks goes to [Wander Nauta](https://codegolf.meta.stackexchange.com/users/19075/wander-nauta) (original author and concept), [PPCG Chat](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte) (comments and help) and anyone who commented in the [sandbox post](https://codegolf.meta.stackexchange.com/a/1332/32686) (more comments). [Answer] # Ruby, InterruptingBlockMaker Instead of initializing gliders like the TrainingBot, it tries to create a [5x5 block-making switch machine as mentioned on Wikipedia](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Examples_of_patterns) at a random point in the maze. Then, with its remaining activations, it just finds enemy points and tries to pepper the nearby area with your cells in an attempt to interrupt them from growing and possibly messing up their patterns. Your cells will die in the next generation, but maybe they also stopped some growth to slow down your opponent! v2: Optimized slightly (?) to try to minimize timeouts. v3: Optimized interruption code to pre-sample a subset of active blocks before rejecting our own cell locations, to prevent timeouts further at the cost of some effectiveness in the interrupt cell attacks. ``` require 'json' class Range def product range2 self.to_a.product range2.to_a end end args = JSON.parse(ARGV[0]) bot_id = args["bot_id"] width = args["x_size"] height = args["y_size"] board = args["board"] generator = [[2,2], [2,3], [2,6], [3,2], [3,5], [4,2], [4,5], [4,6], [5,4], [6,2], [6,4], [6,5], [6,6]] targets = [] iterations = 50 gen_location = nil while !gen_location && iterations > 0 y = rand height - 9 x = rand width - 9 temp = (0...9).product(0...9).map{|_y, _x| [y + _y, x + _x]} if temp.all?{|_y,_x| !board["(#{y},#{x})"]} gen_location = temp targets += generator.map{|_y, _x| [y + _y, x + _x]} end iterations -= 1 end enemies = board.keys.sample(100).reject {|k| board[k] == bot_id} interrupts = [] enemies.each do |location| y, x = location.scan(/\d+/).map &:to_i interrupts |= ((y-1)..(y+1)).product((x-1)..(x+1)).reject{|y, x| gen_location.include?([y,x]) || board["(#{y},#{x})"]} end targets += interrupts.sample(30 - targets.size) puts JSON.dump(targets) ``` [Answer] ## Python 3, Exploder Puts small exploders around the place, with no regard to whether there is already a block there. ``` from random import randint import sys,json,copy q=json.loads(sys.argv[1]) x=q["x_size"];y=q["y_size"];F=[[0,1],[1,0],[1,1],[1,2],[2,0],[2,2]];D=[] for g in [0]*5: X=randint(0,x);Y=randint(0,y);A=copy.deepcopy(F) for C in A:C[0]+=Y;C[1]+=X D+=A print(D) ``` [Answer] ## Python 2, TrainingBot Because everyone needs one of these! ``` import random, copy import sys, json args = json.loads(sys.argv[1]) bot_id = args["bot_id"] x_size = args["x_size"] y_size = args["y_size"] cur_tick = args["tick_id"] board = args["board"] glider = [[1,2],[2,1],[0,0],[0,1],[0,2]] x_add = random.randrange(x_size) y_add = random.randrange(y_size) new_glider = copy.deepcopy(glider) for coord in new_glider: coord[0]+=y_add coord[1]+=x_add move = new_glider print json.dumps(move) ``` [Answer] # Java, Troll Bot Troll Bot has thought about it, and he realizes he does NOT care about the enemy. In fact he just spams these factories to produce more of his guys randomly all over the map. After a while he realized that any additional cells are best used in clumps. These blocks of four cells will stick together and stop gliders in their tracks! He does not think he just fights. Also he is a big supporter of verbose object oriented programming. The troll also assumes that coords are in the format y,x, and he is asking to be tested. Just put him in a file called "TrollBot.java", and he'll be set! ``` package trollbot; /** * * @author Rohans */ public class TrollBot{ public static class coord{ public int x; public int y; public coord(int inX,int inY){ x = inX; y = inY; } @Override public String toString(){ return"["+x+","+y+"]"; } } /** * Input the JSON as the first cla * @param args the command line arguments */ public static void main(String[] args) { String JSON="{\"bot_id\":1,\"y_size\":1000,\"x_size\":1000,\"board\":{}}"; String[] JArray=args[0].split(","); int botId=Integer.parseInt(JSON.charAt(10)+""); int xSize=Integer.parseInt(JArray[2].substring(JArray[2].indexOf(":")+1)); int ySize=Integer.parseInt(JArray[1].substring(JArray[1].indexOf(":")+1)); int[][] board = new int[xSize][ySize];//0 indexed //todo: parse the board to get an idea of state String soldiers="["; //for now just ignore whats on the board and put some troll cells on //Attempts to create 3 10 cells factories of cells, hoping it does not place it on top of allies //Then puts random 2/2 blocks boolean[][] blockspam=new boolean[10][8]; blockspam[7][1]=true; blockspam[5][2]=true; blockspam[7][2]=true; blockspam[8][2]=true; blockspam[5][3]=true; blockspam[7][3]=true; blockspam[5][4]=true; blockspam[3][5]=true; blockspam[1][6]=true; blockspam[3][6]=true; for(int z=0;z<3;z++){ int xOffSet=(int) (Math.random()*(xSize-11)); int yOffSet=(int) (Math.random()*(ySize-9)); //stay away from edges to avoid odd interactions for(int i=0;i<blockspam.length;i++){ for(int j=0;j<blockspam[i].length;j++){ if(blockspam[i][j]) soldiers+=new coord(j+yOffSet,i+xOffSet).toString()+","; } } } soldiers=soldiers.substring(0,soldiers.length()-1); for(int i=0;i<8;i++){ int y=(int ) (Math.random()*(ySize-1)); int x = (int) (Math.random()*(xSize-1)); soldiers+=new coord(y,x).toString()+","; soldiers+=new coord(y+1,x).toString()+","; soldiers+=new coord(y,x+1).toString()+","; soldiers+=new coord(y+1,x).toString()+","; } soldiers+="\b]"; System.out.println(soldiers); //GO GO GO! Lets rule the board } } ``` [Answer] # Python 3, RandomBot This bot has trouble making intelligent decisions, but it at least knows not to try to place things on top of other things. It'll randomly create gliders, boats, [C/2 Orthagonal](http://www.conwaylife.com/wiki/C/2_orthogonal)s, and 2x2 blocks with various orientations, ensuring that when they're placed they're not overlapping with something else, ally or enemy. This bot wasn't tested, seeing as I'm receiving all sorts of errors when I try to run the GUI. Also, I used the TrainingBot as the base and just edit, so any similarities in code is probably because of that. ``` import random, copy import sys, json args = json.loads(sys.argv[1]) bot_id = args["bot_id"] x_size = args["x_size"] y_size = args["y_size"] board = args["board"] occupied = [tuple(key) for key,value in iter(board.items())] cellsleft=30 move=[] choices = [[[1,2],[2,1],[0,0],[0,1],[0,2]], [[0,0],[0,1],[1,1],[1,0]], [[0,1],[1,0],[0,2],[0,3],[1,3],[2,3],[3,3],[4,3],[5,2],[5,0]], [[0,0],[1,0],[0,1],[2,1],[2,2]]] while cellsleft>0: x_add = random.randrange(x_size) y_add = random.randrange(y_size) new_glider = copy.deepcopy(random.choice(choices)) randomdirection = random.choice([[1,1],[1,-1],[-1,1],[-1,-1]]) maxy=max([y[0] for y in new_glider]) maxx=max([x[1] for x in new_glider]) for coord in new_glider: coord[0]=coord[0]*randomdirection[0]+y_add coord[1]=coord[1]*randomdirection[1]+x_add cellsleft-=1 set([tuple(x) for x in new_glider]) if not set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])) and cellsleft>0: if min(y[0] for y in new_glider)<0: new_glider = [[y[0]+maxy,y[1]] for y in new_glider] if min(y[1] for y in new_glider)<0: new_glider = [[y[0],y[1]+maxx] for y in new_glider] move += new_glider elif set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])): cellsleft+=len(new_glider) print(json.dumps(move)) ``` [Answer] ## Python, GuyWithAGun He's a guy, he's got a gun; he's mad. He just dumps glider guns everywhere with no regard to what anyone else is doing ``` import random, copy import sys, json args = json.loads(sys.argv[1]) bot_id = args["bot_id"] x_size = args["x_size"] y_size = args["y_size"] tick_id = args["tick_id"] board = args["board"] start_squares = [[0,5],[2,5],[1,6],[2,6], [35,3],[36,3],[35,4],[36,4]] gun = [[11,5],[11,6],[11,7], [12,4],[12,8], [13,3],[13,9], [14,3],[14,9], [15,6], [16,4],[16,8], [17,5],[17,6],[17,7], [18,6], [21,3],[21,4],[21,5], [22,3],[22,4],[22,5], [23,2],[23,6], [25,1],[25,2],[25,6],[25,7]] templates = [start_squares, gun] def add_squares(pos, coords): new_squares = copy.deepcopy(coords) for coord in new_squares: coord[0]+=pos[0] coord[1]+=pos[1] return new_squares def get_latest_pos(): seed, template_id = divmod(tick_id, 2) random.seed(seed) cur_pos = [random.randrange(y_size), random.randrange(x_size)] cur_template = templates[template_id] try: return add_squares(cur_pos, cur_template) except IndexError: return [] move = get_latest_pos() print json.dumps(move) ``` [Answer] ## Python 3, SquareBot Puts squares everywhere- maybe Squares are static objects in Life- they do not move. So if I place enough inert objects around the place, the gliders and explosions that others create will possibly be blocked, or at least dampened. -Adapted from TrainingBot ``` from random import randint import sys,json,copy args=json.loads(sys.argv[1]) x=args["x_size"];y=args["y_size"] square=[[0,0],[0,1],[1,0],[1,1]];D=[] for g in range(7): X=randint(0,x);Y=randint(0,y) A=copy.deepcopy(square) for C in A:C[0]+=Y;C[1]+=X D+=A print(D) ``` Although I am having trouble testing it ]
[Question] [ You must make a [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") that outputs the square of the input in one language and the square root of the input in another. The shortest answer in bytes wins! You must have a precision of at least 3 decimal places, and the input will always be a positive float. [Answer] # C and C++, ~~68~~ 65 bytes ``` #include<math.h> float f(float n){auto p=.5;return pow(n,2-p*3);} ``` Original answer: ``` #include<math.h> float f(float n){return pow(n,sizeof('-')-1?2:.5);} ``` For both versions, C produces `n^2` and C++ produces `sqrt(n)`. [Answer] # Python 2 & Python 3, ~~23~~ 21 bytes ``` lambda n:n**(1/2or 2) ``` Python 2.x produces `n^2`, Python 3.x produces `sqrt(n)`. 2 bytes saved thanks to @Dennis! [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/) and [MATL](https://github.com/lmendo/MATL), 1 byte ``` U ``` Square root in Jolf, square in MATL. [Try it online!](https://tio.run/##y00syfn/P/T/fxM9UwA "MATL – Try It Online") (MATL) [Try the Jolf code.](http://conorobrien-foxx.github.io/Jolf/#code=VQ&input=NC41) Only works on Firefox. These are both 1 byte, as MATL and Jolf both use ASCII/extended ASCII codepages, so all commands are 1 byte. [Answer] # [2sable](https://github.com/Adriandmen/2sable) / [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` *. ``` 2sable computes the square. [Try it online!](https://tio.run/nexus/2sable#@6@l9/@/oQEA "2sable – TIO Nexus") Jelly computes the square root. [Try it online!](https://tio.run/nexus/jelly#@6@l9///f0MDAA "Jelly – TIO Nexus") ## How it works ### 2sable ``` * Read the input twice and compute the product of both copies. This pushes the square of the input. . Unrecognized token (ignored). ``` ### Jelly ``` . Numeric literal; yield 0.5. * Raise the input to the power 0.5. This yields the square root. ``` [Answer] # [C (clang)](http://clang.llvm.org/) and [Python](http://www.python.org), ~~109~~ ~~107~~ ~~69~~ 53 bytes ``` #/* lambda n:n**.5;'''*/ float a(i){return i*i;}//''' ``` C: [Try it online!](https://tio.run/nexus/c-clang#LYtBCoMwEEX3niIommQQAy3dNHiY0RgY0GmJ6Sp49jRClv@993NnoNnxWBwKfjPA9LJSSjCN3z8YBSrSKWzxF1gQkL2MKToTR3EgsdKphs6eK7JXbe/bcXDaVk6PGdU9v6Gcqi@0kCs//w "C (clang) – TIO Nexus") Python: [Try it online!](https://tio.run/nexus/python2#@6@sr8WVk5iblJKokGeVp6WlZ2qtrq6upc@VlpOfWKKQqJGpWV2UWlJalKeQqZVpXauvD5T@n2aLqoeroCgzr0QhTSMzr6C0RENT878lAA "Python 2 – TIO Nexus") Works by using comments to polyglot. The rest is pretty explanatory. First time using C! * Saved quite a few bytes thanks to @Riker. * Saved 2 bytes by removing unnecessary whitespace. * Saved very many bytes by using a function for C instead of STDIN/OUT. * Saved 16 bytes thanks to @Delioth by removing import statement at the top. [Answer] # [Ohm](https://github.com/MiningPotatoes/Ohm) and [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes Outputs the square in Ohm, the square root in Jelly. Ohm and Jelly use different single-byte codepages, so the program will appear differently in each encoding. xxd hexdump of the program: ``` 00000000: fd7f 0a ... ``` ### Jelly Using Jelly's codepage, it appears like this: ``` ’ ½ ``` Jelly takes the bottom most line to be its main link, and ignores the other links unless specifically called. So here it just does the square root (`½`) and implicitly outputs it. ### Ohm Using Ohm's codepage (CP437), it appears like this: ``` ²⌂◙ ``` `²` is the square function, and `⌂` and `◙` are both undefined, so the program just squares the implicitly read input and implicitly outputs it. [Answer] # C89 and C99, 47+3 = 50 bytes ``` float f(float n){return n//* /sqrt(n)//*/1*n ;} ``` Requires `-lm` flag (+3) C89 produces `n^2`, C99 produces `sqrt(n)`. To test in C89, [Try it online!](https://tio.run/nexus/c-gcc#JYtBDoIwEADvfUWDMekSodGTBPUlXprCapOyaLucCF93bcJpZg4jGGfHGs1OgjWNvCTSZG2tbP4mNgTF7bkm1W/qEMjHZRhvmYcwt@@HCsR6coEMrJ9UAk11jPik6oTmAtBvIj@P0b2yNGW6@2snTZz@ "C (gcc) – TIO Nexus") --- Getting C89 to do the `sqrt` version ought to take less code, but it insists on implicitly declaring the `sqrt` function with `int`s, so this is the best I could manage. [Answer] # Octave / MATLAB, ~~31~~ 29 bytes ``` @(x)x^(2-3*any(version>60)/2) ``` This outputs the square in Octave, and the square root in MATLAB. **Explanation:** The syntax is of course identical in MATLAB and Octave (for this little piece of code at least). This creates an anonymous function: ``` @(x) % Take x as input x^( ) % Raise x to the power of ... version % Returns the version number % 4.2.0 in Octave, % '9.2.0.538062 (R2017a)' in MATLAB version>60 % 'R' is larger than 60. All others are smaller 3*any(version>60)/2 % Checks if there is an 'R' and multiplies it by 1.5 if it is. 2-3*any(version>60) % 2-1.5*(is there an 'R') ``` [Answer] # Basic / Delphi – 6 characters ``` sqr(x) ``` Square root in Basic and square in Delphi. You can use a debugger to inspect the expression, thereby fulfilling any output requirements! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) / [Fireball](https://github.com/okx-code/Fireball), 3 bytes The following bytes make up the program: ``` FD B9 74 ``` 05AB1E calculates square root, Fireball squares. Explanation (05AB1E - `ý¹t`): ``` ý Pushes an empty string to the stack (not entirely sure why) ¹ Push first input t Square root ``` Explanation (Fireball - `²╣t`): ``` ² Square input ╣ Unassigned t Unassigned ``` Sometimes, it helps to have an incomplete language ;) [Answer] # PHP7 + JavaScript, ~~62~~ ~~61~~ 58 bytes This was actually more challenging than I expected! I am quite surprised of how long my code is. ``` eval(['alert((_=prompt())*_)','echo$argv[1]**.5'][+![]]); ``` --- **How does it work?** This works by selecting the code to run, from the array. PHP and JavaScript detection is made with `+![]`. In PHP, `[]` (empty array) is a falsy value, while in JavaScript it is a truthy value (objects (except `null`) are always truthy, even `new Boolean(false)` is truthy!). But, I need to get it to a numeric value, so, I just use a `not` (`!`) and convert it to integer (with the `+`). Now, PHP yields the value `1`, while JavaScript yields `0`. Placing the code inside an array, at those indexes, will allow us to select the right code for the desired language. This can be used as `[JS,PHP][+![]]`, to get the code of the right language. On previous polyglots, I've used `'\0'=="\0"`, which is `true` in JavaScript (since `\0` is parsed as the NULL-byte) and `false` in PHP (the `'\0'` won't be parsed as the NULL-byte, comparing the literal string `\0` with the NULL-byte). I'm happy that I've managed to reduce this check to `+!'0'`. I'm even more happy about [@rckd](https://codegolf.stackexchange.com/users/68084/rckd), which reduced it to the current version! From there on, it simply `eval`s the code required. **PHP** PHP will execute `echo$argv[1]**.5` (equivalent to `echo sqrt($argv[1]);`, square-root the number), receiving the value from the 2nd argument and displays it in the standard output. **JavaScript** JavaScript executes `alert((_=prompt())*_)`, which displays the squared number in an `alert`. --- --- Thank you to [@rckd](https://codegolf.stackexchange.com/users/68084/rckd) for saving 1 byte, and [@user59178](https://codegolf.stackexchange.com/users/59178/user59178) for saving 3 bytes! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) and [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` nqƓ½ ``` [(05AB1E)](https://tio.run/nexus/05ab1e#@59XeGzyob3//xt9zcvXTU5MzkgFAA "05AB1E – TIO Nexus") - [(Jelly)](https://tio.run/nexus/jelly#@59XeGzyob3//5sAAA "Jelly – TIO Nexus") ``` nq # Ignored by Jelly, push n**2 in 05AB1E then quit. Ɠ½ # Ignored by 05AB1E due to quit, push sqroot of input in Jelly. ``` --- Someone else made a good point, I guess since the UTF-8 characters do not share the same operation across code pages that they are technically 2-bytes each to encode. However, when looking at this in terms of the hex dump: ``` 6e 71 93 0a ``` In 05AB1E's CP1252 encoding this results in: ``` nq“\n ``` Meaning it will still output the square and quit, ignoring the rest. When these bytes are encoded using Jelly's codepage: ``` nqƓ½ ``` Which is the original intended code, when executed, results in the desired result of taking the input and taking the sqrt. [Answer] # Python 2 and Forth, ~~43~~ 33 bytes ``` ( """ ) fsqrt \ """);lambda n:n*n ``` **Try it online: [Python 2](https://tio.run/nexus/python2#@6@hoKSkpKDJlVZcWFTCFQPiaVqn2eYk5ialJCrkWeVp5f0vKMrMK1FI0zDWMzQx1PwPAA) (square) | [Forth](https://tio.run/nexus/forth-gforth#MzY0MUzVNf6voaCkpKSgyZVWXFhUwhUD4mla5yTmJqUkKuRZ5Wnl/U/T@w8A) (sqrt)** This evaluates to an anonymous function in Python, and a built-in function `fsqrt` in Forth. Python can have a named function `f` for 2 bytes more by putting `f=` in front of the lambda. The Forth program takes a [floating point literal](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Floating-Point-Tutorial.html), which in Forth must be written in scientific notation. Pi truncated to 3 decimal places (`3.141`) would be written like this: ``` 3141e-3 ``` [Answer] # JavaScript (ES6) / JavaScript (ES7), 52 bytes ``` f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`) ``` Returns the square of the input in ES7 and the square root in ES6. Quite difficult to test, unless you have an older browser which support ES6 but not ES7. ``` f=a=>eval(`try{eval("a**2")}catch(e){Math.sqrt(a)}`) console.log(f(4)); ``` [Answer] # [CJam](https://sourceforge.net/projects/cjam/) / [MATL](https://github.com/lmendo/MATL), 8 bytes ``` ld_*GX^! ``` Computes the square in CJam ([Try it online!](https://tio.run/nexus/cjam#@5@TEq/lHhGn@P@/kYGekSkA)) and the square root in MATL ([Try it online!](https://tio.run/nexus/matl#@5@TEq/lHhGn@P@/kYGekSkA)). ### Explanation of square in CJam ``` ld e# Read input line and interpret as a double _ e# Duplicate * e# Multiply. Pops the input number twice, pushes its square G e# Push 16 X e# Push 1 ^ e# Bitwise XOR. Pops 16 and 1, and pushes 17 ! e# Negate. Pops 17, pushes 0 e# Implicitly display. This prints the squared input with decimals, e# immediately followed by the 0 coming from the negate operation e# Even if the square of the input number is an integer, say 5, e# it is displayed as 5.0, so including an extra 0 always gives a e# correct result ``` ### Explanation of square root in MATL ``` l % Push 1. This is a number or equivalently a 1×1 array d % Consecutive differences. Pops 1, pushes [] (empty array) _ % Negate (element-wise). This leaves [] as is * % Implicitly input a number and push it. Multiply (element-wise): % pops [] and the input number, pushes [] G % Push input number again X^ % Square root. Pops number, pushes its square root ! % Transpose. For a number (1×1 array) this does nothing % Implicitly display. The stack contains [] and the result; but % [] is not displayed at all ``` [Answer] # C, [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 52 bytes ``` ;float f(float x){return sqrt(x);}char* F="_this^2"; ``` In an OFP script, a semicolon at the beginning of a line makes that line a comment, whereas C doesn't care about the additional semicolon. **C:** [Try it online!](https://tio.run/nexus/c-gcc#@2@dlpOfWKKQpgGhKzSri1JLSovyFIoLi0o0KjSta5MzEou0uNxsleJLMjKL44yUrP9n5pUo5CZm5mloclVzKQBBQRFQKE1DSTVNSQdolpGmpjVX7f9/yWk5ienF/3VzcgE) **OFP scripting language:** Save as `init.sqs` in the mission folder, then call it with `hint format["%1", 2 call F]`. Result: [![enter image description here](https://i.stack.imgur.com/uxdp3.jpg)](https://i.stack.imgur.com/uxdp3.jpg) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), [Grok](https://github.com/AMiller42/Grok-Language) ~~10~~ 12 bytes *Edit: In my first version, I forgot that casting to `int` would remove precision in the Vyxal code. Added +2 bytes to fix it.* ``` I√`#:Yp*zq`_ ``` Vyxal (Square Root): ``` # Implicit input I # Cast to int √ # Square root `#:Yp*zq` # Push string _ # Delete string # Implicit output ``` [Try it Online in Vyxal!](http://lyxal.pythonanywhere.com/?flags=&code=I%E2%88%9A%60%23%3AYp*zq%60_&inputs=10&header=&footer=) Grok (Square): ``` I√ # Push '√' to the register `# # Skip ‘#’ command : # Take input from STDIN Yp # Duplicate *z # Multiply and output as int q # Quit `_ # Never gets executed ``` [Try it Online in Grok!](http://grok.pythonanywhere.com?flags=&code=I%E2%88%9A%60%23%3AYp*zq%60_&inputs=10) [Answer] # PHP and [CJam](https://sourceforge.net/p/cjam), ~~30~~ ~~29~~ 25 bytes ``` ECHO"$argv[1]"**2;#];rdmq ``` Calculates the square in PHP and the square root in CJam. Has to be run using `-r` in PHP. ### PHP Raises the first command line argument (`$argv[1]`) to the power 2 and outputs it. Here `$argv[1]` is actually put as an inline variable in a string, which is cast to a number before doing the exponentiation. This is because `v` is not a valid instruction in CJam and will cause it to error out while parsing, but putting it in a string won't cause any problems. `#` starts a comment, so everything after is ignored. [Try it online!](https://tio.run/nexus/php#s7EvyCj47@rs4a@kkliUXhZtGKukpWVkrRxrXZSSW/j//39LAA) ### CJam The first part of the code, `ECHO"$argv[1]"**2;#` pushes a bunch of values and does a bunch of operations, all of which are thoroughly useless. The only important thing is that they doesn't cause any errors, because right afterwards is `];`, which wraps the entire stack in an array and then discards it. After that, it reads a double from input (`rd`), and gets its square root (`mq`), and implicitly outputs it. [Try it online!](https://tio.run/nexus/cjam#@@/q7OGvpJJYlF4WbRirpKVlZK0ca12Uklv4/78lAA "CJam – TIO Nexus") [Answer] # [Desmos](https://www.desmos.com/calculator) and [Pip](https://github.com/dloscutoff/pip), 12 bytes ``` YRTa f(y)=yy ``` [Run in Desmos](https://www.desmos.com/calculator/yw4ip1tet6) [Run in Pip](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZrIoNCErnSNCo1bSsrIUJQmZXRxnqGJoamlrFQAQA) ### Desmos The first line is four undefined variables multiplied together. Desmos complains about it, but ultimately it's a no-op. The second line defines a function `f(y)` as `y` times `y` (with an implicit multiplication operator). This function can be used in other lines and will return the square of any argument number. As a bonus, we also get to see a graph of `x = f(y)`. ### Pip `RTa` calculates the square root of the command-line argument `a`, and `Y` stores the result in `y`. The second line parses as three expressions: * `f` (evaluates to the main function) * `(y)=y` (evaluates to `1` because `y` always equals itself) * `y` (evaluates to the value stored in `y` previously) The last of these expressions ends the program and is therefore autoprinted. [Answer] # [Python](https://python.org) / [PARI/GP](https://pari.math.u-bordeaux.fr), 60 bytes ``` #/* n=int(input());print(n**2);"""*/ print(sqrt(input))\\""" ``` Basically a modification from the [C / Python answer](https://codegolf.stackexchange.com/a/116159/107017). Python does square. PARI/GP does square root. Takes input from `stdin`. Python: [Try It Online!](https://tio.run/##K6gsycjPM/7/X1lfiyvPNjOvRCMzr6C0RENT07qgCMTN09Iy0rRWUlLS0ueCiBQXFkFVaWrGxABl/v83MgUA) PARI/GP: [Try It Online!](https://tio.run/##K0gsytRNL/j/X1lfiyvPNjOvRCMzr6C0RENT07qgCMTN09Iy0rRWUlLS0ueCiBQXFkFVaWrGxABl/v83MgUA) [Answer] # [Reticular](https://tio.run/nexus/reticular#@6@vZqWl58Bll5lnla9cYP3/v6GJCQA) / [Befunge-98](https://tio.run/nexus/befunge-98#@6@vZqWl58Bll5lnla9cYP3/v6ERAA), 15 bytes 2D languages! ``` /&:*.@ >in:o#p; ``` ## Befunge-98 ``` /&:*.@ / divide top two (no-op) & read decimal input : duplicate * square . output @ terminate ``` ## Reticular ``` / mirror up, then right >in:o#p; i read line of input n cast to number :o# square root p print ; terminate ``` [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ) / QBasic, ~~26~~ 18 bytes ``` input a ?a^2'^.25 ``` In **QBasic**, it takes a number, and prints that number squared. The rest of the code is ignored because QBasic sees it as a comment (`'`). **QBIC** uses the same input statement. It then goes on to print that same number squared, then raised to the power of a quarter, effectively rooting it twice. This is because `'`is seen as a code literal: Pure QBasic code that is not parsed by QBIC. [Answer] ## GolfScript/Befunge, 15 bytes ``` #>&:*.@ ~2-1?? ``` Befunge: ``` #>&:*.@ #> // jumps over the arrow & // takes an integer as input :* // multiplies the top of the stack by itself . // outputs as integer @ // halts ~2-1?? // is not executed ``` GolfScript: ``` #>&:*.@ // is a comment ~2-1?? ~ // evaluates the input string 2-1? /* calculates 2^-1 = 1/2 (GolfScript does not support non-integers, but due to a missed int cast in the interpreter, they can be generated with the exponent function */ ? // calculates x^1/2 = sqrt(x) // the stack is output implicitly ``` This is my first golf, please let me know if I'm doing something wrong :) * Edited to be more portable, thanks to Wzl [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) and [><> (Fish)](https://esolangs.org/wiki/Fish), 10\* bytes ``` <?√,;n*: ``` [Try it in Vyxal (Square root)](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiPD/iiJosO24qOiIsIiIsIjI1Il0=) *\*this is 8 bytes in Vyxal but 10 in ><>. I'm scoring them both in UTF-8.* [Try it in ><> (Square)](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiPD/iiJosO24qOiIsImlucHV0IjoiIiwic3RhY2siOiI1Iiwic3RhY2tfZm9ybWF0IjoibnVtYmVycyIsImlucHV0X2Zvcm1hdCI6ImNoYXJzIn0=) # Explanation What Vyxal sees: ``` < # less than ? # push input √ # sqrt , # print that sqrt # (rest doesn't matter) ``` What ><> sees: ``` < # point left and wrap around executing the following : # dup * # multiply n # output ; # end execution ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) and [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes [Thunno 2 encoding](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md): ``` Ẋ,$ƭ ``` [Vyxal encoding](https://github.com/Vyxal/Vyxal/blob/main/vyxal/encoding.py#L3): ``` ²,$₃ ``` This looks like two different programs, since Thunno 2 and Vyxal have different encodings, but it's really the same sequence of bytes. [![Screeshot](https://i.stack.imgur.com/V6y5Xm.png)](https://i.stack.imgur.com/V6y5X.png) (Thunno 2: square root) [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCsiwk4oKDIiwiIiwiMTAiXQ==) (Vyxal: square) #### Explanation ``` Ẋ,$ƭ # Implicit input Ẋ, # (No effect) $ # Push the input ƭ # Square root # Implicit output ²,$₃ # Implicit input ² # Square the input , # Print the result $₃ # (No effect) ``` [Answer] ## [><>](https://esolangs.org/wiki/Fish) / [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes (7 bytes code + 2 for the '-v' flag in ><>) Man, I'm really having fun with the Jelly link structure. ``` :*n; ½ ``` Calculates the square [in ><>](https://tio.run/nexus/fish#@2@llWfNdWjv//@W/3XLLAE) , and the square root [in Jelly](https://tio.run/nexus/jelly#@2@llWfNdWjv////LQE). [Answer] # Python 3 + JavaScript, 101 bytes ``` 0//1or exec("function=lambda a:(lambda b:a);x=0") y=2//2/2 f=(function(x)(x**y))//1 or(lambda x:x**y) ``` Square root in JS, square in Python. Works on Firefox (tested on FF 52) and requires `(function(x) x)(42) === 42` being valid syntax. Also requires ES7 for the `**` operator. [Answer] # macOS Bash and sh, 24 bytes ``` p=^4 : bc<<<"sqrt($1)$p" ``` On the Mac, `sh` is `bash` running in Posix mode, and in this case as per <https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html>: > > Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes > > > Thus for `sh`, the variable `p` has the value `^4` after the `:` is run, but for `bash`, the variable `p` only has this value while `:` is run, and is empty afterwards. Being still really `bash` under the covers, some bashisms such as `<<<` herestrings still work for both the bash and sh cases. --- # Bash and dash (and GNU utils), 27 On Ubuntu 16.01, `sh` is a symlink to `dash`, which doesn't do `<<<` herestrings. So we have this instead: ``` p=^4 : echo "sqrt($1)$p"|bc ``` [Try it online](https://tio.run/nexus/bash#S04sUbCzUyguLNIrzlCwsVFQd/V3U/9fYBtnomDFlZqcka@gBJQs0VAx1FQpUKpJSv4PVMDFlZQIVA7VZcmFxP4PAA). [Answer] # bash and sh, 48 bytes *Update: I must concede defeat. [Digital Trauma](https://codegolf.stackexchange.com/a/116292/8927)'s bash/sh answer is far more elegant than this one.* --- ``` bc -l<<<"sqrt($1^(($(kill -l|wc -l)*3-3)/7+1))" ``` bash produces `n^2`, sh produces `sqrt(n)`. --- `bc` is only needed so that `sqrt` can be calculated. The difference in behaviour is between bash and sh. OK, technically the "sh" I'm using is still bash, but bash in "POSIX" mode (which happens if you invoke `/bin/sh` instead of `/bin/bash` on systems where `/bin/sh` is an alias for bash). If this is the case on your system, you can test with: ``` /bin/bash prog.sh 4 /bin/sh prog.sh 4 ``` --- This is based on one of the differences explained here: <https://www.gnu.org/software/bash/manual/html_node/Bash-POSIX-Mode.html> [Answer] # [Python 3](https://docs.python.org/3/) and [Python 2](https://docs.python.org/2/), 18 bytes I took inspiration from [this answer](https://codegolf.stackexchange.com/a/116162/103772) ``` (1/2or 2).__rpow__ ``` ### Python 3 : [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzX8NQ3yi/SMFIUy8@vqggvzw@/n9BUWZeiYZScWFRiYaxpoKtko5CGpChyYUsYWgGkwGyNP8DAA "Python 3 – Try It Online") `1/2` is evaluated to `0.5` so `1/2or 2` is equal to `0.5` => sqrt ### Python 2 : [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzX8NQ3yi/SMFIUy8@vqggvzw@/n9BUWZeiYKScZyRgq2SjkKahrEmF1TM0AwuaGim@R8A "Python 2 – Try It Online") `1/2` is evaluated to `0` so `1/2or 2` is equal to `2` => ^2 ]
[Question] [ The ancient Greeks had these things called singly and doubly even numbers. An example of a singly even number is 14. It can be divided by 2 once, and has at that point become an odd number (7), after which it is not divisible by 2 anymore. A doubly even number is 20. It can be divided by 2 twice, and then becomes 5. Your task is to write a function or program that takes an integer as input, and outputs the number of times it is divisible by 2 as an integer, in as few bytes as possible. The input will be a nonzero integer (any positive or negative value, within the limits of your language). Test cases: ``` 14 -> 1 20 -> 2 94208 -> 12 7 -> 0 -4 -> 2 ``` The answer with the least bytes wins. **Tip:** Try converting the number to base 2. See what that tells you. [Answer] # x86\_64 machine code, 4 bytes [The BSF (bit scan forward) instruction does exactly this](http://x86.renejeschke.de/html/file_module_x86_id_19.html)! ``` 0x0f 0xbc 0xc7 0xc3 ``` In gcc-style assembly, this is: ``` .globl f f: bsfl %edi, %eax ret ``` The input is given in the EDI register and returned in the EAX register as per standard 64-bit [c](/questions/tagged/c "show questions tagged 'c'") calling conventions. Because of two's complement binary encoding, this works for -ve as well as +ve numbers. Also, despite the documentation saying *"If the content of the source operand is 0, the content of the destination operand is undefined."*, I find on my Ubuntu VM that the output of `f(0)` is 0. ### Instructions: * Save the above as `evenness.s` and assemble with `gcc -c evenness.s -o evenness.o` * Save the following test driver as `evenness-main.c` and compile with `gcc -c evenness-main.c -o evenness-main.o`: ``` #include <stdio.h> extern int f(int n); int main (int argc, char **argv) { int i; int testcases[] = { 14, 20, 94208, 7, 0, -4 }; for (i = 0; i < sizeof(testcases) / sizeof(testcases[0]); i++) { printf("%d, %d\n", testcases[i], f(testcases[i])); } return 0; } ``` Then: * Link: `gcc evenness-main.o evenness.o -o evenness` * Run: `./evenness` --- @FarazMasroor asked for more details on how this answer was derived. I am more familiar with [c](/questions/tagged/c "show questions tagged 'c'") than the intricacies of x86 assembly, so typically I use a compiler to generate assembly code for me. I know from experience that [gcc extensions such as `__builtin_ffs()`, `__builtin_ctz()` and `__builtin_popcount()`](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html) typically compile and assemble to 1 or 2 instructions on x86. So I started out with a [c](/questions/tagged/c "show questions tagged 'c'") function like: ``` int f(int n) { return __builtin_ctz(n); } ``` Instead of using regular gcc compilation all the way to object code, you can use the `-S` option to compile just to assembly - `gcc -S -c evenness.c`. This gives an assembly file `evenness.s` like this: ``` .file "evenness.c" .text .globl f .type f, @function f: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) movl -4(%rbp), %eax rep bsfl %eax, %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE0: .size f, .-f .ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4" .section .note.GNU-stack,"",@progbits ``` A lot of this can be golfed out. In particular we know that the [c](/questions/tagged/c "show questions tagged 'c'") [calling convention](https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl) for functions with `int f(int n);` signature is nice and simple - the input param is passed in the `EDI` register and the return value is returned in the `EAX` register. So we can take most of instructions out - a lot of them are concerned with saving registers and setting up a new stack frame. We don't use the stack here and only use the `EAX` register, so don't need to worry about other registers. This leaves "golfed" assembly code: ``` .globl f f: bsfl %edi, %eax ret ``` Note as @zwol points out, you can also use optimized compilation to achieve a similar result. In particular `-Os` produces exactly the above instructions (with a few additional assembler directives that don't produce any extra object code.) This is now assembled with `gcc -c evenness.s -o evenness.o`, which can then be linked into a test driver program as described above. There are several ways to determine the machine code corresponding to this assembly. My favourite is to use the gdb `disass` disassembly command: ``` $ gdb ./evenness GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1 ... Reading symbols from ./evenness...(no debugging symbols found)...done. (gdb) disass /r f Dump of assembler code for function f: 0x00000000004005ae <+0>: 0f bc c7 bsf %edi,%eax 0x00000000004005b1 <+3>: c3 retq 0x00000000004005b2 <+4>: 66 2e 0f 1f 84 00 00 00 00 00 nopw %cs:0x0(%rax,%rax,1) 0x00000000004005bc <+14>: 0f 1f 40 00 nopl 0x0(%rax) End of assembler dump. (gdb) ``` So we can see that the machine code for the `bsf` instruction is `0f bc c7` and for `ret` is `c3`. [Answer] # Python, 25 bytes ``` lambda n:len(bin(n&-n))-3 ``` `n & -n` zeroes anything except the least significant bit, e.g. this: ``` 100010101010100000101010000 v 000000000000000000000010000 ``` We are interested in the number of trailing zeroes, so we convert it to a binary string using `bin`, which for the above number will be `"0b10000"`. Since we don't care about the `0b`, nor the `1`, we subtract 3 from that strings length. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md) ``` Æfċ2 ``` In the latest version of Jelly, `ÆEḢ` (3 bytes) works. ``` Æf Calculate the prime factorization. On negative input, -1 appended to the end. ċ2 Count the 2s. ``` Try it [here](http://jelly.tryitonline.net/#code=w4ZmxIsy&input=&args=MTIw). [Answer] # Pyth, 6 bytes ``` /P.aQ2 ``` Try it [here](https://pyth.herokuapp.com/?code=%2FP.aQ2&input=120&test_suite=1&test_suite_input=3%0A14%0A20%0A120%0A92408&debug=0). ``` P.aQ In the prime factorization of the absolute value of the input / 2 count the number of 2s. ``` [Answer] # JavaScript (ES6), 18 bytes ``` n=>Math.log2(n&-n) ``` 4 bytes shorter than `31-Math.clz32`. Hah. [Answer] # JavaScript ES6, ~~22~~ 19 bytes ``` f=x=>x%2?0:f(x/2)+1 ``` Looks like recursion is the shortest route. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ọ2 ``` [Try it online!](https://tio.run/##y0rNyan8///h7l6j/4fbHzWt@f/f0ERHwchAR8HSxMjAQkfBXEdB1wQA "Jelly – Try It Online") ## How it works ``` ọ2 - Main link. Takes n on the left ọ - How many times is n divisible by... 2 - ...2? ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 5 bytes ``` Yf2=s ``` This works for all integers. [**Try it online!**](http://matl.tryitonline.net/#code=WWYyPXM&input=LTIw) ``` Yf % implicit input. Compute (repeated) prime factors. For negative input % it computes the prime factors of the absolute value, except that for % -1 it produces an empty array instead of a single 1 2=s % count occurrences of "2" in the array of prime factors ``` [Answer] ## Pyth, 8 bytes ``` lec.BQ\1 ``` ``` Q autoinitialized to eval(input()) .B convert to binary string c \1 split on "1", returning an array of runs of 0s e get the last run of 0s, or empty string if number ends with 1 l take the length ``` For example, the binary representation of `94208` is: ``` 10111000000000000 ``` After splitting on `1`s and taking the last element of the resulting array, this becomes: ``` 000000000000 ``` That's 12 zeroes, so it's "12-ly even." This works because `x / 2` is essentially `x >> 1`—that is, a bitshift right of `1`. Therefore, a number is divisible by 2 only when the LSB is `0` (just like how a decimal number is divisible by 10 when its last digit is `0`). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 5 bytes Now supports negative numbers. Code: ``` Äb1¡g ``` [Try it online!](http://05ab1e.tryitonline.net/#code=w4RiMcKhZw&input=LTk0MjA4) Explanation: ``` Ä # Abs(input) b # Convert the number to binary 1¡ # Split on 1's g # Take the length of the last element ``` Uses CP-1252 encoding. [Answer] ## Pyth, 6 bytes ``` x_.BQ1 ``` Basically just ``` convert2BinString(evaluatedInput())[::-1].index("1") ``` [Answer] ## C, 36 (28) bytes ``` int f(int n){return n&1?0:f(n/2)+1;} ``` (Not testing for zero argument as a nonzero argument was specified.) **Update (in response to comment)**: If we allow K&R style function declarations, then we can have a 28-byte version: ``` f(n){return n&1?0:f(n/2)+1;} ``` In this case, we rely on the fact that the compiler defaults both `n` and the return type of `f` to `int`. This form generates a warning with C99 though and does not compile as valid C++ code. [Answer] ## Java 7, 39 or maybe 44 bytes ``` int s(int a){return a%2!=0?0:s(a/2)+1;} int s(int a){return a%2!=0|a==0?0:s(a/2)+1;} ``` Yay recursion! I had to use a `!=` instead of a shorter comparison so it wouldn't overflow on negative input, but other than that it's pretty straightforward. If it's odd, send a zero. If even, add one and do it again. There are two versions because right now output for zero is unknown. The first will recurse until the stack overflows, and output nothing, because 0 is infinitely even. The second spits out a nice, safe, but probably-not-mathematically-rigorous 0 for output. [Answer] # Ruby 24 bytes My first code golf submission (yey!) ``` ("%b"%$*[0])[/0*$/].size ``` **How I got here**: First I wanted to get code that actually fulfilled the spec to get my head around the problem, so I built the method without regards to number of bytes: ``` def how_even(x, times=1) half = x / 2 if half.even? how_even(half, times+1) else times end end ``` with this knowledge I de-recursed the function into a while loop and added `$*` (ARGV) as the input and i as the count of how many times the number has been halved before it becomes odd. ``` x=$*[0];i=1;while(x=x/2)%2<1;i+=1;end;i ``` I was quite proud of this and almost submitted it before it struck me that all this dividing by two sounded a bit binary to me, being a software engineer but not so much a computer scientist this wasn't the first thing that sprung to mind. So I gathered some results about what the input values looked like in binary: ``` input in binary result --------------------------------- 14 1110 1 20 10100 2 94208 10111000000000000 12 ``` I noticed that the result was the number of positions to the left we have to traverse before the number becomes odd. Doing some simple string manipulations I split the string on the last occurrence of 1 and counted the length of remaining 0s: ``` ("%b"%$*[0])[/0*$/].size ``` using `("%b" % x)` formatting to turn a number to binary, and [String#slice](http://ruby-doc.org/core-2.2.3/String.html#method-i-slice) to slice up my string. I have learnt a few things about ruby on this quest and look forward to more golfs soon! [Answer] # JavaScript (ES6), 20 bytes 19 bytes. ``` f=x=>~x%2&&1+f(x/2) ``` This is a port of the Haskell solution by @nimi to JavaScript. It uses the "short-circuit" properties of `&&` which returns its left side if it is falsey (which in this case is `-0`) or else returns its right side. To implement `odd x = 0` we therefore make the left hand side `1 - (x % 2)` which bubbles `0` through the `&&`, otherwise we recurse to `1 + f(x / 2)`. The shaving of `1 - (x % 2)` as `(~x) % 2` is due to @Neil below, and has the strange property that causes the above function to emit `-0` for small odd numbers. This value is a peculiarity of JS's decision that integers are IEEE754 doubles; this system has a separate `+0` and `-0` which are special-cased in JavaScript to be `===` to each other. The `~` operator computes the 32-bit-signed-integer bitwise inversion for the number, which for small odd numbers will be a negative even number. (The positive number `Math.pow(2, 31) + 1` for example produces `0` rather than `-0`.) The strange restriction to the 32-bit-signed integers does not have any other effects; in particular it does not affect correctness. [Answer] # Perl 6, ~~23~~ 18 bytes ``` {+($_,*/2...^*%2)} ``` **usage** ``` > my &f = {+($_,*/2...^*%2)} -> ;; $_? is raw { #`(Block|117104200) ... } > f(14) 1 > f(20) 2 > f(94208) 12 > f(7) 0 > f(-4) 2 ``` [Answer] # J, 6 bytes ``` 1&q:@| ``` Explanation: ``` | absolute value 1&q: exponent of 2 in the prime factorization ``` [Answer] # C, 37 bytes `f(int x){return x?x&1?0:1+f(x/2):0;}` Recursively check the last bit until it's not a 0. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes My 100th answer. ``` ⊥⍨∘~2∘⊥⍣¯1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RHXUsf9a541DGjzghIgHmLD603/P@obypQNk3B0sTIwIILxjOHsw6tN/kPAA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ⊥⍨∘~2∘⊥⍣¯1 2∘⊥⍣¯1 ⍝ convert the number to binary. ~ ⍝ negate it ⊥⍨ ⍝ count trailing ones in the negated number, ⍝ effectively counting trailing zeros in the number, ⍝ effectively counting how many times is the number divisible by 2. ``` [Answer] # Java, 27 bytes ``` Long::numberOfTrailingZeros ``` [Try it online!](https://tio.run/##lY49D4IwEIZ3fkVHMKFBYuIHcXDXOKiLxuFEIMXSNterCTH8dizxY@eWy733vO9dDU@I6/ujF43RSKz2M3ckJC@dykloxSdZYNxNipzlEqxlOxDqFTBfX9kSkG9PLe6s8cvwQChUdbkywMpGH3aorVbVSQG2e1MgkEZWrvtBXK2Ua24F7ssjgpDefC5Q2/5nzP4Rh9ZS0XDtiBt/hKQKSw7GyHZjh6RwOouiEXiajMKXszRZjHLMR9Hx//su6Po3) ## Explanation The number of times a number can be divided by 2 is equal the number of 0s after the rightmost 1 in its binary representation; Java has a built-in method for finding this. Using `Long` instead of `Integer` saves 3 bytes. See also: [`Long.numberOfTrailingZeros` documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#numberOfTrailingZeros(long)) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 2 bytes ``` 2Ǒ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyx5EiLCIiLCIyMCJd) This one by @lyxal ``` 2Ǒ # I'm running out of things to say for this comment line Ǒ # How many times is the input divisible by... 2 # 2 ``` # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` Eġ∆l ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJFxKHiiIZsIiwiIiwiOTQyMDgiXQ==) Ported from the [Desmos](https://codegolf.stackexchange.com/a/247899/107299) answer. ``` Eġ∆l # 4 bytes! E # 2^input ġ # GCD of that and the input ∆l # log2 ``` # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` bṘȧ1ḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJi4bmYyKcx4bifIiwiIiwiLTQiXQ==) Strategy from the osabie answer. Suprised that there has been no Vyxal answer for a such a popular question. Bit twiddling also gives 5 bytes. ``` bṘȧ1ḟ # This comment line needs some love b # Convert to binary Ṙ # Reverse ȧ # Absolute value of each element in the list. This is to handle negative numbers correctly 1ḟ # First index of 1 ``` [Answer] # [Rust](https://www.rust-lang.org), 18 bytes ``` i8::trailing_zeros ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72kqLS4ZMGGtDyF3MTMPA3N6pzUEoU026WlJWm6FptKLaysSooSM3My89Ljq1KL8oshEjeNrLnS8osUMhUy8xQMSy309GyNDBSquRSAoKAoM68kJ09RQ6m6VkknTSNTU9Oaq5arFqJzwQIIDQA) It's a builtin :) Replace `i8` with any other integer type and it will also work. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~27~~ 15 bytes ``` $pA:2xlL,Al-L=. ``` ### Explanation ``` $pA § Unify A with the list of prime factors of the input :2x § Remove all occurences of 2 in A lL, § L is the length of A minus all the 2s Al-L=. § Unify the output with the length of A minus L ``` [Answer] ## Haskell, 28 bytes ``` f x|odd x=0|1<2=1+f(div x 2) ``` Usage example: `f 94208`-> `12`. If the number is odd, the result is `0`, else `1` plus a recursive call with half the number. [Answer] # Befunge, 20 ``` &:2%#|_\1+\2/# @.< ``` Code execution keeps moving to the right and wrapping around to the second character of the first line (thanks to the trailing `#`) until `2%` outputs `1`, which causes `_` to switch the direction to left, then `|` to up, which wraps around to the `<` on the second row, which outputs and exits. We increment the second-to-the-top element of the stack every time through the loop, then divide the top by 2. [Answer] # [Retina](https://github.com/mbuettner/retina), ~~29~~ 17 ``` +`\b(1+)\1$ ;$1 ; ``` [Try it online!](http://retina.tryitonline.net/#code=K2BcYigxKylcMSQKOyQxCjs&input=LTExMTExMTExMTExMTExMTExMTEx) 2 bytes saved thanks to Martin! Takes unary input. This repeatedly matches the largest amount of `1`s it can such that that number of `1`s matches exactly the rest of the `1`s in the number. Each time it does this it prepends a `;` to the string. At the end, we count the number of `;`s in the string. If you want decimal input, add: ``` \d+ $0$*1 ``` to the beginning of the program. [Answer] # Jolf, 6 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=WmxtKWoy) ``` Zlm)j2 Zl 2 count the number occurrences of 2 in m)j the prime factorization of j (input) ``` Rather simple... Kudos to ETHProductions for ousting Jolf with the version that really should work! [Answer] ## ES6, 22 bytes ``` n=>31-Math.clz32(n&-n) ``` Returns -1 if you pass 0. [Answer] # PARI/GP, 17 bytes ``` n->valuation(n,2) ``` [Answer] ## 6502 machine language, 7 bytes To find the place value of the least significant 1 bit of the nonzero value in the accumulator, leaving the result in register X: ``` A2 FF E8 4A 90 FC 60 ``` To run this on the [6502 simulator on e-tradition.net](http://e-tradition.net/bytes/6502/index.html), prefix it with `A9` followed by an 8-bit integer. This disassembles to the following: ``` count_trailing_zeroes: ldx #$FF loop: inx lsr a ; set carry to 0 iff A divisible by 2, then divide by 2 rounding down bcc loop ; keep looping if A was divisible by 2 rts ; return with result in X ``` This is equivalent to the following C, except that C requires `int` to be at least 16-bit: ``` unsigned int count_trailing_zeroes(int signed_a) { unsigned int carry; unsigned int a = signed_a; // cast to unsigned makes shift well-defined unsigned int x = UINT_MAX; do { x += 1; carry = a & 1; a >>= 1; } while (carry == 0); return x; } ``` The same works on a 65816, assuming MX = 01 (16-bit accumulator, 8-bit index), and is equivalent to the above C snippet. ]
[Question] [ # Introduction The game [Minecraft](https://minecraft.net) has a 1 in 10000 chance of showing "Minceraft" instead of "Minecraft" on the title screen. # Your challenge Your challenge is to code a function or program that takes no input, and on average 1 of 10000 times, returns "Minceraft" and the rest of the time returns "Minecraft". # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest wins! [Answer] # Minecraft, ~~358~~ ~~293~~ ~~277~~ 276 bytes *Implementing Minceraft in Minecraft* Should be run as a set of commands in game. Should be run on a fresh superflat (redstone ready) world. Byte count is the amount of characters you need to type, including newlines. ``` /scoreboard objectives add s dummy /summon bat /execute as @e[type=bat] store result score o s run data get entity @s UUID[1] /scoreboard players set c s 2147054151 /execute if score o s < c s run tellraw @s "Minecraft" /execute if score o s >= c s run tellraw @s "Minceraft" ``` The UUID of an entity is (mostly) randomly generated and stored as four signed 32 bit integers. One of the integers is compared with `2147054151` which is one ten thousandth of the way between `2^31` and `-2^31`. Previous solution because it was so high effort and I'm not deleting it: ## Minecraft, 293 bytes ``` /scoreboard objectives add s dummy /summon horse /execute as @e[type=horse] store result score o s run data get entity @s Attributes[1].Base 100000 /scoreboard players set c s 11883 /execute if score o s >= c s run tellraw @s "Minecraft" /execute if score o s < c s run tellraw @s "Minceraft" ``` ### How does it work? In Minecraft, there are only a limited amount of sources of reliable randomness usable in commands. In Minecraft Functions you can use predicates with specific random chances, but that requires multiple files and submitting that as a zipped data pack would be at least 1 KB. To avoid this and have it run solely from commands a player can type in, this uses horses as a random source. When a horse is spawned, it is assigned a random speed between 0.1125 and 0.3375 (the units are arbitrary). The random speed calculation is as follows: $$0.25(0.45 + 0.3x + 0.3y + 0.3z)$$ Where *x*, *y*, and *z* are uniform independent random variables **[0, 1)**. If you find the cumulative density function by convolving the distribution functions (to get the PDF) and then integrating, you will end up with the following piecewise function: $$ f(x)=\begin{cases}-\frac{9}{16}+15x-\frac{400x^{2}}{3}+\frac{32000x^{3}}{81}&\frac{9}{80}\le x<\frac{3}{16}\\ \frac{29}{4}-110x+\frac{1600x^{2}}{3}-\frac{64000x^{3}}{81}&\frac{3}{16}\le x<\frac{21}{80}\\ -\frac{227}{16}+135x-400x^{2}+\frac{32000x^{3}}{81}&\frac{21}{80}\le x<\frac{27}{80} \end{cases} $$ We need to find the horse speed where the probability of a horse with that speed or lower spawning is one in ten thousand or 0.0001. This can be done by solving the first equation: $$-\frac{9}{16}+15x-\frac{400x^{2}}{3}+\frac{32000x^{3}}{81} = 0.0001\\ f^{-1}(0.0001)\simeq0.11882574$$ This results in the horse speed being multiplied by 100,000 (because scoreboard values must be integers) and compared with 11883 in the code. The precision is currently 1.00202 in 10,000. Two bytes can be added or removed for approximately each order of magnitude required. Two additional bytes will make it 1.00012 in 10,000. [Answer] # Python 3, ~~63~~ 59 bytes My idea was to use the `time` module as a PRNG since the challenge stated > > on average 1 of 10000 times, returns "Minceraft" and the rest of the time returns "Minecraft" > > > and taking the time mod 10000 does exactly that. Thanks [@movatica](https://codegolf.stackexchange.com/users/86751/movatica) for -4 ``` import time print(f"Min{'ceec'[time.time()%1e4>1::2]}raft") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVq6AoM69EI03JNzOvWj05NTVZPRokrgciNDRVDVNN7AytrIxia4sS00qUNP//BwA) Alternative, also 59 bytes: ``` import time print("Min%sraft"%"ceec"[time.time()%1e4>1::2]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRKEkMzeVq6AoM69EQ8k3M0@1uCgxrURJVSk5NTVZKRokqwciNDRVDVNN7AytrIxiNf//BwA) [Answer] # [Python 3](https://docs.python.org/3/), ~~78~~ ~~71~~ ~~69~~ 68 bytes ``` from random import* f=lambda:f'Min{randint(0,1e4)and"ec"or"ce"}raft' ``` [Try it online!](https://tio.run/##FYyxCoAwEEN3v6J00YqDopPgJ/gRVXt6YO/K0UXEb69tlhBekvDEi2lMCYS9EktHNvSBJbYVLLf122FnqFekt1Ck2PTd4CaTg3a7ZtG7059YiHUCFoUKqRydrhT7LDMHKTtojEk "Python 3 – Try It Online") -7 bytes thanks to [@Alex bries](https://codegolf.stackexchange.com/users/99744/alex-bries) -2 bytes thanks to [@Alex bries](https://codegolf.stackexchange.com/users/99744/alex-bries) [Answer] ## Python 3 - ~~45~~ ~~42~~ 41 Bytes 41 bytes with the constraint of running from a different process every run. ``` print(f"Min{'ceec'[id(0)%4e4>1::2]}raft") ``` 42 bytes with limited randomness unless running a different process each time [\*]. ``` print(f"Min{'ceec'[id({})%4e4>1::2]}raft") ``` The idea was to use the same wrapper as in [here](https://codegolf.stackexchange.com/a/224450/103702), but a different RNG: Create a new object (a ~~set~~ dict in this case, because it takes ~~5~~ 2 characters ~~`set()`~~ `{}`), and take the `id()` of that, which is its memory address. The memory address acts like a uniform hash[\*], which has ~~`1/10000`~~ `1/40000` (thanks @ovs) chance to end with zeros. [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI03JNzOvWj05NTVZPTozRaM4tURDU1PVMNXEztDKyii2tigxrURJ8/9/AA "Python 3 – Try It Online") **Update to 42 bytes:** Instead of `set()`, use `{}` which is the `dict` constructor. Can't go shorter for dynamic object creation. [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI03JNzOvWj05NTVZPTozRaO6VlPVMNXEztDKyii2tigxrURJ8/9/AA "Python 3 – Try It Online") **Update to 41 bytes:** - use static object creation! Thanks to @dingledooper **Works only if the program is run in a different process every run!** Instead of `{}`, use `0`. `0` is an object in Python, so it has an address in virtual memory, and that address is constant for that object during the lifetime of the program. If we were to run that in a for loop, it would not be random. However, if we run it in a new process every run, we get the desired randomness. This is the case in a [stateless server](https://tio.run/##K6gsycjPM/7/v6AoM69EI03JNzOvWj05NTVZPTozRaO6VlPVJNXEztDKyii2tigxrURJ8/9/AA "Python 3 – Try It Online"). [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EI03JNzOvWj05NTVZPTozRaO6VlPVJNXEztDKyii2tigxrURJ8/9/AA "Python 3 – Try It Online") [\*] - Objects in Python are freed immediately when they are no longer referenced (reference counting). Thus, running the solution in a loop might always output the same id, as the memory is freed and allocated at the same address. This is OS dependent, and environment dependent, thus may not work as expected, or in a reproducible way. Running a new process each time solves this issue. [Answer] # JavaScript, 37 bytes ``` _=>`Min${new Date%1e4?'ec':'ce'}raft` ``` [Try It Online](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/3tYuwTczT6U6L7VcwSWxJFXVMNXEXj01Wd1KPTlVvbYoMa0k4X9afpFGpq2BtbZ2po1hqpG1ZnJ@XnF@TqpeTn66RpqGpuZ/AA) First of all, write `Min`. Then get the current time with `new Date`. Normally it returns something similar to "2021-10-05T10:29:58.432Z". But if you do a mathematical operation on it, this output becomes the epoch time similar to "1633429932422" (a number, basically). Now divide the number by 10000 (1e4). If the remainder (%) is `0` i.e. `false`, add `ce` to `Min` otherwise add `ec`. At last, add `raft` at the end. [Answer] # [C (gcc)](https://gcc.gnu.org/), 48 bytes ``` f(){printf("Min%sraft",rand()%10000?"ec":"ce");} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O6oCgzryRNQ8k3M0@1uCgxrURJpygxL0VDU9XQAAjslVKTlayUklOVNK1r/wOVKuQmZuZpaHJVcykAQVp@kYIGSDRPwVbBwBpI2SgYA2lt7TxNBYgSsDINTWs4B2ZjTJ4SVLSWq/b/v@S0nMT04v@65QA "C (gcc) – Try It Online") ### Version closer to \$\frac{1}{10000}\$ For a pseudorandomness as close to \$\frac{1}{10000}\$ as possible: # [C (gcc)](https://gcc.gnu.org/), 79 bytes ``` f(){long p=0,m=1e4,i;for(i=m;i--;)p+=rand();printf("Min%sraft",p%m?"ec":"ce");} ``` [Try it online!](https://tio.run/##PY1NCsMgFIT3nuLxIKAkQkq7qpWeoDfoRqwGIb6ICXQRcvVa@zubYYaPGSsHa0vxXKzjRAMk3XdR79yhC8pPmQcdVZBSidTqbOjGhUo50OI5XgI1czZ@wS418YzO4hGtQ6G2UgmIJhAXbGVQVbeAv1oCDb2qdoJ99bYlAR/kjdX9f/gdXQm/7ca28rB@NMNc5P0J "C (gcc) – Try It Online") [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 632 bytes ``` Go to Heisenberg's:W 1 R 3 R 1 L.Pickup a passenger going to Divide and Conquer.1073741824e-4 is waiting at Starchild Numerology.Go to Starchild Numerology:N 1 L 3 L 1 L 3 L.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:W 1 R 3 R 1 R 2 R 1 R.Pickup a passenger going to Trunkers.Go to Trunkers:E 1 R 3 R 1 L.Pickup a passenger going to The Underground.Go to The Underground:E 1 R 2 L.Switch to plan A if no one is waiting.Minecraft is waiting at Writer's Depot.[A]Minceraft is waiting at Writer's Depot.Go to Writer's Depot:N 3 L 2 L.Pickup a passenger going to Post Office.Go to Post Office:N 1 R 2 R 1 L. ``` [Try it online!](https://tio.run/##lZFBT8MwDIX/im87EdGu0lBvE0NwKGPahnZAHELqttaKU5KUwa8vKW2lFRCDQxTFfvn0/OzkGzXNtQan4QbJIj@hySc23kEAa5j6E0AiVqT2dQUSKmm9JkcDuSbO228LeqUUQXIKl5pfajQiOJ9NZ1FwEUZ4FgFZOEhyrVw62DhpVEFlCsv6GY0udf4uOgM/teJla8AbSYb7v2Y69vfGaMQ1hN39K31rat6jsT1zeMZXfw5rWyDcc@ozNrrmdACNqz0v9KzNgZwqWk1VSoY5UAasQTMexSpuiVEZmbkvWe8MOTQTCwustBMP80evVHha2dkaF/0m2i2EJyZcaevgLstIYY85qnxuc8g6EU3zAQ "Taxi – Try It Online") There are two sources of randomness in Taxi: **Heisenberg's** (which holds a random integer passenger), and **Firemouth Grill** (which can hold any number of passengers, who are picked up in a random order). This program uses **Heisenberg's** to grab a random number, which will be used to choose one of two strings randomly. Here is the basic control flow of the program: * Go to **Heisenberg's** and grab a random integer, in the range of \$[0, 2^{31}-1]\$. (\$2^{31}-1\$ is `RAND_MAX` in C++, and Taxi uses C++'s random functions.) * Pick up the value `1073741824e-4` (that's \$\frac{2^{31}}{2 \times 10000}\$) from **Starchild Numerology**. * Drop off both passengers at **Divide and Conquer**, giving us a result of \$\frac{n}{2^{31}} \times 2 \times 10000\$, which is a double in the range \$[0, 2 \times 10000)\$. (We use this range instead of \$[0, 10000)\$ because we will output `Minceraft` when this number is either 0 or 1.) * Bring this result to **Trunkers**, which chops off the fractional part. (The range is still \$[0, 2 \times 10000)\$.) * Bring this result to **The Underground**. One of two things will happen: * + A passenger will be returned, which means that our number was greater than 1 (which has a \$\frac{2 \times 10000 - 2}{2 \times 10000}\$ chance of occurring). Do nothing. * + No passenger will be returned, which means that our number was either 0 or 1 (which has a \$\frac{2}{2 \times 10000}\$ chance of occurring). Declare the value `"Minceraft"` at **Writer's Depot**. * Declare the value `"Minecraft"` at **Writer's Depot**. * Pick up the first passenger waiting at **Writer's Depot**. (If both `"Minecraft"` and `"Minceraft"` are waiting, `"Minceraft"` will be picked up, because it was waiting there first.) * Drop off this passenger at the **Post Office**, outputting the string and (for purposes of Code Golf) ending the program. # [Taxi](https://bigzaphod.github.io/Taxi/), 691 bytes ``` 1e4 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to The Underground.Minceraft is waiting at Writer's Depot.Go to Writer's Depot:E 1 L 2 R.[A]Pickup a passenger going to Cyclone.Go to Cyclone:N.Pickup a passenger going to Firemouth Grill.Pickup a passenger going to Firemouth Grill.Go to Firemouth Grill:S 1 L 2 L 1 R.Go to Fueler Up:E 1 L.Go to The Underground:N.Switch to plan B if no one is waiting.Pickup a passenger going to The Underground.Minecraft is waiting at Writer's Depot.Go to Writer's Depot:N 3 L 2 L.Switch to plan A.[B]Go to Firemouth Grill:S 1 R.Pickup a passenger going to Post Office.Go to Post Office:E 1 R. ``` [Try it online!](https://tio.run/##nVFLb4MwDP4rvu0WqdtO3No9eulYBat6qHqIggnW0hgFo66/ntECUoc2pO7k5LPl72HRX9Q0M3wEquCoSchb0AKp6GAKchnE9QEDO7YntWQQ/rUVbWEGK7iH5FK790qtyXzWJWgodVWhtxjA8pmhXfNRIGx8hsEGrn2m3sgbDDqXkZJtIMFwV8Ezliy9hp9g9DKwq918P0X6dDKOPfZb@l8UTwp9pYAHrqWAZSDnbprteEZolA4BtTUZZmp07aZN2Znp0VFIrdL0SGKKc6902sMCKAfP0Nq4yu3W4NH8M/gYHvpTj3TN1W6x/9t9MqlwzZXAe56TGS51hVzySVTTfAM "Taxi – Try It Online") This program uses **Firemouth Grill** to hold thousands of "Minecraft" and "Minceraft" strings to choose from randomly. Here is the basic control flow of the program: * Pick up the value `1e4` from **Starchild Numerology** to use as a counter. * Declare the value `"Minceraft"` at **Writer's Depot** and go there (but don't pick it up yet). * Repeat these steps: * + Pick up the string currently at **Writer's Depot**, and clone it at **Cyclone**. (Having two strings along for the ride will earn us extra gas money!) * + Take both clones, and drop them off at **Firemouth Grill**. * + Take our counter, and drop it off at **The Underground**. One of two things will happen: * + - A passenger will be left waiting, which was 1 less than our previous counter. Pick up this new counter, and declare the value `"Minecraft"` at **Writer's Depot** and go there. At this point, repeat the previous steps. * + - No passenger will be left waiting, which means that our counter is now 0 and we are done. * Go to **Firemouth Grill**, and pick up a passenger. It will most likely be `"Minecraft"`, but there's a 1/10000 chance it will be `"Minceraft"`. * Drop off this passenger at the **Post Office**, outputting the string and (for purposes of Code Golf) ending the program. # [Taxi](https://bigzaphod.github.io/Taxi/), 849 bytes ``` Go to Fueler Up:W 1 R.Switch to plan B.[A]Go to Fueler Up:E 2 L.[B]Go to Heisenberg's:N 3 R 1 L.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L 3 L.Pickup a passenger going to Magic Eight.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 R 3 R 1 R.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:N 1 R.2e4 is waiting at Starchild Numerology.Go to Starchild Numerology:N 1 R.Pickup a passenger going to Magic Eight.Go to Magic Eight:W 1 R 2 R 1 R.Switch to plan A if no one is waiting.Pickup a passenger going to The Underground.Go to The Underground:E 2 L.Switch to plan C if no one is waiting.Minecraft is waiting at Writer's Depot.[C]Minceraft is waiting at Writer's Depot.Go to Writer's Depot:N 3 L 2 L.Pickup a passenger going to Post Office.Go to Post Office:N 1 R 2 R 1 L. ``` [Try it online!](https://tio.run/##nVLLboMwEPyVveVmqbSn3BJK2wNJI9IoB5SDaxazKrWpMUrz9dQEVyIooo@jZ3dm1rtj@Se17aMGq@GhwRIN7Kr5Hm4gYdsjWVF0larkCpYsXRzGnREEELN06QtPSDWqVzRyVs/XcAuJU4rZhsRbUwGHiteuLh1XalKyo4QnUWqFrBfwL8d1PMef5q64JAERycL@0yPxMyaT/Oij4eWshlAbheYvrb3jJdgbswDvgGo4crIdl1vYWm5EQWUG6@YdjS61PHmFayWv89sF9UIDpD@zO2By7dwLoByUBrepwZiTbi8Fwk5l7vpGNyrzjiPUR2bkFl53W5FCYXhuR5vaG7Jo3EbvsdKWpeHBdQr8ubMf6RI8BzU@TzX1u42uLTznOYnvIA0QH6bAB75tvwA "Taxi – Try It Online") This was my first instinct. It also uses **Heisenberg's** to generate a random integer within the range \$[0, 2 \times 10000)\$, but it does so by repeatedly generating a random number until it is within this range. The taxi has to stop at **Fueler Up** to refill its gas tank, and it has to clone passengers at **Cyclone** and drop the clones off at **Equal's Corner** to make enough money to re-generate random numbers for as long as necessary, but otherwise, the functionality is the same as the 632-byte program. It doesn't depend on the specifics of C++, but it *does* usually take longer to execute, because generating a small enough random number is rarer. If anyone can improve this one, be my guest. [Answer] # [Clojure](https://clojure.org/), 42 bytes ``` #(str"Min"(if(<(rand)1e-4)"ce""ec")"raft") ``` [Try it online!](https://tio.run/##S87JzyotSv2vUVCUmVeioPFfWaO4pEjJNzNPSSMzTcNGoygxL0XTMFXXRFMpOVVJKTVZSVOpKDGtREnzv6bmfwA "Clojure – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~45~~ ~~44~~ 43 bytes ``` `if`(runif(1)<1e-4,"Minceraft","Minecraft") ``` [Try it online!](https://tio.run/##K/r/PyEzLUGjqDQvM03DUNPGMFXXREfJNzMvObUoMa1ECcxOTQazNf//BwA "R – Try It Online") Boring, but shorter than any more-interesting attempt that I've tried so far... --- # [R](https://www.r-project.org/), 42 bytes ~~(p=0.000101)~~ p=1 in 10000.5 *Edit: much closer to exactly 1 in 10000 (for the same bytes) thanks to Robin Ryder* ``` `if`(rexp(1)>1e-4,"Minecraft","Minceraft") ``` [Try it online!](https://tio.run/##K/r/PyEzLUGjKLWiQMNQ084wVddER8k3My81uSgxrUQJzE5OBbM1//8HAA "R – Try It Online") Outputs "Minecraft" if an exponentially-distributed random variable is greater than 1e-4. The exponential distribution is governed by a parameter - lambda - that defaults to 1 in the [R](https://www.r-project.org/) `rexp()` function. This gives cumulative p(up to x)=1-exp(-lambda\*x), equal to 9.9995e-05 with x=1e-4 and lamda=1, which is pretty close to 1 in 10000 (actually 1 in 10000.5). [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes ``` MinPceraft¿‽×χφec ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJNzNPSdOay7c0pySzACKUnFqUmFYCEs1MU9AISsxLyc/VCMnMTS3WMDTQUTA0MDDQ1NRUgBqQmgxU@f//f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` Min ``` Print `Min`. ``` Pceraft ``` Print `ceraft` without moving the cursor. ``` ¿‽×χφ ``` If a random number in the range `[0..10000)` is nonzero, then... ``` ec ``` ... correct it to `ec`. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 29 bytes ``` ce9999*$(ec L@$`.. Min$&raft ``` [Try it online!](https://tio.run/##K0otycxLNPz/nys51RIItFQ0UpO5fBxUEvT0uHwz81TUihLTSv7/BwA "Retina – Try It Online") Explanation: ``` ce9999*$(ec ``` Insert `ce` and `9999` copies of `ec`. ``` L@`.. ``` Select one of the pairs of letters at random.... ``` L$` Min$&raft ``` ... and wrap it between `Min` and `raft`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` ’£Ì³±’œ4°LΩΘ5!*è™ ``` [Try it online!](https://tio.run/##ASoA1f9vc2FiaWX//@KAmcKjw4zCs8Kx4oCZxZM0wrBMzqnOmDUhKsOo4oSi//8 "05AB1E – Try It Online") ``` ’£Ì³±’ -- "minecraft" œ -- permutations: ["minecraft", "minecratf", ...] 4°LΩ -- random integer in the range 1..10000 Θ -- 1 if it’s equal to 1, 0 otherwise 5!* -- multiply by 5! (120) è -- index into the list of permutations ™ -- titlecase ``` [Answer] # APL, 26 bytes ``` 'Min','raft',⍨'ec'⌽⍨1=?1E4 ``` Saved 1 byte thanks to Adam [Answer] # Minecraft, 226 bytes. ``` /scoreboard objectives add d dummy /scoreboard players set c d 2147054151 /execute store result score s d run seed /execute if score s d < c d run tellraw @s "Minecraft" /execute if score s d >= c d run tellraw @s "Minceraft" ``` (Includes a trailing newline, to run the final command) I saw [the other Minecraft answer](https://codegolf.stackexchange.com/a/224504/110376) by [Okx](https://codegolf.stackexchange.com/users/26600/okx) and had some suggestions. I would've put them in the comments of the other response, but I figured I changed it enough for its own submission, and [another CGSE member said it's fine](https://chat.stackexchange.com/transcript/message/63155893#63155893) so whatever. I'm only just now noticing the only change I made was using /seed. Ah, well. The things you learn when you have five ideas for improvements and four of them don't work. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 38 bytes ``` "Min$(('ec','ce')[!(random 1e4)])raft" ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/X8k3M09FQ0M9NVldRz05VV0zWlGjKDEvJT9XwTDVRDNWsygxrUTp/38A "PowerShell – Try It Online") [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 80 bytes ``` iMin<Esc>:r!echo $RANDOM C<c-r>=<c-r>"%10000 <esc>:s/^0\n/ce :s/\d\+/ec kgJAraft ``` [Try it online!](https://tio.run/##K/v/P9M3M8/GtTjZzqpIMTU5I19BJcjRz8Xfl8vZJlm3yM4WTCqpGhoAAZdNKkhhsX6cQUyefnIqF5AZkxKjrZ@azJWd7uVYlJhW8v//f90yAA "V (vim) – Try It Online") Generate a random no. in 0-9999, and then replace 0 with ce and anything else with ec. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 bytes ``` “ẹ?ŀɼƲṬ`Ỵȧ»ȷ4XỊịḲ ``` [Try it online!](https://tio.run/##AS4A0f9qZWxsef//4oCc4bq5P8WAybzGsuG5rGDhu7TIp8K7yLc0WOG7iuG7i@G4sv// "Jelly – Try It Online") Full program. -1 byte thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)! ## How it works ``` “ẹ?ŀɼƲṬ`Ỵȧ»ȷ4XỊịḲ - Main link. Takes no arguments “ẹ?ŀɼƲṬ`Ỵȧ» - Compressed string "Minceraft Minecraft"; Call that S ȷ4 - 10000 X - Random integer between 1 and 10000 Ị - Is that equal to 1? Ḳ - Split S on spaces ị - Index into the split S ``` [Answer] # [J](http://jsoftware.com/), 28 25 bytes ``` 'Minecraft'120&A.~0=?@1e4 ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1X0z81KTixLTStQNjQzUHPXqDGztHQxTTf5rcqUmZ@QrpCkA9VOZ9R8A "J – Try It Online") -3 thanks to Bubbler *Note: J does not allow 0-argument functions, but this function ignores it's argument, which is the J equivalent* To see this work, change `1e4` to `2` in the TIO, which will make the letter swap happen 50% of the time. * `0=?@1e4` Does a random number between 0 and 9999 inclusive equal 0? Returns `1` one in 10000 times. * `120&A.` Transposes the requires letters. * Conditional execution at rate according to step 1 happens as a result of the way `&` works when invoked dyadically. ## alternative 1, 27 bytes ``` 4|.'raftMin','ec'|.~0=?@1e4 ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/TWr01IsS00p8M/PUddRTk9Vr9OoMbO0dDFNN/mtypSZn5CukKair/wcA "J – Try It Online") Rotate `|.` the string `'ec'` with probability 1/10k, then append it to the string `'raftMin`, then rotate the result by 4. ## alternative 2, 28 bytes ``` 'Minecraft'C.~3<@,4#~0=?@1e4 ``` [Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1X0z81KTixLTStSd9eqMbRx0TJTrDGztHQxTTf5rcqUmZ@QrpCmoq/8HAA "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~62~~ 61 bytes -1 byte thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! ``` from random import* print'Min%sraft'%'ceec'[random()>1e-4::2] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVqPtm5qkWFyWmlairqienpiarR0OUaWjaGabqmlhZGcX@/w8A "Python 2 – Try It Online") If a probability of \$\left({92 \over 256}\right)^9 \approx 0.0000999841\$ to print *Minceraft* is fine, 59 bytes is possible: ``` import os print'Min%sraft'%'ceec'[max(os.urandom(9))>91::2] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRCG/mKugKDOvRN03M0@1uCgxrURdVT05NTVZPTo3sUIjv1ivtCgxLyU/V8NSU9PO0tDKyij2P1iHgrqqnqFBmrqqhoalkZ6@kamZppaWpeZ/AA "Python 2 – Try It Online") --- # [Python 2](https://docs.python.org/2/), 63 bytes ``` from random import* print'Min%xraft'%(236-30*0**randrange(1e4)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1ehKDEvBUhl5hbkF5VocRUUZeaVqPtm5qlWFCWmlairahgZm@kaG2gZaGmBlAJxeqqGYaqJpub//wA "Python 2 – Try It Online") [Answer] # [Swift](https://developer.apple.com/swift/), ~~55~~ 53 bytes ``` print(.random(in:1...1e4)<2 ?"Minceraft":"Minecraft") ``` [Try it online!](https://tio.run/##Ky7PTCsx@f@/oCgzr0RDrygxLyU/VyMzz8pQT0/PMNVE08ZIwV7JNzMvObUoMa1EyQrETk0GszX//wcA "Swift – Try It Online") This is also my first Code Golf post. Thanks to [@Dingus](https://codegolf.stackexchange.com/users/92901/dingus) for getting taking off 2 bytes! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 18 bytes ``` „ecтnиćRªΩ”–·ÿraft ``` [Try it online!](https://tio.run/##ASkA1v9vc2FiaWX//@KAnmVj0YJu0LjEh1LCqs6p4oCd4oCTwrfDv3JhZnT//w "05AB1E – Try It Online") [Run 10000 times](https://tio.run/##yy9OTMpM/W9oAARu/x81zEtNvtiUd2HHkfagQ6vOrXzUMPdRw@RD2w/vL0pMKwHKzz20Quc/AA) ``` „ec push string "ec" т push 100 n squared, 10000 и repeat, push ["ec"]*10000 ć head extract R reverse ª append Ω choose random element ”–·ÿraft push "Min" + tos + "raft", which is implicitly outputed ``` [Answer] # Mathematica, ~~48~~ ~~44~~ ~~43~~ 41 bytes ``` If[Random[]<.1^4,"Minceraft","Minecraft"] ``` Here's a simple unit test which found a bug in my first version. ``` Table[If[Random[]<.1^4,"Minceraft","Minecraft"], {ix, 10^6}] // Counts ``` And the result: ``` <|"Minecraft" -> 999909, "Minceraft" -> 91|> ``` [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), ~~100~~ ~~97~~ 81 bytes ``` "tfarec"v 77+:v>0#< v*2\_v ?1v0:# ^#< ^-1\$#+ +55:$< |`-1*:*: >:#,_@ |< ^ "Min"< ``` [Try it online!](https://tio.run/##BcE7CoAwDADQPacIjVOrYAURQlAv4A2k/qji4iCaybvX99a4v9cRUzLPvtxxMwpN41jbkgTUVuOk0HktmSCQYCj8mJEDV9ecCeI3F96yZWiZ8qnHTyCgGc7LSEo/ "Befunge-93 – Try It Online") Uses rejection sampling to generate a random integer between 0 and 9999 inclusive, and then swaps the letters if that number is 0. I abused some coincidences that arose in my code to golf it. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~27~~ ~~20~~ 18 bytes ``` `↔ṅ`₴k2ṁċ[`ec`|`ce`]₴`r…ż`, ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJg4oaU4bmFYOKCtGsy4bmBxItbYGVjYHxgY2VgXeKCtGBy4oCmxbxgLCIsIiIsIiJd) Edit: this is actually 7 less bytes, at only 20: ``` k2ṁ[`↓∑ġ¬`|`↔ṅ⇩ṡ…ż`] ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrMuG5gVtg4oaT4oiRxKHCrGB8YOKGlOG5heKHqeG5oeKApsW8YF0iLCIiLCIiXQ==) Edit 2: Thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a?tab=profile), this has been shortened to 18 bytes. ``` k2ṁ[`↓∑ġ¬`|`↔ṅ⇩ṡ…ż ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrMuG5gVtg4oaT4oiRxKHCrGB8YOKGlOG5heKHqeG5oeKApsW8IiwiIiwiMTEiXQ==) [Answer] # [Bash](https://www.gnu.org/software/bash/), 43 bytes ``` x=(ce ec);echo Min${x[RANDOM%9999?1:0]}raft ``` [Try it online!](https://tio.run/##S0oszvj/v8JWIzlVITVZ0zo1OSNfwTczT6W6IjrI0c/F31fVEgjsDa0MYmuLEtNK/v8HAA "Bash – Try It Online") `RANDOM%9999` has a range of [0,9999], and in bash `0` evaluates to false, so the ternary works as expected. Supposedly, the `$RANDOM` function has an "[approximately](https://stackoverflow.com/questions/15939495/is-the-bash-function-random-supposed-to-have-an-uniform-distribution) linear distribution", but I haven't proved that with a million iterations. Hat-tip to the [Zsh solution](https://codegolf.stackexchange.com/a/224552/15940). [Answer] # JavaScript, ~~51~~ 44 bytes ``` _=>`Min${Math.random()*1e4>1?'ec':'ce'}raft` ``` [try it online](https://tio.run/##BcFRDkQwEADQy2zSlqyo@FrKCZyBSU0ZoSPV@Nk4e723wQ2XDXTGr@cZkzNpNN00kP/8B4hrEcDPfEiVaaw73Qu04icsiieAi1NyHCSZsqFWY9VQnivL/uIdi50X6aRS6QU) That's a lotta bytes for such a simple task... *-7 thanks to the OP* [Answer] # [Bash](https://www.gnu.org/software/bash/), 59 bytes ``` printf "%0.sMinecraft\n" {0..9999}|sed '1s/ec/ce/'|shuf -n1 ``` [Try it online!](https://tio.run/##S0oszvj/v6AoM68kTUFJ1UCv2DczLzW5KDGtJCZPSaHaQE/PEghqa4pTUxTUDYv1U5P1k1P11WuKM0rTFHTzDP//BwA "Bash – Try It Online") Change 9999 to 1 to see it work with 50% probability. Repeats the line "Minecraft" 10,000 times. Changes the first line only to "Minceraft". Shuffles the lines randomly and returns the first. [Answer] # [Factor](https://factorcode.org/), ~~40~~ 38 bytes ``` 1e-4 [ "Minceraft"] [ "Minecraft"] ifp ``` [Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnJ@blJmXCBQp1itKzEvJz1XIzFew/m@YqmuiEK2g5JuZl5xalJhWohQL5aYmQ7mZaQX/C4oy80r@AwA "Factor – Try It Online") *-2 bytes thanks to @Bubbler!* Factor has a version of `if` called `ifp` that calls either quotation depending on a probability. There is also an interpolating version that is slightly longer: ``` 1e4 random 1 < "ce""ec"? [I Min${}raftI] ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~35~~ 34 bytes ``` $><<"Min#{rand<1e-4?:ce: :ec}raft" ``` [Try it online!](https://tio.run/##KypNqvz/X8XOxkbJNzNPubooMS/FxjBV18TeKjnVSsEqNbm2KDGtROn/fwA "Ruby – Try It Online") Thanks to Dingus for a saved byte. [Answer] # Excel, ~~41~~ 40 bytes *-1 byte thanks to MarcMush* ``` ="Min"&IF(RAND()<0.1^4,"ce","ec")&"raft" ``` I tried typing 0.0001 as 1E-4 to save two bytes. Excel changes it to 0.0001. ]
[Question] [ # Code-Bowling You've been hired by Brunswick Bowling to create a simple program to output the text `Code Bowling` on their monitors. This company is worth a pretty penny and you feel you can swindle them for quite the *bit* of cash. The job description clearly states that they pay on a scoring basis and you're pretty confident you can manipulate their scoring system to your advantage and get the largest pay check possible from these guys. To do so will require you packing as much *code* as you can into your program/function, even though their scoring system is designed to prevent you from doing so. Get out your piggy banks, let's code! --- # Challenge The challenge is to simply output the text `Code Bowling`, exactly as it is written here, with the highest score possible. *(See section: **Scoring System** below)* Leading and trailing new-lines (line-breaks) are acceptable. Your code may be an entire program or just an executable function. --- # Rules *Obligatory: This challenge is using [Code-Bowling: Common Rules, Revision 1.0.0](http://meta.codegolf.stackexchange.com/questions/11737/code-bowling-index); See Meta for details.* 1. **Character : Byte Ratio** In Code-Bowling a character-count is preferred over a byte-count. The obvious reasoning for this is that multi-byte unicode characters (e.g. 🁴) can be used in place of single-byte unicode characters to fluff up byte count and will make bowling more about who renames the most variables with high-byte unicode characters rather than who most strategically creates meaningful complex code. 2. **Variable/Function/Object Names** All variable names (or object pointers, function names, etc) should be 1 character long. The only acceptable time to use 2-character variables names is after all possible 1-character variables have been used. The only acceptable time to use 3-character variables names is after all possible 2-character variables have been used. Etc. 3. **Un-used Code** All code must be used. Meaning the program must fail to always properly complete the task if any individual character (or varying set(s) of characters) is/are removed. Naturally, a subset of the program should not be able complete the task on its own without the rest of the program. 4. **Comments** Comments are not permitted towards character-count, unless somehow utilized by your program/function. --- # Scoring System: ###   Pangram Challenge: [A pangram](https://en.wikipedia.org/wiki/Pangram) is a sentence that uses every letter at least once. (The quick brown fox jumps over the lazy dog). This challenge-type has a scoring systems designed where a perfect pangram would achieve the theoretical maximum score *(though you are not **required** to use every character at least once.)* Additionally, using any character more than once will start incurring a penalty. This challenge also expands to more than just the alphabetical characters. ###   Scoring Metric: > > 1. Each character used increases your score by 1. > 2. Repeated use of any alphanumeric character (a-z, A-Z, 0-9) will result in a deduction of 3 points per repeat (first use does not > result in a deduction). > 3. Repeated use of basic punctuation `([!?.-,":';])` - including the brackets - will result in a deduction of 2 points per repeat. > 4. Repeated use of other ASCII characters `{`~@#$%^&*_+=|\/><}` - including the curly brackets - will result in a deduction of 4 points > per repeat. > 5. Use of spaces, tabs, and newlines will result in a deduction of 1 point per use. That is, they do not count towards > character total. > 6. Characters not mentioned above *(Exotic Characters)* will result in a deduction of 1 point per use. That is, they do not count towards > character total. > > > ###   Scoring Tool: An **automated** scoring widget has been created and can be found [**here**.](http://jsfiddle.net/96q4q22y/2/) --- This is a [code-bowling](/questions/tagged/code-bowling "show questions tagged 'code-bowling'") variant. The program with the highest score wins! (Since there is a maximum score of `94`, whoever reaches it first (if it can be reached) will be marked as the accepted answer, though others are free to keep answering for fun) [Answer] # Python 3, ~~82~~ ~~87~~ 88 *Thanks to @JonathanAllan for +1 score* ``` print("g!#$%&'*n+,./012i34579;<l=>?@ADEwFGHIJKLoMNOPQRSBTUVWXYZ ^_`abchejkmqsuvdyz{|}~ \x6f C"[::-8]) ``` [Try it online!](https://tio.run/nexus/python3#@19QlJlXoqGUrqisoqqmrpWnraOnb2BolGlsYmpuaW2TY2tn7@Do4lru5u7h6eXtk@/r5x8QGBTsFBIaFh4RGaUQF5@QmJSckZqVnVtYXFqWUllVXVNbpxBTYZamAAHOStFWVroWsZr//wMA) Nothing special, just slicing and skipping characters. The string is reversed so you can't remove characters and have the original string being printed. [Answer] ## [Glypho](https://web.archive.org/web/20060621185740/http://www4.ncsu.edu/~bcthomp2/glypho.txt), 94 The source file is encoded in [CP437](https://en.wikipedia.org/wiki/Code_page_437). ``` ␀␀!"☺☺#$☻♥♥☻♦♣♦♣%♠♠&•◘•◘'○○(◙♂◙♂♀♪♪♀♫☼♫☼►◄◄►↕↕)*‼¶¶‼§§+,▬↨↨▬↑↓↑↓→←→←∟∟-.↔▲▲↔/▼▼▼⌂Ç⌂Çüééüââ01ää23àååàçêçê4ëë5èïèïîî67ìÄÄì8ÅÅ9ÉÉ:;æÆÆæô<=ôöòòöûùûù>ÿÿÿÖÖ?@ÜÜAB¢££¢¥₧¥₧CƒƒDáíáíóóEFúññúѪѪGººHI¿¿J⌐¬⌐¬K½½½¼¼LM¡««¡N»»»░░OP▒▒QR▓││▓┤╡┤╡S╢╢T╖╕╖╕U╣╣V║╗║╗╝╜╜╝W╛╛╛┐X┐┐Y└└└┴┬┴┬├─├─Z┼┼┼╞╞[\╟╟]^╚╔╔╚╩╦╩╦_╠╠`═╬═╬╧╨╨╧╤╥╥╤a╙╙╙╘╘bc╒╒de╓╓fg╫╪╪╫┘┌┌┘█▄█▄▌hi▌▐j▐▐▀αα▀ßΓßΓπΣπΣkσσσµlµµτmnτΦΘΘΦΩδΩδo∞∞∞φpφφεεqr∩≡≡∩±±st≥≤≤≥u⌠⌠⌠⌡⌡vw÷xy÷≈°°≈∙∙z{·|}·√ⁿⁿ√~²²² ``` [Try it online!](https://tio.run/nexus/glypho#Nc9XbxpBFAXg35Lee@@99957770XEYI3i8IDZWfZdbANmGJKHGNTFLwR0lzJj8t/OH/EubOAznfO3NeZRtjHZsyE1WSzZsOahJ1V1JGDPdzZObCTbC58acStzs5D/Cebj7gN299d2we76OGjBMvprtlEPKDwoQm2YCF8jqzLunryMr9oMcwytBFFHRFosd5GoYW7qw@xJUuhGTDHFc1YBtPpCvnphzfkUIHjUJrSy1dQhjIrV1GSspwk5amouppKVFpDI/TH6yiNrl1HZQpwyuupj/o2UJCCGzdRjjROjqqbt1CV6jTOqdMk/VXdSi0vJpnbtlOCEjt2yrQc5qRlFv68N7umolPR3ZSi314naGLPXmpShdOkiCyq7pNN2dx/QLZk6yBCYVn25pD858WRzuEjMiVLnNRROakCM8KOHYcZZSdOwozB8CvqyECkOnsKIs1OQ5gQorNnIIbZWYgIRLy3AxAJz8A5iF9dRvg8l12AYfRUYZR7m4Dh6@xFGE6XGGSXLkMMsStXIfohDA8fBYhcZ69BJNl1iDBEubd5iBEPH/yDrCdzA8LusdjNWxBRdvsORIzdvQdRgih6SjAsGCGPBVOHGeht6P4DHpjhh1yPz624FX5oyI2ptn3usOqj9ncVWXssa7LWDjx52g64Odfi5NyCW1V9Bn2wo609b2ttza25tRcvoRcQTCl6QVZk5dVrBLMIZjzZNwgle1Ls7TtqvP9ADQR1OSbH@IFus4@fZOPzF9mA3o9vLUXv/yrHVaan/wM "Glypho – TIO Nexus") ### Explanation Glypho is quite useful for challenges like this because it doesn't care about the actual characters being used at all. Instead it looks at each chunk of 4 characters and the command being used is determined by the pattern these four characters make: ``` 0000 n 0001 i 0010 > 0011 \ 0012 1 0100 < 0101 d 0102 [ 0110 + 0111 o 0112 * 0120 - 0121 ] 0122 ! 0123 e ``` That means we can just solve the problem and then fill in unique characters in each quartet with the printable characters and all the repeated ones with some of the "exotic" characters, which are ignored by the scoring. Glypho is sufficiently verbose that a normal handwritten solution contains enough unique characters to fit all the 94 printable ones inside. In fact, I ended up golfing it down until it had exactly 94, just so that I could use unique exotic characters for the repeated ones (hopefully, to make it harder to reduce the program). The shorthand form of the above program is this: ``` 11+d*d*d+d+1+1+dd1+o d+11+d*d1+*1+-+do 11+d*d1+d**do 1+o 11+d*d*d+o <o ddo 11+d*d++o 111++d-<+ddo <-+do <1+1+o 1-+1-+o ``` Where each line prints one of the characters. I've used [this Retina script](https://tio.run/nexus/retina#PYw7DoQwDET7uQVtRpE82TbiIoStTEFD7l@xNhIrR3qZ58@9fXWdfR3Dt7FzluWoOyCYqeEKmOFMCGtKwxhJoSOSwRPC2JINg8GYmonQJdlQA82wJ4Ql0XAkPvct0UsUnYpyFyfi/2ixiJU@8WYvJRNfE4sTPTb@M3x6Ir12pu7PgZ7Xo1MZb/4A) to convert it to Glypho using `0123`. Afterwards, I've just filled in the characters in place of the digits. In theory it might be possible to reduce this further, if someone managed to golf down the shorthand program and then managed to recombine the characters such that the right patterns show up, but I'm not sure how to prove or disprove that this is possible. If anyone manages to form a valid solution from a subset of my program, please let me know so I can delete the answer until it's fixed. Until then, I'll have to assume that this is valid. [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~92~~ 94 **YAY, I DID IT!** `␑` is the *exotic* character `\x11` with decimal value 17. The program exits with an error after printing the result (it's a stack underflow). I had to manage which mirrors and directional commands I used carefully, since I can only use each one once. ``` >"vCoUV␑3`h]Z_X /a[f+ #$%&'r(! .0456~8? :;<=@9l) ABDEFcGe HIJKL* MNOPQ7 RSTWYd bgijk1 mnqst- uwxyz2 {|} , \p^ ``` [**Try it online**](https://tio.run/nexus/fish#@6@goGCnVOacHxomaJyQERsVH8GlAAH6idFp2lzKKqpq6kUailx6BiamZnUW9lxW1ja2DpY5mlyOTi6ubsnuqVwenl7ePlpcvn7@AYHmXEHBIeGRKVxJ6ZlZ2YZcuXmFxSW6XKXlFZVVRlzVNbUKCjoQG2IK4v7/BwA) **The core program:** ``` >"vCoUV␑3`h]Z_X /a[f+ r ! ~ ? 9 ) c e * 7 d 1 - 2 , \p^ ``` **Explanation:** Push the string `vCoUV␑3`h]Z_X >` (execution wraps). Move downward. Reverse the stack and remove the `v`. Push `9` and `c` (12). Multiply to get `108` (`l`). Push `7`. Push `d` (13), subtract `1`, divide by `2` to get `6`. Put `l` at (x,y) of (13,6), which is below the `e`. I could've done this way shorter, but this is lengthened so I have room to put more ASCII characters. Move up into a loop. Push length of stack with `l`. If greater than 14, output character, otherwise create a new stack with top 10 elements, add 15 then reflect execution right then up and output. This is used to prevent the extra spaces and `>` from being printed at the end, as well as turning the random-looking string into what needs to be printed. Continue looping. If any of the lines is shorter (by removing a character), the program will no longer work, either because the vertical parts of the program no longer line up, or because the string to print isn't correct anymore. Attempting to remove a character from in front of each line will change the stack depth and where the `l` is placed, also causing problems. Fish [Answer] # Octave, ~~20~~ ~~21~~ ~~22~~ ~~25~~ ~~27~~ 33 The best I've managed this far is ``` g=@()disp(horzcat([67 9583 -412],'e B',"nvkhmf"+!0)); ``` This creates an anonymous function `f` that takes no input. You can call it `f()`. I'd say the semicolon at the end is necessary, in order to avoid printing of the function body. It is possible this can be improved by combining `eval` and `printf`, but I've tried and failed over and over. This uses all digits once, by exploting the fact that Octave does a `mod(x,256)` operation when implicitly converting numbers to characters. This means that we can use negative numbers, as well as numbers outside the normal `32-126`-range. The following numbers all result in the letter `i` when converted to characters: `... -2455 -2199 -1943 ... 105 361 ...`. Instead of using `'owling'` in the end, we use `"nvkhmf"` and add 1. This creates a vector of integers that are implicitly converted to characters. Instead of `1`, we use `!0` (or `not(false)`. Also, we use `"` instead of `'` to avoid two penalty points. We need to find the set of numbers that gives the lowest score. The string `Code Bowling` result in the following matrix, when we subtract and add -10\*256 - 10\*256. ``` -2493 -2449 -2460 -2459 -2528 -2494 -2449 -2441 -2452 -2455 -2450 -2457 -2237 -2193 -2204 -2203 -2272 -2238 -2193 -2185 -2196 -2199 -2194 -2201 -1981 -1937 -1948 -1947 -2016 -1982 -1937 -1929 -1940 -1943 -1938 -1945 -1725 -1681 -1692 -1691 -1760 -1726 -1681 -1673 -1684 -1687 -1682 -1689 -1469 -1425 -1436 -1435 -1504 -1470 -1425 -1417 -1428 -1431 -1426 -1433 -1213 -1169 -1180 -1179 -1248 -1214 -1169 -1161 -1172 -1175 -1170 -1177 -957 -913 -924 -923 -992 -958 -913 -905 -916 -919 -914 -921 -701 -657 -668 -667 -736 -702 -657 -649 -660 -663 -658 -665 -445 -401 -412 -411 -480 -446 -401 -393 -404 -407 -402 -409 -189 -145 -156 -155 -224 -190 -145 -137 -148 -151 -146 -153 67 111 100 101 32 66 111 119 108 105 110 103 323 367 356 357 288 322 367 375 364 361 366 359 579 623 612 613 544 578 623 631 620 617 622 615 835 879 868 869 800 834 879 887 876 873 878 871 1091 1135 1124 1125 1056 1090 1135 1143 1132 1129 1134 1127 1347 1391 1380 1381 1312 1346 1391 1399 1388 1385 1390 1383 1603 1647 1636 1637 1568 1602 1647 1655 1644 1641 1646 1639 1859 1903 1892 1893 1824 1858 1903 1911 1900 1897 1902 1895 2115 2159 2148 2149 2080 2114 2159 2167 2156 2153 2158 2151 2371 2415 2404 2405 2336 2370 2415 2423 2412 2409 2414 2407 2627 2671 2660 2661 2592 2626 2671 2679 2668 2665 2670 2663 ``` So, `['',2627 2415 2148 1893 -2528 66 -1169 -1161 2668 105 -146 103]` results in `ans = Code Bowling`. The challenge is then to find the set of numbers and characters that reduces the score the most. Using all digits is of course good, but duplicates are bad. Since all digits are used, and non are used twice, this is the best possible mix. Also, we get to use `-`, resulting in one point. One could claim that it can be reduced to the line below (31 points), but then it would no longer be an *"executable function"*, and would therefore have a different functionality. ``` disp(horzcat([67 9583 -412],'e B',"nvkhmf"+!0)) ``` [Answer] # QBasic, 34 This is unformatted code (yay for case-insensitivity). You can run it in [QB64](http://qb64.net) or at [archive.org](http://archive.org/details/msdos_qbasic_megapack) (though note that the latter will format the code as you type it). I *think* I've managed to abide by all the rules. ``` CLS PrINT "C LOcatE 1, 2 : ? CHR$(957-846); "de Bowling ``` The `CLS` is necessary: without it, the `C` is not guaranteed to print at the top left corner of the screen, where it will line up with `ode Bowling`. The `LOcatE` is necessary: without it, `ode Bowling` will be printed on the line below `C`. I don't believe there is any subset of the program (except whitespace) that can be deleted and keep the same output. [Answer] ## C, ~~27~~ 29 *+2 points thanks to @ceilingcat!* ``` f(){char q<:]="Code B\157wling";puts(q);%> ``` [Answer] # [Haskell](https://www.haskell.org/), score ~~21~~ ~~38~~ ~~46~~ ~~47~~ ~~21~~ 70 ``` putStr$toEnum(length"!#%&'*+,-./012345789;<=>?@ADGHIJKLMNOPQRTUVWXYZ[]^_`abcfjkqsvyz{|}~"):"ode B\x6Fwling" ``` [Try it online!](https://tio.run/##y0gszk7Nyfmfm5iZZxvzv6C0JLikSKUk3zWvNFcjJzUvvSRDSVFZVU1dS1tHV0/fwNDI2MTU3MLS2sbWzt7B0cXdw9PL28fXzz8gMCgkNCw8IjIqOjYuPiExKTktK7uwuKyyqrqmtk5J00opPyVVwSmmwsytPCczL13p//9/yWk5ienF/3UjnAMCAA "Haskell – Try It Online") The idea is to get the leading `C` by constructing a string of length 67 which contains all not otherwise used characters and converting the length of this string to a character. I started with `putStr$toEnum(length""):"ode B\x6Fwling"` (`'\x6F'` is hexadecimal for `'\111'` which yields `'o'`) and computed all printable ASCII characters not contained in the program: ``` !#%&'*+,-./012345789;<=>?@ACDGHIJKLMNOPQRTUVWXYZ[]^_`abcfjkqsvyz{|}~ ``` Incidentally there remain exactly 67 printable ASCII characters which can put into the string, and `C` itself which cannot appear in the string because then the program would be reducible to just `putStr"Code B\x6Fwling"`. --- **Previous solution:** (score 21) ``` f|x<-'C'=mapM putStr[(:)x"ode Bowling"] ``` Defines a function `f` which takes no input and prints the string. [Try it online!](https://tio.run/nexus/haskell#@59WU2Gjq@6sbpubWOCrUFBaElxSFK1hpVmhlJ@SquCUX56TmZeuFPs/NzEzT8FWIe0/AA "Haskell – TIO Nexus") [Answer] # JavaScript, 19 ``` prompt('C\157de B\x6fwlin'+"g") ``` Not a very high score. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 94 ``` “!#"$&('*)+-/,13.0456:79<;>=@B?ADFHJLNCPRTEVXZ\G^IKMQ`SWbY[]d_acfhjegliknmprotquvxwy{z}¹|³⁵⁷~°⁹⁻”O%2s8UḄỌ ``` **[Try it online!](https://tio.run/nexus/jelly#AYgAd///4oCcISMiJCYoJyopKy0vLDEzLjA0NTY6Nzk8Oz49QEI/QURGSEpMTkNQUlRFVlhaXEdeSUtNUWBTV2JZW11kX2FjZmhqZWdsaWtubXByb3RxdXZ4d3l7en3CuXzCs@KBteKBt37CsOKBueKBu@KAnU8lMnM4VeG4hOG7jP//9W5vLWNhY2hl)** 105 unique characters, 11 exotics (`“¹³⁵⁷°⁹⁻”ḄỌ`). ### How? Forms the string from 8-bit reversed ASCII where each bit is encoded using the LSB of the Unicode value of a character. ``` “...”O%2s8UḄỌ - Main link: no arguments “...” - the string enclosed ! # " $ & ( ' * ) + - / , 1 3 . 0 4 5 6 : 7 9 < ; > = @ B ? A D F H J L N C P R T E V X Z \ G ^ I K M Q ` S W b Y [ ] d _ a c f h j e g l i k n m p r o t q u v x w y { z } ¹ | ³ ⁵ ⁷ ~ ° ⁹ ⁻ O - cast to ordinal (vectorises) [33,35,34,36,38,40,39,42,41,43,45,47,44,49,51,46,48,52,53,54,58,55,57,60,59,62,61,64,66,63,65,68,70,72,74,76,78,67,80,82,84,69,86,88,90,92,71,94,73,75,77,81,96,83,87,98,89,91,93,100,95,97,99,102,104,106,101,103,108,105,107,110,109,112,114,111,116,113,117,118,120,119,121,123,122,125,185,124,179,8309,8311,126,176,8313,8315] %2 - mod 2 (vectorises) [ 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1] s8 - split into chunks of 8 [[1,1,0,0,0,0,1,0], [1,1,1,1,0,1,1,0], [0,0,1,0,0,1,1,0], [1,0,1,0,0,1,1,0], [0,0,0,0,0,1,0,0], [0,1,0,0,0,0,1,0], [1,1,1,1,0,1,1,0], [1,1,1,0,1,1,1,0], [0,0,1,1,0,1,1,0], [1,0,0,1,0,1,1,0], [0,1,1,1,0,1,1,0], [1,1,1,0,0,1,1]] U - upend (vectorises) [[0,1,0,0,0,0,1,1], [0,1,1,0,1,1,1,1], [0,1,1,0,0,1,0,0], [0,1,1,0,0,1,0,1], [0,0,1,0,0,0,0,0], [0,1,0,0,0,0,1,0], [0,1,1,0,1,1,1,1], [0,1,1,1,0,1,1,1], [0,1,1,0,1,1,0,0], [0,1,1,0,1,0,0,1], [0,1,1,0,1,1,1,0], [1,1,0,0,1,1,1]] Ḅ - binary to int (vectorises) [67, 111, 100, 101, 32, 66, 111, 119, 108, 105, 110, 103] Ọ - to character (vectorises) ['C', 'o', 'd', 'e', ' ', 'B', 'o', 'w', 'l', 'i', 'n', 'g'] - implicit print Code Bowling ``` [Answer] # [Röda](https://github.com/fergusq/roda), 33 ``` {["ode B\x6fwling"]|push chr(3*4+57-2).._} ``` [Try it online!](https://tio.run/nexus/roda#y03MzFOoVkizjflfHa2Un5Kq4BRTYZZWnpOZl64UW1NQWpyhkJxRpGGsZaJtaq5rpKmnF1/7P02h9j8A "Röda – TIO Nexus") I tried to follow all rules. It works by first pushing the string `ode Bowling!` to the stream and then inserting `C`=3\*4+57-2 to the front. [Answer] # Cardinal 20 23 non whitespace characters %#>/NI"CodeB8^o)wl,ing -3 for repeated "o" ``` I >\/N %# "CodeB 8^o ) w l , i n g ``` ## Pointer paths: **Step 1:** Pointer created at % going right **Step 2:** Pointer splits at # to go up, right and down (P1,P2,P3) **Step 3**: P1 Sent right by > P2 Going right P3 Set wait for 3 steps at 8 **Step 4:** P1 Reflected down by \. \ changed to / P2 Set to print mode by " P3 Wait for 2 ticks at 8 **Step 5:** P1 Heading down P2 Print C P3 Wait for 1 tick at 8 **Step 6:** P1 Sent up by ^ P2 Print o P3 Finish wait at continue, pick up ASCII value of " " (32) from ) **Step 7:** P1 Heading up P2 Print d P3 Heading down **Step 8:** P1 Reflected right by \ which was changed to / P2 Print e P3 Print character with ASCII value=32 from , operation **Step 9:** P1 Reflected up by / which is changed to \ P2 Print B P3 Reached end of field and stops **Step 10:** P1 Reflected down by I P2 Reached end of field and stops **Step 11:** P1 Reflected right by / which was changed to \. Changes back to / **Step 12:** P1 Reflected left by N **Step 13:** P1 Reflected down by / **Step 14:** P1 Set to print mode by " **Step 15:** P1 Print o **Step 16:** P1 Print w **Step 17:** P1 Print l **Step 18:** P1 Print i **Step 19:** P1 Print n **Step 20:** P1 Print g **Step 21:** P1 Reaches end of field and stops. [Try it Online](https://tio.run/nexus/cardinal#@6@goODJpWAXo@/HpaqsoOScn5LqxKVgEZfPpaCpUM4FlM7hUtBRyASx8kBE@v//AA) [Answer] # C, 73 *Thanks to @Laikoni!* ``` F(){printf("Code B\157wli%cg",48+strlen("!#$&'*-../2369:<=>?@ADEGHIJKLMNOPQRSTUVWXYZ[]^_`abhjkmquvxyz|~"));} ``` [Try it online!](https://tio.run/##S9ZNT07@/99NQ7O6oCgzryRNQ8k5PyVVwSnG0NS8PCdTNTldScfEQru4pCgnNU9DSVFZRU1dS1dPT9/I2MzSysbWzt7B0cXV3cPTy9vH188/IDAoOCQ0LDwiMio6Ni4@ITEpIys7t7C0rKKyqqZOSVPTuvY/0BqF3MTMPA1NrmouBSAA2m7NVfsfAA) # C, ~~ 31 ~~ ~~ 33 ~~ 35 ``` F(){printf("Code B\157wli%cg",96|0xD+3*4/8);} ``` *Thanks to @ceilingcat and @DLosc for two more points and thanks to @Ørjan Johansen for another two more points!* [Try it online!](https://tio.run/##S9ZNT07@/99NQ7O6oCgzryRNQ8k5PyVVwSnG0NS8PCdTNTldScfSrMagwkXbWMtE30LTuvY/UJ1CbmJmnoYmVzWXAhAAtVtz1f4HAA) [Answer] # Brainfuck: -204 ``` ++++[++++>---<]>.+[--->+<]>+++.-----------.+.--[--->+<]>-.+[->++<]>.-[--->+<]>++++.++++++++.-----------.---.+++++.-------. ``` Well, awful score, but was fun to write. * 122 characters long * repeated alnum: -0 () * repeated punctuation: -134 (--[---].-----------..--[---]-.[-].-[---]..-----------.---..-------.) * repeated other: -192 (+++++++>+>+<>++++>+<>+>++<>>+<>+++++++++++++++++) * whitespace characters: -0 () * exotic characters: -0 () [Answer] ## Batch, 19 characters ``` @echO(Cod%TMP:~5,1% Bowling ``` Starting with Windows Vista, `TMP` begins with `C:\Users\` and therefore `%TMP:~5,1%` is a verbose way of writing `e`, despite requiring a double `%` at -4 penalty. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 94 points ``` ”X1234bcde5fghijk68l9<mn>,o.p|q\/{})r(_-+s=tu*vwxyzAB&YDEFG^HI%$ZK#L@!MNO~PQR`ST':UVW[0];"”€a7ôJCç€? ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcPcCEMjY5Ok5JRU07T0jMysbDOLHEub3Dw7nXy9gprCGP3qWs0ijXhd7WLbklKtsvKKyipHJ7VIF1c39zgPT1WVKG9lHwdFXz//uoDAoITgEHWr0LDwaINYayWg2Y@a1iSaH97i5Xx4OZBp//8/AA "05AB1E – Try It Online") --- ``` - 100 characters long - repeated alnum: -0 () - repeated punctuation: -0 () - repeated other: -0 () - whitespace characters: -0 () - exotic characters: -6 (””€ôç€) Total score: 94 ``` --- Basically converts (The Binary ASCII of Code Bowling): ``` ['1000011', '1101111', '1100100', '1100101', '0100000', '1000010', '1101111', '1110111', '1101100', '1101001', '1101110', '1100111'] ``` Into a string of 1's and 0's, then it replaces each 1 with a letter in the alphabet, and each 0 with a space character or a symbol or a digit. ``` ”X1234bcde5fghijk68l9<mn>,o.p|q\/{})r(_-+s=tu*vwxyzAB&YDEFG^HI%$ZK#L@!MNO~PQR`ST':UVW[0];"” ``` Is the string, where 1's are letters and 0's are symbols, numbers or anything else. We then iterate through, seeing which are alphabetical, pushing 1 for alphabetical 0 for nonalphabetical. We then split into groups of 7, convert back to ASCII and print each character. [Answer] # Java 8, ~~2~~ ~~3~~ ~~5~~ ~~13~~ ~~17~~ ~~18~~ ~~19~~ ~~20~~ ~~21~~ ~~24~~ ~~77~~ 78 points +53 score (24 → 77) thanks to *@Laikoni*. ``` v->(char)"!#$%&'*,/0234689:;<=?@ADEFGHIJKLMNOPQRSTUVWXYZ[]^_`bfjkmpqsuxyz{|}~".length()+"\157de Bowling" ``` 104 characters long - repeated alnum: -15 (`helng`) - repeated punctuation: -10 (`"()""`) - repeated other ASCII: none - whitespace characters: -1 SCORE: 78 [Try it online.](https://tio.run/##Lc/ZVoMwEAbg@z7FiFuiFvcV63bctbhU61KrpiFtQ0NAEtBa8dUxHLmZc2bm4v9@n6SkGkZM@t4gp4IoBXXC5agCwKVmcZdQBm6xAjR0zGUPKGqG3IMUO@aaVcxQmmhOwQUJNcjT6g6ifRJja2x8YnJqemZufmFpeWVtY3PL2a7t7u0fHh2fnJ6dX1zW3avrm9vG3X3z4fHpudV@fXvvdP1BEH2o5Gv4PfrJfi1bMNnTfYRnrZfF1XWPwUH4KYzDyp0iO0o6wmSXhLSQBaYA@se22kBwqR8qzQI7TLQdmZdG0qZIJkLgskiW/wE) --- Old **24 bytes** answer: ``` v->"C\157de Bowlin"+(char)103; ``` 30 characters long - repeated alnum: -3 (`1`) - repeated punctuation: -2 (`"`) - repeated other ASCII: none - whitespace characters: -1 SCORE: 24 [Try it online.](https://tio.run/##LY2xCsIwEIZ3n@LolCAtFhGHooPOdhFc1OFMo6aml9KkEZE@e0yxy8Hd/9/31egxNa2kunoFodFaOKCi7wxAkZPdHYWEclwBjq5T9ADBTkZV4HkRr8MsDuvQKQElEGwg@HSb7C/5al1J2Jm3VpTMmXhix/PFsggAbX/TsT59@RHWRCf7889XQD4JP9bJJjO9y9oYOUaZYNRrzSf3EH4) [Answer] # [;#](https://codegolf.stackexchange.com/q/121921/73884), score -1163 I don't think this would be much competition even if it could compete. ``` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ``` [Try it online!](https://tio.run/##K84o@P/fmnKgzGVNX0AfC@nkLcLWUMMhwzSOBtxiOtpG7xClm33K//8DAA ";#+ – Try It Online") Note: TIO has no ;# interpreter, only ;#+. [Answer] # [stacked](https://github.com/ConorOBrien-Foxx/stacked), 42 ``` (67:43,1 ab)2 9*pf sum 8/0\|>+chr'de Bowling',EPS#` ``` [Try it online!](https://tio.run/nexus/stacked#@69hZm5lYqxjqJCYpGmkYKlVkKZQXJqrYKFvEFNjp52cUaSekqrglF@ek5mXrq7jGhCsnPC/oLTkPwA "stacked – TIO Nexus") [Leaves output on stack.](http://meta.codegolf.stackexchange.com/a/8507/31957) Here's the breakdown: ``` length: 51 repeated alnum: -0 () repeated punct: -4 (',) repeated other: -0 () whitespace characters: -5 ( ) exotic characters: -0 () total score: 42 ``` I could probably make it higher, but it's at 42 soo.... Another contender, 40: ``` (67:43,sum)9 pf 2%MIN 0\|>+chr'de Bowling',EPS#` ``` --- [I used this script for scoring it.](https://gist.github.com/ConorOBrien-Foxx/7b20c8e2f4e864edaa60b57ede39efc8) [Answer] # CJam, score 93 ``` "g!#$&'()n*+/0134i5689:;<l=>?@ADEwFGHIJKLoMNOPQRSBTUVWXYZ [\]^_`aebcfhjkmdqrstuvxpyz{|} C"7~%2,.- ``` [Try it online](http://cjam.aditsu.net/#code=%22g!%23%24%26'()n*%2B%2F0134i5689%3A%3B%3Cl%3D%3E%3F%40ADEwFGHIJKLoMNOPQRSBTUVWXYZ%20%5B%5C%5D%5E_%60aebcfhjkmdqrstuvxpyz%7B%7C%7D%20%20C%227~%252%2C.-) Inspired from [TidB's Python answer](https://codegolf.stackexchange.com/a/112832/7416). Not sure if there's any way to avoid the repetition of the double quotes. **Explanation:** The string contains "Cpde Bowling" in reverse, every 8th character. `7~%` extracts "Cpde Bowling" (`7~` = `-8`) `2,.-` decrements the p character (`2,` = `[0 1]`) [Answer] # [evil](https://esolangs.org/wiki/Evil), -81 Better than Brainfuck! ``` aeeaeuwkaaeeuwygaeaeclaaxjlwalusbdgueuewguwpweewpuuuwuuuwpuweew ``` ## Explanation ``` aeeaeuw //Write 'C' k //Set P[0] to 'C' aaeeuw //Write 'O' y //Set W[0] to 'O' gaeae //Set Accumulator to 'D' claa //Create new Wheel cell at index 0, swap with Accumulator, add 2 xj //Set alternate marker mode and drop marker lwa //Write value of W[0], add 1 lu //Put it back, subtract 1 from Accumulator sb //Go to 'j' if Accumulator != 0 d //Delete W[0] //The above loop writes 'D' and 'E' gueuew //Write ' ' guw //Write 'B' pw //Write 'o' eew //Write 'w' puuuw //Write 'l' uuuw //Write 'i' puw //Write 'n' eew //Write 'g' ``` Submitted because nobody does anything in evil but it's kind of fun. ## Score: Length = 63 ``` a*8 = -24 e*12 = -36 g*2 = -6 l*2 = -6 p*2 = -6 u*12 = -36 w*10 = -30 ``` [Try it online!](https://tio.run/nexus/evil) EDIT: TiO seems to incorrectly handle creation and deletion of new Wheel cells - I've filed a bug report on the subject. It won't work properly on there, but I ran it on my own interpreter and it works and you can trust me so I wouldn't worry about it ;) [Answer] # Perl: 29, 33 ``` $_=OWLING;printf%s,"C\157de".chr(30+8/4).B.lc ``` **Score:** ``` - 46 characters long - repeated alnum: -6 (rc) - repeated punctuation: -6 ("..) - repeated other: -0 () - whitespace characters: -1 ( ) - exotic characters: -0 () Total score: 33 ``` [Answer] # T-SQL, ~~65~~ ~~18~~ 32! points ``` PRINT char(78-9605*43%12) + 'ode Bowling' ``` Inspired by a trick in [Dlosc's QBasic answer](https://codegolf.stackexchange.com/a/112833/70172), I found a way to include all 10 digits and most of the mathematical operators (`%` is remainder/modulo, missing only `/`), mostly via trial and error . I don't *think* there is any way to get a 67 by removing any combination of digits/symbols, but you're welcome to try. **Version 2 (18 points, trivial):** ``` DECLARE @ char(12)='Code Bowling'PRINT @ ``` Not a great score, but this is what my first version simplified to (thanks, MickyT). Everything else I tried (encoding and decoding hex64, picking individual elements out of a string, converting ASCII values, etc) all had too many repeated characters (especially `ECR` and symbols `(),@`) that drive it into the negative. **Version 1 (65 points, invalid):** ``` DECLARE @ char(123)= 'Code Bowling FGHJKMOQSUVWXYZbjkmpqsuvxyz045789 [!?.-":;]{`~#$%^&*_+|\><}' PRINT left(@,LEN(@)/6) ``` I used the length of the string to determine how many characters I use from the left side, so removing any *single* character from the string will drop the integer division result down to 11, outputting only `Code Bowlin`. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), score: 0 ``` [S S T T N _Push_-1_g][S S S T T S N Push_6_n][S S S T N Push_1_i][S S S T S S N _Push_4_l][S S S T T T T N _Push_15_w][S S S T T T N Push_7_o][S S T T S S T T S N _Push_-38_B][S S T T S S T S S S N _Push_-71_space][S S T T T N _Push_-3_e][S S T T S S N _Push_-4_d][S S S T T T N Push_7_o][S S T T S S T S T N _Push_-37_C][N S S N _Create_Label_LOOP][S S S T T S T S S S N _Push_constant_104][T S S S _Add_top_two][T N S S _Print_as_character][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0GBk5NLAUQqgCkwoQBhc8KkQBRQAVQRmKWgAGHCpNAUAg3igglCFHNCTedS4OL6/x8A) (with raw spaces, tabs and new-lines only). Uses [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210) to print the output. The optimal constant `104` is generated by [this Java program](https://tio.run/##fZJda9swFIbv@ysO50pCqclgZcyOKM3YhWHpxZxug1KK7KiJOkf2pJOMMPLbPbm289GN3khI7znP@XxWW3X5vPjZNEWpvIeZMvbPBUC9yUtTgCdF4dpWZgHrILGMnLHL@wdQvDUD6D7Aab8pCSSo@/FD8qIYS@DXqiy1b4XUkl5qF81ufjx@u/ly93kEqfxwlZxSBvOvAw2x058qx1qekWliJu@uxokRos/gmINEHNGoloNX55fvSEMedxlGS03T8OEZP7gDkAzwefV9ZYJSq0JPjVVu13FZfml4crB1klGkf21U6VnNrzG7zTAmLtzRpJY0PPb9bZ6Yi0ptl7RiHCaHSk@S@Kf4E@JJH4@Yo5yGf3MesjuznSe9jqoNRXWohUrLsHOXKAaowCQ0FkUqEGJA8VYvUt6HfU1m5@m/WO0vwtGvUD@jt9jtgG3fkK1yYSqYZSiYnYyvcY4xZsjP16GIh62i6gzVqnymaBWp3DPL@f/mTkIWk/cfwwgDe97vTNc3p2njbLDAW@wq2TdN86laaJhWv8sQ4i8). Since all the characters (except for the `o`) are unique, I couldn't use any duplicates or copies to save bytes (copy the value of `o` would be 1 byte longer than pushing the value of `o` again). **Score:** 117 characters long - 117 whitespace characters = 0 Still better than some of the negative scoring answers. ;) [Answer] # [CJam](https://sourceforge.net/p/cjam), score 47 ``` "'#?GyQ2wE(s6&␟JI!gF$u*Aq;0p4BvOKkHLhM"3/{:i~-z+c}% ``` Hopefully no problems with this... Uses one exotic character (Unit Separator, ASCII 31, represented by `␟`), and one repeated character (`"`). I think it could be made longer still, but I'll leave it as is for now. [Try it online!](https://tio.run/nexus/cjam#@6@krmzvXhloVO6qUWwm7@WpmO6mUqrlWGhtUGDiVObvne3hk@GrZKxfbZVZp1ulnVyr@v8/AA "CJam – TIO Nexus") The program works by taking that long string and splitting it into length-3 substrings. Each substring is then mapped to the block, which converts its characters to their ASCII values, dumps the values on the stack, takes the absolute difference of the second two, adds the result with the first, then converts the final result back to an ASCII character. [Answer] # PHP, 33 points This was quite difficult to come up with. The score may be inproved in the future. ``` <?echo IHASZODECG9F^" '%6z\r+2/.W!"; ``` The newline is assumed to be a Linux-style newline! Windows-style and Old-Mac-Style won't work properly. [Answer] # Ruby, 75 Approximately a port of the Python answer, but Ruby doesn't have that cool step function so I use `gsub` instead. Also I decided to have a little fun with the exotic characters by throwing phrases into Google Translate [Try it online!](https://tio.run/nexus/ruby#AZ8AYP//cHJpbnQiQ2FjaGprbXFceDZmdnl6QURFRmRHSElKS0xNZU5PUFFSU1QgVVZXWFlaMEIyMzQ1ODlbbyE/LTo7XWB3fkBcIyQlXiZsKl8rPXw@PGkg44Kz44O844OJ44K044Or44OVbiAg5Luj56K85L@d6b2h55CDZ866z4nOtM65zrrPjM@CIi5nc3ViIC8oLikuezd9LywnXDEn//8 "Ruby – TIO Nexus") ``` print"Cachjkmq\x6fvyzADEFdGHIJKLMeNOPQRST UVWXYZ0B234589[o!?-:;]`w~@\#$%^&l*_+=|><i コードゴルフn 代碼保齡球 gκωδικός".gsub /(.).{7}/,'\1' ``` [Answer] # USML, 12 or 9 points (non-competing) ``` "Code\tBowling' ``` [Try it online!](https://marksill.github.io/Unnamed-String-Manipulation-Language/?code=%22Code%5CtBowling%27) This answer cheats a bit by abusing how HTML renders. The string actually created by this is `"Code\tBowling "`. Points are lost for repeating the "o" character. For a non-cheatsy answer: ``` "Code Bowling ``` USML is still fairly early in development and is not yet capable of increasing the size of the program any further yet. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 85 ``` Codeha1spqumtr;$"gnilwoB"Sv"ADEFH%IJK2f!OPUzQ0V3XY&*[-|L:]\T`~#x>MR56cGk'?W<()b4j}.{Z_^/978@ ``` [Try it online!](https://tio.run/##Sy5Nyqz4/985PyU1I9GwuKCwNLekyFpFKT0vM6c830kpuEzJ0cXVzUPV08vbKE3RPyC0KtAgzDgiUk0rWrfGxyo2JiShTrnCzjfI1CzZPVvdPtxGQzPJJKtWrzoqPk7f0tzC4f9/AA "Cubix – Try It Online") Cubified with insignificant characters replaced with . ``` C o d e . . . . . . u . . . ; . " g n i l w o B " S v " . . . . . . . . . . . ! . . U . . . . . . . . . . . . L . . \ . . . . . > . R . . . . . . . W < . . . . . . . { . . ^ / . . . @ . . . . ``` I think I have made the path fragile enough that removing characters will break it quite badly. [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgICBDIG8gZCBlCiAgICAgICAgaCBhIDEgcwogICAgICAgIHAgcSB1IG0KICAgICAgICB0IHIgOyAkCiIgZyBuIGkgbCB3IG8gQiAiIFMgdiAiIEEgRCBFIEYKSCAlIEkgSiBLIDIgZiAhIE8gUCBVIHogUSAwIFYgMwpYIFkgJiAqIFsgLSB8IEwgOiBdIFwgVCBgIH4gIyB4Cj4gTSBSIDUgNiBjIEcgayAnID8gVyA8ICggKSBiIDQKICAgICAgICBqIH0gLiB7CiAgICAgICAgWiBfIF4gLwogICAgICAgIDkgNyA4IEAKICAgICAgICAuIC4gLiAuCg==&input=&speed=20) ``` - 92 characters long - repeated alnum: -3 (o) - repeated punctuation: -4 ("") - repeated other: -0 () - whitespace characters: -0 () - exotic characters: -0 () Total score: 85 ``` [Answer] # [Zsh](https://www.zsh.org/) `--nocaseglob`, score 79 ``` >' "%&+,.:<=@ADEGHJKMOQSUVWXYZ^_abfhjkmpqrtuvxyz~'>0 ?()${(#)9}*/PRINTF Code\ Bowling;[!] 1 2 3 4 5 6 7 8 `ls|wc -L` ``` [Try it online!](https://tio.run/##BcHnAoFQGADQ/57iswvZe2TvvTcNKaSLIjJe/TrHUCWsChpQCBTEs6ogyojDtBMsdofb402mM7l8qVytNZrtbn84nkxn88Vmy3J76Xg6X6437f54voyfk/absgRpexNWMvF1@XqDemdUgSLaCSsoIF0@KGJqaV5DAIIQgjBEIAoxiAMjqx@dB6rFYPwH "Zsh – Try It Online") Previous version (score 84): ``` >\";?()/*/PRINTF %s g${9:8|#0} rev <([!-+] A D E G H J K L '&,.=@^_`~1234567MOQSUVWXYZabcfhjkmpqtuxyz nilwoB edoC') ``` [Try it online!](https://tio.run/##BcFVAoJAFADAf0/xTMDC7u7ubkAEFVl1sTCuvs7oWCZY1MCFQEUCh0VJQTxJLUzxNM2wdrbTq7YGJbBikCzvaCzyMXu@hqt4hwQ9N7ocS8hCAYpQhgrUoA4NoGxOdzKzWm9@Xp8/EAyFm@1ufzgaT6Yzjhd28uF4Ol@02/Olg7pXHigH4hblKYaQPw "Zsh – Try It Online") Unfortunately, this wasn't irreducible for a number of reasons. Here is the limit of reducibility: ``` >\";?()/*/PRINTF g$8 rev <([!] A D E G H J K 'nilwoB edoC') ``` [Try it online!](https://tio.run/##qyrO@F@cWqKgm6@Ql5@cWJyanpOf9N8uRsnaXkNTX0s/IMjTL8RNIV3FgqsotUzBRiNaMVbBUcFFwVXBXcFDwUvBW0E9LzOnPN9JITUl31ld8/9/AA "Zsh – Try It Online") [Answer] # [Acc!!](https://github.com/dloscutoff/Esolangs/tree/master/Acc!!), score -197 ``` 119 Write _-52 Write _-8 Count i while i-2 { Write _-19+i } 32 Write _ _+34 Write _ _+45 Write _ _+8 Write _ _-11 Write _ Count i while i-2 { Write 105+i*5 } _-5 Write _ ``` [Try it online!](https://tio.run/##S0xOTkr6/9/Q0JIrvCizJFUhXtfUCM604HLOL80rUchUKM/IzElVyNQ1Uqjm4oRJG1pqZ3LVchnDNXDFaxubIHFMTJE4Fgi2rqEhnIPHBkMDU@1MLVOgFUBXwTT8/w8A "Acc!! – Try It Online") *Acc*!! works well for this challenge as whitespace is necessary and loops are costly. I made use of the *Acc*umulator here, but poorly, to increase chars. Here is a brief overview from the page: > > `Accumulator` Any expression standing by itself is evaluated and assigned to the accumulator (which is accessible as `_`). Thus, e.g., 3 is a statement that sets the accumulator to 3; \_ + 1 increments the accumulator; and \_ \* N reads a character and multiplies the accumulator by its charcode. (N gets input) > > > `Write <charcode>` > Outputs a single character with the given ASCII/Unicode value to stdout. The charcode can be any expression. > > > Loops in Acc, at least for golfing, are a pain. They require braces, and all whitespace is necessary. Otherwise it's pretty self-explanatory. ]
[Question] [ > > **Entries are now closed. Any new entries or edits will not be counted in the final run.** > > > ## [Join the chat!](https://chat.stackexchange.com/rooms/81666/art-attack-discussion) ## Challenge Try to fill the canvas with as much paint as possible. Be careful of other bots that may paint over your hard work though! ***Note:*** In this challenge description, *paint* means to change the colour of the square on the grid and *unpainted* means that the square on the grid has the colour 0 and is not attributed to any of the bots. ## Input Your function will be given four arguments: yourself, the grid, the position of all bots on the grid and game information. ### Myself This is a 1D array which denotes your colour and position on the grid: `[id, xpos, ypos]`. **The top left corner of the grid is the position `(0, 0)`. The position `(1,0)` is to the right of that and the position `(0,1)` is below** Your id is an integer which is synonymous with your colour (see below to find out how your id affects how you paint the grid). Your ID is unique to your bot. ### Grid This is a 2D array which contains integers which tell you what colour each cell is. If the number of a grid cell is `0`, that means that the cell is unpainted. If the number of grid cell is an integer `x`, this means that the cell has been painted by the bot with the ID `x`. To get the colour of the grid at position `(x, y)`, use the array like so: `grid[x][y]`. ### Bots This is an array which contains information about the position of the bots. Each element of the bots array is an array which describes each bot and looks like: `[id, xpos, ypos]`, where `id` is the ID of the bot, `xpos` is the x position of the bot and `ypos` is the y position of the bot. This array includes your own bot's position and id. Eliminated bots will not be included in this array. ### Game Information This is an array containing information about the current game and looks like: `[roundNum, maxRounds]` where `roundNum` is the number of the current round (1-indexed) and `maxRounds` is the number of rounds in the current game. ## Output The output should be a string returned by your function. This is the movement command. The movement command determines your next move. The available commands are: ``` up down left right wait ``` Whenever you move, you paint the square you move to. (see below for more information) Where `wait` means you do not move. (but you paint the square that you stay on) If you try to move outside of the grid, your command will be ignored and you will stay in the same place. ## Painting the grid Whenever you move to a square, you paint it, but there are rules which determine what the colour of that square will be. If the square is unpainted (0), then you simply paint it the same colour as your own ID. However, if the square has been painted previously (non-zero) then the resulting colour of the square will be found according to the following JavaScript code: ``` [botColour, 0, floorColour][Math.abs(botColour - floorColour)%3] ``` This formula is made so as to allow a bot to move over its own colour without repainting it. ## Elimination If, after round 5, you have one or fewer squares painted (the number of squares on the grid which are the same colour as you) then you will be eliminated. This means that you will no longer be in the game and will automatically lose. ## Rules * Your code must a function of the type ``` function(myself, grid, bots, gameInfo) { // Code here return move; } ``` * The grid will be a square of side length \$\text{Number of competing bots} \times 3\$ * To prevent specific bots from being targeting, the bots' IDs will be randomised. * When two bots occupy the same space, the colour of that space will be made unpainted. * Movement is turn-based i.e. during a round, all bots are supplied with identical `grid`, `bots` and `gameInfo` arguments * You may create a maximum of three bots * Bots may work together but must not communicate with each other and will not know each others IDs. The wins will be awarded individually rather than as a team. * You must not create a bot which intentionally targets a single, pre-chosen bot. You may, however, target the tactics of a general class of bots. * Your bot may store data in [`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage). Each bot must use their own data object. If a bot is found to be reading another bot's data (accidentally or on purpose) it will be disqualified until the issue is resolved. * [If your bot uses random numbers, please use `Math.random()`](https://chat.stackexchange.com/transcript/message/46389729#46389729) ## Controller The controller can be found here: <https://gist.github.com/beta-decay/10f026b15c3babd63c004db1f937eb14> Or you can run it here: <https://beta-decay.github.io/art_attack> ***Note:*** I would advise that you do any testing offline (download the controller from the gist) as the webpage is subject to change at any moment. When all of the bots have been added, I will run the 10,000 games with the stripped down controller with no graphical interface. You can run it here: <https://beta-decay.github.io/art_attack/fast> ## Winning The player who has filled the most of the canvas wins the game (a game is 2000 rounds). In the event of a draw, all drawn players win. The player which wins the most out of 10,000 games wins the challenge. The 10,000 games is estimated to be run next Monday (2018-08-27 at 23:00 UTC+1). [Answer] # [Jim](https://chat.stackexchange.com/transcript/message/46303326#46303326) ``` function([mc, mx, my], grid, bots, [round, maxRound]) {const ID = 2; var S = this; const botAm = 3; function log(...args) { //if (round > 1) console.log(ID+" "+args[0], ...args.slice(1)); return true; } if (round == 1) { var all = new Array(bots.length).fill().map((_,i)=>i+1); S.fs = new Array(botAm).fill().map(c => [all.slice(), all.slice(), all.slice(), all.slice()] ); S.doneSetup = false; var center = grid.length/2; // UL=0; DL=1; DR=2; UR=3 S.dir = mx<center? (my<center? 0 : 1) : (my<center? 3 : 2); S.job = 0; S.setupFail = S.finished = false; S.tbotc = undefined; S.botAm = bots.length; S.botEvilness = new Array(bots.length+1).fill(0); S.keys = [[1,1,0,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,0,0], [0,1,1,0,0,1,0,1,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,1,0,1,1,0,0,0,1,1], [1,0,0,1,1,1,1,1,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,1,0]]; /*if (ID == 2) */{ S.chased = 0; S.ignore = []; S.badMoves = 0; S.pastMoves = new Array(100).fill("-1;0"); S.timer = 0; S.jimFn = function([mc, mx, my], grid, bots, [round, maxRound]) { // ---------- BEGIN JIM ---------- \\ var output; var allowRetracing = false; var checkSize = 3; var eatSize = 5; var myScore; var scoreboard; if (grid[mx][my] == 0 && !bots.some(([col, bx, by])=> col != mc && bx==mx && by==my)) return "wait"; // collect those sweet points // rescore every now and then if (S.timer > 200) rescore(); S.pastMoves.push(mx+";"+my); S.pastMoves.shift(); var orth = [[-1,0],[0,-1],[1,0],[0,1]]; if (S.atTarget || S.targetX === undefined || S.targetY === undefined || S.targetX === mx && S.targetY === my || orth.map(([x,y])=>[mx+x,my+y]).filter(c=>get(c)==0 && inbounds(c)).length > 2) { S.atTarget = true; var neighbors = orth .map(([x,y]) => [x+mx, y+my]) .filter(inbounds) .filter(([x,y]) => !bots.some(([bid, bx, by]) => bx==x && by==y)) .map(c=>[c,get(c)]); let test = (neighbors, f, msg) => { return bestOf(neighbors.filter(f).map(c=>c[0])) && log(msg); } if (test(neighbors, ([,c]) => c===0, "good")) return output; if (test(neighbors, ([,c]) => overMap(c, 1) && S.BCs, "sad")) return output; S.atTarget = false; S.targetX = S.targetY = undefined; let bestScore = 7; let bfscore = 0; for (let dist = 4; dist < 8; dist++) { for (let [dsx, dsy, dx, dy] of [[0,-1,1,1], [1,0,-1,1], [0,1,-1,-1], [-1,0,1,-1]]) { for (let i = 0; i < dist; i++) { let cx = dx*i + dsx*dist + mx; let cy = dy*i + dsy*dist + my; if (inbounds([cx, cy]) && grid[cx][cy] === 0 ) { let score = scoreOf(cx, cy, 1, false); if(score>bfscore)bfscore=score; if (score > bestScore) { bestScore = score; S.targetX = cx; S.targetY = cy; } } } } } if (S.targetX) { log("short goto", S.targetX, S.targetY,"(rel",S.targetX-mx, S.targetY-my,") score", bestScore); return to([S.targetX, S.targetY]); } else log("long goto",bfscore); rescore(); return to([S.targetX, S.targetY]); } else log("going to target", S.targetX, S.targetY); return to([S.targetX, S.targetY]); function myScore() { if (!myScore) calculateScoreboard(); return myScore; } function calculateScoreboard() { scoreboard = grid.map(column=> { var arr = new Int16Array(grid.length); column.forEach((c, x) => ( myScore+= c==mc, arr[x] = overMap(c, 1, 0, 0, 0, 5) )); return arr; }); for (let [bc, bx, by] of bots) if (bc != mc) { scoreboard[bx][by] = -100; if (inbounds([bx-2, by])) scoreboard[bx-2][by] = -50; if (inbounds([bx+2, by])) scoreboard[bx+2][by] = -50; if (inbounds([bx, by-2])) scoreboard[bx][by-2] = -50; if (inbounds([bx, by+2])) scoreboard[bx][by+2] = -50; } } function scoreOf (x, y, size, includeEnemies) { if (!scoreboard) calculateScoreboard(); let score = 0; for (let dx = -size; dx <= size; dx++) { let cx = dx + x; if (cx < 1 || cx >= grid.length-1) continue; for (let dy = -size; dy <= size; dy++) { let cy = dy + y; if (cy < 1 || cy >= grid.length-1) continue; let cs = scoreboard[cx][cy]; if (cs > 0 || includeEnemies) score+= cs; } } return score; } function rescore() { // heatmap of best scoring places //log(JSON.stringify(scoreboard)); S.bestScore = -Infinity; var blur = grid.map((column, x)=>column.map((c, y) => { let score = scoreOf(x, y, checkSize, true); if (score > S.bestScore) { S.bestScore = score; S.targetX = x; S.targetY = y; } return score; })); S.atTarget = false; S.timer = 0; S.bestScore = scoreOf(S.targetX, S.targetY, eatSize); S.badMoves = 0; // log("scored to", S.targetX, S.targetY, S.bestScore); } function over(col) { // 1 if overrides happen, -1 if overrides don't happen, 0 if override = 0 let res = Math.abs(mc-col) % 3; return res==1? 0 : res==0? 1 : -1; } function overMap(col, best = 0, good = 0, bad = 0, mine = 0, zero = 0) { // best if overrides happen, bad if overrides don't happen, good if override = 0 let res = Math.abs(mc-col) % 3; return col == 0? zero : col == mc? mine : res==1? good : res==0? best : bad; } function iwin (col) { return over(col) == 1; } function zeroes (col) { return over(col) == 0; } function to([x, y]) { //debugger var LR = x > mx? [mx+1, my] : x < mx? [mx-1, my] : null; var UD = y > my? [mx, my+1] : y < my? [mx, my-1] : null; if (LR && UD) { var LRScore = overMap(LR, 1, 0, 0, 0, 3); var UDScore = overMap(UD, 1, 0, 0, 0, 3); if (LRScore == UDScore) return toPos([LR, UD][Math.random()>.5? 1 : 0]) else if (LRScore > UDScore) return toPos(LR); else return toPos(UD); } else return toPos(LR || UD || [x, y]); } function toPos([x,y]) { if (x > mx) return "right"; if (x < mx) return "left"; if (y < my) return "up"; if (y > my) return "down"; return 'wait'; } function inbounds([x, y]) { // if (x<grid.length && y<grid.length && x>=0 && y>=0) return true; if (x<grid.length-1 && y<grid.length-1 && x>=1 && y>=1) return true; return false; } function get([x,y]) { if (inbounds([x, y])) return grid[x][y]; return 0; } function bestOf (arr) { if (arr.length == 0) return false; var bestScore = -Infinity; var bestPos; for (var [x, y] of arr) { let score = 0; for (var [bcol, bx, by] of bots) { let dist = Math.sqrt((x-bx)**2 + (y-by)**2); let res = over(bcol); let power = res==0? 1 : res==1? 0.4 : 1.4; score+= power * dist; } score-= Math.sqrt((x-S.targetX)**2 + (y-S.targetY)**2); if (S.pastMoves.includes(x+";"+y)) score-= 1000000; if (score > bestScore) { bestScore = score; bestPos = [x,y]; } } if (bestScore < -500000) { if (allowRetracing) log("RETRACING"); else return false; } output = to(bestPos); return true; } } // ---------- END JIM ---------- \\ } } const dirs = ['up','left','down','right']; if (!S.doneSetup && round < 37) { // ---------- HANDSHAKE ---------- \\ let finished = 0; if (round != 1) { for (let id = 0; id < botAm; id++) { let f = S.fs[id]; let remaining = f.map(c=>c.length).reduce((a,b)=>a+b); if (remaining == 1) { finished++; continue; } if (remaining == 0) { // mourn the loss of a good friend finished++; continue; } for (let dir = 0; dir < 4; dir++) { let possible = f[dir]; for (let i = possible.length-1; i >= 0; i--) { let bc = possible[i]; let curr = bots.find(c=>c[0]==bc); let prev = S.pastBots.find(c=>c[0]==bc); if (!curr || !prev) { possible.splice(i,1); continue; } let dx = curr[1]-prev[1]; let dy = curr[2]-prev[2]; let move; if (dy == 0) { if (dx == 1) move = 'right'; else move = 'left'; } else { if (dy == 1) move = 'down'; else move = 'up'; } let omove = rotate(move, dir); let expected = ['down','right'][S.keys[id][round-1]]; // if (id == 0 && dir == S.dir) log(); if (omove != expected) possible.splice(i,1); } } } } S.pastBots = bots; if (finished == botAm) { S.doneSetup = true; S.pastBots = undefined; S.BCs = new Array(botAm).fill().map((_,i) => (S.fs[i].find(c=>c.length > 0) || [-1])[0]); // AKA idtoc S.fighters = S.BCs.slice(0,2); S.ctoid = {[S.BCs[0]]:0, [S.BCs[1]]:1, [S.BCs[2]]:2}; log("identified", S.BCs); if (ID == 2) { log("can beat", bots.filter(c=>S.fighters.filter(b=>Math.abs(b-c[0])%3 != 2).length > 0).map(c=>c[3])); } } else { // log(ID,S.fs); return rotate(['down','right'][S.keys[ID][round]], S.dir); } } if (!S.doneSetup) { // HANDSHAKE FAILED S.setupFail = true; S.BCs=[]; S.fighters = []; S.ctoid = {}; } if (S.pastGrid) for (let [bc, bx, by] of bots) { // calculate bot evilness let prev = S.pastGrid[bx][by]; let fID = S.BCs.indexOf(prev); if (fID === 2) S.botEvilness[bc]+= 10; else if (fID !== -1) S.botEvilness[bc]+= 5; else { let over = Math.abs(bc - prev) % 3; if (over === 0) S.botEvilness[bc]+= 1; else if (over === 1) S.botEvilness[bc]+= 2; } } S.pastGrid = grid; if (ID == 2) return S.jimFn([mc, mx, my], grid, bots, [round, maxRound]); if (S.setupFail || !bots.find(c=>c[0]==S.fighters[1-ID])) return 'wait'; // for my demise // TODO yeah no if (round < 50 || !bots.find(c=>c[0]==S.BCs[2])) return S.jimFn([mc, mx, my], grid, bots, [round, maxRound]); // if Jim's dead or if it's early game, be Jim so others don't win needlessly/scoreboard becomes more clear let tbot = bots.find(c=>c[0] == S.tbotc); // ---------- NEW TARGET ---------- \\ let tried; // { // let scores = S.botEvilness.slice(); // new Array(S.botAm+1).fill(0); // for (let column of grid) for (let item of column) scores[item]++; // log("scores", scores.map((score, id) => [botName(id), score]).sort((a,b)=>b[1]-a[1])); // log("evilness", S.botEvilness.map((score, id) => [botName(id), score]).sort((a,b)=>b[1]-a[1])); // } let makeSureImNotStupidAgain = 0; while ((!S.tbotc || !tbot) && !S.finished) { makeSureImNotStupidAgain++; if (makeSureImNotStupidAgain > 100) { console.log("dzaima is stupid"); S.finished = true; break; } if (!tried) tried = S.BCs.slice(); S.gotoX = S.gotoY = undefined; let scores = S.botEvilness.slice(); // new Array(S.botAm+1).fill(0); for (let column of grid) for (let item of column) scores[item]++; var bbc, bbs=-Infinity; for (let i = 1; i < S.botAm+1; i++) if (scores[i] > bbs && !tried.includes(i)) { bbs = scores[i]; bbc = i; } S.tbotc = bbc; tbot = bots.find(c=>c[0] == bbc); if (!tbot) { tried.push(bbc); } else { S.jobs = [0,0]; let executers = S.fighters.filter(c=>Math.abs(c-bbc)%3 == 1).concat(S.fighters.filter(c=>Math.abs(c-bbc)%3 == 0)); if (executers.length > 1) { S.jobs[S.ctoid[executers.pop()]] = 1; S.jobs[S.ctoid[executers.pop()]] = 2; //S.jobs.forEach((c,id) => c==0? S.jobs[id]=2 : 0); log("targetting", botName(bbc),"jobs",S.jobs); } else { // cry tried.push(bbc); S.tbotc = tbot = undefined; } S.job = S.jobs[ID]; } if (tried.length >= bots.length) { // everyone is dead S.job = 0; S.jobs = new Array(2).fill(0); S.finished = true; break; } } if (tbot && !S.finished) { let [_, tx, ty] = tbot; switch (S.job) { case 1: // follow return to(tx, ty, S.tbotc); break; case 2: // erase let endingClearing = false; if (S.gotoX === undefined || S.gotoX==mx && S.gotoY==my || grid[S.gotoX][S.gotoY] != S.tbotc) { S.gotoX = undefined; var ending = [S.tbotc, ...S.fighters.filter(c=>c != mc)].map(c => bots.find(b=>b[0]==c)).filter(I=>I); search: for (let dist = 1; dist < grid.length*2+2; dist++) { for (let [dsx, dsy, dx, dy] of [[0,-1,1,1], [1,0,-1,1], [0,1,-1,-1], [-1,0,1,-1]]) { for (let i = 0; i < dist; i++) { let cx = dx*i + dsx*dist + mx; let cy = dy*i + dsy*dist + my; if (inbounds(cx, cy)) { if (grid[cx][cy] == S.tbotc && ending.every(([_,bx,by]) => (bx-cx)**2 + (by-cy)**2 > Math.random()*10)) { S.gotoX = cx; S.gotoY = cy; break search; } } } } } if (S.gotoX === undefined) { let available = []; grid.forEach((column, x) => column.forEach((c, y) => c==S.tbotc? available.push([x,y]) : 0)); [S.gotoX, S.gotoY] = available[Math.floor(Math.random()*available.length)]; endingClearing = true; } } return to(S.gotoX, S.gotoY, endingClearing? undefined : S.tbotc); break; case 0: // exercise if (S.gotoX === undefined || S.gotoX==mx && S.gotoY==my || grid[S.gotoX][S.gotoY] != S.tbotc) { let scores = new Uint32Array(S.botAm+1); for (let column of grid) for (let item of column) scores[item]++; var bbc, bbs=-Infinity; for (let i = 1; i < S.botAm+1; i++) if (scores[i] > bbs && Math.abs(mc-i)%3 == 0 && !S.BCs.includes(i)) { bbs = scores[i]; bbc = i; } if (bbc) { S.gotoX = undefined; search: for (let dist = 1; dist < grid.length*2+2; dist++) { for (let [dsx, dsy, dx, dy] of [[0,-1,1,1], [1,0,-1,1], [0,1,-1,-1], [-1,0,1,-1]]) { for (let i = 0; i < dist; i++) { let cx = dx*i + dsx*dist + mx; let cy = dy*i + dsy*dist + my; if (inbounds(cx, cy) && grid[cx][cy] == bbc) { S.gotoX = cx; S.gotoY = cy; break search; } } } } } } if (S.gotoX !== undefined) return to(S.gotoX, S.gotoY); return dirs[Math.floor(Math.random()*4)]; break; } } function to (x, y, col) { if (x == mx&&y== my) return 'wait'; let dx = x - mx ; let dy = y - my ; let ax = Math.abs(dx); let ay = Math.abs(dy); var diag; if ( ax==ay ) { if (col&&ax+ ay==2) { let i=[[x, my], [mx, y]].findIndex(c=>grid[c[0]][c[1]]==col); if (i<0) diag = Math.random()>=.5; else diag = i == 0; } else diag = Math.random()>=.5; } if (ax==ay? diag : ax>ay) { if (dx>0) return 'right'; else return 'left'; } else { if (dy>0) return 'down'; else return 'up'; } } function rotate (move, dir) { if ((move == 'up' || move == 'down') && (dir && dir<3)) { if (move == 'up') return 'down'; else return 'up'; } if ((move == 'left' || move == 'right') && dir>1) { if (move == 'left') return 'right'; else return 'left'; } return move; } function botName(id) { let bot = bots.find(c=>c[0]==id); if (!bot) return id.toString(); return bot[3] + "/" + id; } function inbounds(x, y) { return x<grid.length && y<grid.length && x>=0 && y>=0 } } ``` The simple explanation of the strategy of this bot is as follows: * win [Answer] # Trollbot Picks the closest bot it can paint over and just follows it. If it can't find a valid bot, go to the nearest empty space. If it can't find an empty space, move randomly. Note: Lots of good contributions by Simon ``` function(myself, grid, bots, gameInfo) { var c = myself[0]; var x = myself[1]; var y = myself[2]; var cd = -1; var cx = -1; var cy = -1; var i; for(i = 0; i < bots.length; i++){ var bc = bots[i][0]; var bx = bots[i][1]; var by = bots[i][2]; if (c != bc && Math.abs(c-bc)%3 == 0) { var d = Math.abs(x-bx)+Math.abs(y-by); if (d > 0 && (cd == -1 || d<cd)) { cd = d; cx = bx; cy = by; } } } if (cd == -1) { var j; for(i=0; i<grid.length; i++) { for(j=0; j<grid.length; j++) { if (grid[i][j] == 0) { var d = Math.abs(x-i)+Math.abs(y-j); var sharingWithBot = (i == x && j == y && bots.filter((item) => item[1] == i && item[2] == j).length > 1); if (!sharingWithBot && (cd == -1 || d<cd)) { cd = d; cx = i; cy = j; } } } } } var move; var dx = cx-x; var dy = cy-y; if (cd == -1) { move = ["up","down","left","right"][Math.random() *4 |0]; } else if (dx == 0 && dy == 0) { move = "wait"; } else if (Math.abs(dx) > Math.abs(dy) || (Math.abs(dx) == Math.abs(dy) && Math.random() * 2 < 1)) { if (dx > 0) { move = "right"; } else { move = "left"; } } else { if (dy > 0) { move = "down"; } else { move = "up"; } } return move; } ``` [Answer] ## ¯\\_(ツ)\_/¯ (Random moves) ``` function(myself, grid, bots, gameInfo) { return ["up","down","left","right"][Math.random() *4 |0] } ``` [Answer] # The Bot That Paints The Board Constantly But Is Not A Painter ``` function (me, board, painters, info) { let id = me[0], meX = me[1], meY = me[2], s = board.length, ss = Math.ceil(s / 3), pl = painters.length, r = info[0], storage, sk = 'jijdfoadofsdfasz', s1, s2, scores = [], i, j; let bos = [ [0, 0, ss - 1, ss - 1], [ss, 0, (ss * 2) - 1, ss - 1], [ss * 2, 0, s - 1, ss - 1], [ss * 2, ss, s - 1, (ss * 2) - 1], [ss * 2, ss * 2, s - 1, s - 1], [ss, ss * 2, (ss * 2) - 1, s - 1], [0, ss * 2, ss - 1, s - 1], [0, ss, ss - 1, (ss * 2) - 1], ]; if (r === 1 || typeof this[sk] === 'undefined') { let n = ss + painters[0][1]; s1 = bos[n % 8]; s2 = bos[(n + 1) % 8]; storage = this[sk] = {s1: s1, s2: s2, bs: null, c: 0}; } else { storage = this[sk]; s1 = storage.s1; s2 = storage.s2; } let getDistance = function (x1, y1, x2, y2) { return (Math.abs(x1 - x2) + Math.abs(y1 - y2)) + 1; }; let getColorValue = function (c) { if (c === 0) return 2; if (c === id) return -1; let value = 2 - (Math.abs(id - c) % 3); if (value === 1) return 0.1; return value; }; let getEnemyValue = function (eId) { if (eId === id) return 0; let value = 2 - (Math.abs(id - eId) % 3); return (value === 1 ? 1.75 : value); }; let isInSection = function (x, y, s) { return (x >= s[0] && y >= s[1] && x <= s[2] && y <= s[3]); }; let bs = null; if (storage.bs === null || storage.c <= 0) { let mysi = null; for (i = 0; i < bos.length; i++) { if (isInSection(meX, meY, bos[i])) mysi = i; if ((bos[i][0] === s1[0] && bos[i][1] === s1[1] && bos[i][2] === s1[2] && bos[i][3] === s1[3]) || (r < 5e2 && bos[i][0] === s2[0] && bos[i][1] === s2[1] && bos[i][2] === s2[2] && bos[i][3] === s2[3])) { scores[i] = -100000; } else { scores[i] = 0; for (let bX = Math.max(bos[i][0], 1); bX < Math.min(bos[i][2], s - 1); bX++) for (let bY = Math.max(bos[i][1], 1); bY < Math.min(bos[i][3], s - 1); bY++) scores[i] += getColorValue(board[bX][bY]); for (j = 0; j < pl; j++) { let pId = painters[j][0], pX = painters[j][1], pY = painters[j][2]; if (pId === id || pX === 0 || pX === s - 1 || pY === 0 || pY === s - 1 || !isInSection(pX, pY, bos[i])) continue; scores[i] -= (getEnemyValue(pId) * ss) * 4; } } } let bss = null; for (i = 0; i < scores.length; i++) { if (bss === null || bss < scores[i]) { bss = scores[i]; bs = bos[i]; } } if (mysi !== null && scores[mysi] * 1.1 > bss) bs = bos[mysi]; storage.bs = bs; storage.c = 250; } else { bs = storage.bs; storage.c--; } let getScore = function (x, y) { let score = 0; if (!isInSection(x, y, bs)) score -= s * 10; for (let bX = bs[0]; bX <= bs[2]; bX++) { for (let bY = bs[1]; bY <= bs[3]; bY++) { let distance = getDistance(x, y, bX, bY); let colorValue = getColorValue(board[bX][bY]); let factor = 1; if (distance === 1) factor = 3; else if (distance === 2) factor = 2; score += (colorValue / (distance / 4)) * factor; if (x === meX && y === meY && x === bX && y === bY && colorValue < 2) score -= 1000; } } for (let i = 0; i < pl; i++) { let pId = painters[i][0], pX = painters[i][1], pY = painters[i][2]; if (pId === id || pX === 0 || pX === s - 1 || pY === 0 || pY === s - 1) continue; let pDistance = getDistance(x, y, pX, pY); if (pDistance > 5) continue; let pIdValue = getEnemyValue(pId); let factor = 4; if (pDistance === 1) factor = 8; else if (pDistance === 2) factor = 6; else score -= (pIdValue / pDistance) * factor; } return score + (Math.random() * 10); }; if (isInSection(meX, meY, bs)) { let possibleMoves = [{x: 0, y: 0, c: 'wait'}]; if (meX > 1) possibleMoves.push({x: -1, y: 0, c: 'left'}); if (meY > 1) possibleMoves.push({x: -0, y: -1, c: 'up'}); if (meX < s - 2) possibleMoves.push({x: 1, y: 0, c: 'right'}); if (meY < s - 2) possibleMoves.push({x: 0, y: 1, c: 'down'}); let topCommand, topScore = null; for (i = 0; i < possibleMoves.length; i++) { let score = getScore(meX + possibleMoves[i].x, meY + possibleMoves[i].y); if (topScore === null || score > topScore) { topScore = score; topCommand = possibleMoves[i].c; } } return topCommand; } else { let dX = ((bs[0] + bs[2]) / 2) - meX, dY = ((bs[1] + bs[3]) / 2) - meY; if (Math.abs(dX) > Math.abs(dY)) return (dX < 0 ? 'left' : 'right'); else return (dY < 0 ? 'up' : 'down'); } } ``` This bot tries to find the best area of the board and moves there. Then tries to make the best decision possible by generating a score for each possible move in that area. The best area keeps getting re-selected on some intervals and the bot moves to a new better area if needed. This bot has a few other details that I might explain later. [Answer] # MC ``` function (myself, grid, bots, gameInfo) { "use strict"; if (this.O == null) this.O = {}; const O = this.O; // console.log(this); const MAXBOTS = 60; const MAXSZ = 3 * MAXBOTS; const MAXID = MAXBOTS + 1; if (gameInfo[0] == 1) { if (bots.length > MAXBOTS) { alert("ASSERTION FAILED: MAXBOTS EXCEEDED (contact @tomsmeding)"); return 0; } for (const b of bots) { if (b[0] < 0 || b[0] > MAXID) { alert("ASSERTION FAILED: MAXID EXCEEDED (contact @tomsmeding)"); return 0; } } } function from_base64(bs) { if (bs.length % 4 != 0) throw new Error("Invalid Base64 string"); const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const beta = new Array(256).fill(-1); for (let i = 0; i < alpha.length; i++) beta[alpha.charCodeAt(i)] = i; const arrbuf = new ArrayBuffer(bs.length / 4 * 3 | 0); const buf = new Uint8Array(arrbuf); let j = 0; for (let i = 0; i < bs.length; i += 4) { buf[j++] = (beta[bs.charCodeAt(i+0)] << 2) | (beta[bs.charCodeAt(i+1)] >> 4); if (bs[i+2] == "=") break; buf[j++] = (beta[bs.charCodeAt(i+1)] << 4) | (beta[bs.charCodeAt(i+2)] >> 2); if (bs[i+3] == "=") break; buf[j++] = (beta[bs.charCodeAt(i+2)] << 6) | (beta[bs.charCodeAt(i+3)] >> 0); } return new Uint8Array(arrbuf, 0, j); } function repeat(str, times) { return new Array(times + 1).join(str); } function println_func(ptr) { let s = ""; for (; ptr < O.wa_membuf.length; ptr++) { if (O.wa_membuf[ptr] == 0) break; s += String.fromCharCode(O.wa_membuf[ptr]); } console.log(s); } function print_int_func(value) { console.log(value); } function seed_random() { for (let i = 0; i < O.wa_rand_state.length; i++) { O.wa_rand_state[i] = (Math.random() * 256) & 0xff; } } function transfer_myself(myself) { O.wa_my_id[0] = myself[0]; } function transfer_grid(grid) { const W = grid.length, H = grid[0].length; O.wa_width[0] = W; O.wa_height[0] = H; for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { O.wa_grid[W * y + x] = grid[x][y]; } } } function transfer_bots(bots) { O.wa_nbots[0] = bots.length; for (let i = 0; i < bots.length; i++) { O.wa_bots[3 * i + 0] = bots[i][0]; O.wa_bots[3 * i + 1] = bots[i][1]; O.wa_bots[3 * i + 2] = bots[i][2]; } } function transfer_gameInfo(gameInfo) { O.wa_round_idx[0] = gameInfo[0]; O.wa_total_rounds[0] = gameInfo[1]; } function stringify(thing) { if (Array.isArray(thing)) { return "[" + thing.map(stringify).join(",") + "]"; } else if (thing instanceof Int8Array) { return "[" + thing.toString() + "]"; } else { return thing.toString(); } } function mc_calcmove() { // console.log("mc_calcmove(" + stringify(myself) + "," + stringify(grid) + "," + stringify(bots) + "," + stringify(gameInfo) + ")"); transfer_myself(myself); transfer_grid(grid); transfer_bots(bots); transfer_gameInfo(gameInfo); return ["right", "down", "left", "up", "wait"][O.wa_mc_calcmove()]; // return O.wa_mc_calcmove(); } if (O.wasm_bytes == null) { O.wasm_bytes = from_base64( // INSERT-WASM-HERE "AGFzbQEAAAABCgJgAX8Bf2ABfwACNgMDZW52D19fbGluZWFyX21lbW9yeQIADwNlbnYHcHJpbnRsbgABA2VudglwcmludF9pbnQAAQMCAQAHDAEIZW50cnlfZm4AAgqwEQGtEQIvfwF+QX8hEAJAAkACQAJAIABBAUwEQCAARQ0BIABBAUcNA0EADwsgAEECRg0BIABBh63LAEcNAkEkEABBKhABQX8PC0EEQSw2AgBBAEEoNgIAQQhBMDYCAEEMQTQ2AgBBEEE4NgIAQRRBPDYCAEEYQcAANgIAQRxB0P0BNgIAQSBBkP8BNgIAQQAPC0E8KAIAIQ9BfyEBAkBBMCgCACIRQQFIIiENAEEAIQFB0P0BIQADQCAPIAAtAABGDQEgAEEDaiEAIAFBAWoiASARSA0AC0F/IQELIBFBA2wiEkEIbSIcQQN0IRMgEiATayEiQSwoAgAiHUEoKAIAIhRsIglBCG0iHkEDdCEVIAkgFWshIyAPQf8BcSEaIAFBA2wiAEHY9zlqIgJBAmohJCACQQFqISUgHUF/aiEmIBRBf2ohJyABQQJ0Qaj2O2ohHyATQdj3OWohKCATQYj5N2ohKSAAQdL9AWotAAAhKiAAQdH9AWotAAAhKyAVQZj5OWohLCAVQcj6N2ohLUF/IRYDQAJAIApBAnQiAEGw/wFqKAIAICtqIgJBAEgNACAAQdD/AWooAgAgKmoiAyAdTg0AIAIgFE4NACADQQBIDQAgCUEISCIFRQRAQQAhACAeIQEDQCAAQZj5OWogAEFAaykDADcDACAAQQhqIQAgAUF/aiIBDQALCyAVIgAgCU4iBEUEQANAIABBmPk5aiAAQUBrLQAAOgAAIAkgAEEBaiIARw0ACwsgE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gQR8wMJ+gQR/AMJhwURiQQJlQURjAQJxQURjgQJzQURlwQJ2AURnAQJ4wURoQQJ7gURowQJ+QURqAQJhAYRrgQJjwYRtAQJmwYR0QMJqAYR0QMJuwYRuQQJxwYRxQQJ0gYRtAIJ3gYRywQJ5gYR0QQJ8QYRtwIJ/AYRuQIJhwcRtAIJkwcR1AQJoAcR0QQJrAcRtAIJuAcR4gQJxQcR5QQJ0wcR6QQJ3AcR0QQJ6AcR+AQJ9AcRsgMJgAgR+wQJjAgRhwUJmAgR/AMJpAgRkwUJsAgRnwUJvAgRqAUJyAgRuwUJ1QgR0QMJ4wgR0QMJ8AgR5QQJ/AgRzQUJiAkR3QUJlQkR6AUJuwkR1wUJwgkR7AUJzgkR8wUJ2QkR+QUJ5AkR+wUJ9QkR/QUIgQoAAAmJChGCBgmVChGLBgmlChQACbEKFBgJ3woSAAnoChIqCfEKEj8J+goUwAAJ/woSFQmJCxSIFQmOCxLUAAmXCxSYEwmrCxLSAQi4CwCQBQjJCwCQBQnSCxLpAAjcCwDUBQjwCwCIBgiLDACIBgmUDBL+AAieDADMBgiyDACHBwnRDBS4AgjjDADeBwj0DADeBwn9DBKTAQiHDQCeCAibDQDZCAmnDRKoAQiwDQDZCAm5DRK9AQnEDRS4EQnJDRLnAQnSDRTYDwnfDRL8AQjsDQCfCQj9DQCfCQmGDhKRAgiQDgDhCQmgDhT4DQmlDhKmAgmyDhTQAgjYDgC+CgnhDhK7AgnrDhSYDAnwDhLQAgn5DhS4CgmDDxT4BwmRDxS4BAmdDxSYBgm1DxTYCQnBDxSICgjYDwCCEQj3DwCCEQiSEACVEgmbEBLyAgmtEBSAFwm5EBSYFwAYEXJlbG9jLi5kZWJ1Z19saW5lCwEIKwAA" ); // require("fs").writeFileSync("reverse-base64-output.txt", Buffer.from(O.wasm_bytes)); O.memory = new WebAssembly.Memory({initial: 15}); // O.importObject = {js: {mem: O.memory}, env: {println: println_func}}; O.importObject = { env: { println: println_func, print_int: print_int_func, __linear_memory: O.memory, __indirect_function_table: new WebAssembly.Table({initial: 0, element: "anyfunc"}), }, }; // let wa_membuf, wa_width, wa_height, wa_nbots, wa_round_idx, wa_total_rounds, wa_my_id, wa_grid, wa_bots, wa_rand_state; /*const promise = fetch('../out/main.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, O.importObject) );*/ // const promise = WebAssembly.instantiate(fs.readFileSync("hotpatcher/out.wasm"), O.importObject); const promise = WebAssembly.instantiate(O.wasm_bytes, O.importObject); promise.then(results => { const instance = results.instance; // console.log(instance.exports); // First set some pointers instance.exports.entry_fn(0); O.wa_membuf = new Uint8Array(O.memory.buffer); const ptrs = new Uint32Array(O.memory.buffer, 0, 9 * 4); O.wa_width = new Int32Array(O.memory.buffer, ptrs[0], 1); O.wa_height = new Int32Array(O.memory.buffer, ptrs[1], 1); O.wa_nbots = new Int32Array(O.memory.buffer, ptrs[2], 1); O.wa_round_idx = new Int32Array(O.memory.buffer, ptrs[3], 1); O.wa_total_rounds = new Int32Array(O.memory.buffer, ptrs[4], 1); O.wa_my_id = new Int32Array(O.memory.buffer, ptrs[5], 1); O.wa_grid = new Uint8Array(O.memory.buffer, ptrs[6], MAXSZ * MAXSZ); O.wa_bots = new Uint8Array(O.memory.buffer, ptrs[7], MAXBOTS * 3); O.wa_rand_state = new Uint8Array(O.memory.buffer, ptrs[8], 5 * 4); O.wa_mc_calcmove = function() { return instance.exports.entry_fn(2); } seed_random(); // Signal that we're done setting up, and the wasm code can set itself up instance.exports.entry_fn(1); O.instantiated = true; console.log("MC: Instantiated!"); }).catch(console.error); } if (gameInfo[0] > 5) { if (O.instantiated) { // const start = new Date(); const output = mc_calcmove(); // const end = new Date(); // if (O.time_sum == null) O.time_sum = 0; // O.time_sum += end - start; // if (gameInfo[0] % 50 == 0) { // console.log("Average time taken: " + O.time_sum / (gameInfo[0] - 1)); // } return output; } else { throw new Error("SCREAM FIRE wasm instantiation"); } } else { console.log("MC: RANDOM MOVE BEFORE INSTANTIATE"); return ["right", "down", "left", "up"][Math.random() * 4 | 0]; } } ``` Monte Carlo bot. For each of the five possible moves, it does 100 random playouts, where a "playout" here is 5 random moves from everybody. Only 5 because stuff is unpredictable anyway. At the end of each playout, the bot's score is calculated. The move with the best playout results is taken. This bot is coded in WebAssembly. See [my P bot](https://codegolf.stackexchange.com/a/171243/6689) for a description. [Answer] ## Leonardo da Pixli ``` function(myself, grid, bots, gameInfo) { var ME = this; var w='up',a='left',s='down',d='right'; var ps = [ [ // Castlevania Simon Belmont 16,30,0,11, [s,s,d,s,d,d,w,w,d,d,s,a,s,d,d,s,d,s,s,a,s,a,a,s,a,s,s,a,s,s,s,s,s,s,s,a,a,s,s,d,w,d,s,d,d,d,w,w,a,s,a,w,w,d,w,d,w,a,a,s,w,w,w,d,s,d,w,w,a,d,d,w,d,w,d,s,d,s,s,d,s,d,s,d,s,s,s,s,a,s,d,d,d,d,w,a,a,w,d,d,w,a,a,w,d,d,w,a,a,w,d,a,w,a,s,a,w,w,a,d,d,w,w,w,w,a,a,a,a,s,a,w,w,d,d,d,d,d,d,s,w,w,a,a,a,a,a,w,d,d,d,d,w,a,a,a,a,a,a,w,d,d,d,d,d,d,d,w,a,a,a,a,a,a,w,d,d,d,d,d,d,d,d,w,w,s,s,a,a,w,a,a,a,a,a,a,w,w,a,s,a,a,s,a,a,a,d,d,s,d,w,w,d,d,d,d,d,d,d,d,w,d,d,a,w,w,a,s,a,s,a,a,a,w,a,w,d,d,s,d,w,d,w,d,a,a,a,a,a,s,a,a,s,a,a,w,w,w,d,a,w,w,d,w,d,s,d,s,s,d,d,d,w,a,a,w,d,a,w,a] ], [ // Final Fantasy White Mage 17,25,2,10, [a,w,a,w,w,w,d,w,d,w,d,w,d,d,w,d,d,w,d,d,d,w,d,d,d,d,d,s,d,s,s,s,s,s,a,a,w,a,w,s,d,s,d,s,s,s,s,a,s,s,a,d,s,d,s,d,s,s,s,s,s,s,s,s,s,a,s,a,a,w,w,s,a,s,a,a,w,w,w,s,a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,d,s,d,s,s,d,s,s,a,w,a,s,a,a,d,w,w,a,d,d,w,a,w,a,s,a,w,w,d,a,a,s,a,w,w,d,a,a,a,a,s,a,s,a,d,d,d,w,d,s,s,a,a,a,a,s,a,s,d,d,w,d,d,a,s,s,d,d,s,s,d,d,d,w,w,w,a,a,a,s,a,a,a,a,a,s,s,d,s,s,d,s,d,d,s,d,d,d,d,d,w,d,d,w,d,w,w,d,w] ] ]; if(ME.c === undefined){ ME.c = 9999; ME.t = []; ME.n = Math.floor(Math.random()*Math.floor(ps.length)); } if(gameInfo[0] == 1 && myself[1] < grid.length-ps[ME.n][0]+ps[ME.n][2] && myself[1] > ps[ME.n][2] && myself[2] < grid.length-ps[ME.n][1]+ps[ME.n][3] && myself[2] > ps[ME.n][3]){ ME.c = 0; } if(ps[ME.n][4][ME.c] !== undefined){ return ps[ME.n][4][ME.c++]; } else if(ME.c < 9999){ ME.c = 9999; ME.n = Math.floor(Math.random()*Math.floor(ps.length)); } if(ME.t.length == 0){ var rand = [ [parseInt(Math.random()*(grid.length-ps[ME.n][0]))+ps[ME.n][2],parseInt(Math.random()*(grid.length-ps[ME.n][1]))+ps[ME.n][3]], [parseInt(Math.random()*(grid.length-ps[ME.n][0]))+ps[ME.n][2],parseInt(Math.random()*(grid.length-ps[ME.n][1]))+ps[ME.n][3]], [parseInt(Math.random()*(grid.length-ps[ME.n][0]))+ps[ME.n][2],parseInt(Math.random()*(grid.length-ps[ME.n][1]))+ps[ME.n][3]] ], colorable = [0,0,0], i, j, k; for(i=0;i<rand.length;i++){ for(j=rand[i][0]-ps[ME.n][2];j<rand[i][0]-ps[ME.n][2]+ps[ME.n][0];j++){ for(k=rand[i][1]-ps[ME.n][3];k<rand[i][1]-ps[ME.n][2]+ps[ME.n][1];k++){ if(grid[j][k] == 0 || (grid[j][k] != myself[0] && grid[j][k]%3 == 0)){ colorable[i]++; } } } } if(colorable[0] >= colorable[1] && colorable[0] >= colorable[2]){ ME.t = [rand[0][0],rand[0][1]]; } else if(colorable[1] >= colorable[2]){ ME.t = [rand[1][0],rand[1][1]]; } else{ ME.t = [rand[2][0],rand[2][1]]; } } if(ME.t[0] > myself[1]){ return 'right'; } else if(ME.t[0] < myself[1]){ return 'left'; } else if(ME.t[1] > myself[2]){ return 'down'; } else if(ME.t[1] < myself[2]){ return 'up'; } else{ ME.t = []; ME.c = 0; } } ``` Has a list of (pixelated) paintings it likes to paint; picks one at random along with a random canvas/placement and paints. It seems to have issues with its paint, however, as sometimes the paint cleans the canvas, and other times it doesn't seem to stick to the canvas at all. The painter bot is unfazed by this, however. ### Update 25-Aug-2018: * New pictures * Wants his pictures seen so tries to pick better placement for them ### Update 29-Aug-2018: * New Pictures + Updates to old ones [Answer] ## P ``` function (myself, grid, bots, gameInfo) { "use strict"; if (this.O == null) this.O = {}; const O = this.O; // console.log(this); const MAXBOTS = 60; const MAXSZ = 3 * MAXBOTS; const MAXID = MAXBOTS + 1; if (gameInfo[0] == 1) { if (bots.length > MAXBOTS) { alert("ASSERTION FAILED: MAXBOTS EXCEEDED (contact @tomsmeding)"); return 0; } for (const b of bots) { if (b[0] < 0 || b[0] > MAXID) { alert("ASSERTION FAILED: MAXID EXCEEDED (contact @tomsmeding)"); return 0; } } } function from_base64(bs) { if (bs.length % 4 != 0) throw new Error("Invalid Base64 string"); const alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const beta = new Array(256).fill(-1); for (let i = 0; i < alpha.length; i++) beta[alpha.charCodeAt(i)] = i; const arrbuf = new ArrayBuffer(bs.length / 4 * 3 | 0); const buf = new Uint8Array(arrbuf); let j = 0; for (let i = 0; i < bs.length; i += 4) { buf[j++] = (beta[bs.charCodeAt(i+0)] << 2) | (beta[bs.charCodeAt(i+1)] >> 4); if (bs[i+2] == "=") break; buf[j++] = (beta[bs.charCodeAt(i+1)] << 4) | (beta[bs.charCodeAt(i+2)] >> 2); if (bs[i+3] == "=") break; buf[j++] = (beta[bs.charCodeAt(i+2)] << 6) | (beta[bs.charCodeAt(i+3)] >> 0); } return new Uint8Array(arrbuf, 0, j); } function repeat(str, times) { return new Array(times + 1).join(str); } function println_func(ptr) { let s = ""; for (; ptr < O.wa_membuf.length; ptr++) { if (O.wa_membuf[ptr] == 0) break; s += String.fromCharCode(O.wa_membuf[ptr]); } console.log(s); } function print_int_func(value) { console.log(value); } function seed_random() { for (let i = 0; i < O.wa_rand_state.length; i++) { O.wa_rand_state[i] = (Math.random() * 256) & 0xff; } } function transfer_myself(myself) { O.wa_my_id[0] = myself[0]; } function transfer_grid(grid) { const W = grid.length, H = grid[0].length; O.wa_width[0] = W; O.wa_height[0] = H; for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { O.wa_grid[W * y + x] = grid[x][y]; } } } function transfer_bots(bots) { O.wa_nbots[0] = bots.length; for (let i = 0; i < bots.length; i++) { O.wa_bots[3 * i + 0] = bots[i][0]; O.wa_bots[3 * i + 1] = bots[i][1]; O.wa_bots[3 * i + 2] = bots[i][2]; } } function transfer_gameInfo(gameInfo) { O.wa_round_idx[0] = gameInfo[0]; O.wa_total_rounds[0] = gameInfo[1]; } function stringify(thing) { if (Array.isArray(thing)) { return "[" + thing.map(stringify).join(",") + "]"; } else if (thing instanceof Int8Array) { return "[" + thing.toString() + "]"; } else { return thing.toString(); } } function mc_calcmove() { // console.log("mc_calcmove(" + stringify(myself) + "," + stringify(grid) + "," + stringify(bots) + "," + stringify(gameInfo) + ")"); transfer_myself(myself); transfer_grid(grid); transfer_bots(bots); transfer_gameInfo(gameInfo); return ["right", "down", "left", "up", "wait"][O.wa_mc_calcmove()]; // return O.wa_mc_calcmove(); } if (O.wasm_bytes == null) { O.wasm_bytes = from_base64( // INSERT-WASM-HERE "AGFzbQEAAAABEQNgAX8Bf2ABfwBgA39/fwF9AjYDA2Vudg9fX2xpbmVhcl9tZW1vcnkCAA8DZW52B3ByaW50bG4AAQNlbnYJcHJpbnRfaW50AAEDAwIAAgcMAQhlbnRyeV9mbg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BGohGiADQQNqIRsgA0EBaiESIANBAmohHCADQX9qIRMgA0F+aiEdIANBfWohHiADQXxqIR8gA0F7aiEgIANBemohISADQXlqISJBeCEAIANBeGohIwJAA0ACQCAAIg8gDmoiB0EASA0AIAcgFU4NAiAPIA9BH3UiAGogAHMhCiAHIARsIQ0gEEEBTgRAQXghAANAAkAgACILIABBH3UiAGogAHMgCmpBCEoNACALIANqIgZBAEgNACAGIARODQNDAAAAACEnQdD9ASEAIBAhAQNAIAAtAABBAnQiAkHQ+QVqKAIAQRROBEAgAEECai0AACIFIAdrIgxBH3UhCSAMIAlqIAlzIRQgAEEBai0AACIJIAZrIhFBH3UhDCAnQwAAIEEgFCARIAxqIAxzarJDAACAP5KVkyACQdD9BWooAgAiDCAFaiIFIAdrIhFBH3UhCCARIAhqIAhzISYgAkHQ+wVqKAIAIgIgCWoiCSAGayIUQR91IQggDCAHayAFaiIRQR91IQUgAiAGayAJaiIMQR91IQJDAAAgQSAmIBQgCGogCHNqskMAAIA/kpWTQwAAIEEgESAFaiAFcyAMIAJqIAJzarJDAACAP5KVkyEnCyAAQQNqIQAgAUF/aiIBDQALIAYgDWpBAnRB4P4HaiAnOAIACyALQQFqIQAgC0EISA0ACwwBCwJAIANBCEkNACAPDQAgIyAETg0BIA0gI2pBAnRB4P4HakEANgIACyAKQQdqIQACQCADQQdJDQAgAEEISw0AICIgBE4NASANICJqQQJ0QeD+B2pBADYCAAsgCkEGaiEBAkAgA0EGSQ0AIAFBCEsNACAhIARODQEgDSAhakECdEHg/gdqQQA2AgALIApBBWohAgJAIANBBUkNACACQQhLDQAgICAETg0BIA0gIGpBAnRB4P4HakEANgIACyAKQQRqIQYCQCADQQRJDQAgBkEISw0AIB8gBE4NASANIB9qQQJ0QeD+B2pBADYCAAsgCkEDaiEHAkAgA0EDSQ0AIAdBCEsNACAeIARODQEgDSAeakECdEHg/gdqQQA2AgALIApBAmohBQJAIANBAkkNACAFQQhLDQAgHSAETg0BIA0gHWpBAnRB4P4HakE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MAEQKfbQIAAHgCAAADABEDn3gCAACDAgAAAwARBJ+DAgAAjgIAAAMAEQafjgIAAJkCAAADABEFn5kCAACkAgAAAwARB5+kAgAArwIAAAMAEQifrwIAALoCAAADABEJn7oCAADFAgAAAwARCp/FAgAA0AIAAAMAEQuf0AIAANsCAAADABEMn9sCAADmAgAAAwARDZ/mAgAA8QIAAAMAEQ6f8QIAAPwCAAADABEPn/wCAAAHAwAAAwAREJ8HAwAAEgMAAAMAERGfEgMAAB0DAAADABESnx0DAAAoAwAAAwARE58oAwAAMwMAAAMAERSfMwMAAD4DAAADABEVnz4DAABJAwAAAwARFp9JAwAAVAMAAAMAERefVAMAAF8DAAADABEYn18DAABqAwAAAwARGZ9qAwAAdQMAAAMAERqfdQMAAIADAAADABEbn4ADAACLAwAAAwARHJ+LAwAAlgMAAAMAER2flgMAAKEDAAADABEen6EDAAAHFAAAAwARH58AAAAAAAAAAKEDAACsAwAAAwARAJ+sAwAAtwMAAAMAEQGftwMAAMIDAAADABECn8IDAADNAwAAAwARA5/NAwAA2AMAAAMAEQSf2AMAAOMDAAADABEFn+MDAADuAwAAAwARBp/uAwAA+QMAAAMAEQef+QMAAAQEAAADABEInwQEAAAPBAAAAwARCZ8PBAAAGgQAAAMAEQqfGgQAACUEAAADABELnyUEAAAwBAAAAwARDJ8wBAAAOwQAAAMAEQ2fOwQAAEYEAAADABEOn0YEAABRBAAAAwARD59RBAAAXAQAAAMAERCfXAQAAGcEAAADABERn2cEAAByBAAAAwAREp9yBAAAfQQAAAMAEROffQQAAIgEAAADABEUn4gEAACTBAAAAwARFZ+TBAAAngQAAAMAERafngQAAKkEAAADABEXn6kEAAC0BAAAAwARGJ+0BAAAvwQAAAMAERmfvwQAAMoEAAADABEan8oEAADVBAAAAwARG5/VBAAA4AQAAAMAERyf4AQAAOsEAAADABEdn+sEAADrBAAAAwARHp/rBAAABxQAAAMAER+fAAAAAAAAAACyBQAA5wUAAAMAEQCfAAAAAAAAAAAsBgAAhAYAAAMAE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QjQFADWJQjUFADjJQjgFBfLAAjkFBelAQjoFBf2BAjsFBf/BAjwFBe8BQj0FBfiBQiAFRflAAiEFReXAQiIFRf2BAiMFRf4BAiYFRenAgicFRepAgigFRewAgikFRe7AgioFRe9AgisFRfkAgi4FRe1Awi8FRe3AwjAFRe+AwjEFRfyAwjQFReZBAjUFRf1BAjYFReABQjcFRekBQjoFRe1BAjsFRfnBAjwFReABQj0FReCBQiAFgAACIQWAIQoCIgWFwAIjBYX6QUAHRFyZWxvYy4uZGVidWdfbGluZQsCCCsAAAj5FBcA" ); // require("fs").writeFileSync("reverse-base64-output.txt", Buffer.from(O.wasm_bytes)); O.memory = new WebAssembly.Memory({initial: 15}); // O.importObject = {js: {mem: O.memory}, env: {println: println_func}}; O.importObject = { env: { println: println_func, print_int: print_int_func, __linear_memory: O.memory, __indirect_function_table: new WebAssembly.Table({initial: 0, element: "anyfunc"}), }, }; // let wa_membuf, wa_width, wa_height, wa_nbots, wa_round_idx, wa_total_rounds, wa_my_id, wa_grid, wa_bots, wa_rand_state; /*const promise = fetch('../out/main.wasm').then(response => response.arrayBuffer() ).then(bytes => WebAssembly.instantiate(bytes, O.importObject) );*/ // const promise = WebAssembly.instantiate(fs.readFileSync("hotpatcher/out.wasm"), O.importObject); const promise = WebAssembly.instantiate(O.wasm_bytes, O.importObject); promise.then(results => { const instance = results.instance; // console.log(instance.exports); // First set some pointers instance.exports.entry_fn(0); O.wa_membuf = new Uint8Array(O.memory.buffer); const ptrs = new Uint32Array(O.memory.buffer, 0, 9 * 4); O.wa_width = new Int32Array(O.memory.buffer, ptrs[0], 1); O.wa_height = new Int32Array(O.memory.buffer, ptrs[1], 1); O.wa_nbots = new Int32Array(O.memory.buffer, ptrs[2], 1); O.wa_round_idx = new Int32Array(O.memory.buffer, ptrs[3], 1); O.wa_total_rounds = new Int32Array(O.memory.buffer, ptrs[4], 1); O.wa_my_id = new Int32Array(O.memory.buffer, ptrs[5], 1); O.wa_grid = new Uint8Array(O.memory.buffer, ptrs[6], MAXSZ * MAXSZ); O.wa_bots = new Uint8Array(O.memory.buffer, ptrs[7], MAXBOTS * 3); O.wa_rand_state = new Uint8Array(O.memory.buffer, ptrs[8], 5 * 4); O.wa_mc_calcmove = function() { return instance.exports.entry_fn(2); } seed_random(); // Signal that we're done setting up, and the wasm code can set itself up instance.exports.entry_fn(1); O.instantiated = true; console.log("MC: Instantiated!"); }).catch(console.error); } if (gameInfo[0] > 5) { if (O.instantiated) { // const start = new Date(); const output = mc_calcmove(); // const end = new Date(); // if (O.time_sum == null) O.time_sum = 0; // O.time_sum += end - start; // if (gameInfo[0] % 50 == 0) { // console.log("Average time taken: " + O.time_sum / (gameInfo[0] - 1)); // } return output; } else { throw new Error("SCREAM FIRE wasm instantiation"); } } else { console.log("MC: RANDOM MOVE BEFORE INSTANTIATE"); return ["right", "down", "left", "up"][Math.random() * 4 | 0]; } } ``` Meet P. P isn't really trying to be a good bot, or trying to win the game, it's just trying to paint squares. It's content doing that. P gets nervous when bots are on his tail, but is otherwise just going where the paintable squares are. ## Explanations My bots P and MC are basically compiled from the same code. A description of how it all works can be found below. The bots consist of the Javascript wrapper code shown above and the C code ~~shown~~ linked to below. (Including the code made the post too long for SE's ideas of good post length.) When preparing a bot for submission (or for testing), the C code is compiled via an elaborate process, described later, to a `wasm` file, which is encoded in base64 and inserted into the Javascript file. The Javascript file must instantiate a `WebAssembly.Instance` of the wasm code to be able to use it, but the API for that is asynchronous; therefore, it starts to instantiate it the first time the bot is invoked in a game, and does random moves until the asynchronous instantiation returns, and the wasm code is ready to use. This instantiation usually takes about two turns, which is little enough to not be significant. Once the bot is instantiated, the one exported function of the wasm code is called (`entry_fn`) with mode argument 0, which instructs it to populate a `ptrs` table with pointers to various global variables that contain per-round information like the grid data, the bots array, the number of bots, etc. The table also contains a pointer to the state array used for the internal PRNG — WebAssembly is, as far as I know, only natively capable of performing deterministic actions, and has no built-in random source. Therefore, after the `ptrs` array is filled, the Javascript code generates some random numbers with `Math.random()` and fills this `rand_state` array with random data. When that is done, `entry_fn` is called with mode argument 1, indicating that the JS code is done setting up and that the wasm code can start initialising its data. Once the wasm code has finished setting up and the bot is called again for a move, `entry_fn` is called with its last mode argument, 2, which calculates a move. Before doing that, the JS code first copies all necessary turn information (grid, bots, myself, etc.) to the global variables for which pointers were put in the `ptrs` array. `entry_fn(2)` then returns the move chosen, as an index in the array `["right", "down", "left", "up", "wait"]`. The C code can be found in [this gist](https://gist.github.com/1101106cccdf3b1a8604f70a5fc316c3), and an explanation of it can be found belowwwww. ## The C code The reason for having only one exported function, and not exporting the global variables by name, and possibly other unidiomatic things, is because building this crap is difficult, and the tooling doesn't work together and has incompatibilities with other tooling and browsers. My own compilation pipeline is described later. (Note that the wasm ABI is 32-bit, so returning a pointer as an `int` is actually safe and fine (`sizeof(void*) == 32`).) I use a bit of macro magic to select which bot this is to actually compile to. Both MC's and P's source are in the C source, and which is to be used is determined by the `USED_CALCMOVE_PREFIX` define. If it's `p_`, P's source is used, and if it's `mc_`, MC's source is used. At some point, I had plans of making them work together, after all being able to execute each other's logic, but I didn't. Depending on the value of that define, when calculating a move, control is transferred to either `mc_calcmove()` or `p_calcmove()`. ### MC [MC is a Monte Carlo player](https://codegolf.stackexchange.com/a/170978/6689), which means from the current position it tries all possible moves (5 or less in this game), and from the resulting board position it simulates a number of random games. The move with the best average result after the random playouts is chosen. In this case, I do 100 random playouts, each of only 5 turns. Usually in this kind of game AI's, a game is run till the end in each playout, but since this game is *completely* unpredictable at times, that didn't seem useful. And in any case, it would've been too slow. For optimisation purposes, the entire board is not reset after each playout, but only the cells that were actually changed in the playout. This is done with the `modified` array. Also, the score delta is kept in `mc_random_step`, so that after each playout the entire board's score doesn't need to be calculated. Both reduce the time required to run this algorithm, and do not influence its decisions or calculated scores in any way. For the most part, the C code is completely parallel to the JS code of a previous version of the MC submission here, which may be looked up if wanted. The only change is the use of the `last_dir` array to prevent walking backwards during a random playout. ### P P is a more complex bot than MC. I'll not describe all the specific workings — you have the source now after all — but I'll give a general overview of what it's doing. The main functionality is not far from DFSbot, I think. It's a depth-first search of the possible paths it can take for the coming 8 (= `P_WALK_DISTANCE`) moves, scoring each path as the sum of the scores given to each cell used in the path. Besides the per-cell scoring, each path starting move (i.e. move to be taken right now) is additionally scored using an "evil factor", which helps the bot evade other bots that are on its tail. (Briefly: if a bot is intruding on P's ground for at least 20 turns, the bot's position and the two in front of it in the direction it's travelling repel P; see `p_evil_factor()`. `bot_evil_score` records the number of moves intruding, falling quickly back to zero if the bot isn't intruding anymore.) The base cell score is given by `p_paintScore()`, which doesn't like running over itself, painting stuff that it can't paint directly, running into another bot directly (I don't model the bots-on-same-cell-give-white for performance!), or walking where it's already been in the game. Added to that score is the score given by the `heat_map`, which is calculated by `p_populate_heatmap()`. White squares are good, P's own squares are bad, and other's squares that P can paint into its own colour are moderately good, otherwise they are moderately bad. There is a factor of 0.98 that is multiplied with the tail end of the path at each point, making the starting part of the possible path more important than the tail end. The factor is purposefully chosen very close to 1, so that the total impact will not be very large, but will be large enough indeed to provide a tie-breaker function. (If we have two paths that are equivalent but with the only difference that one has a white square at the end and the other has a white square at the beginning, the second path is clearly better, and this weighting ensures that.) There are a number of arrays, some of which keep their values over turns. Management of this data costs some code, mostly in `p_calcmove()`. The code isn't very beautiful, but it seems to work, so ¯\\_(ツ)\_/¯ ## Compilation process In my working directory, I have a folder `compiler` that contains: * A build of LLVM in `llvm`, compiled with `-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly`. The version is the master tip at the time of cloning, which is commit `3d765ce4b7f2fd25bdbc0efc26afdf42e84fecb2`. Compiling this with 3 threads took about an hour on my machine. Note that the resuilting `build` folder is about 29GB, so be wary of doing this yourself if you're short on disk space. .\_. * A build of [binaryen](https://github.com/WebAssembly/binaryen) in `binaryen`, at commit `57328f8e1e4db509b9956b53dd5300fc49e424eb`. * A build of [WABT](https://github.com/WebAssembly/wabt) in `wabt`, at commit `71647d4f0e86a4c738f742f69f65b2cc41d4c004`. The JS wrapper source is in `main.js` and the C source is in `main.c`. When I want to test what I've written, I save the file (most probably `main.c`), run `./CFIT.sh`, run `pbcopy <main.js` (which copies `main.js` to my clipboard), and paste it in the box in @dzaima's controller. Million thanks @dzaima for providing a controller that is actually that full-featured to let me easily do this. The script `CFIT.sh` drives the compilation process, and looks as follows: ``` #!/usr/bin/env bash # Compile, Fix, Insert, Test set -e ./compile.sh hotpatcher/hotpatcher main.wasm out.wasm compiler/binaryen/build/bin/wasm-opt -O4 out.wasm -o out.wasm ./insert_wasm.sh out.wasm ./run_test.js ``` The hotpatcher is a whole 'nother story, and mentioned later. The script `compile.sh` looks as follows: ``` #!/usr/bin/env bash compiler/llvm/build/bin/clang -Wall -Wextra main.c -c --target=wasm32-unknown-unknown -O3 -fno-builtin-memcpy -fno-builtin-memset -g -o main.wasm compiler/wabt/build/wasm2wat main.wasm -o main.wat ``` The flags `-fno-builtin-{memset,memcpy}` are necessary because otherwise LLVM dutifully recognises the bodies of my `memset_x` and `memcpy_x` functions as the built-in `memset` and `memcpy` functions, which it then replaces the code with, leaving me with undefined references to these functions *despite* providing replacements. The `insert_wasm.sh` script looks as follows: ``` #!/usr/bin/env bash set -e set -o pipefail if [[ -n "$1" ]]; then wasmfile="$1"; else wasmfile="main.wasm"; fi subject="main.js" tmpfile=".insert_wasm_tmpfile.txt" [[ -f "$subject" ]] || exit 1 [[ -f "$wasmfile" ]] || exit 1 echo "Inserting into $subject from wasm file $wasmfile" ./tostring.sh "$wasmfile" >"$tmpfile" result="$( \ cat "$subject" \ | sed -n ':b; s/INSERT-WASM-HERE/INSERT-WASM-HERE/; p; t i; n; b b; :i; r '"$tmpfile"$'\n''; n' \ )" cat >"$subject" <<<"$result" rm "$tmpfile" ``` This replaces the huge base64 string in main.js directly with the compiled wasm code. The `tostring.sh` script looks as follows again: ``` #!/usr/bin/env bash if [[ $# -ge 1 ]]; then exec <"$1" fi # $HOME/code/bin2c/bin2c | sed 's/^"//; s/"$//; s/\\a/\\7/g' | tr -d '\n' base64 | tr -d '\n' | python3 -c 'import sys, re; text = sys.stdin.read(); print("\"" + re.sub(r"(.)\1{29,}", lambda m: "\"+repeat(\"" + m.group(0)[0] + "\"," + str(len(m.group(0))) + ")+\"", text, flags=re.I) + "\"")' ``` The `run_test.js` script just includes the `main.js` (including newly-inserted wasm code) with an `eval` and calls it twice with some parameters taken from a game that produced problems once, making sure to wait some time between the two calls to let the wasm code be instantiated. This provides the most basic of integration tests; if this doesn't work, something is wrong, and usually when something is actually wrong it is so wrong that this test fails, crashes, whatever. ### Hotpatcher That leaves the hotpatcher. This is where this whole thing went overboard, honestly; clang generates fine wasm code, but it fails badly when doing *anything* but generating plain instructions. It doesn't emit exports for exported functions or exported variables, and it for some reason emits an exported *mutable global* used as a store for the stack pointer. And even worse, it actually uses that global. (Fortunately, it doesn't *really* use it: it only reads it at function entry and restores it a function exit, which is easily fixed by replacing the read with a constant and the writes with a `drop`.) Now mutable globals are not supported in any wasm implementation I've seen, so why clang thinks doing this is a good idea is beyond me. I haven't succeeded in making clang do any of this different, and being a lazy programmer I didn't like making all these fixes by hand, so I wrote a program to do it for me. That program became a 1385 line C++ program that parses, modifies and re-serialises a wasm file. The source for that program can be found in [this gist](https://gist.github.com/tomsmeding/031905a866edbe60152ab99fb03b32fe). I'm not even going to explain what it all does; only that the actual bloody *patches* that it does are in `hotpatcher.cpp`; all the rest is only to make that function possible. ## Conclusion Does this whole ton of crap need a conclusion? ¯\\_(ツ)\_/¯ but I guess I'm obliged to say that this might have been done more easily using emscripten. The reason I didn't use it is because when you compile a C file using emcc, by default it generates a complete monstrosity of a JS file and an HTML file along with it, and the stuff was so insane I just dropped emcc in favour of doing everything myself. Later I read somewhere that emscripten is supposed to have some "shared library" mode (shared libraries are a lower-level thing, JS don't go stealing names that aren't yours) that doesn't generate all that bloatcode, but then I was already too far into all the fun stuff of bulding my hotpather (gambler's fallacy anyone?) to try that out. I hope this is actually useful to someone and that I haven't run over SE's post size limit in writing this up. [Answer] ## Random Filler ``` function([id, x, y], grid, bots, gameInfo) { let painted = { false: { un: [], other: [], me: [], }, true: { un: [], other: [], me: [], }, }; let moves = { left: {x: x - 1, y}, up: {x, y: y - 1}, right: {x: x + 1, y}, down: {x, y: y + 1}, wait: {x, y}, }; let isbot = m => bots.some(([, x, y]) => m.x == x && m.y == y); let whose = n => n ? n == id || Math.abs(id - n) % 3 > 1 ? "me" : "other" : "un"; for (let dir in moves) { let move = moves[dir]; if (move.x >= 0 && move.x < grid.length && move.y >= 0 && move.y < grid.length) painted[isbot(move)][whose(grid[move.x][move.y])].push(dir); } choices = [painted.false.un, painted.false.other, painted.true.un, painted.true.other, painted.false.me, painted.true.me].find(choices => choices.length); let move = choices[Math.random() * choices.length | 0]; return move; } ``` Randomly walks with a preference for moving to unpainted squares, then squares it can repaint (twice if necessary), then any square. Edit: Updated to prefer squares that don't already contain a bot (including itself), except that squares with a bot are currently preferred to squares it can't paint. [Answer] # Borderline ``` function(myself, grid, bots, gameInfo) { // Check if already on border if (myself[1] == 0 || myself[1] == grid.length-1 || myself[2] == 0 || myself[2] == grid.length-1) { // Move anticlockwise around the border if (myself[1] == 0 && myself[2] != 0 && myself[2] != grid.length-1) { return "down"; } if (myself[1] == 0 && myself[2] == 0) { return "down"; } if (myself[2] == grid.length-1 && myself[1] != 0 && myself[1] != grid.length-1) { return "right"; } if (myself[1] == 0 && myself[2] == grid.length-1) { return "right"; } if (myself[1] == grid.length-1 && myself[2] != 0 && myself[2] != grid.length-1) { return "up"; } if (myself[1] == grid.length-1 && myself[2] == grid.length-1) { return "up"; } if (myself[2] == 0 && myself[1] != 0 && myself[1] != grid.length-1) { return "left"; } if (myself[1] == grid.length-1 && myself[2] == 0) { return "left"; } } else { // Find the nearest border and move to it if (myself[1] <= grid.length-1 - myself[1]) { // Move to left border return "left"; } else { // Move to right border return "right"; } } } ``` Not too interesting, just moves around the edge of the grid. [Answer] ## M.A.D.S. ``` function(myself, grid, bots, gameInfo) { const w = 6, h = 6; let my_c = myself[0], my_x = myself[1], my_y = myself[2], size = grid.length, roundnum = gameInfo[0]; if (!localStorage.steelyeyedmissileman) { var offset_x = Math.random() *(size-w-1) |0; var offset_y = Math.random() *(size-h-1) |0; localStorage.steelyeyedmissileman = JSON.stringify([offset_x, offset_y]); } offsets = JSON.parse(localStorage.steelyeyedmissileman); offset_x = offsets[0]; offset_y = offsets[1]; let targets = []; for(let grid_x = offset_x; grid_x < offset_x+6; grid_x++) { for(let grid_y = offset_y; grid_y < offset_y+6; grid_y++) { if(grid[grid_x][grid_y] != my_c) { targets.push([grid_x, grid_y]); } } } let target = targets.pop(); if(target == undefined) return 'wait'; if(target[0] > my_x) return 'right'; if(target[0] < my_x) return 'left'; if(target[1] > my_y) return 'down'; if(target[1] < my_y) return 'up'; return "left"; } ``` Picks a 6x6 spot on the board and defends it. [Answer] # Euclid ``` function euclidFn(myself, grid, bots, gameInfo) { const W = grid.length, H = grid[0].length; const meIdx = bots.findIndex(b => b[0] == myself[0]); const meClr = bots[meIdx][0]; const botIdToIndex = {}; for (let i = 0; i < bots.length; i++) { botIdToIndex[bots[i][0]] = i; } function paintValue(floor, clr) { if (floor == 0) return clr; else return [clr, 0, floor][Math.abs(clr - floor) % 3]; } function paint(gr, x, y, clr) { gr[x][y] = paintValue(gr[x][y], clr); } function distance(x1, y1, x2, y2) { return Math.abs(y2 - y1) + Math.abs(x2 - x1); } function calcHeatmap() { const heat = new Array(W).fill(0).map(() => new Array(H).fill(0)); function weight(dx, dy) { const d = dx + dy; return d < 3 ? 1 / (1 + d) : 0; } for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { let s=0; for (let x2 = Math.max(x-3, 0); x2 <= Math.min(W-1, x+3); x2++) { for (let y2 = Math.max(y-3, 0); y2 <= Math.min(H-1, y+3); y2++) { if (grid[x2][y2] == meClr) { s += weight(Math.abs(x2 - x), Math.abs(y2 - y)); } } } heat[x][y] = s; } } return heat; } const heatmap = calcHeatmap(); function scorePos(px, py) { let sc = 0; if (grid[px][py] != meClr && paintValue(grid[px][py], meClr) == meClr) { sc += 100; } let mindist = W + H + 1; for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { if (grid[x][y] != meClr && paintValue(grid[x][y], meClr) == meClr) { let d = distance(px, py, x, y); if (d < mindist) mindist = d; } } } sc -= 3 * mindist; mindist = W + H + 1; for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { if (grid[x][y] == largestBotId) { let d = distance(px, py, x, y); if (d < mindist) mindist = d; } } } sc -= 6 * mindist; sc -= 3 * heatmap[px][py]; sc += Math.random(); return sc; } function calcBotScores() { const res = new Array(bots.length).fill(0).map((_,i) => [bots[i][0], 0]); for (let x = 0; x < W; x++) { for (let y = 0; y < H; y++) { if (grid[x][y] > 0) { let i = botIdToIndex[grid[x][y]]; if (i != undefined) res[i][1]++; } } } return res; } const botScores = calcBotScores(); // [id, size] const largestBotId = botScores .filter(p => p[0] != meClr && paintValue(p[0], meClr) == meClr) .sort((a,b) => b[1] - a[1]) [0][0]; const dxes = [1, 0, -1, 0, 0], dyes = [0, 1, 0, -1, 0]; const outputs = ["right", "down", "left", "up", "wait"]; let allscores = []; let maxscore = -Infinity, maxat = -1; let allowWait = grid[bots[meIdx][1]][bots[meIdx][2]] == 0; for (let i = 0; i < 4 + allowWait; i++) { const nx = bots[meIdx][1] + dxes[i]; const ny = bots[meIdx][2] + dyes[i]; if (nx < 0 || nx >= W || ny < 0 || ny >= H) { allscores.push(null); continue; } let score = scorePos(nx, ny); if (i == 4) score -= 20; if (euclidFn.lastMove != undefined && i != euclidFn.lastMove) score -= 3; allscores.push(~~(score * 1000) / 1000); if (score > maxscore) { maxscore = score; maxat = i; } } // console.log([maxscore, maxat], allscores); let move = maxscore == -1 ? Math.random() * 5 | 0 : maxat; euclidFn.lastMove = move; return outputs[move]; } ``` This does all kinds of arbitrary things. The name is badly chosen, but it does a number of things with distances, so I guess it makes sense somewhere. I chooses the move that maximises `scorePos`, which really likes painting a square to its colour when it wasn't before, and otherwise doesn't like being far from colourable squares or from the largest colourable bot (not sure whether this is actually working well). It also doesn't like being near itself, because otherwise it goes overpainting itself often for some reason. *EDIT* This gave errors before, I hope it's correct now... [Answer] ## Hunter-Killer ``` function(myself, grid, bots, gameInfo) { targetColour = myself[0] % 3; // If I can paint someone else's space to my colour, do so. var options = []; if (myself[1] !== 0 && grid[myself[1] - 1][myself[2]] % 3 === targetColour && grid[myself[1] - 1][myself[2]] !== myself[0] && grid[myself[1] - 1][myself[2]] !== 0) options.push("left"); if (myself[1] !== grid.length - 1 && grid[myself[1] + 1][myself[2]] % 3 === targetColour && grid[myself[1] + 1][myself[2]] !== myself[0] && grid[myself[1] + 1][myself[2]] !== 0) options.push("right"); if (myself[2] !== 0 && grid[myself[1]][myself[2] - 1] % 3 === targetColour && grid[myself[1]][myself[2] - 1] !== myself[0] && grid[myself[1]][myself[2] - 1] !== 0) options.push("up"); if (myself[2] !== grid.length - 1 && grid[myself[1]][myself[2] + 1] % 3 === targetColour && grid[myself[1]][myself[2] + 1] !== myself[0] && grid[myself[1]][myself[2] + 1] !== 0) options.push("down"); if (options.length > 0) return options[Math.random() * options.length | 0]; // Otherwise, move to the closest bot I can paint over. var targetBots = bots.filter(bot => { if (bot[0] === myself[0] || bot[0] % 3 !== targetColour) return false; return true; }); if (targetBots.length > 0) { targetBots.sort((a, b) => (Math.abs(a[1] - myself[1]) + Math.abs(a[2] - myself[2])) < (Math.abs(a[1] - myself[1]) + Math.abs(a[2] - myself[2]))); if (Math.abs(targetBots[0][1] - myself[1]) > Math.abs(targetBots[0][2] - myself[2])){ return targetBots[0][1] - myself[1] > 0 ? "right" : "left"; } return targetBots[0][2] - myself[2] > 0 ? "down" : "up"; } options = []; // If we've killed them all, try to move to a blank space. if (myself[1] !== 0 && grid[myself[1] - 1][myself[2]] === 0 && grid[myself[1] - 1][myself[2]] !== myself[0]) options.push("left"); if (myself[1] !== grid.length - 1 && grid[myself[1] + 1][myself[2]] === 0 && grid[myself[1] + 1][myself[2]] !== myself[0]) options.push("right"); if (myself[2] !== 0 && grid[myself[1]][myself[2] - 1] === 0 && grid[myself[1]][myself[2] - 1] !== myself[0]) options.push("up"); if (myself[2] !== grid.length - 1 && grid[myself[1]][myself[2] + 1] === 0 && grid[myself[1]][myself[2] + 1] !== myself[0]) options.push("down"); if (options.length > 0) return options[Math.random() * options.length | 0]; options = []; // If there aren't any, try to move to a space I can paint white. targetColour = (targetColour + 2) % 3 if (myself[1] !== 0 && grid[myself[1] - 1][myself[2]] % 3 === 0 && grid[myself[1] - 1][myself[2]] !== myself[0]) options.push("left"); if (myself[1] !== grid.length - 1 && grid[myself[1] + 1][myself[2]] % 3 === 0 && grid[myself[1] + 1][myself[2]] !== myself[0]) options.push("right"); if (myself[2] !== 0 && grid[myself[1]][myself[2] - 1] % 3 === 0 && grid[myself[1]][myself[2] - 1] !== myself[0]) options.push("up"); if (myself[2] !== grid.length - 1 && grid[myself[1]][myself[2] + 1] % 3 === 0 && grid[myself[1]][myself[2] + 1] !== myself[0]) options.push("down"); if (options.length > 0) return options[Math.random() * options.length | 0]; // Otherwise, pick one at random. return ["up","down","left","right"][Math.random() * 4 | 0]; } ``` Hunter-Killer targets the closest bot that it can paint over and tries to paint over all of its spaces, eliminating it. If it gets all of them, it reverts to a random-painting algorithm where it tries to move first to white spaces and second to spaces it can make white. It seems to do well if it can latch on to a bot that has a good strategy and follow it for a while, but only moderate if it kills all of its targets quickly (or its targets are weak bots). Doesn't work well with the current version of the controller, as bots aren't removed when eliminated. If that's not changed, I'll rewrite it to ignore bots which haven't moved in a few turns (potentially allowing a turtleing strategy which would allow a bot to survive, though likely not prosper). All that's required to fix this is change the first loop in runBots to ``` for (var j = 0; j < botData.length; j++) { if (!botData[j].eliminated) bots_array.push([botData[j].uid, botData[j].x, botData[j].y]); } ``` [Answer] ## GiveMeSpace ``` function(myself, grid, bots, gameInfo){ if(!localStorage.givemespace){ localStorage.givemespace = JSON.stringify({ recent:[], timeout:-1, corner:[9999,-1,-1], following:[] }); } var firstchoice = {up:-1,down:-1,left:-1,right:-1}, nearestblank = [9999,-1,-1], store = JSON.parse(localStorage.givemespace), unique = [], numunique = 0, currdist, i, j; if(store.timeout >= 0 && store.corner[1] >= 0 && store.corner[2] >= 0){ store.timeout--; persiststorage(store); if(store.corner[2] < myself[2]){ return 'up'; } if(store.corner[2] > myself[2]){ return 'down'; } if(store.corner[1] < myself[1]){ return 'left'; } if(store.corner[1] > myself[1]){ return 'right'; } } if(store.recent.length == 20){ for(i=0;i<store.recent.length;i++){ if(unique.indexOf(store.recent[i][1]+"_"+store.recent[i][2]) == -1){ unique.push(store.recent[i][1]+"_"+store.recent[i][2]); numunique++; } } if(numunique <= 6){ store.recent = []; store.timeout = 10+numunique; store.corner = [[-1,0,0],[-1,0,grid.length-1],[-1,grid.length-1,0],[-1,grid.length-1,grid.length-1]][Math.random()*4|0]; persiststorage(store); } } function dist(a,b){ return Math.abs(a[1]-b[1])+Math.abs(a[2]-b[2]); } function finalcolor(a,b){ return Math.abs(a-b)%3; } function persiststorage(store){ if(store.recent.length > 20) store.recent = store.recent.slice(1); localStorage.givemespace = JSON.stringify(store); } store.recent.push(myself); persiststorage(store); if(myself[2] > 0 && myself[0] != grid[myself[1]][myself[2]-1] && (grid[myself[1]][myself[2]-1] == 0 || finalcolor(myself[0],grid[myself[1]][myself[2]-1]) == 0)){ firstchoice.up = 9999; } if(myself[2] < grid.length-1 && myself[0] != grid[myself[1]][myself[2]+1] && (grid[myself[1]][myself[2]+1] == 0 || finalcolor(myself[0],grid[myself[1]][myself[2]+1]) == 0)){ firstchoice.down = 9999; } if(myself[1] > 0 && myself[0] != grid[myself[1]-1][myself[2]] && (grid[myself[1]-1][myself[2]] == 0 || finalcolor(myself[0],grid[myself[1]-1][myself[2]]) == 0)){ firstchoice.left = 9999; } if(myself[1] < grid.length-1 && myself[0] != grid[myself[1]+1][myself[2]] && (grid[myself[1]+1][myself[2]] == 0 || finalcolor(myself[0],grid[myself[1]+1][myself[2]]) == 0)){ firstchoice.right = 9999; } if(firstchoice.up > 0 || firstchoice.down > 0 || firstchoice.left > 0 || firstchoice.right > 0){ for(i=0;i<bots.length;i++){ if(bots[i][0] != myself[0]){ if(firstchoice.up > 0){ currdist = dist(bots[i],[0,myself[1],myself[2]-1]); if(currdist < firstchoice.up){ firstchoice.up = currdist; } } if(firstchoice.down > 0){ currdist = dist(bots[i],[0,myself[1],myself[2]+1]); if(currdist < firstchoice.down){ firstchoice.down = currdist; } } if(firstchoice.left > 0){ currdist = dist(bots[i],[0,myself[1]-1,myself[2]]); if(currdist < firstchoice.left){ firstchoice.left = currdist; } } if(firstchoice.right > 0){ currdist = dist(bots[i],[0,myself[1]+1,myself[2]]); if(currdist < firstchoice.right){ firstchoice.right = currdist; } } } } if(firstchoice.up >= firstchoice.down && firstchoice.up >= firstchoice.left && firstchoice.up >= firstchoice.right){ return 'up'; } else if(firstchoice.down >= firstchoice.left && firstchoice.down >= firstchoice.right){ return 'down'; } else if(firstchoice.left >= firstchoice.right){ return 'left'; } else{ return 'right'; } } for(i=0;i<grid.length;i++){ for(j=0;j<grid.length;j++){ if((i != myself[1] || j != myself[2]) && grid[i][j] != myself[0] && (grid[i][j] == 0 || finalcolor(myself[0],grid[i][j]) == 0)){ currdist = dist(myself,[0,i,j]); if(currdist < nearestblank[0]){ nearestblank[0] = currdist; nearestblank[1] = i; nearestblank[2] = j; } } } } if(nearestblank[0] < 9999){ if(nearestblank[2] < myself[2]){ return 'up'; } if(nearestblank[2] > myself[2]){ return 'down'; } if(nearestblank[1] < myself[1]){ return 'left'; } if(nearestblank[1] > myself[1]){ return 'right'; } } return ['up','down','left','right'][Math.random()*4|0]; } ``` Checks for any paintable (can paint into its own color) spaces next to it and chooses the one furthest from any other bots. If there are no paintable spaces adjacent to the bot, it finds the closest paintable space and heads towards it. Currently avoids infinite loops. Todo: Avoid hunters. [Answer] # TRAVELER ``` function TRAVELER([myColor, myX, myY], grid, bots, [frame, maxFrames]) { class BinaryHeapStrategy { constructor(options) { this.comparator = options.comparator; this.data = []; this.heapify(); } heapify() { if (this.data.length > 0) { for (let i = 0; i < this.data.length; i++) { this.bubbleUp(i); } } } queue(value) { this.data.push(value); this.bubbleUp(this.data.length - 1); } dequeue() { const ret = this.data[0]; const last = this.data.pop(); if (this.data.length > 0 && last !== undefined) { this.data[0] = last; this.bubbleDown(0); } return ret; } peek() { return this.data[0]; } clear() { this.data.length = 0; } bubbleUp(pos) { while (pos > 0) { const parent = (pos - 1) >>> 1; if (this.comparator(this.data[pos], this.data[parent]) < 0) { const x = this.data[parent]; this.data[parent] = this.data[pos]; this.data[pos] = x; pos = parent; } else { break; } } } bubbleDown(pos) { let last = this.data.length - 1; while (true) { const left = (pos << 1) + 1; const right = left + 1; let minIndex = pos; if (left <= last && this.comparator(this.data[left], this.data[minIndex]) < 0) { minIndex = left; } if (right <= last && this.comparator(this.data[right], this.data[minIndex]) < 0) { minIndex = right; } if (minIndex !== pos) { const x = this.data[minIndex]; this.data[minIndex] = this.data[pos]; this.data[pos] = x; pos = minIndex; } else { break; } } return void 0; } } class PriorityQueue { constructor(options) { this.length = 0; this.length = 0; this.strategy = new BinaryHeapStrategy(options); } queue(value) { this.length++; this.strategy.queue(value); } dequeue() { if (!this.length) return; this.length--; return this.strategy.dequeue(); } peek() { if (!this.length) return; return this.strategy.peek(); } clear() { this.length = 0; this.strategy.clear(); } } const mapSize = { width: grid[0].length, height: grid.length }; const mapArea = mapSize.width * mapSize.height; const maxOpenNodes = 300; const centerNode = Node(myX, myY); const colorStats = new Array(bots.length + 1).fill(0); const nearestBotAtNode = new Array(mapArea); for (let x = 0; x < mapSize.width; ++x) { let row = grid[x]; for (let y = 0; y < mapSize.height; ++y) { let color = row[y]; ++colorStats[color]; let id = nodeId(Node(x, y)); let closestBots = null; for (let [botColor, botX, botY] of bots) { let distance = Math.max(1, manhattanDistance(x, y, botX, botY)); if (closestBots === null || distance < closestBots.distance) { closestBots = { distance, colors: [botColor] }; } else if (distance == closestBots.distance) { closestBots = { distance, colors: [...closestBots.colors, botColor] }; } } nearestBotAtNode[id] = closestBots; } } const bestSpace = { node: null, space: 0 }; const primaryEnemy = winningColor({ includeMyself: false, includeWhite: false, canErase: true }); const isBehindWinner = winningColor({ includeMyself: true, includeWhite: false, canErase: false, ignoreColor: primaryEnemy }) == myColor; var step = Math.round(Math.max(1, mapSize.width / 30)); for (let x = step; x < mapSize.width - step; x += step) { for (let y = step; y < mapSize.height - step; y += step) { let space = countSpace(x, y); if (bestSpace.node == null || space > bestSpace.space) { bestSpace.node = Node(x, y); bestSpace.space = space; } } } const goalNode = bestSpace.node; const isRetreat = nearestBotAtNode[nodeId(centerNode)].colors.length > 1; function Node(x, y) { return { x, y }; } function AStarNode(node) { return Object.assign({}, node); } function nodeId(node) { return node.y * mapSize.height + node.x; } function defaultComparator(a, b) { return (a.cost + a.goal) - (b.cost + b.goal); } function nonDiagonalNodes(node) { return [ node.x + 1 < mapSize.width ? Node(node.x + 1, node.y) : null, node.y + 1 < mapSize.height ? Node(node.x, node.y + 1) : null, node.x > 0 ? Node(node.x - 1, node.y) : null, node.y > 0 ? Node(node.x, node.y - 1) : null ].filter(x => x); } function mixColor(floorColor, botColor) { return [botColor, 0, floorColor][Math.abs(botColor - floorColor) % 3]; } function countSpace(x, y, area = -1) { if (x < 0 || y < 0 || x >= mapSize.width || y >= mapSize.height) { return 0; } let color = grid[x][y]; if (area == -1) { area = 0; while (countSpace(x, y, area)) { ++area; } return area * 2 * 4; } else if (area == 0) { if (color == myColor) { return 0; } if (color == 0 || mixColor(color, myColor) == myColor) { return 1; } return 0; } else { for (let dx = -area; dx <= area; ++dx) { if (!countSpace(x + dx, y - area, 0)) return 0; if (!countSpace(x + dx, y + area, 0)) return 0; } for (let dy = -area + 1; dy <= area - 1; ++dy) { if (!countSpace(x - area, y + dy, 0)) return 0; if (!countSpace(x + area, y + dy, 0)) return 0; } return area * 2 * 4; } } function manhattanDistance(x1, y1, x2, y2) { return Math.abs(x2 - x1) + Math.abs(y2 - y1); } function moveFromNodes(node1, node2) { if (node2.x < node1.x) return 'left'; if (node2.x > node1.x) return 'right'; if (node2.y < node1.y) return 'up'; if (node2.y > node1.y) return 'down'; return 'wait'; } function winningColor(options) { let winningColor = { color: 0, count: 0 }; for (let color = 0; color < colorStats.length; ++color) { if (color === 0) { if (!options.includeWhite) { continue; } } else if (color === myColor) { if (!options.includeMyself) { continue; } } else if (color === options.ignoreColor) { continue; } else if (options.canErase && mixColor(color, myColor) === color) { continue; } if (colorStats[color] > winningColor.count) { winningColor.color = color; winningColor.count = colorStats[color]; } } if (winningColor.count === 0) { return null; } return winningColor.color; } function goal(node) { let goal = manhattanDistance(node.x, node.y, goalNode.x, goalNode.y); return goal; } function cost(node, changes, depth) { let cost = 0; let id = nodeId(node); let color; if (changes[id] !== undefined) { color = changes[id]; } else { color = grid[node.x][node.y]; } if (color !== 0 && color !== myColor) { let mixedColor = changes[id] = mixColor(color, myColor); if (mixedColor === myColor) { if (nearestBotAtNode[nodeId(centerNode)].colors.includes(color) || nearestBotAtNode[id].colors.includes(color)) { cost += 5000; } if (color === primaryEnemy) { if (isBehindWinner) { cost -= 80; } else { cost -= 60; } } else { cost -= 30; } } else if (mixedColor === color) { cost += 0; } else if (mixedColor === 0) { if (color === primaryEnemy) { if (isBehindWinner) { cost -= 15; } else { cost -= 10; } } else { cost -= 5; } } } if (color === 0) { changes[id] = myColor; let nearestBot = nearestBotAtNode[id]; if (nearestBot.colors.includes(myColor)) { if (depth == 1 && nearestBot.colors.length > 1) { cost += 20; } else { cost -= 60; } } else { if (depth == 1 && nearestBot.distance == 0) { cost += 30; } else { let distanceDelta = depth - nearestBot.distance; if (distanceDelta >= 0) { cost += -50 + distanceDelta * 20; } else { cost += -60; } } } } return cost; } function bestMove(options) { let walkCost = 25; let goalImportance = 3; let goalTarget = false; if (options.strategy === 'long-sighted') { walkCost = 0; goalImportance = 25; goalTarget = true; } options.maxOpenNodes = Math.min(options.maxOpenNodes, mapArea); const openNodes = new PriorityQueue({ comparator: defaultComparator }); const bestNodes = new PriorityQueue({ comparator: defaultComparator }); const closedNodes = {}; const closeNode = (node) => closedNodes[nodeId(node)] = node; const getClosedNode = (node) => closedNodes[nodeId(node)]; if (!isRetreat) { const waitNode = AStarNode(options.fromNode); waitNode.depth = 0; waitNode.changes = {}; waitNode.goal = goal(waitNode); waitNode.cost = cost(waitNode, waitNode.changes, waitNode.depth); bestNodes.queue(waitNode); closeNode(waitNode); } const startNode = AStarNode(options.fromNode); startNode.depth = 0; startNode.changes = {}; startNode.goal = goal(startNode); startNode.cost = cost(startNode, startNode.changes, startNode.depth); openNodes.queue(startNode); while (openNodes.length && openNodes.length < maxOpenNodes) { let bestNode = openNodes.dequeue(); nonDiagonalNodes(bestNode).forEach(node => { let nextNode = AStarNode(node); nextNode.depth = bestNode.depth + 1; nextNode.changes = Object.assign({}, bestNode.changes); nextNode.parent = bestNode; nextNode.goal = goal(node) * goalImportance; nextNode.cost = bestNode.cost + walkCost + cost(nextNode, nextNode.changes, nextNode.depth); if (goalTarget && nextNode.x == goalNode.x && nextNode.y == goalNode.y) { bestNodes.queue(nextNode); return; } let closedNode = getClosedNode(node); if (!closedNode || defaultComparator(nextNode, closedNode) < 0) { openNodes.queue(nextNode); } }); closeNode(bestNode); if (bestNode != startNode) { bestNodes.queue(bestNode); } } let directions = []; let bestNode = bestNodes.peek(); if (options.strategy === 'short-sighted' && bestNode.depth < 6 && !isRetreat) { return bestMove(Object.assign({}, options, { strategy: 'long-sighted' })); } else { let nextMoveNode = bestNode; while (nextMoveNode.parent) { directions.unshift(moveFromNodes(nextMoveNode.parent, nextMoveNode)); if (nextMoveNode.parent === startNode) { break; } nextMoveNode = nextMoveNode.parent; } return moveFromNodes(startNode, nextMoveNode); } } return bestMove({ strategy: 'short-sighted', fromNode: centerNode, maxOpenNodes, }); } ``` Stateless bot uses A-star pathing to find the most the most optimal path (optimal being the lowest cost path). Usually predicts 150 moves ahead on average, however if the best path has less than 6 moves ahead, the bot will be forced to walk to a cluster with most obtainable colors. Some costs are driven by determining the winning color, and some costs are set to avoid circling around and losing trolls. If anyone wishes to improve the code by playing around with editing the cost values, or rewriting the cost function, you are more than welcome to. Have fun everyone. **EDIT:** I cannot reply on chat (new accounts are not able to), but I just saw the comments. I optimised it for under 50ms now, all the way from 400ms. It will get faster over time. I am happy to optimise more if needed, just drop a message on chat or comment here. **EDIT 2:** Some here are saying A-Star can only be used for finding path between two points, and while generally it is, in any pathing algorithm you can tweak the G (goal function) to return 0, that makes the path finding have no goal but rather seeks most efficient path in all directions, where each path cost is a cumulative cost of each step. Cost of step can be defined if they are good or bad steps, such as repainting enemy's square colour with ours is a good step, and walking onto a square that cannot be repained is a bad step. You will notice however the `goal()` function does not return 0, instead it slightly contributes to walking towards a cluster with most amount of paintable squares. **tldr; path end is the best cluster and the obstacles are how the color will be mixed along the way.** [Answer] ## FarSightedGreed ``` function([id, x, y], grid, bots, gameInfo) { let value = n => n ? n == id ? 0 : 2 - Math.abs(id - n) % 3 : 2; let directions = [ {name: "wait", x: 0, y: 0}, {name: "left", x: -1, y: 0}, {name: "up", x: 0, y: -1}, {name: "right", x: 1, y: 0}, {name: "down", x: 0, y: 1}, ]; for (let d of directions) { d.score = 0; for (let i = 1; ; i++) { let px = x + i * d.x; let py = y + i * d.y; if (px < 0 || py < 0 || px == grid.length || py == grid.length) break; if (bots.some(([, x, y]) => x == px && y == py)) break; d.score += value(grid[px][py]) / i; } } let best = Math.max(...directions.map(({score}) => score)); return directions.find(({score}) => score == best).name; } ``` Name shamelessly plagirised from NearSightedGreed. Simply scores all the visible squares in all cardinal directions according to distance and colour, and chooses the direction with the highest sum. [Answer] ## DFSBot ``` function(myself, grid, bots, gameinfo) { let max_scores = Array(12); max_scores[11] = 0; max_scores[10] = 0.05 * (1 + 1e-6 + 16.1 * 1e-10); for (let i = 9; i >= 0; i--) { max_scores[i] = max_scores[10] + 0.95 * max_scores[i + 1]; } let my_id = myself[0]; let my_x = myself[1]; let my_y = myself[2]; let delta = [[0, -1], [0, 1], [-1, 0], [1, 0], [0, 0]]; let seen = Array(grid.length).fill().map(() => Array(grid.length).fill(false)); let scores = Array(bots.length + 2).fill(0); for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid.length; j++) { scores[grid[i][j]]++; } } function search(x, y, depth) { if (depth == 11) { return [4, 0]; } let max_score = 0; let best_move = 0; for (let i = 0; i < 4; i++) { let x1 = x + delta[i][0]; let y1 = y + delta[i][1]; if ((x1 < 0) || (x1 >= grid.length)) { continue; } if ((y1 < 0) || (y1 >= grid.length)) { continue; } if (seen[x1][y1]) { continue; } let n = 0; for (let dx = -1; dx <= 1; dx++) { let x2 = x1 + dx; if ((x2 < 0) || (x2 >= grid.length)) { continue; } for (let dy = -1; dy <= 1; dy++) { if ((dx == 0) && (dy == 0)) { continue; } let y2 = y1 + dy; if ((y2 < 0) || (y2 >= grid.length)) { continue; } n++; if (grid[x2][y2] == my_id) { n++; } } } let prev = grid[x1][y1]; if (prev == 0) { next = my_id; } else { next = [my_id, 0, prev][Math.abs(my_id - prev) % 3]; } let score = 0; score += 1e-10 * (n + 0.1 * Math.random()); if (next != prev) { if (next == my_id) { score += 1; } if (prev == 0 || scores[prev] > scores[my_id]) { score += 1e-6; } } score *= 0.05; if (score + 0.95 * max_scores[depth + 1] <= max_score) { continue; } grid[x1][y1] = next; seen[x1][y1] = true; let final_score = score + 0.95 * search(x1, y1, depth + 1)[1]; seen[x1][y1] = false; grid[x1][y1] = prev; if (final_score > max_score) { max_score = final_score; best_move = i; } } return [best_move, max_score]; } let best_move = search(my_x, my_y, 0)[0]; return ["up", "down", "left", "right", "wait"][best_move]; } ``` [Answer] # Humble Paint Salesman ``` // Humble Paint Salesman function(myself, grid, bots, gameInfo) { let [id, x, y] = myself; // if first move if(gameInfo[0] == 1) { this.size = grid.length; this.mid = this.size / 2; this.dx = x < this.mid ? "right" : "left"; this.dy = y < this.mid ? "down" : "up"; this.flip = function(v) { this.dict = this.dict || { right: "left", left: "right", down: "up", up: "down" }; return this.dict[v]; } this.queue = []; } if(grid[x][y] == 0) { return "wait"; } else if(this.queue.length) { return this.queue.shift(); } else if(x == 0 || x + 1 == this.size) { this.dx = this.flip(this.dx); if(y == 0 || y + 1 == this.size) { this.dy = this.flip(this.dy); } this.queue.push(this.dx); return this.dy; } return this.dx; } ``` Simply covers the board, iterating up and down the board. Waits if the cell below him is empty (a salesman must peddle his wares!). [Answer] # DragonBot ``` function dragonCurve(myself, grid, bots, gameInfo){ dCurve=n=>{ if(n==0){return "1 "} return dCurve(n-1).replace(/(.)(.)/g,"1$10$2") } [id,x,y]=myself; dir=0; if(gameInfo[0]==1){ dragon=dCurve(12); if(x<3*bots.length-x){ if(y<x){dir=0;} else if(3*bots.length-y<x){dir=2;} else{dir=3;} } else{ if(y<3*bots.length-x){dir=0;} else if(y>x){dir=2;} else{dir=1;} } window.localStorage.setItem("dragon",dragon); window.localStorage.setItem("dragonDir",dir); window.localStorage.setItem("dragonStep",0); return ["up","right","down","left"][dir]; } dragon=window.localStorage.getItem("dragon") dir=window.localStorage.getItem("dragonDir")-0; step=window.localStorage.getItem("dragonStep")-0; if(gameInfo[0]%2==0){ return ["up","right","down","left"][dir]; } validStep=false; while(!validStep){ if(-dragon[step]){dir=(dir+1)%4;} else{dir=(dir+3)%4;} step+=1; validStep=((dir==0&&y!=0)||(dir==3&&x!=0)||(dir==1&&x!=3*bots.length-1)||(dir==2&&y!=3*bots.length-1)); } window.localStorage.setItem("dragon",dragon); window.localStorage.setItem("dragonDir",dir); window.localStorage.setItem("dragonStep",step); return ["up","right","down","left"][dir]; } ``` DragonBot simply tries to draw a dragon curve with side lengths of 2 (so that it leaves spaces). [Answer] # Drone-BEA7 ``` function(myData, gridData, botData, gameInfoData) { function customSetup(fThis) { fThis.botUID = 0; fThis.swarm = new Array(3); fThis.matchedSize = 0; bots.forEach(b => { b.failedSignal = 0; b.trespass = 0; b.desecrate = 0; }); delete fThis.connected; delete fThis.target; delete fThis.chaser; delete fThis.cleaners; delete fThis.roamers; } let XY = this.xyClass; let Bot = this.botClass; let Cell = this.cellClass; function at(pos, usedGrid = grid) { // NEVER EVER THINK ABOUT PUTTING THIS ON THE GRID ITSELF return pos.withinBounds() ? usedGrid[pos.toIndex()] : new Cell(null); } if (gameInfoData[0] === 1) { XY = this.xyClass = (class XY { constructor(x, y) { this.x = x; this.y = y; } static fromIndex(index) { return new XY(Math.floor(index / gridSize), index % gridSize); } toIndex() { return this.x * gridSize + this.y; } add(other) { return new XY(this.x + other.x, this.y + other.y); } sub(other) { return new XY(this.x - other.x, this.y - other.y); } div(value) { return new XY(Math.round(this.x / v), Math.round(this.y / v)); } mul(value) { return new XY(Math.round(this.x * m), Math.round(this.y * m)); } equals(other) { return this.x === other.x && this.y === other.y; } distance(other) { return Math.abs(other.x - this.x) + Math.abs(other.y - this.y); } chebyshevDistance(other) { return Math.max(Math.abs(other.x - this.x), Math.abs(other.y - this.y)); } withinBounds() { return this.x >= 0 && this.x < gridSize && this.y >= 0 && this.y < gridSize; } getNeighbors() { return neighbors.map(p => this.add(p)); } getRealNeighbors() { return this.getNeighbors().filter(p => p.withinBounds()); } }); Bot = this.botClass = (class Bot extends XY { constructor(botData) { super(botData[1], botData[2]); this.id = botData[0]; this.score = 0; this.dead = true; } }); Cell = this.cellClass = (class Cell { constructor(id, xy) { this.id = id; this.pos = xy; } }); this.botMap = []; this.botIDs = []; botData.forEach(d => { this.botMap[d[0]] = new Bot(d); this.botIDs.push(d[0]); }); this.currentRound = 0; delete this.prevGrid; } const gridSize = gridData.length; const gridSizeSqr = gridSize * gridSize; const grid = new Array(gridSize * gridSize); for (var x = 0; x < gridSize; x++) { for (var y = 0; y < gridSize; y++) { grid[x * gridSize + y] = new Cell(gridData[x][y], new XY(x, y)); } } const prevGrid = this.prevGrid; this.prevGrid = grid; const bots = []; const botMap = this.botMap; this.botIDs.forEach(id => botMap[id].dead = true); botData.forEach(d => { const r = botMap[d[0]]; r.dead = false; r.lastPosition = new XY(r.x, r.y); r.x = d[1]; r.y = d[2]; r.score = grid.reduce((sum, cell) => sum + (cell.id === r.id), 0); bots.push(r); at(r).bot = r; }); const me = botMap[myData[0]]; const currentRound = this.currentRound++; const maxRound = gameInfoData[1] - 1; const zero = new XY(0, 0); const neighbors = [new XY(1, 0), new XY(0, 1), new XY(-1, 0), new XY(0, -1)]; const moves = ["right", "down", "left", "up", "wait"]; if (gameInfoData[0] === 1) { customSetup(this); } function rand(max = 1, min = 0) { return min + Math.random() * (max - min); } function randInt(max, min = 0) { return Math.floor(rand(max, min)); } function roll(chance = 0.5) { return Math.random() < chance; } function separation(id1, id2) { return Math.abs(id1 - id2) % 3; } function value(id, bot = me) { return id === bot.id ? 1 : id === 0 ? 4 : id === null ? 0 : [5, 3, 2][separation(bot.id, id)]; } function travelTo(goal, start = me) { const relative = goal.sub(start); return Math.abs(relative.x) > Math.abs(relative.y) ? ( relative.x > 0 ? 0 : 2 ) : ( relative.y > 0 ? 1 : relative.y < 0 ? 3 : 4 ); } function travelToList(goal, start = me) { const relative = goal.sub(start); return [...start.getRealNeighbors(), start].sort((a, b) => (a.chebyshevDistance(goal) - b.chebyshevDistance(goal)) * gridSizeSqr + (a.distance(goal) - b.distance(goal))); } const swarm = this.swarm; const swarmSize = swarm.length; const botUID = this.botUID; const signalPatterns = [[3, 0, 1, 1, 0], [0, 1, 2, 2, 2, 3, 3, 2, 2, 1], [2, 3, 2, 3, 0, 0, 1, 0, 3, 3]]; function patternMove(pos, round, ...pattern) { const e = pattern[round % pattern.length]; const f = (e + 2) % 4; function calcPos(d) { return pos.add(neighbors[d]); } if (calcPos(e).withinBounds()) { return e; } else { return f; } } function signal(uid = botUID, pos = me, round = currentRound) { return patternMove(pos, round, ...signalPatterns[uid]); } if (currentRound) { for (var i = 0; i < swarmSize; i++) { if (!swarm[i]) { const consideredBots = bots.filter(b => !(b.failedSignal & (1 << i))); const matchedBots = consideredBots.filter(b => { const prevPos = b.lastPosition; const expected = neighbors[signal(i, prevPos, currentRound - 1)]; const performed = b.sub(prevPos); const matched = performed.equals(expected); if (!matched) { b.failedSignal |= (1 << i); } return matched; }); if (matchedBots.length === 1) { swarm[i] = matchedBots[0]; swarm[i].member = true; this.matchedSize++; console.log("Swarm member", i, "found!"); } } } } function findTarget() { const lists = []; lists.unshift(bots.filter(b => b.removal.candidate)); lists.unshift(lists[0].filter(b => b.removal.separations[0] === 0)); lists.unshift(lists[0].filter(b => b.removal.speed === 3)); lists.unshift(lists[2].filter(b => b.removal.separations[0] === 2)); const bestList = lists.find(l => l.length); if (!bestList) { console.log("No more targets!"); return undefined; } const bestTarget = bestList.sort((a, b) => b.trespass - a.trespass)[0]; // TODO: Remove sort. TODO: Improve. console.log("Best target:", bestTarget); return bestTarget; } if (this.matchedSize === swarmSize) { if (!this.connected) { bots.forEach(b => { const separations = swarm.map(m => separation(b.id, m.id)); const speed = Math.floor(separations.reduce((sum, val) => sum + (val < 2 ? 1 : 0.5), 0)); b.removal = {separations: separations, speed: speed, candidate: speed > 1 && !b.member}; }); console.log("All connections established."); this.connected = true; } bots.forEach(b => { if (b.removal.separations[0] !== 2 && at(b, prevGrid).id === swarm[0].id) { b.desecrate++; } swarm.forEach((m, i) => { if (b.removal.separations[i] !== 2 && at(b, prevGrid).id === m.id) { b.trespass++; } }); }); if (!this.target || this.target.dead) { this.target = findTarget(); swarm.forEach(b => { delete b.partner; }); const sep = this.target.removal.separations; const overwriters = []; const eraser = []; const helpers = []; for (var i = 0; i < swarmSize; i++) { if (swarm[i].partner) { continue; } if (sep[i] === 0) { overwriters.push(swarm[i]); } else if (sep[i] === 1) { eraser.push(swarm[i]); } else if (sep[i] === 2) { for (var j = i + 1; j < swarmSize; j++) { if (sep[j] === 2) { swarm[j].partner = swarm[i]; swarm[i].partner = swarm[j]; eraser.push(swarm[i]); break; } } if (!swarm[i].partner) { helpers.push(swarm[i]); } } } this.chaser = eraser.pop() || overwriters.pop(); this.cleaners = [...overwriters, ...eraser]; this.roamers = helpers; // TODO: Make helpers more useful by making them simply target the next guy? } function findImmediate(target, bot = me) { const list = travelToList(target, bot); return list.find(p => !at(p).reserved) || list[0]; } grid.forEach(c => c.reserved = 0); function reserve(bot, target) { if (!bot.target) { bot.immediateTarget = findImmediate(target, bot); bot.target = target; at(bot.immediateTarget).reserved++; at(target).reserved++; } } function unreserve(bot) { if (bot.target) { at(bot.immediateTarget).reserved--; at(bot.target).reserved--; delete bot.immediateTarget; delete bot.target; } } reserve(this.chaser, chase(this.target)); for (var i = 0; i < swarmSize; i++) { const emergency = preserveLife(swarm[i]); if (emergency) { unreserve(swarm[i]); reserve(swarm[i], emergency); } } this.cleaners.forEach(b => reserve(b, clean(b, this.target, this.cleaners))); this.roamers.forEach(b => reserve(b, roam(b))); const immediateTarget = me.immediateTarget || findImmediate(me.partner.target); swarm.forEach(b => unreserve(b)); return moves[travelTo(immediateTarget)]; } else { return moves[signal()]; } function chase(target) { return target; } function clean(bot, target, cleaners) { return grid.filter(c => { return c.id === target.id && !c.reserved; }).reduce((best, c) => { const closest = Math.min(...cleaners.map(b => b.distance(c.pos))); const distance = bot.distance(c.pos); const wrongness = distance - closest; const distanceFromTarget = target.distance(c.pos); if (wrongness < best.wrongness || (wrongness === best.wrongness && (distance < best.distance || (distance === best.distance && distanceFromTarget > best.distanceFromTarget)))) { return {wrongness: wrongness, distance: distance, distanceFromTarget: distanceFromTarget, pos: c.pos}; } else { return best; } }, {wrongness: Infinity, distance: Infinity, distanceFromTarget: -Infinity, pos: bot}).pos; } function roam(bot) { const dangerousBots = bots.filter(b => !b.member && separation(b.id, bot.id) !== 2); return grid.filter(c => { return value(c.id, bot) >= 4 && !c.bot && !c.reserved && !swarm.find(m => m.id === c.id); }).reduce((best, c) => { const val = value(c.id, bot); const distance = bot.distance(c.pos); const comfyness = c.pos.getNeighbors().reduce((sum, next) => sum + (value(at(next).id, bot) <= 2), 0); const closestBotDist = Math.min(...dangerousBots.map(b => b.distance(c.pos))); if (distance < best.distance || (distance === best.distance && (val > best.val || (val === best.val && (comfyness > best.comfyness || (comfyness === best.comfyness && closestBotDist > best.closestBotDist)))))) { return {distance: distance, val: val, comfyness: comfyness, closestBotDist: closestBotDist, pos: c.pos}; } else { return best; } }, {distance: Infinity, val: -Infinity, comfyness: -Infinity, closestBotDist: -Infinity, pos: bot}).pos; } function preserveLife(bot) { if (bot.score < 20) { return roam(bot); } } } ``` This is the leader of a trio of drones. Their task is simple: destroy enemy painters with the power of coding and algorithms! A more in-depth description is coming soon, along with much-needed performance optimizations. ## Changelog ### 1.1 * Fixed on the official controller * Improved performance by ~25% ### 1.0 * Initial release [Answer] # AnnoyingLittleBrother ``` function(myself, grid, bots, gameInfo) { // Some paramters var brother_loop_count = 0; var brother_score = -1; var brother_id = 0; var number_of_brothers_followed = 0; var num_of_bots = -1; var saw_all_brothers_moves = 0; var moves_write = 0; let moves_to_follow = 30; // How much moves will we follow? let moves_to_use = 5; // Only follow the last 5 elements of this array var moves_saw = makeArray(moves_to_follow, 2, 0); var my_id = myself[0]; var my_x = myself[1]; var my_y = myself[2]; var round = gameInfo[0]; var end_round = gameInfo[1]; var last_num_of_bots = 0; // Handle Storage if(!localStorage.LB_nfirst){ // First round (Dont rely on round number) localStorage.LB_nfirst = true; brother_loop_count = 0;// lock on to anyone moves_write = 0; moves_saw = makeArray(moves_to_follow, 2, 0); let num_of_bots = bots.length; localStorage.LB_moves_saw = encode_moves(moves_saw); localStorage.LB_moves_write = moves_write;// Save it localStorage.LB_brother_id = brother_id;// Save it localStorage.LB_brother_loop_count = brother_loop_count; // Save it localStorage.LB_saw_all_brothers_moves = saw_all_brothers_moves; localStorage.LB_number_of_brothers_followed = number_of_brothers_followed; localStorage.LB_num_of_bots = num_of_bots; } else{ moves_saw = decode_moves(localStorage.LB_moves_saw); moves_write = parseInt(localStorage.LB_moves_write); brother_id = parseInt(localStorage.LB_brother_id); brother_loop_count = parseInt(localStorage.LB_brother_loop_count); saw_all_brothers_moves = parseInt(localStorage.LB_saw_all_brothers_moves); last_num_of_bots = parseInt(localStorage.LB_last_num_of_bots); number_of_brothers_followed = parseInt(localStorage.LB_number_of_brothers_followed); num_of_bots = parseInt(localStorage.LB_num_of_bots); } // Check if our big brother was eliminated if(last_num_of_bots !== bots.length){ // A bot was elimitated. Just tell LittleBrother to search for a new brother var found = false; for(var i = 0; i<bots.length; i++){ if (bots[i][0]==brother_id){ found = true; break; } } if(!found){ brother_loop_count = 0; brother_id = 0; } last_num_of_bots = bots.length; } // Check if we are in a infinite loop with big brother function equals(a, b) { return a[0]===b[0] && a[1]===b[1]; } if (brother_id !== 0 && (saw_all_brothers_moves===1)){ var found_curr_step = new Uint32Array(moves_to_use); var left = (moves_write+1)%moves_to_follow; var right = (moves_write+1+moves_to_use)%moves_to_follow; if (right > left){var comp = moves_saw.slice(left,right);} else{var comp = moves_saw.slice(left);comp.push(...moves_saw.slice(0,right));} for (var i = 0; i < moves_to_follow-moves_to_use; i++){ for (var j = 0; j < moves_to_use; j++){if(equals(comp[j], moves_saw[(i+right)%moves_to_follow])){found_curr_step[j]=true;}} } var should_clear = true; for(var j = 0; j < moves_to_use; j++){if(!found_curr_step[j]){should_clear = false;break;}} if (should_clear){ brother_loop_count = 0; brother_id = 0; } } // Are we tired of this brother yet? if (brother_loop_count === 0){ // Determine each bot's score var bot_scores = new Uint32Array(num_of_bots+1); for (var x = 0; x < grid.length; x++) { for (var y = 0; y < grid.length; y++) { bot_scores[grid[x][y]] += 1; // Increase the score of the bot's who color this is // The eliminated bots' scores will just stay zero } } // Find a bot to follow brother_id = 0; if (Math.random() > 0.6){ var backup_bro = 0; var tolerance = 0; var chance = Math.random(); if (chance > 2){tolerance = 1;} // Never if (chance > 2){tolerance = 2;} // Never for (var uid = 1; uid < bot_scores.length; uid++){ if (bot_scores[uid]>brother_score && my_id!==uid){ if (Math.abs(my_id - uid)%3<=tolerance){// Will it be annoying to the brother? brother_score = bot_scores[uid]; brother_id = uid; } else{ if(Math.abs(my_id - uid)%3<2){ backup_id = uid; // In case we didn't find what we wanted. } } } } } // If we don't have a brother yet, find a random one if (brother_id === 0){ var tries = 0; do{ var ridx = Math.round(Math.random()*(bots.length-1)); if(bots[ridx][0]!==my_id && Math.abs(my_id - bots[ridx][0])%3===0){ brother_id = bots[ridx][0]; } }while(brother_id === 0 && tries++<=20); } if (brother_id===0){brother_id = (my_id===1)?2:1;} // Start the brother follow counter moves_write = 0; saw_all_brothers_moves = 0; brother_loop_count = 200 + 300*number_of_brothers_followed; number_of_brothers_followed ++; } // Decrease the loop count variable to make sure we don't stagnate brother_loop_count -= 1; // But only for so long // Now do the actual following var aim_x = -1; var aim_y = -1; var bro_x = -1; var bro_y = -1; if (brother_id > 0){ // Find where brother currently is for (var i = 0; i < bots.length; i++){ if (bots[i][0] === brother_id){ brother_idx = i; break; } } // Which point are we aiming for? if(saw_all_brothers_moves === 1 || moves_write > moves_to_use){ // Did I see how my brother moves? // Calculate the slice of steps we are going to use var left = ((saw_all_brothers_moves===1) ? moves_write+1 : 0)%moves_to_follow; var right = ((saw_all_brothers_moves===1) ? moves_write+moves_to_use+1 : moves_to_use)%moves_to_follow; if (right > left){// want to read left --> right in moves_saw var steps_to_use = moves_saw.slice(left,right); } else{ var steps_to_use = moves_saw.slice(0,right) steps_to_use.push(...moves_saw.slice(left)); } // Check if we are in his footsteps? var in_brothers_footsteps = false; for (var step = 0; step<steps_to_use.length; step++){ if ((steps_to_use[step][0] === my_x) && ((steps_to_use[step][1] === my_y))){ in_brothers_footsteps = true; break; } } if(in_brothers_footsteps === true){ // We are in his footsteps. Go to the next one!; step++; if (step >= steps_to_use.length){step=0;} aim_x = steps_to_use[step][0];aim_y = steps_to_use[step][1]; } else{ // We are not in his footsteps, aim for the footsteps aim_x = 0; aim_y = 0; for (var step = 0; step<steps_to_use.length; step++){// Calculate step's center of mass aim_x += steps_to_use[step][0];aim_y += steps_to_use[step][1]; } aim_x /= moves_to_use; aim_y /= moves_to_use; } } else{ // No, not yet. Just run towards him aim_x = bots[brother_idx][1]; aim_y = bots[brother_idx][2]; } // Check if we might touch big brother let [dx, dy] = PosAt(toPos([aim_x, aim_y])); if (my_x+dx===bots[brother_idx][1] && my_y+dy===bots[brother_idx][2]){ // EEEUUW. Flinch away, because it's weird. aim_x = my_x; aim_y = my_y; } } // Watch big brother's moves if(brother_id > 0){ moves_saw[moves_write][0] = bots[brother_idx][1]; moves_saw[moves_write][1] = bots[brother_idx][2]; moves_write ++; if (moves_write===moves_to_follow){ moves_write = 0; // Wrap counter for circular buffer // Have I seen enough of them? if(saw_all_brothers_moves === 0){ saw_all_brothers_moves = 1; } } } // Save updated variables localStorage.LB_moves_saw = encode_moves(moves_saw); localStorage.LB_moves_write = moves_write;// Save it localStorage.LB_brother_id = brother_id;// Save it localStorage.LB_brother_loop_count = brother_loop_count; // Save it l localStorage.LB_saw_all_brothers_moves = saw_all_brothers_moves; localStorage.LB_last_num_of_bots = last_num_of_bots; localStorage.LB_number_of_brothers_followed = number_of_brothers_followed; // Finish function if (brother_id <= 0){ // If not following anybody, move randomly return ["up","down","left","right"][Math.random()*4|0]; } else{ // Following a big brother! return toPos([aim_x, aim_y]); } // Some functions to ease the load function toPos([x,y]) { var dx = x - my_x; var dy = y - my_y; if(Math.abs(dx)>Math.abs(dy)){ if (x > my_x) return "right"; if (x < my_x) return "left"; if (y < my_y) return "up"; if (y > my_y) return "down"; } else{ if (y < my_y) return "up"; if (y > my_y) return "down"; if (x > my_x) return "right"; if (x < my_x) return "left"; } return 'wait'; } function PosAt(dir){ if (dir === 'left') return [-1,0]; if (dir === 'right') return [1, 0]; if (dir === 'up') return [0, -1]; if (dir === 'down') return [0, 1]; return [0,0]; } function decode_moves(moves_str){ var moves_array = []; var moves_strs = moves_str.split(';'); for (var i = 0; i<moves_to_follow; i++){ var splot = moves_strs[i].split(','); moves_array[i] = []; moves_array[i][0] = parseInt(splot[0]); moves_array[i][1] = parseInt(splot[1]); } return moves_array; } function encode_moves(moves_array){ var moves_str = ""; for (var i = 0; i < moves_array.length; i++){ moves_str += moves_array[i][0] + ',' + moves_array[i][1]; if (i < moves_array.length - 1){moves_str += ';';} } return moves_str; } function makeArray(w, h, val) { var arr = []; for(i = 0; i < w; i++) { arr[i] = []; for(j = 0; j < h; j++) { arr[i][j] = 0; } } return arr; } } ``` This little bot is like any little brother. It will **latch on to you**, and mirror your **every step**. Like your little brother would jump into your footsteps with his over-sized boots. But he will only follow you if he can annoy you. He is your little brother after all. Essentially it selects the highest ranking bot it can affect as its big brother, and follows it relentlessly. Initially it just runs straight towards it, but then it starts to remember the big brother's moves, and follows them step-by-step (using some circular buffer magic). This is my first submission in this SE, and my first time programming in Javascript. So any advice/feedback would be greatly appreciated! I hope `LittleBrother` doesn't annoy you guys too much ;) *Note: Although the function itself is pretty huge, it's very quick. There isn't much time consuming things in.* **Update 22 Aug 2018 20:42:** * Big brother selection improved to actually work. Now it only has 30% chance of chasing someone who's colour it will only clear. The rest of the times it will try and overwrite colours. It will never follow anyone that it can't do anything against. * As game time passes it will grow attached for longer periods of time. * Stop relying on round number for variable initialization. **Update 23 Aug 2018 11:19:** * Little brother no longer gets lots if he struggles to find a big brother. * He is now more light footed because he is scared of John. So never will he step on Jim, or any other big brother of his. **Update 25 Aug 2018 19:26 (*Niceness* Update):** * Lil'Bro no longer latches on to the leaders. It only finds a random older brother to follow. But, as we all do, he sometimes get jealous. So he has a 40% chance of selecting to follow the leading brother. * He also knows nice people get stepped on. So he now follows bots from a distance. Usually about 25 cells behind, but still follows your *every step*. Hopefully this will keep John at peace. * A large purpose of this update is to limit the infinite loops. Top bots usually takes the closest squares, which usually are the ones Lil'Bro just took from them. Therefore, Lil'Bro follows random bots, hoping they won't notice as easily. Also, by trailing so far behind, there is *usually* nicer bait for the target, than the cells Lil'Bro just overwrote. **Update 27 Aug 2018 21:32 (Some New Smarts):** * Improved smart while another player dies. No longer just resets, instead LittleBrother now checks if it actually concerned him. * LittleBrother realized his score is severely inhibited if he gets into a quarrel (infinite loop) with his brother. No he gets annoyed, and looks for someone else if this happens. [Answer] ## NearSightedGreed ``` function(myself, grid, bots, gameInfo) { let ret = []; let col = myself[0]; let myX = myself[1]; let myY = myself[2]; if(grid[myX][myY] != col){ return "wait"; } if(myX != 0 && grid[myX-1][myY] != col){ ret.push("up") } if(myX != grid.length-1 && grid[myX+1][myY] != col){ ret.push("down") } if(myY != 0 && grid[myX][myY-1] != col){ ret.push("left") } if(myY != grid[0].length && grid[myX][myY+1] != col){ ret.push("right") } return ret[Math.random() * ret.length|0] } ``` Tries to move to adjacent fields with enemy colors, otherwise moves randomly. Always prefers painting the current field until it's the right color [Answer] # Boxer ``` function(myself, grid, bots, gameInfo) { let val = gameInfo[0] % 16; if(val < 3){ return "right"; }else if(val < 6){ return "up"; }else if(val < 9){ return "left"; }else if(val < 12){ return "down"; }else if(val < 14){ return ["up","down","left","right"][Math.random() *4 |0]; }else{ let xdist = myself[1]; let ydist = myself[2]; let xfardist = grid.length - 1 - myself[1]; let yfardist = grid.length - 1 - myself[2]; if(gameInfo[0] % 400 < 200){ if (xdist < ydist && xdist < xfardist && xdist < yfardist){ return "right"; }else if (ydist < xfardist && ydist < yfardist){ return "down"; }else if (xfardist < yfardist){ return "left"; }else{ return "up"; } }else{ if (xdist > ydist && xdist > xfardist && xdist > yfardist){ return "right"; }else if (ydist > xfardist && ydist > yfardist){ return "up"; }else if (xfardist > yfardist){ return "left"; }else{ return "down"; } } } } ``` Pretty straightforward; moves in a small 4x4 box repeatedly, and after every loop it takes a random step and then moves a few steps closer or further from the center. Pretty vulnerable to hunters, since it moves in a small zone. Main goal is just to control one area. [Answer] # Jack Starting of with NearSightedGrid's logic (I wanted to created such a bot), I have come up with the following strategy: * Will move from the right bottom to the left top (i.e. first the bottom row by going left, then one above by going right, etc.). Thus, starting somewhere right bottom gives it an advantage. * It will though never do the opposite move of the last move (so that it won't get stuck, which it did in earlier versions). * It will also not prefer to move to a location on which it needs to stay another round, depending on the current color of that location. If possible, such a move is not executed. But it is done if the alternative is moving random. * If no move can be found from above, it will move random. Once it moves random and tries to move random again right away, it will move in the same direction so that it doesn't get stuck in a big field of a color which it cannot defeat. It will though move random again if it will go outside the boundary. Note: not a developer so my code is awful. But strategically it is not that bad. ``` function (myself, grid, bots, gameInfo) { var col = myself[0]; var myX = myself[1]; var myY = myself[2]; var notPreferred = []; var move = "wait"; if(grid[myX][myY] != col){ var go = checkMove(move, grid[myX][myY]); if(go) { if(go == "notPreferred") { //notPreferred.push(move); } else { nextMove(move, "standard"); return move; } } } move = "left"; if(myX > 0 && grid[myX-1][myY] != col){ var go = checkMove(move, grid[myX-1][myY]); if(go) { if(go == "notPreferred") { notPreferred.push(move); } else { nextMove(move, "standard"); return move; } } } move = "right"; if(myX < grid.length-1 && grid[myX+1][myY] != col){ var go = checkMove(move, grid[myX+1][myY]); if(go) { if(go == "notPreferred") { notPreferred.push(move); } else { nextMove(move, "standard"); return move; } } } move = "up"; if(myY > 0 && grid[myX][myY-1] != col){ var go = checkMove(move, grid[myX][myY-1]); if(go) { if(go == "notPreferred") { notPreferred.push(move); } else { nextMove(move, "standard"); return move; } } } move = "down"; if(myY < grid[0].length && grid[myX][myY+1] != col){ var go = checkMove(move, grid[myX][myY+1]); if(go) { if(go == "notPreferred") { notPreferred.push(move); } else { nextMove(move, "standard"); return move; } } } if(notPreferred[0]) { nextMove(notPreferred[0], "notPreferred"); return notPreferred[0]; } var random = randomMove(); nextMove(random, "random"); return random; function checkMove(move, currentColor) { var go = false; if(currentColor === 0) { go = true; } else { var z = [col, 0, currentColor][Math.abs(col - currentColor)%3] go = z == 0 ? "notPreferred" : z != currentColor; } if(go) { if(localStorage.jacksNextMoveShouldNotBe && localStorage.jacksNextMoveShouldNotBe == move) { return false; } } return go; } function randomMove() { if(localStorage.jacksPreviousMoveWasRandom) { var repeatMove = localStorage.jacksPreviousMoveWasRandom; if(repeatMove == "left" && myX > 0 || repeatMove == "right" && myX < grid.length-1 || repeatMove == "up" && myY > 0 || repeatMove == "down" && myY < grid.length-1){ return repeatMove; } } var random = ["up","down","left","right"][Math.random() *4|0]; localStorage.jacksPreviousMoveWasRandom = random; return random; } function nextMove(move, message) { var oppositeMove = "wait"; if(move == "left") { oppositeMove = "right"; } else if(move == "right") { oppositeMove = "left"; } else if(move == "up") { oppositeMove = "down"; } else if(move == "down") { oppositeMove = "up"; } localStorage.jacksNextMoveShouldNotBe = oppositeMove; if(message != "random") { localStorage.jacksPreviousMoveWasRandom = ""; } } } ``` [Answer] # Clever Name ``` function(myself, grid, bots, gameInfo) { // Do a quick dance for identification. let round = gameInfo[0]; if (round < 5) { return ["down", "right", "up", "left"][round % 4]; } // Parse the arguments. let [myId, myX, myY] = myself; // Check each square to see if it's a good target. let targetX, targetY, targetDist = Infinity; let numAtDist; for (let x = 0; x < grid.length; x++) { for (let y = 0; y < grid.length; y++) { // Whoever's fighting for this square can have it. if (x === myX && y === myY) { continue; } // We don't care about our own squares. if (grid[x][y] === myId) { continue; } // Only squares that we can recolor are useful. if (grid[x][y] === 0 || Math.abs(grid[x][y] - myId) % 3 !== 2) { // Avoid squares that take effort. if (Math.abs(grid[x][y] - myId) % 3 === 1 && Math.random() < 0.5) { continue; } // If this is the closest we've seen, target it. let dist = Math.abs(myX - x) + Math.abs(myY - y); if (dist < targetDist) { targetX = x; targetY = y; targetDist = dist; numAtDist = 1; // If it's tied for the closest, sometimes target it. } else if (dist === targetDist) { numAtDist++; if (Math.floor(numAtDist * Math.random()) === 0) { targetX = x; targetY = y; } } } } } // Move toward the target. if (targetX < myX) { return "left"; } if (targetX > myX) { return "right"; } if (targetY < myY) { return "up"; } if (targetY > myY) { return "down"; } return "wait"; } ``` There are two ways to be the best: build yourself up, or tear others down. This takes the former approach. It moves greedily toward one of the nearest squares that can be colored. [Answer] # Kneecapper ``` function(myself, grid, bots, gameInfo) { let [myId, myX, myY] = myself; let round = gameInfo[0]; // Find our friend. if (round === 1) { localStorage.kneecapper_possibleAllies = JSON.stringify(bots.map(bot => bot[0])); } let possibleAllies = JSON.parse(localStorage.kneecapper_possibleAllies); // Players who don't do the identifying dance aren't allies. if (1 < round && round <= 5) { let previousPositions = JSON.parse(localStorage.kneecapper_previousPositions); let expectedDx = [-1, 0, 1, 0]; let expectedDy = [0, 1, 0, -1]; let notAllies = []; for (let i = 0; i < possibleAllies.length; i++) { let j = possibleAllies[i] - 1; let dx = bots[j][1] - previousPositions[j][1]; let dy = bots[j][2] - previousPositions[j][2]; if (dx === 0 && dy === 0) { if (expectedDx === -1 && bots[j][1] !== 0) { notAllies.push(possibleAllies[i]); } else if (expectedDx === 1 && bots[j][1] !== grid.length - 1) { notAllies.push(possibleAllies[i]); } else if (expectedDy === -1 && bots[j][2] !== 0) { notAllies.push(possibleAllies[i]); } else if (expectedDy === 1 && bots[j][2] !== grid.length - 1) { notAllies.push(possibleAllies[i]); } } if (dx !== expectedDx[round % 4] || dy !== expectedDy[round % 4]) { notAllies.push(possibleAllies[i]); } } possibleAllies = possibleAllies.filter(id => notAllies.indexOf(id) < 0); localStorage.kneecapper_possibleAllies = JSON.stringify(possibleAllies); } localStorage.kneecapper_previousPositions = JSON.stringify(bots); let partner = possibleAllies[0]; // Figure out who's doing well. let targets = bots.map(bot => bot[0]).filter(id => (id !== myId) && (id !== partner) && (Math.abs(id - myId) % 3 !== 2)); let flatGrid = [].concat.apply([], grid); targets = targets.sort((a, b) => flatGrid.reduce((n, val) => n + (val === a) - (val === b), 0)); let targetX, targetY; let targetScore = 0; for (let x = 0; x < grid.length; x++) { for (let y = 0; y < grid.length; y++) { let dist = Math.abs(x - myX) + Math.abs(y - myY); let scariness = targets.indexOf(grid[x][y]) + 1; if (scariness === 0) { continue; } // Find a successful opponent who's not too far away. let score = scariness ** 1.5 / (dist + 1); if (score > targetScore) { targetX = x; targetY = y; targetScore = score; } } } // Move toward the target. if (targetX < myX) { return "left"; } if (targetX > myX) { return "right"; } if (targetY < myY) { return "up"; } if (targetY > myY) { return "down"; } return "wait"; } ``` There are two ways to be the best: build yourself up, or tear others down. This takes the latter approach. This finds nearby squares owned by the higher-scoring players and removes them. [Answer] ## Fuzzy Guy ``` function(myself, grid, bots, gameInfo) { var i,j,x,y = 0; this.answerToLifeTheUniverseAndEverything = 42; this.round = gameInfo[0]; this.coloringStruggle = []; this.myColor = myself[0]; this.botCount = bots.length; this.sizeOfGrid = grid.length; this.storageName = 'm53kp1of6igcnpsq'; this.storageName2 = 'ji38df8djsdf8zf0a'; this.distances = {up: 0, right: 0, down: 0, left: 0}; this.foodSmell = {up: 0, right: 0, down: 0, left: 0}; this.botSmell = {up: 0, right: 0, down: 0, left: 0}; this.botPredictedSmell = {up: 0, right: 0, down: 0, left: 0}; this.directionPoints = {up: 0, right: 0, down: 0, left: 0}; this.blockedMoves = function() { var backwards = 'wait', prevDirection, blocked = []; if(myself[1] == 0) { blocked.push('left'); } if(myself[2] == 0) { blocked.push('up'); } if(myself[1] == this.sizeOfGrid - 1) { blocked.push('right'); } if(myself[2] == this.sizeOfGrid - 1) { blocked.push('down'); } if (this.round > 1) { prevDirection = JSON.parse(localStorage.getItem(this.storageName2)); backwards = (prevDirection == 'up' ? 'down' : backwards); backwards = (prevDirection == 'down' ? 'up' : backwards); backwards = (prevDirection == 'left' ? 'right' : backwards); backwards = (prevDirection == 'right' ? 'left' : backwards); blocked.push(backwards); } return blocked; } this.getDistance = function(x1,y1) { return [Math.abs(myself[1]-x1), Math.abs(myself[2]-y1)]; } this.finddeliciousDirection = function() { for (x = 0; x < this.sizeOfGrid; x++) { for (y = 0; y < this.sizeOfGrid; y++) { if (y < myself[2]) { this.foodSmell.up+= ((1.9 - this.coloringStruggle[x][y]) / this.getDistance(x, y).reduce((a, b) => a + b, 0)) / 4; } if (y > myself[2]) { this.foodSmell.down+= ((1.9 - this.coloringStruggle[x][y]) / this.getDistance(x, y).reduce((a, b) => a + b, 0)) / 4; } if (x < myself[1]) { this.foodSmell.left+= ((1.9 - this.coloringStruggle[x][y]) / this.getDistance(x, y).reduce((a, b) => a + b, 0)) / 4; } if (x > myself[1]) { this.foodSmell.right+= ((1.9 - this.coloringStruggle[x][y]) / this.getDistance(x, y).reduce((a, b) => a + b, 0)) / 4; } } } } this.predictFuture = function(x0,y0,x1,y1) { var xMovement = x1-x0; var yMovement = y1-y0; var xAfter2Turns = x1 + xMovement * 2; var yAfter2Turns = y1 + yMovement * 2; var hitsWall = [1, 1]; if (xMovement == 1) { hitsWall = [2, 1] } else if (xMovement == -1) { hitsWall = [0, 1] } else if (yMovement == 1) { hitsWall = [1, 2] } else if (yMovement == -1) { hitsWall = [1, 0] } else { hitsWall = [1, 1] } if (xAfter2Turns < 0) { xAfter2Turns = 0; } else if (xAfter2Turns >= this.sizeOfGrid) { xAfter2Turns = this.sizeOfGrid -1; } if (yAfter2Turns < 0) { yAfter2Turns = 0; } else if (yAfter2Turns >= this.sizeOfGrid) { yAfter2Turns = this.sizeOfGrid -1; } return [xAfter2Turns, yAfter2Turns, hitsWall]; } this.findCloseBots = function() { var prevPositions; var currentBot; var future; if (this.round > 1) { prevPositions = JSON.parse(localStorage.getItem(this.storageName)); } for (i = 0; i < bots.length; i++) { if (bots[i][2] < myself[2]) { this.botSmell.up+= 3 / (this.getDistance(bots[i][1], bots[i][2]).reduce((a, b) => a + b, 0)); } if (bots[i][2] > myself[2]) { this.botSmell.down+= 3 / (this.getDistance(bots[i][1], bots[i][2]).reduce((a, b) => a + b, 0)); } if (bots[i][1] < myself[1]) { this.botSmell.left+= 3 / (this.getDistance(bots[i][1], bots[i][2]).reduce((a, b) => a + b, 0)); } if (bots[i][1] > myself[1]) { this.botSmell.right+= 3 / (this.getDistance(bots[i][1], bots[i][2]).reduce((a, b) => a + b, 0)); } if (this.round > 1) { currentBot = prevPositions.find(function(element) { return element[0] == bots[i][0]; }); if (currentBot[0] != this.myColor) { future = this.predictFuture(currentBot[1], currentBot[2], bots[i][1], bots[i][2]); if (future[1] < myself[2]) { this.botPredictedSmell.up+= (3.14159 / 3 * ([Math.abs(this.myColor - bots[i][0])%3] + 1)) / (this.getDistance(future[0], future[1]).reduce((a, b) => a + b, 0)); } if (future[1] > myself[2]) { this.botPredictedSmell.down+= (3.14159 / 3 * ([Math.abs(this.myColor - bots[i][0])%3] + 1)) / (this.getDistance(future[0], future[1]).reduce((a, b) => a + b, 0)); } if (future[0] < myself[1]) { this.botPredictedSmell.left+= (3.14159 / 3 * ([Math.abs(this.myColor - bots[i][0])%3] + 1)) / (this.getDistance(future[0], future[1]).reduce((a, b) => a + b, 0)); } if (future[0] > myself[1]) { this.botPredictedSmell.right+= (3.14159 / 3 * ([Math.abs(this.myColor - bots[i][0])%3] + 1)) / (this.getDistance(future[0], future[1]).reduce((a, b) => a + b, 0)); } if (future[2][0] == 0) { this.botPredictedSmell.left+=0.314159; } if (future[2][0] == 2) { this.botPredictedSmell.right+=0.314159; } if (future[2][1] == 0) { this.botPredictedSmell.up+=0.314159; } if (future[2][1] == 2) { this.botPredictedSmell.down+=0.314159; } } } } localStorage.setItem(this.storageName, JSON.stringify(bots)); } this.calculateColoringStruggle = function() { for (x = 0; x < this.sizeOfGrid; x++) { var yAxis = []; for (y = 0; y < this.sizeOfGrid; y++) { if (this.myColor == grid[x][y]) { yAxis[y] = 2; } else if (grid[x][y] == 0) { yAxis[y] = 0; } else { yAxis[y] = [0, 1, 2][Math.abs(this.myColor - grid[x][y])%3]; } } this.coloringStruggle.push(yAxis); } } this.getEmptySlotsInDirection = function() { for (x = (myself[1] + 1); x < this.sizeOfGrid; x++) { if (grid[x][myself[2]] == 0) { this.distances.right = (x-myself[1]) * 1.23456789; } else { if (x-myself[1]-1 == 0) { this.distances.right = 0; } break; } } for (y = (myself[2] + 1); y < this.sizeOfGrid; y++) { if (grid[myself[1]][y] == 0) { this.distances.down = (y-myself[2]) * 1.23456789; } else { if (y-myself[2]-1 == 0) { this.distances.down = 0; } break; } } for (x = (myself[1] - 1); x > -1; x--) { if (grid[x][myself[2]] == 0) { this.distances.left = (myself[1]-x) * 1.23456789; } else { if (myself[1]-x-1 == 0) { this.distances.left = 0; } break; } } for (y = (myself[2] - 1); y > -1; y--) { if (grid[myself[1]][y] == 0) { this.distances.up = (myself[2]-y) * 1.23456789; } else { if (myself[2]-y-1 == 0) { this.distances.up = 0; } break; } } } this.getBestDistance = function() { var max = -999, maxDir = 'up'; for (var property in this.distances) { if (this.distances.hasOwnProperty(property)) { this.directionPoints[property] = (this.distances[property] + this.foodSmell[property] - this.botSmell[property] - this.botPredictedSmell[property]); if (this.directionPoints[property] > max && this.blockedMoves().indexOf(property) == -1) { max = this.directionPoints[property]; maxDir = property; } } } return maxDir; }; this.findCloseBots(); this.calculateColoringStruggle(); this.getEmptySlotsInDirection(); this.finddeliciousDirection(); var answer = this.getBestDistance(); localStorage.setItem(this.storageName2, JSON.stringify(answer)); return(answer); } ``` This is my first participation here, but I think it's not last as I really like this KoTH idea Basically what my bot does is: 1. Calculates how much food and how far is in each direction 2. Calculates how many and how close are bots to each direction 3. Calculates some more "very useful" data 4. *Update* - Doesn't go to previous cell in next turn In the end it uses fuzzy logic to weight each direction and picks one with best value I think I'll create a new bot from scratch later as this one was meant to kinda get me rolling [Answer] ### ClaimEverything ``` function (myself, grid, bots, gameInfo) { let my_c = myself[0], my_x = myself[1], my_y = myself[2], size = grid.length, roundnum = gameInfo[0]; let getDistance = function (x1, y1, x2, y2) { return (Math.abs(x1 - x2) + Math.abs(y1 - y2)); }; let getColorValue = function (color) { if (color === 0) { return my_c; } return [my_c, 0, color][Math.abs(my_c - color) % 3]; }; if (!localStorage.claim) { let lastMove = ""; localStorage.claim = JSON.stringify([lastMove]); } offsets = JSON.parse(localStorage.claim); lastMove = offsets[0]; let targets = []; let distance = 999999; let lowestDistance = 999999; for (let grid_x = 0; grid_x < size; grid_x++) { for (let grid_y = 0; grid_y < size; grid_y++) { if (grid[grid_x][grid_y] !== my_c && getColorValue(grid[grid_x][grid_y]) === my_c) { distance = getDistance(my_x, my_y, grid_x, grid_y); targets[distance] = [grid_x, grid_y]; if (distance < lowestDistance) { lowestDistance = distance; } } } } let target = targets[lowestDistance]; //Nothing directly paintable available, search for erasable if (target === undefined) { targets = []; distance = 999999; lowestDistance = 999999; for (let grid_x = 0; grid_x < size; grid_x++) { for (let grid_y = 0; grid_y < size; grid_y++) { if (grid[grid_x][grid_y] !== my_c && getColorValue(grid[grid_x][grid_y]) !== grid[grid_x][grid_y]) { distance = getDistance(my_x, my_y, grid_x, grid_y); targets[distance] = [grid_x, grid_y]; if (distance < lowestDistance) { lowestDistance = distance; } } } } } target = targets[lowestDistance]; let move = ""; if (target === undefined) { move = 'wait'; } else if (target[0] > my_x) { move = 'right'; } else if (target[0] < my_x) { move = 'left'; } else if (target[1] > my_y) { move = 'down'; } else if (target[1] < my_y) { move = 'up'; } else { move = "wait"; } if (move === "wait" && lastMove === "wait") { move = "left"; } localStorage.claim = JSON.stringify([move]); return move; } ``` [Answer] # Eraser This bot tries to erase as much of the board as possible. To avoid getting stuck in an infinite loop, it ignores cells that are very close to the bot that created them. Priorities: 1. If the current cell is erasable, wait 2. Move ~~counter~~-clockwise around the edge of an erasable area (changed to avoid getting stuck erasing borderline) 3. Move towards the nearest erasable cell 4. Move left ``` function([id,x,y],grid,bots){ function manhattan_search(x,y,board_size,callback){ var dest_x,dest_y; try{ for(var dist=1;dist<grid.length*2;dist++){ check(0, dist); //x+ check(0,-dist); //x- check( dist,0); //y+ check(-dist,0); //y- for(var i=1;i<dist;i++){ check( i, dist-i ); //++ check(-i, dist-i ); //-+ check( i,-(dist-i)); //+- check(-i,-(dist-i)); //-- } } return undefined; }catch(e){ //console.log(e); return [dest_x,dest_y]; } function check(vx,vy){ dest_x=x+vx; dest_y=y+vy; if(callback(dest_x,dest_y)) throw undefined; } } function can_erase(x,y){ if(grid[x]!==undefined && grid[x][y]!==undefined && grid[x][y]!==0 && Math.abs(id-grid[x][y])%3===1){ for(var i=0;i<bots.length;i++) if(bots[i][0]===grid[x][y]) break; if(bots[i]) return Math.abs(x-bots[i][1])+Math.abs(y-bots[i][2])>3; } } if(can_erase(x,y)) return "wait"; var name=["up","right","down","left"]; var dx=[0,1,0,-1],dy=[-1,0,1,0]; dir=this.last_dir-1&3; for(var i=1;i<=4;i++){ if(can_erase(x+dx[dir],y+dy[dir])) return name[this.last_dir=dir]; dir=dir+1&3; } var dest=manhattan_search(x,y,grid.length,can_erase); if(dest){ return name[this.last_dir=[ [0,0,1], [3,3,1], [3,2,2] ][Math.sign(dest[1]-y)+1][Math.sign(dest[0]-x)+1]]; } return "left"; } ``` [Answer] # Muncher ``` function(myself, grid, bots, gameInfo) { const W = grid.length, H = grid[0].length; const rounds_left = gameInfo[1] - gameInfo[0]; const directions = [[0, -1], [1, 0], [0, 1], [-1, 0]]; function rank_square([x, y]) { if (grid[x][y] == myself[0]) return 3; if (grid[x][y] == 0) return 1; var value = Math.abs(grid[x][y] - myself[0]) % 3; if (value) value += 1; return value; } function select_long_paths() { const ranked = directions.map(to_coords).filter(legal).map((coords)=>{ return calculate_min_score(4, [coords]); }); const min = Math.min(...ranked); const result = directions.filter((dir, index)=>{return ranked[index] == min;}); return result; } function new_coords([x, y], path) { const last_coords = path[path.length - 1]; return [x + last_coords[0], y + last_coords[1]]; } function calculate_min_score(num_steps, path_so_far) { if (!num_steps) return 0; var scores = directions.map((dir)=>{ return new_coords(dir, path_so_far); }).filter(legal).filter((coords)=>{ var i; for (i = 0; i < path_so_far.length; i++) { if (path_so_far[i] == coords) return false; } return true; }).map((coords)=>{ var new_path = path_so_far.slice(); new_path.push(coords); return rank_square(coords) + calculate_min_score(num_steps - 1, new_path); }); return Math.min(...scores); } function to_coords([x, y]) { return [x + myself[1], y + myself[2]]; } function legal([x, y]) { return 0 <= x && x < W && 0 <= y && y < H; } function filter_by_strength(dirs) { const ranked = dirs.map(to_coords).filter(legal).map(rank_square); const min = Math.min(...ranked); const result = dirs.filter((dir, index)=>{return ranked[index] == min;}); return result; } function convert([x, y]) { x += myself[1]; y += myself[2]; if (x > myself[1]) return "right"; if (x < myself[1]) return "left"; if (y < myself[2]) return "up"; return "down"; } const options = select_long_paths(); const choices = filter_by_strength(options); return convert(choices[Math.random() * choices.length |0]); } ``` [Answer] # No Do Overs ``` function(myself, grid, bots, gameInfo) { this.setupDone = false; if(this.setupDone == false) { var c = myself[0]; var x = myself[1]; var y = myself[2]; var n = grid.length; var dirs = ["left", "up", "down", "right"] for(var _ = 0; _ < 4; _++) { var dir = dirs.splice(Math.random() * dirs.length | 0, 1); if(dir == "left" && x != 0 && grid[x-1][y] == 0) { return "left"; } if(dir == "right" && x != n - 1&& grid[x+1][y] == 0) { return "right"; } if(dir == "up" && y != 0 && grid[x][y-1] == 0) { return "up"; } if(dir == "down" && y != n - 1 && grid[x][y+1] == 0) { return "down"; } if(dir == "left" && x != 0 && grid[x-1][y] != c) { return "left"; } if(dir == "right" && x != n - 1 && grid[x+1][y] != c) { return "right"; } if(dir == "up" && y != 0 && grid[x][y-1] != c) { return "up"; } if(dir == "down" && y != n - 1 && grid[x][y+1] != c) { return "down"; } } dirs = []; if(x != 0) dirs[dirs.length] = "left"; if(x != n - 1) dirs[dirs.length] = "right"; if(y != 0) dirs[dirs.length] = "up"; if(y != n - 1) dirs[dirs.length] = "down"; return dirs[Math.random() * dirs.length | 0]; } } ``` Named "No Do Overs" because it will not paint over its own color, unless the only other option would be "wait". ]
[Question] [ In 2014, demoscener Jakub 'Ilmenit' Debski [released](http://www.pouet.net/prod.php?which=62917) a 250-byte(1) procedural graphics demo for the [Atari XL](https://en.wikipedia.org/wiki/Atari_8-bit_family) called *Mona*. It's drawing the following picture(2): [![mona](https://i.stack.imgur.com/3aZ5s.png)](https://i.stack.imgur.com/3aZ5s.png) Your task is to generate the exact same picture, using the language of your choice. --- (1) Breakdown: 136 bytes of data + 114 bytes of code. (2) The original picture is 128x96. The above version was magnified to 256x192. A few pixels differ from the original, but this is the expected output with the pseudo-code described in this challenge. ## How? This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Although you're authorized to use any method, best results will most probably be achieved by using the original algorithm which is described below. **NB**: This paragraph is *not* a specification but rather a general description. Please refer to the pseudo-code and the reference implementation for the details of the algorithm. The image is made of 64 pseudo-random brush strokes ([see this video](https://youtu.be/0NHaFS9YJBE)), cycling through the following colors (in RRGGBB hexadecimal format): ``` COLOR = [ 0xFFE289, 0xE99E45, 0xA55A00, 0x000000 ] ``` The background is initially filled with the 4th color (black). Each stroke is shorter than the previous one. The pseudo-random generator is using a Linear-Feedback Shift Register (LFSR) on a 32-bit integer initially set to `0x7EC80000` and XOR'ed with `0x04C11DB7`. Each stroke is initialized with a 16-bit value which overwrites the least significant bytes of the seed: ``` BRUSH = [ 0x030A, 0x37BE, 0x2F9B, 0x072B, 0x0E3C, 0xF59B, 0x8A91, 0x1B0B, 0x0EBD, 0x9378, 0xB83E, 0xB05A, 0x70B5, 0x0280, 0xD0B1, 0x9CD2, 0x2093, 0x209C, 0x3D11, 0x26D6, 0xDF19, 0x97F5, 0x90A3, 0xA347, 0x8AF7, 0x0859, 0x29AD, 0xA32C, 0x7DFC, 0x0D7D, 0xD57A, 0x3051, 0xD431, 0x542B, 0xB242, 0xB114, 0x8A96, 0x2914, 0xB0F1, 0x532C, 0x0413, 0x0A09, 0x3EBB, 0xE916, 0x1877, 0xB8E2, 0xAC72, 0x80C7, 0x5240, 0x8D3C, 0x3EAF, 0xAD63, 0x1E14, 0xB23D, 0x238F, 0xC07B, 0xAF9D, 0x312E, 0x96CE, 0x25A7, 0x9E37, 0x2C44, 0x2BB9, 0x2139 ]; ``` These values are also used to set the new position ***(bx, by)*** of the brush at the beginning of the stroke: ***bx*** is given by the least significant byte and ***by*** is given by the most significant byte. The direction of the stroke is given by bits #1 and #7 of the seed. (See the SWITCH statement in the pseudo-code.) ## Pseudo-code Below is the algorithm in pseudo-code, assuming 0-indexed arrays, where `AND`, `OR` and `XOR` mean bitwise operations. ``` seed = 0x7EC80000 dir = 0x00 FOR part = 0 TO 63 word = BRUSH[part] seed = (seed AND 0xFFFF0000) OR word bx = word AND 0xFF by = (word >> 8) AND 0xFF FOR len = 0 TO (64 - part) * 32 - 1 carry = seed AND 0x80000000 seed = (seed << 1) AND 0xFFFFFFFF IF carry seed = seed XOR 0x04C11DB7 dir = seed AND 0xFF ENDIF SWITCH dir AND 0x82 CASE 0x00: by = (by + 1) AND 0x7F ENDCASE CASE 0x02: bx = (bx + 1) AND 0x7F ENDCASE CASE 0x80: by = (by - 1) AND 0x7F ENDCASE CASE 0x82: bx = (bx - 1) AND 0x7F ENDCASE ENDSWITCH drawPixel(bx, by, COLOR[part AND 3]) ENDFOR ENDFOR ``` ## Reference implementation Below is an ungolfed reference implementation in JavaScript. ``` const SEED = 0x7EC80000, XOR_MSK = 0x04C11DB7, COLOR = [ '#FFE289', '#E99E45', '#A55A00', '#000000' ], BRUSH = [ 0x030A, 0x37BE, 0x2F9B, 0x072B, 0x0E3C, 0xF59B, 0x8A91, 0x1B0B, 0x0EBD, 0x9378, 0xB83E, 0xB05A, 0x70B5, 0x0280, 0xD0B1, 0x9CD2, 0x2093, 0x209C, 0x3D11, 0x26D6, 0xDF19, 0x97F5, 0x90A3, 0xA347, 0x8AF7, 0x0859, 0x29AD, 0xA32C, 0x7DFC, 0x0D7D, 0xD57A, 0x3051, 0xD431, 0x542B, 0xB242, 0xB114, 0x8A96, 0x2914, 0xB0F1, 0x532C, 0x0413, 0x0A09, 0x3EBB, 0xE916, 0x1877, 0xB8E2, 0xAC72, 0x80C7, 0x5240, 0x8D3C, 0x3EAF, 0xAD63, 0x1E14, 0xB23D, 0x238F, 0xC07B, 0xAF9D, 0x312E, 0x96CE, 0x25A7, 0x9E37, 0x2C44, 0x2BB9, 0x2139 ]; var ctx = document.getElementById('output').getContext('2d'), seed = SEED, bx, by, word, len, carry, dir = 0, part; ctx.fillStyle = COLOR[3]; ctx.fillRect(0, 0, 128 * 2, 128 * 2); for(part = 0; part < 64; part++) { word = BRUSH[part]; seed = (seed & 0xffff0000) | word; bx = word & 0xff; by = (word >> 8) & 0xff; ctx.fillStyle = COLOR[part & 3]; for(len = 0; len < (64 - part) * 32; len++) { carry = seed & 0x80000000; seed <<= 1; if(carry) { seed ^= XOR_MSK; dir = seed & 0xff; } switch(dir & 0x82) { case 0x00: by = (by + 1) & 0x7f; break; case 0x02: bx = (bx + 1) & 0x7f; break; case 0x80: by = (by - 1) & 0x7f; break; case 0x82: bx = (bx - 1) & 0x7f; break; } ctx.fillRect(bx * 2, by * 2, 2, 2); } } ``` ``` <canvas id="output" width=256 height=192></canvas> ``` You can also [see an animated version here](https://repl.it/JrzB/0). ## Clarification and rules * The output must be cropped to 128x96, even though the algorithm draws outside this area. * If your language/platform is not able to output the exact colors described above, you must use colors that are as close as possible. * Should you decide to use an alternate method, you still must generate the exact same output. * Just in case: submitting the original 6502 assembly code or any slightly edited version is not allowed. * Can you beat 250 bytes? Happy drawing! [Answer] # Excel VBA 32-Bit, ~~1011~~ 407 + 128 = 535 Bytes *Revision 69; ŒîScore= \$-476\$ Bytes* A full VBA subroutine, and helper file ,`"B"`, that takes no input and outputs the *Mona Lisa* to the `ActiveSheet` object on the range `[A1:DX96]`. This solution starts from the Previous Approach, shown below, and uses old school file relies VBA's `Open` and `Get` commands to pull the raw 16-bit values from the file, byte by byte. This approach of using `Open`, `Put`, `Get`, and `Close` for handling raw data I/O dates back at least as far as 1981 with [IBM's Disk Basic and Advanced Basic](https://archive.org/details/IBMBASICAV1.10Manual/page/n337/mode/2up), authored by Microsoft. It is possible that this style of IO goes back even earlier, possibly being defined in 'ANSI X3.60-1978 "For Minimal BASIC"', however this standard is not freely available to the public. This style of handling raw data I/O was inherited by many Microsoft authored BASIC dialects, including GW-BASIC, QuickBASIC, Visual Basic, and Visual Basic for Applications. Notably, this style of raw data I/O was not included in VB.Net. *Note: This solution has been restricted to 32-Bit versions of Excel VBA as [`^` is the `LongLong` type literal](https://codegolf.stackexchange.com/a/143645/61846) in 64-Bit versions* #### The Code, 408 bytes ``` DefByte X-Y Sub M Cells.RowHeight=48 Cells.Interior.Color=0 s=4057*2^19 Open 1As#1Len=1 For p=1To 64 Get#1,,y Get#1,,x s=x+y*256&Or-4^8And s For l=1To(65-p)*32 c=s<0 s=-c*79764919XOr(s And 2^30-1Or-(2^30And s))*2 d=130And IIf(c,s,d) e=2And d f=(-1)^(d>2) x=255-e^7And.5*e*f+x y=IIf(e,y,127And y+f) Cells(y+1,x+1).Interior.Color=Array(0,9036543,4562665,23205)(3And p)*-(y\96+x\128=0) Next l,p Close#1 End Sub ``` ###### Commented ``` DefByte X-Y ' Define all variables starting w. `x` or `y` to be bytes Sub M ' Begin a subroutine Cells.RowHeight=48 ' Make all cells square Cells.Interior.Color=0 ' Fill all squares with black s=4057*2^19 ' define the seed Open 1As#1Len=1 ' open file '1' from the current directory For p=1To 64 ' iter over over all parts Get#1,,y ' grab high byte of word from file '1'; assign as seed for y Get#1,,x ' grab low byte of word from file '1'; assign as seed for x s=x+y*256&Or-4^8And s ' update overall seed, including read seed data For l=1To(65-p)*32 ' Iterate 32 x (65-p) times c=s<0 ' Check if negative (if one of two highest bits is high) ' bit shift lowest 30 bits to the left, include carry s=-c*79764919XOr(s And 2^30-1Or-(2^30And s))*2 d=130And IIf(c,s,d) ' extract direction bits e=2And d ' get lowest bit f=(-1)^(d>2) ' multiplier - negative if 8th lowest bit not set x=255-e^7And.5*e*f+x ' find x value to be updated y=IIf(e,y,127And y+f) ' find y value to be updated ' update the found cell, if and only if x<129 and y<97 Cells(y+1,x+1).Interior.Color=Array(0,9036543,4562665,23205)(3And p)*-(y\96+x\128=0) Next l,p ' close both loops Close#1 ' close file '1' End Sub ' end subroutine ``` #### The Helper File, 128 bytes The read-only helper file, `1` used by this code it the raw bytes of the `BRUSH` array defined in the problem statement saved to a file. A hex dump and the VBA code used to generate the file are included below for completeness ###### Hex Dump ``` Offset: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 00000000: 03 0A 37 BE 2F 9B 07 2B 0E 3C F5 9B 8A 91 1B 0B ..7>/..+.<u..... 00000010: 0E BD 93 78 B8 3E B0 5A 70 B5 02 80 D0 B1 9C D2 .=.x8>0Zp5..P1.R 00000020: 20 93 20 9C 3D 11 26 D6 DF 19 97 F5 90 A3 A3 47 ....=.&V_..u.##G 00000030: 8A F7 08 59 29 AD A3 2C 7D FC 0D 7D D5 7A 30 51 .w.Y)-#,}|.}Uz0Q 00000040: D4 31 54 2B B2 42 B1 14 8A 96 29 14 B0 F1 53 2C T1T+2B1...).0qS, 00000050: 04 13 0A 09 3E BB E9 16 18 77 B8 E2 AC 72 80 C7 ....>;i..w8b,r.G 00000060: 52 40 8D 3C 3E AF AD 63 1E 14 B2 3D 23 8F C0 7B R@.<>/-c..2=#.@{ 00000070: AF 9D 31 2E 96 CE 25 A7 9E 37 2C 44 2B B9 21 39 /.1..N%'.7,D+9!9 ``` ###### Generation Code ``` Private Sub PutBytes() ' Declare vars to be used in making the helper file Dim Brush As Variant, _ HighByte As Byte, _ LowByte As Byte, _ iter As Byte ' open helper file "B" in the current directory ' current directory may be queried using `?CurDir` Open "B" For Binary As #1 ' store the array of unsigned 2-byte ints from the original Let Brush = Array( _ 778, 14270, 12187, 1835, 3644, 62875, 35473, 6923, _ 3773, 37752, 47166, 45146, 28853, 640, 53425, 40146, _ 8339, 8348, 15633, 9942, 57113, 38901, 37027, 41799, _ 35575, 2137, 10669, 41772, 32252, 3453, 54650, 12369, _ 54321, 21547, 45634, 45332, 35478, 10516, 45297, 21292, _ 1043, 2569, 16059, 59670, 6263, 47330, 44146, 32967, _ 21056, 36156, 16047, 44387, 7700, 45629, 9103, 49275, _ 44957, 12590, 38606, 9639, 40503, 11332, 11193, 8505) ' iterate across the Brush values For iter = 0 To 63 ' Split the 16-Bit Brush val into its high and low byte Let HighByte = Brush(iter) \ 256 Let LowByte = Brush(iter) Mod 256 ' Put the bytes into the the open file Put #1, , HighByte Put #1, , LowByte Next iter 'close the file Close #1 End Sub ``` ## Output Gif showing output to the `ActiveSheet` when `M` is called in the VBE immediate window. Note that due to file size limitations this gif has fewer frames than actually produced. [![Mona](https://i.stack.imgur.com/ta7Q9.gif)](https://i.stack.imgur.com/ta7Q9.gif) ## Previous Approach, 618 Bytes An immediate window function that takes no input and outputs the *Mona Lisa* to the `ActiveSheet` object on the range `[A1:DX96]`. There was a *lot* of black magic involved in golfing this down to its current state - some of the tricks involved are [pixel art prep](https://codegolf.stackexchange.com/a/138127/61846), [bit shifting colors](https://codegolf.stackexchange.com/a/137354/61846) [implicit type conversion](https://codegolf.stackexchange.com/a/123224/61846)[,](https://codegolf.stackexchange.com/a/144793/61846) and ~~[`base64` compression](https://codegolf.stackexchange.com/a/167175/61846)~~ [compressing bytes as a `String`](https://codegolf.stackexchange.com/a/167314/61846). ``` Cells.RowHeight=48:Cells.Interior.Color=0:s=4057*2^19:k=256:For p=1To 64:w=k*Asc(Mid(";3 √π≈Ω‚Ä¬¥t√$$A*√£‚Ä∫‚Äù¬ß≈Ω -¬ßÅ√ô4√òX¬∂¬µ≈Ω-¬¥WB√≠ ¬º¬∞‚ÄûV‚ÄòB¬±""¬∂'√Ѭ≥5≈°)¬¢0/%",p))+Asc(Mid("¬ªÀú(9Àú≈Ω¬∫u;W¬≤}¬Æ√èê‚Ñ¢√ì√≤¬†D√¥V¬™)√πzwN.(?‚Äú√Æ)¬∏t√üo√Ñ=9¬¨`:≈íx≈°+√㬧4A¬∂6",p))-1021:s=s And-4^8Or w:x=w mod k:y=w\k mod k:For l=1To(65-p)*32:c=s And-2^31:s=2*(s And 2^30-1Or-(2^30And s)):s=IIf(c,79764919Xor s,s):d=IIf(c,s mod k,d)And 130:e=2And d:f=(-1)^(d>2):x=255-e^7And.5*e*f+x:y=IIf(e,y,127And y+f):Cells(y+1,x+1).Interior.Color=Array(0,9036543,4562665,23205)(3And p)*-(y\96+x\128=0):Next l,p ``` #### Slightly More Readably Formatted Line continuation characters (`:`) are replaced with newline literals for readability ``` Cells.RowHeight=48 Cells.Interior.Color=0 s=4057*2^19 k=256 For p=1To 64 w=k*Asc(Mid(";3 √π≈Ω‚Ä¬¥t√$$A*√£‚Ä∫‚Äù¬ß≈Ω -¬ßÅ√ô4√òX¬∂¬µ≈Ω-¬¥WB√≠ ¬º¬∞‚ÄûV‚ÄòB¬±""¬∂'√Ѭ≥5≈°)¬¢0/%",p))+Asc(Mid("¬ªÀú(9Àú≈Ω¬∫u;W¬≤}¬Æ√èê‚Ñ¢√ì√≤¬†D√¥V¬™)√πzwN.(?‚Äú√Æ)¬∏t√üo√Ñ=9¬¨`:≈íx≈°+√㬧4A¬∂6",p))-1021 s=s And-4^8Or w x=w mod k y=w\k mod k For l=1To(65-p)*32 c=s And-2^31 s=2*(s And 2^30-1Or-(2^30And s)) s=IIf(c,79764919Xor s,s) d=IIf(c,s mod k,d)And 130 e=2And d f=(-1)^(d>2) x=255-e^7And.5*e*f+x y=IIf(e,y,127And y+f) Cells(y+1,x+1).Interior.Color=Array(0,9036543,4562665,23205)(3And p)*-(y\96+x\128=0) Next l,p ``` #### Ungolfed Ungolfed full `sub`routine that takes no input and produces the mona lisa using the method described above on the `ActiveSheet` object ``` Option Private Module Option Compare Text Option Explicit Option Base 0 Public Sub MonaLisa() On Error GoTo 0 Dim part As Integer, _ length As Integer, _ M As Long, _ seed As Long, _ dir As Long, _ word As Long, _ carry As Long, _ bx As Byte, _ by As Byte, _ BRUSH, _ COLOR Let COLOR = Array(&H89E2FF, &H459EE9, &H5AA5, 0) Let BRUSH = Array( _ 778, 14270, 12187, 1835, 3644, 62875, 35473, 6923, _ 3773, 37752, 47166, 45146, 28853, 640, 53425, 40146, _ 8339, 8348, 15633, 9942, 57113, 38901, 37027, 41799, _ 35575, 2137, 10669, 41772, 32252, 3453, 54650, 12369, _ 54321, 21547, 45634, 45332, 35478, 10516, 45297, 21292, _ 1043, 2569, 16059, 59670, 6263, 47330, 44146, 32967, _ 21056, 36156, 16047, 44387, 7700, 45629, 9103, 49275, _ 44957, 12590, 38606, 9639, 40503, 11332, 11193, 8505) Let dir = 0 Let carry = 0 Let seed = &H7EC80000 Let Cells.Interior.Color = 0 Let Cells.ColumnWidth = 2 Call Range("A1:DX96").Select Let ActiveWindow.Zoom = True Call Range("A1").Select For part = 0 To 63 Step 1 Call VBA.DoEvents Let word = BRUSH(part) Let seed = (seed And &HFFFF0000) Or word Let bx = word And 255 Let by = Int(word / (2 ^ 8)) And 255 For length = 0 To (64 - part) * 32 - 1 Step 1 Let carry = seed And &H80000000 Let M = seed And &H40000000 Let seed = (seed And &H3FFFFFFF) * 2 If M <> 0 Then Let seed = seed Or &H80000000 Let seed = seed And &HFFFFFFFF If carry Then Let seed = seed Xor 79764919 Let dir = Int(seed And 255) End If Select Case dir And 130 Case 0: Let by = Int(by + 1) And 127 Case 2: Let bx = Int(bx + 1) And 127 Case 128: Let by = Int(by - 1) And 127 Case 130: Let bx = Int(bx - 1) And 127 End Select If bx<128 And by<96 Then Let Cells(by + 1, bx + 1).Interior.Color = COLOR(part And 3) End If Next length Next part End Sub ``` [Answer] # 8086 Assembly - NASM (MBR) - ~~248~~ 245 bytes ``` [org 0x7C00] [bits 16] push 0xA000 pop es mov si, $brush xor cx, cx mov ax, 0x0013 int 0x10 mov ebx, 0x7EC80000 part_loop: lodsw mov bx, ax mov bp, 64 sub bp, cx shl bp, 5 mov sp, bp len_loop: shl ebx, 1 jnc not_carry xor ebx, 0x04C11DB7 mov dh, bl not_carry: and dh, 0x82 je dir_00 jpe dir_82 js dir_80 dir_02: inc al jmp dir_end dir_82: dec al jmp dir_end dir_00: inc ah jmp dir_end dir_80: dec ah dir_end: and ax, 0x7F7F cmp ah, 96 jae skip movzx di, ah movzx bp, al imul di, 320 add di, bp mov bp, cx and bp, 3 mov dl, byte[bp + color] mov [es:di], dl skip: dec sp jnz len_loop inc cx cmp cx, 64 jl part_loop jmp $ color: db 0x43, 0x42, 0x06, 0x00 brush: dw 0x030A, 0x37BE, 0x2F9B, 0x072B, 0x0E3C, 0xF59B, 0x8A91, 0x1B0B dw 0x0EBD, 0x9378, 0xB83E, 0xB05A, 0x70B5, 0x0280, 0xD0B1, 0x9CD2 dw 0x2093, 0x209C, 0x3D11, 0x26D6, 0xDF19, 0x97F5, 0x90A3, 0xA347 dw 0x8AF7, 0x0859, 0x29AD, 0xA32C, 0x7DFC, 0x0D7D, 0xD57A, 0x3051 dw 0xD431, 0x542B, 0xB242, 0xB114, 0x8A96, 0x2914, 0xB0F1, 0x532C dw 0x0413, 0x0A09, 0x3EBB, 0xE916, 0x1877, 0xB8E2, 0xAC72, 0x80C7 dw 0x5240, 0x8D3C, 0x3EAF, 0xAD63, 0x1E14, 0xB23D, 0x238F, 0xC07B dw 0xAF9D, 0x312E, 0x96CE, 0x25A7, 0x9E37, 0x2C44, 0x2BB9, 0x2139 times 510 - ($-$$) db 0 DB 0x55 DB 0xAA ``` [![mona.jpg](https://i.stack.imgur.com/mkoxS.jpg)](https://postimg.org/image/9ojp15hs3/) [Answer] # x86 opcode, ~~227~~ ~~224~~ 223 Bytes ``` 0000h: 68 20 A8 07 B8 13 00 CD 10 66 BF 40 00 C8 7E 5A 0010h: 89 FD BE 5B 01 AD 89 C7 89 E9 C1 E1 05 66 D1 E7 0020h: 73 09 66 81 F7 B7 1D C1 04 89 FA 80 E2 82 74 09 0030h: 7A 04 78 08 40 40 05 7F 7F 80 C4 02 FE CC 25 7F 0040h: 7F 89 EB 83 E3 03 8A B7 DB 01 88 E3 6B DB 40 01 0050h: C3 26 88 37 E2 C7 4D 75 BC EB FE 0A 03 BE 37 9B 0060h: 2F 2B 07 3C 0E 9B F5 91 8A 0B 1B BD 0E 78 93 3E 0070h: B8 5A B0 B5 70 80 02 B1 D0 D2 9C 93 20 9C 20 11 0080h: 3D D6 26 19 DF F5 97 A3 90 47 A3 F7 8A 59 08 AD 0090h: 29 2C A3 FC 7D 7D 0D 7A D5 51 30 31 D4 2B 54 42 00a0h: B2 14 B1 96 8A 14 29 F1 B0 2C 53 13 04 09 0A BB 00b0h: 3E 16 E9 77 18 E2 B8 72 AC C7 80 40 52 3C 8D AF 00c0h: 3E 63 AD 14 1E 3D B2 8F 23 7B C0 9D AF 2E 31 CE 00d0h: 96 A7 25 37 9E 44 2C B9 2B 39 21 43 00 06 42 0100 6820A8 push A820 0103 07 pop es 0104 B81300 mov ax, 0013 0107 CD10 int 10 0109 66BF4000C87E mov edi, 7EC80040 010F 5A pop dx 0110 89FD mov bp, di 0112 BE5B01 mov si, 015B 0115 AD lodsw 0116 89C7 mov di, ax 0118 89E9 mov cx, bp 011A C1E105 shl cx, 05 011D 66D1E7 shl edi, 01 0120 7309 jnb 012B 0122 6681F7B71DC104 xor edi, 04C11DB7 0129 89FA mov dx, di 012B 80E282 and dl, 82 012E 7409 je 0139 0130 7A04 jpe 0136 0132 7808 js 013C 0134 40 inc ax 0135 40 inc ax 0136 057F7F add ax, 7F7F 0139 80C402 add ah, 02 013C FECC dec ah 013E 257F7F and ax, 7F7F 0141 89EB mov bx, bp 0143 83E303 and bx, 0003 0146 8AB7DB01 mov dh, [bx+01DB] 014A 88E3 mov bl , ah 014C 6BDB40 imul bx, 0040 014F 01C3 add bx, ax 0151 268837 mov es:[bx], dh 0154 E2C7 loop 011D 0156 4D dec bp 0157 75BC jne 0115 0159 EBFE jmp 0159 015B 0A03BE37...3921 brush_dw 01DB 43000642 color_db ``` Image: [![enter image description here](https://i.stack.imgur.com/2dIrs.png)](https://i.stack.imgur.com/2dIrs.png) [Answer] # HTML + CSS + JavaScript (ES6), 499 bytes * HTML: 33 bytes * CSS: 17 bytes * JS: ~~678~~ ~~...~~ ~~478~~ ~~475~~ ~~473~~ ~~465~~ ~~459~~ ~~455~~ ~~451~~ ~~447~~ 449 bytes It's nowhere near 250 bytes, but I'll definitely settle for under 500 bytes! Huge thanks to @Arnauld and @Firefly for helping me golf this monster down. ``` with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x,y,1,1))(s*=2)/2>>31&&(d=s^=79764919),D=d&128?-1:1,d&2?x=x+D&127:y=y+D&127 ``` ``` *{background:#000 ``` ``` <canvas id=C width=128 height=96> ``` For a bigger scale, replace the CSS with the following: ``` canvas { background: #000; image-rendering: pixelated; zoom: 3 } ``` --- ## Annotated History! I had a blast golfing Arnauld's reference code, and you can get some of that here. Enjoy! ``` // One pass through Closure Compiler ADVANCED mode // Added with statement, golfed switch statement, golfed color array // I was surprised Closure Compiler didn't touch the switch statement, like, at least convert it into a bunch of conditional statements. with(C.getContext("2d")){e=2127036416;m=0;fillRect(0,0,256,256);for(n=0;n<64;n++)for(h=[778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505][n],e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e<<=1,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1);} // Background moved to CSS with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=[778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505][n],e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e<<=1,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1);} // e<<=1 same as e*=2 with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=[778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505][n],e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1);} // Semicolon with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=[778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505][n],e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // Failed to golf those colors down ;-; a=n=>["FFE289","E99E45","A55A00","000"][n&3] b=n=>"FFE289E99E45A55A00000".substr(n%4*6,6) c=n=>btoa`Q6√≥√ë=√¥N9@√ìM4√ìM4`.substr(n%4*6,6) // <-- there are 2 unprintables somewhere in there A = [0,1,2,3] console.log(A.map(n=>a(n))) console.log(A.map(n=>b(n))) console.log(A.map(n=>c(n))) d=n=>`FFE289 E99E45 A55A00 000`.split` `[n&3] // Let's compress that hunky array of numbers... [778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505].map(n=>String.fromCharCode(n)).join`` `Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n) // And the char at n=20 became 65533 instead of 57113?? with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n),e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // Maybe try replacing that char with \u000? (Nope, editor doesn't like that at all) with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n)||57113,e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // Okay, just check if n is 20 and make an exception. with(C.getContext("2d")){e=2127036416;m=0;for(n=0;n<64;n++)for(h=n-20?`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n):57113,e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // Also, this could work too... (how to do byte comparison properly? Not so knowledgeable about encodings) +('0x'+btoa`√ì}√ü¬∞D√ò_A√ì¬Ω√êM√ÇA√∞u√î√ê@C√∑~√º√ç√ÑN@√Ø@y√ìo4@u√¥ √∂√õOw√õOB√ú=u√õ¬†√∫]}√∑¬±y√∑@7~;√∞{√ì√é}√õ√ê}√¨1B√ê>√É√Ä√üNu√µ√ßn6]x√∞z√õ√ùxAu√ß}√ìw√ê =√ú@A√ùz√ó√é√ª√Å6.√∂√≥@¬ª√ßn4√∞=√Ç√ú@>¬∑√îMxm√É√õN√Å_C√ü]√∑¬†√õ;√¥M√ª√ò.8√ò}√õ]√Ω`.substr(n*4,4)) // ES6 template string syntax, easy-peasy. with(C.getContext`2d`){e=2127036416;m=0;for(n=0;n<64;n++)for(h=n-20?`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n):57113,e=e&4294901760|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&2147483648,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // 0x80000000 = 2147483648 = 2**31 = 1<<31 // 0x4C11DB7 = 2127036416 = 4057<<19 // 0xffff0000 = 4294901760 with(C.getContext`2d`){e=4057<<19;m=0;for(n=0;n<64;n++)for(h=n-20?`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n):57113,e=e&0xffff0000|h,p=[h>>8&255,,h&255],fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?p[i]--:p[i]++,fillRect(p[2]&127,p[0]&127,1,1)} // Turns out individual x and y vars were better with(C.getContext`2d`){e=4057<<19;m=0;for(n=0;n<64;n++)for(h=n-20?`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=0;k<32*(64-n);k++)l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++,fillRect(x&127,y&127,1,1)} // Reverse loop k with(C.getContext`2d`){e=4057<<19;m=0;for(n=0;n<64;n++)for(h=n-20?`Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñÔøΩÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["FFE289","E99E45","A55A00","000"][n&3],k=32*(64-n);k--;)l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++,fillRect(x&127,y&127,1,1)} // Reverse loop n (wow!) // Side effects: string is reversed, 20th character becomes 43rd character, color array is reversed, and we must add 1 to n when used in the k loop with(C.getContext`2d`){e=4057<<19;m=0;for(n=64;n--;)for(h=n-43?`‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["000","A55A00","E99E45","FFE289"][n&3],k=32*-~n;k--;)l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++,fillRect(x&127,y&127,1,1)} // Everything in the for loop to eliminate "with" brackets with(C.getContext`2d`)for(e=4057<<19,m=0,n=64;n--;)for(h=n-43?`‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["000","A55A00","E99E45","FFE289"][n&3],k=32*-~n;k--;)l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++,fillRect(x&127,y&127,1,1) // Use third argument of "for" with(C.getContext`2d`)for(e=4057<<19,m=0,n=64;n--;)for(h=n-43?`‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["000","A55A00","E99E45","FFE289"][n&3],k=32*-~n;k--;fillRect(x&127,y&127,1,1))l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // Iterate 65 to 1 instead of 64 to 0; removes need to add 1 with -~ at cost of increasing string length by 1 with(C.getContext`2d`)for(e=4057<<19,m=0,n=65;n--;)for(h=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,e=e&0xffff0000|h,x=h&255,y=h>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=e&1<<31,e*=2,l&&(e^=79764919,m=e&255),j=m&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // Rename variables to be more aligned with original names // s = seed, d = direction, w = word with(C.getContext`2d`)for(s=4057<<19,d=0,n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&0xffff0000|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(s^=79764919,d=s&255),j=d&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // s&0xffff0000|w same as s>>16<<16|w (@Arnauld) with(C.getContext`2d`)for(s=4057<<19,d=0,n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s>>16<<16|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(s^=79764919,d=s&255),j=d&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // d can be initialized to 65 (@Arnauld) with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s>>16<<16|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(s^=79764919,d=s&255),j=d&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // Much shorter way to calculate direction (@Arnauld) // j=d&130,i=j%4,2<j?i?x--:y--:i?x++:y++ // d&128?d&2?x--:y--:d&2?x++:y++ with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s>>16<<16|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(s^=79764919,d=s&255),d&128?d&2?x--:y--:d&2?x++:y++ // "&255" of "d=s&255" isn't necessary now (@Arnauld) // s^=79764919,d=s&255 // d=s^=79764919 with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s>>16<<16|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(d=s^=79764919),d&128?d&2?x--:y--:d&2?x++:y++ // s>>16<<16 same as s&~65535 (@FireFly) with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(d=s^=79764919),d&128?d&2?x--:y--:d&2?x++:y++ // Even shorter way to calculate direction (@FireFly) // d&128?d&2?x--:y--:d&2?x++:y++ // D=d&128?-1:1,d&2?x+=D:y+=D with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))l=s&1<<31,s*=2,l&&(d=s^=79764919),D=d&128?-1:1,d&2?x+=D:y+=D // Get rid of l (@Arnauld) // l=s&1<<31,s*=2,l&& // (s*=2)/2>>31&& with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8&255,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))(s*=2)/2>>31&&(d=s^=79764919),D=d&128?-1:1,d&2?x+=D:y+=D // "&255" isn't necessary y=w>>8&255 (@Arnauld) with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x&127,y&127,1,1))(s*=2)/2>>31&&(d=s^=79764919),D=d&128?-1:1,d&2?x+=D:y+=D // x and y are constrained within 255 only upon direction change, making the drawing invalid; constraining every time fixes it. (@Arnauld) // x+=D:y+=D // fillRect(x&127,y&127,1,1) // x=x+D&127:y=y+D&127 // fillRect(x,y,1,1) with(C.getContext`2d`)for(s=4057<<19,d=n=65;n--;)for(w=n-44?` ‚Ñπ‚Æπ‚±ÑÈ∏∑‚ñßÈõé„ÑÆÍæùÏŪ‚éèÎàΩ·∏î͵£„∫ØË¥ºÂâÄËÉáͱ≤Σ¢·°∑Ó§ñ„∫ª‡®â–ìÂå¨Îɱ‚§îË™ñÎÑîÎâÇÂê´Ì걄ÅëÌï∫‡µΩÁ∑ºÍ娂¶≠‡°ôË´∑ÍçáÈÇ£ÈüµÔøΩ‚õñ„¥ë‚Çú‚ÇìÈ≥íÌDZ ÄÁǵÎÅöΆæÈç∏‡∫Ω·¨ãË™ëÔñõ‡∏º‹´‚æõ„ûæÃä`.charCodeAt(n):57113,s=s&~65535|w,x=w&255,y=w>>8,fillStyle="#"+["FFE289","000","A55A00","E99E45"][n&3],k=32*n;k--;fillRect(x,y,1,1))(s*=2)/2>>31&&(d=s^=79764919),D=d&128?-1:1,d&2?x=x+D&127:y=y+D&127 ``` [Answer] # –ë–ö 0010, 254 bytes ### 16-bit DEC PDP-11 compatible Soviet home computer from 1984 [![–ë–ö 0010](https://i.stack.imgur.com/d3B8T.png)](https://i.stack.imgur.com/d3B8T.png) ``` ; Mona Lisa 254-byte intro for BK 0010 ; Download link: https://www.pouet.net/prod.php?which=86820 ; Watch it using RGB->GreyScale adapter! ; Compile this source with PDPy11: https://github.com/imachug/PDPy11 ; Manwe/SandS 2020 BX = BXBY ; low byte in word BY = BXBY+1 ; hight byte in word EMT 14 ; clear screen MOV #233,R0 ; set 256x256 mode EMT 16 MOV #77310,R5 ; seed high word 0x7EC8, R4 = seed low word MOV #BRUSH+128.,R4 LOOP1: MOV R4,R0 ASR R0 COM R0 BIC #177774,R0 ADD #221,R0 ; set color ascii code EMT 16 ; set color MOV -(R4),R0 ; word, seed = (seed AND 0xFFFF0000) OR word MOV (R4),BXBY ; bx in low byte, by in high byte LEN: MOV #2048.,R3 ; (64 - part) * 32 SUB #32.,LEN+2 BEQ LEN+2 ; end of data? go to HALT LOOP2: ASL R0 ROL R5 ; seed = (seed << 1) AND 0xFFFFFFFF BCC NOCAR ; carry = unmodified seed AND 0x80000000 MOV #2301,R2 ; high word of XOR 0x04C1 XOR R2,R5 ; seed = seed XOR 0x04C11DB7 MOV #16667,R2 ; low word of XOR 0x1DB7 XOR R2,R0 DIR: MOV R0,#0 ; direction NOCAR: MOV #BY,R1 ; pointer to coordinate to modify BITB #2,DIR+2 ; dir AND 0x2 BEQ 1 DEC R1 ; point to bx 1: TSTB DIR+2 ; dir AND 0x80 BMI 2 INCB (R1) BR 3 2: DECB (R1) 3: BIC #100200,BXBY ; bx AND 0x7F, by AND 0x7F MOVB BX,R1 MOVB BY,R2 ADD #64.,R1 ADD #144.,R2 EMT 30 ; draw pixel R1,R2 SOB R3,LOOP2 BR LOOP1 BRUSH: ; reversed array .WORD 8505., 11193., 11332., 40503., 9639., 38606., 12590., 44957. .WORD 49275., 9103., 45629., 7700., 44387., 16047., 36156., 21056. .WORD 32967., 44146., 47330., 6263., 59670., 16059., 2569., 1043. .WORD 21292., 45297., 10516., 35478., 45332., 45634., 21547., 54321. .WORD 12369., 54650., 3453., 32252., 41772., 10669., 2137., 35575. .WORD 41799., 37027., 38901., 57113., 9942., 15633., 8348., 8339. .WORD 40146., 53425., 640., 28853., 45146., 47166., 37752., 3773. .WORD 6923., 35473., 62875., 3644., 1835., 12187., 14270., 778. BXBY: ; low word, hight word 0x7EC8 .END ``` ``` [Answer] # Python 3, 544 536 523 519 518 bytes ``` from tkinter import* s=32456<<16 d=0 b="#000" a=Canvas(Tk(),w=128,he=96,bg=b) a.pack() for p in range(64):w=ord("Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ"[p]);s=s&~65535|w;*e,=divmod(w,256)[::-1];exec("c=s&8<<28>0;s=s*2^79764919*c;d=[d,s&255][c];e[d&2<1]=e[d&2<1]+(d&128<1)*2-1&127;a.create_line(*e,e[0]+1,e[1]+1,f=['#FFE289','#E99E45','#A55A00',b][p&3]);"*(64-p)*32) ``` This is a further golfed-down version of [CCB60](https://codegolf.stackexchange.com/users/70031/ccb60)'s Python translation of the reference implementation. I originally used a large hex number to represent the brush of the algorithm, but I later realized that my unfounded assumption that a Unicode string representation wouldn't work in Python was false. I originally thought my byte count was significantly lower, but as [ASCII-only](https://codegolf.stackexchange.com/users/39244/ascii-only) pointed out, I didn't remember to count the Unicode characters as more than one byte. ## Output (128 x 96) [![Mona Lisa in tk window](https://i.stack.imgur.com/MygNU.png)](https://i.stack.imgur.com/MygNU.png) Identical to CCB60's output. [Answer] # Befunge, ~~1131~~ 1052 bytes ``` "Dq~"1+00g"Ot"0"-R"0003"7/"727*"E1"5*\2*39*27*"\1"3*\2*:8-"ph"2*2\"N"2*" =&~a"v v *83+"k~>"*524\*2"XS)"*2"E"-1:*2"YT"*2"j0"\+94*3"G}"+"%~)"8*2\+"%~E"-7:+" w"+< >"V\"2*\2*"@"2*"R/"3*">~/"+56*"Y"2*"##`"2*\5*"1K"2*"%O"2*",+!_"2*25*\"{ "+"+<{"v v"/~Y"+"y~G"+"%~"*5"1"*55*2"k"+98+9:*3"1"*2\*3";i"*2\+"7~@Z>x"*3"?"+92+" q"+" "< >+",~"2*"}zQ1+BK"2*45*\45*",~s"+\25*9+9"~="+29+2*"wq"2*"r~I"+"@<c#"5*\45*"=o "+v v_,#!>#:<"P3 128 96 127"_v`+" k":p39+1:%*:*82<<0<<<\*5"%9D7"+")~"*2"g."+" }{"< #@_:63p"@d~"03p2*13p043p0v^_:"@"%\"@"/p93g28*:*+^>\04>1-:93p3g2*+:v>g+\%:v>:"_"` _3*55+,:2g.:1+2g.2+2g.1+v_:48**\1-:83p\83g:1g:23p\0v |:g39`\0p3g39<3v4\+4<^+1$$< `v0:\%4g++77/"@"\%"@":::<^!:$$_\73g>0#p0#33g#:`#g^#< _$!#v_28*:*::0^>/2%8*-03p:v ">\:88vv%"@":\g38:\<_\73p\1-:!^v4:%\+g32::p31-*2+%2\*"@"% 4/"@":\++"C~":%\+g31:< ~v<\%*<>\"@"/77++p\0^!-g36:%**<>5*9++\:4/8%4*\2%+2*-23p:3 3g+\%:"="3*+\033g`28*v ">88*/7v>g!+53g2-!-153g2%+28*8^v2`\0\%2/2+*:*82:g34+*:*82<p34p33:-*2++%8\*+88< 8 ^-1p++7<^35+*:*28\%**8*28-%2g35>#<*#2+#-:#!5#-3#3p#g1#3-#5!#+< >8+#:/#\4#*%#*^#< ``` There are a number of issues that make this a challenging problem in Befunge: 1. Befunge has only got 2000 bytes of memory to work with (and that includes the source code), so there is no way we can render the entire image into memory before outputting it. The way I work around this is by repeatedly running the algorithm 96 times, once for each line. Each run stores just the pixels that are needed for the current line, which are then output at the end of the run. This allows us to get by with a pixel buffer of just 128 bytes. 2. Befunge has no bit operations whatsoever. Many of the `AND` operations can simply be emulated with a modulo operator (e.g. `a AND 0x7F` can be replaced with `a % 0x80`). However, the `XOR` requires some rather complicated bit manipulation, which we have to deal with one byte at a time, using a set of custom formulas hardcoded to handle the four bytes we need. For example, to calculate `a XOR 0xC1`, we use the formula: `a + 0xC1 - (a/64%4*64 + a%2)*2` 3. While not a limitation of Befunge per se, the interface on TIO is incapable of handling extended ASCII characters in the source, which would have been the easiest way to store the brush and colour tables. I work around this by generating those tables as a list of numbers on the stack, then have a little initialisation loop that copies the values from the stack to memory. A significant chunk of my time was spent golfing this table, which takes up the first five and half lines of code. Unfortunately, despite all my effort to make the code compatible with TIO, and my choice of a file format that could be extracted from TIO ([PPM](https://en.wikipedia.org/wiki/Netpbm_format)), it's just too slow to complete within the 60 second time limit (running the algorithm 96 times probably doesn't help). But since it generates the image line by line, you should still get enough of the output to recover nearly half the image. [Try it online!](http://befunge.tryitonline.net/#code=IkRxfiIxKzAwZyJPdCIwIi1SIjAwMDMiNy8iNzI3KiJFMSI1KlwyKjM5KjI3KiJcMSIzKlwyKjo4LSJwaCIyKjJcIk4iMioiICA9Jn5hInYKdiAgKjgzKyJrfj4iKjUyNFwqMiJYUykiKjIiRSItMToqMiJZVCIqMiJqMCJcKzk0KjMiR30iKyIlfikiOCoyXCsiJX5FIi03OisiIHciKzwKPiJWXCIyKlwyKiJAIjIqIlIvIjMqIj5+LyIrNTYqIlkiMioiIyNgIjIqXDUqIjFLIjIqIiVPIjIqIiwrIV8iMioyNSpcInsgIisiKzx7InYKdiIvflkiKyJ5fkciKyIlfiIqNSIxIio1NSoyImsiKzk4Kzk6KjMiMSIqMlwqMyI7aSIqMlwrIjd+QFo+eCIqMyI/Iis5MisiIHEiKyIgIjwKPisiLH4iMioifXpRMStCSyIyKjQ1Klw0NSoiLH5zIitcMjUqOSs5In49IisyOSsyKiJ3cSIyKiJyfkkiKyJAPGMjIjUqXDQ1KiI9byAiK3YKICB2XywjIT4jOjwiUDMgMTI4IDk2IDEyNyJfdmArIiBrIjpwMzkrMTolKjoqODI8PDA8PDxcKjUiJTlENyIrIil+IioyImcuIisiIH17IjwKI0BfOjYzcCJAZH4iMDNwMioxM3AwNDNwMHZeXzoiQCIlXCJAIi9wOTNnMjgqOiorXj5cMDQ+MS06OTNwM2cyKis6dj5nK1wlOnY+OiJfImAKXzMqNTUrLDoyZy46MSsyZy4yKzJnLjErdl86NDgqKlwxLTo4M3BcODNnOjFnOjIzcFwwdiB8OmczOWBcMHAzZzM5PDN2NFwrNDxeKzEkJDwKYHYwOlwlNGcrKzc3LyJAIlwlIkAiOjo6PF4hOiQkX1w3M2c+MCNwMCMzM2cjOmAjZ14jPCBfJCEjdl8yOCo6Kjo6MF4+LzIlOCotMDNwOnYKIj5cOjg4dnYlIkAiOlxnMzg6XDxfXDczcFwxLTohXnY0OiVcK2czMjo6cDMxLSoyKyUyXCoiQCIlIDQvIkAiOlwrKyJDfiI6JVwrZzMxOjwKfnY8XCUqPD5cIkAiLzc3KytwXDBeIS1nMzY6JSoqPD41KjkrK1w6NC84JTQqXDIlKzIqLTIzcDozIDNnK1wlOiI9IjMqK1wwMzNnYDI4KnYKIj44OCovN3Y+ZyErNTNnMi0hLTE1M2cyJSsyOCo4XnYyYFwwXCUyLzIrKjoqODI6ZzM0Kyo6KjgyPHAzNHAzMzotKjIrKyU4XCorODg8IDgKXi0xcCsrNzxeMzUrKjoqMjhcJSoqOCoyOC0lMmczNT4jPCojMisjLTojITUjLTMjM3AjZzEjMy0jNSEjKzwgPjgrIzovI1w0IyolIypeIzw&input=) If you don't have a local PPM file viewer, you can easily convert to another format using one of the many online converters. One example being [Convertio](https://convertio.co/ppm-converter/). [Answer] # Java 7, ~~681~~ ~~677~~ ~~675~~ ~~626~~ ~~612~~ 610 bytes ``` Object l(){BufferedImage g=new BufferedImage(128,96,1);String b="Ãä„ûæ‚æõ ‹´\u0E3C\uF59B˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮⠄∫ª\uE916·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù\u312EÈõé‚ñßÈ∏∑‚±Ñ\u2BB9‚Ñπ";for(int s=0x7EC80000,d=0,x,y,z=130,u,w,c,r=255,t=127,p=0,o;p<64;p++) {w=b.charAt(p);s=s&0xFFFF0000|w;x=w&r;y=(w>>8)&r;for(o=0;o<(64-p)*32;o++) {c=s&0x80000000;s<<=1;if(c!=0){s^=0x4C11DB7;d=s&r;}x=(u=d&z)==2?x+1&t:u==z? x-1&t:x;y=u==0?y+1&t:u==128?y-1&t:y;if(x<128&y<96)g.setRGB(x,y,new int[] {0xFFE289,0xE99E45,0xA55A00,0}[p&3]);}}return g;} ``` Outputs the following image in resolution 128x96: [![enter image description here](https://i.stack.imgur.com/cvC9v.png)](https://i.stack.imgur.com/cvC9v.png) I know it is not even near 250 bytes but hey it's java -2 bytes thanks to Zachar√Ω [Answer] # C#, ~~960~~ 850 bytes ``` using System.Drawing;_=>{var m = new Bitmap(128,96);Graphics.FromImage(m).FillRectangle(Brushes.Black,0,0,128,96);for(int s=0x7EC80000,d=0,p=0,w,x,y,l,c,t,n=127;p<64;++p){w=new[]{778,14270,12187,1835,3644,62875,35473,6923,3773,37752,47166,45146,28853,640,53425,40146,8339,8348,15633,9942,57113,38901,37027,41799,35575,2137,10669,41772,32252,3453,54650,12369,54321,21547,45634,45332,35478,10516,45297,21292,1043,2569,16059,59670,6263,47330,44146,32967,21056,36156,16047,44387,7700,45629,9103,49275,44957,12590,38606,9639,40503,11332,11193,8505}[p];s=s>>16<<16|w;x=w&255;y=w>>8&255;for(l=0;l++<(64-p)*32;){c=(int)(s&0x80000000);s*=2;if(c!=0){s^=79764919;d=s&255;}t=d&130;x=t==2?(x+1)&n:t==130?(x-1)&n:x;y=t<1?(y+1)&n:t==128?(y-1)&n:y;if(x<=n&y<96)m.SetPixel(x,y,Color.FromArgb((int)new[]{0xFFFFE289,0xFFE99E45,0xFFA55A00,0xFF000000}[p&3]));}}return m;} ``` A straight forward copy of the pseudo code with some golfing added in. There is still a lot that can be golfed but I wanted to post my answer to get the ball rolling. Full/Formatted version: ``` using System.Drawing; class P { static void Main() { System.Func<object, Bitmap> f = _ => { var m = new Bitmap(128, 96); Graphics.FromImage(m).FillRectangle(Brushes.Black, 0, 0, 128, 96); for (int s = 0x7EC80000, d = 0, p = 0, w, x, y, l, c, t, n = 127; p < 64; ++p) { w = new[] { 778, 14270, 12187, 1835, 3644, 62875, 35473, 6923, 3773, 37752, 47166, 45146, 28853, 640, 53425, 40146, 8339, 8348, 15633, 9942, 57113, 38901, 37027, 41799, 35575, 2137, 10669, 41772, 32252, 3453, 54650, 12369, 54321, 21547, 45634, 45332, 35478, 10516, 45297, 21292, 1043, 2569, 16059, 59670, 6263, 47330, 44146, 32967, 21056, 36156, 16047, 44387, 7700, 45629, 9103, 49275, 44957, 12590, 38606, 9639, 40503, 11332, 11193, 8505 }[p]; s = s >> 16 << 16 | w; x = w & 255; y = w >> 8 & 255; for (l = 0; l++ < (64 - p) * 32;) { c = (int)(s & 0x80000000); s *= 2; if (c != 0) { s ^= 79764919; d = s & 255; } t = d & 130; x = t == 2 ? (x + 1) & n : t == 130 ? (x - 1) & n : x; y = t < 1 ? (y + 1) & n : t == 128 ? (y - 1) & n : y; if (x <= n & y < 96) m.SetPixel(x, y, Color.FromArgb((int)new[] { 0xFFFFE289, 0xFFE99E45, 0xFFA55A00, 0xFF000000 }[p & 3])); } } return m; }; f(null).Save("monaLisa.jpg"); } } ``` [Answer] # Python 2.7; ~~880~~ 876 bytes total (including data) -4 bytes to 876 thanks to ZacharyT. (My python interpreter did not like his suggestion to drop the spaces between the 80s and else). Taylor Scott's suggestion to put the brush into Base 10 is excellent, but notjagan (in a comment) took his suggestion one step further, using python's extended integer format in hex. notjagan's answer is in Python 3, and is such an improvement from what I did that he deserves credit. I hope he'll post it as a separate answer. Output into a Tkinter window. Without scaling, the image is very small, but scaling adds about a dozen bytes to the count. ``` B=[0x030A,0x37BE,0x2F9B,0x072B,0x0E3C,0xF59B,0x8A91,0x1B0B, 0x0EBD,0x9378,0xB83E,0xB05A,0x70B5,0x0280,0xD0B1,0x9CD2, 0x2093,0x209C,0x3D11,0x26D6,0xDF19,0x97F5,0x90A3,0xA347, 0x8AF7,0x0859,0x29AD,0xA32C,0x7DFC,0x0D7D,0xD57A,0x3051, 0xD431,0x542B,0xB242,0xB114,0x8A96,0x2914,0xB0F1,0x532C, 0x0413,0x0A09,0x3EBB,0xE916,0x1877,0xB8E2,0xAC72,0x80C7, 0x5240,0x8D3C,0x3EAF,0xAD63,0x1E14,0xB23D,0x238F,0xC07B, 0xAF9D,0x312E,0x96CE,0x25A7,0x9E37,0x2C44,0x2BB9,0x2139] s=0x7EC80000 d=0x00 from Tkinter import * m=Tk() a=Canvas(m,w=128,he=96,bg='black') a.pack() for p in range(64): w=B[p];s=(s&0xFFFF0000)|w;x=w%256;y=w/256 for t in range((64-p)*32): c=s&0x80000000;s=(s<<1)&0xFFFFFFFF; if c:s=s^0x04C11DB7;d=s&0xFF if d&2:x=(x+(-1if d&0x80 else 1))&0x7f else:y=(y+(-1if d&0x80 else 1))&0x7f a.create_line(x,y,x+1,y+1,f=['#FFE289','#E99E45','#A55A00','#000000'][p&3]) mainloop() ``` There's not much going on here except translation into Python and some basic golfing. Sometimes bit-wise manipulations are shorter, sometimes integer math. I could not find a way to pack more of the logic into lists or arrays. The basic algorithm is already pretty dense. [![Mona Lisa as Tkinter output](https://i.stack.imgur.com/DKf2r.png)](https://i.stack.imgur.com/DKf2r.png) [Answer] # [Julia 1.0](http://julialang.org/), ~~627 608 605 597~~ 581 bytes ``` using Images g(i=RGB.(zeros(999,999)),S=0x7EC80000,Z=0x0,F=127,X=255,D=Z)=(1:64 .|>P->(W=Int["Ãä„ûæ‚æõ‹´\ue3c\uf59b˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ª\ue916·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ"...][P];S=S&0xFFFF0000|W;x=W&X;y=W>>8&X;0:32(65-P)-1 .|>_->(C=S&2^31;S=2S&~-2^32;C!=Z&&(S‚äª=0x04C11DB7;D=S&X);(A=D&130)<1 ? (y=-~y&F) : A<3 ? (x=-~x&F) : A<129 ? (y=~-y&F) : (x=~-x&F);i[y+1,x+1]=reinterpret(RGB24,[Z,0xFFE289,0xE99E45,0xA55A00][1+P&3])));save("m.png",i[1:96,1:128])) g() ``` -24 MarcMush Pretty straightforward version of the reference implementation. It writes `m.png` which looks like this [![enter image description here](https://i.stack.imgur.com/UeUce.png)](https://i.stack.imgur.com/UeUce.png) Ungolfed version ``` using Images function m(i=RGB.(zeros(999,999)),S=0x7EC80000,Z=0x0,F=127,X=255,D=Z) for P=0:63 W=codepoint.(["Ãä„ûæ‚æõ‹´\ue3c\uf59b˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ª\ue916·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ"...])[P+1] S=(S&0xFFFF0000)|W x=W&X y=(W>>8)&X for _=0:(64-P)*32-1 C=S&0x80000000 S=(S<<1)&0xFFFFFFFF C!=Z&&(S‚äª=0x04C11DB7;D=S&X) (A=D&130)==Z ? (y=(y+1)&F) : A==2 ? (x=(x+1)&F) : A==128 ? (y=(y-1)&F) : (x=(x-1)&F) i[y+1,x+1]=reinterpret.(RGB24,[0xFFE289,0xE99E45,0xA55A00,Z])[1+(P&3)] end end save("m.png",i[1:96,1:128]) end m() ``` [Answer] # Tcl/Tk, 805 # ~~808~~ ~~815~~ ~~816~~ ~~819~~ ~~826~~ ~~839~~ ~~840~~ ~~843~~ [![Mona](https://i.stack.imgur.com/Tvi3y.png)](https://i.stack.imgur.com/Tvi3y.png) ~~Still the loser, but~~ I had to do it! may be I can golf it more later! **Not the loser now!** ``` rename set S rename expr E pack [canvas .c -w 130 -he 98 -bg #000] .c cr i 67 51 -i [S I [image c photo -w 128 -h 96]] S s 0x7EC80000 S d 0 time {S s [E $s&0xFFFF0000|[S w 0x[lindex {. 30A 37BE 2F9B 72B E3C F59B 8A91 1B0B EBD 9378 B83E B05A 70B5 280 D0B1 9CD2 2093 209C 3D11 26D6 DF19 97F5 90A3 A347 8AF7 859 29AD A32C 7DFC D7D D57A 3051 D431 542B B242 B114 8A96 2914 B0F1 532C 413 A09 3EBB E916 1877 B8E2 AC72 80C7 5240 8D3C 3EAF AD63 1E14 B23D 238F C07B AF9D 312E 96CE 25A7 9E37 2C44 2BB9 2139} [incr p]]]] S x [E $w&255] S y [E $w>>8] time {S c [E $s&1<<31] S s [E $s<<1] if \$c {S s [E $s^79764919] S d [E $s&255]} switch [E $d&130] {0 {S y [E $y+[S h 1&127]]} 2 {S x [E $x+$h]} 128 {S y [E $y-$h]} 130 {S x [E $x-$h]}} $I p #[lindex {FFE289 E99E45 A55A00 000} [E $p-1&3]] -t $x $y} [E (65-$p)*32]} 64 ``` # Tcl/Tk, 1370 Very ungolfed transliteration of the Pseudo-code before the golfing spree began! The `update` line makes possible to view the drawing being done progressively! ``` pack [canvas .c -w 130 -he 98 -bg #000] .c create i 67 51 -i [set p [image create photo -w 128 -h 96]] set COLOR {FFE289 E99E45 A55A00 000000} set BRUSH { 0x030A 0x37BE 0x2F9B 0x072B 0x0E3C 0xF59B 0x8A91 0x1B0B 0x0EBD 0x9378 0xB83E 0xB05A 0x70B5 0x0280 0xD0B1 0x9CD2 0x2093 0x209C 0x3D11 0x26D6 0xDF19 0x97F5 0x90A3 0xA347 0x8AF7 0x0859 0x29AD 0xA32C 0x7DFC 0x0D7D 0xD57A 0x3051 0xD431 0x542B 0xB242 0xB114 0x8A96 0x2914 0xB0F1 0x532C 0x0413 0x0A09 0x3EBB 0xE916 0x1877 0xB8E2 0xAC72 0x80C7 0x5240 0x8D3C 0x3EAF 0xAD63 0x1E14 0xB23D 0x238F 0xC07B 0xAF9D 0x312E 0x96CE 0x25A7 0x9E37 0x2C44 0x2BB9 0x2139} set seed 0x7EC80000 set dir 0x00 set part 0 while {$part<64} { set word [lindex $BRUSH $part] set seed [expr ($seed&0xFFFF0000)|$word] set bx [expr $word&0xFF] set by [expr $word>>8] set len 0 while {$len<[expr (64-$part)*32]} { set carry [expr $seed&0x80000000] set seed [expr $seed<<1] if \$carry { set seed [expr $seed^0x04C11DB7] set dir [expr $seed&0xFF] } switch [expr $dir&0x82] { 0 { set by [expr $by+1&0x7F] } 2 { set bx [expr $bx+1&0x7F] } 128 { set by [expr $by-1&0x7F] } 130 { set bx [expr $bx-1&0x7F] } } $p put #[lindex $COLOR [expr $part&3]] -to $bx $by incr len update } incr part } ``` [Answer] # SmileBASIC, ~~454~~ ~~447~~ 444 bytes ``` DIM C[5]C[1]=-7543C[2]=-1466811C[3]=-5940736S=32456<<16FOR P=-63TO.W=ASC("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"[-P])S=W+(S>>16<<16)C[4]=127AND W C[0]=W>>8FOR L=0TO 31-P*32O=S S=S<<1IF O<0THEN S=79764919XOR S:D=130AND S T=D*2AND 4C[T]=127AND C[T]-(D>>6)+1GPSET C[4],C[0]+144,C[3AND P]NEXT NEXT ``` The string of "x"s had some invalid unicode characters, so I'm not able to post it here. Here are the character codes in decimal (just the BRUSH array in reverse): `8505, 11193, 11332, 40503, 9639, 38606, 12590, 44957, 49275, 9103, 45629, 7700, 44387, 16047, 36156, 21056, 32967, 44146, 47330, 6263, 59670, 16059, 2569, 1043, 21292, 45297, 10516, 35478, 45332, 45634, 21547, 54321, 12369, 54650, 3453, 32252, 41772, 10669, 2137, 35575, 41799, 37027, 38901, 57113, 9942, 15633, 8348, 8339, 40146, 53425, 640, 28853, 45146, 47166, 37752, 3773, 6923, 35473, 62875, 3644, 1835, 12187, 14270, 778` [![enter image description here](https://i.stack.imgur.com/ncCIE.jpg)](https://i.stack.imgur.com/ncCIE.jpg) [Answer] # Python 3 + matplotlib, 541 ``` from pylab import* B='‡®ÉÎ∏∑Ȩ؂¨á„∞éÈصÈÜ䇨õÎ¥éÁ¢ì„∫∏™∞Îï∞ËÄÇÎáêÌäúÈå†È∞†·ÑΩÌò¶·ßüÔñóÍéê‰û£Ôûä§àÍ¥©‚≤£Ô±ΩÁ¥çÁ´ïÂÑ∞„áî‚≠î‰ä≤·í±Èöä·ê©ÔÜ∞‚±ì·åч§äΨæ·õ©ÁúòÓä∏Áä¨ÏûĉÅí„≤çͺæÊé≠·êû„∂≤˺£ÁØÄÈ∂Ø‚∏±Ï∫ñÍú•„ûû‰ê¨Î§´„§°' s=32456<<16 d=0 i=zeros((256,256),'I') for p in range(64): W=ord(B[p]);w=W>>8|W%256<<8;s=s&65535<<16|w;x=[w>>8,w&255] for l in range((64-p)*32): s*=2 if s>>32:s=d=s^4374732215 a=(-1)**(d>>7);b=d>>1&1;x[b]=x[b]+a&127;i[(*x,)]=[9036543,4562665,23205,0][p&3] imsave('i',i.view('4B')[:96,:128,:3]) ``` This saves the image as a png file "i". To display the image you can replace the imsave with an imshow and a show for 545 bytes. [![enter image description here](https://i.stack.imgur.com/0hG9W.png)](https://i.stack.imgur.com/0hG9W.png) [Answer] # :r4, 764 bytes the source for run in [:r4 github](https://github.com/phreda4/reda4/blob/master/r4/Dev/monalisa.txt) [![enter image description here](https://i.stack.imgur.com/nr0v2.png)](https://i.stack.imgur.com/nr0v2.png) ``` ^r4/lib/gui.txt #c $FFE289 $E99E45 $A55A00 $000000 #b $37BE030A $072B2F9B $F59B0E3C $1B0B8A91 $93780EBD $B05AB83E $028070B5 $9CD2D0B1 $209C2093 $26D63D11 $97F5DF19 $A34790A3 $08598AF7 $A32C29AD $0D7D7DFC $3051D57A $542BD431 $B114B242 $29148A96 $532CB0F1 $0A090413 $E9163EBB $B8E21877 $80C7AC72 $8D3C5240 $AD633EAF $B23D1E14 $C07B238F $312EAF9D $25A796CE $2C449E37 $21392BB9 :m pick2 + $7f7f and dup $7f and over 8 >> 96 >? ( 2drop ; ) setxy ink@ a! ; :s +? ( 2* ; ) 2* $4c11db7 xor rot drop dup 24 << 31 >> 1 or over $2 and 2 << 8 xor << rot rot ; :d $100 $7ec80000 0 ( 64 <? )( dup $3 and 2 << 'c + @ ink dup >r 2* 'b + w@ $ffff and swap $ffff0000 and over or 64 r@ - 5 << ( 1? )( >r s swap m swap r> 1- ) drop nip r> 1+ ) 3drop ; : cls d show 'exit >esc< ; ``` I use a trick for make the move without conditionals, transform bit 8 in sign and shift with bit 2. version with stack names: ``` | PHREDA 2017 | https://codegolf.stackexchange.com/questions/126738/lets-draw-mona-lisa ^r4/lib/gui.txt #color $FFE289 $E99E45 $A55A00 $000000 #brush [ $030A $37BE $2F9B $072B $0E3C $F59B $8A91 $1B0B $0EBD $9378 $B83E $B05A $70B5 $0280 $D0B1 $9CD2 $2093 $209C $3D11 $26D6 $DF19 $97F5 $90A3 $A347 $8AF7 $0859 $29AD $A32C $7DFC $0D7D $D57A $3051 $D431 $542B $B242 $B114 $8A96 $2914 $B0F1 $532C $0413 $0A09 $3EBB $E916 $1877 $B8E2 $AC72 $80C7 $5240 $8D3C $3EAF $AD63 $1E14 $B23D $238F $C07B $AF9D $312E $96CE $25A7 $9E37 $2C44 $2BB9 $2139 ] :movxy | dir seed bxy -- dir seed bxy pick2 + $7f7f and dup $7f and over 8 >> 96 >? ( 2drop ; ) setxy ink@ a! ; :step | dir bxy seed -- dir bxy seed +? ( 2* ; ) 2* $4c11db7 xor rot drop dup 24 << 31 >> 1 or over $2 and 2 << 8 xor << rot rot ; :draw $100 | dir $7ec80000 | seed 0 ( 64 <? )( dup $3 and 2 << 'color + @ ink dup >r 2* 'brush + w@ $ffff and | dir seed brush swap $ffff0000 and over or | dir bxy seed 64 r@ - 5 << ( 1? )( >r | dir bxy seed step swap movxy swap r> 1- ) drop nip r> 1+ ) 3drop ; : cls draw show 'exit >esc< ; ``` [Answer] # PICO-8, 343 bytes ``` z=128s=32456g=0cls()for p=64,1,-1do x=ord("9„Åøùò•7„Åõ„Ƕ.„Åà{‚óÜ=‚Åòc„Å´<@„Çìr„Éåw‚óÄ„ÇÅ\t‚Åô,„É®‚Åò‚àß‚Åòùò£+1ùò≤z}„É•,„Å®ùò∫„ÉØùò®„Åì„ɨ„Äç„ǵ‚ñ†„ÅÜ‚ßó„Ç≠„Å≠‚ñà„ŵùòª>x„ÇÑ·µá‚û°Ô∏è„ÅÑ<+„ÅÑ„ÇÜ\n",p)y=ord("!+,„Åä%‚àß1„Å´„Çâ#„ÅÆ„Çõ„Å®>‚ô™ùò≥‚ñà„Ŷ„Åæ„Äå„Éõ>\n‚Å¥ùò¥„Ũ)‚åÇ„Å≠„ÅÆùòµ„DZ0„Ç≥\r}„Åì)‚Å∏‚åÇ„Åì‚Ķ‚ùé„Éà&= „ÅÜ„Ç™¬≤p„Ũ„Åæ‚ßó·µâ‚Ä¢‚åDŽɨ·µâ‚Å∑/7¬≥",p)s=s\1|x>>16|y>>8for l=1,p*32do c=s>>>15s*=2if(c>1)s^^=0x4c1.1db7g=s<<16 n=g>>6&2if(g&2>0)x-=n-1else y-=n-1 if(y%z<96)pset(x%z,y%z,ord("‚Å¥\t·∂†",p-1&3))end end ``` *(Note: StackExchange seems to clobber the tabs, so wherever there is a `\t` sequence, replace it with a literal tab. It still works either way, but using literal tab characters makes the program shorter.)* [![Output of mona.p8](https://i.stack.imgur.com/SRZpx.png)](https://i.stack.imgur.com/SRZpx.png) [Answer] # Yabasic, ~~790~~ 779 bytes An [basic](/questions/tagged/basic "show questions tagged 'basic'") answer that takes no input and outputs to a new graphics window. ``` Open Window 128,96 j=127 s=4057*2^19 k=255 For p=-1To 63 Color Mid$("255,226,137233,158,069165,090,0000,0,0",1+And(3,p)*11,11) If p<0Then Fill Circle 0,0,k:p=0Fi w=Dec(Mid$("30A37BE2F9B072B0E3CF59B8A911B0B0EBD9378B83EB05A70B50280D0B19CD22093209C3D1126D6DF1997F590A3A3478AF7085929ADA32C7DFC0D7DD57A3051D431542BB242B1148A962914B0F1532C04130A093EBBE9161877B8E2AC7280C752408D3C3EAFAD631E14B23D238FC07BAF9D312E96CE25A79E372C442BB92139",4*p,4),16) s=Or(And(-4^8,s),w) x=And(k,w) y=And(w/2^8,k) For l=1To(64-p)*32 c=And(-2^31,s) z=And(2^30,s) s=And(1073741823,s)*2 t=s If z Then t=Or(s,-2^31)Fi s=And(-1,t) If c Then s=Xor(79764919,s):d=And(k,s)Fi d=And(130,d) If d=0Then y=And(y+1,j)Fi If d=2Then x=And(x+1,j)Fi If d=128Then y=And(y-1,j)Fi If d=130Then x=And(x-1,j)Fi Dot x,y Next Next ``` ### Output *The below is scaled by a factor of 8* [![Mona.yab](https://i.stack.imgur.com/R31Ev.png)](https://i.stack.imgur.com/R31Ev.png) [Answer] # Java 11, 518 Bytes ``` var i=new BufferedImage(128,96,1);for(int s=4057<<19,d=0,x,z=130,u,y,c,r=255,t=127,p=-1,o;++p<64;){y="Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ".charAt(p);s=s&~65535|y;x=y&r;y>>=8;for(o=0;o++<(64-p)*32;){c=s>>63;s+=s;d=c!=0?s^=79764919:d;x=(u=d&z)==2?x+1&t:u<z?x:x-1&t;y=u==0?y+1&t:u==128?y-1&t:y;if(x<=t&y<96)i.setRGB(x,y,new int[]{~7542,0xE99E45,0xA55A00,0}[p&3]);}} ``` Readable version: ``` var i = new BufferedImage(128, 96, 1); for (int s = 4057 << 19, d = 0, x, z = 130, u, y, c, r = 255, t = 127, p = -1, o; ++p < 64;) { y = "Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ".charAt(p); s = s & ~65535 | y; x = y & r; y >>= 8; for (o = 0; o++ < (64 - p) * 32;) { c = s >> 63; s += s; d = c != 0 ? s ^= 79764919 : d; x = (u = d & z) == 2 ? x + 1 & t : u < z ? x : x - 1 & t; y = u == 0 ? y + 1 & t : u == 128 ? y - 1 & t : y; if (x <= t & y < 96) i.setRGB(x, y, new int[] { ~7542, 0xE99E45, 0xA55A00, 0 }[p & 3]); } } ``` (scaled by a factor of 4): [![correct version output](https://i.stack.imgur.com/IOqxp.png)](https://i.stack.imgur.com/IOqxp.png) # Out of competition: 497 Bytes Note: As it's not pixel perfect anymore, this one fails the rule: * Should you decide to use an alternate method, you still must generate the exact same output It's a nice result anyway, so I'd like to share the code. ``` var i=new BufferedImage(128,96,1);for(int s=4057<<19,d=0,x,y,z=130,u,c,t=127,p=-1,o;++p<64;){x="Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ".charAt(p);s=s&~65535|x;y=x>>8;for(o=0;o++<64-p<<5;){c=s>>63;s+=s;d=c!=0?s^=79764919:d;x=x+((u=d&z)==2?1:u<z?0:-1)&t;y=y+(u<1?1:u==128?-1:0)&t;if(y<96)i.setRGB(x,y,new int[]{~7542,0xE99E45,0xA55A00,0}[p&3]);}} ``` readable version: ``` var i = new BufferedImage(128, 96, 1); for (int s = 4057 << 19, d = 0, x, y, z = 130, u, c, t = 127, p = -1, o; ++p < 64;) { x = "Ãä„ûæ‚æõ‹´‡∏ºÔñõ˙뷨ã‡∫ΩÈç∏ΆæÎÅöÁǵ ÄÌDZÈ≥í‚Çì‚Çú„¥ë‚õñ\udf19ÈüµÈÇ£ÍçáË´∑‡°ô‚¶≠Íå¨Á∑º‡µΩÌï∫„ÅëÌê±Âê´ÎâÇÎÑîË™ñ‚§îÎɱÂ娖쇮â„∫ªÓ§ñ·°∑Σ¢Í±≤ËÉáÂâÄË¥º„∫Ø͵£·∏îÎàΩ‚éèÏŪÍæù„ÑÆÈõé‚ñßÈ∏∑‚±Ñ‚Æπ‚Ñπ".charAt(p); s = s & ~65535 | x; y = x >> 8; for (o = 0; o++ < 64 - p << 5;) { c = s >> 63; s += s; d = c != 0 ? s ^= 79764919 : d; x = x + ((u = d & z) == 2 ? 1 : u < z ? 0 : -1) & t; y = y + (u < 1 ? 1 : u == 128 ? -1 : 0) & t; if (y < 96) i.setRGB(x, y, new int[] { ~7542, 0xE99E45, 0xA55A00, 0 }[p & 3]); } } ``` Out of competition output (scaled by a factor of 4): [![out of competition output](https://i.stack.imgur.com/4rP8p.png)](https://i.stack.imgur.com/4rP8p.png) ]
[Question] [ An unspeakable number is a number which is divisible by seven or has seven as one of its digits. A children game is to count skipping unspeakable numbers ``` 1 2 3 4 5 6 ( ) 8 9 10 11 12 13 ( ) 15 16 ( ) 18 ... ``` Cantor's version of the game is the sequence defined by recursively filling in the sequence "1 2 3 4 5 6 ( ) 8..." into the gaps ( ) above. `1 2 3 4 5 6 *1* 8 9 10 11 12 13 *2* 15 16 *3* 18 19 20 *4* 22 23 24 25 26 *5 6* 29 30 31 32 33 34 ***1*** 36 *8* 38 ...` Print/output at least the first 7^7 numbers of Cantor's unspeakable number game... While the definition is given recursively, you are not obliged to use recursion in the code. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the shortest byte count wins! Note: The sum of numbers in 1 to 7^7 is 203511962727. The last 10 numbers in that range are 823534 823535 221563 108068 823538 823539 823540 823541 823542 221565. Pastebin dump of first 1000 iterates: <http://pastebin.com/Ksiu9Svf> [Answer] # Python 2, ~~77~~ ~~75~~ ~~74~~ 70 bytes *Thanks to @MartinEnder for suggesting the limit of `9e5` which enderd up working after a change. Thanks to @mschauer for suggesting an infinite stream, saving 4 bytes.* ``` def f(n=0): i=f() while 1:n+=1;yield next(i)if'7'in`n`or n%7<1else n ``` This is a generator that yields an infinite stream of the numbers. [Answer] # Perl, ~~47~~ ~~46~~ ~~41~~ 39 bytes Saved 5 bytes thanks to @Dada ``` say$_=$_%7*!/7/?$_:$a[$b++]for@a=1..1e6 ``` [Try It Online!](https://tio.run/nexus/perl#@1@cWKkSb6sSr2qupahvrm@vEm@lkhitkqStHZuWX@SQaGuop2eYavb//39dX1M9A0MDAA "Perl – TIO Nexus") TIO Nexus, now with Perl support! This will truncate the output after a certain point, but if you have Perl installed, you can run it locally to produce the full output. The code makes use of a couple of strange quirks of Perl's syntax, so I'll break down how it works below. ### Code breakdown: ``` say$_=$_%7*!/7/?$_:$a[$b++]for@a=1..1e6 @a=1..1e6 #Assign the range (1..1,000,000) to the array @a for #and then loop through this list, with $_ as an alias for the list member. As an alias, modifying $_ modifies @a. $_%7*!/7/?$_:$a[$b++] #Ternary operation $_%7 #Returns the residue modulo 7... *!/7/ #...and multiplies it by the negation of whether or not there exists a 7 $_ #Since % and * have the same operator precedence, it must be evaluated in this order #otherwise we would get (!/7/*$_)%7 instead of ($_%7)*!/7/ ?$_ #If the result is non-zero (i.e. truthy), then return $_ :$a[$b++] #Otherwise, return the $b-th element of @a, and increment $b $_= #Reassign the result back to $_, modifying @a say #Prints the result of the assignment, separated by newlines ``` [Answer] # [Pyth](http://github.com/isaacg1/pyth), ~~25~~ ~~23~~ 22 bytes *Thanks to @Maltysen for -2 bytes* ``` .V1=+Y ?}7+PbjbT@Y~hZb ``` A program that prints an infinite stream. [Try it online!](http://pyth.tryitonline.net/#code=LlYxPStZCj99NytQYmpiVEBZfmhaYg&input=) (Output flushed at intervals and times out at 1 min) **How it works** ``` .V1=+Y ?}7+PbjbT@Y~hZb Z = 0, Y = [] Implicit variable assignment .V1 Infinite incrementing for loop with variable b, starting at 1: =+Y Y = Y + (newline) (Implicitly print the result of the following:) ? If }7 7 is in Pb the prime factorisation of b + or jbT the digits of b: @Y Index into Y at index Z Z ~h (Increment Z) else: b b ``` [Answer] ## Haskell, ~~67~~ 66 bytes ``` i#x|mod x 7<1||'7'`elem`show x=f!!i:(i+1)#(x+1)|y<-x+1=x:i#y f=0#1 ``` `f` is an infinite list of the numbers. [Try it online!](https://tio.run/##DcbRCoQgEEDR975iwiBjCZwnIfJXloSUhjSjgp3Af3d9uedu9t5dCKWQ4BzTCgx6xpx73S8uuLjcW/oBG9@2NEn64CAk1@Z3HquGJxJv440SWKKlAwycFx0PdPDY3QGqeuuVTpD6q0dUA/jyBw "Haskell – Try It Online") `f` starts a new iteration with `1` and an index which number to pick of 0. Whenever there's a gap we take a new iteration an pick it's `ith` element and continue the current iteration with `i+1`. If there's no gap, we take the current number `x` and go on without increasing `i`. Edit: -1 byte thanks to @BMO. [Answer] # PHP, 80 (Wahooka) 57 54 bytes While the idea is from Wahooka. I think my version is different enough to make it an own answer: ``` for(;;)echo$a[]=strpos(++$n,55)<-$n%7?"$n ":$a[+$b++]; ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~26~~ 25 bytes ``` 9e5:`t7\yFYA!7-A*~s:2M(2M ``` [Try it online!](http://matl.tryitonline.net/#code=OWU0OmB0N1x5RllBITctQSp-czoyTSgyTQ&input=) with `9e5` replaced by `9e4`, so that the maximum running time and output size of the online compiler are not exceeded. ### How it works This uses iteration instead of recursion. (In fact, MATL doesn't have recursion). An array of numbers from `1` to `9e5` is first generated (this is enough, because `9e5` exceeds `7^7`). Then, numbers that are multiples of `7` or have `7` as digit are identified, and replaced by `1`, `2`, ... The process is iterated until there are no numbers that need to be replaced. ``` 9e5: % Generate array of numbers [1 2 ... 9e5]. This array will become the % output, after some numbers have been replaced ` % Do...while t % Duplicate the array of numbers 7\ % Modulo 7. Gives zero for multiples of 7 y % Duplicate the array of numbers FYA! % Matrix of decimal digits, with a column for each number 7- % Subtract 7 to each entry of that matrix A % Array that contains "true" for columns that only contain nonzeros; % that is, for numbers that do not have 7 as digit * % Multiply. This corresponds to a logical "and" of the two conditions. % A zero indicates that the number at that index needs to be replaced ~ % Logical negate. Each "true" corresponds to a number to be replaced s % Sum. This is the amount of numbers to be replaced, say n : % Push array [1 2 ... n] 2M % Push array of logical values again ( % Replace the numbers at the positions indicated by the logical array % by the values [1 2 ... n] 2M % Push n again. This is used as loop condition, so if it is nonzero % the next iteration will be executed. Note that this executes one % too many iterations: the exit condition is that no replacing has % been needed in the current iteration; but then the current iteration % (which will be the last) was not really necessary. This does not % matter; the last iteration is useless but also harmless % End do...while implicitly. Display implicitly ``` [Answer] # [Tcl](http://tcl.tk), 121 Bytes The trivial solution using infinite loop, nothing fancy.. ``` set r 0;set n 0;while {[set r [expr $r+1]]} {if {![expr $r%7]||(7 in[split $r ""])} {puts [set n [expr $n+1]]} {puts $r}} ``` Ungolfed: ``` set r 0 set n 0 while {[set r [expr $r+1]]} { if {![expr $r % 7] || (7 in [split $r ""])} { puts [set n [expr $n+1]] } { puts $r } } ``` [Answer] # PHP, ~~106~~ 80 bytes Thank you Ismael Miguel for help with the ternary solution and shorter loop code using for instead of while. Could not verify the last parts of the full sequence due to PhpFiddle's 30 second max runtime. Seems to work at least up to 1K based on the sample output provided by the OP. **Golf:** ``` for($n=1;;$n++)echo$a[]=!(strpos($n,"7")>-1||$n%7==0)?"$n ":array_shift($a)." "; ``` **Original golfed version**: ``` $n=1;while(1){if(!(strpos($n,"7")>-1||$n%7==0)){echo$a[]=$n." ";}else{echo$a[]=array_shift($a)." ";}$n++;} ``` [Answer] # Julia, 62 bytes ``` x=[];j=0;for i=1:7^7;x=[x;i%7<1||('7' in "$i")?x[j+=1]:i]end;x ``` Nothing fancy. Uses that the sequence within the gaps is the sequence itself. Makes excessive array copies to save some bytes. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 39 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) `{(⍵⍴⍨⍴i)@(i←⍸('7'∊¨⍕¨⍵)∨0=7|⍵)⊢⍵}⍣≡⍳7*7` `⍳7*7` is 1 2 3...77 `{ }⍣≡` is the *fixed point* operator - apply a function repeatedly until the result stabilises `A@I⊢B` *amend* operator - replace the elements at indices `I` in `B` with `A` `0=7|⍵` bitmask for where the argument is divisible by 7 `'7'∊¨⍕¨⍵` bitmask for where the decimal formatting of the argument contains a 7 `∨` or `⍸` at what indices is either of the above bitmasks true? `i←` assign to `i` `⍵⍴⍨⍴i` reshape the argument to the number of elements in `i` [Answer] # [Perl 6](https://perl6.org), ~~74 57 54~~ 53 bytes ``` sub u{my@u;(1..*).map: {if $_%%7||.comb('7') {@u||=u;@u.shift} else {$_}}} ``` ``` sub u{(1..*).map: {$_%%7||.comb('7')??(@||=u).shift!!$_}} ``` ``` sub u{map {$_%%7||.comb('7')??(@||=u).shift!!$_},1..*} ``` ``` sub u{map {$_%%7||.comb(~7)??(@||=u).shift!!$_},1..*} ``` [Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u2/l9cmqRQWp2bWKBQrRKvqmpeU6OXnJ@bpFFnrmlvr@FQU2NbqqlXnJGZVqKoqBJfq2Oop6dV@19ZISczN7NEAYhK8hWMTA0MDBRS80qKMlOLufSKEysV0vKLFEo1NKPjwHKx/wE "Perl 6 – TIO Nexus") ## Expanded: ``` sub u{ map # for each element transform using: { # bare block lambda with implicit parameter 「$_」 $_ %% 7 # if it is divisible by 7 || # or .comb(~7) # contains the number 7 (implicit method call on 「$_」) ?? # then ( @ ||= u ) # store a new instance of the Seq into an unnamed state array if it is empty # ( it is only empty the first time it is seen in this Seq instance ) .shift # pull one off of the front !! # else $_ # return the value }, 1 .. * # infinite range starting at one ( elements to be mapped over ) } ``` ## Test: ``` $ time perl6 -e'sub u{map {$_%%7||.comb(~7)??(@||=u).shift!!$_},1..*};put 203511962727 == sum u()[^7**7]' True real 2m45.744s user 2m45.416s sys 0m0.212s ``` [Answer] ## Javascript, 80 bytes ``` n=[] r=l=>(m=n[l]=++n[l]||1,!/7/.test(m)m%7?m:r(l+1)) for(;;)console.log(r(0)) ``` Since there is only a minimum requirements but not a maximum requirements, this solution continues to output indefinitely. To verify that the algorithm is correct, you can execute the same code printing only the last 10 numbers and the sum: ``` n = [] r = l => (m = n[l] = ++n[l] || 1, !/7/.test(m) && m % 7 ? m : r(l + 1)) var tot = 0 for (i = 0; i + 1; i++) { v = r(0) tot += v if (i > Math.pow(7, 7) - 11) { console.log(v) } if (i === Math.pow(7, 7) - 1) { console.log(tot) break } } ``` [Answer] # Ceylon, 202 bytes ``` object u satisfies{Integer*}{iterator()=>object satisfies Iterator<Integer>{variable value i=0;late Iterator<Integer>n;next()=>if(++i%7<1||'7'in"``i``")then(i<8then(n=iterator())else n).next()else i;};} ``` This is not a function, but an object declaration implementing an infinite sequence (Iterable). The object can be printed directly, `print(u)` outputs this: `{ 1, 2, 3, 4, 5, 6, 1, 8, 9, 10, 11, 12, 13, 2, 15, 16, 3, 18, 19, 20, 4, 22, 23, 24, 25, 26, 5, 6, 29, 30, ... }` To print more, use `printAll(u)`. The following code uses newlines, and also prints the sum (and the first 30 elements shown above): ``` shared void run() { printAll(u.take(7^7), "\n"); print(sum({0, * u.take(7^7)})); print(u); } ``` Here is the ungolfed and commented version: ``` // Prints cantor's unspeakable numbers. // // Question: http://codegolf.stackexchange.com/q/101231/2338 // My answer: http://codegolf.stackexchange.com/a/101297/2338 // this object u (which is like a singleton class with its single instance) // implements the Iterable<Integer> interface. object u satisfies {Integer*} { // That interface has just one formal method, // `shared formal Iterator<Integer> iterator()`. // Lets implement it by ... iterator() // ... providing for each call ... => // ... a new (anonymous) object, which // implements the Iterator<Integer> interface. object satisfies Iterator<Integer> { // This is the counter (the type `Integer` // is longer than `value`, so we infer it). // We start at 0. variable value i = 0; // This is a nested Iterator. It will be // initialized when first needed, so we don't // get an endless recursion when creating the // first iterator. late Iterator<Integer> n; // `shared formal Integer next()` is the single method // of Iterator which needs to be implemented. next() // each time it is called, the following // expression will be evaluated. => // increment the counter, then check if it // is an unspeakable number. if (++i % 7 < 1 || '7' in "``i``") then // if so, take the nested iterator (and the // first time, for i == 7, create it first), // and take its next element. (i < 8 then (n = iterator()) else n).next() else // otherwise, just return i. i; }; } ``` [Answer] # Ruby, 80 bytes `l=->x{x%7==0||x.to_s[/7/]};a=(1..100);b=a.reject &l p a.map{|x|!l[x]?x:b.shift}` First submission, I'm sure it can be improved :) [Answer] # C ~~157~~ 155 Bytes ``` int c[999999],r;main(_,p){if(_){p=--_;c[_]=1;for(;;){printf("%d ",c[_]);main(0,++_+1);c[_]=r?_+1:c[p++];}}else!p?r=1:p%7?p%10-7?main(0,p/10):(r=0):(r=0);} ``` It looks right, I didn't bother to fully check. Goes up to 999999 which is apparently large enough. Ungolfed version: ``` int cantor_n[1000000]; int cantor_n_safe(int x) { if (!x) return 1; if (x % 7 == 0) return 0; if (x % 10 == 7) return 0; return cantor_n_safe(x / 10); } int main(_, prev_index) { prev_index = --_; cantor_n[_] = 1; for(;;) { printf("%d ", cantor_n[_]); _++; if (!cantor_n_safe(_+1)) { cantor_n[_] = cantor_n[prev_index++]; } else { cantor_n[_] = _+1; } } return 0; } ``` Partially golfed version: ``` int c[999999];int r; safe(x){ !x? r=1: x%7? x%10-7? safe(x/10): (r=0): (r=0); } main(_){ int p; p=--_; c[_]=1; for(;;){ printf("%d ",c[_]); safe(++_+1); if (!r) { c[_]=c[p++]; } else { c[_]=_+1; } } } ``` [Answer] ## R, 86 bytes ``` x=1;while(T<7^7){T=T+1;x[T]=if(!T%%7|7%in%el(strsplit(c(T,""),""))){F=F+1;x[F]}else T} ``` Uses R's Truthy built-in `T` (initialized to `TRUE`/`1`) to count the numbers in the the sequence and the Falsy value `F` (initialized to `FALSE`/`0`) to count the unspeakables. Other than that the program simply checks whether each number is divisible by seven or contains the number. [Answer] # C - 115 bytes ``` s[99],r;g(x){return x%10-7&&(!x||g(x/10));};f(i){(r=++s[i])%7&&g(r)||f(i+1);}main(){for(;;f(0),printf("%d\n",r));} ``` EDIT: Thanks to @mschauer who pointed out I missed some things. [Answer] # Mathematica, 82 bytes ``` Nest[#2&[i=1,If[Or@@(#==7&)/@IntegerDigits@#,i++,#]&/@#]&,Table[i,{i,7^7}],20] ``` [Answer] # JavaScript 81 bytes ### Original (98 bytes) ``` for(c=0,i=1;i<=Math.pow(7,7);i++)/7/.test(i)||i%7==0?(6==c?c=1:c++,console.log(c)):console.log(i); ``` ### Golfed ``` p=console.log;for(c=0,i=1;i<9e5;i++)/7/.test(i)||i%7==0?(6==c?c=1:c++,p(c)):p(i); ``` [Answer] ## Befunge, 100 or 156 bytes This first version is the more portable of the two, limiting itself to 7-bit memory cells, which is what you get in the reference interpreter. ``` "O":0>\#09#:p#-:#1_v<0$.< 9\*"~"g9+1:+1::p00:<+3$_^#g01$$<v"~":/"~"p9g00%"~"::+1+g9\*"~"+g :#15#+5#g+#0%#17#\-#/!#+\#5:#5_^>%00g1+9p"~"/00g2+9p::7%!10>>p#0 ``` The second version only works with interpreters that have 32-bit memory cells, and thus isn't strictly standard Befunge, but that lets us store larger values in memory without having to split them across cells. ``` "O":0>\#09#:p#-:#1_v<0$.< %7::p9g00:+1g9:p00:<+1$_^#g01$$<v01! :#15#+5#g+#0%#17#\-#/!#+\#5:#5_^>p#0 ``` In both cases the program runs indefinitely, but the first version will overflow around the 2 million mark, while the second version should get up to the max int value (around 2 billion). You can [Try it online](http://befunge.tryitonline.net/#code=Ik8iOjA-XCMwOSM6cCMtOiMxX3Y8MCQuPCAKOVwqIn4iZzkrMTorMTo6cDAwOjwrMyRfXiNnMDEkJDx2In4iOi8ifiJwOWcwMCUifiI6OisxK2c5XCoifiIrZwo6IzE1Iys1I2crIzAlIzE3I1wtIy8hIytcIzU6IzVfXj4lMDBnMSs5cCJ-Ii8wMGcyKzlwOjo3JSExMD4-cCMw&input=), but you'll need to kill the process to prevent it from trying to run forever. [Answer] ## Clojure, 130 bytes ``` #(let[R(range(inc %))](rest((reduce(fn[[r s]i](if(or(=(mod i 7)0)((set(str i))\7))[(assoc r i(r s))(inc s)][r s]))[(vec R)0]R)0))) ``` Basic reduce, keeping track of contents of the result vector and how many values have been skipped. The last `0` takes first element of the reduced `[r s]`, `rest` drops first element of the 0-indexed result. [Answer] ## Perl6, 41 bytes ``` put {($_=++$)%%7|m/7/??@_[$++]!!$_}…1e6 ``` [Answer] # JavaScript, 64 bytes ``` for(f=n=>!/7/.test(m=++n[0])*m%7?m:f(n.t=n.t||[0]);;)alert(f(f)) ``` ``` output=[];index=0;for(f=n=>!/7/.test(m=++n[0])*m%7?m:f(n.t=n.t||[0]);index<100;)output[index++]=f(f);console.log(output.join(',')) ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 25 bytes ``` []L³õ@pX%7«/7/tX ?X:UgV° ``` [Test the sum](https://ethproductions.github.io/japt/?v=2.0a0&code=W11Ms/VAcFglN6svNy90WCA/WDpVZ1awCnMwLDdwNyl4&input=) and [last 10 elements.](https://ethproductions.github.io/japt/?v=2.0a0&code=W11Ms/VAcFglN6svNy90WCA/WDpVZ1awCnM3cDcgLUEsN3A3&input=) Generates first 1,000,000 entries of the sequence and prints them. One million is the shortest number over `7**7 == 823543` in Japt. The trailing newline is significant, as it activates the implicit assignment to `U`. Generating the list only takes around a second, but outputting the entire array will likely make your browser hang. ### Unpacked & How it works ``` []L³õX{UpX%7&&!/7/tX ?X:UgV++ [] Assign empty array to U L³õX{ Map over 1 to 1,000,000 inclusive... X%7&& If X is not divisible by 7 and !/7/tX X does not have a digit 7 ?X:UgV++ then X, otherwise the next element already in U Up Push it to the end of U Implicit print U ``` Uses the property that the recursive definition can be resolved by looking at the already generated sequence. [Answer] # [Tcl](http://tcl.tk/), 72 bytes ``` while 1 {puts [expr {[incr i]%7&&7ni[split $i ""]?$i:([incr s]-1)%6+1}]} ``` [Try it online!](https://tio.run/##K0nO@f@/PCMzJ1XBUKG6oLSkWCE6taKgSKE6OjMvuUghM1bVXE3NPC8zurggJ7NEQSVTQUkp1l4l00oDoqA4VtdQU9VM27A2tvb/fwA "Tcl – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [N>ÐѪ˜7åi¯¾è¼}=ˆ ``` Port of [*@TheBikingViking*'s Pyth answer](https://codegolf.stackexchange.com/a/101288/52210), so make sure to upvote him as well! Also outputs the infinite sequence, each number on a separated line. [Try it online.](https://tio.run/##ASUA2v9vc2FiaWX//1tOPsOQw5HCqsucN8OlacKvwr7DqMK8fT3Lhv//) **Explanation:** ``` [ # Start an infinite loop: N> # Push the 0-based loop-index + 1 Ð # Triplicate this now 1-based index Ñ # Pop one and push a list of its divisors ª # Implicitly convert another number to a list of digits, and # append this list of divisors to it ˜ # Flatten it 7åi # Pop and if it contains a 7 # (so either the digits contained a 7 or the divisors): ¯ # Push the global array ¾è # Index the counter variable into it ¼ # And increase the counter variable by 1 afterwards } # Close the if-statement = # Print the top number (without popping) ˆ # Pop and add it to the global array ``` If we only want to output the first \$7^7\$ results instead of printing indefinitely, the `[N>` could be `7mEN` instead. ]
[Question] [ The basic idea of a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](http://codegolf.stackexchange.com/questions/53417/ascii-borromean-rings) to [The Gettysburg Address](http://codegolf.stackexchange.com/questions/15395/how-random-is-the-gettysburg-address). ##Your Task This question is similar, except that it requires printing of a special text - the text of this question. Specifically, the very Markdown code that I am typing right now. To prevent an infinite recursion in the question, the exact text you have to print can be found [here](http://codegolf.stackexchange.com/revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). ##Clarifications * You are not allowed to use any external sources like the internet. * This means that the purpose of this question is not to download this question text and parse it, but instead to store it in you program. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in **bytes** wins! [Answer] # Bash, ~~608~~ 597 bytes ``` 0000000: 74 61 69 6c 20 2d 6e 36 20 24 30 7c 7a 63 61 74 0a tail -n6 $0|zcat. 0000011: 1f 8b 08 00 00 00 00 00 00 00 95 93 d5 b6 e3 3c 0c ...............<. 0000022: 46 ef fb 14 fa 71 a8 2e f7 d0 d5 30 33 f3 8c 9a 28 F....q.....03...( 0000033: 89 57 13 2b c7 56 0a 6f 3f 56 3d cc 53 6e ec 6c 69 .W.+.V.o?V=.Sn.li 0000044: ed 4f 7e 58 11 2c 30 d8 0c 6c 4e 08 5c 00 c2 0b c1 .O~X.,0..lN.\.... 0000055: f2 68 c9 75 c3 25 7b 5e 99 8c 9b b6 a6 8d 95 ed 2b .h.u.%{^........+ 0000066: c8 2a ac 6b 72 25 81 0d 20 0c ad b7 4e 00 21 90 00 .*.kr%.. ...N.!.. 0000077: 77 d2 76 02 d6 81 44 6a a8 d8 0b 05 81 8c 73 82 93 w.v...Dj......s.. 0000088: 52 71 57 56 71 05 05 1a 42 67 5d 09 15 06 05 46 5a RqWVq...Bg]....FZ 0000099: 0e 8e d7 a7 06 f0 84 a0 c2 95 7e e4 d0 a0 db 02 17 ..........~...... 00000aa: 0a 6b fa 50 78 6e e0 c5 79 f6 9e f5 76 b8 1f 01 e1 .k.Pxn..y...v.... 00000bb: d5 c9 4a a4 3d 1a 0e b5 46 c9 75 31 08 82 d9 92 36 ..J.=...F.u1....6 00000cc: 89 3a 88 9d 0f 8f 3b 0a 62 d9 85 e1 7c 3a 1b ef 0f .:....;.b...|:... 00000dd: 31 64 d6 9a c5 07 90 f1 0a 3a 05 c2 f0 42 65 5c 21 1d.......:...Be\! 00000ee: 91 6d 58 74 be 84 73 79 ee 29 fc 61 91 f1 7c 7a 38 .mXt..sy.).a..|z8 00000ff: 1f 56 bc 36 1e 5d ce 8d b1 c1 48 45 a6 fc c8 35 98 .V.6.]....HE...5. 0000110: b8 a7 06 bd de 3f ff 3c e3 ce c3 43 0c cb 5e ef 61 .....?.<...C..^.a 0000121: 15 9d 7e 20 a9 df 60 1b 5b a3 ef 43 ac 45 ad 24 79 ..~ ..`.[..C.E.$y 0000132: 56 c0 d3 71 67 23 22 d9 8f fd a7 dc 42 4b 99 c5 1a V..qg#".....BK... 0000143: 84 36 02 46 bd a5 9f ea f0 73 f4 00 1e e8 ce c2 66 .6.F.....s......f 0000154: 31 cb 6d 7f b7 71 45 7e 0b b7 d0 2f 73 5e bb 14 d9 1.m..qE~.../s^... 0000165: ae da 35 c0 06 64 db 6a 11 6f cb 4a 34 a8 41 ec 55 ..5..d.j.o.J4.A.U 0000176: a3 a7 15 69 f8 0e ac 2b ac b3 42 e0 29 eb 7c d0 f6 ...i...+..B.).|.. 0000187: d3 14 7c ac 99 aa d0 06 33 49 4d 6d b9 4b 51 7f 1c ..|.....3IMm.KQ.. 0000198: a2 2c 82 16 04 05 77 2e 87 17 15 79 fa 1d f3 b1 09 .,....w....y..... 00001a9: 1b 92 f9 62 7f 3a 26 9c 9a d1 e1 7c 64 66 8b d1 d4 ...b.:&....|df... 00001ba: 20 1d ce cd 64 56 e0 c1 78 82 87 38 39 18 ae 2c ad ...dV..x..89..,. 00001cb: 4d 88 ce 33 4a fe 2f 44 c1 3b 15 a2 90 5e cf 40 4c M..3J./D.;...^.@L 00001dc: 04 d0 13 38 16 88 82 78 4d b9 36 d9 05 02 9d c8 d8 ...8...xM.6...... 00001ed: 3c 79 17 35 27 4a 80 da 2e 55 16 81 75 ba 42 32 88 <y.5'J...U..u.B2. 00001fe: 10 cd 72 37 e7 21 79 d4 f5 b6 f3 2d 07 fa 26 0f b0 ..r7.!y....-..&.. 000020f: 41 8b 69 11 b5 5f 33 e6 5f 6e 48 c6 30 6a 69 d1 47 A.i.._3._nH.0ji.G 0000220: 80 95 3e 2c 76 27 2d 08 e9 66 86 20 ec 75 41 bd ab ..>,v'-..f. .uA.. 0000231: da d6 73 e9 b1 f9 d8 8a 0d e9 58 ab 49 a3 2a 5f f5 ..s.......X.I.*_. 0000242: 21 f0 97 87 54 ef 3d 7d 7a b1 15 0a a7 4f c3 3a d2 !...T.=}z....O.:. 0000253: ff 7a .z ``` The above is a reversible hexdump. To create the file, execute ``` xxd -r -c 17 > 55857.sh ``` paste the hexdump and press `Enter`, then `Ctrl` + `D`. To run created file, execute ``` bash 55857.sh 2>&- ``` Any other filename that contains no whitespace, doesn't start with a dash or contains shell expansion characters (e.g. `*`) will do. I chose [zopfli](https://github.com/google/zopfli) as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz. `tail -n6 $0|zcat` reads the last six lines of the source file and pipes them to zcat. The following lines are full of syntax errors and produce no output. Note that zcat will print a warning (since I stripped the checksum of the compressed file), as will bash (because of the syntax errors). These warnings are printed to STDERR (suppressed by `2>&-`), which is allowed by default per [consensus on Meta](https://codegolf.meta.stackexchange.com/q/4780). [Answer] # Javascript (ES6), ~~977~~ ~~964~~ 902 bytes Used the find-and-replace method to save 95 bytes overall, then converted the entire program to Base64, which saved another 62. (Converting the entire thing took me *two whole hours!*) ``` eval(btoa`k23\r8^ù¶¬Ï¢u澡ÿVJ%(®óÝÊ&¦W±Ü³ãç!jY^¾Ãù¯¬zߨºÚn·è§6Èh®×¬·ç(uï³æØhº~¶­úg)àú¬ùÈZúz0Ϭûùg¾«Þúúf§ËêúØ^?>~º&û=A/äb'þwã^ÿjÇ"=Û/=ëx,Ï£³Õ8^øb¾×kzË'ýyßÞ3Þ¶§v³Þ+3ÞØ^Ïx Ïvv·¬³>³íÀÌ(º¿jÉLO¢³ë")Z¯?>{¦ß­«~ß«z«¢­ë>>)àúþkë)yÈ\\÷úØ^þ´Lûù*^r'âq©eË?\r½êòøÆ«Ú0ç(uï­«~#æ¦úÜ©x>®(!·éèÃ>ÐN©­ëÞßè§~)âµï«yË«²*'ú)Í'?\r{´\\¨»èZ½ãùƧù·¾~§wìõêÞ·¯È¨Ïõ½õy­óßOyÓ=øoMóݧ½ç=öáö¼×f½ko?¾'°Ï{(º·Ï¬ûC03\0)Z®'âq«b¢{Ï¢ï­ï§¢ßZ0yÓ®±ï/Æ׫©~²«që>)6)íz¹Þ´yj{>¶­6«¦úþ´O¢³éè´çhÂyhiß­V§wêZ®Ç¾Üüù»­ú)ìµæ:Ëh­ï¢·è§û*.ú趦+r^Ïx(üøÏϬ£ë!¢»^²ß¡×¾³0[Ê׬ÌÁû§³0³?3×>óï>ÜÌÉ@14ãÕÌøϹ§>qÌÊk2ϺަV{>^½©sç0ÿÌ\\ÆÇ1ÿ0óë?3?sõøÏm¶öÿ÷(uè(üû²Öì\\©à{>Ü¢oÙ+>%­{~g>ó÷=þN¬ù®zËb¢v^¶Ü¬nêàfë¢g­ïúÚ>fâÖ~Ï[Z=³>ì¦X­Ì6s=\\ϸ§uìN>qϬøϬúÏÆ¥z»så¬ú`.replace(/z(.)/g,y=>' [:-]().,\r#*!`\\${}=\'>'[parseInt(y[1],36)]).replace(/\+/g,' ')) ``` There are a *ton* of unprintable characters in this, so here's the raw data: <http://pastebin.com/FR6Ah0ZL> And the original encoded text: ``` a=`The basic idea of aVkolmogorov-complexity] challenge isOP a set output inNshortest code (though that meaning has changed now). We have had many of them, from [BL Rings](DJ/53417/ascii-bL-rings)O[The GK Address](DJ/15395/how-random-is-the-gK-address).Q##Your TaskQTE is similar, except that it requires Ping of a specialF- theFof tE. Specifically,Nvery Markdown code that I am typing right now.QTo prevent an infinite recursion inNJ,NexactFyou haveOP can be found [here](Drevisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source).Q##ClarificationsQ- You are not allowedOuse any external sources likeNinternetHmeans thatNpurpose of tE is notOdownload tEFand parse it, but insteadOstore it in you programHisVcode-golf], so shortest code in **bytes** wins!`,[...c='QDEFHJKLNOPV'].map(x=>a=a.replace(eval(`/${x}/g`),` Zhttp://codegolf.stackexchange.com/Zhis JZ text Z. - This ZquestionZettysburgZorromeanZ the Z to ZprintZ [tag:`.split`Z`[c.indexOf(x)])),alert(a) ``` More explanation coming soon! **EDIT 1:** Shaved off 13 bytes. **EDIT 2:** Converted to Base64. [Answer] # Linux Shell 843 bytes ``` #!/bin/sh base64 -d <<M|zcat H4sIAKBL5lUAA5WTQW/bMAyF7/kVHHppgyhOmgRtett2GHbYZQswDEEPtE3bQmzRlegk/vejZLTY etoAIw4s6fHxe9ShIcgx2AJsSQhcAcJRsH46cdtxzZ7PpuCub+lqZXyGosG2JVcT2ADC0HvrRM8E EuBB+kHAOhBVDQ17oSBQcElwKw0PdaMrKNAROutqaDBEQVUrwfHlbgk/ST+e408JHboxGlKxbgGV 5w6On9jrW4/DdxUIz7eNSP+UZbFGzW21DILFia6T6lKdZy+DmrDsQrbbbNcPGYbCWpO/Chkfhe5i L8eD2v5CImPIB1/Dx7L0FP6zyHq32e+yhi/Goyu5MzYY7cDUb7oGJ9275Wx2c/OLBw8HDKfZ7NAo 01elyDfYzrboF6C1qJcJnhXw9DJYlZjoR5Ipt9BTYbEFoauASSGkv4nhH9JL+BF3VrbQLMdF2ngm P8I39KeSL26KLFX7CtiBjH0s4m3dSAxKjR9i9HSmGL56dZV1VkidFYMPyf40Ba81pyp0xUImUyMP U9RvQ1SoUE5Q8eBKODbk6V/IqwkbJvLVw2ZNuDGr/W5ltvlqY5D2O3O/rfBxfY97vH/MzpYuJijz gib+nxVwQpHim80MaCKAnrRR7a1t+aLTqSaHQBAnUs2Td4p5UgnQ2hOl7rQJXSFZqkjKMs5XmDjG 9X7wPavK+zxi1LGYFon0W9bh/3tDIqbjBD16FbCygDzdtCCEyV0Q9nEhco9oe8+1x+7Nij7pWkeS JqJ8XmgD7y6pnp3P81E/zOdwUfUPvwFrjlp7HwQAAA== M ``` All the code in is in the second line. * `base64 -d` decodes base64 data from stdin * `<<M` directs stdin from the script itself with end-of-file at the first line containing only `M` * `|` is a pipe directing the output to * `zcat` a gzip decompressor that reads from stdin. * this followed by the message first gzip compressed and then base64 encoded. Could probably be further golfed by removing line line breaks from the data and using echo instead og heardoc to store it. I feel like I'm missing something important... [Answer] # PHP, 812 Very naive solution. I might come up with something better later. ``` <?=gzinflate(base64_decode("lZNBb9swDIXv+RUcemmDKE6aBG1623YYdthlCzAMQQ+0TdtCbNGV6CT+96NktNh62gAjDizp8fF71KEhyDHYAmxJCFwBwlGwfjpx23HNns+m4K5v6WplfIaiwbYlVxPYAMLQe+tEzwQS4EH6QcA6EFUNDXuhIFBwSXArDQ91oyso0BE662poMERBVSvB8eVuCT9JP57jTwkdujEaUrFuAZXnDo6f2Otbj8N3FQjPt41I/5RlsUbNbbUMgsWJrpPqUp1nL4OasOxCttts1w8ZhsJak78KGR+F7mIvx4Pa/kIiY8gHX8PHsvQU/rPIerfZ77KGL8ajK7kzNhjtwNRvugYn3bvlbHZz84sHDwcMp9ns0CjTV6XIN9jOtugXoLWolwmeFfD0MliVmOhHkim30FNhsQWhq4BJIaS/ieEf0kv4EXdWttAsx0XaeCY/wjf0p5IvboosVfsK2IGMfSzibd1IDEqNH2L0dKYYvnp1lXVWSJ0Vgw/J/jQFrzWnKnTFQiZTIw9T1G9DVKhQTlDx4Eo4NuTpX8irCRsm8tXDZk24Mav9bmW2+WpjkPY7c7+t8HF9j3u8f8zOli4mKPOCJv6fFXBCkeKbzQxoIoCetFHtrW35otOpJodAECdSzZN3inlSCdDaE6XutAldIVmqSMoyzleYOMb1fvA9q8r7PGLUsZgWifRb1uH/e0MipuMEPXoVsLKAPN20IITJXRD2cSFyj2h7z7XH7s2KPulaR5ImonxeaAPvLqmenc/zUT/M53BR9Q+/AQ==")); ``` [Answer] # Bash (+ppmd), 588 bytes This one beats @Dennis answer by 9 bytes, by utilizing the [Prediction by partial matching](https://en.wikipedia.org/wiki/Prediction_by_partial_matching) compression, as implemented by the *ppmd* package (available in the official Debian/Ubuntu repositories). **Golfed (hex dump)** ``` 7461696c202d322024303e450a70706d642064204520313e262d0a6d3420 440a8fafac84a4810000f49f01005c1764584454163b8b4ebdd8f8e5852e 8649a4a01a7674929af8d6cd1d71d0758fed9551a4097e7bb3c21be619a9 ec5d7ea12677f8352b75824dc025a6c1f0b5ca6671431d03ba38e91326eb 8ea9e13a57a9607afd0ae43c8ae548ee3880197e6df9f90b4d6b45baa46b 159a15cd2993dc3f3a50d46226e301b7009174d32328bee2a7c9245a6861 779227a80ca5a016af3f08597440c86db41769b2b2b41646440eda804f9c 3b2aa70530f3080bec7acd58674a3d3b2f78f1c6674d938e415b3d07ab1e 3431a2e3165013b8251d1641f8d94be72b33aecd638d4332faa99662d848 cd5564e305b13f6ba0ccd2b105a0771ab454c417d2ebb9095291e768edde acec556546dcf60c2cc0af962f96bb7b92d98f465bb799cd92b1b0a49a03 3261943b57a194110556ee4d39226ddfc7483ac83c6a840ba93d41ab64cf 926bbfd0423a43f7c75d73ac55d653e7de9c2d6c9508f6d371870041b133 91da72facf5b83edaf665607277384f903c1475b46e77ee58be32c6bfd5e 0eff7b206eb69b149b6649fd2f5fd933e7f8e2c61179f633551369077edb c3de193a36f439718d0e249c04c99a88dc45ed7f4b1a8af2684d123397d9 efbca4ce93d202c7ef1f3d895fd56b655b2e34d9da1b301091e2d34e4272 342d5ea16b0973cf83dfb702009437de36f5f6292ec02aab23c3b27bb6ea dfc40c378f61236db04dda644577114b8340ff93b65928041d8fa801f03c abe0a89e552dc56842c5782a83992efe7200 ``` **Usage** > > Please take care to pre-install *ppmd* and *m4* packages (if not installed) before running this > > > ``` #Decode into "C" xxd -p -r <<EOF>C 7461696c202d322024303e450a70706d642064204520313e262d0a6d3420 440a8fafac84a4810000f49f01005c1764584454163b8b4ebdd8f8e5852e 8649a4a01a7674929af8d6cd1d71d0758fed9551a4097e7bb3c21be619a9 ec5d7ea12677f8352b75824dc025a6c1f0b5ca6671431d03ba38e91326eb 8ea9e13a57a9607afd0ae43c8ae548ee3880197e6df9f90b4d6b45baa46b 159a15cd2993dc3f3a50d46226e301b7009174d32328bee2a7c9245a6861 779227a80ca5a016af3f08597440c86db41769b2b2b41646440eda804f9c 3b2aa70530f3080bec7acd58674a3d3b2f78f1c6674d938e415b3d07ab1e 3431a2e3165013b8251d1641f8d94be72b33aecd638d4332faa99662d848 cd5564e305b13f6ba0ccd2b105a0771ab454c417d2ebb9095291e768edde acec556546dcf60c2cc0af962f96bb7b92d98f465bb799cd92b1b0a49a03 3261943b57a194110556ee4d39226ddfc7483ac83c6a840ba93d41ab64cf 926bbfd0423a43f7c75d73ac55d653e7de9c2d6c9508f6d371870041b133 91da72facf5b83edaf665607277384f903c1475b46e77ee58be32c6bfd5e 0eff7b206eb69b149b6649fd2f5fd933e7f8e2c61179f633551369077edb c3de193a36f439718d0e249c04c99a88dc45ed7f4b1a8af2684d123397d9 efbca4ce93d202c7ef1f3d895fd56b655b2e34d9da1b301091e2d34e4272 342d5ea16b0973cf83dfb702009437de36f5f6292ec02aab23c3b27bb6ea dfc40c378f61236db04dda644577114b8340ff93b65928041d8fa801f03c abe0a89e552dc56842c5782a83992efe7200 EOF #Run bash C 2>/dev/null #Cleanup rm -f C D ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 543 bytes ``` ¨ë⁶ḂcΔȦ₀fα [ȧġ:ko¦Ṁġċov-ẋΞ1y]ŀḣ˹∫⁰ Ṗn↑a₂sẏ_†¹¬Ëβḟ…cÖ¿(σ‼Ä ẏġ¬Ȧ,χg∂ηw).ẆW√ ÷hṀẏ₀fεm,ḟm [ÿ→Ȯṁ¬¥Ż'](⁸ẋ…://cθ)£⌈g.ẋKżxχg.ςm/□os/53417/⁸ÿ:-ÿ→⁰ṁ¬-►gs)†o [ëGγ⁸?Ÿ÷D](⁸ẋ…://cθ)£⌈g.ẋKżxχg.ςm/□os/15395/ȯw-ŸṙÖ-is-´-γ⁶Ÿg-Ÿ∂Δ).¶¶##γYTψ<ıT□N¹∫₇>,ẊΠȦ…¹↑ṙṘ∫ḃρ!θ a⁹←£x -ε£x₀fı≤□N.πΓÄl,ε√Yṁ⌐÷ΦcÖ¿Ä Iαmẏẏġṙ↔Ṅ¤.¶…o□√Ėα¬ΓŸïβγx↕ε□N,ε×Ẋ3£xẏo√ †oΠN↑ċnb₃‡÷[½→](⁸ẋ…://cθ)£⌈g.ẋKżxχg.ςm/Ω∟ṡ/1f731ea3-0950-4b03-ae95-24fa812a9a28/√w-Ȯ().¶¶##Ŀ=Cσ¶¶-ẏuα→⁰tα◄₇⁰ Üu▲ΨΞẊėŻ⁵←↕Ëλ;≠.¶-ïTÄẋȦ…εṗ↑₀fı≤□N¹∫ṅ ⁰ ⌉⌋ḋṡ □,ẋ'▲∂ȷ₉'it,⁸t□ḋ≠†oȮR₃i↑↕ẏo⁹ṙ.¶-ïT¹∫[ȧġ:cθ)-£⌈g],⁵o⁶‡+□{Φ¹¬**ḃŸy**Ẇ≠s! ``` [Try it online!](https://tio.run/##lZPPTxpBHMX/lTUeFMuyIhLF/jq0SdM08dCYNMaYBo2iscgBrZpelpWu0CVRq0LbNArRUhuJFi2wizYkM7sJp@FvmPlH7NulPfTWnnaz853Pe/Pe7MJqcun2lpzSM5Gqc1ObZfvtstDUeVaVptpf7dLYUoKUuaXaJdtIvJZ502CHwY1pR@XmMTWIJTLY@V3iVn5Z6LtRoWlJ3tx@KdQisUiFGuySm0dCLc/SPGn1dzaFekPTEkbsEqm0y/7OVkxkNNZY8wV4U38hMp8k2liAIEY8H7W4H4S4NEVbQn/fPudWilTIF@e6b7pfpEwYAn1MUWaZ6SPHIpeJAWQ8c27WgQ50tLgi8qVEUgmHhoMjCnbQ1pjsseDbg8ki34wlfbCcgMrZE3aFqYeOSRuP/08iGA5Fwkr7Yk12TG59pHl5MSmTH7ILrDtmDJ/ds@77AqRO6r297GpyopO5Z1cnsH@8m6W29cDPm@9YETWoZXzTd4Hi1gcscnOzk@phphQVKSzskON1SWY1PNyk7KrInrigQEdlezT9ys9qiHMSZxS5Hdpg3Q6Q/lNWjSNerwTAhb7PrTQ5gStIJoDANjvPqqTC9hDDBbtkV@tCPwAPeGBpARZD0AUi4VbmZseK4zBrG8szQkPNJdqYIj8R879myL6JzBG3SkpwfiQUnIuG5MFIeFAenhkMydG5SFgeGp6PjgaHopHo0KgC1TW5fd7/J0u7df9RZ9N9xx3dXmXVbsEreCmkkap7SennVZG/ZKfsEPbtgnMtUjXEiJPhnl7fFdkiYDK9mKBpePMKYDVuFXCsvwL2muLWW8mFilxW5AxuGrAuYRXtGX2QQdPthtCyfYsrfgSwgiUMQcPNqn3@HCEtumD9wAsxZaGJ3/Iev/v3uXHJ3bymgalhECWV7oD2hpXdX2xgANfCMTfwbOrAJ3tub38B "Husk – Try It Online") I have just revamped the compression algorithm in Husk, making it quite a lot faster. I wanted to try it on a question with a long text to compress, and here was my occasion. This took less than two seconds to compress, so I'm happy about my revamping. It's also currently shorter than any other answer to this challenge (which I realize is quite old, but I'm happy about my compression system all the same ^^). [Answer] # PHP, 890 bytes (no built in compression) I promised a solution less naive than gzipping (which feels too much like cheating even though it's legal here), so here it is. ``` <?php @$e=explode;$s='Thzbasic ideaKEkolmogorov-compl#ity] c:llengz`Da sejQtpuj_L^(thQgh<meX6 :s chXgeHnF). Wz:vz:HmXy of{emxfrom [BO R6@53417/ascii-bO-r6s) Z[ThzGU A&@15395/hF-rXdom-is-the-gU-a&sJYQr Task Th`} `simil+x#cept<ijPquiPs pr_t6Kspecial V-LV?. Spec>lly,Lvery M+kdFn %<I am typ6 righjnF. To pPvenjX _f_itzPcurs; _L},L#acjVyQ :vzDcX bzfQnH[heP~Pvis;s/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-=JCl+>t;s - YQ +znojallFeHZuszXy #$al =s likeL_$etNmeXs{atLpurposz? `nojZdFnload{`} VXHp+szitxbuj_steaHZstorzij_ yQ programN`E%-golf]xso ^_ **bytes** w_s!';$m=$e('|',', |ex|tern|code|ddPs|ar|_g|ha|ion|{aj|sQrce|ifica|of{`}|s~}s/|Zpr_j|[tag:|ow|d |). ##| of a |{z|. - Th`|orromeX|re|ou|ettysburg|texj|an|to |shortesjcodz|in|is |t |e | th|question|](http://codegolf.stackexchange.com/');foreach(str_split('x#$%&+6:;<=>?@DEFHJKLNOPQUVXZ^_`jz{}~')as$i=>$l)$s=implode($m[$i],$e($l,$s));echo$s; ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 1055 bytes ``` interface T{static void main(String[]a){System.out.print("The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](_%s/53417/ascii-borromean-rings) to [The Gettysburg Address_%s/15395/how-random-is-the-gettysburg-address). \n##Your Task\nThis % is similar, except that it requires printing of a special text - the text of this %. Specifically, the very Markdown code that I am typing right now. \nTo prevent an infinite recursion in the %, the exact text you have to print can be found [here_revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). \n##Clarifications\n- You are not allowed to use any external sources like the internet. \n- This means that the purpose of this % is not to download this % text and parse it, but instead to store it in you program. \n- This is [tag:code-golf], so shortest code in **bytes** wins!".replaceAll("_","])http://codegolf.stackexchange.com/").replaceAll("%","question"));}} ``` [Try it online!](https://tio.run/##XZNvb9pADMa/ikeFBBUHpRT1z151ezHtxd6sSNNEUWUSJ7mS3KV3DjSq@tmZnbTVNgkBurOfe/yz/Yh7NL4m95jujkfrmEKGCcHqJTKyTWDvbQoVWje642Bdvt7g@OWujUzV1Dc8reWQR4NVQbDFKAk2JQSfAcKaMb/Z@bLyuQ9@bxJf1SU9W243kBRYluRyAhuBPXQykhOJQWTrhsE6YFGNhQ9MkSHxKcGIC9/khdwgQ0XoxBIUGFVQ1FJw/jCewi@Sw71@qXnXqiERqyaQBV/B@osP8ivp8FME4mb0MIyz5eJifjnDmFhrtu8BRouOY/W41iK/EXMbt03I4TZNA8WoqfPl4no5K/zBBHSpr4yNRt4z@Ue0wT5azN27k5Pfvgmwwri7d6tCEAyVQ7SVLTFMgJ4Tqrkv0jIEemqsJPeUtOKOb6wpsVgC0zOD6WB1f7taVXMKdxqS2URgt5MuYk@hhR8Ydqk/uJ5p98x3wAq4rVU92LxgJaleV9oc2pO2x0lTMussk3hKmhCtd@99Gvb69IwJ9z5a3/Rd@OhvIgpbgsw3LoV1QYEeRNqqjDDMLhdzwoU5u16emYvt2cIgXS/N@UWGV/NzvMbzq9ne0sFEgZfQG8mvQqwrkVXl3hkQtoCBpACxXJb@IGMhFppIoKMg1ig44dbLRCjtjjrv3fg7YhU20PVFRyD2hDSibkLtRecDsbZN3xF9BVp6Gbi3m46BTAPUGCTF8gS23VjL7mDnKLIPeqEIFVYdfB6w@ut5@XRbpH0yuS@zzURs/7cTkn16um3l4PQUDqL/aTANVJeyx7dlORo8DCaDzbhgrm9mM81Qoansd7KTQev2Ziq7ORuM/0kbStpTI68I18F4/Pn19Xj8Aw "Java (OpenJDK 8) – Try It Online") By using `replaceAll` for some of the long strings, I saved a few bytes. Golfed 2 bytes by putting "](" before "\_" into the replace part. Thanks to FlipTack for golfing 19 bytes by taking out unnecessary whitespace and unnecessary stuff! (This was a really long time; I've learned a lot since then) Thanks to Kevin Cruijssen for golfing off a few bytes. I'm not sure how to use string formatting to help me here, unfortunately. NOTE: This answer is now referenced [here](https://codegolf.stackexchange.com/a/226479/68942) and thus cannot be golfed anymore. [Answer] # Fourier, 3359 bytes ``` 84a104a-3a32a98ava115a105a99a32a105a-5a^a97a32a111a-9a32a97a32a91a116a97a+6a58a107a+4a-3a^a+2a-8a+8a+3a-3a+7a45a99a111a-2a+3a-4a-7a120a105a116a+5a93a32a99a+5a97a108aa-7a+9a-7a-2a32a105a115a32a116a-5a32a112a+2a-9a+5a+6a32a97a32a115a101a116a32a111a+6ava-4a+5ava32a105a+5a32a116a104a-3a32a115a104a+7a+3a+2a101a115a^a32a99a111a100a^a32a40a116a104a+7a+6a103a^a32a116a104a97a116a32a109a-8a97a110a-5a+5a-7a32a104a97a115a32a99a+5a97a110a-7a-2ava32a110a^a+8a41a46a32a87a101a32a104a97a118a101a32a104a97a+3a32a109a97a110a121a32a111a-9a32a116a104a-3a+8a44a32a102a114a-3a-2a32a91a66a111a+3aa-3a-2a-8a97a110a32a82a105a+5a-7a115a93a40a104a116aa-4a58a47aa99a111a100a^a+2a+8a-3a-6a46a115a^a97a99a+8a-6a120a99a+5a97a110a-7a-2a46a99a111a-2a47a113a+4a101a115a^a105a+6ava+5a47a53417o47a97a115a99a+6aa45a98a111a+3aa-3a-2a-8a97a110a45a114a-9a+5a-7a115a41a32a116a-5a32a91a84a104a-3a32a71a101a116aa+5a-6a98a117a-3a103a32a65a100aa114a101a115aa93a40a104a116aa-4a58a47aa99a111a100a^a+2a+8a-3a-6a46a115a^a97a99a+8a-6a120a99a+5a97a110a-7a-2a46a99a111a-2a47a113a+4a101a115a^a105a+6ava+5a47a15395o47a104a+7a+8a45a114a97a110a100a111a-2a45a105a115a45a116a104a-3a45a103a-2a116aa+5a-6a98a117a-3a103a45a97a+3aa114a101a115aa41a46a10aa35aa89a111a+6a-3a32a84a97a115a-8a10aa84a104a^a115a32a113a+4a101a115a^a105a+6ava32a105a115a32a115a105a+4a-4a+3a97a114a44a32a101a120a99a+2a112a+4a32a116a104a97a116a32a105a116a32a114a101a113a+4a105a+9a101a115a32a112a+2a-9a+5a+6a105a+5a-7a32a111a-9a32a97a32a115a-3a101a99a+6a97a108a32a116a101a120a-4a32a45a32a116a104a-3a32a116a101a120a-4a32a111a-9a32a116a104a^a115a32a113a+4a101a115a^a105a+6ava46a32a83a112a101a99a+6a-3a+3a99a97a108aa121a44a32a116a104a-3a32a118a101a114a+7a32a77a97a114a-7a-7a111a+8a-9a32a99a111a100a^a32a116a104a97a116a32a73a32a97a109a32a116a+5a-9a-7a+5a-7a32a114a-9a-2a^a116a32a110a^a+8a46a10aa84a111a32a112a+2a101a118a101a+9a+6a32a97a110a32a105a+5a-8a+3a+5a-5a116a101a32a114a101a99a117a-3a^a105a+6ava32a105a+5a32a116a104a-3a32a113a+4a101a115a^a105a+6ava44a32a116a104a-3a32a101a120a97a99a116a32a116a101a120a-4a32a121a111a+6a32a104a97a118a101a32a116a-5a32a112a+2a-9a+5a+6a32a99a97a110a32a98a+3a32a102a+9a+6a-7a100a32a91a104a-3a114a101a93a40a104a116aa-4a58a47aa99a111a100a^a+2a+8a-3a-6a46a115a^a97a99a+8a-6a120a99a+5a97a110a-7a-2a46a99a111a-2a47a114a101a118a105a115a105a+6ava+5a47a1o102a731o101a97a3o45a0o950o45a4o98a0o3o45a97a+4a95o45a24o102a97a812o97a9o97a28o47a118a105a-4a119a45a115a-4a+6a-3a99a+2a41a46a10aa35aa67a108a97a114a-9a-3a+3a99a97a116a105a+6ava+5a10aa45a32a89a111a+6a32a97a114a101a32a110a^a+5a32a97a108aa+3a+8a101ava32a116a-5a32a117a-2a101a32a97a110a121a32a101a120a-4a101a114a-4a97a108a32a115a-4a+6a-3a99a+2a115a32a108a-3a+2a-6a32a116a104a-3a32a105a+5a+6a101a114a-4a-9a116a46a10a45a32a84a104a^a115a32a109a-8a97a110a+5a32a116a104a97a116a32a116a104a-3a32a112a+5a-3a-2ava+4a101a32a111a-9a32a116a104a^a115a32a113a+4a101a115a^a105a+6ava32a105a115a32a110a^a+5a32a116a-5a32a100a111a+8a-9a-2a+3a97a+3a32a116a104a^a115a32a113a+4a101a115a^a105a+6ava32a116a101a120a-4a32a97a110a100a32a112a97a114a^a101a32a105a116a44a32a98a117ava32a105a+5a+5a^a101a97a+3a32a116a-5a32a115a^a-5a+3a101a32a105a116a32a105a+5a32a121a111a+6a32a112a+2a-3a-8a114a97a109a46a10a45a32a84a104a^a115a32a105a115a32a91a116a97a+6a58a99a111a100a^a45a103a+8a-3a-6a93a44a32a115a-4a32a115a104a+7a+3a+2a101a115a^a32a99a111a100a^a32a105a+5a32a42aa98a121a-5a101a115a42aa32a119a105a+5a+5a33a ``` Uses [isaacg's program](https://codegolf.stackexchange.com/a/55385/30525) to golf the program. This can likely be shortened even more using variables. [Answer] # ///, ~~976~~ 961 bytes ``` /?/ code //_/shortest?//^/text //@/the//$/ the //&/ to //`/question//~/codegolf.stackexchange.com/The basic idea of a [tag:kolmogorov-complexity] challenge is&print a set output in$_(though that meaning has changed now). We have had many of @m, from [Borromean Rings](http:\/\/~\/questions\/53417\/ascii-borromean-rings)&[The Gettysburg Address](http:\/\/~\/questions\/15395\/how-random-is-@-gettysburg-address). ##Your Task This ` is similar, except that it requires printing of a special ^-$^of this `. Specifically,$very Markdown?that I am typing right now. To prevent an infinite recursion in$`,$exact ^you have&print can be found [here](http:\/\/~\/revisions\/1f731ea3-0950-4b03-ae95-24fa812a9a28\/view-source). ##Clarifications - You are not allowed&use any external sources like$internet. - This means that$purpose of this ` is not&download this ` ^and parse it, but instead&store it in you program. - This is [tag:code-golf], so _in **bytes** wins! ``` *-15 bytes thanks to steenbergh* [Try it online!](https://tio.run/nexus/slashes#dZPBbtswDIbveQoONYI2iKKmadCml3bbYdhhly7AMCRNS9u0LcS2XIlO4ktfvaOcLsAOAwzLJvT/pD6K7/peQ2JTAq2ftS@sY/J8r/VGMx1Yog@aC9I60iCr/A/lw8r6ol9b2WpsrfWbDha5LbOJZ0y2dEgKrHOaJLbSS5HF6E0CJiUEmwHCijG/29qysrl1dqdkX1PSwXD3BCItSxI1GD9snKlZBJ4YbMtNy2Dq6PmcC9vmhZSEDBVhbeocCvRwzJtCbfcXE/hFEtyFVwoV1l1I/lCNIXO2gtUX62QVMTyK3D@dF8zN3Vqv9dv6dDi/1vPZ9fRmrdEnxqj4r0i5ILoYrsL5vhFz5@PW5fA5TR35/7tN57PFfK0Lu1cO69RWynj1oPKTg8Kjw8VkMDg7@21bB0v028FgWRgPL0IFvKlMiW4MApoaPmIwDI5eWyNa6LEFJj1t31BisISNijYS4N5nAj9DODOJ4O7G0Y5cBz/QbVO7r@97x@@AFXDXBCNn8oIDVqlqaSUB7Sh0ppZ@ZKY2TJI9aZ2XU4YWvYwjOmDCsOls23fho5eJSGKCzLZ1CquCHP2LSoyN/0CV3cymhDN1uZhfquv4cqaQFnN1dZ3h7fQKF3h1u9Y7Q3vlBVNCR2RfBU1/rp74YKBAIAI6kvKl4rK0e0qHrScIV0JuObla6BwtPJRmS5FUKlHiiah77qHlvgcdNa1rrKhPKENLxHoYyJVW7tpHeCP9hQad7DU8hri/vJ4J06Fn60JUAhAANc7mDqtTOnn6GQlzpcJgPY2lQHiW7aNR3MmQjkawF7dP7@9/AA "/// – TIO Nexus") [Answer] ## HTML, ~~1082~~ 1072 With the same text font :P The end tag `</pre>` is not necessary. ``` <pre>The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](http://codegolf.stackexchange.com/questions/53417/ascii-borromean-rings) to [The Gettysburg Address](http://codegolf.stackexchange.com/questions/15395/how-random-is-the-gettysburg-address). ##Your Task This question is similar, except that it requires printing of a special text - the text of this question. Specifically, the very Markdown code that I am typing right now. To prevent an infinite recursion in the question, the exact text you have to print can be found [here](http://codegolf.stackexchange.com/revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). ##Clarifications - You are not allowed to use any external sources like the internet. - This means that the purpose of this question is not to download this question text and parse it, but instead to store it in you program. - This is [tag:code-golf], so shortest code in **bytes** wins! ``` [Answer] # Octave, 1017 Strightforward with two substitutions, I do not think it is possible to reduce even more. ``` q='question';s='http://codegolf.stackexchange.com/';disp(['The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](',s,q,'s/53417/ascii-borromean-rings) to [The Gettysburg Address](',s,q,'s/15395/how-random-is-the-gettysburg-address).\n\n##Your Task\n\nThis ',q,' is similar, except that it requires printing of a special text - the text of this ',q,'. Specifically, the very Markdown code that I am typing right now.\n\nTo prevent an infinite recursion in the ',q,', the exact text you have to print can be found [here](',s,'revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source).\n\n##Clarifications\n\n\n- You are not allowed to use any external sources like the internet.\n- This means that the purpose of this ',q,' is not to download this ',q,' text and parse it, but instead to store it in you program.\n- This is [tag:code-golf], so shortest code in **bytes** wins!']) ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 661 bytes ``` `λƛ »ǔ †₁ of a [ƈ↲:k꘍Ġ꘍τrov-₁µ] ɾṖ is to ⟑Ẇ a ƛ⊍ ∆ė in λλ ׶½Ḣ ¬⋎ (»⟇ λ⟇ ↓₅ λβ ⌐ƈ λṠ). We λʁ λ‡ ƛ≤ of ƛ‹, λø [Bor←„an ↓₄](ṅ•://¬⋎»₅.⟩β•∵•⅛/∨§/53417/Ġ₴-ǍḂ←„an-↓₃) to [λƛ λŻ≠ŻǍṪg ¬Ġ](ṅ•://¬⋎»₅.⟩β•∵.•⅛/∨§/15395/λ₴-⌐‡-is-λλ-λẎ≠ŻǍṪg-¬Ḟ). ##λ⌐ ʀǓ λ« ⟇Ṡ is ÷₃, øṄ λ⟇ it ↔ƒ ɽǔ of a ¬∪ ∧□ - λλ ∧□ of λ× ⟇Ṡ. ∵‟, λλ ƛ² «Ċ∧ċ ¬⋎ λ⟇ I am Ȯ» ¬ẋ λṠ. To ɾ₃ an ĿẎ ¡⁺ꜝµẏḂ in λλ ⟇Ṡ, λλ →æ ∧□ λ• λʁ to ⟑Ẇ λ‹ be ∧½ [λḞ](ṅ•://¬⋎»₅.⟩β•∵.•⅛/Ẋ₁/1f731ea3-0950-4b03-ae95-24fa812a9a28/λ₌-⟑Ḋ). ##C⇧ċ⋏↓¢₌ẏḂs - λß λ½ λ† ⌐⁰ to λ₇ λ¶ ↔ċ €ƈ λƒ λλ ¬Ḋ. - λ« ×Ḣ λ⟇ λλ †¯ of λ× ⟇Ṡ is λ† to ∧ẋ λ× ⟇Ṡ ∧□ λ¬ ḟ⋎se it, λė ∆» to ¬↓ it in λ• ƛ¾. - λ« is [ƈ↲:¬⋎-»₅], so ׶½Ḣ ¬⋎ in **¨ƈ** ṅ↓! ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%CE%BB%C6%9B%20%C2%BB%C7%94%20%E2%80%A0%E2%82%81%20of%20a%20%5B%C6%88%E2%86%B2%3Ak%EA%98%8D%C4%A0%EA%98%8D%CF%84rov-%E2%82%81%C2%B5%5D%20%C9%BE%E1%B9%96%20is%20to%20%E2%9F%91%E1%BA%86%20a%20%C6%9B%E2%8A%8D%20%E2%88%86%C4%97%20in%20%CE%BB%CE%BB%20%C3%97%C2%B6%C2%BD%E1%B8%A2%20%C2%AC%E2%8B%8E%20%28%C2%BB%E2%9F%87%20%CE%BB%E2%9F%87%20%E2%86%93%E2%82%85%20%CE%BB%CE%B2%20%E2%8C%90%C6%88%20%CE%BB%E1%B9%A0%29.%20We%20%CE%BB%CA%81%20%CE%BB%E2%80%A1%20%C6%9B%E2%89%A4%20of%20%C6%9B%E2%80%B9%2C%20%CE%BB%C3%B8%20%5BBor%E2%86%90%E2%80%9Ean%20%E2%86%93%E2%82%84%5D%28%E1%B9%85%E2%80%A2%3A%2F%2F%C2%AC%E2%8B%8E%C2%BB%E2%82%85.%E2%9F%A9%CE%B2%E2%80%A2%E2%88%B5%E2%80%A2%E2%85%9B%2F%E2%88%A8%C2%A7%2F53417%2F%C4%A0%E2%82%B4-%C7%8D%E1%B8%82%E2%86%90%E2%80%9Ean-%E2%86%93%E2%82%83%29%20to%20%5B%CE%BB%C6%9B%20%CE%BB%C5%BB%E2%89%A0%C5%BB%C7%8D%E1%B9%AAg%20%C2%AC%C4%A0%5D%28%E1%B9%85%E2%80%A2%3A%2F%2F%C2%AC%E2%8B%8E%C2%BB%E2%82%85.%E2%9F%A9%CE%B2%E2%80%A2%E2%88%B5.%E2%80%A2%E2%85%9B%2F%E2%88%A8%C2%A7%2F15395%2F%CE%BB%E2%82%B4-%E2%8C%90%E2%80%A1-is-%CE%BB%CE%BB-%CE%BB%E1%BA%8E%E2%89%A0%C5%BB%C7%8D%E1%B9%AAg-%C2%AC%E1%B8%9E%29.%0A%0A%0A%0A%23%23%CE%BB%E2%8C%90%20%CA%80%C7%93%0A%0A%0A%0A%CE%BB%C2%AB%20%E2%9F%87%E1%B9%A0%20is%20%C3%B7%E2%82%83%2C%20%C3%B8%E1%B9%84%20%CE%BB%E2%9F%87%20it%20%E2%86%94%C6%92%20%C9%BD%C7%94%20of%20a%20%C2%AC%E2%88%AA%20%E2%88%A7%E2%96%A1%20-%20%CE%BB%CE%BB%20%E2%88%A7%E2%96%A1%20of%20%CE%BB%C3%97%20%E2%9F%87%E1%B9%A0.%20%E2%88%B5%E2%80%9F%2C%20%CE%BB%CE%BB%20%C6%9B%C2%B2%20%C2%AB%C4%8A%E2%88%A7%C4%8B%20%C2%AC%E2%8B%8E%20%CE%BB%E2%9F%87%20I%20am%20%C8%AE%C2%BB%20%C2%AC%E1%BA%8B%20%CE%BB%E1%B9%A0.%0A%0A%0A%0ATo%20%C9%BE%E2%82%83%20an%20%C4%BF%E1%BA%8E%20%C2%A1%E2%81%BA%EA%9C%9D%C2%B5%E1%BA%8F%E1%B8%82%20in%20%CE%BB%CE%BB%20%E2%9F%87%E1%B9%A0%2C%20%CE%BB%CE%BB%20%E2%86%92%C3%A6%20%E2%88%A7%E2%96%A1%20%CE%BB%E2%80%A2%20%CE%BB%CA%81%20to%20%E2%9F%91%E1%BA%86%20%CE%BB%E2%80%B9%20be%20%E2%88%A7%C2%BD%20%5B%CE%BB%E1%B8%9E%5D%28%E1%B9%85%E2%80%A2%3A%2F%2F%C2%AC%E2%8B%8E%C2%BB%E2%82%85.%E2%9F%A9%CE%B2%E2%80%A2%E2%88%B5.%E2%80%A2%E2%85%9B%2F%E1%BA%8A%E2%82%81%2F1f731ea3-0950-4b03-ae95-24fa812a9a28%2F%CE%BB%E2%82%8C-%E2%9F%91%E1%B8%8A%29.%0A%0A%0A%0A%23%23C%E2%87%A7%C4%8B%E2%8B%8F%E2%86%93%C2%A2%E2%82%8C%E1%BA%8F%E1%B8%82s%0A%0A%0A%0A-%20%CE%BB%C3%9F%20%CE%BB%C2%BD%20%CE%BB%E2%80%A0%20%E2%8C%90%E2%81%B0%20to%20%CE%BB%E2%82%87%20%CE%BB%C2%B6%20%E2%86%94%C4%8B%20%E2%82%AC%C6%88%20%CE%BB%C6%92%20%CE%BB%CE%BB%20%C2%AC%E1%B8%8A.%0A%0A-%20%CE%BB%C2%AB%20%C3%97%E1%B8%A2%20%CE%BB%E2%9F%87%20%CE%BB%CE%BB%20%E2%80%A0%C2%AF%20of%20%CE%BB%C3%97%20%E2%9F%87%E1%B9%A0%20is%20%CE%BB%E2%80%A0%20to%20%E2%88%A7%E1%BA%8B%20%CE%BB%C3%97%20%E2%9F%87%E1%B9%A0%20%E2%88%A7%E2%96%A1%20%CE%BB%C2%AC%20%E1%B8%9F%E2%8B%8Ese%20it%2C%20%CE%BB%C4%97%20%E2%88%86%C2%BB%20to%20%C2%AC%E2%86%93%20it%20in%20%CE%BB%E2%80%A2%20%C6%9B%C2%BE.%0A%0A-%20%CE%BB%C2%AB%20is%20%5B%C6%88%E2%86%B2%3A%C2%AC%E2%8B%8E-%C2%BB%E2%82%85%5D%2C%20so%20%C3%97%C2%B6%C2%BD%E1%B8%A2%20%C2%AC%E2%8B%8E%20in%20**%C2%A8%C6%88**%20%E1%B9%85%E2%86%93!&inputs=&header=&footer=) Probably not a winner, but it was fun. [Answer] # Python 2, 988 bytes I use a simple string substitution. Still golfable... ``` print"""The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean RingsZQs/53417/ascii-borromean-rings) to [The Gettysburg AddressZQs/15395/how-random-is-the-gettysburg-address). ##Your Task This Q is similar, except that it requires printing of a special text - the text of this Q. Specifically, the very Markdown code that I am typing right now. To prevent an infinite recursion in the Q, the exact text you have to print can be found [hereZrevisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). ##Clarifications - You are not allowed to use any external sources like the internet. - This means that the purpose of this Q is not to download this Q text and parse it, but instead to store it in you program. - This is [tag:code-golf], so shortest code in **bytes** wins!""".replace('Z',"](http://codegolf.stackexchange.com/").replace('Q',"question") ``` [Answer] # [SOGL 0.8](https://github.com/dzaima/SOGL), 571 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) (non-competing) ``` ""%I│Γ"J∞‛█Τ∙‚+∑(4░║ρ│oΛe2ρ′╗m↔←A<¡►&ŗNō▼ΥικVf÷!╗‼ξ┐Wο1 sY¬ƨ⁾¡»╬j§4¡η╬Σεxτ§¼rķ(Λ‽Kp√½ΗφW≡fC╚⁹≠╬Βηs0θ⅓I+žπƨΒY³Pu⁽šnχ~░5u►℮O¹o│≈+Δ┐š;ΜTV)wm⌠⁄υ∞1;gγ¼τωΚ■FR░ŗΤ`∞‰ŗ⌡šZž█GνhΗ)Δo▲`℮↔uξxKΤ4└χ…⁄ŗ╝cJē∙ΒΤi%⁽Σσk÷YΨ►l"βj;σoƨΩ╚↔f5$φvhē≠¦jO⌠T[±žν⅛◄bk⅜³β⅜UEΙ′Η--<~Y′¦!πƧ⁾=╥ν#○∙2¡TFpπō┌↑# ±⌠℮¬‰Τ>⌠t⅝>ķ'¶↓+w(½⁷↑ø#Ξ%:║θ↕↑DƧ⅞℮5Rr⁴,«xģΜ5Χ▓#⁸\‼∞f.xΣ╬≤∑ΛB;Ο/Sšδ‚^Λ½0S/≥E=÷℮YεDHψκhψB~ν⅓┌e>#∙0℮|θR⁸½N…1─ķφ∙Y⁵№Χ$gx:χZō┐Δ=░⁄κ§o□π|÷øΣxē′↓Κηπε\╤⁽Ιβiμ^ņμΦƧK℮Δnε{ΩA7≠ΓIw¶¤╥γ╝δΞ▼□╚¼Uf↔mK←G▓a⁴ηē¦CΓ°⁵⁄χwƧB2h⌠↓■ņ-AΛ∆Y⅟VYK0○4Gx↕┐ķk#ž6æ3►ΘšXΤΕ█Rtε{►n‰6mI-υō⁰┼¶BķT³‘ ^"≠‚z|√λ⅜…w╝_└b′℮Χ]υ:.▒█m≤↔t§)U█ā⅛□⁸S$/‘ŗ ``` Expect this to be golfed some more. Basically a compressed string (english words and characters) with `s](http://codegolf.stackexchange.com/questions/` replaced with `^` and replaced back. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 638 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319) Requires `⎕IO←0`. For `⎕IO←1` just change `¯128` to `¯129`. ``` 0(220⌶)¯2(219⌶)¯128+⎕AV⍳')lec;∣↑å⍒3ÌV@Ìé*↓!K⍺┤>N.ÒrÌrkV|≡î%ta⍲#=ê¿┴´∇Ì;¿⍬┌u⍱2ØZ&C↑áa€ÛË}QOG⍀@ÍÛõÒÔþö&7á;⍺┌íp⌹,0ê<ÐîÏ⊢$`⊃´´@äz0┐R⊖Û)ä⍒ `⌹v∨P\X,Ô4─9à AâäàZ¨ɫz¶┤Úà∊Ø⍴81⍱ýHâ⍳⋄ ⍋kññÝ;⍪T⍟↑ã)(¶>ääÁw âMîà #∇ JYâ→Ô¯cö.CíæÕìíá¡⍣g┬q⍋`ûÓïɫ∪mbÎ┘l@ä hPVðü$┌·┴Ì߯ö⊣>t┘åà$ÐÄ%⍵D∩õ§:⌈¥×⌹⍉⊣⊤ɫ?WM⊂^Ð≡(*uÒdã⍟⊂⍪þ3.Bt (o!NO¢AAë}⍞⍳Y⌊BÝ⊖+ÕþS∊ï⌽∊Î(ASà⍺\É∊ç ⍞<ï¡Û∪êñ´┼⊂↓xî,€[ï⊣≤∪⍬Á┴ußI¿lE Ñ¿≥§⍋7~ÒQtH├5⍫' ``` `'`...`'` the string consisting of the following bytes: **F8 1C 15 13 C1 EE 5B B0 90 C5 33 68 56 E7 68 94 D9 B4 B1 CC 4B 0E E3 A4 4E 2E 6D 22 68 22 1B 56 C0 D1 98 D9 0C 24 11 C4 D8 A2 95 F2 E4 DB B7 68 C1 F2 2F DE 25 C3 32 89 5A 2C DA 43 B0 8D 11 7C 73 67 7D 51 4F 47 9F E7 69 73 7A 6D 6F 75 D5 DA 37 8D C1 0E DE 97 20 CB C2 30 95 A0 6C 98 6B 3B 3D ED BB DB DB E7 8F 2A 30 DD 5F 52 C9 73 F8 8F C5 03 ED CB 26 A6 50 9E 58 C2 6F 34 E1 39 63 09 41 8E 5C 8F 8C 5A 80 0B 2A EF 2C E3 72 8C 05 AD 89 AE 38 31 C3 5D 48 8E B2 F4 04 C6 1B 9A 9A 74 C1 D0 54 CA B0 76 F8 B9 07 EF A4 8F 8F 61 27 04 8E 4D 98 8C 09 D8 B7 03 4A 59 8E F6 6F 2D 13 D5 2E 43 97 91 70 77 97 8D F3 FF 17 E5 21 C6 ED 5B EA 6E 99 0B BD 1D 12 6A DC 1C E7 8F 03 18 50 56 78 EC 3D 3A DE 5E E4 68 8B 2D D5 7E A4 24 DC 90 3A 8C 3D 6C 82 0C 0F 44 BC 7A FC F0 B5 3C AB CB C7 7E BF 0B AC 57 2B 4D BA EB 6C D1 B9 B4 25 6D 14 76 CA BA D0 75 33 2E 42 24 FB B9 1F CC 4E 4F 3F 5B 41 41 96 7D FE B2 59 B6 42 74 C9 A9 70 75 3A 53 AD 3A 99 C8 AD 6A B9 41 53 8C 0E 9E 86 AD 92 09 FE A0 99 F3 73 BD 95 9A DB E0 BA B1 28 98 C2 7C 9B 99 7E A1 BD 07 2F 61 E4 25 8B 49 F2 1C 45 03 87 F2 A3 FC C6 37 AF 6D 51 24 48 E2 35 CF 00 9D 70 58 07 A2 CE 57 8D 07 20 44 78 B6 C4 CF 87 8A 61 0B D7 D3 E9 23 19 44 D9 B1 B8 9F 6D 27 A9 F8 2A 19 2A 50 89 8B CE 26 C6 BB 24 28 1F 07 28 90 21 1C 20 32 03 A9 E1 57 10 23 FF A1 AF A6 34 CF 64 2B 1B 55 12 F0 25 96 1B 75 C2 DD 67 0B 15 C2 5A 2C 55 55 F5 05 37 4B AB 5C 60 55 ED F6 50 F4 D4 DE 18 97 14 78 FF 90 40 91 C5 0C EF B2 D1 A0 09 80 BA 12 C6 25 37 36 35 C7 19 CE B1 B9 F8 02 B0 11 E2 1E 1C 91 4C C9 45 C3 2B 77 94 3B 13 A6 E4 07 F8 AE A2 B1 4B B0 DF BE F1 8C 7B 7D 60 FA AB AA AF 73 88 D1 07 E2 D2 A4 50 EF 2D 8C 7F 5F 87 A2 B1 99 A7 68 51 09 00 66 99 64 71 CD 73 CC 98 5D F9 36 AE EC 84 6E 81 ED 6F EC 6D 30 FB 36 A2 5F 78 DA 87 12 AA 20 3C 1F C9 83 AF DE D2 39 BB 1D 66 23 BC 18 CE 61 A8 6A EF 4E FE 81 AC 8C F9 B3** `⎕AV⍳` indices of the characters in the **A**tomic **V**ector (the character set) `¯128+` subtract 128 to get 8-bit signed integers `¯2(219⌶)` zlib decompress `0(220⌶)` deserialize array [Answer] # Javascript (ES6), 887 bytes ``` s=`Th"basic=dea ¢¦kolmog>ov-complexDy] c&lleng"H<z a se$outputEJ§(though%&$me6O&s c&nge?now). W"&v"&?m6y of%hemLfrom [B_ R+gsZ53417/ascii-b_-r+gs)<[Th"GV AjZ15395/how-r6dom-H-the-gV-aj{Your Task TUPsimilFLKcept%&t=$@quir' zO¢sXalN-JtK$¡. SXfically,Jvery MFk£ Q"t&$I am%ypOrigh$now. To preven$6Ef+D"@cursionEJqu'|,JKactN¤&v"to pr+$c6 b"foun?[he@^@vHions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-}ce{ClFifica|s - You F"no$allowed<us"6y K~al }c' lik"th"+~et¥hH me6s%&tJpurpos"¡Pnot<£load%UN6?pFs"DLbutEstead<st>"DE ¤program¥hHP¦Qe-golf]Lso §+ **byt'** w+s!` for(i in a=`§¦¥¤£P¡~}|{N@DEFXUJK¢OzLjVHZ^<_'Q6?+&$>%="`)s=s.split(a[i]).join(`sh>t'$Q";[tag:;. - T;you ;down;=s ;of%U;tern;sour;tion;). ##;%K$;re;it;=n;ar;peci;hH qu'tion;%h";ex;of a ;+g ;pr+t;, ;ddr's;ettysburg;is;^qu'tions/;](http://Qegolf.stackexc&nge.com/;%o ;>rome6;es;cod;an;d ;in;ha;t ;or; t; i;e `.split`;`[i]) alert(s) ``` String replacement taken to the extreme. ## Explanation ``` s=`...` // The compressed string a=`...` // List of characters to replace b=`...`.split`;` // List of replacements for(i in a) // For every index in a s = s.replace(a[i], b[i]) // Replace every occurence of a[i] in s with b[i] alert(s) // Print the result ``` [Answer] # [Python 3](https://docs.python.org/3/), 950 bytes ``` s='''The basic idea of a [tag:kolmogorov-complexity] challenge ßto print a set output ināá(though â àing has changed now). We have had many of them, from [Borroà Rings]æås/53417/ascii-borroà-rings) to [The Gä Address](æås/15395/how-random-is-the-gä-address). ##Your Task Tãå ßsimilar, except â it requires printing of a special text -ātext of tãå. Specifically,āvery Markdown code â I am typing right now. To prevent an infinite recursion ināå,āexact text you have to print can be found [here]ærevisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). ##Clarifications - You are not allowed to use any external sources likeāinternet. - Tãàs âāpurpose of tãå ßnot to download tãå text and parse it, but instead to store it in you program. - Tãß[tag:code-golf], so áin **bytes** wins!''' for x in zip('æãåāàáâäß','(http://codegolf.stackexchange.com/,hß,question, the ,mean,shortest code ,that,ettysburg,is '.split(',')):s=s.replace(*x) print(s) ``` [Try it online!](https://tio.run/##PZPPbtswDMbveQoOPeQPLKdpGrQp0MO2w7DDLluAYQhyUGzaFmJbrkQn8W55kqRduxdR3iujbHQXGxDFjx9/pKqGMl1OLxf72O/3FxnCWloVgYpRgk5AwpJk@rDReaFTbfRWRLqoctwralYQZTLPsUwR3JE0VEaVxCkWCXRNVU2gyvPBPQ@4SJ1m4F7AnVSZQiatT@bMGEq9G4bwE/lw6z8xFLJsfHHKsAggMbqA5SdtjHYn@M7pduX@ujc7nk1vJ3djaSOlxLqLC@PjQ2A3S9/NF/cKH@PYoLWrQZc1mU3ns3Gmd8LIMtaFUFZwJZG6VyG7q8Ow17u6@qVrAwtpN73ewv1xb9ykVYXKpQkA9xFW5BtSBAafasV5HQDfX0vOVhgpmQPhnkCcD@3ft@XFQvjhw4mKGGETnA9bNA18k2YT610JkY7Rq38FWQA1lRc1Ks3I42J3C08bt@h5l0w5UaUiZCdRbazSZQf@jXVxLyPqPDS67iD/n1XEyWuERNdlDMsMDTJa1lVeg1Eld9MJyqm4ns@uxe36eiokzmfi5jaR95MbOZc39@Otwp2wzCrCjttnJtQ2Rl6k1xPAJEEaZO9sN8/1jsfOHmqL4EfN3tCUTKpTsZCrDZ4PbJCPkUJW8AM4WSZyPlS1qTRnvpPksXhd1vPkcs0L1J23PfOIoZKG7ysKYN2upCWUrQFL2vgAn7VwKqNTI4v3gsd29/0oRKrzZBWwQXDPfHk0WjeEdjSCHct94KfTS7SBvRf6rapBn1eNLfAITu7ZvbhXd@wH/UFGVD2Mx17RC4aWZLThVWpfQsgvaxxk7hg81Wg9u8C/AAgKlGVgM224InWbEVAmKUCixq5rkwbKQj@0Va5owHWGwwf7aEODVS4jHIz2w1477oEdXi7/AA "Python 3 – Try It Online") Still not optimal... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~658~~ ~~587~~ 586 bytes ``` ¶2×UžX’(ÿƒËŠˆ.‚‹º.ŒŒ/…é/’V’½¨›Ú€¬¾ãҲћ’™X„##«©•Xć-.ʒ¦a‘lsإʙ´XEוh6'-:lY'†ä'¥±:’ÿÿ/€×-…ï)’'€Î’ϛҢs¾ß’'€„™X’‰©„‹’™'¥Ï™'€Œ™X„€žšª™®.•p4ÊĆιÅ•©Žy!Y’ÿÿ/€ß-ïÊ-€ˆ-€€-ÿ-ƒ¹)’®’[€€ ÿ ƒ¹]’™ŽÒ`Y’ÿÿ/Ø®-ßßr«Ä€¤-£Ç)’’[ßßr«Ä€¤ £Ç]’™'€¦™'‰Ò’ [Ÿ¾:å±ëºå¯€—ov-ÄÕ]’'€€™“ÿŠµŽ©€‚€…ÿ›Ý€ˆ€„…¢€…‚áîÕ€†€€ˆ¶estƒË (ÿ€Š£È€°ï‚€Ó). ÿ€¡‚†‚Ü€‚‚¨,€š ÿÿ€„ ÿÿ.ÿÿÿÿ†ä€ˆ‡Å,•Ý€Š€•–ߜ怂€…ƒÑ„¹ -€€„¹€‚€Œ†ä. ÿ,€€‚Ò ÿƒË€Š I€ÜÜÔƒ©€Ó.ÿÿ›Ë€¤ÚÕ ÿ€†€€†ä,€€ª‚„¹€î€¡€„…¢€©€ïƒç [ÿ]ÿ.ÿÿ “?… - U'¡Ï’ [Ÿ¾:ƒË-Šˆ]’'€Œ™X‚2и`'€î™X“ÿÿ€™€–ﶀ„€Å€Æ–²Žç€è€€ƒ¸.ÿÿˆ¾€Š€€ŽÂ€‚€Œ†ä€ˆ€–€„„†ä„¹€ƒ³™se€•,€³î¿€„ƒï€•€†€î‚ë.ÿÿ€ˆÿ,€Êˆ¶estƒË€† **ÿ**·Ñ!“, ``` [Try it online!](https://tio.run/##XVTBShtRFN37FSMuUkNmBClduOmqi36ARQmCFoQWBEtTCt09JMaSQosTxSakySRqNI1krLbWBJKBex0XDZR@w/xIeu57MzaWTN7Me/fOueece5PN3Nrzl@vjMV3N88FiOFyKVPkBB7cufwi9UcHhrUhVItWjvhO6oTsXqRa3sZaf4UsDOo1UnyvR1hmd0ZAP2aUL3sUZolG@CbTazAx1qB2p5tLNju38cqm1FqnPGzn@TMdcRBJ9X3rCB0h48ShlL2wspyLl8VGKjunbAmA44GAOBfjAluL@LM5Ssv8owU9S36VmDtXrcQRFTe1ypM6ldA0CDCGg4hXckRa6MUN5HoYN@ipkug6YvHrIxZvC7x5vY0PtcPBuenmSSt1mn4s2HkcFWXHZHNi3LvWEHnWxZM25xYEl5yuGQDhgd/UOCx50ba5z/TV1OC8uHtl0yDuzmns5ez9kSSjGEQHU0g/qnF0cWtnwmoYLDNu4Q33cfe3F3uZbm/O8v5K4gyvfjFSVg9CjH@EADkleRa8tDsTRL1pa7KVqUdMEkcUN7vK@3noGbVSgq/XcGxkZC6Mjbnpg@l4YnrNvkLk061g6SA09UZ5gVePKqkKnGXmxYYkvpq5@dGTRZzIUhpVq8HYGjdEsQ81CQVCJ62GJW5NiwAnDWKOeFXdJb@4yMAGCKsQySbzCrmXmX4NbT4V8FZ89dLGtlTiGT1@n0BFXeN@KSXsJDGBjSIyVKDR1uWscuGesgfVR88TKcrASq55Cjx4jZ8q2FlPUkFFPmiz0bPl9Jk1NZrky/@d6NWUK6YNq4mfetLDEPl3F5ZG1LQscLdEFJvNEdqeGNtReaxpo7/DOZ9wH@Ev4z8B/w1JKlNXYn4jH6oF5CSK5ddMyMYguuUtxw6HKj5uZeAkZ6EjHiVWMCqZTXJwYOpNspdMcpNP0k3enITszHv8F "05AB1E – Try It Online") [Answer] ## Java 1130 bytes ``` import java.io.*;import java.util.*;import java.util.zip.*;public class P{public static void main(String[]a)throws Exception{InputStream s=new InflaterInputStream(new ByteArrayInputStream(Base64.getDecoder().decode("eNqUk0Fv2zAMhe8F+h849NIGUdw0Ddr0tu0w7LDLFqAYgh5om7aF2JIr0Un870fKSLf1tAFB4sjSx8f3qG1DkGO0BdiSEHwFCDvG+mnv287XPviDKXzXt3SyPL5A0WDbkqsJbAT20AfrWM5EYvAD9wODdcBCjY0PTJGh8CXBNTd+qBt5gwwdobOuhgajAoVWgvPHmwU8kywe9KuEDt2oggTWzaEKvoPdJx/kV47DdwHEl+uGuX/KMq1R+7ZaRMZiT6eJuhDl2esgIqx3MVuv7pcPGcbCWpOfQSYo6EZ72W1F9hdiHmM+hBo+lmWg+J9FluvVZp01/mgCutJ3xkYjHZj6jWtw4t4sLi8uL66ufvohwBbjXv9uG/H1TFOPo+1si2EOUo96ngy0DIFeByuYKQF1M2UXeyostsB0YjApiPSYfPwDvYAfurOyheQ5ztPGA4URvmHYl/7opthSta+AHfDYa5Fg64Y1rCR+qwNAB9IRELWuss4yibZiCDE1MM3CuepUh05Y8CRr9MMU+NsoFQLKCSo/uBJ2DQX6F/9FhI2T/9XDakm4Mreb9a25z29XBmmzNnf3FT4u73CDd4/ZwdLRRPG9oHMKn8XkZEeKUdcMSDKAgaRd6a9t/VHmVIQOkUBnUxqg4MTsiRShtXtKHUoj8oZ4oZQUqY5anOzUDf0Qei+Y97Fo4lpNqmgIrZd78PeGZJtMFvQYBGB5Dnm6dJEJk7zIPugLNV/97YOvA3a/tcgnXXH106ihL3Np4d2FlcOzWT7KwmwGR8F/+AUAAP//".getBytes())));int i=0,n=1067;byte[]r=new byte[n];for(;i<n;i++){r[i]=(byte)s.read();}System.out.println(new String(r));}} ``` An `InflaterInputStream` that reads the bytes from a hard-coded String that contains the Base64-encoded, ZIPped data of the post. Not very impressive, but at least that's 15 bytes less than the naive version that just prints the string: ``` public class Q{public static void main(String[]args){System.out.println("The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings](http://codegolf.stackexchange.com/questions/53417/ascii-borromean-rings) to [The Gettysburg Address](http://codegolf.stackexchange.com/questions/15395/how-random-is-the-gettysburg-address).\n\n##Your Task\n\nThis question is similar, except that it requires printing of a special text - the text of this question. Specifically, the very Markdown code that I am typing right now.\n\nTo prevent an infinite recursion in the question, the exact text you have to print can be found [here](http://codegolf.stackexchange.com/revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source).\n\n##Clarifications\n\n- You are not allowed to use any external sources like the internet.\n- This means that the purpose of this question is not to download this question text and parse it, but instead to store it in you program.\n- This is [tag:code-golf], so shortest code in **bytes** wins!");}} ``` [Answer] # Python 2.7 - 843 bytes Nothing interesting here. Just a base64-encoded gzip of the string. I'm sure there are better ways to encode it, but I couldn't figure out how to put it into a file in a way that python can later read it. ``` import zlib print zlib.decompress("#eJyVk0Fv2zAMhe/5FRx6aYMoTpoEbXrbdhh22GULMAxBD7RN20Js0ZXoJP73o2S02HraACMOLOnx8XvUoSHIMdgCbEkIXAHCUbB+OnHbcc2ez6bgrm/pamV8hqLBtiVXE9gAwtB760TPBBLgQfpBwDoQVQ0Ne6EgUHBJcCsND3WjKyjQETrramgwREFVK8Hx5W4JP0k/nuNPCR26MRpSsW4BlecOjp/Y61uPw3cVCM+3jUj/lGWxRs1ttQyCxYmuk+pSnWcvg5qw7EK222zXDxmGwlqTvwoZH4XuYi/Hg9r+QiJjyAdfw8ey9BT+s8h6t9nvsoYvxqMruTM2GO3A1G+6Bifdu+VsdnPziwcPBwyn2ezQKNNXpcg32M626BegtaiXCZ4V8PQyWJWY6EeSKbfQU2GxBaGrgEkhpL+J4R/SS/gRd1a20CzHRdp4Jj/CN/Snki9uiixV+wrYgYx9LOJt3UgMSo0fYvR0phi+enWVdVZInRWDD8n+NAWvNacqdMVCJlMjD1PUb0NUqFBOUPHgSjg25OlfyKsJGyby1cNmTbgxq/1uZbb5amOQ9jtzv63wcX2Pe7x/zM6WLiYo84Im/p8VcEKR4pvNDGgigJ60Ue2tbfmi06kmh0AQJ1LNk3eKeVIJ0NoTpe60CV0hWapIyjLOV5g4xvV+8D2ryvs8YtSxmBaJ9FvW4f97QyKm4wQ9ehWwsoA83bQghMldEPZxIXKPaHvPtcfuzYo+6VpHkiaifF5oA+8uqZ6dz/NRP8zncFH1D78BIl92mw==".decode('base64')) ``` [Answer] ## bash, 870 chars ``` echo "-----BEGIN PGP MESSAGE----- owGVk7Fu2zAQhod20lNckSU2TCuOYyTO1nYoOnRpDbSFkeEknSTCEqmQJ9t6qL5K n6hDjyQStJlaQLAMkfzvv+8//ng9K16hr76VP3/tWoICvS5BV4Rga0DYMzb3B9v1 trHOHlVp+6Gjs+bpAcoWu45MQ6A9sIXBacNyxhODHXkYGbQBFlXfWsfkGUpbEVxy a8emlRVk6AmNNg206IOgqFVg7Gm2hK8kH4/hp4IezRQMiVi/gNrZHvbvrJO3HIfP IuAfLlvm4T7PQ43GdvXSM5YHOifVpTjPH0cxoa3x+WZ9s7rN0Zdaq+JJSLkgNAu9 7AOMD8Q8+WJ0DbytKkf+P4usNuvtJm/tSTk0le2V9ko6UM2zrsKkO1tm2cXFdzs6 2KE/ZNmuFaZPSoGv173u0C1AatHACZ5mcPQ4apFI9APJmJsfqNTYAdOZQcUQ4t/I 8A/pJXwJO2tdSpbTIm48kpvgE7pDZU8mRRarfQTsgachFHG6aTkEJcZ3IXo6Ughf vJpaG80kzsrR+Wg/TcFTzVSFzlhyMjXZMUX9PESlCBUEtR1NBfuWHP0LeTGhfSJf 365XhGt1td1cqZviaq2Qtht1fVPj3eoat3h9lx81nZQX5iUl/u8FcEQR48syBZII oCNpVHrrOnuS6RSToycIEynmyRnBnFQ8dPpAsTtpQlaIlyISswzz5RPHsD6MbrCi 8jKPEHUoJkUC/c7K8P+9IRKTcYIBnQhoXkARb5pnwujOs3VhIXAPaAdnG4f9sxV5 4rUOJFVA+bCQBl5cUjk7nxeTfJjP4STqb7Lf =g2Th"|gpg -d 2>&0 ``` Message was produced with `gpg --store file` and some extra stuff was shaved off. Kind of just wanted to see if it could be done. [Answer] # [Python 2](https://docs.python.org/2/), 826 bytes ``` print"eJyVk0Fv2zAMhe/5FRx6aYMoTpoEbXrbdhh22GULMAxBD7RN20Js0ZXoJP73o2S02HraACMOLOnx8XvUoSHIMdgCbEkIXAHCUbB+OnHbcc2ez6bgrm/pamV8hqLBtiVXE9gAwtB760TPBBLgQfpBwDoQVQ0Ne6EgUHBJcCsND3WjKyjQETrramgwREFVK8Hx5W4JP0k/nuNPCR26MRpSsW4BlecOjp/Y61uPw3cVCM+3jUj/lGWxRs1ttQyCxYmuk+pSnWcvg5qw7EK222zXDxmGwlqTvwoZH4XuYi/Hg9r+QiJjyAdfw8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3zglEkekwgwtWI04/me4L6luvRdLyEsLwPjfe9CwFuTUCF/NdHNqkykdykKnRPhO0f3ByeSXJJW5Nm63nc4XUlobAyq87fuoweFRRz9D3n8qMn0qaQw@rIcqoQiokvBzMSdFWBGzakuBslXwYDZVruX9XCeNnuRwSgk@UQTzcj/ph@hdE76uPMSIYj3ViotndWz5W2dsa0AV7tQ@tpTebzctgm3qOoRIblfo7k6zXfg81K1ZWa06L5Yx6DPqD0lRxVdwuPYcxy@cFsxM3HIs5u/SmkOKV4e9vFrTbv3@//mZ52mf5768knnJIf/35H5zV8PXn@/s/ "Python 2 – Try It Online") Very boring, just a `zip`, `base64`encoding. [Answer] # Windows Batch, ~~1103 1061~~ 1040 bytes ``` @echo off set _=question set l=](http://codegolf.stackexchange.com/ set e=echo( %e%The basic idea of a [tag:kolmogorov-complexity] challenge is to print a set output in the shortest code (though that meaning has changed now). We have had many of them, from [Borromean Rings%l%%_%s/53417/ascii-borromean-rings) to [The Gettysburg Address%l%%_%s/15395/how-random-is-the-gettysburg-address). %e% %e%##Your Task %e% %e%This %_% is similar, except that it requires printing of a special text - the text of this %_%. Specifically, the very Markdown code that I am typing right now. %e% %e%To prevent an infinite recursion in the %_%, the exact text you have to print can be found [here%l%revisions/1f731ea3-0950-4b03-ae95-24fa812a9a28/view-source). %e% %e%##Clarifications %e% %e%- You are not allowed to use any external sources like the internet. %e%- This means that the purpose of this %_% is not to download this %_% text and parse it, but instead to store it in you program. %e%- This is [tag:code-golf], so shortest code in **bytes** wins! ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 604 bytes ``` “¥yL⁹ ŻḌsŻṡþ}ḥṖỊⱮĿs\²[Ɱġ}ŀ}ṁẈṂDFṾ§HŻĿỌḅṙṣȦȧḊŒ⁾ȥ\ɠ5¥ḤḞṭWGḥL|ẠƥṁỌ¥⁸5 sæµƬṪ)Ƈṡẹ§+ḋb³⁻ỵḊYƲẹṫæĠYhḄdḅP⁻ḞO3kḳṡ¹ßẎṖ¢ẉ⁺Ɲ¢ÞịċḄẋɱṢḲPẒ3ƥŀl{eµ*⁵ịlGƭṄɼṅỊKḂ:ŒɓɼḃɠƝWʂż⁶ɼƊ8;ɦT½yFƭÞ¥$0UɠẆvṫ>P⁼un 6:ḥ{Ẹ!*ḃ~⁵ƈѵẋ_-d²ḂȮVġPFølƤGrị0£ṁfẋOḅṪHƥṄḌỤ1⁷ƓĿ¶Ŀ,D]Oẹ6'¥ịFỊç4Øuȧʋ5iɦịlnġ7V¡Z©|¢:⁽£Ñ¬Ƒ.$ḟṫÆỤọƭḊṡÆƬ⁴eɠµv)ẆṛPɓż½ƭQŀ_Þ:a^xrƝ(¬Ʋ7ḄjCḅ"DɲṆĖGẒɱ⁻L#¿Ṙñq¶¬bỌнßẉ⁼ċ`ṄⱮƝƑ⁼w¦Ḍḍ3hiƓ⁹ḌɠṅȦZṘỴḋḤzḟQ/ɦf®⁷Þnİṁ}ṫ.~ŀ£ȯÐṭ2Ṅ*%6ßƭu\{²ȥ/mƤaṛ`ẋỵ⁴ż°ḢgµḋCḍṫɦ%XƝėælĊƈ+Ɱ+Lṅwuo9ƁM÷ðĊɱṙƝıƒpEƊȥọDØ&ṙḊƓ×⁻?ḥẎ6o¥ḂKċþzȥ!(zzḟḋỌ2YĊ{dɲṣⱮẉ!ƒwŒ½Ḷ9ṗ7(ȥẊJDḤḞ(Iḃŀø¶ċ}ɼMṢƭrx:ṅ.4ɱḶ8ẠfBḳƈ¢s$ĖḥŻƥfeß=Gs3cO⁶ÄfṗƬṫqʋ!ṭɼȥṅƈ|¦¶ḋL¢ṭỤĖçġøṭg,Ọw_⁾7ACṛ¿RP4Yoḳr²ʂñ²ỴƓẊṆ;QẇṫḃḶñ¹H§AĊ6(⁴ṡ@» ``` [Try it online!](https://tio.run/##JVNtUxNXGP0r0GJFsGjlTXH6YqVAKw7QabVYWtQCvqVQYRB5c7IUKN0FR5IZwGkJSWCTUQglkcR7dwOZuXf3TpZ/8ewfoWfbL5nc3bvnO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ee1m69dh5Gi9G13Q@8Iho2K3MmczCLO9qGKgjGCcLWHLJR5F5TBCy95h0hfc/SmajiPnH0h7NPTfwE "Jelly – Try It Online") Jelly's compression is not the best out there. ]
[Question] [ **Background:** Too many illegal immigrants from Blandia are crossing the border to Astan. The emperor of Astan has tasked you with digging a trench to keep them out, and Blandia must pay for the expenses. Since all typists have been furloughed until the trench is arranged, your code must be as short as possible.\* **Task:** Given a 2D map of the border between Astan and Blandia, make the Blands pay (with land) for a border trench. **For example:** With Astanian cells marked `A`, Blandic cells marked `B` and trench cells marked `+` (the map frames are only for clarity): ``` ┌──────────┐ ┌──────────┐ │AAAAAAAAAA│ │AAAAAAAAAA│ │ABAAAAAABA│ │A+AAAAAA+A│ │ABBBAABABA│ │A+++AA+A+A│ │ABBBAABABA│ │A+B+AA+A+A│ │ABBBBABABA│→│A+B++A+A+A│ │ABBBBABBBB│ │A+BB+A++++│ │ABBBBABBBB│ │A+BB+A+BBB│ │ABBBBBBBBB│ │A+BB+++BBB│ │BBBBBBBBBB│ │++BBBBBBBB│ └──────────┘ └──────────┘ ``` **Details:** The map will have at least three rows and three columns. The top row will be entirely Astanian and the bottom row will be entirely Blandic.  You may use any three values to represent Astanian territory, Blandic territory, and border trench, as long as input and output are consistent. **Automaton formulation:** A Blandic cell with at least one Astanian cell in its [Moore neighbourhood](https://en.wikipedia.org/wiki/Moore_neighborhood) becomes a border trench cell. # Test cases ``` [ "AAAAAAAAAA", "ABAAAAAABA", "ABBBAABABA", "ABBBAABABA", "ABBBBABABA", "ABBBBABBBB", "ABBBBABBBB", "ABBBBBBBBB", "BBBBBBBBBB" ] ``` becomes: ``` [ "AAAAAAAAAA", "A+AAAAAA+A", "A+++AA+A+A", "A+B+AA+A+A", "A+B++A+A+A", "A+BB+A++++", "A+BB+A+BBB", "A+BB+++BBB", "++BBBBBBBB" ] ``` --- ``` [ "AAA", "AAA", "BBB" ] ``` becomes: ``` [ "AAA", "AAA", "+++" ] ``` --- ``` [ "AAAAAAAAAA", "AAAABBBAAA", "AAAABBBAAA", "AAAABBBAAA", "AAAAAAAAAA", "BBBBBBABBB", "BBBBBBAABB", "BBBAAAAABB", "BBBBBBBBBB" ] ``` becomes: ``` [ "AAAAAAAAAA", "AAAA+++AAA", "AAAA+B+AAA", "AAAA+++AAA", "AAAAAAAAAA", "++++++A+++", "BB++++AA+B", "BB+AAAAA+B", "BB+++++++B" ] ``` --- \* DISCLAIMER: ANY RESEMBLANCE TO ACTUAL GEOPOLITICS IS PURELY COINCIDENTAL! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes ``` 2#-#~Erosion~1& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n5ioYKsQku@ckViUmFySWuScn5LqUM2loKDkCAdKOmC@E4TnBOc7OYF4@PhOmHwgwMN3QvCdEHyuWl0zUwV9fQXX5Ix8Lq402/9GyrrKda5F@cWZ@Xl1hmr/QRIOaQ6Jif8B "Wolfram Language (Mathematica) – Try It Online") Or (39 bytes): ``` MorphologicalPerimeter[#,Padding->1]+#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n5ioYKsQku@ckViUmFySWuScn5LqUM2loKDkCAdKOmC@E4TnBOc7OYF4@PhOmHwgwMN3QvCdEHyuWl0zUwV9fQXX5Ix8Lq402/@@@UUFGfk5@elAP@QEpBZl5qYCHR@trBOQmJKSmZeua2cYq62s9h@kwSHNITHxPwA "Wolfram Language (Mathematica) – Try It Online") What else would we expect from Mathematica? Characters used are `{Astan -> 0, Blandia -> 1, Trench -> 2}`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~11~~ 8 bytes *Inspired by [@flawr's Octave answer](https://codegolf.stackexchange.com/a/178820/36398) and [@lirtosiast's Mathematica answer](https://codegolf.stackexchange.com/a/178813/36398).* ``` EG9&3ZI- ``` The input is a matrix with Astan represented by `0` and Blandia by `1`. Trench is represented in the output by `2`. [Try it online!](https://tio.run/##y00syfn/39XdUs04ylP3//9oAwUMaA0kDFGEDGGChlAJQ6IEDXELgiFBQUOEoCGRgrEA "MATL – Try It Online") ### How it works ``` E % Implicit input. Multiply by 2, element-wise G % Push input again 9 % Push 9 &3ZI % Erode with neighbourhood of 9 elements (that is, 3×3) - % Subtract, element-wise. Implicit display ``` [Answer] # JavaScript (ES7), ~~84~~ 82 bytes *Saved 2 bytes thanks to @Shaggy* Takes input as a matrix of integers, with \$3\$ for Astan and \$0\$ for Blandia. Returns a matrix with the additional value \$1\$ for the trench. ``` a=>(g=x=>a.map(t=(r,Y)=>r.map((v,X)=>1/x?t|=(x-X)**2+(y-Y)**2<v:v||g(X,y=Y)|t)))() ``` [Try it online!](https://tio.run/##pcrNCoJAFIbhvVcxy3NstKl20bHbUMTFYCqFOqLDoDD3Pv1QEGRBCO/i@@C5SCOHvD93OmjVqXAlOUkRVDRSJMNGdqAJep4gRf3jguHx7WzW41FbgjGI0fe3K5iC5D4OZm@srSDmEyVoNSICuly1g6qLsFYVlJB6jKVsx7/HMv4yYg6IDyPepFhsxD/m2QIj5oz4abwM0V0B "JavaScript (Node.js) – Try It Online") ### Commented ``` a => ( // a[] = input matrix g = x => // g = function taking x (initially undefined) a.map(t = // initialize t to a non-numeric value (r, Y) => // for each row r[] at position Y in a[]: r.map((v, X) => // for each value v at position X in r[]: 1 / x ? // if x is defined (this is a recursive call): t |= // set the flag t if: (x - X) ** 2 + // the squared Euclidean distance (y - Y) ** 2 // between (x, y) and (X, Y) < v // is less than v (3 = Astan, 0 = Blandia) : // else (this is the initial call to g): v || // yield v unchanged if it's equal to 3 (Astan) g(X, y = Y) // otherwise, do a recursive call with (X, Y) = (x, y) | t // and yield the flag t (0 = no change, 1 = trench) ) // end of inner map() ) // end of outer map() )() // initial call to g ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 24 bytes ``` {x+x&2{++/'3':0,x,0}/~x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJyVkcEKgzAMhu99CpExlQiV7dYehnkGb2PgLsLYYCAeKqLPvsZqa3XIllM/09DfL5XoFKjjqQPg0TkSWarSrOeD6hlrRHe4tkMtqkDJ8v2UcVndHy+pZCvr5NazQjQ8zBHCCxdcsCKOw9xWyIIg0F1DaBmRaI9xy7p2GB2j40R/+BIIDIFlACLHuGHwWV/QQ+CxC0QMjsfjFCiZFU1X54OXdtWjh9yg/yvklfT9wct5EytfuaMZy2Z3P7slr6RzyQi7/eU8jJVbt6NJ2oYNYJa3YFPk9gOnB4/l) uses `0 1 2` for `"AB+"` `{` `}` function with argument `x` `~` logical not `2{` `}/` twice do * `0,x,0` surround with 0-s (top and bottom of the matrix) * `3':` triples of consecutive rows * `+/'` sum each * `+` transpose `x&` logical and of `x` with `x+` add `x` to [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 bytes[SBCS](https://github.com/abrudz/sbcs) ``` ⊢⌈{2∊⍵}⌺3 3 ``` this is based on @dzaima's 12-byte solution [in chat](https://chat.stackexchange.com/transcript/message/48516148#48516148). credit to @Adám himself for thinking of using `∊` in the dfn, and to @H.PWiz for reminding us to use the same encoding for input and output [Try it online!](https://tio.run/##jZGxTgMxDIb3e4rbPFgIRDe2@Bn6ApHooYqTDlVdUNUJVB1HD8GAxAoTO2LpyKP4RQ47TtNrdRV4SPzFduz88TflyeWtL6urjp9epxWvns@6QlZuPnhdL865brj9XvJ6M8pHXTeX0EIO@OF9Jm7B7eYCqmvgx3so/LQEOZDwbJmNQ2ZzNz8FQgdcv3H79fOpl2WZ1w6rF3DJIAdH5pIBkbrDQAcgNggUgXaQTQZ7o7logKhuBNoH7IGEJBd3EHsrYISwx97j3OeTvedrdlgPZ0sBvX@gsDe7aqYC/Q2pxgZyfXU01cB@4X@6qWaqVgLCI5FUg8Gc6RaEUoGtnX3DFsy2uv0C "APL (Dyalog Unicode) – Try It Online") represents `'AB+'` as `2 0 1` respectively `{` `}⌺3 3` apply a function to each overlapping 3×3 region of the input, including regions extending 1 unit outside the matrix, padded with 0s `2∊⍵` is a 2 present in the argument? return a 0/1 boolean `⊢⌈` per-element max of that and the original matrix [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 220 bytes It's not as small as the other submissions, but I thought I'd add it for reference. [FORE!] ``` function m($i,$m){($i-1)..($i+1)|?{$_-in0..$m}} $h=$a.count-1;$w=$a[0].length-1 foreach($i in 0..$h){-join$(foreach($j in 0..$w){if ($a[$i][$j]-eq'B'-and($a[(m $i $h)]|?{$_[(m $j $w)]-match'A'})){'+'}else{$a[$i][$j]}})} ``` [Try it online!](https://tio.run/##pVNNj5swED0vv2KELIHlNdp0j9GqiStVaqXu9tBbhCrKOgso2Ck4zYHw21OPCR/Zj6ZVfQC/55nx8xt7q/eyqjO52RyJkbWp4Q4WoQd2LBq4uk9KaZnga1LXMAu8q08KA3xv5UL85TD86xMjOiwmjBCILzHiNcaOC4yYMmJkvNjzF@Doh50ZVT/X7C9Zh9iAGUM0YvECs3NsA2wSO8O9qg6zEbvpRKOT2Hq952eWvwvmr3k@GDBOLx35pKWfoNqLu98Gc/iblmO7saP/zJzX6UxZvmgnZk6Y7nr9X8ux3djlKRbsj@vTfObGcmi5azBeEjHg7kqJ6TpegnPTqbfWlUzSDEIg3@zzg1x1kxooNC6MJPYg7m1GdvEAqVa/ZGU@Vrrkn2utuiC9M1t3ZBLCcb1Tqcm1gjIk@TUpaWP/fEajyP7ZjB7eN@Q7z9VNFJGybT2S3ZEkSvVOGT6bk71Fq5s42kj1ZDI@60XaZNSHWRlteKFzRcJhrejX9rTJ1xDaGiSPV6SIufwZiIAn6hHJsARbx1aInQyHC7BZMS8Tk2bBMmgpbQIWtHJTy2as07a0hSMel44@GM0LdMHZgPvCB11uk0ryhx@FTM1gTWehBYOz7oNjX@VG8kxb//17beAL6rBOuk5E@CSoPwT39Q6ntH1SqVw9wamn@EXdpz2ely/fKt167fH4Gw "PowerShell – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~37 31~~ 26 bytes This function performs a [morphological erosion](https://en.wikipedia.org/wiki/Erosion_(morphology)) on the Astan (`1-b`) part of the "image" using ~~`conv2`~~ `imerode`, and then uses some arithmetic to make all three areas different symbols. Thanks @LuisMendo for -5 bytes! ``` @(b)2*b-imerode(b,ones(3)) ``` [Try it online!](https://tio.run/##y08uSSxL/Z9kG22ggAmtuQwUDFFEDOGihlAZQyJFDfGIQiBhUUMkUUOiRWOt/ztoJGkaaSXpZuamFuWnpGok6eTnpRZrGGtq/k/MKwZK/gcA "Octave – Try It Online") [Answer] # [J](http://jsoftware.com/), 28 bytes ``` >.3 3(2 e.,);._3(0|:@,|.)^:4 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7fSMFYw1jBRS9XQ0rfXijTUMaqwcdGr0NOOsTP5rcilwpSZn5CukKVgqGBooqCgYYYUGWHgGYAjjExIzwClGDAs/hHkB6FE0H4Dl/wMA "J – Try It Online") `'AB+'` -> `2 0 1` Inspired by ngn's APL solution. 12 bytes just to pad the matrix with zeroes... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes ``` ≔⪫θ⸿θPθFθ⎇∧№KMA⁼Bι+ι ``` [Try it online!](https://tio.run/##fcyxCoMwEAbg3acImU6aPoGTV7oUBIdu1iHYtA0NiTm10KdPEwUdCt70fz93170kdU6aEMph0E8LF6cteMH4jXgumM@LrJrMqHvSdoTEhyMWA6vn5qrISvpCae9wclNsaqXelXOkIN7zMn05@0maAThywXSe6sOSihCaJmNxbR0uZuMiXI2YtGf8d5wd42bcnLVtOH7MDw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⪫θ⸿θ ``` Join the input array with carriage returns rather than the usual newlines. This is needed so that the characters can be printed individually. ``` Pθ ``` Print the input string without moving the cursor. ``` Fθ ``` Loop over each character of the input string. ``` ⎇∧№KMA⁼Bι ``` If the Moore neighbourhood contains an `A`, and the current character is a `B`... ``` + ``` ... then overwrite the `B` with a `+`... ``` ι ``` ... otherwise print the current character (or move to the next line if the current character is a carriage return). [Answer] # JavaScript, 85 bytes Threw this together late last night and forgot about it. Probably still room for some improvement somewhere. Input and output is as an array of digit arrays, using `3` for Astan, `0` for Blandia & `1` for the trench. ``` a=>a.map((x,i)=>x.map((y,j)=>o.map(v=>o.map(h=>y|=1&(a[i+v]||x)[j+h]))|y),o=[-1,0,1]) ``` [Try it online](https://tio.run/##jZBbDoMgEEX/XYYfDRMpqQvARLZBSSVWq6YVUxqDiXu3KD76SJPOz9xzGTIXKtlKnd7L5rGv1TkbcjpIGklykw1CBpdAI@Ogw5UFNUG7iIJGXU/DHZK8DFrR9wZ4FRQCoO8AK8r3IT7gUMCQqlqra0au6oK4xz0/XsvHlpjTbCbGRv2L2CfZ@kFsIbaRJ7ALME259ua/BhtDjfv/ou2eWxW/LR@nZ3KP/Q7mielfDY1yZBbJCSFmPdBEZ/KeFsiArcVdhzU3AkilyjpJ5n6sE6xpwoJTvFnWhOEJ) (For convenience, maps from & back to the I/O format used in the challenge) [Answer] # Javascript, ~~126~~ 118 bytes ``` _=>_.map(x=>x.replace(/(?<=A)B|B(?=A)/g,0)).map((x,i,a)=>[...x].map((v,j)=>v>'A'&&(a[i-1][j]<v|(a[i+1]||x)[j]<v)?0:v)) ``` Pass in one of the string arrays from the question, and you'll get an array of ~~strings~~ character arrays (thanks @Shaggy!) out using 0 for the trench. Can *probably* be golfed more (without switching over to numerical arrays), but I can't think of anything at the moment. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~92~~ 80 bytes ``` (?<=¶(.)*)B(?=.*¶(?<-1>.)*(?(1)_)A|(?<=¶(?(1)_)(?<-1>.)*A.*¶.*)) a iT`Ba`+`.?a.? ``` [Try it online!](https://tio.run/##K0otycxL/P9fw97G9tA2DT1NLU0nDXtbPS0gx95G19AOKKJhr2GoGa/pWANVBOHCpR1BivW0NDW5ErkyQxKcEhO0E/TsE/Xs//93hAMuRycIwwnEdHICMTCZTihMIMBgggEXnOUEAA "Retina 0.8.2 – Try It Online") Loosely based on my answer to [Will I make it out in time?](https://codegolf.stackexchange.com/questions/138108/) Explanation: Any `B`s immediately above or below `A`s are turned into `a`s. This then reduces the problem to checking `B`s to the left or right of `A`s or `a`s. The `a`s themselves also need to get turned into `+`s of course, but fortunately the `i` flag to `T` only affects the regex match, not the actual transliteration, so the `A`s remain unaffected. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` _2FIн¸.øVgN+FYN._3£})εøO}ø}*Ā+ ``` Matrices aren't really 05AB1E's strong suit (nor are they my strong suit).. Can definitely be golfed some more, though. Inspired by [*@ngn*'s K (ngn/k) answer](https://codegolf.stackexchange.com/a/178814/52210), so also uses I/O of a 2D integer matrix with `012` for `AB+` respectively. [Try it online](https://tio.run/##yy9OTMpM/f8/3sjN88LeQzv0Du8IS/fTdov004s3PrS4VvNR05rDO/wP76jVOtKg/d/r0O7/0dEGOhgwVgcoaogiZggXNYTKGBIpaohHFAyJEDVEEjXEIhoLAA). (The footer in the TIO is to pretty-print the output. Feel free to remove it to see the matrix output.) **Explanation:** ``` _ # Inverse the values of the (implicit) input-matrix (0→1 and 1→0) # i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] # → [[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0]] 2F # Loop `n` 2 times in the range [0, 2): Iн # Take the input-matrix, and only leave the first inner list of 0s # i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] → [0,0,0,0] ¸ # Wrap it into a list # i.e. [0,0,0,0] → [[0,0,0,0]] .ø # Surround the inverted input with the list of 0s # i.e. [[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0]] and [0,0,0,0] # → [[0,0,0,0],[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0]] V # Pop and store it in variable `Y` g # Take the length of the (implicit) input-matrix # i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] → 4 N+ # Add `n` to it # i.e. 4 and n=0 → 4 # i.e. 4 and n=1 → 5 F # Inner loop `N` in the range [0, length+`n`): Y # Push matrix `Y` N._ # Rotate it `N` times towards the left # i.e. [[0,0,0,0],[1,1,1,1],[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0]] and N=2 # → [[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,1,1,1]] 3£ # And only leave the first three inner lists # i.e. [[1,0,1,1],[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,1,1,1]] # → [[1,0,1,1],[1,0,0,0],[0,0,0,0]] } # After the inner loop: ) # Wrap everything on the stack into a list # → [[[0,0,0,0],[1,1,1,1],[1,0,1,1]],[[1,1,1,1],[1,0,1,1],[1,0,0,0]],[[1,0,1,1],[1,0,0,0],[0,0,0,0]],[[1,0,0,0],[0,0,0,0],[0,0,0,0]]] €ø # Zip/transpose (swapping rows/columns) each matrix in the list # → [[[0,1,1],[0,1,0],[0,1,1],[0,1,1]],[[1,1,1],[1,0,0],[1,1,0],[1,1,0]],[[1,1,0],[0,0,0],[1,0,0],[1,0,0]],[[1,0,0],[0,0,0],[0,0,0],[0,0,0]]] O # And take the sum of each inner list # → [[2,1,2,2],[3,1,2,2],[2,0,1,1],[1,0,0,0]] ø # Zip/transpose; swapping rows/columns the entire matrix again # i.e. [[2,1,2,2],[3,1,2,2],[2,0,1,1],[1,0,0,0]] # → [[2,3,2,1],[1,1,0,0],[2,2,1,0],[2,2,1,0]] } # After the outer loop: # i.e. [[3,5,5,4,2],[4,6,5,4,2],[2,3,2,2,1],[1,1,0,0,0]] * # Multiple each value with the input-matrix at the same positions, # which implicitly removes the trailing values # i.e. [[3,5,5,4,2],[4,6,5,4,2],[2,3,2,2,1],[1,1,0,0,0]] # and [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] # → [[0,0,0,0],[0,1,0,0],[0,2,1,0],[2,2,1,0]] Ā # Truthify each value (0 remains 0; everything else becomes 1) # i.e. [[0,0,0,0],[0,1,0,0],[0,2,1,0],[2,2,1,0]] # → [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,0,0]] + # Then add each value with the input-matrix at the same positions # i.e. [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,0,0]] # and [[0,0,0,0],[0,1,0,0],[0,1,1,1],[1,1,1,1]] # → [[0,0,0,0],[0,2,0,0],[0,2,2,2],[2,2,1,1]] # (and output the result implicitly) ``` [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 187 bytes ``` a=>a.Select((b,i)=>b.Select((c,j)=>{int k=0;for(int x=Math.Max(0,i-1);x<Math.Min(i+2,a.Count);x++)for(int y=Math.Max(0,j-1);y<Math.Min(j+2,a[0].Count);)k+=a[x][y++];return k>1&c<1?9:c;})) ``` Instead of chaining `Take()`s, `Skip()`s, and `Select()`s, instead this uses double for loops to find neighbors. HUGE byte decrease, from 392 bytes to 187. Linq isn't always the shortest! [Try it online!](https://tio.run/##jZFNb4IwGMfvfIqellaqAreNlx2WLVkipx12IB5q18UHXFmwOAzhs7NWBHXqtj5J6fPyJ//@ytdjvobWQno9lZIHM1irbgOpoog@P8ryQxRssRLB8XnXjdBnjsKWhRGbvIiV4ArjBQUSRosh5zTVea3nURY6/nteYHOuwpip5SRmFXYojF3iV0FXAYnB9iibPOSlVLpu26RXbY9VqVFtD6rUqBJn3gtJZocsqebJ1rbnfiFUWUiURe4ND9z72zvuN4S0vqX/LRhf4g0rUIZA6jthKb7QDxL1UDNp7dF9NPS04dAuzhqeKZrWNYXTaEO19VqAEjOQApNTcwDGXdaPYAA90OiYjkabHN5QjE89I0aRoQbdJyVWbV3lT8/Z/vUiv8I/XGN4g53d@B9wnUuYvEtQ99yoS7Xf0bT9Bg "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Perl 5, ~~58~~ 46 bytes ``` $m=($n=/$/m+"@+")-2;s/A(|.{$m,$n})\KB|B(?=(?1)A)/+/s&&redo ``` [TIO](https://tio.run/##K0gtyjH9/18l11ZDJc9WX0U/V1vJQVtJU9fIuljfUaNGr1olV0clr1YzxtupxknD3lbD3lDTUVNfW79YTa0oNSX//39HOOBydIIwnEBMJycQA5PphMIEAgwmGHA5IZhcYMOBGMaBWwiyDGQ6PiZULcQsR4TRIEVcEHUwJszCf/kFJZn5ecX/dQsMDAA) -12 bytes thanks to @Grimy ``` /. /;s/A(|.{@{-}}.?.?)\KB|B(?=(?1)A)/+/s&&redo ``` [TIO](https://tio.run/##K0gtyjH9/19fj0vfuljfUaNGr9qhWre2Vs9ez14zxtupxknD3lbD3lDTUVNfW79YTa0oNSX//39HOOBydIIwnEBMJycQA5PphMIEAgwmGHA5IZhcYMOBGMaBWwiyDGQ6PiZULcQsR4TRIEVcEHUwJszCf/kFJZn5ecX/dQsMDAA) * `-p` like `-n` but print also * `-00` paragraph mode * to get the width-1 `/.\n/` matches the last character of first line * `@{-}` special array the position of start of match of previous matched groups, coerced as string (first element) * `s/../+/s&&redo` replace match by `+` while matches + `/s` flag, so that `.` matches also newline character * `A(|.{@{-}}.?.?)\KB` matches + `AB` or `A` followed by (width-1) to (width+1) characters folowed by `B` + `\K` to keep the left of `B` unchanged * `B(?=(?1)A)`, + `(?1)` dirverting recursive, to reference previous expression `(|.{$m,$o})` + `(?=..)` lookahead, to match without consuming input [Answer] # Java 8, ~~169~~ 145 bytes ``` m->{for(int i=m.length,j,k;i-->0;)for(j=m[i].length;j-->0;)for(k=9;m[i][j]==1&k-->0;)try{m[i][j]=m[i+k/3-1][j+k%3-1]<1?2:1;}catch(Exception e){}} ``` -24 bytes thanks to *@OlivierGrégoire*. Uses `0` instead of `A` and `1` instead of `B`, with the input being a 2D integer-matrix. Modifies the input-matrix instead of returning a new one to save bytes. The cells are checked the same as in [my answer for the *All the single eights* challenge](https://codegolf.stackexchange.com/a/175766/52210). [Try it online.](https://tio.run/##rZNNb4MwDIbv/RW@bAIVWLOdVkanHXZcLz0iDhmlbfgICEy3CvHbWQJBpR9b12mKBNhP4tgvdki31AyXUePHtCjgjTJejQAYxyBfUT@AuTQBtilbgq8Jv@u5HiS6Ldz1SDwKpMh8mAMHp0nMWbVKc7kPmJNYccDXuDFCI7KZac4mti5p6CQu8xS0wz2InEdbIjf0HIfcRh3BfFf1XvEeR3cPJhHWOLqRH0/k@X5K7Nqn6G@0108/yJClHAK9quvGljlm5XssclSptrUkolJtgTnja1EP1bsyMShQ48EHqEI7L0A1MU5WbewhOUDkGBK1gfwJksuwXVdDcgrJGVi3P/uSOMMLDsxrgnyvcK9sr9a/wrN3DkWY/KSTCn8Mh/3wK4WH49T2aKtVP3KMZyWqNuWWHEVpd6LK2dnSHOi086q7FrsCg8RKS7Qy0egYcy0U826VyGLrJc/prrAw7YZAo7oKduaUSq9uvgA) **Explanation:** ``` m->{ // Method with integer-matrix parameter and no return-type for(int i=m.length,j,k;i-->0;)// Loop over the rows for(j=m[i].length;j-->0;) // Inner loop over the columns for(k=9;m[i][j]==1& // If the current cell contains a 1: k-->0;) // Inner loop `k` in the range (9, 0]: try{m[i][j]= // Set the current cell to: m[i+k/3-1] // If `k` is 0, 1, or 2: Look at the previous row // Else-if `k` is 6, 7, or 8: Look at the next row // Else (`k` is 3, 4, or 5): Look at the current row [j+k%3-1] // If `k` is 0, 3, or 6: Look at the previous column // Else-if `k` is 2, 5, or 8: Look at the next column // Else (`k` is 1, 4, or 7): Look at the current column <1? // And if this cell contains a 0: 2 // Change the current cell from a 1 to a 2 : // Else: 1; // Leave it a 1 }catch(Exception e){}} // Catch and ignore ArrayIndexOutOfBoundsExceptions // (try-catch saves bytes in comparison to if-checks) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~86~~ 80 bytes ``` $p="(.?.?.{$(($args|% i*f ' ')-1)})?" $args-replace"(?s)(?<=A$p)B|B(?=$p`A)",'+' ``` [Try it online!](https://tio.run/##fZLhToMwFIX/9yluWCetBRP/S4C@iJKtcyQMKmVRAzw79raDbU53ScmXw2kvp7m6@VSt2auqmugOEugnqpOAPaX26SljtGjfzbCG8nEHIQl5/MxHngbE6XGrdFVsVMBSw1n6kuRUczlIliZUv@U8iEIRTiMhGSMRywKSL0Vy6UEiSolwi/IKbd2gKyLPGGTRr0bCg0AUAsGhvESxoJWtS8zoGiEKh@49N@JLKLeuuruF51zall/C3Bj0Hp68vlt@Tokm4n0z/p8dc2PmE0rxh3ryClf4gbi4eD14ur8@j758dg4DrKEnYIseCh1R9aXVplNbO0b01eutMseqs8KDnS50Xcqx@lj2OH01@1dwrDfN4aDqDrp9aaAqawVdA9vS2In7Bu8zZJx@AA "PowerShell – Try It Online") The map is a string with newlines. This script replaces `B` to `+` with regexp `(?<=A(.?.?.{$MapWidth-1})?)B|B(?=(.?.?.{$MapWidth-1})?A)`. Less golfed Test script: ``` $f = { $l=($args|% indexOf "`n")-1 $p="(.?.?.{$l})?" $args-replace"(?s)(?<=A$p)B|B(?=$p`A)",'+' } @( ,(@" AAAAAAAAAA ABAAAAAABA ABBBAABABA ABBBAABABA ABBBBABABA ABBBBABBBB ABBBBABBBB ABBBBBBBBB BBBBBBBBBB "@,@" AAAAAAAAAA A+AAAAAA+A A+++AA+A+A A+B+AA+A+A A+B++A+A+A A+BB+A++++ A+BB+A+BBB A+BB+++BBB ++BBBBBBBB "@) ,(@" AAA AAA BBB "@,@" AAA AAA +++ "@) ,(@" AAAAAAAAAA AAAABBBAAA AAAABBBAAA AAAABBBAAA AAAAAAAAAA BBBBBBABBB BBBBBBAABB BBBAAAAABB BBBBBBBBBB "@,@" AAAAAAAAAA AAAA+++AAA AAAA+B+AAA AAAA+++AAA AAAAAAAAAA ++++++A+++ BB++++AA+B BB+AAAAA+B BB+++++++B "@) ) | % { $map,$expected = $_ $result = &$f $map $result-eq$expected #$result # uncomment this line to display results } ``` Output: ``` True True True ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 102 bytes ``` ->a{a+=?.*s=a.size (s*9).times{|i|a[j=i/9]>?A&&a[j-1+i%3+~a.index($/)*(i/3%3-1)]==?A&&a[j]=?+} a[0,s]} ``` [Try it online!](https://tio.run/##fY7RCoIwGIXv/6eISFGXM/HKiynba8guFiksKKIpVGqvvpyaJVIHBt/PDpzvWu3vuiDaT0QtEEmxp4jASj5ycJQXu7iUp1zVjWxEdiQyiHmSUtvuDj9E0orQU2B5PuQ3ZxO4niODyIr80OWEjDVOUtSCyHZbxVsNl6pUqyKDNZ0ClA3ADDJmYIlshl0W2AcmYmvg0O/BbBXM@/09SRkhY/APx@6wRz/zpgRD743fUgD6BQ "Ruby – Try It Online") input/output as a newline separated string [Answer] # [Python 2](https://docs.python.org/2/), ~~123~~ 119 bytes ``` lambda m:[[[c,'+'][c=='B'and'A'in`[x[j-(j>0):j+2]for x in m[i-(i>0):i+2]]`]for j,c in e(l)]for i,l in e(m)];e=enumerate ``` [Try it online!](https://tio.run/##lZDNisMgFIX3PoV0o1Jbhi5TUoiLvoQj1EkMcyWakKbQefpU40z6S2Huyu@ccy8Hu5/hu/Wbsc4/x0a7r0pjl0kpS06WRMkyz4kg2lekIOAP8iztitrdB8vscqPqtsdnDB47CSsKUYYgq8PkWF5Gz9CGTQy8SeyY2prc@JMzvR7MWJka74OaIRxzU6qmTne0gePAHYsO7nrwAyZkbVvw4SZKCkJ7KoO9KOZZ8IlFIjGzEJHesXjmMG9YXFlcGSl2W@s3//d4kbgvHkvHbv/g2/1UongoFndmTh/zuvh4AQ "Python 2 – Try It Online") I/O is a list of lists [Answer] # TSQL, 252 bytes Splitting the string is very costly, if the string was split and already in a table the byte count would be 127 characters. Script included in the bottom and completely different. Sorry for taking up this much space. Golfed: ``` WITH C as(SELECT x,x/z r,x%z c,substring(@,x+1,1)v FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z WHERE'P'=type)SELECT @=stuff(@,x+1,1,'+')FROM c WHERE exists(SELECT*FROM c d WHERE abs(r-c.r)<2and abs(c-c.c)<2and'AB'=v+c.v)PRINT @ ``` Ungolfed: ``` DECLARE @ varchar(max)= 'AAAAAAAAAA ABAAAAAABA ABBBAABABA ABBBAABABA ABBBBABABA ABBBBABBBB ABBBBABBBB ABBBBBBBBB BBBBBBBBBB'; WITH C as ( SELECT x,x/z r,x%z c,substring(@,x+1,1)v FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z WHERE'P'=type ) SELECT @=stuff(@,x+1,1,'+') FROM c WHERE exists(SELECT*FROM c d WHERE abs(r-c.r)<2 and abs(c-c.c)<2 and'AB'=v+c.v) PRINT @ ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/968018/dig-a-border-trench)** # TSQL, 127 bytes(Using table variable as input) Execute this script in management studio - use "query"-"result to text" to make it readable ``` --populate table variable USE master DECLARE @v varchar(max)= 'AAAAAAAAAA ABAAAAAABA ABBBAABABA ABBBAABABA ABBBBABABA ABBBBABBBB ABBBBABBBB ABBBBBBBBB BBBBBBBBBB' DECLARE @ table(x int, r int, c int, v char) INSERT @ SELECT x+1,x/z,x%z,substring(@v,x+1,1) FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@v)z)z WHERE'P'=type and len(@v)>number -- query(127 characters) SELECT string_agg(v,'')FROM(SELECT iif(exists(SELECT*FROM @ WHERE abs(r-c.r)<2and abs(c-c.c)<2and'AB'=v+c.v),'+',v)v FROM @ c)z ``` **[Try it out](https://data.stackexchange.com/stackoverflow/query/968103/dig-a-border-trench)** - warning output is selected and not readable. Would be readable with print, but that is not possible using this method ]
[Question] [ > > **NOTICE** - This challenge is now closed. Any new answers will be ignored and the accepted answer will *not* change > > > ## Challenge Write a valid program which, when just two characters in the program are changed, removed or added, completely changes the output. The changed output must have a Levenshtein Distance of **15** or more from your original output. The output must be non empty and finite. Your program therefore must terminate within 1 minute. Your output *must* be deterministic, outputting the same thing each time you run the program. It also must not be platform dependent. Any hash functions are ***disallowed***, as are built in PRNGs. Similarly, seeding an RNG is not allowed. After a period of three days, an uncracked submission will become safe. In order to claim this safety, you should edit your answer to show the correct answer. (Clarification: Until you reveal the answer, you are not safe and can still be cracked.) ## Formatting Your answer should be in the following format: ``` # <Language name>, <Program length> ## Code <code goes here> ## Original Output <output goes here> ## Changed output <changed output goes here> ``` ## Robbers The robbers' challenge is to find out which two characters you have changed. If a robber has cracked your solution, they will leave a comment on your answer. You can find the robbers' thread [here](https://codegolf.stackexchange.com/questions/54466). ## Winning The person with the shortest uncracked solution wins. ## Leaderboard ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>site = 'meta.codegolf';postID = 5686;isAnswer = false;QUESTION_ID = 54464;var safe_list=[];var uncracked_list=[];var n=0;var bycreation=function(x,y){return (x[0][0]<y[0][0])-(x[0][0]>y[0][0]);};var bylength=function(x,y){return (x[0][1]>y[0][1])-(x[0][1]<y[0][1]);};function u(l,o){ jQuery(l[1]).empty(); l[0].sort(o); for(var i=0;i<l[0].length;i++) l[0][i][1].appendTo(l[1]); if(l[0].length==0) jQuery('<tr><td colspan="3" class="message">none yet.</td></tr>').appendTo(l[1]);}function g(p) { jQuery.getJSON('//api.stackexchange.com/2.2/questions/' + QUESTION_ID + '/answers?page=' + p + '&pagesize=100&order=desc&sort=creation&site=codegolf&filter=!.Fjs-H6J36w0DtV5A_ZMzR7bRqt1e', function(s) { s.items.map(function(a) { var he = jQuery('<div/>').html(a.body).children().first(); he.find('strike').text(''); var h = he.text(); if (!/cracked/i.test(h) && (typeof a.comments == 'undefined' || a.comments.filter(function(b) { var c = jQuery('<div/>').html(b.body); return /^cracked/i.test(c.text()) || c.find('a').filter(function() { return /cracked/i.test(jQuery(this).text()) }).length > 0 }).length == 0)) { var m = /^\s*((?:[^,;(\s]|\s+[^-,;(\s])+)\s*(?:[,;(]|\s-).*?([0-9]+)/.exec(h); var e = [[n++, m ? parseInt(m[2]) : null], jQuery('<tr/>').append( jQuery('<td/>').append( jQuery('<a/>').text(m ? m[1] : h).attr('href', a.link)), jQuery('<td class="score"/>').text(m ? m[2] : '?'), jQuery('<td/>').append( jQuery('<a/>').text(a.owner.display_name).attr('href', a.owner.link)) )]; if(/safe/i.test(h)) safe_list.push(e); else uncracked_list.push(e); } }); if (s.length == 100) g(p + 1); else { var s=[[uncracked_list, '#uncracked'], [safe_list, '#safe']]; for(var p=0;p<2;p++) u(s[p],bylength); jQuery('#uncracked_by_length').bind('click',function(){u(s[0],bylength);return false}); jQuery('#uncracked_by_creation').bind('click',function(){u(s[0],bycreation);return false}); } });}g(1);</script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><style>table th,table td { padding: 5px;}th { text-align: left;}.score { text-align: right;}table a { display: block;}.main { float: left; margin-right: 30px;}.main h3,.main div { margin: 5px;}.message { font-style: italic;}</style><div class="main"><h3>Uncracked submissions</h3><table> <tr> <th>Language</th> <th class="score">Length</th> <th>User</th> </tr> <tbody id="uncracked"></tbody></table><div>Sort by: <a href="#" id="uncracked_by_length">length</a> <a href="#" id="uncracked_by_creation">creation</a></div></div><div class="main"><h3>Safe submissions</h3><table> <tr> <th>Language</th> <th class="score">Length</th> <th>User</th> </tr> <tbody id="safe"></tbody></table></div> ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54637/6741) # Shakespeare, 1721 bytes I tried a Shakespeare answer. It is not short, and I had difficulties to change the output with only 2 characters, but I think I succeeded quite well. Good Luck everybody. As a side note, I used the "compiler" available at [this](https://github.com/drsam94/Spl/ "this") address and **it may not work with another one.** (it does not work with the online interpreter) The output does not contain any unprintable characters. ## Code ``` The Hidden Change. Helen, a young woman with a remarkable patience. Helena, a likewise young woman of remarkable grace. Claudio, a remarkable man much in dispute with Claudius. Claudius, the flatterer. The Archbishop of Canterbury, the useless. Act I: Claudius's insults and flattery. Scene I: The insulting of Helen. [Enter Claudius and Helen] Claudius: Thou art as hairy as the sum of a disgusting horrible fatherless dusty old rotten fat-kidneyed cat and a big dirty cursed war. Thou art as stupid as the product of thee and a fat smelly half-witted dirty miserable vile weak son. [Exeunt] Scene II: The complimenting of Helena. [Enter Claudio and Helena] Claudio: Thou art the sunny amazing proud healthy peaceful sweet joy. Thou art as amazing as the product of thee and the pretty lovely young gentle handsome rich Hero. Thou art as great as the sum of thee and the product of a fair golden prompt good honest charming loving noble king and a embroidered rich smooth golden angel. [Exeunt] Scene III: The insulting of Claudio [Enter Claudius and Helen] Helen: Thou art as stupid as the sum of the sum of thee and a cat and me. [Exit Helen] [Enter Claudio] Claudius: Thou art as stupid as the sum of thee and the product of the product of me and Helen and Helena [Exeunt] Scene IV: The Final Countdown [Enter The Archbishop of Canterbury and Claudius] Claudius: Thou art the sum of you and a cat. The Archbishop of Canterbury: Am I better than a fine road? Claudius: If not, let us return to the insulting of Claudio. [Exit The Archbishop of Canterbury] [Enter Claudio] Claudius: Open your heart! Open your heart! [Exeunt] ``` ## Original Output ``` 11324620811132462081 ``` ## Changed Output ``` 11 ``` [Answer] # J, 76 bytes (safe) ## Code ``` ,:|.,.<,:>><|.,:>,.<|.>,:<<|.>|.,:,.<,.<,:,.<,:>|.<,:>,.|.<,:,.|.<<,:>126$a. ``` ## Original Output ``` ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐│ ││┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐││ │││┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐│││ ││││┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐││││ │││││ ┌┬┐├┼┤└┴┘│─ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}│││││ ││││└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘││││ │││└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘│││ ││└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘││ │└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘│ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` ## Changed output ``` ┌──────────────────────┐ │┌────────────────────┐│ ││┌──────────────────┐││ │││┌────────────────┐│││ ││││┌──────────────┐││││ │││││┌───────────┬┐│││││ ││││││0 0 0 0 0 0│││││││ │││││└───────────┴┘│││││ ││││└──────────────┘││││ │││└────────────────┘│││ ││└──────────────────┘││ │└────────────────────┘│ └──────────────────────┘ ``` # EDIT: Solution `{:` added (shown between `###`) ``` ,:|.,.<,:>><|.,:>,.<|.>,:<<|.>|.,:,.<,.<,:,.<,###{:###:>|.<,:>,.|.<,:,.|.<<,:>126$a. ``` Makes use of the monad [`{::` Map](http://www.jsoftware.com/jwiki/Vocabulary/curlylfcoco). Most of the rest of the code is useless garbage. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54566/6828) # Ruby, 14 ## Code ``` x=9;puts x*9*9 ``` ## Original Output ``` 729 ``` ## Changed output ``` 99999999999999999 ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54534) # Bash, 15 bytes ``` echo {{{1..9}}} ``` ### Original output ``` {{1}} {{2}} {{3}} {{4}} {{5}} {{6}} {{7}} {{8}} {{9}} ``` ### Modified output ``` 1 2 3 4 5 6 7 8 9 ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54489/20080) # Prolog, 10 bytes ## Code ``` X is 1/42. ``` ## Original Output ``` X = 0.023809523809523808. ``` ## Changed output ``` X = -2. ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54533/20080) # Python 2, 43 bytes ## Code ``` print (sum(range(054321)*9876)*87654)/01234 ``` ## Original Output ``` 334960491355406 ``` ## Changed output ``` 222084148077792 ``` The Levenshtein Distance is 15 exactly. Both the original and the changed run under 1 minute on my computer. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54515/20080) # BrainFuck , 504 bytes No one should ever need to analyse a brainfuck code. This is a modified version of an earlier code, but any change in a Brainfuck code make a big difference in the output. I use the Interpreter at <http://esoteric.sange.fi/brainfuck/impl/interp/i.html> to test my code. Good Luck ! # Code ``` ++++++++++[->++++++++<]>>++++++[-<---------->]<-------[----------->>>-<<+<[-->->+<<]]>>>+<<>>>+++[->++++++++++<]>++.<+++++++++[->>>>>>>++++++++++<+++++<++++++++++++++<++++++++++<+++++<++++++++++<<]++++++++++>>+++++...>++>++>-->+>++++<<<<<<<.<<<[->>>>>>.<<>>>>>.<<<<<.>>>>>.<<<<<>>>.<<<<.>>>>>.<<<<.>>>>>.<<<<<.>>>>.<<<<<.>>>>.<<...>.<<<<<<]>[->>>>>.<<...>>>.<<<<.>>>>>.<<<<...>>>>.<<<<<.>>>>.<<...>.<<<<<]>[->>>>.<<>>>>>>.<<<<<<..>>>.<<<<.>>>>>.<<<<>>>>>>.<<<<<<.>>>>>>.<<<<<<>>>>.<<<<<.>>>>.<<...>.<<<<] ``` # Original Output ``` ___ / \ | | \___/ ``` # Changed Output ``` }}}\}}}|.}}}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\\}}|.}.|///\ ``` Note: The Changed Output contains several STX(ASCII 2) and EOT(ASCII 4) characters Here is the version with ASCII codes in parenthesis instead of unprintable characters: ``` (2)}}}(2)\}}}|(2).}}}.(2)|///\\(4)}|(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)///\\(4)}}|(2).(4)}(4).(2)|///\\(4)}}(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)|/(4)/\\(4)}}|(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)|///\\(4)}}|(2).(4)}(4).(2)|///\ ``` [Answer] # [cracked](/a/54644) # Wolfram Language (Mathematica or WolframAlpha), 3 bytes ## Code ``` 8.! ``` ## Original Output ``` 40320. ``` ## Changed output ``` 2.67182 - 0.891969 I ``` For those trying it on WolframAlpha the result shows up as ![Mathematica graphics](https://i.stack.imgur.com/ySCO4.png) I deleted my previous answer because it worked only on Mathematica and not in [WolframAlpha](http://www.wolframalpha.com/input/?i=8.!). That put robbers behind a paywall (instead of the deserved bars), which wasn't fair. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54550/21654) # MATLAB / OCTAVE, 7 bytes # Code: ``` cos(pi) ``` # Original output: ``` ans = -1 ``` # Changed output: ``` ans = 1.5708 - 0.8814i ``` This gives a Levenshtein distance of exactly 15. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54514/20080) # CJam, 8 characters ## Code ``` "~f":i:# ``` ## Original output ``` 17290024234092933295664461412112060373713158853249678427974319674060504032816100667656743434803884485234668769970047274563123327020396104330878852891146011372048615474145637592955298601510765168228550988848615653376 ``` ## Changed output Output after modification is [here](https://bpaste.net/raw/f449928d9870). Both take under a minute on my 2GHz laptop. ## Explanation People seem amazed at how this works. The code works like this: ``` "~f" Push a string :i Convert to a list of bytes [126 102] :# Fold with # (power) ``` This calculates 126^102. The solution was: ``` "}\t~f" :i Convert to a list of bytes [125 9 126 102] :# Fold with # (power) ``` This calculates ((125^9)^126)^102, which is hundreds of thousands of digits long. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54730/20080) # Pyth, 8 bytes ## Code: ``` %CG^3y21 ``` ## Initial Output: ``` 51230235128920219893 ``` ## Changed Output: ``` 58227066 ``` [Answer] # CJam, 13 bytes (safe) ``` J{m!_)mQ%2b}/ ``` [Try it online.](http://cjam.aditsu.net/#code=J%7Bm!_)mQ%252b%7D%2F) ### Original output ``` 000010010101001010001101111000111011100110100100001011101101010100011111110010010010001111111111010000010011001110001010011111000010001001110111100000010110000010000111011011110101110010000011100111100 ``` ### Modified output ``` 11101101100011110001011010000100111011000010011101100000001010100111011010011011010111101000000011101111100000000110001000111110110110101111110100101110000101110100110011110000010101110 ``` ### Solution ``` J{m!_)ci%2b}/ ``` [Try it online.](http://cjam.aditsu.net/#code=J%7Bm!_)ci%252b%7D%2F) ### How it works This takes advantage of how CJam implicitly prints the entire stack after executing the program. Simply dumping the base-2 representations of a few integers on the stack causes them to be printed without any separator, so it should be hard to figure out where one of them begins and another one ends. The original code does the following: ``` J{ e# For each I from 0 to 18, do the following: m! e# Calculate the factorial of I. _) e# Push a copy and add 1. mQ e# Compute the result's integer square root. % e# Calculate the residue of the factorial divided by the square root. 2b e# Push the array of base 2-digits of the resulting integer. }/ e# ``` As @AndreaBiondo notes in the comments, the binary representations of **0!** to **8!** can be found at the beginning of the output (spaces added for clarity): ``` 1 1 10 110 11000 1111000 1011010000 1001110110000 1001110110000000 ``` The intended change was to replace `mQ` with `ci`, which takes the integer modulo 65536, using 16-bit character arithmetic (casting to an unsigned 16-bit character, then back to integer). I hoped the idea of using `c` to replace a mathematical operator would be obscure enough. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54574/21487) # Python 2, 58 bytes ## Code ``` R=range(01234);print sum(m<<min(m,n)for m in R for n in R) ``` ## Original Output ``` 2444542772018013876036977350299418162656593659528311114655474359757543862791958572561591492595632222632192542272836836649846934427359810217936317967768095940470375690509652583392001888886352103127515963142 ``` ## Changed output ``` 4669 ``` That 15 distance rule sure made things tricky. I hope this goes well. [Answer] # [Cracked](https://codegolf.stackexchange.com/questions/54466/two-makes-all-the-difference-robbers/54641#54641) # Python 2, 50 bytes Original Code: ``` '~'*sum([(x,y)[x%2]for x in[y for y in range(8)]]) ``` Original Output: ``` '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' ``` Modified Output: ``` '~~~~~~~~~~~~~~~~~~~' ``` Not overly short, and maybe not too hard, I don't really know. I'll try to come up with something better soon. [Answer] # [Cracked](https://codegolf.stackexchange.com/questions/54466/two-makes-all-the-difference-robbers/54707#54707) # PHP, 164 bytes ## Code ``` $S_U_M_M_E_R = 1; $A_U_T_U_M_N = 2; $T_I_M_E = 1; if ($T_I_M_E == $S_U_M_M_E_R) { $A_C_=$T_I_=$O_N= 'SWIM' ? 'TAN' : 'DRINK'; } print $T_I_M_E * $A_U_T_U_M_N; ``` ## Original Output ``` 2 ``` ## Changed output ``` -1.1306063769532 ``` [Answer] # GolfScript, 15 bytes (safe) ## Code `10,{1+3?}%{*}*]` ## Changed code `107,{1+3?}%{^}*]` ## Original Output `47784725839872000000` ## Changed output `557154` Explainations: ``` 10, # numbers from 0 to 10 {1+3?}% # add one and raise to the cube. (%=for each) {*}*] # take the product and place it in a list(useless)` ``` Changed code ``` 107, # numbers from 0 to 107 {1+3?}% # add one and raise to the cube. (%=for each) {^}*] # xor them and place it in a list(useless) ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54763) # [APL](http://ngn.github.io/apl/web/), 7 bytes # Code ``` -/3⍴157 ``` # Original output ``` 157 ``` # Changed output ``` 0.11479360684269167J0.37526348448410907 ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54484/20080) # C, 53 bytes ## Code ``` main(a,_){puts(_*_*_*_*_-1?"Expected Output":"?");} ``` ## Original Output ``` Expected Output ``` ## Changed output ``` ? ``` Probably too easy, but who knows. (Note: it is technically system dependent but the type of system on which it fails would also fail all the other submissions here, so I figured it was a moot point). # [Cracked](https://codegolf.stackexchange.com/a/54493/20080) # Edit I made a mistake. New code which is more secure to the obvious attack: ``` main(a,_){puts(_*_-1||_*_*_-1||_*_*_*_-1?"Expected Output":"?");} ``` same outputs. New size of 65 bytes. Hopefully harder... though still probably too easy. [Answer] [Cracked by issacg](https://codegolf.stackexchange.com/questions/54466/two-makes-all-the-difference-robbers/54664#54664) # MATLAB, 20 bytes ## Code ``` format long sin(i^pi) ``` ## Original Output ``` 0.331393418243797 - 1.109981778186163i ``` ## Changed Output ``` 0.220584040749698 - 0.975367972083631i ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54754/43044) # Octave, 20 bytes ``` format long; cos(1)*1 ``` ## Output: ``` 0.540302305868140 ``` ## Changed Output: ``` 111 ``` [Answer] # CJam, 28 bytes (safe) ``` "jK=\~"5*)ib257b~{G$5$+}*]Jb ``` [Try it online](http://cjam.aditsu.net/#code=%22jK%3D%5C~%225*)ib257b~%7BG%245%24%2B%7D*%5DJb). ### Original output ``` 7705397905065379035618588652533563996660018265606606763127193120855297133322151462150247488267491212817218321670720380456985476811737021068519164822984561148339610474891720342171053455881107227302663880445203851079295537592154028123394687360216561235621729967011148112746984677807932995700334185726563970223018774 ``` ### Modified output ``` 16650180159137697345989048346412185774444335111603430666402604460993564226370500963166158223117360250140073061887053326627468495236957122711656527124216908303912850181595147494475577084810653496778801228980874902968634143062 ``` ### Solution ``` "jK=\~"5*Wcib257b~{G$5$+}*]Jb ``` [Try it online.](http://cjam.aditsu.net/#code=%22jK%3D%5C~%225*Wcib257b~%7BG%245%24%2B%7D*%5DJb) ### How it works I went a little overboard with this one... The original code does the following: ``` "jK=\~"5* e# Push "jK=\~jK=\~jK=\~jK=\~jK=\~". )i e# Pop the last character and cast it to integer. b257b e# Convert the remainder of the string from that base to base 257. ~ e# Dump all resulting base-257 digits on the stack: e# 137 72 124 88 81 145 85 32 28 251 118 230 53 13 245 147 256 116 187 22 224 { e# Do the following 224 times: G$5$+ e# Add copies of the 5th and 17th topmost integers on the stack e# (recurrence of a lagged Fibonacci sequence). }* e# ] e# Wrap the entire stack in an array. Jb e# Convert from base 19 to integer. e# The resulting integer is printed implicitly. ``` The intended change is replacing `(i` with `Wci`. This leaves the repeated string untouched and pushes **65535** (by casting to an unsigned 16-bit character, then back to integer), so that the first elements of the lagged Fibonacci sequence become ``` 87 225 162 210 73 196 142 219 175 61 40 147 0 93 75 55 103 116 237 188 108 122 176 133 135 240 251 155 224 82 181 75 23 87 139 49 148 169 84 109 110 166 52 103 83 185 78 73 ``` and the loop is repeated **126** times. [Answer] # Javascript, 47 (safe) ## Code ``` for(var i=64460,x=773;i>=1324;)x=i--/x;alert(x) ``` ## Original Output ``` 11.948938595656971 ``` ## Changed output ``` 3.679331284911481 ``` Distance is exactly 15. Tested in Chrome and IE. ## Solution ``` for(var i=64460,x=773;i>>=1<324;)x=i--/x;alert(x) ``` This uses the bit shift assignment operator `i>>=1` to make the loop interval non-linear. Also this has the amusing property that someone trying to brute force a solution will run into several variations that run infinitely. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54510/20080) # [Fantom](http://fantom.org/), 26 ## Code ``` Float.makeBits(1123581321) ``` ## Original Output ``` 5.55122931E-315 ``` ## Changed output ``` 124.24518585205078 ``` Security Through Obscurity, if nobody knows the language, nobody can crack it. Levenshtein Distance of 15. Run it in fansh. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54521/20080) ## CJam, 6 characters ``` 25mse7 ``` **Original output** ``` -1323517.5009777304 ``` **Changed output** ``` 72004899337.38588 ``` This might be too easy. :P [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54497/20080) # Java, 149 Characters ``` class T{public static void main(String[]a){System.out.print(((Integer.MAX_VALUE^25214903917L)&281474976710655L)*25214903917L+11L&281474976710655L);}} ``` ## Original Output ``` 174542852132661 ``` ## Modified Output ``` 106906909674100 ``` Hint: > > Random.java > > > [Answer] # Brainfuck, 100 bytes ## Code ``` ++++++++++++++++++++++++++>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[>.+<-] ``` ## Original output ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` ## Changed output ``` [ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` Note: Possibly easy to crack. But then, nothing is easy in Brainfuck. [Answer] # [cracked](/a/54601) # modern Perl 5, 70 ## Code ``` @array = (qw smiles) x 11; s/.*// foreach @array; print "@array\n"; ``` ## Original Output A single newline. ## Changed output ``` mile mile mile mile mile mile mile mile mile mile ``` The output begins with a space and ends with a newline. [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54616/31516) # Matlab, 12 bytes ## Code ``` -sin(2:.5:3) ``` ## Original output ``` -0.9093 -0.5985 -0.1411 ``` ## Changed output ``` 0.4228 0.7032 0.9228 ``` [Answer] ## perl, 12 bytes # [cracked](/a/54613/20198) Code ``` print sin 97 ``` Original output ``` 0.379607739027522 ``` Desired output ``` -0.64618863474386 ``` [Answer] # [Cracked](https://codegolf.stackexchange.com/a/54605/7951) # SWI-Prolog, 54 bytes ## Code ``` assert(d(E,F):-(print(E),print(F))). d(123456,123456). ``` ## Original Output ``` true. 123456123456 true. ``` ## Changed output ``` true. false. ``` ]
[Question] [ There are [clever ways](/q/17456) of determining whether a number is a power of 2. That's no longer an interesting problem, so let's determine whether a given integer is an integer power of **-2**. For example: ``` -2 => yes: (-2)¹ -1 => no 0 => no 1 => yes: (-2)⁰ 2 => no 3 => no 4 => yes: (-2)² ``` ## Rules * You may write a [program or a function](//codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](//codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output. * Your input is a single integer, and output must be a truthy value if the integer is an integer power of -2, and a falsy value otherwise. No other output (e.g. warning messages) is permitted. * 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. * You may use any [programming language](//codegolf.meta.stackexchange.com/q/2028), but note that these [loopholes](//codegolf.meta.stackexchange.com/q/1061/) are forbidden by default. ## Winning condition This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") contest: the answer which has the fewest bytes (in your chosen encoding) is the winner. [Answer] ## Mathematica, 22 bytes ``` EvenQ@Log2@Max[#,-2#]& ``` [Try it online!](https://tio.run/nexus/mathics#C07NSU0uiQ5KzEtPjdY1NDDQAeJYnf@uZal5gQ4@@elGDr6JFdHKOrpGyrFq/2MV9PUVAooy80r@AwA "Mathics – TIO Nexus") (Using Mathics instead, where this solution also works.) I tried to find a solution with bitwise operators for a while, and while one definitely exists, I ended up finding something which is probably simpler: * `Max[#,-2#]` multiplies the input by **-2** if it's negative. Multiplying by another factor of **-2** doesn't change whether the value is a power of **-2** or not. But now all odd powers of **-2** have been turned into even powers of **-2**. * But even powers of **-2** are also even powers of **2**, so we can use a simple `Log2@...` and check if the result is an integer (to check whether it's a power of **2**). This already saves two bytes over `Log[4,...]` (another way to look at even powers of **-2**). * As an added bonus, checking whether a value is an even integer is shorter than just checking whether it's an integer: we can save three more bytes by using `EvenQ` instead of `IntegerQ`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` æḟ-2= ``` [Try it online!](https://tio.run/nexus/jelly#ARkA5v//w6bhuJ8tMj3/LTlyOcK1xbzDh@KCrEf/ "Jelly – TIO Nexus") ### How it works ``` æḟ-2= Main link. Argument: n æḟ-2 Round n towards 0 to the nearest power of -2. = Test if the result is equal to n. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` b-2S⁼1 ``` [Try it online!](https://tio.run/nexus/jelly#@5@kaxT8qHGP4f///3WNAA "Jelly – TIO Nexus") This is based on how Jelly converts an integer *N* to any arbitrary base *B*, doing so by converting *N* to an array, in which each integer is a digit *d* of (*N*)*B*, which can have a value 0≤*Vd*<*B*. Here, we will 0-index digits from the right, so every digit adds *VdBd* to form *N*. *Vd*<*B*⇔*VdBd*<*BBd*=*B**d*+1, therefore every possible *N* has only one unique representation, if we ignore leading 0s in (*N*)*B*. Here, *d*=input, *B*=-2. *N*=*Bd*=1*Bd*=*VdBd*⇔1=*Vd*⇔*Vd*=1, and, since we're not adding any other multiples of powers of *B*, every other *V* would be 0. Right now, the array should be a 1 concatenated with *d* 0s. Since Jelly 1-indexes from the left, we should check whether the array's 1st element is 1, and all other elements are 0. Hmm... all good, right? No? What's going on? Oh yeah, I have a better idea! First, let's take the sum of all of the integers in the array, treating it as if it was an integer array and not a number in base -2. If it is 1, it means that there is only one 1, and all other integers are 0. Since there can't be leading zeroes, except in the case of 0-2 (where the sum would be 0≠1 anyways), the 1st integer must be non-zero. The only non-zero integer in the array is the 1, so it must be the first one. Therefore, this is the only case that the sum of all of the integers in the array would be 1, because the smallest possible sum of a pair of positive integers is Σ{1,1}=2, since the smallest positive integer is 1. Every integer in a base representation is non-negative, so the only way the sum is 1 is to only have one 1, and all other integers are 0. Therefore, we can just check if the sum of all of the integers in the array is 1. Here is what the code does: ``` b-2S⁼1 Main link. Arguments: d b-2 Convert d to base -2. S Take the sum. ⁼1 Check if the sum is equal to 1. ``` [Answer] # [Python](https://docs.python.org/3/), 46 bytes *-2 bytes thanks to @ovs.* ``` def g(x): while x%-2==0!=x:x/=-2 return x==1 ``` Function with usage: ``` g(4) # put your number between the brackets ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFdo0LTikuhPCMzJ1WhQlXXyNbWQNG2wqpC31bXiEuhKLWktChPocLW1vB/QVFmXglQg4nmfwA) [Answer] # [Python 2](https://docs.python.org/2/), ~~35~~ ~~34~~ 32 bytes ``` f=lambda n:n==1or n!=n%2<f(n/-2) ``` [Try it online!](https://tio.run/nexus/python2#FcvRCkAwAAXQZ77ieli2sjSKkvmXiUlxafj@4fXUid5ubh8nB3a01hwBzCxF1XvJUlcq@p@wEsFxmaU2TWFa1aXJGVbeyEX9QA8QVw4ByQJfVCq@ "Python 2 – TIO Nexus") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Y(IÄÝm¹å ``` [Try it online!](https://tio.run/nexus/05ab1e#@x@p4Xm45fDc3EM7Dy/9/9/QDAA) or as a [Test suite](https://tio.run/nexus/05ab1e#qymr/B@pUXm45fDc3MrDS/9XKh3eb6VweL@Szn9dCy5dEy5dIy5dQy4DLkMuIy5jLhMuQzMA) **Explanation** ``` Y( # push -2 IÄÝ # push range [0 ... abs(input)] m # element-wise power ¹å # check if input is in the resulting list ``` [Answer] # JavaScript (ES6), 37 28 24 bytes ``` f=x=>!x|x%2?x==1:f(x/-2) ``` Saved 4 bytes thanks to Arnauld. ``` f=x=>!x|x%2?x==1:f(x/-2) console.log(f(-2)); console.log(f(-1)); console.log(f(0)); console.log(f(1)); console.log(f(2)); console.log(f(3)); console.log(f(4)); ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~98~~ 50 bytes ``` lambda x:x*(x&-x==abs(x))*((x<0)^x.bit_length()&1) ``` [Try it online!](https://tio.run/nexus/python2#BcFLDkAwEADQq8yKGUp8dqI3aUgbyiSUVBdz@3rPa5Mve7vNgkxSoRSNaG3dh0JUIcrc0SKt47ReezjSiVT0lP0TgYEDSLTh2LEZBzUOdU8TvJFDAlalSaXyyJR/ "Python 2 – TIO Nexus") [Answer] # Excel, ~~40~~ 36 bytes Saved 4 bytes by CallumDA Excel can certainly do it but correcting errors adds 11 bytes ``` =IFERROR(-2^IMREAL(IMLOG2(A1)),1)=A1 ``` Input is in cell `A1`. Output is `TRUE` or `FALSE` If it was allowed to return either `FALSE` or `#NUM!` error for false values, it would be only 25 bytes: ``` =-2^IMREAL(IMLOG2(A1))=A1 ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~34~~ 29 bytes ``` f(n){n=n%2?n==1:f(n?n/-2:2);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs82T9XIPs/W1tAKyLfP09c1sjLStK79n5uYmaehyVXNpaBQUJSZV5KmoaSaEpOnpJOmoWuhqWmNTdwEh7gRDnFD7OIG2IVxqMZhuDF2YRxOxOEjQzOQeC3X/695@brJickZqQA "C (gcc) – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes ``` 2_y|:q^m ``` [Try it online!](https://tio.run/nexus/matl#@28UX1ljVRiX@/@/rgUA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/hvFF9ZY1UYl/vfJeS/rhGXriGXAZchlxGXMZcJAA). ### How it works Consider input `-8` as an example ``` 2_ % Push -2 % STACK: -2 y % Implicit input. Duplicate from below % STACK: -8, -2, -8 | % Absolute value % STACK: -8, -2, 8 : % Range % STACK: -8, -2, [1 2 3 4 5 6 7 8] q % Subtract 1, element-wise % STACK: -8, -2, [0 1 2 3 4 5 6 7] ^ % Power, element-wise % STACK: -8, [1 -2 4 -8 16 -32 64 -128] m % Ismember. Implicit display % STACK: 1 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 28 bytes ``` @(n)any((-2).^(0:abs(n))==n) ``` This defines an anonymous function. The approach is similar to that in my MATL answer. [Try it online!](https://tio.run/nexus/octave#@@@gkaeZmFepoaFrpKkXp2FglZhUDBTStLXN0/yfpmCrkJhXbM2VBpLWUQBShmDKAExC2BAJYzBpovkfAA "Octave – TIO Nexus") [Answer] # Regex (ECMAScript / Java), ~~38~~ ~~37~~ ~~34~~ 33 bytes ``` \b(?=(^|x))((x*)\3\3(?=\3$))*x\1$ ``` [Try it online!](https://tio.run/##TY89b8IwGIT/CrUQvG/SmARQVWEMUweGdmjHppUMmMStcSzbQMrHb0@ToVKXG@453em@xFH4jVM2JN6qrXT7ynzLn8ZxI0@9V1k81RbgzBejqMnXsOTwea0RAeoI80k@aZ180keM6jzrN9HojDRUb8EpUwBSr9VGwsN9MkVknqfsVCotATR3Umy1MhIQ77g5aI2XgmvqrVYBhpQOkakdgOEF1dIUocTF@HpV/kW8gOJWOC9XJkDxnn4g/gH5H5hFtsxmHcZQuupEVuYotNr2nDCFnPVIrNmucsDUnEum4hi7QVDzdEkSMiMEY1IT6qSVIsCzCCUVaw@q7aN7ETYlOMSLHwxsezZA9y9j9hB8cG2I3W5NMk6nj5R2@gs "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##bVNtT9swEP7Or7hFTLXb4iWwT5gIbdMmTRrbBB@bTnISpzE4TmY7NMD47d05zQZIRFHO9@Ln7p67XItbcXRd3uxU07XWwzXqTLVszuG5pfdKv2qzciMH9Bx0fa5VAYUWzsGFUAYeYLI5LzyK21aV0KCHXHmrzAaE3bjVmoKvbbt18HkoZOdVizcPAL4oLaFKjdyORxKxoi0lQ39E@ce@qqSV5aUUpbSQj2EvjeTfzUmtKOVTXrf0fFsHfEJcmmMPovymjCSUvklNrzVVFXFM/u6FdiR6N5/PI0ofXobuEQjxrwI8IIL/j4AA7xAhx7gb7hbpLDOzID1/3NsefwrvpTVg0@mE3TZdSOAoRzbyttVSGLhPK0SUHK4KYQy2rkzXe0ghdDvZyNWd87JhylAOU59jGKuF@y4Hj2WOFANMhGisHTH2QQYjphYn/2oNGt0hirlOK0@iLGP44iTwkgcTo/ur8bgLlnXCOokK0at4TZdgkledTEuz8fXZMZxDiIRTFMkaEYta2NV6mJoatQvha9aIgYwHkTtiYrp8UhJKF8mawwdrxZ1jldKaDMvZMEO4AcHT2dGMjx1XrQ1sYM2piTmYs9QkKBYLpATxiho5bTC1xXSjRsZdN/hLfMJK9jvGtlZ0ZEpWtN3dj@pSmI3EnOYsPo9Pk2e1YWWUBqIqIA2WZkrkP@zHPZ0G1SLrW6u8JGExKL9Pve3DjJ/cHc7BVyR66yJklPLH8ByEzdxlOTlPya8/A6WEDHOanWQnaMlODimdD1lyuAvrtztK4uP3jIXvXw "Java (JDK) – Try It Online") - Java Takes its input in unary, as an optional `-` sign followed by a string of `x` characters, the count of which represents the absolute value of the number. (As such, it is not bijective unary, as zero can be represented in two ways. The regex works with both.) Sets a flag for whether a negative sign is present. Operating on the absolute value, repeatedly divides by 4 (requiring that there is no remainder), and then asserts that the remaining number is 1 if there was no negative sign, or 2 if there was. ``` \b # Anchor on the border between {start or "-"} and "x"; in the # domain of this problem, it is actually equivalent to # (?<=^(?=x)|-|x$) - so it can anchor on the end instead of the # beginning, but that would result in a non-match. (?=(^|x)) # \1 = 1 if negative sign is present, 0 if not ( # loop the following: (x*)\3\3(?=\3$) # assert tail is divisible by 4; tail = tail / 4 )* # iterate as many times as possible (minimum 0) x # tail -= 1 \1 # tail -= \1 $ # assert tail==0 ``` ## Regex (ECMAScript), 36 bytes ``` ^(-(x*)(?=\2$))?((x*)\4\4(?=\4$))*x$ ``` [Try it online!](https://tio.run/##TY/NbsIwEIRfhVoIdpPGhCiqKozJqQcO5dAeSyu5YBK3xrFsAyk/z54mh0q9rDTzjWY1X@Io/MYpGxJv1Va6fW2@5U/ruJGnwYssnxoLcOaLSdR@QAJNhFDwdTZELKBX63yd907eOVEzbKPJGWmoX4NTpgSkXquNhIf7JEdknqfsVCktATR3Umy1MhIQ77g5aI2XkmvqrVYBxpSOkakdgOEl1dKUocJFdr0qvxIrUNwK5@XSBCjf0nfEPyD/A7OYFtNZjzFUrj6RpTkKrbYDJ0wpZwMSa7arHTA155KpOMb@Iah5WpCEzAjBmDSEOmmlCPAsQkXFpwfV9dG9CJsKHOLFj0a2Gxug3zdl9hB8cF2I3W5tkqX5I6X9/QU "JavaScript (SpiderMonkey) – Try It Online") This was the original version I posted; I'm keeping it here, as it's sufficiently different, yet close enough in length, to be interesting. If it sees a negative sign, it strips it and divides the number by 2 (requiring that there is no remainder). It then asserts that the remaining number is a power of 4. ``` ^ ( - # eat a leading negative sign (x*)(?=\2$) # assert tail is even; tail = tail / 2 )? # do the above optionally # Assert that tail is a power of 4 ( # loop the following: (x*)\4\4(?=\4$) # assert tail is divisible by 4; tail = tail / 4 )* # iterate as many times as possible (minimum 0) x$ # assert tail == 1; if this fails to match, the regex engine will # try backtracking the loops, but that cannot result in a match ``` # Regex (Perl / PCRE / Boost / Python / Ruby / .NET), 32 bytes ``` ^(-)?((x*)\3\3(?=\3$))*x(?(1)x)$ ``` [Try it online!](https://tio.run/##RU/LasMwEPyVJYhYm/iluL1UVuxAeu2ptyo1TolBoCau5IKKcH/dldNALsvO7OzObH8y@nH6/AFiOHh9@Wg1kIwHKMr97nW3HaG7GEqsyHm55ehBdQGh7406D7CQ5wUfodbC9loNNJKpTKPYfh/tELaaOGExw9PXrKvubB54fCIN8vmcDaatqXW5QV/rN3YQoeYHfrNWN0hUKa7j0K3X6FUHlEZJ5IKkzBFSiFwEDtqjDQwiiF/IiMnQE7tcXvNe44ZfGP@PTxQfx7Fpnl/2TTO90wQrSt0KZSELWglZEMSVoxVl6JBMU8LyzUOazvUP "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##XVBNa4NAEL3nVyyysDOJGk16KF3FS1sIlB7a3mK6GLtGwayLGhBCfrudDT11YYf5ePPezNjazklma8t4z1LmrT0WMtvrk@q1bYtSg1iHy0ypumhHVXZn27S6zyFHmX@sB@EzQb@ipDppBzCjNuMASr3u3l6UQp/FSJRELBdV1wNv0kjyNq0IPsDn1/PuHSVeWVMBb/fD2LfakIdBfEhTLzceEni4HKlCaT/ygxhdv55s2/1o8MLQ8wkviaDsLmZ0zcmGuvbEQDY6yAVjd2nzF3OTpPc6easVkjaD@87nYixr4L1P2CTKRCCehMCQtN05dDGCmIRfHAeqIz12dWM3qMu6c7NKRuvFkrmYcSNvpHz7dztAOX9DgBnAtMR8m28hS/MtR1xOkEGME/J5DjbRw2MYOvsL "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##bVLBkppAEL37Fb3uVugWMKKpHEC0Kp@QyiEpNRTiCFORgQIs2U3tr6/pGaJBN3NgmOnu916/nqQs3TRJzo9SJYfjTsB8WxR187ESqWjHWVkuBkkWVxCVqw2E8HX45XT6tZ0dfzw/f/@WfT5leP6JLi0R2xGtZ@sZLsP17Ilo1OISPWrp6Uz3NUMHRmUYlbYXDP4RS@atRJwvBo87sZdKQB63GDtbAsSYFrhlmph83mkgVcNhqZDg9wB4lSuuPgiFJbneJpwEcOSc2TRqoNAnXZDqn7rZ@T7nSpXyZXlsAlOfFKpuwDTv@6Z7qASWzs2V78skrgUFl9s6j5skg1MW/4XZFxWg5nq5cqWiOXA3aA6JVE5HS8FFul66RE3Y4bgpJJqEcRKxTCRyQHkOlEXN4S7C7uxwOB4PKbgiKI/DOukh7Pfo@0pfLv8DDLbJt2FK4DN7cKsmZzwzgW2NasIqzI9HPU7zNEZalxKn7rRSuT3dBJCLvBYN1jZLt1qLe8jZtlqHzXiuGFfHZKj0nOah8gKwbdm35ypKSW0CLEKYMKQ@GFU5uXqXTCH3gA@cR5pM6kdruVZwi8Qp/bFGtYirJEPs@UYfdLnNQBvHzNfh90D3mi5oLwRsrDYArbWyWMZL6AXvUrsnUBwbmM9B3sZf30m866LtddEld99KNMdKAVv6ena9yfTTeKy/b8n@EKf12T2YViPT6R8 "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##NY7basMwDEDf8xXC9EHKxcTNnpKafEiTQba5rYdnB9lj6ddndcdehBDnHLTe0y34brdfa@AE8R5rNvVnDH4A1iyE2F@xoRFxK2nqpg5HPXUHonLDERVtdNgf0Fn1jZoHsLotLoHBgfU5JmP6sL4vwGkn4@psQiGloALsBZzx6Oh07MFV2hWQRZ9FXvzVoPUJ3bmdqf7b1EyVokcru2xkNAu/35BrEI0o0Z9aqsQmyuUtoqcnmEnbw8q5QM@DVsP/Y@E7yR@2yWBMnJW9Ue3xRco8fwE "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##PU9La8MwDL7vV2imUCkjIo@dlppQ6K47jN2SNrTUTQ3GDY5Ls8v@emaXrQcJPul7SO56@J4dSPhUvZoGtuoGm/XXmp3aHyvQMqvgdtZGgZG98uMTgD6BadJ8K6VorajCwjQZc1psK1D2GBhhwuNgtMcl85L@NGyU7f0ZaVUEURMMgu6hOV0cWNAW4pD9pdOYZ8QciQ8YeHcvRLvKapGKNyHoRUwisbw/jATyB1wVGfo5Xj5c/XgPiJ/kATttPdj/zNhjdd37x6br5h2mVCNOCbVlW2It23JBlExYY04TLeY5zbPilTn2Xw "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##RY/RaoQwEEV/RWQgGW2Crn1aCW7pc79ALVg3WwNpIjGLsuK329hS@jJw5t65zB3tLN00SK13cKJ28lMu7fls5EwvZH@nDCtKlwSboiloJZoCEJOFVjTHBWEnl6f41X6NSstrjCU8RFberJNdP1DQkTIRKDPePa7QCdBsGrXyccMbHpfqRqHjvb0bz7SPTocnFdDVWbuFDApG1Mr49mdTgmFa/nF@cJriemQ4/tb5fpATJYwk9DD6KMOULCSpgzSEPi8fUxAQfy8euM5OeckGO/ktPJ2X/xwxY0N9rYyMwGzbtrM8Oz1zfsxv "PowerShell – Try It Online") - .NET Uses essentially the same algorithm as the 33 byte ECMAScript version, but in a more straightforward way, which never matches strings outside the problem's domain. ``` ^ (-)? # \1 = negative sign if it is present; unset otherwise ( # loop the following: (x*)\3\3(?=\3$) # assert tail is divisible by 4; tail = tail / 4 )* # iterate as many times as possible (minimum 0) x # tail = tail - 1 (?(1)x) # if \1 is set, then tail = tail - 1, else do nothing $ # assert tail == 0 ``` --- # Regex (ECMAScript or better), 26 bytes ``` ^((.*)\2\2(?=\2$))*(x|oo)$ ``` [Try it online!](https://tio.run/##TY9NTwIxFEX/Ck4IvDdIGSbEGGqHlQsWstClaFLhMfO0dJq2fIjw20dmYeLmbs7NvTmfeq/DyrOLw@B4TX5b2y/6bryydOg8U/l4dAAnVYzS5h1ApLjMlznM1DLvIqZwPNc1dpt0dEIR65fo2ZaAIhheEdzdDieIMqhMHio2BGCUJ702bAkQb5TdGYM/pTIiOMMR@kL0UfIGwKpSGLJlrLDIz2cOC70AVk77QHMboXzN3hD/AP0HthjPxtMWY6x8fUjmdq8Nrzte25KmnWRg5Kb2IPlBkeTBANtD4CKbJcdkmtQJCk@OdIQnHSuhPwLwdUxsdVxV4BF/Qq/nrqYRWrmxdLsYor@W5OXSDPNsci9Em78 "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##RU/LasMwEPyVJYhImzh@0UKJLNuB9NpTb1UqnBKDQI1dywUX1f11V3YDvQw7s4@ZbS@duZ/ev4B0HJxp3ioDJOKeiux4eD7kI9RNx4gVMc9yjg507Rm6ttPXHlbyuuIjlEbY1uieURnKkAb282x7v6WCXRIkePmY54p/NfY67olCPp@z3rTqSpOl6ErzkpyEx/jEb9b6RonOxNL21XaLTtfAmG/ncUEHuqcNRRigOluvIYL4gYh0ETpi1@sl7RLWf5Lwv/BE83EclXp8Oio1vTIWblCmMmWFkClB3LDhu2mQTNMuje8ewnDGXw "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVNtT9swEP7Or7hFTLVLMWm1TwQPbdMmTRrbBB/bTnITpzE4dmY7NMD47d05zQaVakWx78XP3T13vhX34vS2uNuqurEuwC3KTFk2zuC1pg1KH9Q5uZYdWo6adqVVDrkW3sOVUAaeYND5IAJu91YVUKOF3ASnzBqEW/v5kkKonN14@NzlsgnK4s0jgC9KSyi5kZv@SBKW20IytCc0@9iWpXSyuJaikA5Wvdu@kvy7OYglpdkQ109CtqkiPiGer7AGUXxTRhJK33DTak1VSTyTv1uhPUnOxuNxQunTvusOgZBwEOAJEcJ/BAQ4Q4QV@t1l/oSPFmYU95A973TPP0UI0hlwfDhhtXUTA3iaIRsra7UUBh55iYgyg5tcGIOlK9O0ATjEagcduXnwQdZMGZrBUGfvxirhv8suYJo9xQADIRpzR4ydk0GPocTBPl@CRnP0Yr7RKpBksWD4YSfwUgCTovmrCTgLjjXCeYkC0fN0SSdgpgeNTEuzDtXFDC4hesI5btMlIuaVcPNlNxTVS1ciVKwWHekPYuWJSenkRZhSuszgg3PiwbNSaU26iUnf8/Ry1I3OR3bUkwhQWhe5wIy5STMwF9xMcTs5QUKwY4bzlO6j4H1MCSPlFbJdY1IOE@kl0r8Cg4/lE@a4mz62caIhA0Rum4cf5bUwa4lI6at8KS6krgRSYyBTYEdi/Ec6tM5iHzZOBUniqNDskQfXxq6/mBvsTChJ8tYnyDHNnuM6irO6/UUIG9PFbDEjl3wxO6Z0TLo/1tLjbZzE7ek0nb1jLP7/Ag "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##bVLbjpswEH3nK6bZVbEDocBWfYCQSP2Eqg@tkhQRxwGrwVgYlOy2@@tNx6ZJSVo/@DbHZ86cMVNqVjJ2fhCSHfodh/m2aXT3ruUlPwWVUguHVUULuVptIINPk4/H4/ftU//1@fnL5@rDsSLnb4QEU7qO1zFZZuv4kdIpOf1sGvp4pvfoiQ9TleXKi1Lnb0qBGVte1AvnYcf3QnKoixMp/C0FQgq6IFu6xDXBlTpCdhgWklD44QAOtcLXBy6JorNok4Up9Ih5ivMOGnMyD0qz0d0uSRArZImXqu9S@541Undgy04SWze0nCj/5ipJBCs0p@nlVtdFxyo4VsUfmn3TAjG5Xq65St4dsBpiD0xIf0hL04t0M8wTGaK3RdcIYgEBy1EmodQHGfmgGo3hIYLu7MgkCCY0vTLICMMG9CYb15gk0lwu/0MMnsV7EFNIMHt6q6ZGPtuBrSYyRBV2E9FRTvsppkaX5MfhtJK1F21SqHmteUc0ig8XWbh0T27iNi4ea7RPI8w06cp09U1k0nRrnskoBc8TY5OstD3isiykowzIPfDeIk0RwlhqdNd0ZlZxD0K6cYdzzYuWVYSMLKRvUa7Y@LbNPn4Lei/qwvRCAf01PhB3LV0s9CWL0n@gw09o@g7mcxC38VfndjfMLe/6VgIa9nqeRWH8PgjM/IvtD0Wpz7ODrSG3JfwG "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##NY5BTsMwEEX3OcXI6mImTa04sErqcpAmSAFcajTY0diIVuLuoS5iM/r6X@9plms@x/Cw@s8lSoZ0TY245iPFMIBYUUqtz4i6prEbO3yyY7chqvHyEyNt1tt8NP3OTAN421anKMDgQ9HolN986Ctgyzot7DMqrRVV4E/ALiDTvuuBt5YrKGAooMzh3aEPGfnYTtT8JTPR1tDNVVhxOrlZXs8oDaC6qFKGQwuOkwMVFdXzS8JAd6CMvodFionuhTXD/4PxK@tv8dlhylKQdWfa7lHrcn8B "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##PU/BasMwDL3vKzRTqB2IcMxO9bxS6K47jN2SzrTUTQ3GDo5LMxj79cwuWw968KT3nqR4OXzNERS8m95MA3pzhe3mY4PR7I8SrOISrmfrDDjVmzQ@ANgTuLZudkqRzhOZB67liLXYSTD@mBW5g@PgbKJLxCX786Azvk9nyp5FNrU5IPvunlOI4MF6KE1MQVvacIZYhHeadbcsSv0LX5OJrEggrPK4P4wM1A9EWcb2sZw9XNJ4Sy9vNJlH6xP4/4UFS2n9@rbVev6kFCvWiU7QterEgrGKTt8hsMU81w0XT4gFfwE "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##XVBNa8MwDL33V4hgiNWmaRJ2GHOzXLZBYeyw7VZ3Js2cJpDaJkmh0PW3Z3LZaQYLfTy9J8k1bloXrnHAesghWAUQg@v1QfXadWWlebiK54VSTdmNqrJH13a6l1yikO@rIYwgpF9TUh20B5hRm3HgSr1sXp@VwghSJEoiFrPa9py1eSJYl9cEH/jH59PmDQVeoK0567bD2HfakIfLdJfngTQBEng47alC6SiJlin6fn12nf3WPIjjICK8IILKnszom9cZdW2JgWyyEzOAm7T5i5lZ57c6eYsFkjbw287HcqwazvqI1PwBdEl05jEpwnP4ENowKvcDJZAeXPzELeqqsX5MAbRZKsDHwIy4kuj139k4iumL83iOMpMZL3KZMcQ5P/9Yi2yalllydx/H3v4C "PHP – Try It Online") - PCRE2 [Try it online!](https://tio.run/##RZDRaoQwFER/RcKFJNoElT6tSLf0uV@gFqy9uwbSRJIsytp8u9WW0pcLM5w7MDPZGZ0fUesNXN04vOLSnU4GZ3am2xtjMuVt2ZbsqW5L4Dxly5e1HDZ6fiAv9nNSGj8Ir@Be59XFOuyHkYFOlElAmekW@Ap9DVr4SatAWtlKUqkLg14O9maC0CEpDyaroW/yLu4ZDEzdKBO6H6cCIzT@6eLQWcbXI8PJ1z4MI3pGgB2GEdeQ85UuNKL2uFJLIydps2Pj3ur53e8M57/fd77OTgUUo/Uh7gWK6l8nwth9BK0MJmBijJso8vJRyuN@Aw "PowerShell – Try It Online") - .NET Takes its input in bijective signed unary. A nonnegative number is a string of `x` characters, and a nonpositive number is a string of `o` characters. The the length of the string is the absolute value of the number. ``` ^ # tail = N = input number ( # Loop the following: (.*)\2\2(?=\2$) # Assert tail is divisible by 4; tail = tail / 4; # use "." so that either "x" or "o" can be matched, as # long as all characters are identical. )* # Iterate as many times as possible (minimum 0). (x|oo)$ # Assert tail == 1 or tail == -2 ``` [Answer] **HP 28s 36 bytes** ``` WHILE DUP ABS 1 > REPEAT 2 NEG / END 1 == ``` [Answer] # PHP, 41 Bytes ``` for(;$argn%-2==0;)$argn/=-2;echo$argn==1; ``` # PHP, 52 Bytes ``` echo($l=log(abs($argn),2))==($i=$l^0)&&$argn>0^$i%2; ``` # PHP, 64 Bytes Working with a Regex ``` echo preg_match("#^".($argn>0?1:"1+0")."(00)*$#",decbin($argn)); ``` [Answer] ## JavaScript (ES6), 21 bytes A recursive function that returns `0` or `true`. ``` f=n=>n==1||n&&f(n/-2) ``` ### How it works This doesn't include any explicit test -- like `n` being odd or `abs(n)` being less than one -- to stop the recursion early when the input is *not* an exact power of -2. We exit only when `n` is exactly equal to either `1` or `0`. This does work however because any IEEE-754 float will eventually be rounded to `0` when divided by 2 (or -2) enough times, because of [arithmetic underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow). ### Test cases ``` f=n=>n==1||n&&f(n/-2) console.log(f(-2)); console.log(f(-1)); console.log(f(0)); console.log(f(1)); console.log(f(2)); console.log(f(3)); console.log(f(4)); ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 33 bytes ``` f(n){return n%2?n==1:n&&f(n/-2);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@mkadZXZRaUlqUp5CnamSfZ2traJWnpgYU19c10rSu/Z@bmJmnoclVzaWgUFCUmVeSpqGkmhKTp6STpqFroalpjU3cBIe4EQ5xQ@ziBtiFcajGYbgxdmEcTsThI0MzkHgt1/@vefm6yYnJGakA "C (gcc) – TIO Nexus") [Answer] # [Python](https://docs.python.org/2/), 24 bytes ``` lambda n:n*n&n*n-1<n%3%2 ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKk8rTw2IdQ1t8lSNVY3@FxRl5pUoROcppOUXKeQpZOYpFCXmpadq6BoaGBjogAhNhcw0hTSNPM3Y/wA "Python 2 – Try It Online") The bit trick `k&k-1==0` checks whether `k` is a power of 2 (or `k==0`). Checking this for `k=n*n` as `n*n&n*n-1==0` tells us whether `abs(n)` is a power of 2. To further see if `n` is a power of -2, we need only check that `n%3==1`. This works because mod 3, the value -2 is equal to 1, so its powers are 1. In contrast, their negations are 2 mod 3, and of course 0 gives 0 mod 3. We combine the checks `n*n&n*n-1==0` and `n%3==1` into a single expression. The first can be written with `<1` for `==0`, since it's never negative. The `n%3==1` is equivalent to `n%3%2`, giving 0 or 1. So, we can combine them as `n*n&n*n-1<n%3%2`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 4 bytes *Ties [emanresu A's Vyxal answer](https://codegolf.stackexchange.com/a/256288) for #1.* ``` 2(вO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fSOPCJv///3WNAQ "05AB1E – Try It Online") ``` 2(вO # full program O # push sum of... в # list of base-10 values of base... ( # negative... 2 # literal.... в # digits of... # implicit input # implicit output ``` [Answer] # Python 3, 34 bytes ``` lambda n:n==(-2)**~-n.bit_length() ``` [Answer] # Java 7, 55 bytes ``` boolean c(int n){return n==0?0>1:n%-2==0?c(n/-2):n==1;} ``` **Explanation:** ``` boolean c(int n){ // Method with integer parameter and boolean return-type return n==0 ? // If n is zero: 0>1//false // Return false : n%-2==0 ? // Else-if n mod -2 is zero: c(n/-2) // Recursive call for the input divided by -2 : // Else: n==1; // Return if n is one } // End of method ``` **Test code:** [Try it here.](https://tio.run/nexus/java-openjdk#LY5BCoMwEEX3nuJTKCSIVqUrbdoTdOWydBFTWwJxIiYWinh2G8XF8Abmz5tRRjqH@xQBzkuvFZbGWtNKgmKaPIhPQ@vHgUBCZLfsmpd0TIq1V4xOScHLMMireQH6sTHBsIu@Vr/QSU2s9oOmz@MJyddDwNsOm1xDICmqwIvAOTCO9wRQ/5xvu9SOPu3DujfENGIcShwCwnOcV1t0jtaalz8) ``` class M{ static boolean c(int n){return n==0?0>1:n%-2==0?c(n/-2):n==1;} public static void main(String[] a){ for(int i = -2; i <= 4; i++){ System.out.println(i + ": " + c(i)); } } } ``` **Output:** ``` -2: true -1: false 0: false 1: true 2: false 3: false 4: true ``` [Answer] # [Perl 6](https://perl6.org), 21 bytes ``` {$_==(-2)**(.lsb//0)} ``` [Try it](https://tio.run/nexus/perl6#VY1LasMwFEXnWsUjmEpKkPyJm7YxbhfSFGM7CgT8KZZTMMYF7aikX0@9FG3EscAdZHTh3fvOOUkBbxueBihv4CYt9wLCsbWiMCTMo8sl4ZlMbNuh3XgoK8iOhZCE8jx@Je2Kp2WeEBsz/LTbr2z67Lx0FFoEMMGsSshTVkMIhkqsiAZTIeMGFla0q@d6Cy02JgzvwHOZ8LqKC0mw43pr/3Zzd/@AIXwErNXH0A/n4VOrL62@tfrR6lerP616TOF4@Nd1iwB1I/MR88xfI@QWDH/oEXPNpSiRM6d7tZgMyJub9Zz@NeN8AQ "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 $_ # is the input == # equal to (-2)**( .lsb // 0 ) # -2 to the power of the least significant bit of the input } ``` Note that [`0.lsb`](https://docs.perl6.org/routine/lsb) returns [`Nil`](https://docs.perl6.org/type/Nil) which produces a warning when used as a number, so the defined or operator [`//`](https://docs.perl6.org/routine/$SOLIDUS$SOLIDUS) is used. (Think of [`//`](https://docs.perl6.org/routine/$SOLIDUS$SOLIDUS) as [`||`](https://docs.perl6.org/routine/$VERTICAL_LINE$VERTICAL_LINE) with a different slant) A method call with no invocant where a term is expected is implicitly called on [`$_`](https://docs.perl6.org/syntax/$DOLLAR_SIGN_). ([`.lsb`](https://docs.perl6.org/routine/lsb)) [Also works with](https://tio.run/nexus/perl6#VY1dasJAFIXfZxUXCZ0ZJZMfrbaGaReiEmIcQTCJZGIhhBRmR8XW1rxmKbORmIH0wacD95z7fWcp4GPO4gAlJTzF2U4A7yor5JzYPh2PCUvk1nFcWnf7LIfjIRWSUJZEJ1JNWJwlW@JgG7@vdxOHrtxNTaFCAD3MyoU8HwvgYKjECmnQFzIqYWSF62Kol1BhY8LwCUbFijxKJcGu509nz/PFyysG/gZYq6@2aS/tt1Y/Wl21@tXqT6ubVg2mcNj/6@pRgOrO9s1TKeQSDLxtkO2ZS5ohd0jvYdHjkT800yFnj4zLHQ "Perl 6 – TIO Nexus") [`.msb`](https://docs.perl6.org/routine/msb). [Answer] # R, 22 bytes Takes input from stdin, returns `TRUE` or `FALSE` accordingly. ``` scan()%in%(-2)^(0:1e4) ``` I'm not 100% sure that this is a valid answer, as it only works for integers up to R's size limit, and if the integers were unbounded it wouldn't work. However, the rules state: > > 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. > > > In a hypothetical version of R which *does* allow unbounded integers, then we could use the following code, for the same byte count: ``` scan()%in%(-2)^(0:Inf) ``` Of course, in real R, the above code just gives `Error in 0:Inf : result would be too long a vector`. [Answer] # Haskell, 24 23 bytes ``` f 0=0 f 1=1 f n=f(-n/2) ``` Defines a function `f` which returns `1` for powers of -2 and `0` otherwise. A golfed version of my first submission to the [other challenge](https://codegolf.stackexchange.com/a/115641/67875). [Answer] # [Julia 0.5](http://julialang.org/), 20 bytes ``` !n=n∈(-2).^(0:n^2) ``` [Try it online!](https://tio.run/nexus/julia5#@6@YZ5v3qKNDQ9dIUy9Ow8AqL85I839afpFCnkJmnoKuqaGRFRBzcWamKSjmcXFyOhQUZeaVpGkoqZqkxOQp6SjkaXJxpualcAHxfwA "Julia 0.5 – TIO Nexus") [Answer] # Pyth, 7 bytes ``` !tsjQ_2 ``` [Test suite](http://pyth.herokuapp.com/?code=%21tsjQ_2&input=-7&test_suite=1&test_suite_input=-2%0A-1%0A0%0A1%0A2%0A3%0A4%0A5%0A6&debug=0) Explanation: ``` _2 # -2 jQ # Cast input to that base # Iff input is a power of -2, then jQ_2 returns something of the form [1]+[0]*n # where n is the power of -2 # This is also the only situation in which the sum of that is 1 !ts # so we check for that: is the (s)um equal to 1 (or, equivalently, "!(sum - 1)" ) ``` [Answer] # [Risky](https://github.com/Radvylf/risky), 14 bytes ``` __-+_-2{[?+_0:__0+_0+__?+_0 ``` [Try it online!](https://radvylf.github.io/risky?p=WyJfXy0rXy0ye1s_K18wOl9fMCtfMCtfXz8rXzAiLCJbLTRdIiwwXQ) **Explanation:** * `__-+_-`: `-2`, written as `-1 + -1` with padding * `2`: Power * `{[?+_0`: `log_2(abs(input))`, with `+_0` as padding * `:`: Equals * `__0+_0+__?+_0`: Input (`?`), with padding So basically, `-2 ** log_2(abs(input)) == input` [Answer] # x86-32 machine code, ~~20 18~~ 16 bytes -2 bytes thanks to @xiver77 -2 bytes by removing an unnecessary jump (This submission was originally 19 bytes, but I adjusted it to 20 since I forgot to add `ret`). ``` 00000000: f8a9 ffff 7f00 7507 c1f8 1730 e0d1 f8c3 ......u....0.... ``` [Try it online!](https://tio.run/##dVJbbsIwEPz3KbauKjkSqSBBKqKAeoZeIDKOA64cG8UGQiuu3nTjkEBf@@FoZ2dfsxG7XbwRorlXRuh9LmGhrPOV5OWKXLG18k76W0RoVSL4DXI@VwZZZG2tBuWM3OzsMWGFttxDHcEHAbQ9ktIk83B6JgHIMu7KLMPvwWrulZbosFfKQrS10h5A8noED5Omx4QWQ9xL5zvCuH4qWhtCb@YdpMnJADheddQkHbDaVsD1CPj2StsGWvAxfx76RjT4c6DLFyEEBXaKeqRCrx48TKXRZb9K@n1lgLWyRLj0mZCDVXmY@qc4QboTLG/kq/s6qO98Luzew2IBdftQiFdAL2FVDOP8YtOTdMgLy2gn/yEZS/9qFRzUQIfR8XpQcmVYP3K3Ae@qH7d4PmB3XQFlHqUtWNRTr6WVgdWqT@pPyHjUAedb3cbYtolnJJ6SOCHxhIzJhCQkJVMy@xSF5hvXxGWa4IP/0RLnk/oL "C++ (gcc) – Try It Online") Expects a single precision float in `eax`. Output is in the carry flag. It takes advantage of some fundamental properties of floats, for some power of -2 `n`: * `abs(n)` is a power of 2, therefore `n`'s mantissa must be 0. * `n` is positive for odd numbered exponents, and negative for even exponents. In other words, `sign ^ exponent[0] = 1` where `exponent[0]` is the least significant bit of the exponent. NASM source: ``` [BITS 32] isnegpow2: ; Clear carry clc ; Check if mantissa is non-zero test eax, 0x7fffff ; If it is, then abs(eax) is not a ; power of 2, so eax cannot be a power ; of -2 jnz .end ; Shift away the mantissa sar eax, 23 ; Now ah contains the sign, ; and al contains the exponent. ; For powers of -2, sign ^ exponent[0] = 1 xor al, ah ; Check lsb by shifting it to the carry flag ; If it's 1, then eax is a power of -2, so the ; carry will be set sar eax, 1 .end: ret ``` [Answer] # Javascript(ES7), 45 bytes ``` x=>-1**Math.log2(Math.abs(x))*Math.abs(x)==x ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org/pldoc/doc/home/jan/src/plweb/index.html), 44 bytes ``` p(X):-X=1;X\=0,X mod 2=:=0,Z is X/(-2),p(Z). ``` [Online interpreter](http://swish.swi-prolog.org/p/naQGHdxk.pl) ]
[Question] [ [Identicons](https://en.wikipedia.org/wiki/Identicon) are small images of geometric patterns that represent the [hash value](https://en.wikipedia.org/wiki/MD5) of a string. Stack Exchange [uses](https://meta.stackexchange.com/questions/17443/how-is-the-default-user-avatar-generated) the identicons from [Gravatar](https://en.gravatar.com/site/implement/images/) as each user's default avatar image. In this challenge, we will use the Gravatar identicons as well to generate some text to golf. # Challenge This stack snippet (a minified version of [this JSFiddle](https://web.archive.org/web/20150507221655/https://jsfiddle.net/CalvinsHobbies/je0apehk/)) lets you type in a string and gives back a 100×100 pixel black and white version of that string's identicon, along with a text version where `1` is for black and `0` is for white: ``` <!-- Click "Run code snippet" --> <div style='text-align:center;'> <input id='str' type='text' size='32' value='Python'> <button type='button' onclick='go()'>Go</button><br><br><input id='type1' name='type' type='radio' value='identicon' checked> <label for='type1'>Identicon</label> <input id='type2' name='type' type='radio' value='monsterid'> <label for='type2'>Monster</label> <input id='type3' name='type' type='radio' value='wavatar'> <label for='type3'>Wavatar</label> <input id='type4' name='type' type='radio' value='retro'> <label for='type4'>Retro</label> <br><br><a id='origLink'>original</a><br><canvas id='original' style='border:1px solid gray;'> Your browser does not support the canvas tag. </canvas> <br><br>binary<br><canvas id='binary' style='border:1px solid gray;'> </canvas> <br><br>text</br> <textarea id='text' style='background-color:#eee' readonly></textarea> <br><br>your text</br> <textarea id='userText'></textarea><br><button type='button' onclick='markDiffs()'>Mark Differences With X</button><br><br><span id='diffCount'></span> <br><br><small>(this snippet has only been tested in Chrome and Firefox)</small></div><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>function rgbDist(t,n){return Math.sqrt((Math.pow((t[0]-n[0])/255,2)+Math.pow((t[1]-n[1])/255,2)+Math.pow((t[2]-n[2])/255,2))/3)}function toBinImg(t,n){for(var r=0;r<t.data.length;r+=4){var e=rgbDist([t.data[r],t.data[r+1],t.data[r+2]],[255,255,255])<n;t.data[r]=t.data[r+1]=t.data[r+2]=e?255:0}}function getText(t){for(var n="",r=0,e=0;SIZE>e;e++){for(var o=0;SIZE>o;o++)n+=t.data[r]?"0":"1",r+=4;e!=SIZE-1&&(n+="\n")}return n}function markDiffs(){var t=0,n=$("#text").val().split("\n"),r=$("#userText").val(),e=new RegExp("(?:[01]{"+SIZE+"}\n){"+(SIZE-1)+"}(?:[01]{"+SIZE+"})\n?");if(!r.match(e))return void $("#diffCount").text("bad input");r=r.split("\n");for(var o="",a=0;SIZE>a;a++){for(var i=0;SIZE>i;i++)r[a][i]!==n[a][i]?(o+="X",t++):o+=r[a][i];o+="\n"}r[r.length-1].length&&(o=o.substring(0,o.length-1)),$("#diffCount").text(t+" differences found"),$("#userText").val(o)}function go(){var t=new Image;t.crossOrigin="anonymous",t.src="https://www.gravatar.com/avatar/"+md5($("#str").val())+"?&s="+SIZE+"&d="+$("input:radio[name=type]:checked").val(),$("#origLink").attr("href",t.src),t.onload=function(){ctxOrig.drawImage(t,0,0);var n=ctxOrig.getImageData(0,0,SIZE,SIZE);toBinImg(n,.05),$("#text").val(getText(n)),ctxBin.putImageData(n,0,0)}}var SIZE=100;$("#str").keyup(function(t){13==t.keyCode&&go()}),$("input[name=type]:radio").change(go),$(function(){var t=$("#original"),n=$("#binary");t.prop({width:SIZE,height:SIZE}),n.prop({width:SIZE,height:SIZE}),$("#text").prop({rows:SIZE+5,cols:SIZE+5}),$("#userText").prop({rows:SIZE+5,cols:SIZE+5}),ctxOrig=t[0].getContext("2d"),ctxBin=n[0].getContext("2d"),go()}),!function(t){"use strict";function n(t,n){var r=(65535&t)+(65535&n),e=(t>>16)+(n>>16)+(r>>16);return e<<16|65535&r}function r(t,n){return t<<n|t>>>32-n}function e(t,e,o,a,i,u){return n(r(n(n(e,t),n(a,u)),i),o)}function o(t,n,r,o,a,i,u){return e(n&r|~n&o,t,n,a,i,u)}function a(t,n,r,o,a,i,u){return e(n&o|r&~o,t,n,a,i,u)}function i(t,n,r,o,a,i,u){return e(n^r^o,t,n,a,i,u)}function u(t,n,r,o,a,i,u){return e(r^(n|~o),t,n,a,i,u)}function c(t,r){t[r>>5]|=128<<r%32,t[(r+64>>>9<<4)+14]=r;var e,c,f,g,d,h=1732584193,s=-271733879,v=-1732584194,I=271733878;for(e=0;e<t.length;e+=16)c=h,f=s,g=v,d=I,h=o(h,s,v,I,t[e],7,-680876936),I=o(I,h,s,v,t[e+1],12,-389564586),v=o(v,I,h,s,t[e+2],17,606105819),s=o(s,v,I,h,t[e+3],22,-1044525330),h=o(h,s,v,I,t[e+4],7,-176418897),I=o(I,h,s,v,t[e+5],12,1200080426),v=o(v,I,h,s,t[e+6],17,-1473231341),s=o(s,v,I,h,t[e+7],22,-45705983),h=o(h,s,v,I,t[e+8],7,1770035416),I=o(I,h,s,v,t[e+9],12,-1958414417),v=o(v,I,h,s,t[e+10],17,-42063),s=o(s,v,I,h,t[e+11],22,-1990404162),h=o(h,s,v,I,t[e+12],7,1804603682),I=o(I,h,s,v,t[e+13],12,-40341101),v=o(v,I,h,s,t[e+14],17,-1502002290),s=o(s,v,I,h,t[e+15],22,1236535329),h=a(h,s,v,I,t[e+1],5,-165796510),I=a(I,h,s,v,t[e+6],9,-1069501632),v=a(v,I,h,s,t[e+11],14,643717713),s=a(s,v,I,h,t[e],20,-373897302),h=a(h,s,v,I,t[e+5],5,-701558691),I=a(I,h,s,v,t[e+10],9,38016083),v=a(v,I,h,s,t[e+15],14,-660478335),s=a(s,v,I,h,t[e+4],20,-405537848),h=a(h,s,v,I,t[e+9],5,568446438),I=a(I,h,s,v,t[e+14],9,-1019803690),v=a(v,I,h,s,t[e+3],14,-187363961),s=a(s,v,I,h,t[e+8],20,1163531501),h=a(h,s,v,I,t[e+13],5,-1444681467),I=a(I,h,s,v,t[e+2],9,-51403784),v=a(v,I,h,s,t[e+7],14,1735328473),s=a(s,v,I,h,t[e+12],20,-1926607734),h=i(h,s,v,I,t[e+5],4,-378558),I=i(I,h,s,v,t[e+8],11,-2022574463),v=i(v,I,h,s,t[e+11],16,1839030562),s=i(s,v,I,h,t[e+14],23,-35309556),h=i(h,s,v,I,t[e+1],4,-1530992060),I=i(I,h,s,v,t[e+4],11,1272893353),v=i(v,I,h,s,t[e+7],16,-155497632),s=i(s,v,I,h,t[e+10],23,-1094730640),h=i(h,s,v,I,t[e+13],4,681279174),I=i(I,h,s,v,t[e],11,-358537222),v=i(v,I,h,s,t[e+3],16,-722521979),s=i(s,v,I,h,t[e+6],23,76029189),h=i(h,s,v,I,t[e+9],4,-640364487),I=i(I,h,s,v,t[e+12],11,-421815835),v=i(v,I,h,s,t[e+15],16,530742520),s=i(s,v,I,h,t[e+2],23,-995338651),h=u(h,s,v,I,t[e],6,-198630844),I=u(I,h,s,v,t[e+7],10,1126891415),v=u(v,I,h,s,t[e+14],15,-1416354905),s=u(s,v,I,h,t[e+5],21,-57434055),h=u(h,s,v,I,t[e+12],6,1700485571),I=u(I,h,s,v,t[e+3],10,-1894986606),v=u(v,I,h,s,t[e+10],15,-1051523),s=u(s,v,I,h,t[e+1],21,-2054922799),h=u(h,s,v,I,t[e+8],6,1873313359),I=u(I,h,s,v,t[e+15],10,-30611744),v=u(v,I,h,s,t[e+6],15,-1560198380),s=u(s,v,I,h,t[e+13],21,1309151649),h=u(h,s,v,I,t[e+4],6,-145523070),I=u(I,h,s,v,t[e+11],10,-1120210379),v=u(v,I,h,s,t[e+2],15,718787259),s=u(s,v,I,h,t[e+9],21,-343485551),h=n(h,c),s=n(s,f),v=n(v,g),I=n(I,d);return[h,s,v,I]}function f(t){var n,r="";for(n=0;n<32*t.length;n+=8)r+=String.fromCharCode(t[n>>5]>>>n%32&255);return r}function g(t){var n,r=[];for(r[(t.length>>2)-1]=void 0,n=0;n<r.length;n+=1)r[n]=0;for(n=0;n<8*t.length;n+=8)r[n>>5]|=(255&t.charCodeAt(n/8))<<n%32;return r}function d(t){return f(c(g(t),8*t.length))}function h(t,n){var r,e,o=g(t),a=[],i=[];for(a[15]=i[15]=void 0,o.length>16&&(o=c(o,8*t.length)),r=0;16>r;r+=1)a[r]=909522486^o[r],i[r]=1549556828^o[r];return e=c(a.concat(g(n)),512+8*n.length),f(c(i.concat(e),640))}function s(t){var n,r,e="0123456789abcdef",o="";for(r=0;r<t.length;r+=1)n=t.charCodeAt(r),o+=e.charAt(n>>>4&15)+e.charAt(15&n);return o}function v(t){return unescape(encodeURIComponent(t))}function I(t){return d(v(t))}function l(t){return s(I(t))}function p(t,n){return h(v(t),v(n))}function E(t,n){return s(p(t,n))}function S(t,n,r){return n?r?p(n,t):E(n,t):r?I(t):l(t)}"function"==typeof define&&define.amd?define(function(){return S}):t.md5=S}(this);//thanks https://github.com/blueimp/JavaScript-MD5/blob/master/js/md5.min.js</script> ``` (It also lets you load the Monster, Wavatar, and Retro Gravatar styles, but those are just for fun and aren't meant to be used for this challenge. [Unicornicons](https://meta.stackexchange.com/questions/37328/my-god-its-full-of-unicorns) are unfortunately missing due to [XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) constraints. :/ ) Your task is to write a program that outputs the 100×100 character text block of `0`'s and `1`'s that is generated when you put your programming language's name into the snippet input box. For example, if your submission is written in [Python](https://www.python.org/), you would type `Python` into the stack snippet and see that ![Python identicon](https://i.stack.imgur.com/HNQMh.png) is the identicon for Python, and ![binary Python identicon](https://i.stack.imgur.com/saFGU.png) is the black and white (binary) version, and ``` 0000000000000000000000011111111111111111111111111100000000000000000000000010000000000000000000000000 0000000000000000000001111011111111111111111111111100000000000000000000011110000000000000000000000000 0000000000000000000111111011111111111111111111111100000000000000000001111110000000000000000000000000 0000000000000000011111111011111111111111111111111100000000000000000111111110000000000000000000000000 0000000000000001111111111001111111111111111111111100000000000000001111111110000000000000000000000000 0000000000000111111111111001111111111111111111111100000000000000111111111110000000000000000000000000 0000000000001111111111111000111111111111111111111100000000000111111111111110000000000000000000000000 0000000000000011111111111000111111111111111111111100000000011111111111111110000000000000000000000000 0000000000000000111111111000011111111111111111111100000001111111111111111110000000000000000000000000 0000000000000000001111111000001111111111111111111100000011111111111111111110000000000000000000000000 0000000000000000000011111000001111111111111111111100001111111111111111111110000000000000000000000000 0000000000000000000000111000000111111111111111111101111111111111111111111110000000000000000000000000 0000000000000000000000001000000111111111111111111111111111111111111111111110000001000000000001000000 0000000000000000000000111000000111111111111111111111111111111111111111111110000011000000000001100000 0000000000000000000011111000000011111111111111111111111111111111111111111110000011100000000011100000 0000000000000000001111111000000011111111111111111111111111111111111111111110000111100000000011110000 0000000000000000111111111000000001111111111111111111111111111111111111111110000111110000000111110000 0000000000000011111111111000000001111111111111111111111111111111111111111110001111110000000111111000 0000000000001111111111111000000000111111111111111111111111111111111111111110001111111000001111111000 0000000000000111111111111000000000011111111111111111111111111111111111111110011111111000001111111100 0000000000000001111111111000000000011111111111111111111111111111111111111110011111111100011111111100 0000000000000000011111111000000000001111111111111111111111111111111111111110111111111100011111111110 0000000000000000000111111000000000001111111111111111111111111111111111111110111111111110111111111110 0000000000000000000001111000000000001111111111111111111111111111111111111111111111111110111111111111 0000000000000000000000011000000000000111111111111111111111111111111111111111111111111111111111111111 1111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000001 0111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000001111 0111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000111111 0111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000011111111 0011111111111111111111111000000000000000000000000000000000000000000000000000000000000000000111111111 0011111111111111111111111000000000000000000000000000000000000000000000000000000000000000011111111111 0001111111111111111111111000000000000000000000000000000000000000000000000000000000000011111111111111 0001111111111111111111111000000000000000000000000000000000000000000000000000000000001111111111111111 0000111111111111111111111000000000000000000000000000000000000000000000000000000000111111111111111111 0000011111111111111111111000000000000000000000000000000000000000000000000000000001111111111111111111 0000011111111111111111111000000000000000000000000000000000000000000000000000000111111111111111111111 0000001111111111111111111000000000000000000000000000000000000000000000000000111111111111111111111111 0000001111111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000001111111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000111111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000111111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000011111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000011111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000001111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000111111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000011111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000011111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000011111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 0000000000001111111111111000000000000000000000000000000000000000000000000001111111111111111111111111 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111000000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111100000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111100000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111110000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111110000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111000000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111100000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111100000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111110000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111110000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111111000000 1111111111111111111111111000000000000000000000000000000000000000000000000001111111111111111111000000 1111111111111111111111110000000000000000000000000000000000000000000000000001111111111111111111100000 1111111111111111111111000000000000000000000000000000000000000000000000000001111111111111111111100000 1111111111111111111100000000000000000000000000000000000000000000000000000001111111111111111111110000 1111111111111111110000000000000000000000000000000000000000000000000000000001111111111111111111110000 1111111111111111000000000000000000000000000000000000000000000000000000000001111111111111111111111000 1111111111111100000000000000000000000000000000000000000000000000000000000001111111111111111111111000 1111111111110000000000000000000000000000000000000000000000000000000000000001111111111111111111111100 1111111111000000000000000000000000000000000000000000000000000000000000000001111111111111111111111100 1111111100000000000000000000000000000000000000000000000000000000000000000001111111111111111111111110 1111110000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111110 1111000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111 1100000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111 1111111111111111111111111111111111111111111111111111111111111110000000000001100000000000000000000000 1111111111111111111111111111111111111111111111111111111111111111000000000001111000000000000000000000 0111111111110111111111111111111111111111111111111111111111111111000000000001111110000000000000000000 0111111111110011111111110111111111111111111111111111111111111111100000000001111111100000000000000000 0011111111100011111111110111111111111111111111111111111111111111100000000001111111111000000000000000 0011111111000001111111100111111111111111111111111111111111111111110000000001111111111110000000000000 0001111111000001111111100111111111111111111111111111111111111111110000000001111111111111000000000000 0001111111000000111111000111111111111111111111111111111111111111111000000001111111111100000000000000 0000111110000000111111000111111111111111111111111111111111111111111000000001111111110000000000000000 0000111110000000011110000111111111111111111111111111111111111111111100000001111111000000000000000000 0000011100000000011100000111111111111111111111111111111111111111111100000001111100000000000000000000 0000011100000000001100000111111111111111111111111111111111111111111110000001110000000000000000000000 0000001000000000001100000111111111111111111111111111111111111111111110000001000000000000000000000000 0000000000000000000000000111111111111111111111111011111111111111111111000001110000000000000000000000 0000000000000000000000000111111111111111111111100011111111111111111111000001111100000000000000000000 0000000000000000000000000111111111111111111110000011111111111111111111100001111111000000000000000000 0000000000000000000000000111111111111111111000000011111111111111111111100001111111110000000000000000 0000000000000000000000000111111111111111100000000011111111111111111111110001111111111100000000000000 0000000000000000000000000111111111111110000000000011111111111111111111110001111111111111000000000000 0000000000000000000000000111111111111000000000000011111111111111111111111001111111111110000000000000 0000000000000000000000000111111111100000000000000011111111111111111111111001111111111000000000000000 0000000000000000000000000111111110000000000000000011111111111111111111111101111111100000000000000000 0000000000000000000000000111111000000000000000000011111111111111111111111101111110000000000000000000 0000000000000000000000000111100000000000000000000011111111111111111111111111111000000000000000000000 0000000000000000000000000110000000000000000000000011111111111111111111111111100000000000000000000000 ``` is the corresponding textual output that your Python program must produce. However, since identicons can have a lot of awkward angles and their rasterization as a black and white image can leave [jaggies](https://en.wikipedia.org/wiki/Jaggies), **your output is allowed to have up to 300 `0`'s or `1`'s that are the opposites of what they are supposed to be.** (That's 3% of the 10000 total `0`'s and `1`'s.) Near the bottom of the snippet, you can paste in the output of your program and check how many `0`'s or `1`'s are different than what they should be. Any number of differences at or below 300 is valid. # Scoring The submission with the fewest bytes wins. ([Handy byte counter.](https://mothereff.in/byte-counter)) Tiebreaker goes to the submission with the fewest incorrect `0`'s and `1`'s. If there's still a tie, the earlier submission wins. # Details * Output goes to stdout or a similar alternative if your language does not have stdout. * The output may optionally have a trailing newline. * Please include the color identicon image in your post along with the exact string that generates it. There's no need to waste space and post your entire textual output. * Your program should run without an internet connection. You need to generate the text in your code, not query it from the Gravatar site. * Use common sense when "naming" your language. Use the language name you would normally use on this site. Don't be annoying and contrive a name that makes the identicon easy to golf. e.g. `Python 2` is fine for Python but `python 2.7.2` is stretching it and `python 2.7.2 by Guido van Rossum` would be ridiculous. * I realize some languages are inherently easier than others because their identicon shapes are simpler. That's just the way it's gonna be, don't get too disgruntled or competitive about that. ;) [Answer] # Octave ~~166~~ 164 bytes, 0 errors Octave has a great stength in handling/building matrices. For the 'diamonds' I made an x-y-coordinate system and used manhattan norm for deciding whether the entries will be 1 or 0. As the diamonds are not fully symmetrical, I had to fiddle around with the 'distance' and the centerpoint, so with the center point (13.1,13.1) it worked for both kinds of 'diamond' shapes. After that I could just set one quarter of those to zero in order to get those C-shapes. The squares and the matrix concatenation were easy. New Version -2 characters (works the same way as the old, but I managed to abuse the Octave syntax even somewhat more: ``` C=ones(25);M=(R=(R=meshgrid(abs(-12.1:12)))+R')>12|R<6.5;S=T=U=V=13.1>R&R>5.8;C(k=8:19,k)=S(f,s)=T(f,f)=U(s,f=1:12)=V(s=14:25,s)=0;[C,U,T,C;U,M,M,T;V,M,M,S;C,V,S,C] ``` Old version: ``` C=ones(25); %corner squares C(k=8:19,k)=0; %set the inner squares to 0 X=meshgrid(abs(-12.1:12)); %build coordinate system R=X+X'; %R already has the distances to the chosen centerpoint (13.1, 13.1) M=R>12|R<6.5; %diamond (for the center) S=T=U=V=13.1>R&R>5.8; %diamond (for the edges) S(f,s)=T(f,f)=U(s,f=1:12)=V(s=14:25,s)=0; %set each one quarter to 0 for the C-shape [C,U,T,C;U,M,M,T;V,M,M,S;C,V,S,C] %concatenate and display the big matrix ``` Output ![enter image description here](https://i.stack.imgur.com/lyr5v.png) ``` 1111111111111111111111111000000000000110000000000000000000000011000000000001111111111111111111111111 1111111111111111111111111000000000001111000000000000000000000011100000000001111111111111111111111111 1111111111111111111111111000000000011111100000000000000000000011110000000001111111111111111111111111 1111111111111111111111111000000000111111110000000000000000000011111000000001111111111111111111111111 1111111111111111111111111000000001111111111000000000000000000011111100000001111111111111111111111111 1111111111111111111111111000000011111111111100000000000000000011111110000001111111111111111111111111 1111111111111111111111111000000111111111111110000000000000000011111111000001111111111111111111111111 1111111000000000000111111000001111111011111111000000000000000001111111100001111111000000000000111111 1111111000000000000111111000011111110001111111100000000000000000111111110001111111000000000000111111 1111111000000000000111111000111111100000111111110000000000000000011111111001111111000000000000111111 1111111000000000000111111001111111000000011111111000000000000000001111111101111111000000000000111111 1111111000000000000111111011111110000000001111111100000000000000000111111111111111000000000000111111 1111111000000000000111111111111100000000000111111111111110000000000011111111111111000000000000111111 1111111000000000000111111000000000000000001111111111111111000000000111111111111111000000000000111111 1111111000000000000111111000000000000000011111111001111111100000001111111101111111000000000000111111 1111111000000000000111111000000000000000111111110000111111110000011111111001111111000000000000111111 1111111000000000000111111000000000000001111111100000011111111000111111110001111111000000000000111111 1111111000000000000111111000000000000011111111000000001111111101111111100001111111000000000000111111 1111111000000000000111111000000000000111111110000000000111111111111111000001111111000000000000111111 1111111111111111111111111000000000000111111100000000000011111111111110000001111111111111111111111111 1111111111111111111111111000000000000111111000000000000001111111111100000001111111111111111111111111 1111111111111111111111111000000000000111110000000000000000111111111000000001111111111111111111111111 1111111111111111111111111000000000000111100000000000000000011111110000000001111111111111111111111111 1111111111111111111111111000000000000111000000000000000000001111100000000001111111111111111111111111 1111111111111111111111111000000000000110000000000000000000000111000000000001111111111111111111111111 0000000000001100000000000111111111111111111111111111111111111111111111111110000000000001100000000000 0000000000011110000000000111111111111001111111111111111111111100111111111110000000000001110000000000 0000000000111111000000000111111111110000111111111111111111111000011111111110000000000001111000000000 0000000001111111100000000111111111100000011111111111111111110000001111111110000000000001111100000000 0000000011111111110000000111111111000000001111111111111111100000000111111110000000000001111110000000 0000000111111111111000000111111110000000000111111111111111000000000011111110000000000001111111000000 0000001111111111111100000111111100000100000011111111111110000010000001111110000000000001111111100000 0000011111110111111110000111111000001110000001111111111100000111000000111110000000000000111111110000 0000111111100011111111000111110000011111000000111111111000001111100000011110000000000000011111111000 0001111111000001111111100111100000111111100000011111110000011111110000001110000000000000001111111100 0011111110000000111111110111000001111111110000001111100000111111111000000110000000000000000111111110 0111111100000000011111111110000011111111111000000111000001111111111100000010000000000000000011111111 1111111000000000001111111100000111111111111100000010000011111111111110000001111111000000000001111111 0000000000000000011111111100000011111111111000000110000001111111111100000011111111100000000011111111 0000000000000000111111110110000001111111110000001111000000111111111000000110111111110000000111111110 0000000000000001111111100111000000111111100000011111100000011111110000001110011111111000001111111100 0000000000000011111111000111100000011111000000111111110000001111100000011110001111111100011111111000 0000000000000111111110000111110000001110000001111111111000000111000000111110000111111110111111110000 0000000000001111111100000111111000000100000011111111111100000010000001111110000011111111111111100000 0000000000001111111000000111111100000000000111111111111110000000000011111110000001111111111111000000 0000000000001111110000000111111110000000001111111111111111000000000111111110000000111111111110000000 0000000000001111100000000111111111000000011111111111111111100000001111111110000000011111111100000000 0000000000001111000000000111111111100000111111111111111111110000011111111110000000001111111000000000 0000000000001110000000000111111111110001111111111111111111111000111111111110000000000111110000000000 0000000000001100000000000111111111111011111111111111111111111101111111111110000000000011100000000000 0000000000001100000000000111111111111111111111111111111111111111111111111110000000000001000000000000 0000000000011110000000000111111111111001111111111111111111111100111111111110000000000011000000000000 0000000000111111000000000111111111110000111111111111111111111000011111111110000000000111000000000000 0000000001111111100000000111111111100000011111111111111111110000001111111110000000001111000000000000 0000000011111111110000000111111111000000001111111111111111100000000111111110000000011111000000000000 0000000111111111111000000111111110000000000111111111111111000000000011111110000000111111000000000000 0000001111111111111100000111111100000100000011111111111110000010000001111110000001111111000000000000 0000011111110111111110000111111000001110000001111111111100000111000000111110000011111110000000000000 0000111111100011111111000111110000011111000000111111111000001111100000011110000111111100000000000000 0001111111000001111111100111100000111111100000011111110000011111110000001110001111111000000000000000 0011111110000000111111110111000001111111110000001111100000111111111000000110011111110000000000000000 0111111100000000011111111110000011111111111000000111000001111111111100000010111111100000000000000000 1111111000000000001111111100000111111111111100000010000011111111111110000001111111000000000001111111 1111111100000000000000000100000011111111111000000110000001111111111100000011111111100000000011111111 0111111110000000000000000110000001111111110000001111000000111111111000000110111111110000000111111110 0011111111000000000000000111000000111111100000011111100000011111110000001110011111111000001111111100 0001111111100000000000000111100000011111000000111111110000001111100000011110001111111100011111111000 0000111111110000000000000111110000001110000001111111111000000111000000111110000111111110111111110000 0000011111111000000000000111111000000100000011111111111100000010000001111110000011111111111111100000 0000001111111000000000000111111100000000000111111111111110000000000011111110000001111111111111000000 0000000111111000000000000111111110000000001111111111111111000000000111111110000000111111111110000000 0000000011111000000000000111111111000000011111111111111111100000001111111110000000011111111100000000 0000000001111000000000000111111111100000111111111111111111110000011111111110000000001111111000000000 0000000000111000000000000111111111110001111111111111111111111000111111111110000000000111110000000000 0000000000011000000000000111111111111011111111111111111111111101111111111110000000000011100000000000 1111111111111111111111111000000000000110000000000000000000000010000000000001111111111111111111111111 1111111111111111111111111000000000001111000000000000000000000110000000000001111111111111111111111111 1111111111111111111111111000000000011111100000000000000000001110000000000001111111111111111111111111 1111111111111111111111111000000000111111110000000000000000011110000000000001111111111111111111111111 1111111111111111111111111000000001111111111000000000000000111110000000000001111111111111111111111111 1111111111111111111111111000000011111111111100000000000001111110000000000001111111111111111111111111 1111111111111111111111111000000111111111111110000000000011111110000000000001111111111111111111111111 1111111000000000000111111000001111111011111111000000000111111100000000000001111111000000000000111111 1111111000000000000111111000011111110001111111100000001111111000000000000001111111000000000000111111 1111111000000000000111111000111111100000111111110000011111110000000000000001111111000000000000111111 1111111000000000000111111001111111000000011111111000111111100000000000000001111111000000000000111111 1111111000000000000111111011111110000000001111111101111111000000000000000001111111000000000000111111 1111111000000000000111111111111100000000000111111111111110000000000011111111111111000000000000111111 1111111000000000000111111111111110000000000000000011111111000000000111111111111111000000000000111111 1111111000000000000111111011111111000000000000000001111111100000001111111101111111000000000000111111 1111111000000000000111111001111111100000000000000000111111110000011111111001111111000000000000111111 1111111000000000000111111000111111110000000000000000011111111000111111110001111111000000000000111111 1111111000000000000111111000011111111000000000000000001111111101111111100001111111000000000000111111 1111111000000000000111111000001111111100000000000000000111111111111111000001111111000000000000111111 1111111111111111111111111000000111111100000000000000000011111111111110000001111111111111111111111111 1111111111111111111111111000000011111100000000000000000001111111111100000001111111111111111111111111 1111111111111111111111111000000001111100000000000000000000111111111000000001111111111111111111111111 1111111111111111111111111000000000111100000000000000000000011111110000000001111111111111111111111111 1111111111111111111111111000000000011100000000000000000000001111100000000001111111111111111111111111 1111111111111111111111111000000000001100000000000000000000000111000000000001111111111111111111111111 ``` [Answer] # CJam, ~~92~~ ~~81~~ ~~79~~ 71 bytes, 120 errors ![Identicon](https://www.gravatar.com/avatar/072949cc6cbf396adf85faf49f453472?&s=100&d=identicon) ``` 25:M{'0*MXe[}%2/z:~M,_ff{_)2$)d/2mLz1>@@+38<^}:A.+AM'1*f++_W%z.+N*N1$W% ``` There is probably still some room to golf this. [Test it here.](http://cjam.aditsu.net/#code=25%3AM%7B'0*MXe%5B%7D%252%2Fz%3A~M%2C_ff%7B_)2%24)d%2F2mLz1%3E%40%40%2B38%3C%5E%7D%3AA.%2BAM'1*f%2B%2B_W%25z.%2BN*N1%24W%25) ## Explanation I'm not using any compression, but instead I actually compute the individual tiles and piece the result together from those. The top-left tile is intentionally approximated. A few other errors result from the binarised image not being fully rotationally symmetric. Let's go through the code. The first tile should theoretically look like this: ``` 1111111111111111111111111 1111111111111111111111100 1111111111111111111110000 1111111111111111111000000 1111111111111111100000000 1111111111111110000000000 1111111111111000000000000 1111111111100000000000000 1111111110000000000000000 1111111000000000000000000 1111100000000000000000000 1110000000000000000000000 1111111111111111111111111 1111111111111111111111110 1111111111111111111111000 1111111111111111111100000 1111111111111111110000000 1111111111111111000000000 1111111111111100000000000 1111111111110000000000000 1111111111000000000000000 1111111100000000000000000 1111110000000000000000000 1111000000000000000000000 1100000000000000000000000 ``` That's 12 lines, then 13 lines of the point between `1`s and `0`s decreasing by 2 at a time. Notice that the first block has an even number of `0`s and the second block an odd number. We can make the pattern even more regular if we sacrifice accuracy on the middle row and turn it into `1` followed by 24 `0`s. Then we actually have one row for each number of zeroes from 0 to 24, alternating between the top and bottom parts. So we can just generate them in order (as a single triangle), and then pull out every other line: ``` 25:M{'0*MXe[}%2/z:~ 25:M e# Push 25 and store it in M for future use. { }% e# Map this block onto the range [0 ... 24]. '0* e# Create a string of i zeroes. MXe[ e# Pad to width 25 with 1s from the left. 2/ e# Group the lines into pairs. z e# Zip the pairs, thereby grouping even and odd lines. :~ e# Flatten the two groups so we've got a plain 2D grid again. ``` Next up is that fancy triangle to the right of this tile: ``` 1100000000000000000000000 1111000000000000000000000 0111110000000000000000000 0111111100000000000000000 0011111111000000000000000 0011111111110000000000000 0001111111111100000000000 0001111111111111000000000 0000111111111111110000000 0000111111111111111100000 0000011111111111111111000 0000011111111111111111110 0000001111111111111111111 0000001111111111111111111 0000000111111111111111110 0000000111111111111111100 0000000011111111111111000 0000000011111111111110000 0000000001111111111100000 0000000001111111111000000 0000000000111111110000000 0000000000111111100000000 0000000000011111000000000 0000000000011110000000000 0000000000001100000000000 ``` If we consider a coordinate system with origin in the top right corner and `x` going right and `y` going down, then the region of `1`s satisfies 3 inequalities: `x/y ≥ 1/2`, `x/y ≥ 2`, `x + y < 38`. We can just compute these separately and take the logical end. It doesn't save any characters but cleans up the code slightly if we combine the first two inequalities though: ``` 1/2 ≤ x/y ≤ 2 => -1 ≤ log2(x/y) ≤ 1 => |log2(x/y)| ≤ 1 ``` Ultimately, we'll save another byte by checking the opposite and using `xor` instead of `and` to combine the result with the other inequality: ``` M,_ff{_)2$)d/2mLz1>@@+38<^} M,_ e# Create a range [0 .. 24] and duplicate it. ff{ } e# This creates a 25x25 array, where each element is e# determined by executing the block on the pair of its e# x and y coordinates. _) e# Copy x and increment. 2$) e# Copy y and increment. d/ e# Convert to double and divide. 2mL e# Get base-2 logarithm. z1> e# Take modulus and check if it's greater than 1. @@ e# Get the other two copies of x and y. +38< e# Add them and check that they are less than 38. ^ e# Take the XOR with the other condition. ``` We've got everything in place now - the remaining tiles are just copies and rotations of these, as well as the solid (boring) tile in the centre. So let's pull everything together: ``` :A.+AM'1*f++_W%z.+N*N1$W% :A e# Store the fancy triangle in A. .+ e# Join the two existing tiles horizontally. A e# Push the triangle again. M'1* e# Create a string of 25 ones. f+ e# Add it to each line of the triangle. + e# Add these two tiles to the first two tiles, completing e# the upper left quadrant. _W%z e# Duplicate the quadrant, reverse the rows, transpose. e# These two operations together perform a 90 degree e# clockwise rotation. .+ e# Join the two quadrants horizontally. N* e# Join the lines together with newline characters. N1$ e# Push a newline to separate the two halves and copy the e# first half. W% e# Reverse the entire string. Since this reverse the string e# both vertically and horizontally, this rotates the e# half by 180 degrees. ``` At the end of the program, CJam simply prints the stack contents back-to-back, creating the desired result. [Answer] # Brainfuck 9418 2237 bytes, 88 errors **Edit:** As mbomb007 pointed out the 'official' name seems to not be capitalized, this is not mentioned on wikipedia, but is on [esolangs](https://esolangs.org/wiki/brainfuck). This annoys me, but not nearly enough to redo this ;). My first Brainfuck program! Now actually uses math and logic and stuff! (for every pixel it decides 0 or 1 depending on a few conditionals). This was quite fun to do; that being said I don't think I'm going to code again with Brainfuck for a long **long** time. ``` >>>++[<+>+++++]<-->>++[<+>+++++]<--[->+++++[>+++++<-]<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<+>]<+<[->>>>>>>+<<<<<<<]>>>>>>>->+++++[>+++++<-]<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>[-<<<<<<<<+>>>>>>>>]<<<<<<<<+>>>>>>+>>>>>>+<<<<<<[>>+++<<<[>>>-<+<<-]>>[<<+>>-]>[<<->>[-]]<<<[->>+<<]>+>[<->[-<<+>>]]>>>>>]<<<<<<[-<<<<<<+>>>>>>]<<<<<+<[-[->-<>>>>[->>>+>>>>>>>++>>>>>>>>>>>>>>>>>+>>>>>>>++<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<]<[->>>>>>>>>>>>>>>>+>>>>>>>++>>>>>>>>>>>>>>>>>+>>>>>>>++<<<<<<<<<<<<<<<<<<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>-]>[<<<<+>>[-]+>>->]<+<<-]>>[-]<[-]<<[-]>>>>>>>>>]<<<<<<<<<<[-<<<<<<+>>>>>>]<<<<<<[-<<<<<<+>>>>>>]<<<<<<<+++>[-<->]<[<<<<<+>>>>>[-]]<[-]>>>]<]>[-<<<[->>>>>+>+<<<<<<]>>>>>[->>>>>>>>>>>>>>>+>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<]>[->>+>>>>>>>+<<<<<<<<<]>>>>++++[<++++>-]<+>>>+>+++++[>++++++<-]>>>>>+>>>>+++[<++++++>-]<+>>>+>+++++[>++++++<-]>+>>>>+[<<<[>+>+<<-]>>[<<+>>-]<<<[>>>+<<<-]>>>[>-]>[<<<<+>>[-]>>->]<+<<[>-[>-]>[<<<<+>>[-]+>>->]<+<<-]>>[-]<[-]<<[-]<<<]>>>>>>>>>>>>>>>>>>>>[-<<<<<<+>>>>>>]<<<<<<[-<<<<<<+>>>>>>]<<<<<<[-<<<<<<+>>>>>>]<<<<<<[-<<<<<<<<<<<<<+>>>>>>>>>>>>>[-]]<[-]<<<<<<[-]<<[-]>>>]<<<<<<<<<+[>+<+++++]>---.[-]>-[->>+<<]>>>+<[>-<[-<<+>>]]>[<<->++[<<+>>+++++]<<-->>>[-]++++++++++.[-]]<<] ``` producing the bitmap of the image: ![enter image description here](https://i.stack.imgur.com/FACgw.png) A version with some comments (might not be very useful as they were mostly for my own benefit): ``` >> >++[<+>+++++]<-- > >++[<+>+++++]<-- 100 100 x y range from 1 to 100 (min is not 0) [ while y - x * y_1 >+++++[>+++++<-]< [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] x * 0 y_1 25_(y_1)%25 (y_1)%25 y//25 >[-<+>]<+ x * y 0 25_(y_1)%25 (y_1)%25 y//25 <[->>>>>>>+<<<<<<<]>>>>>>>- 0 y 0 25_(y_1)%25 (y_1)%25 y//25 0 * x_1 >+++++[>+++++<-]< [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] 0 y 0 25_(y_1)%25 (y_1)%25 y//25 0 * 0 x_1 25_(x_1)%25 (x_1)%25 x//25 >[-<<<<<<<<+>>>>>>>>]<<<<<<<<+ * x y 0 25_(y_1)%25 (y_1)%25 y//25 0 0 0 25_(x_1)%25 (x_1)%25 x//25 >>>>>>+>>>>>>+<<<<<< [ >>+++<< <[>>>-<+<<-] >>[<<+>>-] >[<<->>[-]] x y 0 25_(y_1)%25 (y_1)%25 y//25 y//25=3 0 * 0 25_(x_1)%25 (x_1)%25 x//25 <<<[->>+<<] >+> [<->[-<<+>>]] x y 0 25_(y_1)%25 (y_1)%25 y//25 y//25=0|3 *0 0 25_(x_1)%25 (x_1)%25 x//25 >>>>> ] <<<<<< x y 0 25_(y_1)%25 (y_1)%25 y//25 y//25=0|3 0 0 25_(x_1)%25 (x_1)%25 x//25 * x//25=0|3 [-<<<<<<+>>>>>>] x y 0 25_(y_1)%25 (y_1)%25 y//25 p 0 0 25_(x_1)%25 (x_1)%25 x//25 * 0 <<<<< +< [ - [ ->-< ### p == 2 ### x y 0 v1 v0 y//25 0 * 0 0 u1 u0 x//25 0 >>>> [->>>+ >>>>>>>++ >>>>>>>>>>>>>>>>>+ >>>>>>>++<<<<<<< <<<<<<<<<<<<<<<<< <<<<<<< <<<] < [->>>>>>>>>>>>>>>>+ >>>>>>>++ >>>>>>>>>>>>>>>>>+ >>>>>>>++ <<<<<<< <<<<<<<<<<<<<<<<< <<<<<<< <<<<<<<<<<<<<<<<] <<<<< [->>>>>>>>>>++ >>>>>+ >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>++ >>>>>+ <<<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< <<<<< <<<<<<<<<<] < [->>>>>>>>>>>>>>>>>>>>>>>++ >>>>>+ >>>>>>>++ >>>>>+ <<<<< <<<<<<< <<<<< <<<<<<<<<<<<<<<<<<<<<<<] >>>>>>>> >>>+ >>>+>>>+ >>>+>>> >>>+>>+> >>>+>>++> >>>+>>>++ >>>+>>>++ >>>+>>++> >>>+<<< <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< x y 0 0 0 y//25 0 0 0 0 0 x//25 * 0 [ < <<[>+>+<<-] >>[<<+>>-] <<<[>>>+<<<-] >>>[>-]> [< <<<+ >>[-] > >->]<+< <[>- [>-]> [< <<<+ >>[-]+ > >->]<+< <-] >>[-]<[-]<<[-]>>>>>>>>> ] <<<<<<<<<< [<<<<<<[<<<<<<[<<<<<<[<+>-]>>>>>>-]>>>>>>-]>>>>>>-] <<<<<<[-]<<<<<<[-]<<<<<<[-] <<<<<< [<<<<<<[<<<<<<[<<<<<<[<+>-]>>>>>>-]>>>>>>-]>>>>>>-] <<<<<<[-]<<<<<<[-]<<<<<<[-] >>>>>> >>>>>> >>>>>> >>>>> [-<<<<<< <<<<<< <<<<<< <<<<<< + >>>>>> >>>>>> >>>>>> >>>>>>] <<<<<< <<<<<< <<<<<< <<<<<< [<<<<<<<<<<<<<+>>>>>>>>>>>>>[-]] <[-]<<<<<<[-]> ] > [ - ### p == 1 ### x y 0 v1 v0 y//25 0 * 0 0 u1 u0 x//25 0 << [ [->+<] >-< ] > [ <<[-]<[->+<] >->>[-] ] x y 0 ~ v 0 * 0 0 0 u1 u0 x//25 0 >>>>> [ [->+<] >-< ] > [ <<[-]<[->+<]- >->>[-] ] x y 0 ~ v 0 0 0 0 ~ u 0 * 0 >>>+>>> >++[<++>+++++++] >>+<<< <<<<<<<+< [->+<<<<<++>>>> >>>>>>>+<<<<<<<] <[-]+<<<<+< [->+>>>>>>>++>>>>>+<<<<<<<<<<<<<] x y 0 ~ * 0 v 2u_1 0 0 ~ 0 u 2v_1 >>>>> [ < <<[>+>+<<-] >>[<<+>>-] <<<[>>>+<<<-] >>>[>-]> [< <<<+ >>[-] > >->]<+< <[>- [>-]> [< <<<+ >>[-]+ > >->]<+< <-] >>[-]<[-]<<[-]>>>>>>>>> ] <<<<<<<<<< x y 0 ~ 0 v~2u_1 0 0 0 0 0 u~2v_1 0 [-<<<<<<+>>>>>>]<<<<<< [-<<<<<<+>>>>>>]<<<<<< <+++> [-<->] <[<<<<<+>>>>>[-]] <[-]>>> ] < ] > [ - ### p = 0 ### x y 0 v1 v0 y//25 p * 0 0 u1 u0 x//25 <<<[->>>>>+>+<<<<<<] x y 0 v1 * 0 y//25 p 0 0 v0|u1 v0|u0 x//25 >>>>> [->>>>>>>>>>>>>>>+>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<] x y 0 v1 0 y//25 p 0 0 * 0 v0|u0 x//25 x y t0 t1 _ _ x y t0 t1 _ _ x y t0 t1 _ _ x y t0 t1 _ _ >[->>+>>>>>>>+<<<<<<<<<] x y 0 v1 0 y//25 p 0 0 0 *0 x//25 x y t0 t1 _ _ x y t0 t1 _ _ x y t0 t1 _ _ x y t0 t1 _ _ >>>>++++[<++++>-]<+ >>>+ >+++++[>++++++<-]> >>>>+ >>>>+++[<++++++>-]<+ >>>+ >+++++[>++++++<-]>+ >>>>+ [ < <<[>+>+<<-] >>[<<+>>-] <<<[>>>+<<<-] >>>[>-]> [< <<<+ >>[-] > >->]<+< <[>- [>-]> [< <<<+ >>[-]+ > >->]<+< <-] >>[-]<[-]<<[-]<<< ] >> >>>>>> >>>>>> >>>>>> [-<<<<<<+>>>>>>]<<<<<< [-<<<<<<+>>>>>>]<<<<<< [-<<<<<<+>>>>>>]<<<<<< [-<<<<<<<<<<<<<+>>>>>>>>>>>>>[-]] x y 0 v1 0 y//25 p 0 0 0 0 x//25 *0 <[-]<<<<<<[-]<<[-] >>> ] < <<<<< <<< +[>+<+++++]>---.[-] > - decrement x [->>+<<]>>>+< [ >-< [-<<+>>] ] > [ if x is 0 <<- decrement y >++[<<+>>+++++]<<-- set x to 100 >>>[-] ++++++++++. output '/n' [-] ] << ] ``` [Answer] # Python, ~~294~~ ~~273~~ ~~239~~ ~~188~~ ~~179~~ ~~170~~ ~~159~~ 154 bytes Here is the **158-byte** version: ``` I=100*[100*"0"] for j in range(7500):i=j%25;j/=100;I=map(list,zip(*I[::-1]));I[i][j]=`+[abs(i%12-6)+5<j/2,j>i/2+24,2*i>72-j][j/25]` for r in I:print"".join(r) ``` This is a Python 2 only program, but I'm using the identicon for "Python" (i.e. the one in the OP). The diff should be 78 bits. By throwing accuracy out the door, here is the **154-byte** version: ``` I=100*[100*"0"] for j in range(7425):i=j%25;j/=99;I=map(list,zip(*I[::-1]));I[i][j]=`+[~i%12<j/2>i%12,j>i/2+24,2*i>72-j][j/25]` for r in I:print"".join(r) ``` which has a diff of 224 bits instead. *(-4 bytes thanks to Stefan Pochmann)* ## Explanation Here's an alternate expanded version: ``` I=100*[100*"0"] for _ in range(4): I=map(list,zip(*I[::-1])) for i in range(25): for j in range(75): I[i][j]=`+[abs(i%12-6)+5<j/2,j>i/2+24,2*i>72-j][j/25]` for r in I:print"".join(r) ``` For this version, we treat the identicon as a 4x4 grid of patterns. We start with a 100x100 grid of 0s and do the following four times: * Fill in the first three patterns on pattern row 1 using inequalities * Rotate the whole thing clockwise ![enter image description here](https://i.stack.imgur.com/nwJQA.png) The original version is similar, but instead of rotating *after* the three patterns are complete, we rotate *every time we modify a single cell*. This makes the program take a few seconds, but the output is the same. [Answer] # C, ~~255~~ ~~245~~ ~~237~~ 234 bytes C's identicon is *really* symmetrical. ![C identicon](https://i.stack.imgur.com/WTytO.png) **Golfed:** (newlines added for "readability") ``` d[100],j,y,i,o[100]; main(c){ for(;i<100;++i){j=i>12?25-i:i,y=j<7?-1u>>63-j:127,d[i]=y<<12-j|y<<(j<7?12:j+6), o[i]=i<25?(-1<<12|-1u>>76-i|-(i<13))<<25|d[i]:d[i-25]<<25; for(c=50;c--+50;putchar(o[i<50?i:99-i]>>(c<0?~c:c)&1|48));puts("");}} ``` This stores half of each line in the top half into a 64-bit integer, then prints the lower 50 bits of the appropriate integer in binary twice, with the second print being reversed. 64-bit ints are required for this to run (if your system does not use 64-bit ints, then you may add `long` or `long long` before `d[50]`, and `(long)` or `(long long)` after `o[i-1]=i<26?`). **Ungolfed and commented:** ``` int diamond[25], j, y, i, out[50]; main(c){ // generate diamond pattern for(i = 0; i < 25; ++i){ j = i > 12 ? 25 - i : i; y = j < 7 ? -1u >> 63 - j : 127; diamond[i] = y << 12 - j | y << (j < 7 ? 12 : j + 6); } // generate top half outputs in reverse order for(i = 0; i < 50; ++i){ if(i < 25) // i < 50: out[i] = [diamond] [0 ... x25] out[i] = diamond[i] << 25; else // i < 25: out[i] = [1...x25] [diamond] out[i] = (int)(-1 << 12 | -1u >> 27 + i | -(i > 36)) << 25 | diamond[i - 25]; // i >= 50: use out[100 - i] } // print rows for(i = 50; i-- + 50; putchar('\n')){ // print last 50 bits of the correct 64-bit integer, then print it reversed for(c = 50; c-- + 50; putchar(out[i < 0 ? -i - 1 : i] >> (c < 0 ? -c - 1 : c) & 1 | '0')); } } ``` Output has 291 errors. Thanks to ace for the tip of using `puts("")` [Answer] # C, ~~224~~ ~~206~~ ~~200~~ 176 bytes, 243 errors ``` char b[101],i,j,k=1,s,a;main(){for(;i+1;i+=k=i-50?puts(b),k:-1)for(j=0;j<50;j++)s=i-j,a=i+j-49|1,b[j]=b[99-j]=(i/25+j/25?14/a&&s/12&&38/s&&a/6|19/s+s/31:i<13||j<13^i+j>36)+48;} ``` To replicate: ![C Identicon](https://i.stack.imgur.com/WTytO.png) The above code outputs binary which correlates to this image, with 243 errors: ![243 Errors](https://i.stack.imgur.com/luTXM.png) From what I can tell, I use a rather different method from es1024's solution. This method can probably be further golfed, so I'll hold off on explanation for a bit, but here it is in its unraveled glory: ``` char b[101],i,j,k=1,s,a; main(){ for(;i+1;i+=k=i-50?puts(b),k:-1) for(j=0;j<50;j++) s=i-j, a=i+j-49|1, b[j]=b[99-j]=(i/25+j/25?14/a&&s/12&&38/s&&a/6|19/s+s/31:i<13||j<13^i+j>36)+48; } ``` It essentially uses a set of inequalities to define the polygons, and relies heavily on symmetry. It is currently midnight, and my ability to read my own code is rapidly deteriorating. You can probably fiddle with some constants to lower the errors, but I can only consistently break everything. Fun fact, not only is this the shortest version I have come up with, but *gcc throws no warnings*! [Answer] # [gs2](https://github.com/nooodl/gs2): 72 bytes, 200 errors ![](https://www.gravatar.com/avatar/0106ddb45fc03420c024663bf88aea0b?r=PG&s=100&default=identicon) Haven't really golfed this yet, not sure if I will. Mnemonics: ``` # Square abs both1 biggest 6 <= b5 # Left triangle { over abs both1 + 13 <= swap 1 < and } # Diagonal triangle { >= @0 double 10 + @4 <= or } # ^ 12 gives way more accuracy here but pushing 10 saves a byte. # Plot each of these 3 make-array { pop-a -12 13 crange dup cartesian-product dump swap push-a eval show m5 25 / } map # Make corner dump reverse zip @1 rot zip + unlines lines dup reverse transpose zip dup reverse show reverse m2 + unlines ``` The program itself: ``` 23 f8 39 16 75 e4 08 45 23 f8 30 01 0d 75 42 11 70 35 09 08 73 a0 2a 1a 30 a4 75 36 09 13 0e 08 cc 02 f4 ff 01 0d 4f 40 83 0e 42 d0 20 52 ec 01 19 33 09 34 0e 20 b0 a1 43 b0 30 2b 2a 40 20 9a b0 40 20 52 20 e9 30 2b ``` [Answer] # Z80, 194 bytes, 0 errors ![Z80 identicon](https://i.stack.imgur.com/mo0YZ.png) # Z80, 178 bytes, 80 errors ![Z80 identicon with errors](https://i.stack.imgur.com/yCxdD.png) The errors are highlighted in green. As this is an old-school CPU, I have used old-school conventions. I have used &8000 for hex values instead of the more familiar 0x8000 and I have chosen to end each line of the pattern with a "\r" instead of a "\n". ## Source code HEX encoded ``` 0 1 2 3 4 5 6 7 8 9 A B C D E F -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- &8000 69 31 18 00 DB 42 81 E7 21 00 40 11 04 80 0E 04 &8010 06 19 D5 1A F5 C5 E6 03 5F 1A 32 20 80 06 19 18 &8020 00 36 31 23 10 F9 C1 F1 E6 FC 0F 0F 20 E6 36 0D &8030 23 D1 10 DE 13 0D 20 D8 C9 3E 1A 90 58 C1 C5 D5 &8040 58 47 7B 87 FE 1A 38 02 D6 19 5F 80 FE 1B 28 34 &8050 18 0E 78 C1 C5 5F D5 87 FE 1A 38 02 D6 19 5F 80 &8060 FE 1A 28 20 30 06 90 90 30 1A 18 14 90 90 38 14 &8070 FE 01 38 10 20 0A 7B D6 05 30 FC C6 05 0F 38 04 &8080 36 30 18 02 36 31 D1 43 18 99 58 C1 C5 78 83 FE &8090 0D 38 26 FE 27 30 22 93 93 30 04 FE F3 30 04 FE &80A0 0E 30 16 83 83 FE 15 38 14 FE 20 30 10 93 93 30 &80B0 04 FE FB 30 04 FE 06 30 04 36 30 18 02 36 31 43 &80C0 18 C6 ``` ## Source code explained As the Z80 is a CPU, it doesn't have any standard output of its own. As such, I merely wrote each character directly into memory, starting from &4000, and then MEMDUMP'd the 10,100 bytes to verify the correct pattern. The Z80 has registers as follows: ``` +-------+ | B / C | 8-bit general purpose B & C or 16-bit general purpose BC +-------+ | D / E | 8-bit general purpose D & E or 16-bit general purpose DE +-------+ | H / L | 8-bit general purpose H & L or 16-bit specialised HL +-------+ | A | F | 8-bit accumulator A (main working register) & Flag register F +-------+ ``` The special Flag register contains the following flags: `SZ-H-VNC`. **S**ign, **Z**ero, **H**alf-carry, O**v**erflow (also used as **P**arity), **N**egative and **C**arry. The positions marked by `-` are unused. The **H**alf-carry and **N**egative flags are only used internally by the CPU. **S**ign and O**v**erflow/**P**arity take extra bytes to use so I am only using **Z**ero and **C**arry which get set or reset after each calculation, but not when moving values around. There are other registers available but they aren't relevant to a golfing challenge as they take extra bytes to use. * `LD` **l**oa**d**s a value into a register or address, e.g. `LD C, 4` is `C = 4`. The value can be direct (one or two extra bytes for an 8-bit or 16-bit value respectively) or can be copied from another register. A value of `(HL)` means copy to or from the address pointed to by `HL`. * `PUSH` and `POP` **push** (save to) and **pop** (restore from) the stack, which can only store 16-bit values. As such, `AF` is treated as a single 16-bit register even though no other instructions use it like that. * `AND` is bitwise **and**. The Z80 has no boolean logic instructions, but does have boolean flags. * `JR` **j**ump **r**elative using a one-byte signed offset. This uses one byte less than the absolute **j**um**p** `JP`, but has fewer conditions that can be tested for. * `INC` and `DEC` **inc**rement and **dec**rement 8 and 16 bit registers. * `DJNZ` **d**ecrement and **j**ump if **n**on-**z**ero. This does exactly the same as `DEC B; JR NZ, ##;` in one less byte but is only available for the `B` register. * `RET` **ret**urns to the calling location. It can optionally have conditions on it. * `ADD` and `SUB` **add** to and **sub**tract from either the 8 bit `A` register or the 16 bit `HL` register. * `CP` **c**om**p**are subtracts the value from the `A` register, sets flags as appropriate but discards the result leaving `A` unchanged. * `RRCA` **r**otate **r**ight **c**ircular **a**ccumulator. Rotates all the bits in `A` once to the right, copying bit 0 into bit 7. It also copies bit 0 into the Carry (`C`) flag, not to be confused with the `C` register. Every Identicon pattern can be broken down like so: ``` 0451 4885 6887 2673 ``` where 0-3 are the corners, rotated as appropriate, 4-7 are the edge tiles, rotated as appropriate and 8 is the centre tile which is (as far as I can tell) always rotationally symetrical. Luckily, the Z80 Identicon can be simplified to: ``` 3123 1002 2001 3213 ``` I put the "0"s in the centre to enable me to efficiently check for an end condition. In fact, to golf the code it made sense to do almost everything backwards! `:Offsets` is a block of four byte values which I use as offsets to the pattern for each block. The program works out which block to run then alters itself to jump to the right code. Strangely, this seems to use fewer bytes than by checking directly! `:DATA` (also called magic data in the comments!) is the encoded order in which the blocks need to be rendered. There are 16 values, normally requiring 16 bytes but since each value is only 2 bits long I was able to put 4 into one byte, saving 12 bytes! The code to store, restore and decode these values is 6 bytes. Additionally, by avoiding using the number 0 in the highest 2 bits I was able to double this as a counter, saving at least 3 bytes (2 to initialise, 1 to decrement)! Total bytes saved: 12 - 6 + 3 = 9. The offset data must be stored at a location ending in 00 hex to work properly. I chose &8000 as it seemed like a good out-of-the-way location. This means that the program starts at &8008. Coincidentally, Intel produced an early CPU called the 8008 which could be considered the grandfather of the Z80! Intel also produced the 8080, which Zilog based their Z80 on, being fully compatible with. The Z80 has a range of extended instructions which the 8080 doesn't. I have avoided using these extended instructions as each one has a one-byte prefix, meaning that this program will also produce the same results on the 8080! Since the pattern for Block-3 is all "1"s I have embedded it into the main loop, which is why it has an offset of 00. This saves 2 bytes by not having to return from Block-3! Luckily I was able to fit the starting locations for all four blocks into less than 128 bytes. This is good because the range of a relative jump is -128 to 127 from the current position, calculated after reading the offset byte. I.e. a `JR` instruction reads two bytes then performs the calculation. `JR 00` does nothing. `JR 01` skips one byte. `JR FF` goes back by one byte causing the next instruction to be the offset of the `JR` just executed, which is really bad because the instruction `FF` is not for the faint hearted! `JR FE` goes back by two bytes causing an infinite loop, etc. However, the jump back from Block-0 is too far (less than -128) so I simply jump back into a previous block, which then jumps again! ``` #### DATA #### :Offsets (&8000) # It is important that this address is of the form &XX00 69 (#Block-0, &808A) 31 (#Block-1, &8052) 18 (#Block-2, &8039) 00 (#Block-3, &8021) :DATA (&8004) DB 42 81 E7 # Magic data #### CODE #### :MAIN (&8008) 21 00 40 .. LD HL, &4000 # Start address of pattern output 11 04 80 .. LD DE, #DATA (&8004) # Load DE with data address 0E 04 .. .. LD C, 4 # Load C with 4 (outer loop) :OUTY (&8010) 06 19 .. .. LD B, 25 # Load B with 25 (outer loop) :INRY (&8012) D5 .. .. .. ! PUSH DE # DE -> Stack, Stack = "DE" (save block pattern address) 1A .. .. .. ! LD A, (DE) # Get block mask (ppoonnmm) :OUTX (&8014) F5 .. .. .. PUSH AF # AF -> Stack, Stack = "DE, AF" (save block mask) C5 .. .. .. PUSH BC # BC -> Stack, Stack = "DE, AF, BC" (save outer loop variables) E6 03 .. .. AND &03 # Get block number (0, 1, 2 or 3). A = 000000XX where each X can be 0 or 1 5F .. .. .. LD E, A # Copy A to E. DE now contains &800X where X is one of (0, 1, 2 or 3) 1A .. .. .. LD A, (DE) # Copy the byte at address pointed to by DE to A 32 20 80 .. LD (&8020!), A # Alter JR instruction in innermost loop with offset of current pattern block 06 19 .. .. LD B, 25 # Load B with 25 (inner loop) :INRX (&801F) 18 00 .. .. JR 00 # (Relative) Jump to overridden pattern block location (Mock CALL). The second byte of this instruction is at address &8020 (see instruction two above) :Block-3 (&8021 + &00 = &8021) 36 31 .. .. LD (HL), 49 # Write ASCII "1" to address in HL :RESUME (&8023) 23 .. .. .. INC HL # Move pointer to next (8 bit) memory location 10 F9 .. .. DJNZ #INRX (&801F) # Repeat B times (end of inner B loop) &8026 C1 .. .. .. POP BC # Stack -> BC, Stack = "DE, AF" F1 .. .. .. POP AF # Stack -> AF, Stack = "DE" E6 FC .. .. AND &FC # Zero out current block number: A = XXXXXX00 where each X can be 0 or 1 0F .. .. .. RRCA # Rotate Right A. (rotate bits to the right by one place. Bit 0 is copied into bit 7) 0F .. .. .. RRCA # Rotate Right A again. The next pattern block is now in bits 1 & 0. 20 E6 .. .. JR NZ, #OUTX (&8014) # If A is Non-Zero (Relative) Jump (Repeat until pattern is empty) &802E 36 0D .. .. LD (HL), 0D # Write "\r" 23 .. .. .. INC HL # Move pointer D1 .. .. .. POP DE # Stack -> DE, Stack = "" 10 DE .. .. DJNZ #INRY (&8012) # Repeat B times (end of outer B loop) &8034 13 .. .. .. INC DE # Move DE to next pattern of blocks 0D .. .. .. DEC C # Decrement C (end of outer C loop) 20 D8 .. .. JR NZ, #OUTY (&8010) # If C is Non-Zero (Relative) Jump (Repeat C times) &8038 C9 .. .. .. RET # Return :Block-2 (&8039) 3E 1A .. .. LD A, 26 # A = 26 90 .. .. .. SUB A, B # A = 26 - x 58 .. .. .. LD E, B # Copy B to E, E = x C1 .. .. .. POP BC # Restore B (& C), B = y C5 .. .. .. PUSH BC # Save B (& C) again D5 .. .. .. PUSH DE # Save (D &) E 58 .. .. .. LD E, B # E = y 47 .. .. .. LD B, A # B = 26 - x 7B .. .. .. LD A, E # A = y 87 .. .. .. ADD A, A # A = 2 * y FE 1A .. .. CP 26 # A - 26 (compare) 38 02 .. .. JR C, 2 # if Carry, skip next instruction D6 19 .. .. SUB A, 25 # A = 2 * y % 25 5F .. .. .. LD E, A # Copy A to E, E = 2 * y % 25, B = 26 - x 80 .. .. .. ADD A, B # A = 2 * y % 25 + 26 - x :Extra-1s FE 1B .. .. CP 27 # A - 27 (compare) 28 34 .. .. JR Z, #Bl1-1 # if Zero, (Relative) Jump to Block-1 "1" :End-Extra-1s 18 0E .. .. JR #BL1a # (Relative) Jump to Block-1a :Block-1 (&8052) 78 .. .. .. LD A, B # A = x C1 .. .. .. POP BC # Restore B (& C), B = y C5 .. .. .. PUSH BC # Save B (& C) again 5F .. .. .. LD E, A # Save A (copy of B) in E, E = x D5 .. .. .. PUSH DE # Save (D &) E 87 .. .. .. ADD A, A # A = 2 * x FE 1A .. .. CP 26 # A - 26 (compare) 38 02 .. .. JR C, 2 # if Carry, skip next instruction D6 19 .. .. SUB A, 25 # A = 2 * x % 25 5F .. .. .. LD E, A # Copy A to E, E = 2 * x % 25, B = y 80 .. .. .. ADD A, B # A = 2 * x % 25 + y :BL1a # From this point on until character written to memory, swap x and y in comments if from Block-2 FE 1A .. .. CP 26 # A - 26 (compare) 28 20 .. .. JR Z, #Bl1-1 # if Zero, (Relative) Jump to Block-1 "1" 30 06 .. .. JR NC, #BL1b # if Non-Carry, (Relative) Jump to Block-1b 90 .. .. .. SUB A, B # A = 2 * x % 25 90 .. .. .. SUB A, B # A = 2 * x % 25 - y 30 1A .. .. JR NC, #Bl1-1 # if Non-Carry, (Relative) Jump to Block-1 "1" 18 14 .. .. JR #Bl1-0 # (Relative) Jump to Block-1 "0" :BL1b 90 .. .. .. SUB A, B # A = 2 * x % 25 90 .. .. .. SUB A, B # A = 2 * x % 25 - y 38 14 .. .. JR C, #Bl1-1 # if Carry, (Relative) Jump to Block-1 "1" FE 01 .. .. CP 1 # A - 1 (compare) 38 10 .. .. JR C, #Bl1-1 # if Carry, (Relative) Jump to Block-1 "1" :Jaggies 20 0A .. .. JR NZ, #Bl1-0 # if Non-Zero, (Relative) Jump to Block-1 "0" 7B .. .. .. LD A, E # A = 2 * x % 25 :MOD5 D6 05 .. .. SUB A, 5 # A = A - 5 30 FC .. .. JR NC, MOD5 # if Non-Carry (A >= 0), (Relative) Jump to #MOD5 C6 05 .. .. ADD 5 # A = 2 * x % 5. A was [-5,-1], needed to add 5 for positive mod 5 0F .. .. .. RRCA # Rotate Right A. Bit 0 is copied into Carry flag 38 04 .. .. JR C, #Bl1-1 # if Carry, (Relative) Jump to Block-1 "1" :End-Jaggies 36 30 .. .. LD (HL), 0 # Write "0" 18 02 .. .. JR #B1-end # Skip next instruction 36 31 .. .. LD (HL), 1 # Write "1" :B1-end D1 .. .. .. POP DE # Restore (D &) E, E = x 43 .. .. .. LD B, E # Restore B from E 18 99 .. .. JR #RESUME (&8023) # (Relative) Jump back into inner loop :Block-0 (&808A) 58 .. .. .. LD E, B # Copy B to E, E = x C1 .. .. .. POP BC # Restore B (& C), B = y C5 .. .. .. PUSH BC # Save B (& C) again 78 .. .. .. LD A, B # A = y 83 .. .. .. ADD A, E # A = y + x FE 0D .. .. CP 13 # A - 13 (compare) 38 26 .. .. JR C, #Bl0-0 # if Carry, (Relative) Jump to Block-0 "0" FE 27 .. .. CP 39 # A - 39 (compare) 30 22 .. .. JR NC, #Bl0-0 # if Non-Carry, (Relative) Jump to Block-0 "0" 93 .. .. .. SUB A, E # A = y 93 .. .. .. SUB A, E # A = y - x 30 04 .. .. JR NC, 4 # if Non-Carry (A >= 0), skip next two instructions FE F3 .. .. CP -13 # A - -13 (compare) 30 04 .. .. JR NC, 4 # if Non-Carry, skip next two instructions FE 0E .. .. CP 14 # A - 14 (compare) 30 16 .. .. JR NC, #Bl0-0 # if Non-Carry, (Relative) Jump to Block-0 "0" 83 .. .. .. ADD A, E # A = y 83 .. .. .. ADD A, E # A = y + x FE 15 .. .. CP 21 # A - 21 (compare) 38 14 .. .. JR C, #Bl0-1 # if Carry, (Relative) Jump to Block-0 "1" FE 20 .. .. CP 32 # A - 32 (compare) 30 10 .. .. JR NC, #Bl0-1 # if Non-Carry, (Relative) Jump to Block-0 "1" 93 .. .. .. SUB A, E # A = y 93 .. .. .. SUB A, E # A = y - x 30 04 .. .. JR NC, 4 # if Non-Carry, skip next two instructions FE FB .. .. CP -5 # A - -5 (compare) 30 04 .. .. JR NC, #Bl0-0 # if Non-Carry, (Relative) Jump to Block-0 "0" FE 06 .. .. CP 6 # A - 6 30 04 .. .. JR NC, #Bl0-1 # if Non-Carry, (Relative) Jump to Block-0 "1" :Bl0-0 (&80B9) 36 30 .. .. LD (HL), 30 # Write "0" 18 02 .. .. JR 2 # Skip next instruction :Bl0-1 (&80BD) 36 31 .. .. LD (HL), 31 # Write "1" 43 .. .. .. LD B, E # Restore B from E 18 C6 .. .. JR -39!=&8041 # (Relative) Jump back into inner loop &80C2 ``` There is certainly room to golf this a bit further. My first fully working version was 239 bytes. 4 bytes can be saved by removing the section "Extra-1s" at the expense of 48 errors and a further 12 bytes can be saved by removing the section "Jaggies" at the expense of 32 errors. [Answer] # Haskell, 201 190 bytes, 44 errors ``` main=mapM_ putStrLn$h++map v(v h) h=[[b$p i j|p<-q,j<-x]|q<-[[a,r,d,a],[r,w,w,d]],i<-x] a i j=abs i+abs j>13 d i j=i>0&&abs j+i<12 r=flip d w _ _=1<3 v=reverse x=[-12..12] b x|x='0'|1<3='1' ``` ![Haskell](https://i.stack.imgur.com/nU4XA.png) Uses a matrix of functions for each different shape: `a` (diamond); `u`, `d`, `l`, `r` (triangles facing each direction) and `w` (white), and applies each to a 25x25 grid with coordinates `[-12..12]`. The diamond and triangle shapes are computed using the Manhattan norm, similar to [flawr's Octave solution](https://codegolf.stackexchange.com/a/49576/1811). Actually only generate the upper half, which needs only `a`, `w`, `d`, and `r`. Produce the lower half through mirroring (`map reverse . reverse`). [Answer] # C# - 423 bytes, 237 errors ![c# identicon](https://i.stack.imgur.com/AnqVz.png) Just piling up inequalities. Most of the errors are due to me substituting t(=25) in places that should be using 24. ``` using System;class A{static void Main(string[]a){for(int t=25,k,l,i,j=0;j<100;j++){for(i=0;i<100;i++){Console.Write((((i>12&&i<87&&j>12&&j<87)||Math.Abs(i-49.5)+Math.Abs(j-49.5)<63)&&!((i>36&&i<63)||(j>36&&j<63)||(i>11&&i<88&&j>t&&j<75)||(j>11&&j<88&&i>t&&i<75)))||(i>t&&i<75&&j>t&&j<75&&(((k=i%t)*2<(l=j%t)&&k*-2+t>l)||(l*2<k&&l*-2+t>k)||((k=t-k)*2<(l=t-l)&&k*-2+t>l)||(l*2<k&&l*-2+t>k)))?"0":"1");}Console.WriteLine();}}} ``` Here is an attempt to visualize how it works: ![process visualization](https://i.stack.imgur.com/zGZlA.png) More readable code: ``` using System; class A { static void Main(string[]a) { for(int t=25,k,l,i,j=0;j<100;j++){for(i=0;i<100;i++){ Console.Write( (((i>12&&i<87&&j>12&&j<87) //big square ||Math.Abs(i-49.5)+Math.Abs(j-49.5)<63) //big diamond &&!((i>36&&i<63)||(j>36&&j<63)||(i>11&&i<88&&j>t&&j<75)||(j>11&&j<88&&i>t&&i<75))) //subtract four central rects ||(i>t&&i<75&&j>t&&j<75 //add the central square &&(((k=i%t)*2<(l=j%t)&&k*-2+t>l) //stars: subtract left sides ||(l*2<k&&l*-2+t>k) //stars: subtract top sides ||((k=t-k)*2<(l=t-l)&&k*-2+t>l) //stars: subtract right sides ||(l*2<k&&l*-2+t>k)) //stars: subtract bottom sides ) ?"0":"1"); }Console.WriteLine();} } } ``` Probably could golf the parens and logical operators a bit, but I'm getting Lisp flashbacks. [Answer] # Perl ~~186~~ ~~184~~ ~~181~~ ~~151~~ 147 bytes, 0 errors ![Perl identicon](https://i.stack.imgur.com/Fh8hB.png) ``` for$y(@i=0..99){$l=24-($k=$_%25-$y%25)-$y%25*2,$c=!($_/25%3)+!($y/25%3),print$c-2?abs$k>5|abs$l>5&&$c:$k<0^$l>0^$_>49^$y>49|!$k|!$l,' 'x/99/ for@i} ``` The code is ~~almost as simple as the image is! I could reduce it by two more bytes by having the pattern start with a newline instead of ending with it but technically it doesn't validate without errors.~~ getting to the point where I'm having a hard time understanding it! [Answer] # JavaScript (ES6), 239 bytes, 99 different ``` f=(c,n=50)=>Array(n).fill().map(c) a=f((e,y)=>f((_,x)=>+((x+y>48&(x+y<68|x+y>80|x<y-6|x>y+6))|x>y-13&x<13&y>11))) f((e,i)=>f((g,j)=>a[i].push(a[49-j][i]))) f((e,i)=>a.push(f((g,j)=>a[49-i][99-j],100))) alert(a.map(e=>e.join('')).join(` `)) ``` This uses inequalities to generates the shapes for one quadrant, and the rest of the code rotates that to fill the others. The text was just `JavaScript`. This is a pretty simple identicon: ![JavaScript identicon](https://i.stack.imgur.com/1H26V.png) Use the snippet below to verify, as it is uses more well-supported JavaScript and outputs in a monospace font. You'll probably have to click "Full page" to see all of it. ``` f=function(c,n){ n=n||50 for(arr=[];n>0;n--)arr.push(undefined) return arr.map(c) } a=f(function(e,y){ return f(function(_,x){ return +((x+y>48&(x+y<68|x+y>80|x<y-6|x>y+6))|x>y-13&x<13&y>11) }) }) f(function(e,i){ f(function(g,j){ a[i].push(a[49-j][i]) }) }) f(function(e,i){ a.push(f(function(g,j){ return a[49-i][99-j] },100)) }) document.getElementById('p').innerHTML=a.map(function(e){return e.join('')}).join('\n') ``` ``` <style>pre{font-size:12px;line-height:100%}</style><pre id="p"></pre> ``` [Answer] # Python 3, ~~975~~ 963 bytes ![python identicon](https://i.stack.imgur.com/HNQMhm.png) ``` Z,L,J=zip,list,''.join;y=[134217727,520093695,2130706431,8573157375,34334572543,137413787647,274848546815,68690116607,17148411903,4262461439,1041235967,235405311,34078719,235405311,1040449535,4261675007,17146445823,68686053375,274844418047,137405431807,34326216703,8556396543,2113945599,503332863,100671487,1125899873288192,562949919866880,562949919866880,562949919866880,281474943156224,281474943156224,140737454800896,140737454800896,70368710623232,35184338534400,35184338534400,17592152489984,17592152489984,17592152489984,8796059467776,8796059467776,4398012956672,4398012956672,2198989701120,1099478073344,1099478073344,549722259456,549722259456,549722259456,274844352512];C=[L(n) for n in map(lambda j:'0'*(50-len(j[2:]))+j[2:],[bin(i) for i in y])];U=L(Z(*C[::-1]));Q=L(Z(*U[::-1]));Y=L(Z(*Q[::-1]));Y=[J(i) for i in Y];Q=[J(i) for i in Q];U=[J(i) for i in U];C=[J(i) for i in C];H=[i+j for i,j in Z(C,U)];R=[i+j for i,j in Z(Y,Q)];r='\n'.join(H+R);print(r) ``` The string printed is `"Python"` at 975 bytes with 30 errors. For `"Python 3"` I used ``` Z,L,J=zip,list,''.join;y=[206183596032,515427532800,1082364788736,2190466744320,4393785065472,8793979084800,17591145854976,35046429810176,69887472902016,139672235548640,279293098729464,558560492658686,1117108092018687,1121510446079998,560768075440120,280409723903968,140256217079680,70230801899008,35183331899392,17590072107008,8791831576576,4389489999872,2181876416512,1065183346688,481061502976,844424930131968,1055531162664960,1108307720798208,1121501860331520,1124800395214848,1125625028935680,1125831187369984,1125607849080832,1123971466558464,1117377618050560,1090990144356096,985437229547392,563224798298048,985437229547456,1090990144356224,1117377618050816,1123971466558976,1125607849081856,1125831187372032,1125625028935680,1124800395214848,1121501860331520,1108307720798208,1055531162664960,844424930131968];C=[L(n) for n in map(lambda j:'0'*(50-len(j[2:]))+j[2:],[bin(i) for i in y])];U=L(Z(*C[::-1]));Q=L(Z(*U[::-1]));Y=L(Z(*Q[::-1]));Y=[J(i) for i in Y];Q=[J(i) for i in Q];U=[J(i) for i in U];C=[J(i) for i in C];H=[i+j for i,j in Z(C,U)];R=[i+j for i,j in Z(Y,Q)];r='\n'.join(H+R);print(r) ``` Which *would* bring it up to 1104 bytes with 124 errors, but I think I'll stick with just `"Python"` unless requested by OP. [Answer] # HTML - ~~223~~ ~~210~~ ~~193~~ 191 bytes, 0 errors ![HTML identicon](https://i.stack.imgur.com/jftKV.png) ``` <!DOCTYPE html><title>A</title><script>D=document;M=Math.abs;for(y=0;b=y%75/25&3,y<100;D.write('<br>'),++y)for(x=0;a=x%75/25&3,x<100;++x)D.write(+!(a+b?a*b:M(x%25-12)+M(y%25-12)>13))</script> ``` 100% valid HTML. Both HTML and JavaScript are quite verbose so despite the simplicity of the identicon the code is still very long. [Answer] ## PowerShell 2.0, 448 399 392 374 349 bytes, 49 errors ![enter image description here](https://i.stack.imgur.com/Xr5oV.png) this is just printing one line at a time, with some fancy meta-replacement/expressions for golfing ``` filter a{switch($_){1{"1"*13;"0"*12}2{"0"*12;"1"*13}3{"1"*25}4{"0"*25}6{"1"*$b;"0"*(25-2*$b);"1"*$b}7{$b--;"0"*$b;"1"*(25-2*$b);"0"*$b}}}$a='1164132c6417dd3317c26317116313164441d847717d3771163441162443d827737d27741624441132362c7236dd7233c27246113246';$x='$($a[$d++])';0..17|%{iex "`"0x$x..0x$x|%{```$b=```$_;```$($x|a;$x|a;$x|a;$x|a)-join''}`""}|iex ``` ungolfed: ``` filter a { switch($_) { 1 { "1"*13; "0"*12 } 2 { "0"*12; "1"*13 } 3 { "1"*25 } 4 { "0"*25 } 6 { "1"*$b; "0"*(25-2*$b); "1"*$b } 7 { $b--; "0"*$b; "1"*(25-2*$b); "0"*$b } } } $a='1164132c6417dd3317c26317116313164441d847717d3771163441162443d827737d27741624441132362c7236dd7233c27246113246'; $x='$($a[$d++])'; 0..17|%{iex "`"0x$x..0x$x|%{```$b=```$_;```$($x|a;$x|a;$x|a;$x|a)-join''}`""}|iex ``` this is what eventually gets piped to `iex`: ``` 0x1..0x1|%{$b=$_;$(6|a;4|a;1|a;3|a)-join''} 0x2..0xc|%{$b=$_;$(6|a;4|a;1|a;7|a)-join''} 0xd..0xd|%{$b=$_;$(3|a;3|a;1|a;7|a)-join''} 0xc..0x2|%{$b=$_;$(6|a;3|a;1|a;7|a)-join''} 0x1..0x1|%{$b=$_;$(6|a;3|a;1|a;3|a)-join''} 0x1..0x6|%{$b=$_;$(4|a;4|a;4|a;1|a)-join''} 0xd..0x8|%{$b=$_;$(4|a;7|a;7|a;1|a)-join''} 0x7..0xd|%{$b=$_;$(3|a;7|a;7|a;1|a)-join''} 0x1..0x6|%{$b=$_;$(3|a;4|a;4|a;1|a)-join''} 0x1..0x6|%{$b=$_;$(2|a;4|a;4|a;3|a)-join''} 0xd..0x8|%{$b=$_;$(2|a;7|a;7|a;3|a)-join''} 0x7..0xd|%{$b=$_;$(2|a;7|a;7|a;4|a)-join''} 0x1..0x6|%{$b=$_;$(2|a;4|a;4|a;4|a)-join''} 0x1..0x1|%{$b=$_;$(3|a;2|a;3|a;6|a)-join''} 0x2..0xc|%{$b=$_;$(7|a;2|a;3|a;6|a)-join''} 0xd..0xd|%{$b=$_;$(7|a;2|a;3|a;3|a)-join''} 0xc..0x2|%{$b=$_;$(7|a;2|a;4|a;6|a)-join''} 0x1..0x1|%{$b=$_;$(3|a;2|a;4|a;6|a)-join''} ``` and this one which is 471 bytes, 104 errors, which uses rotation logic ``` filter x($x,$y){1..$_|%{$t=49-$x;$x=$y;$y=$t};$x;$y}0..9999|%{$i=$_;$x=$i%100;$y=[math]::floor($i/100);if($x-ge50){$x-=50;if($y-ge50){$y-=50;$x,$y=2|x $x $y}else{$x,$y=1|x $x $y}}else{if($y-ge50){$y-=50;$x,$y=3|x $x $y}}if($x-ge25){$x-=25;if($y-ge25){$y-=25;[int]([math]::abs(13-$x)+[math]::abs(12-$y)-lt7)}else{[int]($y-gt11)}}else{if($y-ge25){$y-=25;[int]($y-gt11)}else{[int](($y-le$x-or$y-le24-$x)-and($y-ge$x-or$y-ge24-$x))}}}|%{if($i%100){$s+=$_}else{$s;$s="$_"}};$s ``` (relatively) ungolfed: ``` function rotate($x, $y, $n) { 1..$n|%{ $t = 49-$x $x = $y $y = $t } $x $y } $s='' 0..9999|%{ $i=$_ $x = $i%100 $y = [math]::floor($i/100) if ($x -ge 50) { $x-=50 if ($y -ge 50) { # bottom right $y -= 50 $x,$y = rotate $x $y 2 } else { # top right $x,$y = rotate $x $y 1 } } else {if ($y -ge 50) { # bottom left $y -= 50 $x,$y = rotate $x $y 3 }} if ($x -ge 25) { $x-=25 if ($y -ge 25) { $y-=25 # bottom right [int]([math]::abs(13-$x)+[math]::abs(12-$y) -lt 7) } else { # top right [int]($y -gt 11) } } else { if ($y -ge 25) { $y-=25 # bottom left [int]($y -gt 11) } else { # top left [int](($y -le $x -or $y -le 24-$x) -and ($y -ge $x -or $y -ge 24-$x)) } } }|%{if ($i%100){$s+=$_}else{$s;$s="$_"}};$s ``` [Answer] # Python 2, ~~712~~ 711 bytes This program generates the bit array for 'Python' by using run length encoding and storing runs as characters. ``` a=":>;$ 8'$;8' 6)$;6) 4+$;4+ 2-%:3, 0/%:1. /0&9.1 1.&9,3 3,'8*5 5*(7)6 7((7'8 9&)6$; ;$)O)$.$ 9&)O(%.% 7(*N(&,& 5**N'',' 3,+M'(*( 1.+M&)*) /0,L&*(* 0/-K%+(+ 2--K%,&, 4+.J$-&- 6).J$.$. 8'.V$ :%/ #<m $;j $;h $;f %:e %:c &9` &9^ '8\ (7[ (7Y )6V )6U )6U *5U *5U +4U +4U ,3U -2U -2U .1U .1U .1U /0U #<U0 #<U1 #<U1 #<U2 #<U2 #<U3 #<U3 #<U4 #<U4 #<U5 #<U5 #<U6 #<U6 #;V7 #9X7 #7Z8 #5\8 #3^9 #1`9 #/b: #-d: #+f; #)h; #'j #%l #b/% #c.' $.$V.) $.%-$K-+ %,&-$K-- %+(+%L,/ &*(+%L,0 &*))&M+. '(*)&M+, '(+''N** (&,&(N*( (&-%(O)& )$.%(O)$ <;$7(& <9&7(( <7(8'* <5*8', <3,9&. <1.9&0 </0:%/ <-2:%- <+4;$+ <)6;$) <'8@ <%:>".split() for b in[[ord(c)-35for c in L]for L in a]:print''.join(c*n for c,n in zip('01'*8,b+[100-sum(b)])) ``` Before the auto-golfer, it looked (quite similar!) like: ``` ctext = ":>;$ 8'$;8' 6)$;6) 4+$;4+ 2-%:3, 0/%:1. /0&9.1 1.&9,3 3,'8*5 5*(7)6 7((7'8 9&)6$; ;$)O)$.$ 9&)O(%.% 7(*N(&,& 5**N'',' 3,+M'(*( 1.+M&)*) /0,L&*(* 0/-K%+(+ 2--K%,&, 4+.J$-&- 6).J$.$. 8'.V$ :%/ #<m $;j $;h $;f %:e %:c &9` &9^ '8\ (7[ (7Y )6V )6U )6U *5U *5U +4U +4U ,3U -2U -2U .1U .1U .1U /0U #<U0 #<U1 #<U1 #<U2 #<U2 #<U3 #<U3 #<U4 #<U4 #<U5 #<U5 #<U6 #<U6 #;V7 #9X7 #7Z8 #5\8 #3^9 #1`9 #/b: #-d: #+f; #)h; #'j #%l #b/% #c.' $.$V.) $.%-$K-+ %,&-$K-- %+(+%L,/ &*(+%L,0 &*))&M+. '(*)&M+, '(+''N** (&,&(N*( (&-%(O)& )$.%(O)$ <;$7(& <9&7(( <7(8'* <5*8', <3,9&. <1.9&0 </0:%/ <-2:%- <+4;$+ <)6;$) <'8@ <%:>".split() for seq in [[ord(c)-35 for c in L] for L in ctext] : print ''.join(c*n for c,n in zip('01'*8, seq + [100 - sum(seq)])) ``` This RLE method should result in zero errors. The identicon array for 'python' looks much easier, but I thought it would be cheating if I used that. [Answer] # IDL, 472 bytes, 290 errors Ugh. This would be much shorter if I could store functions as variables, or do multiple string replacements at once, etc. ``` v=execute(repstr(repstr(repstr("n=25&a=12&b=24&r='IDLanROI'&x=rebin([0:b],n,n,/s)&y=#x,4)&w=.5*(x-1)&h=(y ge w@y lt b-.5*x)@~(y ge a-w@y lt a+w@x lt a)&i=reform((obj_new(r,[0,a,13,b,b,18,a,6,a,a,11,0],[a,0,0,11,a,a,6,a,18,b,b,a^,n,n)&j=reform(~((obj_new(r,[a,7,a,13,17,17,a],[7,a,17,17,13,a,7^),n,n)&print,string([[h,i,#i,1),#h,1)],[i,j,j,#i,1)],[#i,3),j,j,#i,2)],[#h,3),#i,3),#i,2),#h,2)]],'(100I1)')",'@',' and '),'#','rotate('),'^','])).containspoints(x,y)<1')) ``` ![enter image description here](https://i.stack.imgur.com/Cwbcx.png) ``` 1100000000000000000000000000000000000110000000000000000000000010000000000000111111111111111111111111 1111000000000000000000000000000000001111000000000000000000000111000000000000111111111111111111111111 1111110000000000000000000000000000011111100000000000000000001111100000000000011111111110111111111110 1111111100000000000000000000000000111111110000000000000000011111110000000000011111111110011111111110 1111111111000000000000000000000001111111111000000000000000111111111000000000001111111100011111111100 1111111111110000000000000000000011111111111100000000000001111111111100000000001111111100001111111100 1111111111111100000000000000000111111111111110000000000011111111111110000000000111111000001111111000 1111111111101111000000000000001111111011111111000000000111111101111111000000000111111000000111111000 1111111110001111110000000000011111110001111111100000001111111000111111100000000011110000000111110000 1111111000001111111100000000111111100000111111110000011111110000011111110000000011110000000011110000 1111100000001111111111000001111111000000011111111000111111100000001111111000000001100000000011100000 1110000000001111111111110011111110000000001111111111111111000000000111111100000001100000000001100000 1100000000001111111111110111111100000000000111111111111110000000000011111110000000111111111111000000 1111000000001111111111000011111110000000000000000000000000000000000111111110000000111111111111000000 1111110000001111111100000001111111000000000000000000000000000000001111111100000000011111111110000000 1111111100001111110000000000111111100000000000000000000000000000011111111000000000011111111110000000 1111111111001111000000000000011111110000000000000000000000000000111111110000000000001111111100000000 1111111111111100000000000000001111111000000000000000000000000001111111100000000000001111111100000000 1111111111110000000000000000000111111100000000000000000000000011111111000000000000000111111000000000 1111111111000000000000000000000011111100000000000000000000000011111110000000000000000111111000000000 1111111100000000000000000000000001111100000000000000000000000011111100000000000000000011110000000000 1111110000000000000000000000000000111100000000000000000000000011111000000000000000000011110000000000 1111000000000000000000000000000000011100000000000000000000000011110000000000000000000001100000000000 1100000000000000000000000000000000001100000000000000000000000011100000000000000000000001100000000000 0000000000000000000000000000000000001100000000000000000000000011000000000000000000000000000000000000 0000000000001100000000000111111111111111111111111111111111111111111111111110000000000001000000000000 0000000000011110000000000111111111111111111111111111111111111111111111111110000000000011100000000000 0000000000111111000000000111111111111111111111111111111111111111111111111110000000000111110000000000 0000000001111111100000000111111111111111111111111111111111111111111111111110000000001111111000000000 0000000011111111110000000111111111111111111111111111111111111111111111111110000000011111111100000000 0000000111111111111000000111111111111111111111111111111111111111111111111110000000111111111110000000 0000001111111111111100000111111111111111111111111111111111111111111111111110000001111111111111000000 0000011111110111111110000111111111111011111111111111111111111101111111111110000011111110111111100000 0000111111100011111111000111111111110001111111111111111111111000111111111110000111111100011111110000 0001111111000001111111100111111111100000111111111111111111110000011111111110001111111000001111111000 0011111110000000111111110111111111000000011111111111111111100000001111111110011111110000000111111100 0111111100000000011111111111111110000000001111111111111111000000000111111111111111100000000011111110 1111111000000000001111111111111100000000000111111111111110000000000011111111111111000000000001111111 0111111100000000000000000111111110000000000111111111111111000000000011111110000000000000000011111111 0011111110000000000000000111111111000000001111111111111111100000000111111110000000000000000111111110 0001111111000000000000000111111111100000011111111111111111110000001111111110000000000000001111111100 0000111111100000000000000111111111110000111111111111111111111000011111111110000000000000011111111000 0000011111110000000000000111111111111001111111111111111111111100111111111110000000000000111111110000 0000001111111000000000000111111111111111111111111111111111111111111111111110000000000001111111100000 0000000111111000000000000111111111111111111111111111111111111111111111111110000000000001111111000000 0000000011111000000000000111111111111111111111111111111111111111111111111110000000000001111110000000 0000000001111000000000000111111111111111111111111111111111111111111111111110000000000001111100000000 0000000000111000000000000111111111111111111111111111111111111111111111111110000000000001111000000000 0000000000011000000000000111111111111111111111111111111111111111111111111110000000000001110000000000 0000000000011000000000000111111111111111111111111111111111111111111111111110000000000001100000000000 0000000000011000000000000111111111111111111111111111111111111111111111111110000000000001100000000000 0000000000111000000000000111111111111111111111111111111111111111111111111110000000000001100000000000 0000000001111000000000000111111111111111111111111111111111111111111111111110000000000001110000000000 0000000011111000000000000111111111111111111111111111111111111111111111111110000000000001111000000000 0000000111111000000000000111111111111111111111111111111111111111111111111110000000000001111100000000 0000001111111000000000000111111111111111111111111111111111111111111111111110000000000001111110000000 0000011111111000000000000111111111111111111111111111111111111111111111111110000000000001111111000000 0000111111110000000000000111111111111011111111111111111111111101111111111110000000000000111111100000 0001111111100000000000000111111111110001111111111111111111111000111111111110000000000000011111110000 0011111111000000000000000111111111100000111111111111111111110000011111111110000000000000001111111000 0111111110000000000000000111111111000000011111111111111111100000001111111110000000000000000111111100 1111111100000000000000000111111110000000001111111111111111000000000111111110000000000000000011111110 1111111000000000001111111111111100000000000111111111111110000000000011111111111111000000000001111111 0111111100000000011111111111111110000000000111111111111111000000000011111111111111100000000011111110 0011111110000000111111100111111111000000001111111111111111100000000111111110111111110000000111111100 0001111111000001111111000111111111100000011111111111111111110000001111111110011111111000001111111000 0000111111100011111110000111111111110000111111111111111111111000011111111110001111111100011111110000 0000011111110111111100000111111111111001111111111111111111111100111111111110000111111110111111100000 0000001111111111111000000111111111111111111111111111111111111111111111111110000011111111111111000000 0000000111111111110000000111111111111111111111111111111111111111111111111110000001111111111110000000 0000000011111111100000000111111111111111111111111111111111111111111111111110000000111111111100000000 0000000001111111000000000111111111111111111111111111111111111111111111111110000000011111111000000000 0000000000111110000000000111111111111111111111111111111111111111111111111110000000001111110000000000 0000000000011100000000000111111111111111111111111111111111111111111111111110000000000111100000000000 0000000000001000000000000111111111111111111111111111111111111111111111111110000000000011000000000000 0000000000000000000000000000000000001100000000000000000000000110000000000000000000000000000000000000 0000000000011000000000000000000000011100000000000000000000001110000000000000000000000000000000000011 0000000000011000000000000000000000111100000000000000000000011110000000000000000000000000000000001111 0000000000111100000000000000000001111100000000000000000000111110000000000000000000000000000000111111 0000000000111100000000000000000011111100000000000000000001111110000000000000000000000000000011111111 0000000001111110000000000000000111111100000000000000000011111110000000000000000000000000001111111111 0000000001111110000000000000001111111100000000000000000111111110000000000000000000000000111111111111 0000000011111111000000000000011111111000000000000000001111111100000000000000000000000011111111111111 0000000011111111000000000000111111110000000000000000011111111000000000000000000000001111001111111111 0000000111111111100000000001111111100000000000000000111111110000000000000000000000111111000011111111 0000000111111111100000000011111111000000000000000001111111100000000000000000000011111111000000111111 0000001111111111110000000111111110000000000000000011111111000000000000000000001111111111000000001111 0000001111111111110000000111111100000000000111111111111110000000000011111110111111111111000000000011 0000011000000000011000000011111110000000001111111101111111000000000111111110111111111111000000000111 0000011100000000011000000001111111000000011111110000111111100000001111111000001111111111000000011111 0000111100000000111100000000111111100000111111100000011111110000011111110000000011111111000001111111 0000111110000000111100000000011111110001111111000000001111111000111111100000000000111111000111111111 0001111110000001111110000000001111111011111110000000000111111101111111000000000000001111011111111111 0001111111000001111110000000000111111111111100000000000011111111111110000000000000000011111111111111 0011111111000011111111000000000011111111111000000000000001111111111100000000000000000000111111111111 0011111111100011111111000000000001111111110000000000000000111111111000000000000000000000001111111111 0111111111100111111111100000000000111111100000000000000000011111110000000000000000000000000011111111 0111111111110111111111100000000000011111000000000000000000001111100000000000000000000000000000111111 1111111111111111111111110000000000001110000000000000000000000111000000000000000000000000000000001111 1111111111111111111111110000000000000100000000000000000000000010000000000000000000000000000000000011 ``` [Answer] # PHP - ~~417~~ ~~414~~ ~~413~~ 410 bytes, 0 errors, (~~2~~ 0 warnings!) ![PHP identicon](https://i.stack.imgur.com/MabAB.png) ``` <?eval(preg_replace(['/[&|]/','/[a-z]/'],['$0$0','$$0'],"FOR(y=0,r=49+s=1+t=99;y<s;++y,PRINT' ')FOR(x=0;u=2*x-y,v=2*x+y,w=x-2*y,z=x+2*y,x<s;++x)ECHO-(w<-150&z<198|u>0&v<49|w>51&z>t|u<t&v>249|x<50&(w>26&z>49|z>74&(w>1|x<25&(w>-49|z>t&w>-74)))|y<50&(v>224&u<r|u<124&(v>199|y<25&(v>r|v>124&u<t)))|y>49&(v<74&u>-50|u>-25&(v<t|y>74&(v<r|v<174&u>0)))|x>49&(z<248&w<-125|z<223&(w<-s|x>74&(w<-50|w<-25&z<198))))+1;")); ``` Requires PHP>=5.4. PHP allows its keywords to be any case so I have used uppercase for keywords and lowercase for variables within the golfed code. `preg_replace` is only used to ungolf the code and `eval` to run it. I removed `$` from all variables and reinserted them with a regex. I also changed each instance of `&&` and `||` to `&` and `|` and doubled them with a regex. I can't do the same trick for `++` because I also use `+` that I don't want doubled. I tried reversing the logic to get rid of the `-` just after `echo` but it changed too many `99`s into `100`s. However, I did manage to avoid using a single space! I was able to apply [Ismael Miguel's](https://codegolf.stackexchange.com/users/14732/ismael-miguel) suggestion to the other set of `{}` braces for the `for` loop too, however, I had to use `print` instead of `echo`. `print` and `echo` are both language constructs ("magic" keywords that don't need parentheses `()`) and are therefore not allowed inside a `for` declaration. However, since `print` has a return value like a function does, it is allowed inside the `for`. By moving the variable assignments from the third to the second section I was able to eliminate the warnings, too! [Answer] # [Pip](http://github.com/dloscutoff/pip), 116 bytes (96 errors) ![Pip identicon](https://i.stack.imgur.com/LfzzI.png) Newlines are for formatting purposes only and have no effect on the code: ``` l:24-_*2 b:1X25RL25 t:0Xl.1X25-lM,13 tAL:t@>1 g:(b@<13AL(1X12-_RL2J0X2*_+1M,12)).tALt.b Fi,50Fj,50g@i.:(g50-j-1i) PgJ:n RVg ``` Slightly ungolfed with comments: ``` l: 24-_*2 Lambda function for use in calculating t b: (1 X 25) RL 25 25x25 block of 1s t: (0 X l).(1 X (25-l)) M ,13 One of the skinny white triangles t AL: t@>1 Append t[1:] to t, so as to have two triangles w: (1 X 12-_) RL 2 J (0 X 2*_+1) M ,12 The white wedge shape g: (b@<13 AL w).t AL t.b Build top left quadrant Fi ,50 Fj ,50 g@i .: g@(50-j-1)@i Copy, rotating, and add as top right quadrant P(g J: n) Join on newline and print as top half RV g Reverse top half for bottom half (auto-printed) ``` The code builds the identicon as a list of strings. Once you know that `X` is string multiplication, `RL` is repeat list, `AL` append list, and `J` join, it's fairly readable (IMHO). The variables `b`, `t`, and `w` (in the ungolfed version) correspond to the following parts of the identicon: ![Part 1](https://i.stack.imgur.com/ujg0t.png) ![Part 2](https://i.stack.imgur.com/Q0Skz.png) ![Part 3](https://i.stack.imgur.com/t2mvz.png) The top left quadrant is put together like so: `Wt` `tb` where `W` represents 13 lines of `b` placed on top of `w`. We then rotate and reverse to get the rest of the figure. The errors result from how we generate the skinny white triangles (second piece above). They're not exactly the same size--one has odd numbers of white pixels and the other has even numbers--but treating them as being the same (sans the top row of the bottom one, to total 25 rows) saves a few bytes. Here's a 122-byte version that does the even-odd stairstepping correctly (0 errors): ``` f:25 l:23-_*2+f*(_>12) b:1XfRLf t:(0Xl.1Xf-l)@<fM,f g:(b@<13AL(1X12-_RL2J0X2*_+1M,12)).tALt.b Fi,50Fj,50g@i.:(g50-j-1i) PgJ:nRVg ``` And, just for fun, a Python translation of the original (not golfed): ``` l = lambda a: 24 - a * 2 b = ["1" * 25] * 25 t = list(map(lambda a: "0"*l(a) + "1"*(25-l(a)), range(13))) t += t[1:] w = list(map(lambda a: ("0"*(2*a+1)).join(["1"*(12-a)]*2), range(12))) g = list(map(str.__add__, b[:13] + w, t)) + list(map(str.__add__, t, b)) for i in range(50): for j in range(50): g[i] += g[50-j-1][i] g = "\n".join(g) print(g) print(g[::-1]) ``` [Answer] # Ruby, 324 bytes, 216 errors ![identicon for Ruby](https://i.stack.imgur.com/smxmm.png) Identicon uses the string `Ruby`, and I kind of like it. Pure geometry + symmetry. Edge equations for the triangle, rotation by 45゜ for the rectangles to make them axis aligned. About 100 errors have been sacrificed for a few bytes less. ``` A=[] 5.times{|b|0.upto(49){|j|b<2&&A<<[0]*50&&next 0.upto(49){|i|A[99-j][i]=A[j][99-i]=A[i][j]=A[99-i][99-j]=A[i][j] i<25&&j>24?0:next A[i][j]=2*j-i<50?0:j>37&&i>13&&j-i+2<26?0:1 b<3&&A[j-13][24-i]=A[i][j] A[i+=25][j-25]=A[i-25][j] x=i-j y=i+j A[i][j]=x>-7&&x<7&&y>67&&y<81||x<-12||x>12||y<63||y>86?1:0}}} puts A.map(&:join) ``` [Answer] # [///](https://esolangs.org/wiki////), 1319 bytes, 0 errors [![enter image description here](https://i.stack.imgur.com/TC2MV.png)](https://i.stack.imgur.com/TC2MV.png) ``` /=/gD//_/QPG//-/NAN//)/N0M//(/M0F//*/LCL//&/GTQ//%/GRG//$/GIG//#/DPK//@/BcQ//!/BH//z/BAQ//y/CI//x/AP//w/ALOK//v/ALIL//u/NRM//t/CR//s/SRS//r/NPN//q/MIM//p/GcG//o/DAAD//n/CP//m/C0//l/1AFK//k/CT//j/CE//i/FAF//h/CH//g/CO//f/AO//e/FMHFM//d/FD//c/AH//b/FF//a/QH1HQ//Z/LHBHL//Y/KHGHK//X/DHMHD//W/1HSH1//V/BHKHB//U/JA//T/EE//S/F1//R/E0//Q/B1//P/IE//O/I0//N/G1//M/GD//L/DD//K/D1//J/CA//I/AE//H/A0//G/BD//F/BB//E/00//D/11//C/AAA//B/11111//A/00000/bBAIFKUbB sfdUs ifdUi qxSUq rxSUr pCFUp aCFUa VmMUV ZmMUZ YjNUY XjNUX WtGUW lnGUlH WkQgKHSH1 XkQhQHMHD YJBkMHGHK ZJBjdH!L VhLCFV ahLfFNH1HQ pyKcFScG ryKPbLPN q=IbGIM i=Abi sn1RbFKRS d0dn10bFQ0d AIFL=g1U fd0DkK0DkKU fd0*E*JH xSE@R@JH xSE$T$JI CFRuAuJI CFReJO mMT)I)JO mMT%O%JP jNAzPzJP jNvAvCC tGH#c#CC tGt1n1Cm kQHocoJOD kQwAwJHL JBA!BP!BgQ JBT&O&hN hLTNENINENtF hLRemd yKR(A(fFL yKE-T-cFQ =E_R_OFN =0BfBEBf!b n10KjL0KjLRbD nKhLhD0bL bQ==n bKRDkK0DkLn FSA*E*0Dg FMO@R@0Dg FGAA$T$EKy FBfuAuEKy FKCeRLh St)I)RLh MJ%O%TBJ GgzPzTBJ BULILAvAQk KJO#c#AQk 1CJI1n1HGt CmocoAGt CCLOKAwANj CC!BP!BTNj JP&O&TMm JPNENINEum JOeRFC JO(A(EFC JI-T-ESx JI_R_0Sx JHBfBEBfB0df JHKjL0KjFQf UDhLhFBAI bbSnbB SRbFLE1ns FAbSTDgi MIbNHDgq NPbBOKyr GcbDAAKyp QH1HFMAILha !KHFQxLhV LH!FKmBJZ KHGHFtBJY DHMHGJQkX 1HSHLyQkW lH1nGtlH WUGtW XUNjX YUNjY ZUMmZ VUMmV aUFCa pUFCp rUSxr qUSxq iUdfi sUdfs d0dUFKAId0d ``` [Try it online!](http://slashes.tryitonline.net/#code=Lz0vZ0QvL18vUVBHLy8tL05BTi8vKS9OME0vLygvTTBGLy8qL0xDTC8vJi9HVFEvLyUvR1JHLy8kL0dJRy8vIy9EUEsvL0AvQmNRLy8hL0JILy96L0J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zBEa0xuCkZTQSpFKjBEZwpGTU9AUkAwRGcKRkdBQSRUJEVLeQpGQmZ1QXVFS3kKRktDZVJMaApTdClJKVJMaApNSiVPJVRCSgpHZ3pQelRCSgpCVUxJTEF2QVFrCktKTyNjI0FRawoxQ0pJMW4xSEd0CkNtb2NvQUd0CkNDTE9LQXdBTmoKQ0MhQlAhQlROagpKUCZPJlRNbQpKUE5FTklORXVtCkpPZVJGQwpKTyhBKEVGQwpKSS1ULUVTeApKSV9SXzBTeApKSEJmQkVCZkIwZGYKSkhLakwwS2pGUWYKVURoTGhGQkFJCmJiU25iQgpTUmJGTEUxbnMKRkFiU1REZ2kKTUliTkhEZ3EKTlBiQk9LeXIKR2NiREFBS3lwClFIMUhGTUFJTGhhCiFLSEZReExoVgpMSCFGS21CSloKS0hHSEZ0QkpZCkRITUhHSlFrWAoxSFNITHlRa1cKbEgxbkd0bEgKV1VHdFcKWFVOalgKWVVOalkKWlVNbVoKVlVNbVYKYVVGQ2EKcFVGQ3AKclVTeHIKcVVTeHEKaVVkZmkKc1VkZnMKZDBkVUZLQUlkMGQ&input=) This took me around 2 hours to make, because I was manually replacing stuff. The biggest thing I made in ///. Probably I can golf a few more bytes. Also, [see Erik the Golfer's answer in /// (4 bytes shorter than mine).](https://codegolf.stackexchange.com/a/95437/41024) [Answer] # Fortran, 214 bytes, 200 errors ![Identicon for the string "Fortran"](https://i.stack.imgur.com/wT45Z.png) Fortran may not be the first choice for code golf, but its identicon looked so simple that I thought I would give it a try. In fact I cannot compete with some of the terser languages, but using implicit variables and other such niceties (e.g., `-` doubles as `xor`), it is not so bad — I got it down to 214 bytes: ``` logical A(-12:87,-12:87) do 1 r=-12,12 do 1 s=-12,12 x=abs(r) y=abs(s) l=x+y<6 k=(x<y/2+7.and.y<x/2+7)-l A((/r+25,r+50/),(/s,s+75/))=k A((/r,r+75/),(/s+25,s+50/))=k 1A((/r,r+75/),(/s,s+75/))=l print'(100I1)',-A end ``` Note: This will not work with `gfortran`. It compiles with `ifort` if you give the file a `.f90` extension (this activates free form source). [Answer] # Perl - ~~3244~~ ~~3188~~ ~~1609~~ 1387 bytes, ~~0~~ ~~13~~ ~~66~~ 78 errors It took me a little while to realize it, but the icon is symmetrical. Also, I can just print a newline after every 100 characters rather than hard-coding it. ``` @i=qw(1;76 0;24 1;77 0;21 1;2 1;78 0;22 1;79 0;21 0;4 1;17 0;4 1;55 0;20 1;81 0;13 1;6 0;6 1;13 0;6 1;57 0;11 1;7 0;7 1;11 0;7 1;12 0;1 1;45 0;9 1;8 0;8 1;9 0;8 1;11 0;3 1;22 0;3 1;20 0;7 1;9 0;9 1;7 0;9 1;10 0;5 1;20 0;5 1;20 0;5 1;10 0;10 1;5 0;10 1;9 0;7 1;18 0;7 1;20 0;3 1;11 0;11 1;3 0;11 1;8 0;9 1;16 0;9 1;20 0;1 1;12 0;12 1;1 0;12 1;7 0;11 1;14 0;11 1;32 0;11 1;3 0;11 1;8 0;9 1;16 0;9 1;33 0;10 1;5 0;10 1;9 0;7 1;18 0;7 1;20 0;3 1;11 0;9 1;7 0;9 1;10 0;5 1;20 0;5 1;20 0;5 1;10 0;8 1;9 0;8 1;11 0;3 1;22 0;3 1;20 0;7 1;9 0;7 1;11 0;7 1;12 0;1 1;24 0;1 1;20 0;9 1;8 0;6 1;13 0;6 1;57 0;11 1;7 0;5 1;15 0;5 1;56 0;13 1;6 0;4 1;17 0;4 1;55 0;15 1;5 0;3 1;19 0;3 1;54 0;17 1;4 0;2 1;21 0;2 1;53 0;19 1;3 0;1 1;23 0;1 1;52 0;21 1;2 1;76 0;23 1;1 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;12 0;1 1;12 0;50 1;12 0;1 1;12 1;11 0;3 1;11 0;50 1;11 0;3 1;11 1;10 0;5 1;10 0;50 1;10 0;5 1;10 1;9 0;7 1;9 0;50 1;9 0;7 1;9 1;8 0;9 1;8 0;50 1;8 0;9 1;8 1;7 0;11 1;7 0;50 1;7 0;11 1;7 1;8 0;9 1;8 0;50 1;8 0;9 1;8 1;9 0;7 1;9 0;50 1;9 0;7 1;9 1;10 0;5 1;10 0;50 1;10 0;5 1;10 1;11 0;3 1;11 0;50 1;11 0;3 1;11 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25 1;25 0;50 1;25);$n=0;for(@i,reverse@i){@p=split';';$n+=$p[1];print $p[0]x int($p[1]);if($n>=100){print"\n";$n=0}} ``` Generates the text for this: ![Perl](https://www.gravatar.com/avatar/0114ad06d728f1834e36fe1a39574ef4?&s=100&d=identicon) [Answer] # [///](http://esolangs.org/wiki////), 1315 bytes, 0 errors ![///](https://www.gravatar.com/avatar/884a6325c5f164f3cc6d5f97bd3e3231?&s=100&d=identicon) ``` /-/\/\///O/00000-I/11111-o/OOO-i/11-@/000-!/II-8/O0-|/Ii-*/O@-+/0|-_/i1-=/oO-#/ii-$/I1-%/|i-^/!1-&/*0-2/+1-3/=O-4/I8_8I-5/!!-6/#8I8#-7/$818$-9/18^81-A/_8|8_-B/i8%8i-C/o@-D/O8-d/o8-E/o0-F/|1-g/+i-H/O*-h/o*-j/!%8!%-k/!i-l/!O!-m/#80#-n/0_-p/1O!_-q/^@^-r/iOOi-s/0$-t/ =-u/%8g-v/o&-w/|D|-x/ F*2-y/#*_O-z/#o#0-Z/0IHI-Y/E0/5i_D0!_35I qHk3q lHk3l uO&^3uxO&^3F*2 wo!3w 7o!37 4og34 6og36 AE23A BE23B 9C|39 ph+3p8 9Csh_8^81 BCsd$8%8i A=ICg8|8_ 6=IYk8I8# 4d#o!4 7d#H!F818$ wdnD!^D|xdn&5#*2 uhi805|8g lhiO5l qv1@5!_@^ k0kv105!$0k D0!#hih13 Hk0iCn0iCn3 Hk0z0#o#=8 O&^00ID$@ID$=8 O&^0+8+@+8+=80 o!@F@%OF@%=80 o!@j=* og@2g82g=* og@+@|*|@|=& E2OIO$&IO$=& E2OmOOmoo C|8i&_Di&_oo C|C1v1oE Cs8rDr=*i CsOyO#*_=8#tIOI8I&I8Ih$tI@+@s*|@sdF d#@2028202C! d#@jEk dn@%0!O%0!H!# dn02OF@2OFD!$ hi0s*+@$*+*!F hiZ0Z85 v1nY#nY#@5i v_d#di05# 5$hihiv 5_@iCn0iC0#v !^Oz0zih !%*ID$@ID$0ih !|OO|8+@+8+0nd0 !IHF@%OF@%0nd0 !_oj@#d ^CFg82g@#d %=|@|*|@|@0I= |hIO$&IO$@0I= I3mOOmO$C0 _=*i&_Di&_O$C0 1o=801v18|C oErDrO|C ooyOyFY ooI8I&I8I@2Yt*+@s*|@s@gEt*2028202@%Et*j@!ot*%0!O%0!00!ot82OF@2OF00^O&t8s*+@$*+0^O&t8IHI0Z0kHt8_Y#nY!$H 3id#d!ID0 55^v5I ^@5!#001vq !O5^@0ihl %805F8ihu F&5I*_d2*2 |D5iOO_d+D| $818!%D0#d7 I8_8!$O&#d4 #8I8!_EI=6 _8|8!CI=A i8%8|=$C0B 18^8#dsC09 p81h+Cp8 93|C9 B3FYB A3FYA 63%E6 43%E4 73!o7 w3!owx3^H2*2 u3^Hg8g l3kHl q3kHq k0k3!_D0k0k ``` [Try it online!](http://slashes.tryitonline.net/#code=Ly0vXC9cLy8vTy8wMDAwMC1JLzExMTExLW8vT09PLWkvMTEtQC8wMDAtIS9JSS04L08wLXwvSWktKi9PQC0rLzB8LV8vaTEtPS9vTy0jL2lpLSQvSTEtJS98aS1eLyExLSYvKjAtMi8rMS0zLz1PLTQvSThfOEktNS8hIS02LyM4STgjLTcvJDgxOCQtOS8xOF44MS1BL184fDhfLUIvaTglOGktQy9vQC1EL084LWQvbzgtRS9vMC1GL3wxLWcvK2ktSC9PKi1oL28qLWovISU4ISUtay8haS1sLyFPIS1tLyM4MCMtbi8wXy1wLzFPIV8tcS9eQF4tci9pT09pLXMvMCQtdC8KPS11LyU4Z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GtIdDhfWSNuWSEkSAozaWQjZCFJRDAKNTVedjVJCl5ANSEjMDAxdnEKIU81XkAwaWhsCiU4MDVGOGlodQpGJjVJKl9kMioyCnxENWlPT19kK0R8CiQ4MTghJUQwI2Q3Ckk4XzghJE8mI2Q0CiM4STghX0VJPTYKXzh8OCFDST1BCmk4JTh8PSRDMEIKMTheOCNkc0MwOQpwODFoK0NwOAo5M3xDOQpCM0ZZQgpBM0ZZQQo2MyVFNgo0MyVFNAo3MyFvNwp3MyFvd3gzXkgyKjIKdTNeSGc4ZwpsM2tIbApxM2tIcQprMGszIV9EMGswaw) This is the identicon for `///`. It's possibly the biggest thing I've ever done in ///! [Answer] # IDL 8.4, 333 bytes, 105 errors This gave a different identicon, and I was able to golf it considerably more using an entirely different method. ![IDL 8.4 identicon](https://i.stack.imgur.com/ZLBKo.png) ``` b=byte('AKMLOJMLPIMLQHMLRGMLSFMLTEMLUDMLVCMLWBMLXAMLfLfLNKBWOJCVPIDUQHETRGFSSFGRTEHQUDIPVCJOWBKNXALMfLMLfLfLfLfLfLfLfLTLFLTLFLTLFLTLFLTLFLTLFLTLFLTLFLTLFLTLFLTLFLTLFLfLfLfLfLfLf')-64 f=[] for i=1,169 do f=[f,replicate(i mod 2,b[i-1])] f=reform(f,50,50) print,[[rotate(f,4),rotate(f,5)],[rotate(f,7),rotate(f,6)]],format='(100I1)' end ``` First, convert the characters in line 1 to byte values and subtract 64 (so that A = 1, B = 2, etc.). Then, stick those many consecutive 1s and 0s into a array, and reform it into 50x50 (i.e., the upper left quadrant, but transposed). Then, transpose & rotate it 4 times, stitch them together, and print it. ``` 1111111111111111111111111000000000000000000000000011111111111110000000000001111111111111000000000001 0111111111111011111111111000000000000000000000000011111111111110000000000001111111111111000000000011 0011111111111001111111111000000000000000000000000011111111111110000000000001111111111111000000000111 0001111111111000111111111000000000000000000000000011111111111110000000000001111111111111000000001111 0000111111111000011111111000000000000000000000000011111111111110000000000001111111111111000000011111 0000011111111000001111111000000000000000000000000011111111111110000000000001111111111111000000111111 0000001111111000000111111000000000000000000000000011111111111110000000000001111111111111000001111111 0000000111111000000011111000000000000000000000000011111111111110000000000001111111111111000011111111 0000000011111000000001111000000000000000000000000011111111111110000000000001111111111111000111111111 0000000001111000000000111000000000000000000000000011111111111110000000000001111111111111001111111111 0000000000111000000000011000000000000000000000000011111111111110000000000001111111111111011111111111 0000000000011000000000001000000000000000000000000011111111111110000000000001111111111111111111111111 1111111111111111111111111111111111111111111111111111111111111110000000000001111111111111111111111111 1111111111111111111111111111111111111111111111111111111111111110000000000000000000000011000000000001 1111111111111011111111111111111111111111111111111111111111111110000000000000000000000111000000000011 1111111111111001111111111111111111111111111111111111111111111110000000000000000000001111000000000111 1111111111111000111111111111111111111111111111111111111111111110000000000000000000011111000000001111 1111111111111000011111111111111111111111111111111111111111111110000000000000000000111111000000011111 1111111111111000001111111111111111111111111111111111111111111110000000000000000001111111000000111111 1111111111111000000111111111111111111111111111111111111111111110000000000000000011111111000001111111 1111111111111000000011111111111111111111111111111111111111111110000000000000000111111111000011111111 1111111111111000000001111111111111111111111111111111111111111110000000000000001111111111000111111111 1111111111111000000000111111111111111111111111111111111111111110000000000000011111111111001111111111 1111111111111000000000011111111111111111111111111111111111111110000000000000111111111111011111111111 1111111111111000000000001111111111111111111111111111111111111110000000000001111111111111111111111111 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000000000000000000111111100000000000011111111111100000000000011111111111111111111000000000000 0000000000000000000000000111111100000000000011111111111100000000000011111111111111111111000000000000 0000000000000000000000000111111100000000000011111111111100000000000011111111111111111111000000000000 0000000000000000000000000111111100000000000011111111111100000000000011111111111111111111000000000000 0000000000000000000000000111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111100000000000011111111111100000000000011111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111111111111111111111111111111 0000000000001111111111111111111100000000000011111111111100000000000011111110000000000000000000000000 0000000000001111111111111111111100000000000011111111111100000000000011111110000000000000000000000000 0000000000001111111111111111111100000000000011111111111100000000000011111110000000000000000000000000 0000000000001111111111111111111100000000000011111111111100000000000011111110000000000000000000000000 0000000000001111111111111111111100000000000011111111111100000000000011111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 0000000000001111111111111111111111111111111111111111111111111111111111111110000000000000000000000000 1111111111111111111111111000000000000111111111111111111111111111111111111111000000000001111111111111 1111111111101111111111110000000000000111111111111111111111111111111111111111100000000001111111111111 1111111111001111111111100000000000000111111111111111111111111111111111111111110000000001111111111111 1111111110001111111111000000000000000111111111111111111111111111111111111111111000000001111111111111 1111111100001111111110000000000000000111111111111111111111111111111111111111111100000001111111111111 1111111000001111111100000000000000000111111111111111111111111111111111111111111110000001111111111111 1111110000001111111000000000000000000111111111111111111111111111111111111111111111000001111111111111 1111100000001111110000000000000000000111111111111111111111111111111111111111111111100001111111111111 1111000000001111100000000000000000000111111111111111111111111111111111111111111111110001111111111111 1110000000001111000000000000000000000111111111111111111111111111111111111111111111111001111111111111 1100000000001110000000000000000000000111111111111111111111111111111111111111111111111101111111111111 1000000000001100000000000000000000000111111111111111111111111111111111111111111111111111111111111111 1111111111111111111111111000000000000111111111111111111111111111111111111111111111111111111111111111 1111111111111111111111111000000000000111111111111100000000000000000000000001000000000001100000000000 1111111111101111111111111000000000000111111111111100000000000000000000000001100000000001110000000000 1111111111001111111111111000000000000111111111111100000000000000000000000001110000000001111000000000 1111111110001111111111111000000000000111111111111100000000000000000000000001111000000001111100000000 1111111100001111111111111000000000000111111111111100000000000000000000000001111100000001111110000000 1111111000001111111111111000000000000111111111111100000000000000000000000001111110000001111111000000 1111110000001111111111111000000000000111111111111100000000000000000000000001111111000001111111100000 1111100000001111111111111000000000000111111111111100000000000000000000000001111111100001111111110000 1111000000001111111111111000000000000111111111111100000000000000000000000001111111110001111111111000 1110000000001111111111111000000000000111111111111100000000000000000000000001111111111001111111111100 1100000000001111111111111000000000000111111111111100000000000000000000000001111111111101111111111110 1000000000001111111111111000000000000111111111111100000000000000000000000001111111111111111111111111 ``` [Answer] # Bubblegum, 535 bytes, 0 errors [![enter image description here](https://i.stack.imgur.com/0Smsp.png)](https://i.stack.imgur.com/0Smsp.png) ``` 0000000: bd96 410a 4431 0843 f739 4d73 ffcb cdf2 ..A.D1.C.9Ms.... 0000010: 93a1 0f2a 04b3 ab22 b1ad 1acf 07fb c489 ...*..."........ 0000020: 70ee 7006 9f0f 0207 b31c 60b1 33d4 3792 p.p.......`.3.7. 0000030: b033 4b24 03b9 dbc9 2220 2796 6b36 9f31 .3K$...." '.k6.1 0000040: c3fe 49d2 8a2c 904e d8fc 2149 d288 2c90 ..I..,.N..!I..,. 0000050: 4f98 9c01 1f49 da90 0512 0a8b 131f 0914 O....I.......... 0000060: 275c 3e8e 61a0 0756 384e 00be 9148 8da5 '\>.a..V8N...H.. 0000070: a25b ae09 4adc cea3 b1e8 75e2 cc2c f080 .[..J.....u..,.. 0000080: 71a2 f655 1e91 056a 210e 0822 4938 0e63 q..U...j!.."I8.c 0000090: 346f 7208 d53f 2174 ab0b 50ed 1342 b5e3 4or..?!t..P..B.. 00000a0: 01dd d905 e84e 6142 554f 0855 6524 5435 .....NaBUO.Ue$T5 00000b0: 1ed0 dd56 086a ee5d 04b9 0666 d7a1 801a ...V.j.]...f.... 00000c0: 8b2d fedf 128b 6d71 a54e c1ed 2cee b939 .-....mq.N..,..9 00000d0: a8d5 c4d3 630c 9c37 e239 3806 4e4e e144 ....c..7.98.NN.D 00000e0: e752 6307 6880 509b b80c d801 696a aeb2 .Rc.h.P.....ij.. 00000f0: 7387 705c 635e e4e0 2b8a 0629 ab2c 39f8 s.p\c^..+..).,9. 0000100: b384 230e 6b85 1c8c ed9b f4ff 64b1 ba16 ..#.k.......d... 0000110: fa64 a1e3 7766 d7f2 145e d093 0565 5cd0 .d..wf...^...e\. 0000120: f89d 6d65 67ef 424f 11b2 6b1c 87ec c2df ..meg.BO..k..... 0000130: 9a03 6b48 5877 7360 3708 3b68 0eec 6be1 ..kHXws`7.;h..k. 0000140: 2c98 0327 94e6 628a c059 abb1 98b2 0355 ,..'..b..Y.....U 0000150: 4363 3165 07ea 9f8a 2a8b 4aae b198 b203 Cc1e....*.J..... 0000160: 7712 8dc5 941d b85d 692c a6ec c03d 71fd w......]i,...=q. 0000170: 26fd 3f59 acae 853e 59e8 f89d d9b5 3c85 &.?Y...>Y.....<. 0000180: 17f4 6441 1917 347e 655b d9d9 bb0e 61cc ..dA..4~e[....a. 0000190: 1e01 7162 129b cccc 11a9 bc91 98ac cc11 ..qb............ 00001a0: f77d 2331 199d a056 7b23 c150 e4c8 9f7b .}#1...V{#.P...{ 00001b0: 2331 999c 8068 bf91 982c c891 ee37 1293 #1...h...,...7.. 00001c0: 0139 d2fb 4662 38a7 01a3 fd40 3250 5988 .9..Fb8....@2PY. 00001d0: f61b 89e9 7198 2315 9349 5865 b161 21da ....q.#..IXe.a!. 00001e0: f218 3ce0 e624 cd9b d0b8 2bff 896f a857 ..<..$....+..o.W 00001f0: d795 a3de 2737 8e7e c73b 519f 5d10 d29e ....'7.~.;Q.]... 0000200: c270 f9b2 9ef0 bfb6 9531 2f58 d678 20ef .p.......1/X.x . 0000210: 6e2b e0e8 ee5d 3f n+...]? ``` Compressed using zopfli (`--deflate --i10000`). [Try it online.](http://bubblegum.tryitonline.net/#code=MDAwMDAwMDogYmQ5NiA0MTBhIDQ0MzEgMDg0MyBmNzM5IDRkNzMgZmZjYiBjZGYyICAuLkEuRDEuQy45TXMuLi4uCjAwMDAwMTA6IDkzYTEgMGYyYSAwNGIzIGFiMjIgYjFhZC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AuLmRBLi40fmVbLi4uLmEuCjAwMDAxOTA6IDFlMDEgNzE2MiAxMjliIGNjY2MgMTFhOSBiYzkxIDk4YWMgY2MxMSAgLi5xYi4uLi4uLi4uLi4uLgowMDAwMWEwOiBmNzdkIDIzMzEgMTk5ZCBhMDU2IDdiMjMgYzE1MCBlNGM4IDlmN2IgIC59IzEuLi5WeyMuUC4uLnsKMDAwMDFiMDogMjMzMSA5OTljIDgwNjggYmY5MSA5ODJjIGM4OTEgZWUzNyAxMjkzICAjMS4uLmguLi4sLi4uNy4uCjAwMDAxYzA6IDAxMzkgZDJmYiA0NjYyIDM4YTcgMDFhMyBmZDQwIDMyNTAgNTk4OCAgLjkuLkZiOC4uLi5AMlBZLgowMDAwMWQwOiBmNjFiIDg5ZTkgNzE5OCAyMzE1IDkzNDkgNTg2NSBiMTYxIDIxZGEgIC4uLi5xLiMuLklYZS5hIS4KMDAwMDFlMDogZjIxOCAzY2UwIGU2MjQgY2Q5YiBkMGI4IDJiZmYgODk2ZiBhODU3ICAuLjwuLiQuLi4uKy4uby5XCjAwMDAxZjA6IGQ3OTUgYTNkZSAyNzM3IDhlN2UgYzczYiA1MTlmIDVkMTAgZDI5ZSAgLi4uLic3Ln4uO1EuXS4uLgowMDAwMjAwOiBjMjcwIGY5YjIgOWVmMCBiZmI2IDk1MzEgMmY1OCBkNjc4IDIwZWYgIC5wLi4uLi4uLjEvWC54IC4KMDAwMDIxMDogNmUyYiBlMGU4IGVlNWQgM2YgICAgICAgICAgICAgICAgICAgICAgICBuKy4uLl0_&input=) Fairly straightforward; I might experiment with adding some errors later. [Answer] # ForceLang, ~~2749~~ ~~2499~~ 2495 bytes ![](https://www.gravatar.com/avatar/2d2ecf8ce1eeccae0937868763c5005f?&s=100&d=identicon) ``` def S set S W io.writeln S R string.rev S a ""+0x6D79F82328EA3DA61E0701C9182D91DDE8B1C71C7 S b ""+0x786C90F379CE770387732B1CDC3135DC3CE1C71C6 S c ""+0x7984D36EB5187CC012312A961B9A27CB5BF9C71BC S d ""+0x79A0DA14A16CB0862210C8BE24D40F55C1D5C7158 S e ""+0x79A3A78B9F751C1A0472203FA900BFF60DEBC6D70 S f ""+0x79A3EF4AB8DC5A0FFC9CDC4D56BD69F1DBBAC4660 S g ""+0x79A3F6776E99E049FE5189BC60823AF3FB1C2BFC0 S h ""+0x79A3F72F1A60079DE42E0BC3623C9CC0D0A4F7D80 S i ""+0x79A3F741785A41CCDA794C67E9EBDAB9EAC2CE700 S j ""+0x79A3F7434E8CFFB9AC2E70DEA901D141036760600 S k ""+0x79A3F7437D9343C8FBEF208311B066CF95614BC00 S l ""+0x79A3F7438253021069541D3C0D7DBD353F18E9800 S m ""+0x79A3F74382CB60F176B1C1A99D8D000C45AA51000 W a+a W b+b W c+c W d+d W e+e W f+f W g+g W h+h W i+i W j+j W k+k W l+l W m+m W l+l W k+k W j+j W i+i W h+h W g+g W f+f W e+e W d+d W c+c W b+b W a+a W S n ""+0x2082FAED7A3F16F730463D6FB0529164157A6772E72577EC590ADCDD251957F2BC21BCECCEDA1000001 W S o "0"+0x3404C4AF29FE8B251A078D51F3422C44257DE9CCEE48C93AB6DDD70037D6F058EF1E96AE389780000B W S p "00"+0x533AD44B766411D4F4ED5F3E08CDC08896ADBCDC1213E71D9792DAFE2655B4B0D387777F349C0006F W S q "000"+0x852AED458A39B62094B066CF194EDEE006289DFD2093DCC403A9A369F588AB436E4125B928600457 W S r "0000"+0xD5117BA276C2BC68EEC80E4BF8D5C1A068B3ABB7496F715789D4298974E6B48DA0883E68B702B67 W S s "00000"+0x154E8C5D0BE0401A871156A755E768D3BEF3334F8FA7C61A4F116CE6907EB4964CFA6EB1559B207 W S t "000000"+0x221746FB462FE3C989A43900F01111A46D39389143FAB11D7C222D858D8B7420DC570C3CCCF447 W S u "0000000"+0x368BA4C53AC7AFE49E5162CA0DA3D0B1C8CDBE64A8195738CB712D2038B74223F9C849AEF8AC7 W S v "00000000"+0x5745D46D515CD860B238C63288EE96F8425A28BBF8CE27A5F060FE9F8B742263237710A66BC7 W S w "000000000"+0x8BA2EC93C7B8B205605DCC1242ACE73FE320C62A60CEC941E4474B78B742266B0F5F107B5C7 W S x "0000000000"+0xDF6A832B1C8B32B27AA702FBBFD960651EAB9E37CE30AD4E093DA78B7422670BEB558DD9C7 W S y "00000000000"+0x1651C9F6F18C5FB47C580D61E4F69EB8CFDD04644901F0B5CFB5078B742267151AEC7761C7 W S z "000000000000"+0x202C1796B182D85E5704E2B93930E38C74A50C6F9CC338492A1C78B7422671603C11C71C7 W y W x W w W v W u W t W s W r W q W p W o W n W R n W R o W R p W R q W R r W R s W R t W R u W R v W R w W R x W R y W R z W R y W R x W R w W R v W R u W R t W R s W R r W R q W R p W R o W R n W S a R a+a W S b R b+b W S c R c+c W S d R d+d W S e R e+e W S f R f+f W S g R g+g W S h R h+h W S i R i+i W S j R j+j W S k R k+k W S l R l+l W R m+m W l W k W j W i W h W g W f W e W d W c W b W a ``` ]
[Question] [ In this challenge, you will be "reversing" the alphabet or swapping `a-z` with `z-a`. This is commonly known as the [Atbash](https://en.wikipedia.org/wiki/Atbash) cypher. Because this transformation makes the output look like some foreign language, your code will need to be as short as possible. --- ## Examples ``` abcdefghijklmnopqrstuvwxyz zyxwvutsrqponmlkjihgfedcba Programming Puzzles & Code Golf Kiltiznnrmt Kfaaovh & Xlwv Tlou Hello, World! Svool, Dliow! ``` ## Specification * The input may contain multiple lines, and will be ASCII-only * **No** *additional* whitespace should be added to the output * Case *must* be preserved ## Leaderboard ``` var QUESTION_ID=68504,OVERRIDE_USER=40695;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> ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins [Answer] # C, 59 bytes Sorry for bringing up C again, but I was a bit disappointed to see only C *functions* here. I was under the impression OP was looking for a usable product. ``` main(c){while(~(c=getchar()))putchar(isalpha(c)?c+4^31:c);} ``` Compiled on Ubuntu 14.04 with a simple: ``` cc swalpha.c ``` The resulting executable reads any number of lines from stdin, and writes the result to stdout. Thanks to so many of the other posters for the XOR trick. [Answer] ## Pyth, 8 bytes ``` XXzG)rG1 ``` @xnor suggested this simpler approach on @FryAmTheEggman's Pyth answer, then I translated it to Pyth. This uses the handy behavior of `X` (translate) when given only two arguments: it translates from the second argument to the reversed second argument. We do this first with the lowercase alphabet (`G`), and then with uppercased `G`. [Answer] ## CJam, 17 bytes I wanted to help GamrCorps golf his CJam solution, but the result ended up so different that I decided to make a separate answer. ``` q'[,_el^_W%32f^er ``` [Try it online.](http://cjam.aditsu.net/#code=q'%5B%2C_el%5E_W%2532f%5Eer&input=Hello%20World!) ### Explanation ``` q e# Read all input. '[, e# Get a character range from the null byte up to and including "Z". _el e# Duplicate and convert to lowercase. ^ e# Symmetric set difference. Due to the lowercase operation only letters will not e# appear in both sets, and so we get a string with all uppercase letters followed e# by all lowercase letters, i.e "ABC...XYZabc...xyz". _W% e# Duplicate and reverse. Gives: "zyx...cbaZYX...CBA". 32f^ e# Take each character XOR 32 which swaps the case, so now we have: e# "ZYX...CBAzyx...cba" er e# Transliterate: substitute each character in the first string with the correspoding e# character in the second string. ``` [Answer] # JavaScript (ES6), ~~69~~ 67 bytes ``` x=>x.replace(/[A-Z]/gi,c=>String.fromCharCode(c.charCodeAt()+4^31)) ``` Uses the same strategy as my [Japt answer](https://codegolf.stackexchange.com/a/68509/42545): ``` x=>x.replace(/[A-Z]/gi,C=> // Replace each letter C with String.fromCharCode( // the character with char code C.charCodeAt()+4^31)) // the char code of C, plus 4, with the last 5 bits flipped. ``` Curse your incredibly long property names, JS... [Answer] # [Retina](https://github.com/mbuettner/retina), ~~17~~ ~~14~~ 13 bytes Code: ``` \T`w`_dZ-Az-a ``` Explanation: ``` \ # This suppresses the trailing linefeed T # Switches to transliterate mode `w # w is short for _0-9A-Za-z `_d # d is short for 0-9 Z-Az-a # Z-Az-a ``` This does some magic stuff and completes the task. Try it [here](http://retina.tryitonline.net/#code=XFRgd2BfZFotQXotYQ&input=UHJvZ3JhbW1pbmcgUHV6emxlcyAmIENvZGUgR29sZg). [Answer] ## Pyth, ~~10~~ 9 ``` uXGr;H)2z ``` Thanks to Jakube for saving a byte with the new feature of `;`! [Test Suite](https://pyth.herokuapp.com/?code=uXGr%3BH%292z&input=Hello&test_suite=1&test_suite_input=abcdefghijklmnopqrstuvwxyz%0AProgramming+Puzzles+%26+Code+Golf%0AHello%2C+World%21&debug=0) A quick explanation: reduce starting with the input over the numbers 0 and 1. The operation to be performed is translate the lower case alphabet with either `r...0` or `r...1` which are the lower and upper functions from python, respectively, applied to it, and then reversed. [Answer] # Julia, ~~74~~ ~~61~~ 47 bytes ``` s->replace(s,r"[a-z]"i,t->Char(31$Int(t[1])-4)) ``` This is a lambda function that accepts a string and returns a string. To call it, assign it to a variable. We match each letter using a regular expression and replace each letter with the ASCII character corresponding to 31 XOR the ASCII code for the letter, minus 4. [Answer] ## C, ~~150~~ 129 Bytes ``` void rev(char*s){int i,t;for(i=0;i<strlen(s);i++){t=s[i]+25;t=t<116?180-t:244-t;isalpha(s[i])?printf("%c",t):printf("%c",s[i]);}} ``` This function just converts char to int and adds the appropriate offset to the int before printing. I know it's not the shortest but I didn't see a C implementation. Example usage ``` #include<stdio.h> #include<string.h> #include<ctype.h> void rev(char*s){int i,temp;for(i=0;i<strlen(s);i++){temp=s[i]+25;temp=temp<116?180-temp:244-temp;isalpha(s[i])?printf("%c",temp):printf("%c",s[i]);}} int main(){ char *s = "hello, there"; rev(s); return 0; } ``` UPDATE: shortened a variable name. [Answer] ## Python, 61 bytes ``` lambda x:''.join([c,chr(ord(c)+4^31)][c.isalpha()]for c in x) ``` An anonymous function. On letters, does the reversing operation on the bit representation by adding 4, then flipping the last five bits, similar to [ETHproductions' Javascript answer](https://codegolf.stackexchange.com/a/68509/20260). [Answer] # Japt, ~~23~~ 22 bytes ``` Ur"[A-Za-z]"_c +4^31 d ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VXIiW0EtWmEtel0iX2MgKzReMzEgZA==&input=IlByb2dyYW1taW5nIFB1enpsZXMgJiBDb2RlIEdvbGYi) ### How it works ``` Ur"[A-Za-z]"_ // Take the input and replace each letter with: c +4 // Take its char code and add 4. This results in // the string "ABC...XYZabc...xyz" // becoming "EFG...\]^efg...|}~". ^31 // XOR the result by 31. This flips its last five 5 bits. // We now have "ZYX...CBAzyx...cba". d // Convert back from a char code. // Implicit: output last expression ``` [Answer] # C, 64 A void function that modify the string in place. ``` t(char*p){for(int c;c=*p;)*p++=c>64&c<91|c>96&c<123?(c^31)-4:c;} ``` Test: [ideone](http://ideone.com/l1omcP) [Answer] # R, ~~69~~ 61 bytes Thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312) for shaving off some extra bytes: ``` function(s)cat(chartr("a-zA-Z",intToUtf8(c(122:97,90:65)),s)) ``` **Previous version:** ``` function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s)) ``` This is an anonymous function. Usage: ``` > f=function(s)cat(chartr("a-zA-Z",rawToChar(as.raw(c(122:97,90:65))),s)) > f("Hello, World!") Svool, Dliow! > f("Programming Puzzles & Code Golf") Kiltiznnrmt Kfaaovh & Xlwv Tlou > f("This is + a multiline + example.") Gsrh rh z nfogrormv vcznkov. ``` [Answer] # Ruby, 40 bytes New solution: Stole that bit flipping magic from some of the other posts here: ``` ->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}} ``` --- # Ruby, ~~55~~ 46 bytes ``` ->s{s.tr'a-zA-Z',[*?A..?Z,*?a..?z].reverse*''} ``` 9 bytes off thanks to @manatwork --- test run: ``` ->s{s.gsub(/[a-z]/i){($&.ord+4^31).chr}}["Kiltiznnrmt Kfaaovh & Xlwv Tlou"] => "Programming Puzzles & Code Golf" ``` [Answer] # Jolf, 15 bytes ``` ~Ai+plpu+_pl_pu ~A I don't know what to call this, besides "dictionary replace" i the input +plpu previous dictionary: lower + upper alphabet +_p1_pu new dictionary: reversed lower + reversed upper ``` [Test suite](http://conorobrien-foxx.github.io/Jolf/#code=fkFpK3BscHUrX3BsX3B1&input=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoKCnp5eHd2dXRzcnFwb25tbGtqaWhnZmVkY2JhCgpQcm9ncmFtbWluZyBQdXp6bGVzICYgQ29kZSBHb2xmCgpLaWx0aXpubnJtdCBLZmFhb3ZoICYgWGx3diBUbG91CgpIZWxsbywgV29ybGQhCgpTdm9vbCwgRGxpb3ch), or [try it with your own input](http://conorobrien-foxx.github.io/Jolf/#code=fkFpK3BscHUrX3BsX3B1) [Answer] # 𝔼𝕊𝕄𝕚𝕟 2, 12 chars / 26 bytes (non-competitive) ``` ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=Programming%20Puzzles%20%26%20Code%20Golf&code=%C3%AF%C4%AA%28%E1%B6%90%2B%E1%B6%9B%2C%E1%B6%90%E1%B4%99%2B%E1%B6%9B%E1%B4%99)` Added transliterate function after the challenge was posted. # Explanation ``` ïĪ(ᶐ+ᶛ,ᶐᴙ+ᶛᴙ // implicit: ï=input ïĪ( // transliterate ï... ᶐ+ᶛ, // from uppercase+lowercase alphabet... ᶐᴙ+ᶛᴙ // ... to reversed uppercase+reversed lowercase alphabet // implicit output ``` [Answer] ## CJam, 21 bytes ``` q'[,65>__el_@+W%@@+er ``` Not an optimal solution... yet... [Try it online](http://cjam.aditsu.net/#code=q%27%5B%2C65%3E__el_%40%2BW%25%40%40%2Ber&input=Hello%2C%20World!) Its hard to explain without grouping things, so here is a general explanation: gets input, pushes uppercase alphabet twice and lowercase twice, rotates things around, combines uppercase and lowercase strings, reverses one, and uses transliteration (similar to the Retina answer). [Answer] # C (function), 50 ``` f(char*s){for(;*s;s++)*s=isalpha(*s)?*s+4^31:*s;} ``` This builds on [all](https://codegolf.stackexchange.com/a/68587/11259) [three](https://codegolf.stackexchange.com/a/68550/11259) [previous](https://codegolf.stackexchange.com/a/68560/11259) C answers, so credit to @Ruud, @Danwakeem and @edc65. This function modifies a char array in place. My understanding is [function entries are allowed](http://meta.codegolf.stackexchange.com/a/2422/11259) unless explicitly banned in the question. [Try it online.](https://ideone.com/L5v8YF) [Answer] # PostgreSQL, 118 125 bytes ``` SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t))) FROM(SELECT text'Programming Puzzles & Code Golf's,text'abcdefghijklmnopqrstuvwxyz't)r ``` `**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/9eecb7db59d16c80417c72d1e1f4fbf1/8276/0)**` Output: ``` ╔══════════════════════════════════╦═════════════════════════════════╗ ║ s ║ translate ║ ╠══════════════════════════════════╬═════════════════════════════════╣ ║ Programming Puzzles & Code Golf ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║ ╚══════════════════════════════════╩═════════════════════════════════╝ ``` Input: `SELECT text'...'s` --- **EDIT:** Input as table: ``` SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t))) FROM i,(SELECT text'abcdefghijklmnopqrstuvwxyz't)r GROUP BY s,t ``` `**[`SqlFiddleDemo`](http://sqlfiddle.com/#!15/15762/2/0)**` Output: ``` ╔══════════════════════════════════╦═════════════════════════════════╗ ║ s ║ translate ║ ╠══════════════════════════════════╬═════════════════════════════════╣ ║ Hello, World! ║ Svool, Dliow! ║ ║ Programming Puzzles & Code Golf ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║ ║ abcdefghijklmnopqrstuvwxyz ║ zyxwvutsrqponmlkjihgfedcba ║ ╚══════════════════════════════════╩═════════════════════════════════╝ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` žnžo‡ ``` Uses **CP-1252** character set. [Try it online!](http://05ab1e.tryitonline.net/#code=xb5uxb5v4oCh&input=YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXo) Explanation: ``` žn - Push [A-Za-z] žo - Push [Z-Az-a] ‡ - Transliterate. ``` [Answer] ## Seriously, 31 bytes ``` úúû+╗úRúûR+╝,`;╜íuWD╛E(X0WX`Mεj ``` Hex Dump: ``` a3a3962bbba352a396522bbc2c603bbda1755744be452858305758604dee6a ``` [Try It Online](http://seriouslylang.herokuapp.com/link/code=a3a3962bbba352a396522bbc2c603bbda1755744be452858305758604dee6a&input=Programming%20Puzzles) Expl: ``` úúû+╗ Put UPPERCASElowercase in reg0 úRúûR+╝ Put ESACREPPUesacrewol in reg1 , Fetch input. ` `Mεj Map over the characters in string as list, joining result ;╜íu Find 1-index of character in UPPERCASElowercase W 0WX If it is positive (present): D Convert back to 0-index ╛E Look it up in ESACREPPUesacrewol (X Delete the original character. (Else just leave the original character unchanged.) ``` I just realized the spec say no additional whitespace, but there is no way to suppress trailing newlines in Seriously output, so there is no Seriously solution. [Answer] # Python 3, ~~195~~ ~~169~~ ~~168~~ 166 bytes Thanks to [@TrangOul](https://codegolf.stackexchange.com/users/30296/trang-oul) for -2 bytes! How didn't I see that I could have golfed that down before? ``` x=__import__('string').ascii_letters;y,z=x[26:],x[:26];a,b=y[::-1],z[::-1];print(''.join(b[z.index(i)]if i in b else a[y.index(i)]if i in a else i for i in input())) ``` (sorta) ungolfed: ``` x = __import__('string').ascii_letters; y, z = x[26: ], x[: 26]; a, b = y[::-1], z[::-1]; print(''.join(b[z.index(i)] if i in b else a[y.index(i)] if i in a else i for i in input() )) ``` [Try it on Ideone!](http://ideone.com/psNATq) [Answer] # Haskell, ~~119~~ 104 bytes Saved 15 bytes thanks to @nimi. ``` c=fromEnum;s=toEnum;f[]="";f(x:y)|64<c x&&c x<91=s(155-c x):f y|96<c x&&c x<123=s(219-c x):f y|0<1=x:f y ``` **Usage:** ``` f "abcdefghijklmnopqrstuvwxyz" "zyxwvutsrqponmlkjihgfedcba" f "Programming Puzzles & Code Golf" "Kiltiznnrmt Kfaaovh & Xlwv Tlou" f "Hello, World!" "Svool, Dliow!" ``` **Explanation** ``` let c=fromEnum;s=toEnum;--wrap names for later use, fromEnum gets ascii code from char, toEnum gets char from ascii code f[]=[]; --feed empty list (of chars in this case), get empty list f(x:y) --feed a list, separate the first element and... |64<c x&&c x<91= --if its an uppercase char (using ascii code range)... s(c x*(-1)+155) -- inverse its ascii code value, move it to the range of uppercase and get the new char -- (like rotating half turn a ruler by the side and then sliding it to the space it previously occupied) :f y -- feed the rest of the list and stick the new char in front of the result |96<c x&&c x<123= --if its a lowercase char (using ascii code range)... s(c x*(-1)+219) -- inverse its ascii code value, move it to the range of lowercase and get the new char :f y -- feed the rest of the list and stick the new char in front of the result |True=x:f y --otherwise feed the rest of the list and stick the char in front of the result ``` I'm new to Haskell... to functional programming... and to the site, and i know there are (a lot of) better answers to this question, but bear with me. [Answer] # [Perl 6](http://perl6.org), 28 bytes ``` {S:g/\w/{chr $/.ord+4+^31}/} ``` ### Usage: ``` # give it a lexical name my &swap = { … } say swap 'Programming Puzzles & Code Golf'; # Kiltiznnrmt Kfaaovh & Xlwv Tlou say swap ('a'..'z').join # zyxwvutsrqponmlkjihgfedcba ``` [Answer] ## Java, 136 bytes ``` void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}} ``` Example usage: ``` class Test { static void x(String i){for(char c:i.toCharArray()){if(Character.isLetter(c))c=c<91?(char)(90-(c-65)):(char)(122-(c-97));System.out.print(c);}} public static void main(String[] args) { x("Programming Puzzles & Code Golf"); // produces "Kiltiznnrmt Kfaaovh & Xlwv Tlou" } } ``` Probably the worst commonly-used language in terms of byte size. [Answer] ## Unix shell + tr + printf, 35 bytes ``` tr A-Za-z `printf %s {Z..A} {z..a}` ``` Here you are, a canonical answer in tr. I thought how could a question to transliterate the alphabet go without a canonical answer to **tr**ansliterate the alphabet? tr by itself does not even do a "Hello, World!" and as such isn't a programming language, so ~~I marked the answer as noncompeting~~[1]. [1]: Edit: Actually, *Unix shell* is the language and tr is the *standard library*. Thanks to Downgoat and Digital Trauma for helping me spot this out. [Answer] ## Python 3, ~~164~~ 159 bytes ``` def f(t,a="abcdefghijklmnopqrstuvwxyz",b=""): for c in t:u=64<ord(c)<91;c=c.lower();c=a[::-1][a.index(c)] if c in a else c;b+=c.upper() if u else c return b ``` [Answer] # PHP, 73 bytes ``` <?=strtr($argv[1],($b=strtolower($a=join(range(A,Z)))).$a,strrev($a.$b)); ``` do this need any comments? [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 65 bytes ``` -join($args|% t*y|%{[char]($_,(($_-bxor31)-4))[$_-match'[a-z]']}) ``` [Try it online!](https://tio.run/##RZBPS8NAEMXv@RTTsG2zkhxET4IgKCj0UlBQKKVsk02y7SST7m7@NG0/e1xrq3MYmB/vPZhXUSu1ySXiwFJ4hMMQbUiVARM6M8cx2Jv9cXxYxLnQy4CtwsCtaN2Rvrvl0T3nC3cWwsb5dCGifjldnvhw8rynwAM3YeCLdZzINMvVZotFSdVOG1s3bbfv/fBH4vf7rm1qa/SuorLA7UblWSqTeC18fg2Za8q0KApVZjCv@x6lgQk8UyLhlTC9JM0UWtWXpS4szFIhqMmd6gvbBj6Q6v@4N/cuhfBJGpPRxfzeEGEIL6ioHTkphyOM4XC2MBMCk10lYysTVxJb/WItTY3WgYnrjpkz9Flw4VEsd38u/nCV@95p@AY "PowerShell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` σ…'A'Z…'Z'Aσ…'a'z…'z'a ``` [Try it online!](https://tio.run/##yygtzv7//3zzo4Zl6o7qUSAqSt0Rwk9UrwJRVeqJ////T0xKTklNS8/IzMrOyc3LLygsKi4pLSuvqKwCAA "Husk – Try It Online") [Answer] # C, ~~112~~ 98 bytes ``` i;main(){char x[99];gets(x);for(;x[i];i++)if(isalpha(x[i]))x[i]=(x[i]>90?219:155)-x[i];puts(x);} ``` I know that `gets()` is deprecated and unsafe, but `scanf()` doesn't accept whitespace and I need to include `stdio.h` if I want to `fgets` (since `stdin` is defined in `stdio.h`). I assume this program wouldn't work if the user tried to enter a string more than `99` characters. EDIT: Changing `printf("%s",x)` to `puts(x)` saves `7` bytes and changing `i<strlen(x)` to `x[i]` saves another `7` bytes. ]
[Question] [ [Inspired by this question over at Mathematics](https://math.stackexchange.com/q/1775719/248583). --- **The Problem** > > Let `n` be a natural number `≥ 2`. Take the biggest divisor of `n` – which is different from `n` itself – and subtract it from `n`. Repeat until you get `1`. > > > **The Question** *How many steps does it take to reach `1` for a given number `n ≥ 2`.* **Detailed Example** > > Let `n = 30`. > > > The greatest divisor of: ``` 1. 30 is 15 --> 30 - 15 = 15 2. 15 is 5 --> 15 - 5 = 10 3. 10 is 5 --> 10 - 5 = 5 4. 5 is 1 --> 5 - 1 = 4 5. 4 is 2 --> 4 - 2 = 2 6. 2 is 1 --> 2 - 1 = 1 ``` It takes *6 steps* to reach `1`. **Input** * Input is an integer `n`, where `n ≥ 2`. * Your program should support input up to the language's maximum integer value. **Output** * Simply output the number of steps, like `6`. * Leading/trailing whitespaces or newlines are fine. **Examples** ``` f(5) --> 3 f(30) --> 6 f(31) --> 7 f(32) --> 5 f(100) --> 8 f(200) --> 9 f(2016^155) --> 2015 ``` **Requirements** * You can get input from `STDIN`, command line arguments, as function parameters or from the closest equivalent. * You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest answer in bytes wins. * Standard loopholes are disallowed. --- This series can be found on OEIS as well: **[A064097](https://oeis.org/A064097)** > > A quasi-logarithm defined inductively by `a(1) = 0` and `a(p) = 1 + a(p-1)` if `p` is prime and `a(n*m) = a(n) + a(m)` if `m,n > 1`. > > > [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆṪÐĿÆFL€S ``` [Try it online!](http://jelly.tryitonline.net/#code=w4bhuarDkMS_w4ZGTOKCrFM&input=&args=MTU3MDQ3NzgxMTY1NzIzNzIxNzAzODQxMTUyMDYyMDM3MDQ1Nzc0MTQzMTkxNzExNTg0NDExOTM0MDg2MDgzNjM2NzA3Njc5NTM1MDgwMjQwMTY3Njg5MzM2ODk2OTkxMjExMjMyOTk3OTU5NjUzMzYxODIxNTI3Mz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5NTMxOTc0NDA1MjA0MjA1ODQxOTY5NDMwNTE1MDUyMjc4Nzc2MDQ1ODY2NDk0OTUyMzc3ODk2MTEwOTI0MTc1MDk4NzYwOTk5MzU3OTYxNDY1ODQ5OTExOTg3Mzc4MjkwMTg2MTY4OTI1Njg2MzgzODEzNjY5MjExMDE2OTE3NDkyNDkzMTU1OTE0NDAxNjQxNDE1OTM1OTY2Mjc1MjAyMjY1NDM5OTY3MjgzNDYxMzQ1NTMzMDA4NzkyMDM0MjU4NTUzOTY1OTQzMjk4NDU3Ng). ### Background The definition of sequence [A064097](https://oeis.org/A064097) implies that $$\small{a(p)-a(p-1)=1}\text{ for all primes }p\text{ and }a(km)=a(k)+a(m)\text{ for all }k,m\in \mathbb{N}$$ By [Euler's product formula](https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler.27s_product_formula) $$\small{\varphi(n)=n\prod\_{p|n}\left(1-{1\over p}\right)=n\prod\_{p|n}{{p-1}\over p}}$$ where \$\varphi\$ denotes Euler's totient function and \$p\$ varies only over prime numbers. Combining both, we deduce the property $$\small{a(\varphi(n))=a\left(n\prod\_{p|n}{{p-1}\over p}\right)=a(n)+\sum\_{p|n}\left(a(p-1)-a(p)\right)=a(n)-\sum\_{p|n}{1=a(n)-\omega(n)}}$$ where \$\omega\$ denotes the number of distinct prime factors of \$n\$. Applying the resulting formula \$k + 1\$ times, where \$k\$ is large enough so that \$\varphi^{k+1}(n)=1\$, we get $$\small{ \begin{aligned} 0=a\left(\varphi^{k+1}(n)\right)=a\left(\varphi^k(n)\right)-\omega\left(\varphi^k(n)\right)&=a\left(\varphi^{k-1}(n)\right)-\omega\left(\varphi^{k-1}(n)\right)-\omega\left(\varphi^k(n)\right) \\ &= \cdots = a(n)-\sum\_{j=0}^k\omega\left(\varphi^j(n)\right) \end{aligned} }$$ From this property, we obtain the formula $$\small{a(n)=\sum\_{j=0}^k\omega\left(\varphi^j(n)\right)=\sum\_{j=0}^{+\infty}\omega\left(\varphi^j(n)\right)}$$ where the last equality holds because \$\omega(1)=0\$. ### How it works ``` ÆṪÐĿÆFL€S Main link. Argument: n ÐĿ Repeatedly apply the link to the left until the results are no longer unique, and return the list of unique results. ÆṪ Apply Euler's totient function. Since φ(1) = 1, This computes φ-towers until 1 is reached. ÆF Break each resulting integer into [prime, exponent] pairs. L€ Compute the length of each list. This counts the number of distinct prime factors. S Add the results. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ 11 bytes Code: ``` [DÒ¦P-¼D#]¾ ``` Explanation: ``` [ ] # An infinite loop and... D# break out of the loop when the value is equal to 1. D # Duplicate top of the stack (or in the beginning: duplicate input). Ò # Get the prime factors, in the form [2, 3, 5] ¦ # Remove the first prime factor (the smallest one), in order to get the largest product. P # Take the product, [3, 5] -> 15, [] -> 1. - # Substract from the current value. ¼ # Add one to the counting variable. ¾ # Push the counting variable and implicitly print that value. ``` Uses **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=W0TDksKmUC3CvEQjXcK-&input=MjAw). [Answer] # Pyth, 11 bytes ``` fq1=-Q/QhPQ ``` [Test suite](https://pyth.herokuapp.com/?code=fq1%3D-Q%2FQhPQ&test_suite=1&test_suite_input=5%0A30%0A31%0A32%0A100%0A200&debug=0) A straightforward repeat-until-true loop. Explanation: ``` fq1=-Q/QhPQ Implicit: Q = eval(input()) f Apply the following function until it is truthy, incrementing T each time starting at 1: PQ Take the prime factorization of Q h Take its first element, the smallest factor of Q /Q Divide Q by that, giving Q's largest factor -Q Subtract the result from Q = Assign Q to that value q1 Check if Q is now 1. ``` [Answer] # [Retina](https://github.com/mbuettner/retina/wiki/The-Language), 12 * 14 bytes saved thanks to @MartinBüttner ``` (1+)(?=\1+$) ``` This assumes [input given in unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary) and output given in decimal. If this is not acceptable then we can do this for 6 bytes more: # [Retina](https://github.com/mbuettner/retina/wiki/The-Language), 18 * 8 bytes saved thanks to @MartinBüttner ``` .+ $* (1+)(?=\1+$) ``` [Try it online - 1st line added to run all testcases in one go.](http://retina.tryitonline.net/#code=JShHYAouKwokKgooMSspKD89XDErJCk&input=NQozMAozMQozMgoxMDAKMjAw) Sadly this uses unary for the calculations, so input of 2016155 is not practical. * The first stage (2 lines) simply converts the decimal input to unary as a string of `1`s * The second stage (1 line) calculates the largest factor of n using regex matching groups and lookbehinds to and effectively subtracts it from n. This regex will match as many times as is necessary to reduce the number as far as possible. The number of regex matches will be the number of steps, and is output by this stage. [Answer] ## Python 2, ~~50~~ 49 bytes ``` f=lambda n,k=1:2/n or n%(n-k)and f(n,k+1)or-~f(k) ``` This isn't going to finish that last test case any time soon... Alternatively, here's a 48-byte which returns `True` instead of `1` for `n=2`: ``` f=lambda n,k=1:n<3or n%(n-k)and f(n,k+1)or-~f(k) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ÆfḊPạµÐĿi2 ``` [Try it online!](http://jelly.tryitonline.net/#code=w4Zm4biKUOG6ocK1w5DEv2ky&input=&args=MjAw) or [verify most test cases](http://jelly.tryitonline.net/#code=w4Zm4biKUOG6ocK1w5DEv2kyCsOH4oKsRw&input=&args=NSwgMzAsIDMxLCAzMiwgMTAwLCAyMDA). The last test cases finishes quickly locally. ### How it works ``` ÆfḊPạµÐĿi2 Main link. Argument: n (integer) Æf Factorize n, yielding a list of primes, [] for 1, or [0] for 0. Ḋ Dequeue; remove the first (smallest) element. P Take the product. This yields the largest proper divisor if n > 1, 1 if n < 2. ạ Yield the abs. value of the difference of the divisor (or 1) and n. µ Convert the chain to the left into a link. ÐĿ Repeatedly execute the link until the results are no longer unique. Collect all intermediate results in a list. For each starting value of n, the last results are 2 -> 1 -> 0 (-> 1). i2 Compute the 1-based index of 2. ``` [Answer] # Pyth - ~~15~~ ~~14~~ 13 bytes Special casing `1` is really killing me. ``` tl.u-N/Nh+PN2 ``` [Try it online here](http://pyth.herokuapp.com/?code=tl.u-N%2FNh%2BPN2&test_suite=1&test_suite_input=5%0A30%0A31%0A32%0A100%0A200&debug=0). ``` tl One minus the length of .u Cumulative fixed point operator implicitly on input -N N - /N N / h Smallest prime factor +PN2 Prime factorization of lambda var, with two added to work with 1 ``` [Answer] # Julia, ~~56~~ ~~50~~ ~~45~~ 39 bytes ``` f(n)=n>1&&f(n-n÷first(factor(n))[1])+1 ``` This is a recursive function that accepts an integer and returns an integer. Ungolfed: ``` function f(n) if n < 2 # No decrementing necessary return 0 else # As Dennis showed in his Jelly answer, we don't need to # divide by the smallest prime factor; any prime factor # will do. Since `factor` returns a `Dict` which isn't # sorted, `first` doesn't always get the smallest, and # that's okay. return f(n - n ÷ first(factor(n))[1]) + 1 end end ``` [Try it online!](http://julia.tryitonline.net/#code=ZihuKT1uPjEmJmYobi1uw7dmaXJzdChmYWN0b3IobikpWzFdKSsxCgpmb3IgdGVzdCBpbiBbKDUsMyksICgzMCw2KSwgKDMxLDcpLCAoMzIsNSksICgxMDAsOCksICgyMDAsOSksIChiaWcoMjAxNileMTU1LDIwMTUpXQogICAgcHJpbnRsbihmKHRlc3RbMV0pID09IHRlc3RbMl0pCmVuZA&input=) (includes all test cases) Saved 6 bytes thanks to Martin Büttner and 11 thanks to Dennis! [Answer] # JavaScript (ES6), ~~\*44~~ 38 *Edit* 6 bytes saved thanks @l4m2 (\* 4 striked is still 4) Recursive function ``` f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0 ``` Less golfed ``` f=(n, d=n-1)=>{ if (n>1) if(n % d != 0) return f(n, d-1) // same number, try a smaller divisor else return f(n-d)+1 // reduce number, increment step, repeat else return 0 } ``` **Test** ``` f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0 console.log=x=>O.textContent+=x+'\n'; [5,30,31,32,100,200].forEach(x=>console.log(x+' -> '+f(x))) ``` ``` <pre id=O></pre> ``` [Answer] # Regex `🐝` (ECMAScript or better), 12 bytes ``` (x+)(?=\1+$) ``` Takes its input in unary, as a sequence of `x` characters whose length represents the number. Returns its output as the number of matches. This of course has already been done in [Digital Trauma's Retina answer](https://codegolf.stackexchange.com/a/79666/17216), but here it is demonstrated to work on a much wider variety of regex engines. [Try it online!](https://tio.run/##TY@7TsMwFEB/JUSoubdp0hohhga3E0OXDjACg9XeOhccx7LdB32sfACfyI@EVgKJ@ZzhnDe1UWHh2cUiOF6Sb1r7Th@dl5a2ySPph50D2MvJsN/BLkeYyheRX2PXH@6xjO1T9Gw1YBkMLwjuBsUtDpJMZ1gFOaq2NRsCMNKTWhq2BIhX0q6NwYOWpgzOcISsOOu8ArBSl4asjjVObo5HDnM1B5ZO@UAzG0E/j14R/wD9B3YipmJ8wRhr327Tmd0ow8vEK6tpnKS5qVath4rvJVWc53hoZLpLS0@OVATGslFxUYM/l/d67rwV4TIhKreOIXrgPEu@P7@SLIdm2vx2jkeI1enUiUII8QM "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript [Try it online!](https://tio.run/##RY5BasMwEEX3OcUQhkjCdmwVuslYiQPptqvumiBSkwSBmriSCy5GXfYAPWIv4ipuoJth/ufP/NccnL0fXj8AHUFvL/XeAuYUpSo366f1MkyOF8fRq4LKJYkezDEq0TfOnFuYbs9TClBZ5RtrWs4ylvr3F9/GE51mMpXi8HYNrf7dIvpigVrQ9ZePjXtX2fJO9JV9ljsVZ7GjMAEYm83NQFOqMRC3JInhWnHWsQ6NUJ85uvxE6GezkWvEisyS/jDRzBn8fH0Dm1c1haD1w@NG64F3ieArtZUJimGQmZTyFw "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVLLbtswELz7K7ZCA5N@MFaPZYSgLVqgQJMWydHRgZYomw5FqeQqVmzk2g/oJ/ZH3JWsPgJEl9XuDmc5w92qBzXf5vdHU9aVR9hSLkwlJhL@rzRo7Is1r9e6pc6oblbWZJBZFQJcKePgAEMtoEIKD5XJoaQOu0Vv3BqUX4dlygE3vtoF@NhmukZT0ckRwCdjNRSJ07v@l0Ui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xj9GBn0YoE61PPqgSsTyx6CewD5Ig29zUCV8Xl6PXkJRS1RBcR9D23ivt@YbaFs0DuMOWCusy350WStoqgqjhlKXYJsAPc23jS0hNBCQsFU7ba22O6SChK/S6N@rUAd3aBtQ7N1iCT485X@zoqrP8H5w/8/Pji95ZqchZ7NsnQwpP5@TUZIkvwA "PHP – Try It Online") - PCRE [Try it online!](https://tio.run/##bVJLbtswFNzrFK9uEZOWlIYJkIVkOUCPUHTRwjEEmaYlohJFkBTsJPC2B@gRe5C6j3TiTxEuCPJ9ZuYNybVOa873H6Xi7bASMF32vXWfjajF9rrRehbxpjJQ6vkCCvg6@rLZ/FzeDT@enr5/a@43DdmTbUzJQ/HI4k90T//PjxKY6KLUMcujE4lEDiOqbhYhXQt8SXivrINAnmVd5XhTGmGH1tnpIeVlTGZX0NEXI9xgFDgziHwXSeWgq6QiFF4iwKXnCN4KRTRN2aK4yWHAmrvb0kHvb76h9gfrVlmGtVLVGNSDy0P/hZRgBBiBYPlbzAZ9sGmq1451b4B42OcjbC1cK5Ug4cKlSg4MNH9T6ZdvUTfoa@V6SULBNS9REaE0AcUS0L3F9CGzlmpFxumY5kcAxTDraz4U59NkmfLBh3dwIQ71MTAKGZKfsMI7TzydEpvDba5YzBY5dKKzwhGbwHg79sLQC4tJb@6x/2iCLJR3eVoolkMcy/OJw9RrIM8UUJQnIeNHhSOhdSy/KBuUlbUSq@ASR1nnL1LWRmjClwmQ0/eACb3yslK5eDeOUSPoJcvhffrBwXQK0m8j@PPrN@545KfaXXTaX/8fzr7bs5Qx9pev26q2@7QNGssg8R8 "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##LY5BTsQwDEX3PYUVIU1M2moMu5aIg5QuRpoUglKncoKYuQAH4IhcpIwFO/9vvydv1/qW@XGP65alQrmWVkL7XjKPIF6MMbu9OLTP/oXcHe63YqKho3mE6I/NkgUSRFawL/UceWgg@dSXLcVqTWewgbhACmwTPj0MkCaafZqOcwMKs8Jy4tdgI1erC2z/JprREd58KogDbKI9avY0wupVKqFfIp9PKVlpwVzMPaOe/P@TP2r/KbEGW6pYRneAn69vODiNK@JOHRH9Ag "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##PY5BbsIwEEX3PcU0qhS7kFHM1rUQEmy7QOwCsmgZgiVriBwj0h6AA3DEXiR1QtXVaJ7@m/nh8vHVBzCwppq6BpmusFxsFhhof9DgTKnhenKewJuaYpvQEXxVqJ0x2ZYznbivSsRittNAfBgBto13UeRFLh8CeuI6noR8m6VAlewkPYQngOM5AINjGCDGs3VClRJxCP6v4yH3nAo1l9RjfOWM0tAExxF4msPP7Q75VGRd9soS2889i5Cm@6a/asM7a1fvS2t70U2kmJutmrzIvleFUuoX "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##RY9BasMwEEWvIsSApaoyUZcRIoGuewLXC@NOYoE8MrKCTYK3PUCP2Iu4TmjpanjD/4@ZIU6Yxg5DWCG5KuEZ53q/J5zEsVjFrKQ4uHejQK7F8Zm/xn7wAT@4tHB1O3uKCZu2ExCYJwaehkuWN2gcBD0OwWeuufUnAU3ZxgtlHTJ7uQeUg6ba1csmEECu8pTrx8YC6YB/bO6s1NboHaTyrclth6Mo5uIJSD7MV3mbks@ouzjmZbvK2H9mmuL2S/CEjAOx788vBgL6MiCdc/c7JF@W1WhjzA8 "PowerShell – Try It Online") - .NET ``` (x+)(?=\2+$) # \2 = largest proper divisor of tail; tail -= \2; # return \2 as a match ``` [Try it online!](https://tio.run/##TY@7TsMwFEB/JUSoubdp0hohhga3E0OXDjACg9XeOhccx7LdB32sfACfyI@EVgKJ@ZzhnDe1UWHh2cUiOF6Sb1r7Th@dl5a2ySPph50D2MvJsN/BLkeYyheRX2PXH@6xjO1T9Gw1YBkMLwjuBsUtDpJMZ1gFOaq2NRsCMNKTWhq2BIhX0q6NwYOWpgzOcISsOOu8ArBSl4asjjVObo5HDnM1B5ZO@UAzG0E/j14R/wD9B3YipmJ8wRhr327Tmd0ow8vEK6tpnKS5qVath4rvJVWc53hoZLpLS0@OVATGslFxUYM/l/d67rwV4TIhKreOIXrgPEu@P7@SLIdm2vx2jkeI1enUiUII8QM "JavaScript (SpiderMonkey) – Try It Online") # Regex `🐘` (.NET), 15 bytes ``` ((x+)(?=\2+$))* ``` [Try it online!](https://tio.run/##RY9BasMwEEWvIsSApbgyUZYxIoGuewLXC@FOYoEiCUnGJsbbHqBH7EVcp6F0@WY@b/4EP2JMPVq7QlRNxCtO7fHocGTnYmVsKjk7qfdDCZzv1uL8Ql/9LRiLH5TXcFf7@uIj6q5nYIlxBIwLQ@YzaAVWpGBNpoLW5sJAV50fXBY2k8MjUCrQzb5dNgEDpxrjcvs7qcEJi38sH1yWfH44bgpi9aZz12NixVTswPHn5s7nMZqMovcpL1szWf8zEc5vL1njkFBw5Pvzi8Bmq67RDyFtN6pOhzxETM@SnC7LskohpfwB "PowerShell – Try It Online") Returns its output as the capture count of group `\1`. ``` # tail = input number; no need to anchor, as all inputs return a result ( (x+)(?=\2+$) # \2 = largest proper divisor of tail; tail -= \2 )* # Loop the above as many times as possible, minimum zero, and push each # match onto the \1 capture stack ``` # Regex (Perl / Java / PCRE2 v10.34 or later), 26 bytes ``` ((?=(\2?+(x*))x(x\3)+$)x)* ``` Returns its output as the length of the match. [Try it online!](https://tio.run/##RU7dSsMwFL7fU4QRlpy1XZeJN6ZZO5i3Xnm3jjBlg0DcalIhEuKlD@Aj@iL1rArefJzz8f11R2dvh5d3Qp0k0V6eD5bQUuKrqu3mcbNOk9PFcerVUlZrCZGYE34QO2fOPZm256lMpLHKd9b0nBUs929PvkeLzguRCzi@XkX1P7tEHu6oBnnN8th4cI2tVhAbuxN7hbjcyzQhZGw2fwQ1lRoFeGUZRPRyFligBtRHSV0JkfrZbNw1zsLNQv7OpGbByPfnF2EL3mSYVjQFIsiUktb3D1utB85rxdtVnfEwBwg8tDeQUQgwHwZRCCF@AA "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVLLbtswELznK7ZCA5O2w1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WlKiZdUYJjRYLo0WSeHPtMQTbzRIjuB0MgzBibb5oalXlgnqhFyA8xvys2mjX5p6dYNIMCXAdLuIeQFdZ__aJPku6OFr9PoNbBAA2APSAkuukm_E6dVlJiQmwbjtwkTrqN35ANAvImjEGRGyRKrWOC2OwAosfmcg13N0h5iBJ3k7OX_LLK34-mVxNsFp7UslEVlbt8WLAiUQxtD4QPfDg56fP4A12k1hjxyy-_9MiMh8e7mXuKPxn4A9mKL0_RsGNThV0zeHG852s0AkGoinTjXUix9hkJ-ae2JtU4fzWIof304vwFLIyRRYktwHUlbVyqT6C1Fll8Eo4tAXaeZc6LQVURYHXAXKZg64cdDBbVzoHV4FDwFKspNZSrxAKKdykSj6WQh6sIbVDslfjKVi3r__FjIhO5_ve_T8PAkX5tnFFePqd0lFC5yejPm2OGGtoM3_K-oQ17GgLeNj9ojCKoq3zCw "PHP - Attempt This Online") - PCRE2 v10.40+ We can't just do a direct port of the .NET version, because we need to subtract at least 1 from tail on each iteration (as a regex loop terminates after a zero-width match), and with most inputs, the iteration count exceeds the cumulative result of subtracting the largest divisor before the last iteration has finished. So instead, we let `\2` be the sum of the subtracted divisors minus the iteration count: ``` # tail = input number; no need to anchor, as all inputs return a result ( (?= (\2?+(x*)) # \3 = {conjectured largest proper divisor of tail-\2} - 1; # \2 = {\2, or 0 if \2 is unset} + \3; tail -= \2; note that the # subtraction of 1 from this divisor compensates for the "tail -= 1" # on each iteration (below) x(x\3)+$ # assert tail - 1 is divisible by \3 + 1 ) x # head += 1; tail -=1 )* # Loop the above as many times as possible, minimum zero ``` (The PCRE version requirement is because PCRE2 v10.33 and earlier automatically makes any group containing a nested backreference atomic, thus `\3` always captures the entire remaining tail, making the regex always return 0.) # Regex (.NET), 28 bytes ``` (?=((x+)(?=\2+$))*)(?<-1>x)* ``` [Try it online!](https://tio.run/##RY/BboMwDEB/JUKWSMqCmh7LslXaeV/AOCDmQqTUQSEIVMR1H7BP3I@wsGnayX629Wz3bkI/dGjtBl6XHlucq/OZcOKXdOPPmvM5EzG@nTIQ4hDTR6meZnHY0stD8uJuvbH4nogC7vpYXJ3Huuk4WGaIgaF@DGKBWoOVQ29NSGRSmCuHOm/cSEHawE77QKahLo/VGgUcSJeGQvVTKYCkxT9WO2eZWHbHTYPPX@vQdDjwdE4PQOK3cxfL5E1A2bkhrPEyVfwzk@Tif9YQsgSIfX18Moi2vPVu7Ie4M7dIbehEsq7rpqRS6hs "PowerShell – Try It Online") A simple port of the 15 byte .NET version, that returns its output as the length of the match instead. ## Regex (Perl / Java / PCRE2 v10.34 or later / .NET), ~~29~~ bytes Obsoleted by the 29 byte regex below, which supports a superset of regex engines. # Regex (Perl / Java / PCRE / Python[`regex`](https://github.com/mrabarnett/mrab-regex) / Ruby / .NET), ~~33~~ 29 bytes ``` ((?=.*(?=\3$|^)(x+)(\2+$))x)* ``` [Try it online!](https://tio.run/##RU7LSgMxFN33K0IJTW7nmYobM2mnULeu3HVqqNJCILZjMsJIjEs/wE/0R8bbUXBzuPdwXu3B2evh@Y1QJ0mw56e9JbSQ@Kpqs75fL@PkeHacelXKaikhEHPED0LrzKkj0@Y0lZHUVvnWmo6zjKX@9dF3aNFpJlIBh5eLaPXPlsjDDdUgL1keG/euttUCQm23YqcQy52ME0LGZvNHUFOpUYBXkkBAL2c966kB9VFQV0CgfjYbd42zcLOQvzOpyRn5/vwiLOd1gmlZnSGCjDFqfXu30XrgfKXyOUJzRd8fgPcJ8GaRUIAe5sMgMiHEDw "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVLLbtswELznK7ZCApN@MFZ6KyMEbdECBZq2SI6OC9ASZdOhKJWkYsWur/2AfmJ/xF3K7CNAdBC5u8NZznDX4kFM1sX9QVVNbT2sMWaqZkMO/2dar/SzOSuXssPKSdMutMoh18I5uBbKwA5iznnhcXmoVQEVVsitt8osQdilm80p@JWtNw7edblsvKrx5AnAe6UllJmRm35LEpbXhWRYTyh/05altLK4kaKQFhY97GmS/DkZw5JSHvu6seebVeAnxGU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RqhkMLXVMnnVsiDPaR2SHY3noJ1l@ZfzIhodD62jv/8ECjKidJhErbRzF@Qw2dG9x1G5zcdwtietU@nqBtF0S8 "PHP – Try It Online") - PCRE2 v10.33** [Attempt This Online!](https://ato.pxeger.com/run?1=fVPBbtNAED1wy1dMrVW9m9hOXC4VrlUJ0aIgaFEIpySsHHsdL92srd0NCmp75QO4cqmE-Ax-hCNfwtghRaCKg8ezO2_ezM7b_fK1qZq7H4_OT07RAWIgBW_oQQSNEStuRKOyXFB_GPVPOa8y5XherxuphJnTOUvmk6H1A_DxK3GTr0QL0E5oZynn5-OXZ5yzAGKGlEic9KSW3ApHvSY3Ilpm-ZUzaLiSa-m8ALww9ljyN8qIfGOsrPV_Ue93kREGemVtKJHpKCEqLbEpS99Mn40vWMKuQZaUqJl1RgmNHgvjRZp6c-0xBNvNEiO4HYyCMGZtvtg2qi4E9UIvQHiC-Xm90a7NPTnCpBkSoB0tkh5AV1n_XhN9knZx9AYDBtcIAGwA6AElV2k343Xm8ooSE2DdduAic9Tf-gHRLCBrxhgQsUOqzDoujMEKLLlnIldwc4OYgzR9PTl7zi8u-dlkcjnBau1JJRN5VbfHSwAnEifQroHoyIOfnz6DF-0nscaOWXL7p0VkPjx8kLmj8J-AH81Qen-MghudKeiaw42ne1mhEwzEtso21okCY5O9mA_EXmUK57cWBbydnofHkFcZsiC5DaCprZVL9RGkzmuDV8KhL9AvutRpJaAuS7wOUMgCdO2gg9mm1gW4GhwClmIltZZ6hVDI4EOm5H0p5MEaUjskezGegnUP9b-YEdHpfNu7_edBoCjfNq4Mj79TeppGfTTzx-TmHaPbAaPzowFhbMv6O8zd_heHcRzvFr8A "PHP - Attempt This Online") - PCRE2 v10.40+ **[Try it online!](https://tio.run/##PY5NasMwEIX3PsUgApnxH1GysytyEMcF0yqJijw2kkId6LoH6BF7EVdKaTfDm5/3zZvv4TrxYTXjPLkA/u5Lpy96Kd/8xC045YQQK@JR1Xksp8Pm45lwKQhP@2JDtFC@xotONpXsWzBql50nBxYMJ1jtw6vhJgOrbO1nawKKSlAG5gxWM1p62jdgO9kr2@36DJKZk9kNfNFoOGBaUPmrZE@FpMiDUT1y1l4P7uWKrgSxiJwjOrHHdJKEaWB2yUvtY6Jk@5druoX63Zmg0QeHTMUWvj@/YFukdoxpB0aKH6t/HXPQKisp5Q8 "Python 3 – Try It Online") - Python `import regex` [Try it online!](https://tio.run/##PY7BasMwEETv@YqtMbXWiRfLPbqiBNJrDiU3OxUtURyBUIyiEBdCj/2AfmJ@xJWdJpeBeczsjjt@fvUOBLypRnUtWXWCxXw1J6c@NiVokZdw2mmjwIhG@UNAWzBVxtdCRLWNysBNlRNlxboEZTcjoENrtGdJluC1QEbZxu8YPhchUIV2KF0LE4Dt3oEFbWGA5PdSM54j0RC82/EQi7ootQjiG9wI9MOwsD0Oy8bvWvDgnbYe7CyBy88vJLP48T7gP3aTiZSvy4WUPWMvgtIg9VN8fkfWTZHVxTRG7DDte55xzv8A "Ruby – Try It Online") - Ruby** [Try it online!](https://tio.run/##RY9RaoQwEIavEsKAiTay2b6thC70uSdwLYjNaiA7kRhR1vraA/SIvYiNLaUvA9/8wzczvZu0Hzpt7QZelV63eq5OJ9QTOycbY08qT2O5PML7K2dzxtnlmAHnM0@35PxAn92tN1a/UV7AXR2Kq/O6bjoGlhgkYLAfA1@gVmDF0FsTqKCFuTKo88aNGIQN5LgPZArq8lCtUcAAVWkwVD@dAlBY/cdy5yzjy@64KfD5Sx2aTg8smZMUkP8md75M3gQtOjeENV4mi38mAl180BrUhAKSr49PAtGWt96N/RB35lZjGzpO13XdpJBSfgM "PowerShell – Try It Online") - .NET For regex engines that lack nested backreferences but support forward-declared backreferences, we switch to a different approach. In this version, each iteration, while inside a lookahead, stores the new value of tail in the capture group `\3`, so that the next iteration can then recall that value rather directly. Since this directly sets `\3` instead of building it up incrementally, there's no need to emulate a nested backreference. ``` # tail = N = input number; # no need to anchor, as all inputs return a result ( (?= .*(?=\3$|^) # tail = \3, or N if \3 is unset (x+)(\2+$) # \2 = largest proper divisor of tail; \3 = tail - \2 ) x # Increment the return value )* # Loop the above as many times as possible, minimum zero ``` # Regex (Perl / PCRE / Python[`regex`](https://github.com/mrabarnett/mrab-regex)), 63 bytes ``` (?=(xx+?)\1*(?=\1$)((?R)))(?=(x+)\3*(?=\3$)((?R)))\2\4|x\B(?R)| ``` This implements the recursive definition of the function:\$a(1) = 0\$ \$a(p) = 1 + a(p-1)\$ if \$p\$ is prime \$a(nm) = a(n) + a(m)\$ if \$m,n > 1\$ [Try it online!](https://tio.run/##RY5BTsMwEEX3PYVVWbWHJG3cwgbHTYrKtgvEDldWQa1kybTBDlKQa5YcgCNykeAEBJvR/Dczf369t@aqe35D2HLkzelpZxCe8ShFsV7dr5ZhdDhZip3IebHk4JE@RAW@tvrYoLE8jnlAlRGuNrqhJCOpe310TTxRacZSBvuXfqn8p3nkcI0V8N7LxY87W5liDr4yD2wrYs23PIwQGj7rX4B1IYaF2CUJ@HhLSUtarEG8z7CdgcduMhlyDbFiZsZ/YmI9Jejr4xORKa2S6JZVWazAQwhK3W7WSnW0FLRtkxIku4i9ZBgoLe8AYJgkIBcDX/xxOZeX51be9OrcdSxjjH0D "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##hVTbbtpAEH3nK6a0CbvYRGyoqsrGQUmaqg80qRCRWmFkUbMGq2ZtrU0hCbz2A/qJ/ZDS2V2cOBepFrJmZ2fOnDkzJsyy1iwMd69jESbLKYduFkp@ND@phfOJhCAbjcGDQf1stfrxvbP8dnPzdTh/t5qTHel5ZL22etRnTbR99oYS0htQSvWNRf2O9nfu/f6x/3az9s/UabOjTyHrNjQzL8gs5tYe6OTFNE4Vn6pLxmL22Ben6OWTxfO4k1osCsjQLAIuZSpJmIq8AN1fc8HzfDLj9A7rOE6IAdDtwt6rTO3nYpq4IHmxlAKYu9WQi0ksCIW7GuCTjbBawgXJaIuNvbYLS4zpHAcFpOqkEmZo6GCNadjhRbYsXFCqQ1NyF6rskE5WSJMteb5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8fn6SuaXw34Dfn6H0/gQFNzpT0A6HgZujrNAKBmJXZlvrRIG55CjmidzHTOH@NqKAL9Pb3mvIywxZkNwGUFfWyoX6BlLnlcEn4dAWaBdt6bQUUC2X@BygkAXoykELs3WlC3AVOAQsxEpqLfUKoZDBQ6bkSyvkwR5SOyR7P5mCdafmn8@IaHV@6jz980OgKAc6iulu1x2xNLxAOw0Jo3SUoIptpsvS6zZ@/RJPr9JX@11603j7wyHshWH4Cw "PHP – Try It Online") - PCRE2 v10.33 ``` # tail = input number; no need to anchor, as all inputs return a result (?= (xx+?)\1*(?=\1$) # Assert tail isn't prime; # tail = \1 = smallest prime factor of tail ((?R)) # \2 = recursive result of f(tail) ) (?= (x+)\3*(?=\3$) # tail = \3 = largest proper divisor of tail ((?R)) # \4 = recursive result of f(tail) ) \2\4 # return \2 + \4 as the match | # or if tail is prime: x # tail -= 1; return result += 1 \B # Assert tail > 0 (?R) # return 1 + recursive result of f(tail) | # or if tail == 1: # return 0 at the match ``` Note that `(?0)` could have been used as a synonym for `(?R)`. # Regex (Perl / PCRE / Boost / Python[`regex`](https://github.com/mrabarnett/mrab-regex)), 65 bytes ``` ((?=(xx+?)\2*(?=\2$)((?1)))(?=(x+)\4*(?=\4$)((?1)))\3\5|x\B(?1)|) ``` The intent of the 63 byte version was to create a version that works under Boost, but as it turned out Boost has a bug (which I've [reported](https://github.com/boostorg/regex/issues/177)) in which it ignores top-level alternatives in a top-level recursive call (i.e. `(?R)`), trying only the first top-level alternative. The workaround is to nest the entire regex in a capture group, so that Boost sees the other alternatives. Either `(?R)` or `(?1)` would work, but the latter is used for slightly better efficiency. [Try it online!](https://tio.run/##RY5BTsMwEEX3PYVVWY2HJE0c2g2OmxSVbVfscBUV1EqWTBviIAW5YckBOCIXCRODYDOa/2bmz68PjVkOz2@ENoI4c37aG0ITgVLmm/X9etVPjueGUStTka8EOKKPqMDVjT61ZKpOU9GT0khbG92yIA4i@/poWzypophHHA4v41LxT1PkcEMrEKOXxY/7pjR5Bq40D3wnsaY70U8I8Z/1L6A6l34BuzAEh7cs6IKOapDvCW0ScNTOZj6Xj4WZufiJSfU8IF8fnySYszJEt7iMsYLo@76q7rabqhoYKyTrurAAlV1hrzIKyDgA@EkIauH54o@ra7W8dOp2VBcYBh5zzr8B "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##fVPdbtMwFL7vU5xF1mKv6U/GkBBpVGmiQ0WwoVKumslKE7cxdZ3IdlHQ2lsegEfkRcpJRodAExexzs93vnN8PqcqquNoXBUVEAMxeAMP@lAZseZGVCrNBPUH/Ysx50WqHM/KbSWVMAlNWJTMBtYPwMdvhUG@Fg1AO6GdpZzfTN9POGcBhAwpkTjqSC25FY56VWZEf5lmG2fw4EpupfMC8Hqhx6K/UUZkO2Nlqf@L@vKYGWKisyoNJTIeRkTFKxzK0k/zN9NbFrEHkCtK1MI6o4RGi/XC@zj2Eu0xBNvdEjMYDoZBL2RNvagrVeaCej0vQHiE9Vm5066pHV1i0QIJ8BzeRx2AtrP@7RM9its8Wt0ugwcEAA4A9IySTdzueJu6rKDEBNi3WbhIHfVrPyCaBWTLGAMiHpEqtY4LY7ADi56YyAb2e8ScxfHH2eQtv73jk9nsbobdmptKJrKibK4XAW4kjKDxgei@Bz@//wCvf9rEFidm0eHPiMh8fv4sc0vhvwa/v0Dp/SkKbnSqoB0OA9cnWaEVDERdpDvrRI652UnMZ3IfUoX724ocPs9veq8gK1JkQXIbQFVaK5fqG0idlQafhENboJ23pfNCQLla4XOAXOagSwctzFalzsGV4BCwFGuptdRrhEIKX1Mln1ohD/aQ2iHZu@kcrHtu/vsFEa3Oh87hnx8CRTlSOo5pXXfHLLm8QDu5JAxjIcrYZrosuWrjV0/x5EXycl8n1423Z8dj2AvD8Bc "PHP – Try It Online") - PCRE2 **[Try it online!](https://tio.run/##bVLNcpswEL77KbZup5YMOJGd9gAmnskjdHpox3gYIsugKRYaEIOTJtc8QB@xDxJ3JWripOWg2d9v9/sWrnWQc358LxUv262A5W1VNeaiFrk4zAqtr0e8yGpI9XoDMXwZ33Tdj9tF@/3u7tvX4nNXkCMhq5gcDt6KJvMp2sn8A8UYo5S6jEeTKxe/GuLJIvn0cEhurPdAj/Qt6NiHqY5T7bFo9LKZxMVqke2vR1IZ2GdSEQo/R4CfXmOqFIpoGrBNfBlBizWLeWqgsp5tyK3RmG0YYq1UOQZ1ayLXzyvVGHDUw9Bxh1ogWHSKNfvM8AK6IvvbsatqIBb2foDNhSmlEsQ5XCq/n0Cj05b2sy3qEqXMTCWJK5jxFDcilPqgmA@6ajDdZ3ZSbckkmNBoAFAMs7bmXXzOJgyVDa7@gwueq/eAUQhx@AuWO@3UjlOi6721Yh7bRLAX@0YY0vgwOUzsYqhFg0kr7tA/iCBjZVVexopF4HnynLFjvQNyrm7aiKzmBSFnDOhHix/Ije9k9vEC9C3OCeueAhK0C5NJolAePAOL/intL1G1BpZLkPYZw@@nX/iiaYfM8J/JTUHo697H0Wurf2th2loB8n88soAx9sx3ZZY3x6B03FJH7Q8 "C++ (gcc) – Try It Online") - Boost** [Try it online!](https://tio.run/##PU9LboMwEN1zipFVKZ4YUEzSDdSK1GtgFqh1EkfGINtViZR1D9Aj9iLUpmp2b97M@8x0C5fR7hc9TKML4G8@d@qs5vzqR9uAE44QslB6FHSe2RFltY1YVk8YOY6I64ahPKz84cHLvXy@z/I1TXdcokvL64J3DWixy06jAwPapsDSh3dt6wyMMKWfjA6UFAQz0CcwylKDL1UNpuWdMO2uyyCJbRK73p4V1TbQtMD8D/EOGcfoB4NYfym96t3bhbocyEy2Nlon7yGdJKBrmFzSYrMygjf/vcaPUH46HRT1wVGLbAM/X9@wYWkcYtveUoyJxQPHHrjwgnP@Cw "Python 3 – Try It Online") - Python `import regex` # Regex (Ruby), ~~76~~ 71 bytes ``` (?=(xx+?)\1*(?=\1$)(\g<0>))(?=(x+)\3*(?=\3$)(\g<0>))\k<2+0>\4|x\B\g<0>| ``` [Try it online!](https://tio.run/##RY5BTsMwEEX3PcUQVcRuGstO2SVuVVS2LBC7uIpAdVMLy41cVzVSxZIDcEQuEhwXymY08/7/9rfH1/feAocn2UrfESNPsFo@L4mVL5sSFKclnHZKS9C8le4Q0BZ0nbM154kwSRm4rikhebEuQZpNBOTQaeVQmqf4EiBamtbtEK6KYKhDOoQugRHAdm/BgDIwQOL2jUKMYkIG4/WMD6HEJxODgX@AjUDdDA2749As/q44C7dVxoGZpvD9@QXpdHx7LfBr@xujpnl4XDVNjxYceZ8tsGCTsAs2xki0FZ1jHKUMi1kUZv@CeKuKjM7F3dmL@8jOfc9yxtgP "Ruby – Try It Online") This is a port to Ruby's style of recursion; `(?R)` is replaced with `\g<0>`. Also, the backreference `\2` needs to be replaced with `\k<2+0>` to get its value at the current level of recursion, rather than its global value which may have been overwritten at deeper levels of recursion. [Answer] ## Mathematica, 36 bytes ``` f@1=0;f@n_:=f[n-Divisors[n][[-2]]]+1 ``` An unnamed function takes the same bytes: ``` If[#<2,0,#0[#-Divisors[#][[-2]]]+1]& ``` This is a very straightforward implementation of the definition as a recursive function. [Answer] ## PowerShell v2+, 81 bytes ``` param($a)for(;$a-gt1){for($i=$a-1;$i-gt0;$i--){if(!($a%$i)){$j++;$a-=$i;$i=0}}}$j ``` Brutest of brute force. Takes input `$a`, enters a `for` loop until `$a` is less than or equal to `1`. Each loop we go through another `for` loop that counts down from `$a` until we find a divisor (`!($a%$i`). At worst, we'll find `$i=1` as a divisor. When we do, increment our counter `$j`, subtract our divisor `$a-=$i` and set `$i=0` to break out of the inner loop. Eventually, we'll reach a condition where the outer loop is false (i.e., `$a` has reached `1`), so output `$j` and exit. **Caution**: This will take a *long* time on larger numbers, especially primes. Input of 100,000,000 takes ~35 seconds on my Core i5 laptop. *Edit* -- just tested with `[int]::MaxValue` (2^32-1), and it took ~27 minutes. Not *too* bad, I suppose. [Answer] # Octave, ~~59~~ ~~58~~ 55 bytes ``` function r=f(x)r=0;while(x-=x/factor(x)(1));r++;end;end ``` > > Updated thanks to Stewie Griffin, saving 1 byte > > > Further update, saving three more bytes by using result of factorization in while-check. > > > Sample runs: ``` octave:41> f(5) ans = 3 octave:42> f(30) ans = 6 octave:43> f(31) ans = 7 octave:44> f(32) ans = 5 octave:45> f(100) ans = 8 octave:46> f(200) ans = 9 ``` [Answer] # Haskell, 59 bytes ``` f 1=0;f n=1+(f$n-(last$filter(\x->n`mod`x==0)[1..n`div`2])) ``` Usage: ``` Prelude> f 30 Prelude> 6 ``` It may be a little inefficient for big numbers because of generating the list. [Answer] # Python 3, ~~75, 70~~, 67 bytes. ``` g=lambda x,y=0:y*(x<2)or[g(x-z,y+1)for z in range(1,x)if x%z<1][-1] ``` This is a pretty straight forward recursive solution. It takes a VERY long time for the high number test cases. [Answer] # Matlab, 58 bytes ``` function p=l(a),p=0;if(a-1),p=1+l(a-a/min(factor(a)));end ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes ``` ⁽∆ṫ↔v† ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4oG94oiG4bmr4oaUduKAoCIsIiIsIjE1NzA0Nzc4MTE2NTcyMzcyMTcwMzg0MTE1MjA2MjAzNzA0NTc3NDE0MzE5MTcxMTU4NDQxMTkzNDA4NjA4MzYzNjcwNzY3OTUzNTA4MDI0MDE2NzY4OTMzNjg5Njk5MTIxMTIzMjk5Nzk1OTY1MzM2MTgyMTUyNzMwNjk2MTg1ODYwOTU2NzYyMjI4OTg4ODgwNjUwNTU2MjU4Mzk4MzkyOTA5NTQzMjE1NzMzMDI3NTMyOTgxNjMwNzc2MTM3ODUzODgxMTE2ODM4MDQyMTc2NzYzMTA5NDU3MDAwMDY0MTM2ODAxNTU4MDE3MjY3NDM0MTU5MTM2NzM3ODUwMTgxODkzOTcyMDEwNzk5NTYxNDAxNzE4MjY4OTIyMDk0NjE5NDg4NDczNDEyNTI1NDM5NTMxOTc0NDA1MjA0MjA1ODQxOTY5NDMwNTE1MDUyMjc4Nzc2MDQ1ODY2NDk0OTUyMzc3ODk2MTEwOTI0MTc1MDk4NzYwOTk5MzU3OTYxNDY1ODQ5OTExOTg3Mzc4MjkwMTg2MTY4OTI1Njg2MzgzODEzNjY5MjExMDE2OTE3NDkyNDkzMTU1OTE0NDAxNjQxNDE1OTM1OTY2Mjc1MjAyMjY1NDM5OTY3MjgzNDYxMzQ1NTMzMDA4NzkyMDM0MjU4NTUzOTY1OTQzMjk4NDU3NiJd) Port of Jelly. ``` ⁽∆ṫ↔v† ⁽ ↔ # Repeatedly apply until the result does not change, collecting intermediate results: ∆ṫ # Euler's totient v† # For each, get the number of distinct prime factors # s flag sums ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `l`, ~~6~~ 5 bytes ``` ≬K¯÷ẋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBbCIsIiIsIuKJrEvCr8O34bqLIiwiIiwiMVxuMlxuM1xuNFxuNVxuNlxuN1xuOFxuOVxuMTBcbjExXG4xMlxuMTNcbjE0XG4xNVxuMTZcbjE3XG4xOFxuMTlcbjIwXG4yMVxuMjJcbjIzXG4yNFxuMjVcbjI2XG4yN1xuMjhcbjI5XG4zMFxuMzFcbjMyXG4zM1xuMzRcbjM1XG4zNlxuMTAwXG4yMDAiXQ==) This is the same as the 6 byte answer below except the length is taken by the `l` flag rather than a `L` element. # [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ 6 bytes ``` ≬K¯÷ẋL ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLJvihu4oK0YCA9PiBg4oK0bs67Iiwi4omsS8Kvw7fhuotMIiwiO+KAoCwpIiwiMTExIl0=) ``` ≬ # 3-element lambda: K # Push a list of the divisors, from 1 to the number itself in increasing order ¯ # Deltas - returns a list of the consecutive differences in the list. # The resulting list has a length of 1 less than the one fed to it. ÷ # Unwrap the list onto the stack. For a non-empty list, this is effectively # equivalent to t (Tail - get the last item). But for an empty list, the # result is effectively whatever was already on the stack, i.e. the the # number whose list of divisors was taken, i.e., 1, the only one that yields # an empty deltas list. This makes 1, instead of 0, the fixed point. ẋ # Repeat the lambda on the number at the top of the stack (which is initially # the input) until the result no longer changes, returning a list of the # results. The last result will be 1, our fixed point. L # Length ``` This is very slow for most numbers of more than 60 decimal digits or so, since it has to generate a full list of divisors (even if it only uses the largest two). Prime factorization is still fast enough at that level, but unless the number has only one distinct prime factor, the list of divisors will be orders of magnitude longer. [Answer] ## [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` @!(UµUk Å×}a ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=QFW1VWsgsqTXIKUxfWHE&input=MzA=) ### How it works ``` @ !(Uµ Uk Å × }a XYZ{!(U-=Uk s1 r*1 }a // Implicit: U = input integer XYZ{ }a // Return the smallest non-negative integer X which returns // a truthy value when run through this function: Uk // Take the prime factorization of U. s1 // Slice off the first item. // Now we have all but the smallest prime factor of U. r*1 // Reduce the result by multiplication, starting at 1. // This takes the product of the array, which is the // largest divisor of U. U-= // Subtract the result from U. !( // Return !U (which is basically U == 0). // Since we started at 0, U == 1 after 1 less iteration than // the desired result. U == 0 works because the smallest // divisor of 1 is 1, so the next term after 1 is 0. // Implicit: output result of last expression ``` This technique was inspired by the [05AB1E answer](https://codegolf.stackexchange.com/a/79648/42545). A previous version used `²¤` (push a 2, slice off the first two items) in place of `Å` because it's one byte shorter than `s1 ` (note trailing space); I only realized after the fact that because this appends a 2 to the *end* of the array and slices from the *beginning*, it in fact fails on any odd composite number, though it works on all given test cases. [Answer] # ><>, 32 bytes ``` <\?=2:-$@:$/: 1-$:@@:@%?!\ ;/ln ``` Expects the input number, `n`, on the stack. This program builds the complete sequence on the stack. As the only number that can lead to `1` is `2`, building the sequence stops when `2` is reached. This also causes the size of the stack to equal the number of steps, rather than the number of steps +1. [Answer] # Ruby, 43 bytes ``` f=->x{x<2?0:1+f[(1..x).find{|i|x%(x-i)<1}]} ``` Find the smallest number `i` such that `x` divides `x-i` and recurse until we reach `1`. [Answer] # Haskell, 67 bytes Here's the code: ``` a&b|b<2=0|a==b=1+2&(b-1)|mod b a<1=1+2&(b-div b a)|1<2=(a+1)&b (2&) ``` And here's one reason why Haskell is awesome: ``` f = (2&) (-->) :: Eq a => a -> a -> Bool (-->) = (==) h=[f(5) --> 3 ,f(30) --> 6 ,f(31) --> 7 ,f(32) --> 5 ,f(100) --> 8 ,f(200) --> 9 ,f(2016^155) --> 2015 ] ``` Yes, in Haskell you can define `-->` to be equivalent to `==`. [Answer] # Matlab, 107 bytes ``` a=input('');b=factor(a-isprime(a));c=log2(a);while(max(b)>1),b=max(factor(max(b)-1));c=c+1;end,disp(fix(c)) ``` * Non-competing, this is not the iterative translation of my last submission, just another direct algerbraic method, it sums up all binary-logs of all prime factors, kinda ambiguous to illustrate. * I will golf this more when i have time. [Answer] # MATL, ~~17~~ 16 bytes ``` `tttYfl)/-tq]vnq ``` [**Try it Online**](http://matl.tryitonline.net/#code=YHR0dFlmbCkvLXRxXXZucQ&input=MzA) **Explanation** ``` % Implicitly grab input ` % Do while loop ttt % Make three copies of top stack element Yf % Compute all prime factors l) % Grab the smallest one / % Divide by this to get the biggest divisor - % Subtract the biggest divisor t % Duplicate the result q % Subtract one (causes loop to terminate when the value is 1). This % is functionally equivalent to doing 1> (since the input will always be positive) % with fewer bytes ] % End do...while loop v % Vertically concatenate stack contents (consumes entire stack) n % Determine length of the result q % Subtract 1 from the length % Implicitly display result ``` [Answer] # C99, ~~62~~ 61 bytes 1 byte golfed off by @Alchymist. ``` f(a,c,b)long*c,a,b;{for(*c=0,b=a;a^1;a%--b||(++*c,b=a-=b));} ``` Call as f(x,&y), where x is the input and y is the output. [Answer] # Julia, ~~39~~ 36 bytes ``` \(n,k=2)=n%k>0?n>1&&n\-~k:\(n-n/k)+1 ``` [Try it online!](http://julia.tryitonline.net/#code=XChuLGs9Mik9biVrPjA_bj4xJiZuXC1-azpcKG4tbi9rKSsxCgpwcmludGxuKFwoNSkpCnByaW50bG4oXCgzMCkpCnByaW50bG4oXCgzMSkpCnByaW50bG4oXCgzMikpCnByaW50bG4oXCgxMDApKQpwcmludGxuKFwoMjAwKSk&input=) [Answer] # Clojure, ~~116~~ 104 bytes ``` (fn[n](loop[m n t 1](let[s(- m(last(filter #(=(rem m %)0)(range 1 m))))](if(< s 2)t(recur s (inc t)))))) ``` -12 bytes by filtering a range to find multiples, then using `last` one to get the greatest one Naïve solution that basically just solves the problem as it's described by the OP. Unfortunately, finding the greatest divisor alone takes up like half the bytes used. At least I should have lots of room to golf from here. Pregolfed and test: ``` (defn great-divider [n] ; Filter a range to find multiples, then take the last one to get the largest (last (filter #(= (rem n %) 0) (range 1 n)))) (defn sub-great-divide [n] (loop [m n step 1] (let [g-d (great-divider m) ; Find greatest divisor of m diff (- m g-d)] ; Find the difference (println m " is " g-d " --> " m " - " g-d " = " diff) (if (< diff 2) step (recur diff (inc step)))))) (sub-great-divide 30) 30 is 15 --> 30 - 15 = 15 15 is 5 --> 15 - 5 = 10 10 is 5 --> 10 - 5 = 5 5 is 1 --> 5 - 1 = 4 4 is 2 --> 4 - 2 = 2 2 is 1 --> 2 - 1 = 1 6 ``` [Answer] # [Perl 6](http://perl6.org/), 35 bytes ``` {+({$_ -first $_%%*,[R,] ^$_}...1)} ``` [Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fra1RrRKvoJuWWVRcoqASr6qqpRMdpBOrEKcSX6unp2eoWfu/OLFSIU3B1JoLwjA2gLMM4SwjGMvQAC5tBGT@BwA "Perl 6 – TIO Nexus") ### How it works ``` { } # A bare block lambda. [R,] ^$_ # Construct range from arg minus 1, down to 0. first $_%%*, # Get first element that is a divisor of the arg. $_ - # Subtract it from the arg. { }...1 # Do this iteratively, until 1 is reached. +( ) # Return the number of values generated this way. ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~9~~ 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Åiw^Å♫┌ ``` [Run and debug it](https://staxlang.xyz/#p=8f69775e8f0eda&i=5%0A30%0A31%0A32%0A100%0A200&m=2) These two operations are identical. 1. Take the biggest divisor of `n` – which is different from `n` itself – and subtract it from `n`. 2. Let `d` be the smallest prime divisor of `n`. Calculate `n * (d - 1) / d`. I like #2 better, so let's count how many times we can do that one instead. So at each step, we decrement the smallest prime factor. Let's work an example starting with 30. ``` Step n Factors Operation 0 30 [2, 3, 5] Replace 2 with 1 1 15 [1, 3, 5] = [3, 5] Replace 3 with 2 2 10 [2, 5] Replace 2 with 1 3 5 [1, 5] = [5] Replace 5 with 4 4 4 [4] = [2, 2] Replace 2 with 1 5 2 [1, 2] = [2] Replace 2 with 1 6 1 [1] = [] End of the line ``` From the example we can see a recursive definition for `steps(x)` that solves the problem. Presented here in python-ish pseudo-code. ``` def steps(n): pf = primeFactors(n) return sum(steps(d - 1) for d in pf) + 1 ``` The stax program, unpacked into ascii looks like this. ``` Z push a zero under the input |fF for each prime factor of the input, run the rest of the program v decrement the prime factor G run the *whole* program from the beginning +^ add to the running total, then increment ``` [Run this one](https://staxlang.xyz/#c=Z+++%09push+a+zero+under+the+input%0A%7CfF+%09for+each+prime+factor+of+the+input,+run+the+rest+of+the+program%0A++v+%09decrement+the+prime+factor%0A++G+%09run+the+*whole*+program+from+the+beginning%0A++%2B%5E%09add+to+the+running+total,+then+increment&i=5%0A30%0A31%0A32%0A100%0A200&m=2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` ÆḌṀạƊƬL’ ``` [Try it online!](https://tio.run/##y0rNyan8//9w28MdPQ93NjzctfBY17E1Po8aZv4/3P6oac3//6Y6CsYGQGwIxEY6CoYGQI6RgQEA "Jelly – Try It Online") A different approach that takes advantage of Jelly's newer features. ## How it works ``` ÆḌṀạƊƬL’ - Main link. Takes n on the left Ɗ - Group the previous 3 links as a monad f(n): ÆḌ - Proper divisors of n Ṁ - The largest ạ - Absolute different with n Ƭ - Repeatedly run f(n) on n, updating n with the result, until reaching a fixed point (1), collecting intermediate steps L - Take the length ’ - Decrement to account for the 1 ``` ]